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