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