disable engine info until report popup bug is fixed.
[blender.git] / source / blender / windowmanager / intern / wm_files.c
1 /*
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version. 
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19  *
20  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
21  * All rights reserved.
22  *
23  * Contributor(s): Blender Foundation 2007
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/windowmanager/intern/wm_files.c
29  *  \ingroup wm
30  */
31
32
33         /* placed up here because of crappy
34          * winsock stuff.
35          */
36 #include <stddef.h>
37 #include <string.h>
38 #include <errno.h>
39
40 #ifdef WIN32
41 #include <windows.h> /* need to include windows.h so _WIN32_IE is defined  */
42 #ifndef _WIN32_IE
43 #define _WIN32_IE 0x0400 /* minimal requirements for SHGetSpecialFolderPath on MINGW MSVC has this defined already */
44 #endif
45 #include <shlobj.h> /* for SHGetSpecialFolderPath, has to be done before BLI_winstuff because 'near' is disabled through BLI_windstuff */
46 #include <process.h> /* getpid */
47 #include "BLI_winstuff.h"
48 #else
49 #include <unistd.h> /* getpid */
50 #endif
51
52 #include "MEM_guardedalloc.h"
53 #include "MEM_CacheLimiterC-Api.h"
54
55 #include "BLI_blenlib.h"
56 #include "BLI_linklist.h"
57 #include "BLI_utildefines.h"
58
59 #include "DNA_anim_types.h"
60 #include "DNA_ipo_types.h" // XXX old animation system
61 #include "DNA_object_types.h"
62 #include "DNA_space_types.h"
63 #include "DNA_userdef_types.h"
64 #include "DNA_scene_types.h"
65 #include "DNA_screen_types.h"
66 #include "DNA_windowmanager_types.h"
67
68 #include "BKE_blender.h"
69 #include "BKE_context.h"
70 #include "BKE_depsgraph.h"
71 #include "BKE_DerivedMesh.h"
72 #include "BKE_exotic.h"
73 #include "BKE_font.h"
74 #include "BKE_global.h"
75 #include "BKE_library.h"
76 #include "BKE_main.h"
77 #include "BKE_packedFile.h"
78 #include "BKE_report.h"
79 #include "BKE_sound.h"
80 #include "BKE_texture.h"
81
82
83 #include "BLO_readfile.h"
84 #include "BLO_writefile.h"
85
86 #include "RNA_access.h"
87
88 #include "IMB_imbuf.h"
89 #include "IMB_imbuf_types.h"
90 #include "IMB_thumbs.h"
91
92 #include "ED_datafiles.h"
93 #include "ED_object.h"
94 #include "ED_screen.h"
95 #include "ED_sculpt.h"
96 #include "ED_view3d.h"
97 #include "ED_util.h"
98
99 #include "RE_pipeline.h" /* only to report missing engine */
100
101 #include "GHOST_C-api.h"
102 #include "GHOST_Path-api.h"
103
104 #include "UI_interface.h"
105
106 #include "GPU_draw.h"
107
108 #ifdef WITH_PYTHON
109 #include "BPY_extern.h"
110 #endif
111
112 #include "WM_api.h"
113 #include "WM_types.h"
114 #include "wm.h"
115 #include "wm_files.h"
116 #include "wm_window.h"
117 #include "wm_event_system.h"
118
119 static void write_history(void);
120
121 /* To be able to read files without windows closing, opening, moving 
122    we try to prepare for worst case:
123    - active window gets active screen from file 
124    - restoring the screens from non-active windows 
125    Best case is all screens match, in that case they get assigned to proper window  
126 */
127 static void wm_window_match_init(bContext *C, ListBase *wmlist)
128 {
129         wmWindowManager *wm;
130         wmWindow *win, *active_win;
131         
132         *wmlist= G.main->wm;
133         G.main->wm.first= G.main->wm.last= NULL;
134         
135         active_win = CTX_wm_window(C);
136
137         /* first wrap up running stuff */
138         /* code copied from wm_init_exit.c */
139         for(wm= wmlist->first; wm; wm= wm->id.next) {
140                 
141                 WM_jobs_stop_all(wm);
142                 
143                 for(win= wm->windows.first; win; win= win->next) {
144                 
145                         CTX_wm_window_set(C, win);      /* needed by operator close callbacks */
146                         WM_event_remove_handlers(C, &win->handlers);
147                         WM_event_remove_handlers(C, &win->modalhandlers);
148                         ED_screen_exit(C, win, win->screen);
149                 }
150         }
151         
152         /* reset active window */
153         CTX_wm_window_set(C, active_win);
154
155         ED_editors_exit(C);
156         
157 return; 
158         if(wm==NULL) return;
159         if(G.fileflags & G_FILE_NO_UI) return;
160         
161         /* we take apart the used screens from non-active window */
162         for(win= wm->windows.first; win; win= win->next) {
163                 BLI_strncpy(win->screenname, win->screen->id.name, MAX_ID_NAME);
164                 if(win!=wm->winactive) {
165                         BLI_remlink(&G.main->screen, win->screen);
166                         //BLI_addtail(screenbase, win->screen);
167                 }
168         }
169 }
170
171 /* match old WM with new, 4 cases:
172   1- no current wm, no read wm: make new default
173   2- no current wm, but read wm: that's OK, do nothing
174   3- current wm, but not in file: try match screen names
175   4- current wm, and wm in file: try match ghostwin 
176 */
177
178 static void wm_window_match_do(bContext *C, ListBase *oldwmlist)
179 {
180         wmWindowManager *oldwm, *wm;
181         wmWindow *oldwin, *win;
182         
183         /* cases 1 and 2 */
184         if(oldwmlist->first==NULL) {
185                 if(G.main->wm.first); /* nothing todo */
186                 else
187                         wm_add_default(C);
188         }
189         else {
190                 /* cases 3 and 4 */
191                 
192                 /* we've read file without wm..., keep current one entirely alive */
193                 if(G.main->wm.first==NULL) {
194                         /* when loading without UI, no matching needed */
195                         if(!(G.fileflags & G_FILE_NO_UI)) {
196                                 bScreen *screen= CTX_wm_screen(C);
197
198                                 /* match oldwm to new dbase, only old files */
199                                 for(wm= oldwmlist->first; wm; wm= wm->id.next) {
200                                         
201                                         for(win= wm->windows.first; win; win= win->next) {
202                                                 /* all windows get active screen from file */
203                                                 if(screen->winid==0)
204                                                         win->screen= screen;
205                                                 else 
206                                                         win->screen= ED_screen_duplicate(win, screen);
207                                                 
208                                                 BLI_strncpy(win->screenname, win->screen->id.name+2, sizeof(win->screenname));
209                                                 win->screen->winid= win->winid;
210                                         }
211                                 }
212                         }
213                         
214                         G.main->wm= *oldwmlist;
215                         
216                         /* screens were read from file! */
217                         ED_screens_initialize(G.main->wm.first);
218                 }
219                 else {
220                         /* what if old was 3, and loaded 1? */
221                         /* this code could move to setup_appdata */
222                         oldwm= oldwmlist->first;
223                         wm= G.main->wm.first;
224
225                         /* ensure making new keymaps and set space types */
226                         wm->initialized= 0;
227                         wm->winactive= NULL;
228                         
229                         /* only first wm in list has ghostwins */
230                         for(win= wm->windows.first; win; win= win->next) {
231                                 for(oldwin= oldwm->windows.first; oldwin; oldwin= oldwin->next) {
232                                         
233                                         if(oldwin->winid == win->winid ) {
234                                                 win->ghostwin= oldwin->ghostwin;
235                                                 win->active= oldwin->active;
236                                                 if(win->active)
237                                                         wm->winactive= win;
238
239                                                 if(!G.background) /* file loading in background mode still calls this */
240                                                         GHOST_SetWindowUserData(win->ghostwin, win);    /* pointer back */
241
242                                                 oldwin->ghostwin= NULL;
243                                                 
244                                                 win->eventstate= oldwin->eventstate;
245                                                 oldwin->eventstate= NULL;
246                                                 
247                                                 /* ensure proper screen rescaling */
248                                                 win->sizex= oldwin->sizex;
249                                                 win->sizey= oldwin->sizey;
250                                                 win->posx= oldwin->posx;
251                                                 win->posy= oldwin->posy;
252                                         }
253                                 }
254                         }
255                         wm_close_and_free_all(C, oldwmlist);
256                 }
257         }
258 }
259
260 /* in case UserDef was read, we re-initialize all, and do versioning */
261 static void wm_init_userdef(bContext *C)
262 {
263         UI_init_userdef();
264         MEM_CacheLimiter_set_maximum(U.memcachelimit * 1024 * 1024);
265         sound_init(CTX_data_main(C));
266
267         /* needed so loading a file from the command line respects user-pref [#26156] */
268         if(U.flag & USER_FILENOUI)      G.fileflags |= G_FILE_NO_UI;
269         else                                            G.fileflags &= ~G_FILE_NO_UI;
270
271         /* set the python auto-execute setting from user prefs */
272         /* enabled by default, unless explicitly enabled in the command line which overrides */
273         if((G.f & G_SCRIPT_OVERRIDE_PREF) == 0) {
274                 if ((U.flag & USER_SCRIPT_AUTOEXEC_DISABLE) == 0) G.f |=  G_SCRIPT_AUTOEXEC;
275                 else                                                                                      G.f &= ~G_SCRIPT_AUTOEXEC;
276         }
277         if(U.tempdir[0]) BLI_where_is_temp(btempdir, FILE_MAX, 1);
278 }
279
280 void WM_read_file(bContext *C, const char *name, ReportList *reports)
281 {
282         int retval;
283
284         /* so we can get the error message */
285         errno = 0;
286
287         WM_cursor_wait(1);
288
289         /* first try to append data from exotic file formats... */
290         /* it throws error box when file doesnt exist and returns -1 */
291         /* note; it should set some error message somewhere... (ton) */
292         retval= BKE_read_exotic(CTX_data_scene(C), name);
293         
294         /* we didn't succeed, now try to read Blender file */
295         if (retval == BKE_READ_EXOTIC_OK_BLEND) {
296                 int G_f= G.f;
297                 ListBase wmbase;
298
299                 /* put aside screens to match with persistant windows later */
300                 /* also exit screens and editors */
301                 wm_window_match_init(C, &wmbase); 
302                 
303                 retval= BKE_read_file(C, name, reports);
304                 G.save_over = 1;
305
306                 /* this flag is initialized by the operator but overwritten on read.
307                  * need to re-enable it here else drivers + registered scripts wont work. */
308                 if(G.f != G_f) {
309                         const int flags_keep= (G_SCRIPT_AUTOEXEC | G_SCRIPT_OVERRIDE_PREF);
310                         G.f= (G.f & ~flags_keep) | (G_f & flags_keep);
311                 }
312
313                 /* match the read WM with current WM */
314                 wm_window_match_do(C, &wmbase);
315                 WM_check(C); /* opens window(s), checks keymaps */
316                 
317 // XXX          mainwindow_set_filename_to_title(G.main->name);
318
319                 if(retval == BKE_READ_FILE_OK_USERPREFS) wm_init_userdef(C);    // in case a userdef is read from regular .blend
320                 
321                 if (retval != BKE_READ_FILE_FAIL) {
322                         G.relbase_valid = 1;
323                         if(!G.background) /* assume automated tasks with background, dont write recent file list */
324                                 write_history();
325                 }
326
327
328                 WM_event_add_notifier(C, NC_WM|ND_FILEREAD, NULL);
329 //              refresh_interface_font();
330
331                 CTX_wm_window_set(C, CTX_wm_manager(C)->windows.first);
332
333                 ED_editors_init(C);
334                 DAG_on_visible_update(CTX_data_main(C), TRUE);
335
336 #ifdef WITH_PYTHON
337                 /* run any texts that were loaded in and flagged as modules */
338                 BPY_driver_reset();
339                 BPY_modules_load_user(C);
340 #endif
341                 CTX_wm_window_set(C, NULL); /* exits queues */
342
343 #if 0   /* gives popups on windows but not linux, bug in report API but disable for now to stop users getting annoyed  */
344                 /* TODO, make this show in header info window */
345                 {
346                         Scene *sce;
347                         for(sce= G.main->scene.first; sce; sce= sce->id.next) {
348                                 if(sce->r.engine[0] && BLI_findstring(&R_engines, sce->r.engine, offsetof(RenderEngineType, idname)) == NULL) {
349                                         BKE_reportf(reports, RPT_WARNING, "Engine not available: '%s' for scene: %s, an addon may need to be installed or enabled", sce->r.engine, sce->id.name+2);
350                                 }
351                         }
352                 }
353 #endif
354
355                 // XXX          undo_editmode_clear();
356                 BKE_reset_undo();
357                 BKE_write_undo(C, "original");  /* save current state */
358                 
359         }
360         else if(retval == BKE_READ_EXOTIC_OK_OTHER)
361                 BKE_write_undo(C, "Import file");
362         else if(retval == BKE_READ_EXOTIC_FAIL_OPEN) {
363                 BKE_reportf(reports, RPT_ERROR, "Can't read file: \"%s\", %s.", name, errno ? strerror(errno) : "Unable to open the file");
364         }
365         else if(retval == BKE_READ_EXOTIC_FAIL_FORMAT) {
366                 BKE_reportf(reports, RPT_ERROR, "File format is not supported in file: \"%s\".", name);
367         }
368         else if(retval == BKE_READ_EXOTIC_FAIL_PATH) {
369                 BKE_reportf(reports, RPT_ERROR, "File path invalid: \"%s\".", name);
370         }
371         else {
372                 BKE_reportf(reports, RPT_ERROR, "Unknown error loading: \"%s\".", name);
373                 BLI_assert(!"invalid 'retval'");
374         }
375
376         WM_cursor_wait(0);
377
378 }
379
380
381 /* called on startup,  (context entirely filled with NULLs) */
382 /* or called for 'New File' */
383 /* op can be NULL */
384 int WM_read_homefile(bContext *C, ReportList *reports, short from_memory)
385 {
386         ListBase wmbase;
387         char tstr[FILE_MAXDIR+FILE_MAXFILE];
388         int success= 0;
389         
390         free_ttfont(); /* still weird... what does it here? */
391                 
392         G.relbase_valid = 0;
393         if (!from_memory) {
394                 char *cfgdir = BLI_get_folder(BLENDER_USER_CONFIG, NULL);
395                 if (cfgdir) {
396                         BLI_make_file_string(G.main->name, tstr, cfgdir, BLENDER_STARTUP_FILE);
397                 } else {
398                         tstr[0] = '\0';
399                         from_memory = 1;
400                         BKE_report(reports, RPT_INFO, "Config directory with "STRINGIFY(BLENDER_STARTUP_FILE)" file not found.");
401                 }
402         }
403         
404         /* prevent loading no UI */
405         G.fileflags &= ~G_FILE_NO_UI;
406         
407         /* put aside screens to match with persistant windows later */
408         wm_window_match_init(C, &wmbase); 
409         
410         if (!from_memory && BLI_exists(tstr)) {
411                 success = (BKE_read_file(C, tstr, NULL) != BKE_READ_FILE_FAIL);
412                 
413                 if(U.themes.first==NULL) {
414                         printf("\nError: No valid "STRINGIFY(BLENDER_STARTUP_FILE)", fall back to built-in default.\n\n");
415                         success = 0;
416                 }
417         }
418         if(success==0) {
419                 success = BKE_read_file_from_memory(C, datatoc_startup_blend, datatoc_startup_blend_size, NULL);
420                 if (wmbase.first == NULL) wm_clear_default_size(C);
421         }
422         
423         /* prevent buggy files that had G_FILE_RELATIVE_REMAP written out by mistake. Screws up autosaves otherwise
424          * can remove this eventually, only in a 2.53 and older, now its not written */
425         G.fileflags &= ~G_FILE_RELATIVE_REMAP;
426
427         /* match the read WM with current WM */
428         wm_window_match_do(C, &wmbase); 
429         WM_check(C); /* opens window(s), checks keymaps */
430
431         G.main->name[0]= '\0';
432
433         wm_init_userdef(C);
434         
435         /* When loading factory settings, the reset solid OpenGL lights need to be applied. */
436         if (!G.background) GPU_default_lights();
437         
438         /* XXX */
439         G.save_over = 0;        // start with save preference untitled.blend
440         G.fileflags &= ~G_FILE_AUTOPLAY;        /*  disable autoplay in startup.blend... */
441 //      mainwindow_set_filename_to_title("");   // empty string re-initializes title to "Blender"
442         
443 //      refresh_interface_font();
444         
445 //      undo_editmode_clear();
446         BKE_reset_undo();
447         BKE_write_undo(C, "original");  /* save current state */
448
449         ED_editors_init(C);
450         DAG_on_visible_update(CTX_data_main(C), TRUE);
451
452 #ifdef WITH_PYTHON
453         if(CTX_py_init_get(C)) {
454                 /* sync addons, these may have changed from the defaults */
455                 BPY_string_exec(C, "__import__('addon_utils').reset_all()");
456
457                 BPY_driver_reset();
458                 BPY_modules_load_user(C);
459         }
460 #endif
461
462         WM_event_add_notifier(C, NC_WM|ND_FILEREAD, NULL);
463
464         /* in background mode the scene will stay NULL */
465         if(!G.background) {
466                 CTX_wm_window_set(C, NULL); /* exits queues */
467         }
468
469         return TRUE;
470 }
471
472 int WM_read_homefile_exec(bContext *C, wmOperator *op)
473 {
474         int from_memory= strcmp(op->type->idname, "WM_OT_read_factory_settings") == 0;
475         return WM_read_homefile(C, op->reports, from_memory) ? OPERATOR_FINISHED : OPERATOR_CANCELLED;
476 }
477
478 void WM_read_history(void)
479 {
480         char name[FILE_MAX];
481         LinkNode *l, *lines;
482         struct RecentFile *recent;
483         char *line;
484         int num;
485         char *cfgdir = BLI_get_folder(BLENDER_CONFIG, NULL);
486
487         if (!cfgdir) return;
488
489         BLI_make_file_string("/", name, cfgdir, BLENDER_HISTORY_FILE);
490
491         lines= BLI_read_file_as_lines(name);
492
493         G.recent_files.first = G.recent_files.last = NULL;
494
495         /* read list of recent opend files from recent-files.txt to memory */
496         for (l= lines, num= 0; l && (num<U.recent_files); l= l->next) {
497                 line = l->link;
498                 if (line[0] && BLI_exists(line)) {
499                         recent = (RecentFile*)MEM_mallocN(sizeof(RecentFile),"RecentFile");
500                         BLI_addtail(&(G.recent_files), recent);
501                         recent->filepath = BLI_strdup(line);
502                         num++;
503                 }
504         }
505         
506         BLI_free_file_lines(lines);
507
508 }
509
510 static void write_history(void)
511 {
512         struct RecentFile *recent, *next_recent;
513         char name[FILE_MAXDIR+FILE_MAXFILE];
514         char *user_config_dir;
515         FILE *fp;
516         int i;
517
518         /* will be NULL in background mode */
519         user_config_dir = BLI_get_folder_create(BLENDER_USER_CONFIG, NULL);
520         if(!user_config_dir)
521                 return;
522
523         BLI_make_file_string("/", name, user_config_dir, BLENDER_HISTORY_FILE);
524
525         recent = G.recent_files.first;
526         /* refresh recent-files.txt of recent opened files, when current file was changed */
527         if(!(recent) || (BLI_path_cmp(recent->filepath, G.main->name)!=0)) {
528                 fp= fopen(name, "w");
529                 if (fp) {
530                         /* add current file to the beginning of list */
531                         recent = (RecentFile*)MEM_mallocN(sizeof(RecentFile),"RecentFile");
532                         recent->filepath = BLI_strdup(G.main->name);
533                         BLI_addhead(&(G.recent_files), recent);
534                         /* write current file to recent-files.txt */
535                         fprintf(fp, "%s\n", recent->filepath);
536                         recent = recent->next;
537                         i=1;
538                         /* write rest of recent opened files to recent-files.txt */
539                         while((i<U.recent_files) && (recent)){
540                                 /* this prevents to have duplicities in list */
541                                 if (BLI_path_cmp(recent->filepath, G.main->name)!=0) {
542                                         fprintf(fp, "%s\n", recent->filepath);
543                                         recent = recent->next;
544                                 }
545                                 else {
546                                         next_recent = recent->next;
547                                         MEM_freeN(recent->filepath);
548                                         BLI_freelinkN(&(G.recent_files), recent);
549                                         recent = next_recent;
550                                 }
551                                 i++;
552                         }
553                         fclose(fp);
554                 }
555
556                 /* also update most recent files on System */
557                 GHOST_addToSystemRecentFiles(G.main->name);
558         }
559 }
560
561 static void do_history(char *name, ReportList *reports)
562 {
563         char tempname1[FILE_MAXDIR+FILE_MAXFILE], tempname2[FILE_MAXDIR+FILE_MAXFILE];
564         int hisnr= U.versions;
565         
566         if(U.versions==0) return;
567         if(strlen(name)<2) return;
568                 
569         while(hisnr > 1) {
570                 BLI_snprintf(tempname1, sizeof(tempname1), "%s%d", name, hisnr-1);
571                 BLI_snprintf(tempname2, sizeof(tempname2), "%s%d", name, hisnr);
572         
573                 if(BLI_rename(tempname1, tempname2))
574                         BKE_report(reports, RPT_ERROR, "Unable to make version backup");
575                         
576                 hisnr--;
577         }
578
579         /* is needed when hisnr==1 */
580         BLI_snprintf(tempname1, sizeof(tempname1), "%s%d", name, hisnr);
581
582         if(BLI_rename(name, tempname1))
583                 BKE_report(reports, RPT_ERROR, "Unable to make version backup");
584 }
585
586 static ImBuf *blend_file_thumb(Scene *scene, int **thumb_pt)
587 {
588         /* will be scaled down, but gives some nice oversampling */
589         ImBuf *ibuf;
590         int *thumb;
591         char err_out[256]= "unknown";
592
593         *thumb_pt= NULL;
594         
595         if(G.background || scene->camera==NULL)
596                 return NULL;
597
598         /* gets scaled to BLEN_THUMB_SIZE */
599         ibuf= ED_view3d_draw_offscreen_imbuf_simple(scene, BLEN_THUMB_SIZE * 2, BLEN_THUMB_SIZE * 2, IB_rect, OB_SOLID, err_out);
600         
601         if(ibuf) {              
602                 float aspect= (scene->r.xsch*scene->r.xasp) / (scene->r.ysch*scene->r.yasp);
603
604                 /* dirty oversampling */
605                 IMB_scaleImBuf(ibuf, BLEN_THUMB_SIZE, BLEN_THUMB_SIZE);
606
607                 /* add pretty overlay */
608                 IMB_overlayblend_thumb(ibuf->rect, ibuf->x, ibuf->y, aspect);
609                 
610                 /* first write into thumb buffer */
611                 thumb= MEM_mallocN(((2 + (BLEN_THUMB_SIZE * BLEN_THUMB_SIZE))) * sizeof(int), "write_file thumb");
612
613                 thumb[0] = BLEN_THUMB_SIZE;
614                 thumb[1] = BLEN_THUMB_SIZE;
615
616                 memcpy(thumb + 2, ibuf->rect, BLEN_THUMB_SIZE * BLEN_THUMB_SIZE * sizeof(int));
617         }
618         else {
619                 /* '*thumb_pt' needs to stay NULL to prevent a bad thumbnail from being handled */
620                 fprintf(stderr, "blend_file_thumb failed to create thumbnail: %s\n", err_out);
621                 thumb= NULL;
622         }
623         
624         /* must be freed by caller */
625         *thumb_pt= thumb;
626         
627         return ibuf;
628 }
629
630 /* easy access from gdb */
631 int write_crash_blend(void)
632 {
633         char path[FILE_MAX];
634         BLI_strncpy(path, G.main->name, sizeof(path));
635         BLI_replace_extension(path, sizeof(path), "_crash.blend");
636         if(BLO_write_file(G.main, path, G.fileflags, NULL, NULL)) {
637                 printf("written: %s\n", path);
638                 return 1;
639         }
640         else {
641                 printf("failed: %s\n", path);
642                 return 0;
643         }
644 }
645
646 int WM_write_file(bContext *C, const char *target, int fileflags, ReportList *reports, int copy)
647 {
648         Library *li;
649         int len;
650         char di[FILE_MAX];
651
652         int *thumb= NULL;
653         ImBuf *ibuf_thumb= NULL;
654
655         len = strlen(target);
656         
657         if (len == 0) {
658                 BKE_report(reports, RPT_ERROR, "Path is empty, cannot save");
659                 return -1;
660         }
661
662         if (len >= FILE_MAX) {
663                 BKE_report(reports, RPT_ERROR, "Path too long, cannot save");
664                 return -1;
665         }
666  
667         BLI_strncpy(di, target, FILE_MAX);
668         BLI_replace_extension(di, FILE_MAX, ".blend");
669         /* dont use 'target' anymore */
670         
671         /* send the OnSave event */
672         for (li= G.main->library.first; li; li= li->id.next) {
673                 if (BLI_path_cmp(li->filepath, di) == 0) {
674                         BKE_reportf(reports, RPT_ERROR, "Can't overwrite used library '%.200s'", di);
675                         return -1;
676                 }
677         }
678
679         /* operator now handles overwrite checks */
680
681         if (G.fileflags & G_AUTOPACK) {
682                 packAll(G.main, reports);
683         }
684         
685         ED_object_exit_editmode(C, EM_DO_UNDO);
686         ED_sculpt_force_update(C);
687
688         /* don't forget not to return without! */
689         WM_cursor_wait(1);
690         
691         /* blend file thumbnail */
692         ibuf_thumb= blend_file_thumb(CTX_data_scene(C), &thumb);
693
694         /* rename to .blend1, do this as last before write */
695         do_history(di, reports);
696
697         if (BLO_write_file(CTX_data_main(C), di, fileflags, reports, thumb)) {
698                 if(!copy) {
699                         G.relbase_valid = 1;
700                         BLI_strncpy(G.main->name, di, sizeof(G.main->name));    /* is guaranteed current file */
701         
702                         G.save_over = 1; /* disable untitled.blend convention */
703                 }
704
705                 if(fileflags & G_FILE_COMPRESS) G.fileflags |= G_FILE_COMPRESS;
706                 else G.fileflags &= ~G_FILE_COMPRESS;
707                 
708                 if(fileflags & G_FILE_AUTOPLAY) G.fileflags |= G_FILE_AUTOPLAY;
709                 else G.fileflags &= ~G_FILE_AUTOPLAY;
710
711                 write_history();
712
713                 /* run this function after because the file cant be written before the blend is */
714                 if (ibuf_thumb) {
715                         ibuf_thumb= IMB_thumb_create(di, THB_NORMAL, THB_SOURCE_BLEND, ibuf_thumb);
716                         IMB_freeImBuf(ibuf_thumb);
717                 }
718
719                 if(thumb) MEM_freeN(thumb);
720         }
721         else {
722                 if(ibuf_thumb) IMB_freeImBuf(ibuf_thumb);
723                 if(thumb) MEM_freeN(thumb);
724                 
725                 WM_cursor_wait(0);
726                 return -1;
727         }
728
729         WM_cursor_wait(0);
730         
731         return 0;
732 }
733
734 /* operator entry */
735 int WM_write_homefile(bContext *C, wmOperator *op)
736 {
737         wmWindowManager *wm= CTX_wm_manager(C);
738         wmWindow *win= CTX_wm_window(C);
739         char tstr[FILE_MAXDIR+FILE_MAXFILE];
740         int fileflags;
741         
742         /* check current window and close it if temp */
743         if(win->screen->temp)
744                 wm_window_close(C, wm, win);
745         
746         BLI_make_file_string("/", tstr, BLI_get_folder_create(BLENDER_USER_CONFIG, NULL), BLENDER_STARTUP_FILE);
747         printf("trying to save homefile at %s ", tstr);
748         
749         /*  force save as regular blend file */
750         fileflags = G.fileflags & ~(G_FILE_COMPRESS | G_FILE_AUTOPLAY | G_FILE_LOCK | G_FILE_SIGN);
751
752         if(BLO_write_file(CTX_data_main(C), tstr, fileflags, op->reports, NULL) == 0) {
753                 printf("fail\n");
754                 return OPERATOR_CANCELLED;
755         }
756         
757         printf("ok\n");
758
759         G.save_over= 0;
760
761         return OPERATOR_FINISHED;
762 }
763
764 /************************ autosave ****************************/
765
766 void wm_autosave_location(char *filename)
767 {
768         char pidstr[32];
769 #ifdef WIN32
770         char *savedir;
771 #endif
772
773         BLI_snprintf(pidstr, sizeof(pidstr), "%d.blend", abs(getpid()));
774
775 #ifdef WIN32
776         /* XXX Need to investigate how to handle default location of '/tmp/'
777          * This is a relative directory on Windows, and it may be
778          * found. Example:
779          * Blender installed on D:\ drive, D:\ drive has D:\tmp\
780          * Now, BLI_exists() will find '/tmp/' exists, but
781          * BLI_make_file_string will create string that has it most likely on C:\
782          * through get_default_root().
783          * If there is no C:\tmp autosave fails. */
784         if (!BLI_exists(U.tempdir)) {
785                 savedir = BLI_get_folder_create(BLENDER_USER_AUTOSAVE, NULL);
786                 BLI_make_file_string("/", filename, savedir, pidstr);
787                 return;
788         }
789 #endif
790         
791         BLI_make_file_string("/", filename, U.tempdir, pidstr);
792 }
793
794 void WM_autosave_init(wmWindowManager *wm)
795 {
796         wm_autosave_timer_ended(wm);
797
798         if(U.flag & USER_AUTOSAVE)
799                 wm->autosavetimer= WM_event_add_timer(wm, NULL, TIMERAUTOSAVE, U.savetime*60.0);
800 }
801
802 void wm_autosave_timer(const bContext *C, wmWindowManager *wm, wmTimer *UNUSED(wt))
803 {
804         wmWindow *win;
805         wmEventHandler *handler;
806         char filename[FILE_MAX];
807         int fileflags;
808
809         WM_event_remove_timer(wm, NULL, wm->autosavetimer);
810
811         /* if a modal operator is running, don't autosave, but try again in 10 seconds */
812         for(win=wm->windows.first; win; win=win->next) {
813                 for(handler=win->modalhandlers.first; handler; handler=handler->next) {
814                         if(handler->op) {
815                                 wm->autosavetimer= WM_event_add_timer(wm, NULL, TIMERAUTOSAVE, 10.0);
816                                 return;
817                         }
818                 }
819         }
820         
821         wm_autosave_location(filename);
822
823         /*  force save as regular blend file */
824         fileflags = G.fileflags & ~(G_FILE_COMPRESS|G_FILE_AUTOPLAY |G_FILE_LOCK|G_FILE_SIGN);
825
826         /* no error reporting to console */
827         BLO_write_file(CTX_data_main(C), filename, fileflags, NULL, NULL);
828
829         /* do timer after file write, just in case file write takes a long time */
830         wm->autosavetimer= WM_event_add_timer(wm, NULL, TIMERAUTOSAVE, U.savetime*60.0);
831 }
832
833 void wm_autosave_timer_ended(wmWindowManager *wm)
834 {
835         if(wm->autosavetimer) {
836                 WM_event_remove_timer(wm, NULL, wm->autosavetimer);
837                 wm->autosavetimer= NULL;
838         }
839 }
840
841 void wm_autosave_delete(void)
842 {
843         char filename[FILE_MAX];
844         
845         wm_autosave_location(filename);
846
847         if(BLI_exists(filename)) {
848                 char str[FILE_MAXDIR+FILE_MAXFILE];
849                 BLI_make_file_string("/", str, U.tempdir, "quit.blend");
850
851                 /* if global undo; remove tempsave, otherwise rename */
852                 if(U.uiflag & USER_GLOBALUNDO) BLI_delete(filename, 0, 0);
853                 else BLI_rename(filename, str);
854         }
855 }
856
857 void wm_autosave_read(bContext *C, ReportList *reports)
858 {
859         char filename[FILE_MAX];
860
861         wm_autosave_location(filename);
862         WM_read_file(C, filename, reports);
863 }
864