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