split BKE_utildefines.h, now it only has blender specific defines like GS() MAKE_ID...
[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 #include "BKE_utildefines.h"
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= G.main->wm.first;
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                 BKE_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, wmOperator *op)
356 {
357         ListBase wmbase;
358         char tstr[FILE_MAXDIR+FILE_MAXFILE];
359         int from_memory= op && strcmp(op->type->idname, "WM_OT_read_factory_settings")==0;
360         int success= 0;
361         
362         free_ttfont(); /* still weird... what does it here? */
363                 
364         G.relbase_valid = 0;
365         if (!from_memory) {
366                 char *cfgdir = BLI_get_folder(BLENDER_USER_CONFIG, NULL);
367                 if (cfgdir) {
368                         BLI_make_file_string(G.main->name, tstr, cfgdir, BLENDER_STARTUP_FILE);
369                 } else {
370                         tstr[0] = '\0';
371                         from_memory = 1;
372                         if (op) {
373                                 BKE_report(op->reports, RPT_INFO, "Config directory with startup.blend file not found."); 
374                         }
375                 }
376         }
377         
378         /* prevent loading no UI */
379         G.fileflags &= ~G_FILE_NO_UI;
380         
381         /* put aside screens to match with persistant windows later */
382         wm_window_match_init(C, &wmbase); 
383         
384         if (!from_memory && BLI_exists(tstr)) {
385                 success = (BKE_read_file(C, tstr, NULL) != BKE_READ_FILE_FAIL);
386                 
387                 if(U.themes.first==NULL) {
388                         printf("\nError: No valid startup.blend, fall back to built-in default.\n\n");
389                         success = 0;
390                 }
391         }
392         if(success==0) {
393                 success = BKE_read_file_from_memory(C, datatoc_startup_blend, datatoc_startup_blend_size, NULL);
394                 if (wmbase.first == NULL) wm_clear_default_size(C);
395         }
396         
397         /* prevent buggy files that had G_FILE_RELATIVE_REMAP written out by mistake. Screws up autosaves otherwise
398          * can remove this eventually, only in a 2.53 and older, now its not written */
399         G.fileflags &= ~G_FILE_RELATIVE_REMAP;
400
401         /* match the read WM with current WM */
402         wm_window_match_do(C, &wmbase); 
403         WM_check(C); /* opens window(s), checks keymaps */
404
405         G.main->name[0]= '\0';
406
407         wm_init_userdef(C);
408         
409         /* When loading factory settings, the reset solid OpenGL lights need to be applied. */
410         if (!G.background) GPU_default_lights();
411         
412         /* XXX */
413         G.save_over = 0;        // start with save preference untitled.blend
414         G.fileflags &= ~G_FILE_AUTOPLAY;        /*  disable autoplay in startup.blend... */
415 //      mainwindow_set_filename_to_title("");   // empty string re-initializes title to "Blender"
416         
417 //      refresh_interface_font();
418         
419 //      undo_editmode_clear();
420         BKE_reset_undo();
421         BKE_write_undo(C, "original");  /* save current state */
422
423         ED_editors_init(C);
424         DAG_on_load_update(CTX_data_main(C), TRUE);
425
426 #ifdef WITH_PYTHON
427         if(CTX_py_init_get(C)) {
428                 /* sync addons, these may have changed from the defaults */
429                 BPY_string_exec(C, "__import__('bpy').utils.addon_reset_all()");
430
431                 BPY_driver_reset();
432                 BPY_modules_load_user(C);
433         }
434 #endif
435         
436         WM_event_add_notifier(C, NC_WM|ND_FILEREAD, NULL);
437         CTX_wm_window_set(C, NULL); /* exits queues */
438
439         return OPERATOR_FINISHED;
440 }
441
442
443 void read_history(void)
444 {
445         char name[FILE_MAX];
446         LinkNode *l, *lines;
447         struct RecentFile *recent;
448         char *line;
449         int num;
450         char *cfgdir = BLI_get_folder(BLENDER_CONFIG, NULL);
451
452         if (!cfgdir) return;
453
454         BLI_make_file_string("/", name, cfgdir, BLENDER_HISTORY_FILE);
455
456         lines= BLI_read_file_as_lines(name);
457
458         G.recent_files.first = G.recent_files.last = NULL;
459
460         /* read list of recent opend files from recent-files.txt to memory */
461         for (l= lines, num= 0; l && (num<U.recent_files); l= l->next) {
462                 line = l->link;
463                 if (line[0] && BLI_exists(line)) {
464                         recent = (RecentFile*)MEM_mallocN(sizeof(RecentFile),"RecentFile");
465                         BLI_addtail(&(G.recent_files), recent);
466                         recent->filepath = (char*)MEM_mallocN(sizeof(char)*(strlen(line)+1), "name of file");
467                         recent->filepath[0] = '\0';
468                         
469                         strcpy(recent->filepath, line);
470                         num++;
471                 }
472         }
473         
474         BLI_free_file_lines(lines);
475
476 }
477
478 static void write_history(void)
479 {
480         struct RecentFile *recent, *next_recent;
481         char name[FILE_MAXDIR+FILE_MAXFILE];
482         char *user_config_dir;
483         FILE *fp;
484         int i;
485
486         /* will be NULL in background mode */
487         user_config_dir = BLI_get_folder_create(BLENDER_USER_CONFIG, NULL);
488         if(!user_config_dir)
489                 return;
490
491         BLI_make_file_string("/", name, user_config_dir, BLENDER_HISTORY_FILE);
492
493         recent = G.recent_files.first;
494         /* refresh recent-files.txt of recent opened files, when current file was changed */
495         if(!(recent) || (strcmp(recent->filepath, G.main->name)!=0)) {
496                 fp= fopen(name, "w");
497                 if (fp) {
498                         /* add current file to the beginning of list */
499                         recent = (RecentFile*)MEM_mallocN(sizeof(RecentFile),"RecentFile");
500                         recent->filepath = (char*)MEM_mallocN(sizeof(char)*(strlen(G.main->name)+1), "name of file");
501                         recent->filepath[0] = '\0';
502                         strcpy(recent->filepath, G.main->name);
503                         BLI_addhead(&(G.recent_files), recent);
504                         /* write current file to recent-files.txt */
505                         fprintf(fp, "%s\n", recent->filepath);
506                         recent = recent->next;
507                         i=1;
508                         /* write rest of recent opened files to recent-files.txt */
509                         while((i<U.recent_files) && (recent)){
510                                 /* this prevents to have duplicities in list */
511                                 if (strcmp(recent->filepath, G.main->name)!=0) {
512                                         fprintf(fp, "%s\n", recent->filepath);
513                                         recent = recent->next;
514                                 }
515                                 else {
516                                         next_recent = recent->next;
517                                         MEM_freeN(recent->filepath);
518                                         BLI_freelinkN(&(G.recent_files), recent);
519                                         recent = next_recent;
520                                 }
521                                 i++;
522                         }
523                         fclose(fp);
524                 }
525
526                 /* also update most recent files on System */
527                 GHOST_addToSystemRecentFiles(G.main->name);
528         }
529 }
530
531 static void do_history(char *name, ReportList *reports)
532 {
533         char tempname1[FILE_MAXDIR+FILE_MAXFILE], tempname2[FILE_MAXDIR+FILE_MAXFILE];
534         int hisnr= U.versions;
535         
536         if(U.versions==0) return;
537         if(strlen(name)<2) return;
538                 
539         while(hisnr > 1) {
540                 sprintf(tempname1, "%s%d", name, hisnr-1);
541                 sprintf(tempname2, "%s%d", name, hisnr);
542         
543                 if(BLI_rename(tempname1, tempname2))
544                         BKE_report(reports, RPT_ERROR, "Unable to make version backup");
545                         
546                 hisnr--;
547         }
548                 
549         /* is needed when hisnr==1 */
550         sprintf(tempname1, "%s%d", name, hisnr);
551         
552         if(BLI_rename(name, tempname1))
553                 BKE_report(reports, RPT_ERROR, "Unable to make version backup");
554 }
555
556 static ImBuf *blend_file_thumb(Scene *scene, int **thumb_pt)
557 {
558         /* will be scaled down, but gives some nice oversampling */
559         ImBuf *ibuf;
560         int *thumb;
561
562         *thumb_pt= NULL;
563         
564         if(G.background || scene->camera==NULL)
565                 return NULL;
566
567         /* gets scaled to BLEN_THUMB_SIZE */
568         ibuf= ED_view3d_draw_offscreen_imbuf_simple(scene, BLEN_THUMB_SIZE * 2, BLEN_THUMB_SIZE * 2, IB_rect, OB_SOLID);
569         
570         if(ibuf) {              
571                 float aspect= (scene->r.xsch*scene->r.xasp) / (scene->r.ysch*scene->r.yasp);
572
573                 /* dirty oversampling */
574                 IMB_scaleImBuf(ibuf, BLEN_THUMB_SIZE, BLEN_THUMB_SIZE);
575
576                 /* add pretty overlay */
577                 IMB_overlayblend_thumb(ibuf->rect, ibuf->x, ibuf->y, aspect);
578                 
579                 /* first write into thumb buffer */
580                 thumb= MEM_mallocN(((2 + (BLEN_THUMB_SIZE * BLEN_THUMB_SIZE))) * sizeof(int), "write_file thumb");
581
582                 thumb[0] = BLEN_THUMB_SIZE;
583                 thumb[1] = BLEN_THUMB_SIZE;
584
585                 memcpy(thumb + 2, ibuf->rect, BLEN_THUMB_SIZE * BLEN_THUMB_SIZE * sizeof(int));
586         }
587         else {
588                 /* '*thumb_pt' needs to stay NULL to prevent a bad thumbnail from being handled */
589                 thumb= NULL;
590         }
591         
592         /* must be freed by caller */
593         *thumb_pt= thumb;
594         
595         return ibuf;
596 }
597
598 /* easy access from gdb */
599 int write_crash_blend(void)
600 {
601         char path[FILE_MAX];
602         BLI_strncpy(path, G.main->name, sizeof(path));
603         BLI_replace_extension(path, sizeof(path), "_crash.blend");
604         if(BLO_write_file(G.main, path, G.fileflags, NULL, NULL)) {
605                 printf("written: %s\n", path);
606                 return 1;
607         }
608         else {
609                 printf("failed: %s\n", path);
610                 return 0;
611         }
612 }
613
614 int WM_write_file(bContext *C, const char *target, int fileflags, ReportList *reports, int copy)
615 {
616         Library *li;
617         int len;
618         char di[FILE_MAX];
619
620         int *thumb= NULL;
621         ImBuf *ibuf_thumb= NULL;
622
623         len = strlen(target);
624         
625         if (len == 0) {
626                 BKE_report(reports, RPT_ERROR, "Path is empty, cannot save");
627                 return -1;
628         }
629
630         if (len >= FILE_MAX) {
631                 BKE_report(reports, RPT_ERROR, "Path too long, cannot save");
632                 return -1;
633         }
634  
635         BLI_strncpy(di, target, FILE_MAX);
636         BLI_replace_extension(di, FILE_MAX, ".blend");
637         /* dont use 'target' anymore */
638         
639         /* send the OnSave event */
640         for (li= G.main->library.first; li; li= li->id.next) {
641                 if (strcmp(li->filepath, di) == 0) {
642                         BKE_reportf(reports, RPT_ERROR, "Can't overwrite used library '%.200s'", di);
643                         return -1;
644                 }
645         }
646
647         /* operator now handles overwrite checks */
648
649         if (G.fileflags & G_AUTOPACK) {
650                 packAll(G.main, reports);
651         }
652         
653         ED_object_exit_editmode(C, EM_DO_UNDO);
654         ED_sculpt_force_update(C);
655
656         /* don't forget not to return without! */
657         WM_cursor_wait(1);
658         
659         /* blend file thumbnail */
660         ibuf_thumb= blend_file_thumb(CTX_data_scene(C), &thumb);
661
662         /* rename to .blend1, do this as last before write */
663         do_history(di, reports);
664
665         if (BLO_write_file(CTX_data_main(C), di, fileflags, reports, thumb)) {
666                 if(!copy) {
667                         G.relbase_valid = 1;
668                         strcpy(G.main->name, di);       /* is guaranteed current file */
669         
670                         G.save_over = 1; /* disable untitled.blend convention */
671                 }
672
673                 if(fileflags & G_FILE_COMPRESS) G.fileflags |= G_FILE_COMPRESS;
674                 else G.fileflags &= ~G_FILE_COMPRESS;
675                 
676                 if(fileflags & G_FILE_AUTOPLAY) G.fileflags |= G_FILE_AUTOPLAY;
677                 else G.fileflags &= ~G_FILE_AUTOPLAY;
678
679                 write_history();
680
681                 /* run this function after because the file cant be written before the blend is */
682                 if (ibuf_thumb) {
683                         ibuf_thumb= IMB_thumb_create(di, THB_NORMAL, THB_SOURCE_BLEND, ibuf_thumb);
684                         IMB_freeImBuf(ibuf_thumb);
685                 }
686
687                 if(thumb) MEM_freeN(thumb);
688         }
689         else {
690                 if(ibuf_thumb) IMB_freeImBuf(ibuf_thumb);
691                 if(thumb) MEM_freeN(thumb);
692                 
693                 WM_cursor_wait(0);
694                 return -1;
695         }
696
697         WM_cursor_wait(0);
698         
699         return 0;
700 }
701
702 /* operator entry */
703 int WM_write_homefile(bContext *C, wmOperator *op)
704 {
705         wmWindowManager *wm= CTX_wm_manager(C);
706         wmWindow *win= CTX_wm_window(C);
707         char tstr[FILE_MAXDIR+FILE_MAXFILE];
708         int fileflags;
709         
710         /* check current window and close it if temp */
711         if(win->screen->temp)
712                 wm_window_close(C, wm, win);
713         
714         BLI_make_file_string("/", tstr, BLI_get_folder_create(BLENDER_USER_CONFIG, NULL), BLENDER_STARTUP_FILE);
715         printf("trying to save homefile at %s ", tstr);
716         
717         /*  force save as regular blend file */
718         fileflags = G.fileflags & ~(G_FILE_COMPRESS | G_FILE_AUTOPLAY | G_FILE_LOCK | G_FILE_SIGN);
719
720         if(BLO_write_file(CTX_data_main(C), tstr, fileflags, op->reports, NULL) == 0) {
721                 printf("fail\n");
722                 return OPERATOR_CANCELLED;
723         }
724         
725         printf("ok\n");
726
727         G.save_over= 0;
728
729         return OPERATOR_FINISHED;
730 }
731
732 /************************ autosave ****************************/
733
734 void wm_autosave_location(char *filename)
735 {
736         char pidstr[32];
737 #ifdef WIN32
738         char *savedir;
739 #endif
740
741         sprintf(pidstr, "%d.blend", abs(getpid()));
742         
743 #ifdef WIN32
744         /* XXX Need to investigate how to handle default location of '/tmp/'
745          * This is a relative directory on Windows, and it may be
746          * found. Example:
747          * Blender installed on D:\ drive, D:\ drive has D:\tmp\
748          * Now, BLI_exists() will find '/tmp/' exists, but
749          * BLI_make_file_string will create string that has it most likely on C:\
750          * through get_default_root().
751          * If there is no C:\tmp autosave fails. */
752         if (!BLI_exists(U.tempdir)) {
753                 savedir = BLI_get_folder_create(BLENDER_USER_AUTOSAVE, NULL);
754                 BLI_make_file_string("/", filename, savedir, pidstr);
755                 return;
756         }
757 #endif
758         
759         BLI_make_file_string("/", filename, U.tempdir, pidstr);
760 }
761
762 void WM_autosave_init(wmWindowManager *wm)
763 {
764         wm_autosave_timer_ended(wm);
765
766         if(U.flag & USER_AUTOSAVE)
767                 wm->autosavetimer= WM_event_add_timer(wm, NULL, TIMERAUTOSAVE, U.savetime*60.0);
768 }
769
770 void wm_autosave_timer(const bContext *C, wmWindowManager *wm, wmTimer *UNUSED(wt))
771 {
772         wmWindow *win;
773         wmEventHandler *handler;
774         char filename[FILE_MAX];
775         int fileflags;
776
777         WM_event_remove_timer(wm, NULL, wm->autosavetimer);
778
779         /* if a modal operator is running, don't autosave, but try again in 10 seconds */
780         for(win=wm->windows.first; win; win=win->next) {
781                 for(handler=win->modalhandlers.first; handler; handler=handler->next) {
782                         if(handler->op) {
783                                 wm->autosavetimer= WM_event_add_timer(wm, NULL, TIMERAUTOSAVE, 10.0);
784                                 return;
785                         }
786                 }
787         }
788         
789         wm_autosave_location(filename);
790
791         /*  force save as regular blend file */
792         fileflags = G.fileflags & ~(G_FILE_COMPRESS|G_FILE_AUTOPLAY |G_FILE_LOCK|G_FILE_SIGN);
793
794         /* no error reporting to console */
795         BLO_write_file(CTX_data_main(C), filename, fileflags, NULL, NULL);
796
797         /* do timer after file write, just in case file write takes a long time */
798         wm->autosavetimer= WM_event_add_timer(wm, NULL, TIMERAUTOSAVE, U.savetime*60.0);
799 }
800
801 void wm_autosave_timer_ended(wmWindowManager *wm)
802 {
803         if(wm->autosavetimer) {
804                 WM_event_remove_timer(wm, NULL, wm->autosavetimer);
805                 wm->autosavetimer= NULL;
806         }
807 }
808
809 void wm_autosave_delete(void)
810 {
811         char filename[FILE_MAX];
812         
813         wm_autosave_location(filename);
814
815         if(BLI_exists(filename)) {
816                 char str[FILE_MAXDIR+FILE_MAXFILE];
817                 BLI_make_file_string("/", str, U.tempdir, "quit.blend");
818
819                 /* if global undo; remove tempsave, otherwise rename */
820                 if(U.uiflag & USER_GLOBALUNDO) BLI_delete(filename, 0, 0);
821                 else BLI_rename(filename, str);
822         }
823 }
824
825 void wm_autosave_read(bContext *C, ReportList *reports)
826 {
827         char filename[FILE_MAX];
828
829         wm_autosave_location(filename);
830         WM_read_file(C, filename, reports);
831 }
832