Fix #32209: Autosave ignores multires sculpting
[blender.git] / source / blender / windowmanager / intern / wm_files.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version. 
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * Contributor(s): Blender Foundation 2007
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file blender/windowmanager/intern/wm_files.c
27  *  \ingroup wm
28  */
29
30
31 /* placed up here because of crappy
32  * winsock stuff.
33  */
34 #include <stddef.h>
35 #include <string.h>
36 #include <errno.h>
37
38 #include "zlib.h" /* wm_read_exotic() */
39
40 #ifdef WIN32
41 #  include <windows.h> /* need to include windows.h so _WIN32_IE is defined  */
42 #  ifndef _WIN32_IE
43 #    define _WIN32_IE 0x0400 /* minimal requirements for SHGetSpecialFolderPath on MINGW MSVC has this defined already */
44 #  endif
45 #  include <shlobj.h>  /* for SHGetSpecialFolderPath, has to be done before BLI_winstuff
46                         * because 'near' is disabled through BLI_windstuff */
47 #  include <process.h> /* getpid */
48 #  include "BLI_winstuff.h"
49 #else
50 #  include <unistd.h> /* getpid */
51 #endif
52
53 #include "MEM_guardedalloc.h"
54 #include "MEM_CacheLimiterC-Api.h"
55
56 #include "BLI_blenlib.h"
57 #include "BLI_linklist.h"
58 #include "BLI_utildefines.h"
59 #include "BLI_callbacks.h"
60
61 #include "BLF_translation.h"
62
63 #include "DNA_anim_types.h"
64 #include "DNA_ipo_types.h" // XXX old animation system
65 #include "DNA_object_types.h"
66 #include "DNA_space_types.h"
67 #include "DNA_userdef_types.h"
68 #include "DNA_scene_types.h"
69 #include "DNA_screen_types.h"
70 #include "DNA_windowmanager_types.h"
71
72 #include "BKE_blender.h"
73 #include "BKE_context.h"
74 #include "BKE_depsgraph.h"
75 #include "BKE_DerivedMesh.h"
76 #include "BKE_font.h"
77 #include "BKE_global.h"
78 #include "BKE_library.h"
79 #include "BKE_main.h"
80 #include "BKE_multires.h"
81 #include "BKE_packedFile.h"
82 #include "BKE_report.h"
83 #include "BKE_sound.h"
84 #include "BKE_screen.h"
85 #include "BKE_texture.h"
86
87
88 #include "BLO_readfile.h"
89 #include "BLO_writefile.h"
90
91 #include "RNA_access.h"
92
93 #include "IMB_imbuf.h"
94 #include "IMB_imbuf_types.h"
95 #include "IMB_thumbs.h"
96
97 #include "ED_datafiles.h"
98 #include "ED_object.h"
99 #include "ED_screen.h"
100 #include "ED_sculpt.h"
101 #include "ED_view3d.h"
102 #include "ED_util.h"
103
104 #include "RE_pipeline.h" /* only to report missing engine */
105
106 #include "GHOST_C-api.h"
107 #include "GHOST_Path-api.h"
108
109 #include "UI_interface.h"
110
111 #include "GPU_draw.h"
112
113 #ifdef WITH_PYTHON
114 #include "BPY_extern.h"
115 #endif
116
117 #include "WM_api.h"
118 #include "WM_types.h"
119 #include "wm.h"
120 #include "wm_files.h"
121 #include "wm_window.h"
122 #include "wm_event_system.h"
123
124 static void write_history(void);
125
126 /* To be able to read files without windows closing, opening, moving
127  * we try to prepare for worst case:
128  * - active window gets active screen from file
129  * - restoring the screens from non-active windows
130  * Best case is all screens match, in that case they get assigned to proper window
131  */
132 static void wm_window_match_init(bContext *C, ListBase *wmlist)
133 {
134         wmWindowManager *wm;
135         wmWindow *win, *active_win;
136         
137         *wmlist = G.main->wm;
138         G.main->wm.first = G.main->wm.last = NULL;
139         
140         active_win = CTX_wm_window(C);
141
142         /* first wrap up running stuff */
143         /* code copied from wm_init_exit.c */
144         for (wm = wmlist->first; wm; wm = wm->id.next) {
145                 
146                 WM_jobs_stop_all(wm);
147                 
148                 for (win = wm->windows.first; win; win = win->next) {
149                 
150                         CTX_wm_window_set(C, win);  /* needed by operator close callbacks */
151                         WM_event_remove_handlers(C, &win->handlers);
152                         WM_event_remove_handlers(C, &win->modalhandlers);
153                         ED_screen_exit(C, win, win->screen);
154                 }
155         }
156         
157         /* reset active window */
158         CTX_wm_window_set(C, active_win);
159
160         ED_editors_exit(C);
161
162         /* just had return; here from r12991, this code could just get removed?*/
163 #if 0
164         if (wm == NULL) return;
165         if (G.fileflags & G_FILE_NO_UI) return;
166         
167         /* we take apart the used screens from non-active window */
168         for (win = wm->windows.first; win; win = win->next) {
169                 BLI_strncpy(win->screenname, win->screen->id.name, MAX_ID_NAME);
170                 if (win != wm->winactive) {
171                         BLI_remlink(&G.main->screen, win->screen);
172                         //BLI_addtail(screenbase, win->screen);
173                 }
174         }
175 #endif
176 }
177
178 /* match old WM with new, 4 cases:
179  * 1- no current wm, no read wm: make new default
180  * 2- no current wm, but read wm: that's OK, do nothing
181  * 3- current wm, but not in file: try match screen names
182  * 4- current wm, and wm in file: try match ghostwin
183  */
184
185 static void wm_window_match_do(bContext *C, ListBase *oldwmlist)
186 {
187         wmWindowManager *oldwm, *wm;
188         wmWindow *oldwin, *win;
189         
190         /* cases 1 and 2 */
191         if (oldwmlist->first == NULL) {
192                 if (G.main->wm.first) ;  /* nothing todo */
193                 else
194                         wm_add_default(C);
195         }
196         else {
197                 /* cases 3 and 4 */
198                 
199                 /* we've read file without wm..., keep current one entirely alive */
200                 if (G.main->wm.first == NULL) {
201                         bScreen *screen = NULL;
202
203                         /* when loading without UI, no matching needed */
204                         if (!(G.fileflags & G_FILE_NO_UI) && (screen = CTX_wm_screen(C))) {
205
206                                 /* match oldwm to new dbase, only old files */
207                                 for (wm = oldwmlist->first; wm; wm = wm->id.next) {
208                                         
209                                         for (win = wm->windows.first; win; win = win->next) {
210                                                 /* all windows get active screen from file */
211                                                 if (screen->winid == 0)
212                                                         win->screen = screen;
213                                                 else 
214                                                         win->screen = ED_screen_duplicate(win, screen);
215                                                 
216                                                 BLI_strncpy(win->screenname, win->screen->id.name + 2, sizeof(win->screenname));
217                                                 win->screen->winid = win->winid;
218                                         }
219                                 }
220                         }
221                         
222                         G.main->wm = *oldwmlist;
223                         
224                         /* screens were read from file! */
225                         ED_screens_initialize(G.main->wm.first);
226                 }
227                 else {
228                         /* what if old was 3, and loaded 1? */
229                         /* this code could move to setup_appdata */
230                         oldwm = oldwmlist->first;
231                         wm = G.main->wm.first;
232
233                         /* preserve key configurations in new wm, to preserve their keymaps */
234                         wm->keyconfigs = oldwm->keyconfigs;
235                         wm->addonconf = oldwm->addonconf;
236                         wm->defaultconf = oldwm->defaultconf;
237                         wm->userconf = oldwm->userconf;
238
239                         oldwm->keyconfigs.first = oldwm->keyconfigs.last = NULL;
240                         oldwm->addonconf = NULL;
241                         oldwm->defaultconf = NULL;
242                         oldwm->userconf = NULL;
243
244                         /* ensure making new keymaps and set space types */
245                         wm->initialized = 0;
246                         wm->winactive = NULL;
247                         
248                         /* only first wm in list has ghostwins */
249                         for (win = wm->windows.first; win; win = win->next) {
250                                 for (oldwin = oldwm->windows.first; oldwin; oldwin = oldwin->next) {
251                                         
252                                         if (oldwin->winid == win->winid) {
253                                                 win->ghostwin = oldwin->ghostwin;
254                                                 win->active = oldwin->active;
255                                                 if (win->active)
256                                                         wm->winactive = win;
257
258                                                 if (!G.background) /* file loading in background mode still calls this */
259                                                         GHOST_SetWindowUserData(win->ghostwin, win);    /* pointer back */
260
261                                                 oldwin->ghostwin = NULL;
262                                                 
263                                                 win->eventstate = oldwin->eventstate;
264                                                 oldwin->eventstate = NULL;
265                                                 
266                                                 /* ensure proper screen rescaling */
267                                                 win->sizex = oldwin->sizex;
268                                                 win->sizey = oldwin->sizey;
269                                                 win->posx = oldwin->posx;
270                                                 win->posy = oldwin->posy;
271                                         }
272                                 }
273                         }
274                         wm_close_and_free_all(C, oldwmlist);
275                 }
276         }
277 }
278
279 /* in case UserDef was read, we re-initialize all, and do versioning */
280 static void wm_init_userdef(bContext *C)
281 {
282         UI_init_userdef();
283         MEM_CacheLimiter_set_maximum(((size_t)U.memcachelimit) * 1024 * 1024);
284         sound_init(CTX_data_main(C));
285
286         /* needed so loading a file from the command line respects user-pref [#26156] */
287         if (U.flag & USER_FILENOUI) G.fileflags |= G_FILE_NO_UI;
288         else G.fileflags &= ~G_FILE_NO_UI;
289
290         /* set the python auto-execute setting from user prefs */
291         /* enabled by default, unless explicitly enabled in the command line which overrides */
292         if ((G.f & G_SCRIPT_OVERRIDE_PREF) == 0) {
293                 if ((U.flag & USER_SCRIPT_AUTOEXEC_DISABLE) == 0) G.f |=  G_SCRIPT_AUTOEXEC;
294                 else G.f &= ~G_SCRIPT_AUTOEXEC;
295         }
296
297         /* update tempdir from user preferences */
298         BLI_init_temporary_dir(U.tempdir);
299 }
300
301
302
303 /* return codes */
304 #define BKE_READ_EXOTIC_FAIL_PATH       -3 /* file format is not supported */
305 #define BKE_READ_EXOTIC_FAIL_FORMAT     -2 /* file format is not supported */
306 #define BKE_READ_EXOTIC_FAIL_OPEN       -1 /* Can't open the file */
307 #define BKE_READ_EXOTIC_OK_BLEND         0 /* .blend file */
308 #define BKE_READ_EXOTIC_OK_OTHER         1 /* other supported formats */
309
310
311 /* intended to check for non-blender formats but for now it only reads blends */
312 static int wm_read_exotic(Scene *UNUSED(scene), const char *name)
313 {
314         int len;
315         gzFile gzfile;
316         char header[7];
317         int retval;
318
319         /* make sure we're not trying to read a directory.... */
320
321         len = strlen(name);
322         if (ELEM(name[len - 1], '/', '\\')) {
323                 retval = BKE_READ_EXOTIC_FAIL_PATH;
324         }
325         else {
326                 gzfile = BLI_gzopen(name, "rb");
327                 if (gzfile == NULL) {
328                         retval = BKE_READ_EXOTIC_FAIL_OPEN;
329                 }
330                 else {
331                         len = gzread(gzfile, header, sizeof(header));
332                         gzclose(gzfile);
333                         if (len == sizeof(header) && strncmp(header, "BLENDER", 7) == 0) {
334                                 retval = BKE_READ_EXOTIC_OK_BLEND;
335                         }
336                         else {
337 #if 0           /* historic stuff - no longer used */
338                                 WM_cursor_wait(TRUE);
339
340                                 if (is_foo_format(name)) {
341                                         read_foo(name);
342                                         retval = BKE_READ_EXOTIC_OK_OTHER;
343                                 }
344                                 else
345 #endif
346                                 {
347                                         retval = BKE_READ_EXOTIC_FAIL_FORMAT;
348                                 }
349 #if 0
350                                 WM_cursor_wait(FALSE);
351 #endif
352                         }
353                 }
354         }
355
356         return retval;
357 }
358
359 void WM_read_file(bContext *C, const char *filepath, ReportList *reports)
360 {
361         int retval;
362
363         /* so we can get the error message */
364         errno = 0;
365
366         WM_cursor_wait(1);
367
368         BLI_callback_exec(CTX_data_main(C), NULL, BLI_CB_EVT_LOAD_PRE);
369
370         /* first try to append data from exotic file formats... */
371         /* it throws error box when file doesn't exist and returns -1 */
372         /* note; it should set some error message somewhere... (ton) */
373         retval = wm_read_exotic(CTX_data_scene(C), filepath);
374         
375         /* we didn't succeed, now try to read Blender file */
376         if (retval == BKE_READ_EXOTIC_OK_BLEND) {
377                 int G_f = G.f;
378                 ListBase wmbase;
379
380                 /* assume automated tasks with background, don't write recent file list */
381                 const int do_history = (G.background == FALSE) && (CTX_wm_manager(C)->op_undo_depth == 0);
382
383                 /* put aside screens to match with persistent windows later */
384                 /* also exit screens and editors */
385                 wm_window_match_init(C, &wmbase); 
386                 
387                 retval = BKE_read_file(C, filepath, reports);
388                 G.save_over = 1;
389
390                 /* this flag is initialized by the operator but overwritten on read.
391                  * need to re-enable it here else drivers + registered scripts wont work. */
392                 if (G.f != G_f) {
393                         const int flags_keep = (G_SCRIPT_AUTOEXEC | G_SCRIPT_OVERRIDE_PREF);
394                         G.f = (G.f & ~flags_keep) | (G_f & flags_keep);
395                 }
396
397                 /* match the read WM with current WM */
398                 wm_window_match_do(C, &wmbase);
399                 WM_check(C); /* opens window(s), checks keymaps */
400
401                 if (retval == BKE_READ_FILE_OK_USERPREFS) {
402                         /* in case a userdef is read from regular .blend */
403                         wm_init_userdef(C);
404                 }
405                 
406                 if (retval != BKE_READ_FILE_FAIL) {
407                         G.relbase_valid = 1;
408                         if (do_history) {
409                                 write_history();
410                         }
411                 }
412
413
414                 WM_event_add_notifier(C, NC_WM | ND_FILEREAD, NULL);
415 //              refresh_interface_font();
416
417                 CTX_wm_window_set(C, CTX_wm_manager(C)->windows.first);
418
419                 ED_editors_init(C);
420                 DAG_on_visible_update(CTX_data_main(C), TRUE);
421
422 #ifdef WITH_PYTHON
423                 /* run any texts that were loaded in and flagged as modules */
424                 BPY_driver_reset();
425                 BPY_app_handlers_reset(FALSE);
426                 BPY_modules_load_user(C);
427 #endif
428
429                 /* important to do before NULL'ing the context */
430                 BLI_callback_exec(CTX_data_main(C), NULL, BLI_CB_EVT_LOAD_POST);
431
432                 if (!G.background) {
433                         /* in background mode this makes it hard to load
434                          * a blend file and do anything since the screen
435                          * won't be set to a valid value again */
436                         CTX_wm_window_set(C, NULL); /* exits queues */
437                 }
438
439 #if 0
440                 /* gives popups on windows but not linux, bug in report API
441                  * but disable for now to stop users getting annoyed  */
442                 /* TODO, make this show in header info window */
443                 {
444                         Scene *sce;
445                         for (sce = G.main->scene.first; sce; sce = sce->id.next) {
446                                 if (sce->r.engine[0] &&
447                                     BLI_findstring(&R_engines, sce->r.engine, offsetof(RenderEngineType, idname)) == NULL)
448                                 {
449                                         BKE_reportf(reports, RPT_WARNING,
450                                                     "Engine not available: '%s' for scene: %s, "
451                                                     "an addon may need to be installed or enabled",
452                                                     sce->r.engine, sce->id.name + 2);
453                                 }
454                         }
455                 }
456 #endif
457
458                 BKE_reset_undo();
459                 BKE_write_undo(C, "original");  /* save current state */
460         }
461         else if (retval == BKE_READ_EXOTIC_OK_OTHER)
462                 BKE_write_undo(C, "Import file");
463         else if (retval == BKE_READ_EXOTIC_FAIL_OPEN) {
464                 BKE_reportf(reports, RPT_ERROR, IFACE_("Can't read file: \"%s\", %s."), filepath,
465                             errno ? strerror(errno) : IFACE_("Unable to open the file"));
466         }
467         else if (retval == BKE_READ_EXOTIC_FAIL_FORMAT) {
468                 BKE_reportf(reports, RPT_ERROR, IFACE_("File format is not supported in file: \"%s\"."), filepath);
469         }
470         else if (retval == BKE_READ_EXOTIC_FAIL_PATH) {
471                 BKE_reportf(reports, RPT_ERROR, IFACE_("File path invalid: \"%s\"."), filepath);
472         }
473         else {
474                 BKE_reportf(reports, RPT_ERROR, IFACE_("Unknown error loading: \"%s\"."), filepath);
475                 BLI_assert(!"invalid 'retval'");
476         }
477
478         WM_cursor_wait(0);
479
480 }
481
482
483 /* called on startup,  (context entirely filled with NULLs) */
484 /* or called for 'New File' */
485 /* op can be NULL */
486 int WM_read_homefile(bContext *C, ReportList *UNUSED(reports), short from_memory)
487 {
488         ListBase wmbase;
489         char tstr[FILE_MAX];
490         int success = 0;
491         
492         BKE_vfont_free_global_ttf(); /* still weird... what does it here? */
493                 
494         G.relbase_valid = 0;
495         if (!from_memory) {
496                 char *cfgdir = BLI_get_folder(BLENDER_USER_CONFIG, NULL);
497                 if (cfgdir) {
498                         BLI_make_file_string(G.main->name, tstr, cfgdir, BLENDER_STARTUP_FILE);
499                 }
500                 else {
501                         tstr[0] = '\0';
502                         from_memory = 1;
503                 }
504         }
505         
506         /* prevent loading no UI */
507         G.fileflags &= ~G_FILE_NO_UI;
508         
509         /* put aside screens to match with persistent windows later */
510         wm_window_match_init(C, &wmbase); 
511         
512         if (!from_memory && BLI_exists(tstr)) {
513                 success = (BKE_read_file(C, tstr, NULL) != BKE_READ_FILE_FAIL);
514                 
515                 if (U.themes.first == NULL) {
516                         printf("\nError: No valid "STRINGIFY (BLENDER_STARTUP_FILE)", fall back to built-in default.\n\n");
517                         success = 0;
518                 }
519         }
520         if (success == 0) {
521                 success = BKE_read_file_from_memory(C, datatoc_startup_blend, datatoc_startup_blend_size, NULL);
522                 if (wmbase.first == NULL) wm_clear_default_size(C);
523
524 #ifdef WITH_PYTHON_SECURITY /* not default */
525                 /* use alternative setting for security nuts
526                  * otherwise we'd need to patch the binary blob - startup.blend.c */
527                 U.flag |= USER_SCRIPT_AUTOEXEC_DISABLE;
528 #endif
529         }
530         
531         /* prevent buggy files that had G_FILE_RELATIVE_REMAP written out by mistake. Screws up autosaves otherwise
532          * can remove this eventually, only in a 2.53 and older, now its not written */
533         G.fileflags &= ~G_FILE_RELATIVE_REMAP;
534         
535         /* check userdef before open window, keymaps etc */
536         wm_init_userdef(C);
537         
538         /* match the read WM with current WM */
539         wm_window_match_do(C, &wmbase); 
540         WM_check(C); /* opens window(s), checks keymaps */
541
542         G.main->name[0] = '\0';
543
544         /* When loading factory settings, the reset solid OpenGL lights need to be applied. */
545         if (!G.background) GPU_default_lights();
546         
547         /* XXX */
548         G.save_over = 0;    // start with save preference untitled.blend
549         G.fileflags &= ~G_FILE_AUTOPLAY;    /*  disable autoplay in startup.blend... */
550
551 //      refresh_interface_font();
552         
553 //      undo_editmode_clear();
554         BKE_reset_undo();
555         BKE_write_undo(C, "original");  /* save current state */
556
557         ED_editors_init(C);
558         DAG_on_visible_update(CTX_data_main(C), TRUE);
559
560 #ifdef WITH_PYTHON
561         if (CTX_py_init_get(C)) {
562                 /* sync addons, these may have changed from the defaults */
563                 BPY_string_exec(C, "__import__('addon_utils').reset_all()");
564
565                 BPY_driver_reset();
566                 BPY_app_handlers_reset(FALSE);
567                 BPY_modules_load_user(C);
568         }
569 #endif
570
571         WM_event_add_notifier(C, NC_WM | ND_FILEREAD, NULL);
572
573         /* in background mode the scene will stay NULL */
574         if (!G.background) {
575                 CTX_wm_window_set(C, NULL); /* exits queues */
576         }
577
578         return TRUE;
579 }
580
581 int WM_read_homefile_exec(bContext *C, wmOperator *op)
582 {
583         int from_memory = strcmp(op->type->idname, "WM_OT_read_factory_settings") == 0;
584         return WM_read_homefile(C, op->reports, from_memory) ? OPERATOR_FINISHED : OPERATOR_CANCELLED;
585 }
586
587 void WM_read_history(void)
588 {
589         char name[FILE_MAX];
590         LinkNode *l, *lines;
591         struct RecentFile *recent;
592         char *line;
593         int num;
594         char *cfgdir = BLI_get_folder(BLENDER_USER_CONFIG, NULL);
595
596         if (!cfgdir) return;
597
598         BLI_make_file_string("/", name, cfgdir, BLENDER_HISTORY_FILE);
599
600         lines = BLI_file_read_as_lines(name);
601
602         G.recent_files.first = G.recent_files.last = NULL;
603
604         /* read list of recent opened files from recent-files.txt to memory */
605         for (l = lines, num = 0; l && (num < U.recent_files); l = l->next) {
606                 line = l->link;
607                 if (line[0] && BLI_exists(line)) {
608                         recent = (RecentFile *)MEM_mallocN(sizeof(RecentFile), "RecentFile");
609                         BLI_addtail(&(G.recent_files), recent);
610                         recent->filepath = BLI_strdup(line);
611                         num++;
612                 }
613         }
614         
615         BLI_file_free_lines(lines);
616
617 }
618
619 static void write_history(void)
620 {
621         struct RecentFile *recent, *next_recent;
622         char name[FILE_MAX];
623         char *user_config_dir;
624         FILE *fp;
625         int i;
626
627         /* will be NULL in background mode */
628         user_config_dir = BLI_get_folder_create(BLENDER_USER_CONFIG, NULL);
629         if (!user_config_dir)
630                 return;
631
632         BLI_make_file_string("/", name, user_config_dir, BLENDER_HISTORY_FILE);
633
634         recent = G.recent_files.first;
635         /* refresh recent-files.txt of recent opened files, when current file was changed */
636         if (!(recent) || (BLI_path_cmp(recent->filepath, G.main->name) != 0)) {
637                 fp = BLI_fopen(name, "w");
638                 if (fp) {
639                         /* add current file to the beginning of list */
640                         recent = (RecentFile *)MEM_mallocN(sizeof(RecentFile), "RecentFile");
641                         recent->filepath = BLI_strdup(G.main->name);
642                         BLI_addhead(&(G.recent_files), recent);
643                         /* write current file to recent-files.txt */
644                         fprintf(fp, "%s\n", recent->filepath);
645                         recent = recent->next;
646                         i = 1;
647                         /* write rest of recent opened files to recent-files.txt */
648                         while ((i < U.recent_files) && (recent)) {
649                                 /* this prevents to have duplicities in list */
650                                 if (BLI_path_cmp(recent->filepath, G.main->name) != 0) {
651                                         fprintf(fp, "%s\n", recent->filepath);
652                                         recent = recent->next;
653                                 }
654                                 else {
655                                         next_recent = recent->next;
656                                         MEM_freeN(recent->filepath);
657                                         BLI_freelinkN(&(G.recent_files), recent);
658                                         recent = next_recent;
659                                 }
660                                 i++;
661                         }
662                         fclose(fp);
663                 }
664
665                 /* also update most recent files on System */
666                 GHOST_addToSystemRecentFiles(G.main->name);
667         }
668 }
669
670 /* screen can be NULL */
671 static ImBuf *blend_file_thumb(Scene *scene, bScreen *screen, int **thumb_pt)
672 {
673         /* will be scaled down, but gives some nice oversampling */
674         ImBuf *ibuf;
675         int *thumb;
676         char err_out[256] = "unknown";
677
678         /* screen if no camera found */
679         ScrArea *sa = NULL;
680         ARegion *ar = NULL;
681         View3D *v3d = NULL;
682
683         *thumb_pt = NULL;
684
685         /* scene can be NULL if running a script at startup and calling the save operator */
686         if (G.background || scene == NULL)
687                 return NULL;
688
689         if ((scene->camera == NULL) && (screen != NULL)) {
690                 sa = BKE_screen_find_big_area(screen, SPACE_VIEW3D, 0);
691                 ar = BKE_area_find_region_type(sa, RGN_TYPE_WINDOW);
692                 if (ar) {
693                         v3d = sa->spacedata.first;
694                 }
695         }
696
697         if (scene->camera == NULL && v3d == NULL) {
698                 return NULL;
699         }
700
701         /* gets scaled to BLEN_THUMB_SIZE */
702         if (scene->camera) {
703                 ibuf = ED_view3d_draw_offscreen_imbuf_simple(scene, scene->camera,
704                                                              BLEN_THUMB_SIZE * 2, BLEN_THUMB_SIZE * 2,
705                                                              IB_rect, OB_SOLID, FALSE, err_out);
706         }
707         else {
708                 ibuf = ED_view3d_draw_offscreen_imbuf(scene, v3d, ar, BLEN_THUMB_SIZE * 2, BLEN_THUMB_SIZE * 2,
709                                                       IB_rect, FALSE, err_out);
710         }
711
712         if (ibuf) {             
713                 float aspect = (scene->r.xsch * scene->r.xasp) / (scene->r.ysch * scene->r.yasp);
714
715                 /* dirty oversampling */
716                 IMB_scaleImBuf(ibuf, BLEN_THUMB_SIZE, BLEN_THUMB_SIZE);
717
718                 /* add pretty overlay */
719                 IMB_overlayblend_thumb(ibuf->rect, ibuf->x, ibuf->y, aspect);
720                 
721                 /* first write into thumb buffer */
722                 thumb = MEM_mallocN(((2 + (BLEN_THUMB_SIZE * BLEN_THUMB_SIZE))) * sizeof(int), "write_file thumb");
723
724                 thumb[0] = BLEN_THUMB_SIZE;
725                 thumb[1] = BLEN_THUMB_SIZE;
726
727                 memcpy(thumb + 2, ibuf->rect, BLEN_THUMB_SIZE * BLEN_THUMB_SIZE * sizeof(int));
728         }
729         else {
730                 /* '*thumb_pt' needs to stay NULL to prevent a bad thumbnail from being handled */
731                 fprintf(stderr, "blend_file_thumb failed to create thumbnail: %s\n", err_out);
732                 thumb = NULL;
733         }
734         
735         /* must be freed by caller */
736         *thumb_pt = thumb;
737         
738         return ibuf;
739 }
740
741 /* easy access from gdb */
742 int write_crash_blend(void)
743 {
744         char path[FILE_MAX];
745         int fileflags = G.fileflags & ~(G_FILE_HISTORY); /* don't do file history on crash file */
746
747         BLI_strncpy(path, G.main->name, sizeof(path));
748         BLI_replace_extension(path, sizeof(path), "_crash.blend");
749         if (BLO_write_file(G.main, path, fileflags, NULL, NULL)) {
750                 printf("written: %s\n", path);
751                 return 1;
752         }
753         else {
754                 printf("failed: %s\n", path);
755                 return 0;
756         }
757 }
758
759 int WM_write_file(bContext *C, const char *target, int fileflags, ReportList *reports, int copy)
760 {
761         Library *li;
762         int len;
763         char filepath[FILE_MAX];
764
765         int *thumb = NULL;
766         ImBuf *ibuf_thumb = NULL;
767
768         len = strlen(target);
769         
770         if (len == 0) {
771                 BKE_report(reports, RPT_ERROR, "Path is empty, cannot save");
772                 return -1;
773         }
774
775         if (len >= FILE_MAX) {
776                 BKE_report(reports, RPT_ERROR, "Path too long, cannot save");
777                 return -1;
778         }
779  
780         BLI_strncpy(filepath, target, FILE_MAX);
781         BLI_replace_extension(filepath, FILE_MAX, ".blend");
782         /* don't use 'target' anymore */
783         
784         /* send the OnSave event */
785         for (li = G.main->library.first; li; li = li->id.next) {
786                 if (BLI_path_cmp(li->filepath, filepath) == 0) {
787                         BKE_reportf(reports, RPT_ERROR, "Can't overwrite used library '%.240s'", filepath);
788                         return -1;
789                 }
790         }
791
792         /* blend file thumbnail */
793         /* save before exit_editmode, otherwise derivedmeshes for shared data corrupt #27765) */
794         if (U.flag & USER_SAVE_PREVIEWS) {
795                 ibuf_thumb = blend_file_thumb(CTX_data_scene(C), CTX_wm_screen(C), &thumb);
796         }
797
798         BLI_callback_exec(G.main, NULL, BLI_CB_EVT_SAVE_PRE);
799
800         /* operator now handles overwrite checks */
801
802         if (G.fileflags & G_AUTOPACK) {
803                 packAll(G.main, reports);
804         }
805         
806         ED_object_exit_editmode(C, EM_DO_UNDO);
807         ED_sculpt_force_update(C);
808
809         /* don't forget not to return without! */
810         WM_cursor_wait(1);
811         
812         fileflags |= G_FILE_HISTORY; /* write file history */
813
814         if (BLO_write_file(CTX_data_main(C), filepath, fileflags, reports, thumb)) {
815                 if (!copy) {
816                         G.relbase_valid = 1;
817                         BLI_strncpy(G.main->name, filepath, sizeof(G.main->name));  /* is guaranteed current file */
818         
819                         G.save_over = 1; /* disable untitled.blend convention */
820                 }
821
822                 if (fileflags & G_FILE_COMPRESS) G.fileflags |= G_FILE_COMPRESS;
823                 else G.fileflags &= ~G_FILE_COMPRESS;
824                 
825                 if (fileflags & G_FILE_AUTOPLAY) G.fileflags |= G_FILE_AUTOPLAY;
826                 else G.fileflags &= ~G_FILE_AUTOPLAY;
827
828                 /* prevent background mode scripts from clobbering history */
829                 if (!G.background) {
830                         write_history();
831                 }
832
833                 BLI_callback_exec(G.main, NULL, BLI_CB_EVT_SAVE_POST);
834
835                 /* run this function after because the file cant be written before the blend is */
836                 if (ibuf_thumb) {
837                         IMB_thumb_delete(filepath, THB_FAIL); /* without this a failed thumb overrides */
838                         ibuf_thumb = IMB_thumb_create(filepath, THB_NORMAL, THB_SOURCE_BLEND, ibuf_thumb);
839                         IMB_freeImBuf(ibuf_thumb);
840                 }
841
842                 if (thumb) MEM_freeN(thumb);
843         }
844         else {
845                 if (ibuf_thumb) IMB_freeImBuf(ibuf_thumb);
846                 if (thumb) MEM_freeN(thumb);
847                 
848                 WM_cursor_wait(0);
849                 return -1;
850         }
851
852         WM_cursor_wait(0);
853         
854         return 0;
855 }
856
857 /* operator entry */
858 int WM_write_homefile(bContext *C, wmOperator *op)
859 {
860         wmWindowManager *wm = CTX_wm_manager(C);
861         wmWindow *win = CTX_wm_window(C);
862         char filepath[FILE_MAX];
863         int fileflags;
864
865         /* check current window and close it if temp */
866         if (win->screen->temp)
867                 wm_window_close(C, wm, win);
868         
869         /* update keymaps in user preferences */
870         WM_keyconfig_update(wm);
871         
872         BLI_make_file_string("/", filepath, BLI_get_folder_create(BLENDER_USER_CONFIG, NULL), BLENDER_STARTUP_FILE);
873         printf("trying to save homefile at %s ", filepath);
874         
875         /*  force save as regular blend file */
876         fileflags = G.fileflags & ~(G_FILE_COMPRESS | G_FILE_AUTOPLAY | G_FILE_LOCK | G_FILE_SIGN | G_FILE_HISTORY);
877
878         if (BLO_write_file(CTX_data_main(C), filepath, fileflags, op->reports, NULL) == 0) {
879                 printf("fail\n");
880                 return OPERATOR_CANCELLED;
881         }
882         
883         printf("ok\n");
884
885         G.save_over = 0;
886
887         return OPERATOR_FINISHED;
888 }
889
890 /************************ autosave ****************************/
891
892 void wm_autosave_location(char *filepath)
893 {
894         char pidstr[32];
895 #ifdef WIN32
896         char *savedir;
897 #endif
898
899         BLI_snprintf(pidstr, sizeof(pidstr), "%d.blend", abs(getpid()));
900
901 #ifdef WIN32
902         /* XXX Need to investigate how to handle default location of '/tmp/'
903          * This is a relative directory on Windows, and it may be
904          * found. Example:
905          * Blender installed on D:\ drive, D:\ drive has D:\tmp\
906          * Now, BLI_exists() will find '/tmp/' exists, but
907          * BLI_make_file_string will create string that has it most likely on C:\
908          * through get_default_root().
909          * If there is no C:\tmp autosave fails. */
910         if (!BLI_exists(BLI_temporary_dir())) {
911                 savedir = BLI_get_folder_create(BLENDER_USER_AUTOSAVE, NULL);
912                 BLI_make_file_string("/", filepath, savedir, pidstr);
913                 return;
914         }
915 #endif
916
917         BLI_make_file_string("/", filepath, BLI_temporary_dir(), pidstr);
918 }
919
920 void WM_autosave_init(wmWindowManager *wm)
921 {
922         wm_autosave_timer_ended(wm);
923
924         if (U.flag & USER_AUTOSAVE)
925                 wm->autosavetimer = WM_event_add_timer(wm, NULL, TIMERAUTOSAVE, U.savetime * 60.0);
926 }
927
928 void wm_autosave_timer(const bContext *C, wmWindowManager *wm, wmTimer *UNUSED(wt))
929 {
930         wmWindow *win;
931         wmEventHandler *handler;
932         char filepath[FILE_MAX];
933         int fileflags;
934         Scene *scene = CTX_data_scene(C);
935
936         WM_event_remove_timer(wm, NULL, wm->autosavetimer);
937
938         /* if a modal operator is running, don't autosave, but try again in 10 seconds */
939         for (win = wm->windows.first; win; win = win->next) {
940                 for (handler = win->modalhandlers.first; handler; handler = handler->next) {
941                         if (handler->op) {
942                                 wm->autosavetimer = WM_event_add_timer(wm, NULL, TIMERAUTOSAVE, 10.0);
943                                 return;
944                         }
945                 }
946         }
947
948         if (scene) {
949                 Object *ob = OBACT;
950
951                 if (ob && ob->mode & OB_MODE_SCULPT)
952                         multires_force_update(ob);
953         }
954
955         wm_autosave_location(filepath);
956
957         /*  force save as regular blend file */
958         fileflags = G.fileflags & ~(G_FILE_COMPRESS | G_FILE_AUTOPLAY | G_FILE_LOCK | G_FILE_SIGN | G_FILE_HISTORY);
959
960         /* no error reporting to console */
961         BLO_write_file(CTX_data_main(C), filepath, fileflags, NULL, NULL);
962
963         /* do timer after file write, just in case file write takes a long time */
964         wm->autosavetimer = WM_event_add_timer(wm, NULL, TIMERAUTOSAVE, U.savetime * 60.0);
965 }
966
967 void wm_autosave_timer_ended(wmWindowManager *wm)
968 {
969         if (wm->autosavetimer) {
970                 WM_event_remove_timer(wm, NULL, wm->autosavetimer);
971                 wm->autosavetimer = NULL;
972         }
973 }
974
975 void wm_autosave_delete(void)
976 {
977         char filename[FILE_MAX];
978         
979         wm_autosave_location(filename);
980
981         if (BLI_exists(filename)) {
982                 char str[FILE_MAX];
983                 BLI_make_file_string("/", str, BLI_temporary_dir(), "quit.blend");
984
985                 /* if global undo; remove tempsave, otherwise rename */
986                 if (U.uiflag & USER_GLOBALUNDO) BLI_delete(filename, 0, 0);
987                 else BLI_rename(filename, str);
988         }
989 }
990
991 void wm_autosave_read(bContext *C, ReportList *reports)
992 {
993         char filename[FILE_MAX];
994
995         wm_autosave_location(filename);
996         WM_read_file(C, filename, reports);
997 }
998