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