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