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