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