Undo: unified undo system w/ linear history
[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  * User level access for blend file read/write, file-history and userprefs (including relevant operators).
30  */
31
32
33 /* placed up here because of crappy
34  * winsock stuff.
35  */
36 #include <stddef.h>
37 #include <string.h>
38 #include <errno.h>
39
40 #include "zlib.h" /* wm_read_exotic() */
41
42 #ifdef WIN32
43 #  include <windows.h> /* need to include windows.h so _WIN32_IE is defined  */
44 #  ifndef _WIN32_IE
45 #    define _WIN32_IE 0x0400 /* minimal requirements for SHGetSpecialFolderPath on MINGW MSVC has this defined already */
46 #  endif
47 #  include <shlobj.h>  /* for SHGetSpecialFolderPath, has to be done before BLI_winstuff
48                         * because 'near' is disabled through BLI_windstuff */
49 #  include "BLI_winstuff.h"
50 #endif
51
52 #include "MEM_guardedalloc.h"
53 #include "MEM_CacheLimiterC-Api.h"
54
55 #include "BLI_blenlib.h"
56 #include "BLI_linklist.h"
57 #include "BLI_utildefines.h"
58 #include "BLI_threads.h"
59 #include "BLI_callbacks.h"
60 #include "BLI_system.h"
61 #include BLI_SYSTEM_PID_H
62
63 #include "BLT_translation.h"
64
65 #include "BLF_api.h"
66
67 #include "DNA_mesh_types.h" /* only for USE_BMESH_SAVE_AS_COMPAT */
68 #include "DNA_object_types.h"
69 #include "DNA_space_types.h"
70 #include "DNA_userdef_types.h"
71 #include "DNA_scene_types.h"
72 #include "DNA_screen_types.h"
73 #include "DNA_windowmanager_types.h"
74
75 #include "BKE_appdir.h"
76 #include "BKE_autoexec.h"
77 #include "BKE_blender.h"
78 #include "BKE_blendfile.h"
79 #include "BKE_blender_undo.h"
80 #include "BKE_context.h"
81 #include "BKE_depsgraph.h"
82 #include "BKE_global.h"
83 #include "BKE_library.h"
84 #include "BKE_main.h"
85 #include "BKE_packedFile.h"
86 #include "BKE_report.h"
87 #include "BKE_sound.h"
88 #include "BKE_scene.h"
89 #include "BKE_screen.h"
90 #include "BKE_undo_system.h"
91
92 #include "BLO_readfile.h"
93 #include "BLO_writefile.h"
94 #include "BLO_undofile.h"  /* to save from an undo memfile */
95
96 #include "RNA_access.h"
97 #include "RNA_define.h"
98
99 #include "IMB_imbuf.h"
100 #include "IMB_imbuf_types.h"
101 #include "IMB_thumbs.h"
102
103 #include "ED_datafiles.h"
104 #include "ED_fileselect.h"
105 #include "ED_screen.h"
106 #include "ED_view3d.h"
107 #include "ED_util.h"
108
109 #include "GHOST_C-api.h"
110 #include "GHOST_Path-api.h"
111
112 #include "UI_interface.h"
113 #include "UI_resources.h"
114 #include "UI_view2d.h"
115
116 #include "GPU_draw.h"
117
118 /* only to report a missing engine */
119 #include "RE_engine.h"
120
121 #ifdef WITH_PYTHON
122 #include "BPY_extern.h"
123 #endif
124
125 #include "WM_api.h"
126 #include "WM_types.h"
127 #include "wm.h"
128 #include "wm_files.h"
129 #include "wm_window.h"
130 #include "wm_event_system.h"
131
132 static RecentFile *wm_file_history_find(const char *filepath);
133 static void wm_history_file_free(RecentFile *recent);
134 static void wm_history_file_update(void);
135 static void wm_history_file_write(void);
136
137
138 /* To be able to read files without windows closing, opening, moving
139  * we try to prepare for worst case:
140  * - active window gets active screen from file
141  * - restoring the screens from non-active windows
142  * Best case is all screens match, in that case they get assigned to proper window
143  */
144 static void wm_window_match_init(bContext *C, ListBase *wmlist)
145 {
146         wmWindowManager *wm;
147         wmWindow *win, *active_win;
148         
149         *wmlist = G.main->wm;
150         BLI_listbase_clear(&G.main->wm);
151         
152         active_win = CTX_wm_window(C);
153
154         /* first wrap up running stuff */
155         /* code copied from wm_init_exit.c */
156         for (wm = wmlist->first; wm; wm = wm->id.next) {
157                 
158                 WM_jobs_kill_all(wm);
159                 
160                 for (win = wm->windows.first; win; win = win->next) {
161                 
162                         CTX_wm_window_set(C, win);  /* needed by operator close callbacks */
163                         WM_event_remove_handlers(C, &win->handlers);
164                         WM_event_remove_handlers(C, &win->modalhandlers);
165                         ED_screen_exit(C, win, win->screen);
166                 }
167         }
168         
169         /* reset active window */
170         CTX_wm_window_set(C, active_win);
171
172         /* XXX Hack! We have to clear context menu here, because removing all modalhandlers above frees the active menu
173          *     (at least, in the 'startup splash' case), causing use-after-free error in later handling of the button
174          *     callbacks in UI code (see ui_apply_but_funcs_after()).
175          *     Tried solving this by always NULL-ing context's menu when setting wm/win/etc., but it broke popups refreshing
176          *     (see T47632), so for now just handling this specific case here. */
177         CTX_wm_menu_set(C, NULL);
178
179         ED_editors_exit(C);
180
181         /* just had return; here from r12991, this code could just get removed?*/
182 #if 0
183         if (wm == NULL) return;
184         if (G.fileflags & G_FILE_NO_UI) return;
185         
186         /* we take apart the used screens from non-active window */
187         for (win = wm->windows.first; win; win = win->next) {
188                 BLI_strncpy(win->screenname, win->screen->id.name, MAX_ID_NAME);
189                 if (win != wm->winactive) {
190                         BLI_remlink(&G.main->screen, win->screen);
191                         //BLI_addtail(screenbase, win->screen);
192                 }
193         }
194 #endif
195 }
196
197 static void wm_window_substitute_old(wmWindowManager *wm, wmWindow *oldwin, wmWindow *win)
198 {
199         win->ghostwin = oldwin->ghostwin;
200         win->multisamples = oldwin->multisamples;
201         win->active = oldwin->active;
202         if (win->active)
203                 wm->winactive = win;
204
205         if (!G.background) /* file loading in background mode still calls this */
206                 GHOST_SetWindowUserData(win->ghostwin, win);    /* pointer back */
207
208         oldwin->ghostwin = NULL;
209         oldwin->multisamples = 0;
210
211         win->eventstate = oldwin->eventstate;
212         oldwin->eventstate = NULL;
213
214         /* ensure proper screen rescaling */
215         win->sizex = oldwin->sizex;
216         win->sizey = oldwin->sizey;
217         win->posx = oldwin->posx;
218         win->posy = oldwin->posy;
219 }
220
221 /* match old WM with new, 4 cases:
222  * 1- no current wm, no read wm: make new default
223  * 2- no current wm, but read wm: that's OK, do nothing
224  * 3- current wm, but not in file: try match screen names
225  * 4- current wm, and wm in file: try match ghostwin
226  */
227
228 static void wm_window_match_do(bContext *C, ListBase *oldwmlist)
229 {
230         wmWindowManager *oldwm, *wm;
231         wmWindow *oldwin, *win;
232         
233         /* cases 1 and 2 */
234         if (BLI_listbase_is_empty(oldwmlist)) {
235                 if (G.main->wm.first) {
236                         /* nothing todo */
237                 }
238                 else {
239                         wm_add_default(C);
240                 }
241         }
242         else {
243                 /* cases 3 and 4 */
244                 
245                 /* we've read file without wm..., keep current one entirely alive */
246                 if (BLI_listbase_is_empty(&G.main->wm)) {
247                         bScreen *screen = NULL;
248
249                         /* when loading without UI, no matching needed */
250                         if (!(G.fileflags & G_FILE_NO_UI) && (screen = CTX_wm_screen(C))) {
251
252                                 /* match oldwm to new dbase, only old files */
253                                 for (wm = oldwmlist->first; wm; wm = wm->id.next) {
254                                         
255                                         for (win = wm->windows.first; win; win = win->next) {
256                                                 /* all windows get active screen from file */
257                                                 if (screen->winid == 0)
258                                                         win->screen = screen;
259                                                 else 
260                                                         win->screen = ED_screen_duplicate(win, screen);
261                                                 
262                                                 BLI_strncpy(win->screenname, win->screen->id.name + 2, sizeof(win->screenname));
263                                                 win->screen->winid = win->winid;
264                                         }
265                                 }
266                         }
267                         
268                         G.main->wm = *oldwmlist;
269                         
270                         /* screens were read from file! */
271                         ED_screens_initialize(G.main->wm.first);
272                 }
273                 else {
274                         bool has_match = false;
275
276                         /* what if old was 3, and loaded 1? */
277                         /* this code could move to setup_appdata */
278                         oldwm = oldwmlist->first;
279                         wm = G.main->wm.first;
280
281                         /* preserve key configurations in new wm, to preserve their keymaps */
282                         wm->keyconfigs = oldwm->keyconfigs;
283                         wm->addonconf = oldwm->addonconf;
284                         wm->defaultconf = oldwm->defaultconf;
285                         wm->userconf = oldwm->userconf;
286
287                         BLI_listbase_clear(&oldwm->keyconfigs);
288                         oldwm->addonconf = NULL;
289                         oldwm->defaultconf = NULL;
290                         oldwm->userconf = NULL;
291
292                         /* ensure making new keymaps and set space types */
293                         wm->initialized = 0;
294                         wm->winactive = NULL;
295
296                         /* only first wm in list has ghostwins */
297                         for (win = wm->windows.first; win; win = win->next) {
298                                 for (oldwin = oldwm->windows.first; oldwin; oldwin = oldwin->next) {
299
300                                         if (oldwin->winid == win->winid) {
301                                                 has_match = true;
302
303                                                 wm_window_substitute_old(wm, oldwin, win);
304                                         }
305                                 }
306                         }
307
308                         /* make sure at least one window is kept open so we don't lose the context, check T42303 */
309                         if (!has_match) {
310                                 oldwin = oldwm->windows.first;
311                                 win = wm->windows.first;
312
313                                 wm_window_substitute_old(wm, oldwin, win);
314                         }
315
316                         wm_close_and_free_all(C, oldwmlist);
317                 }
318         }
319 }
320
321 /* in case UserDef was read, we re-initialize all, and do versioning */
322 static void wm_init_userdef(Main *bmain, const bool read_userdef_from_memory)
323 {
324         /* versioning is here */
325         UI_init_userdef();
326         
327         MEM_CacheLimiter_set_maximum(((size_t)U.memcachelimit) * 1024 * 1024);
328         BKE_sound_init(bmain);
329
330         /* needed so loading a file from the command line respects user-pref [#26156] */
331         SET_FLAG_FROM_TEST(G.fileflags, U.flag & USER_FILENOUI, G_FILE_NO_UI);
332
333         /* set the python auto-execute setting from user prefs */
334         /* enabled by default, unless explicitly enabled in the command line which overrides */
335         if ((G.f & G_SCRIPT_OVERRIDE_PREF) == 0) {
336                 SET_FLAG_FROM_TEST(G.f, (U.flag & USER_SCRIPT_AUTOEXEC_DISABLE) == 0, G_SCRIPT_AUTOEXEC);
337         }
338
339         /* avoid re-saving for every small change to our prefs, allow overrides */
340         if (read_userdef_from_memory) {
341                 BLO_update_defaults_userpref_blend();
342         }
343
344         /* update tempdir from user preferences */
345         BKE_tempdir_init(U.tempdir);
346
347         BLF_antialias_set((U.text_render & USER_TEXT_DISABLE_AA) == 0);
348 }
349
350
351
352 /* return codes */
353 #define BKE_READ_EXOTIC_FAIL_PATH       -3 /* file format is not supported */
354 #define BKE_READ_EXOTIC_FAIL_FORMAT     -2 /* file format is not supported */
355 #define BKE_READ_EXOTIC_FAIL_OPEN       -1 /* Can't open the file */
356 #define BKE_READ_EXOTIC_OK_BLEND         0 /* .blend file */
357 #if 0
358 #define BKE_READ_EXOTIC_OK_OTHER         1 /* other supported formats */
359 #endif
360
361
362 /* intended to check for non-blender formats but for now it only reads blends */
363 static int wm_read_exotic(const char *name)
364 {
365         int len;
366         gzFile gzfile;
367         char header[7];
368         int retval;
369
370         /* make sure we're not trying to read a directory.... */
371
372         len = strlen(name);
373         if (len > 0 && ELEM(name[len - 1], '/', '\\')) {
374                 retval = BKE_READ_EXOTIC_FAIL_PATH;
375         }
376         else {
377                 gzfile = BLI_gzopen(name, "rb");
378                 if (gzfile == NULL) {
379                         retval = BKE_READ_EXOTIC_FAIL_OPEN;
380                 }
381                 else {
382                         len = gzread(gzfile, header, sizeof(header));
383                         gzclose(gzfile);
384                         if (len == sizeof(header) && STREQLEN(header, "BLENDER", 7)) {
385                                 retval = BKE_READ_EXOTIC_OK_BLEND;
386                         }
387                         else {
388 #if 0           /* historic stuff - no longer used */
389                                 WM_cursor_wait(true);
390
391                                 if (is_foo_format(name)) {
392                                         read_foo(name);
393                                         retval = BKE_READ_EXOTIC_OK_OTHER;
394                                 }
395                                 else
396 #endif
397                                 {
398                                         retval = BKE_READ_EXOTIC_FAIL_FORMAT;
399                                 }
400 #if 0
401                                 WM_cursor_wait(false);
402 #endif
403                         }
404                 }
405         }
406
407         return retval;
408 }
409
410 void WM_file_autoexec_init(const char *filepath)
411 {
412         if (G.f & G_SCRIPT_OVERRIDE_PREF) {
413                 return;
414         }
415
416         if (G.f & G_SCRIPT_AUTOEXEC) {
417                 char path[FILE_MAX];
418                 BLI_split_dir_part(filepath, path, sizeof(path));
419                 if (BKE_autoexec_match(path)) {
420                         G.f &= ~G_SCRIPT_AUTOEXEC;
421                 }
422         }
423 }
424
425 void wm_file_read_report(bContext *C)
426 {
427         ReportList *reports = NULL;
428         Scene *sce;
429
430         for (sce = G.main->scene.first; sce; sce = sce->id.next) {
431                 if (sce->r.engine[0] &&
432                     BLI_findstring(&R_engines, sce->r.engine, offsetof(RenderEngineType, idname)) == NULL)
433                 {
434                         if (reports == NULL) {
435                                 reports = CTX_wm_reports(C);
436                         }
437
438                         BKE_reportf(reports, RPT_ERROR,
439                                     "Engine '%s' not available for scene '%s' (an add-on may need to be installed or enabled)",
440                                     sce->r.engine, sce->id.name + 2);
441                 }
442         }
443
444         if (reports) {
445                 if (!G.background) {
446                         WM_report_banner_show();
447                 }
448         }
449 }
450
451 /**
452  * Logic shared between #WM_file_read & #wm_homefile_read,
453  * updates to make after reading a file.
454  */
455 static void wm_file_read_post(bContext *C, const bool is_startup_file, const bool use_userdef)
456 {
457         bool addons_loaded = false;
458         wmWindowManager *wm = CTX_wm_manager(C);
459
460         if (!G.background) {
461                 /* remove windows which failed to be added via WM_check */
462                 wm_window_ghostwindows_remove_invalid(C, wm);
463         }
464
465         CTX_wm_window_set(C, wm->windows.first);
466
467         ED_editors_init(C);
468         DAG_on_visible_update(CTX_data_main(C), true);
469
470 #ifdef WITH_PYTHON
471         if (is_startup_file) {
472                 /* possible python hasn't been initialized */
473                 if (CTX_py_init_get(C)) {
474                         if (use_userdef) {
475                                 /* Only run when we have a template path found. */
476                                 if (BKE_appdir_app_template_any()) {
477                                         BPY_execute_string(C, "__import__('bl_app_template_utils').reset()");
478                                 }
479                                 /* sync addons, these may have changed from the defaults */
480                                 BPY_execute_string(C, "__import__('addon_utils').reset_all()");
481                         }
482                         BPY_python_reset(C);
483                         addons_loaded = true;
484                 }
485         }
486         else {
487                 /* run any texts that were loaded in and flagged as modules */
488                 BPY_python_reset(C);
489                 addons_loaded = true;
490         }
491 #else
492         UNUSED_VARS(use_userdef);
493 #endif  /* WITH_PYTHON */
494
495         WM_operatortype_last_properties_clear_all();
496
497         /* important to do before NULL'ing the context */
498         BLI_callback_exec(CTX_data_main(C), NULL, BLI_CB_EVT_VERSION_UPDATE);
499         BLI_callback_exec(CTX_data_main(C), NULL, BLI_CB_EVT_LOAD_POST);
500
501         /* Would otherwise be handled by event loop.
502          *
503          * Disabled for startup file, since it causes problems when PyDrivers are used in the startup file.
504          * While its possible state of startup file may be wrong,
505          * in this case users nearly always load a file to replace the startup file. */
506         if (G.background && (is_startup_file == false)) {
507                 Main *bmain = CTX_data_main(C);
508                 BKE_scene_update_tagged(bmain->eval_ctx, bmain, CTX_data_scene(C));
509         }
510
511         WM_event_add_notifier(C, NC_WM | ND_FILEREAD, NULL);
512
513         /* report any errors.
514          * currently disabled if addons aren't yet loaded */
515         if (addons_loaded) {
516                 wm_file_read_report(C);
517         }
518
519         if (!G.background) {
520                 /* in background mode this makes it hard to load
521                  * a blend file and do anything since the screen
522                  * won't be set to a valid value again */
523                 CTX_wm_window_set(C, NULL); /* exits queues */
524         }
525
526         if (!G.background) {
527                 if (wm->undo_stack == NULL) {
528                         wm->undo_stack = BKE_undosys_stack_create();
529                 }
530                 else {
531                         BKE_undosys_stack_clear(wm->undo_stack);
532                 }
533                 BKE_undosys_stack_init_from_main(wm->undo_stack, CTX_data_main(C));
534         }
535 }
536
537 bool WM_file_read(bContext *C, const char *filepath, ReportList *reports)
538 {
539         /* assume automated tasks with background, don't write recent file list */
540         const bool do_history = (G.background == false) && (CTX_wm_manager(C)->op_undo_depth == 0);
541         bool success = false;
542         int retval;
543
544         /* so we can get the error message */
545         errno = 0;
546
547         WM_cursor_wait(1);
548
549         BLI_callback_exec(CTX_data_main(C), NULL, BLI_CB_EVT_LOAD_PRE);
550
551         UI_view2d_zoom_cache_reset();
552
553         /* first try to append data from exotic file formats... */
554         /* it throws error box when file doesn't exist and returns -1 */
555         /* note; it should set some error message somewhere... (ton) */
556         retval = wm_read_exotic(filepath);
557         
558         /* we didn't succeed, now try to read Blender file */
559         if (retval == BKE_READ_EXOTIC_OK_BLEND) {
560                 int G_f = G.f;
561                 ListBase wmbase;
562
563                 /* put aside screens to match with persistent windows later */
564                 /* also exit screens and editors */
565                 wm_window_match_init(C, &wmbase); 
566                 
567                 /* confusing this global... */
568                 G.relbase_valid = 1;
569                 retval = BKE_blendfile_read(C, filepath, reports, 0);
570                 /* when loading startup.blend's, we can be left with a blank path */
571                 if (G.main->name[0]) {
572                         G.save_over = 1;
573                 }
574                 else {
575                         G.save_over = 0;
576                         G.relbase_valid = 0;
577                 }
578
579                 /* this flag is initialized by the operator but overwritten on read.
580                  * need to re-enable it here else drivers + registered scripts wont work. */
581                 if (G.f != G_f) {
582                         const int flags_keep = (G_SCRIPT_AUTOEXEC | G_SCRIPT_OVERRIDE_PREF);
583                         G.f = (G.f & ~flags_keep) | (G_f & flags_keep);
584                 }
585
586                 /* match the read WM with current WM */
587                 wm_window_match_do(C, &wmbase);
588                 WM_check(C); /* opens window(s), checks keymaps */
589
590                 if (retval == BKE_BLENDFILE_READ_OK_USERPREFS) {
591                         /* in case a userdef is read from regular .blend */
592                         wm_init_userdef(G.main, false);
593                 }
594                 
595                 if (retval != BKE_BLENDFILE_READ_FAIL) {
596                         if (do_history) {
597                                 wm_history_file_update();
598                         }
599                 }
600
601                 wm_file_read_post(C, false, false);
602
603                 success = true;
604         }
605         else if (retval == BKE_READ_EXOTIC_FAIL_OPEN) {
606                 BKE_reportf(reports, RPT_ERROR, "Cannot read file '%s': %s", filepath,
607                             errno ? strerror(errno) : TIP_("unable to open the file"));
608         }
609         else if (retval == BKE_READ_EXOTIC_FAIL_FORMAT) {
610                 BKE_reportf(reports, RPT_ERROR, "File format is not supported in file '%s'", filepath);
611         }
612         else if (retval == BKE_READ_EXOTIC_FAIL_PATH) {
613                 BKE_reportf(reports, RPT_ERROR, "File path '%s' invalid", filepath);
614         }
615         else {
616                 BKE_reportf(reports, RPT_ERROR, "Unknown error loading '%s'", filepath);
617                 BLI_assert(!"invalid 'retval'");
618         }
619
620
621         if (success == false) {
622                 /* remove from recent files list */
623                 if (do_history) {
624                         RecentFile *recent = wm_file_history_find(filepath);
625                         if (recent) {
626                                 wm_history_file_free(recent);
627                                 wm_history_file_write();
628                         }
629                 }
630         }
631
632         WM_cursor_wait(0);
633
634         return success;
635
636 }
637
638
639 /**
640  * Called on startup, (context entirely filled with NULLs)
641  * or called for 'New File' both startup.blend and userpref.blend are checked.
642  *
643  * \param use_factory_settings: Ignore on-disk startup file, use bundled ``datatoc_startup_blend`` instead.
644  * Used for "Restore Factory Settings".
645  * \param use_userdef: Load factory settings as well as startup file.
646  * Disabled for "File New" we don't want to reload preferences.
647  * \param filepath_startup_override: Optional path pointing to an alternative blend file (may be NULL).
648  * \param app_template_override: Template to use instead of the template defined in user-preferences.
649  * When not-null, this is written into the user preferences.
650  */
651 int wm_homefile_read(
652         bContext *C, ReportList *reports,
653         bool use_factory_settings, bool use_empty_data, bool use_userdef,
654         const char *filepath_startup_override, const char *app_template_override)
655 {
656         ListBase wmbase;
657         bool success = false;
658
659         char filepath_startup[FILE_MAX];
660         char filepath_userdef[FILE_MAX];
661
662         /* When 'app_template' is set: '{BLENDER_USER_CONFIG}/{app_template}' */
663         char app_template_system[FILE_MAX];
664         /* When 'app_template' is set: '{BLENDER_SYSTEM_SCRIPTS}/startup/bl_app_templates_system/{app_template}' */
665         char app_template_config[FILE_MAX];
666
667         /* Indicates whether user preferences were really load from memory.
668          *
669          * This is used for versioning code, and for this we can not rely on use_factory_settings
670          * passed via argument. This is because there might be configuration folder
671          * exists but it might not have userpref.blend and in this case we fallback to
672          * reading home file from memory.
673          *
674          * And in this case versioning code is to be run.
675          */
676         bool read_userdef_from_memory = false;
677         eBLOReadSkip skip_flags = use_userdef ? 0 : BLO_READ_SKIP_USERDEF;
678
679         /* options exclude eachother */
680         BLI_assert((use_factory_settings && filepath_startup_override) == 0);
681
682         if ((G.f & G_SCRIPT_OVERRIDE_PREF) == 0) {
683                 SET_FLAG_FROM_TEST(G.f, (U.flag & USER_SCRIPT_AUTOEXEC_DISABLE) == 0, G_SCRIPT_AUTOEXEC);
684         }
685
686         BLI_callback_exec(CTX_data_main(C), NULL, BLI_CB_EVT_LOAD_PRE);
687
688         UI_view2d_zoom_cache_reset();
689
690         G.relbase_valid = 0;
691
692         /* put aside screens to match with persistent windows later */
693         wm_window_match_init(C, &wmbase);
694
695         filepath_startup[0] = '\0';
696         filepath_userdef[0] = '\0';
697         app_template_system[0] = '\0';
698         app_template_config[0] = '\0';
699
700         const char * const cfgdir = BKE_appdir_folder_id(BLENDER_USER_CONFIG, NULL);
701         if (!use_factory_settings) {
702                 if (cfgdir) {
703                         BLI_path_join(filepath_startup, sizeof(filepath_startup), cfgdir, BLENDER_STARTUP_FILE, NULL);
704                         if (use_userdef) {
705                                 BLI_path_join(filepath_userdef, sizeof(filepath_startup), cfgdir, BLENDER_USERPREF_FILE, NULL);
706                         }
707                 }
708                 else {
709                         use_factory_settings = true;
710                 }
711
712                 if (filepath_startup_override) {
713                         BLI_strncpy(filepath_startup, filepath_startup_override, FILE_MAX);
714                 }
715         }
716
717         /* load preferences before startup.blend */
718         if (use_userdef) {
719                 if (!use_factory_settings && BLI_exists(filepath_userdef)) {
720                         UserDef *userdef = BKE_blendfile_userdef_read(filepath_userdef, NULL);
721                         if (userdef != NULL) {
722                                 BKE_blender_userdef_data_set_and_free(userdef);
723                                 userdef = NULL;
724
725                                 skip_flags |= BLO_READ_SKIP_USERDEF;
726                                 printf("Read prefs: %s\n", filepath_userdef);
727                         }
728                 }
729         }
730
731         const char *app_template = NULL;
732
733         if (filepath_startup_override != NULL) {
734                 /* pass */
735         }
736         else if (app_template_override) {
737                 /* This may be clearing the current template by setting to an empty string. */
738                 app_template = app_template_override;
739         }
740         else if (!use_factory_settings && U.app_template[0]) {
741                 app_template = U.app_template;
742         }
743
744         if ((app_template != NULL) && (app_template[0] != '\0')) {
745                 BKE_appdir_app_template_id_search(app_template, app_template_system, sizeof(app_template_system));
746
747                 /* Insert template name into startup file. */
748
749                 /* note that the path is being set even when 'use_factory_settings == true'
750                  * this is done so we can load a templates factory-settings */
751                 if (!use_factory_settings) {
752                         BLI_path_join(app_template_config, sizeof(app_template_config), cfgdir, app_template, NULL);
753                         BLI_path_join(filepath_startup, sizeof(filepath_startup), app_template_config, BLENDER_STARTUP_FILE, NULL);
754                         if (BLI_access(filepath_startup, R_OK) != 0) {
755                                 filepath_startup[0] = '\0';
756                         }
757                 }
758                 else {
759                         filepath_startup[0] = '\0';
760                 }
761
762                 if (filepath_startup[0] == '\0') {
763                         BLI_path_join(filepath_startup, sizeof(filepath_startup), app_template_system, BLENDER_STARTUP_FILE, NULL);
764                 }
765         }
766
767         if (!use_factory_settings || (filepath_startup[0] != '\0')) {
768                 if (BLI_access(filepath_startup, R_OK) == 0) {
769                         success = (BKE_blendfile_read(C, filepath_startup, NULL, skip_flags) != BKE_BLENDFILE_READ_FAIL);
770                 }
771                 if (BLI_listbase_is_empty(&U.themes)) {
772                         if (G.debug & G_DEBUG)
773                                 printf("\nNote: No (valid) '%s' found, fall back to built-in default.\n\n", filepath_startup);
774                         success = false;
775                 }
776         }
777
778         if (success == false && filepath_startup_override && reports) {
779                 /* We can not return from here because wm is already reset */
780                 BKE_reportf(reports, RPT_ERROR, "Could not read '%s'", filepath_startup_override);
781         }
782
783         if (success == false) {
784                 success = BKE_blendfile_read_from_memory(
785                         C, datatoc_startup_blend, datatoc_startup_blend_size,
786                         NULL, skip_flags, true);
787                 if (success) {
788                         if (use_userdef) {
789                                 if ((skip_flags & BLO_READ_SKIP_USERDEF) == 0) {
790                                         read_userdef_from_memory = true;
791                                 }
792                         }
793                 }
794                 if (BLI_listbase_is_empty(&wmbase)) {
795                         wm_clear_default_size(C);
796                 }
797         }
798
799         if (use_empty_data) {
800                 BKE_blendfile_read_make_empty(C);
801         }
802
803         /* Load template preferences,
804          * unlike regular preferences we only use some of the settings,
805          * see: BKE_blender_userdef_set_app_template */
806         if (app_template_system[0] != '\0') {
807                 char temp_path[FILE_MAX];
808                 temp_path[0] = '\0';
809                 if (!use_factory_settings) {
810                         BLI_path_join(temp_path, sizeof(temp_path), app_template_config, BLENDER_USERPREF_FILE, NULL);
811                         if (BLI_access(temp_path, R_OK) != 0) {
812                                 temp_path[0] = '\0';
813                         }
814                 }
815
816                 if (temp_path[0] == '\0') {
817                         BLI_path_join(temp_path, sizeof(temp_path), app_template_system, BLENDER_USERPREF_FILE, NULL);
818                 }
819
820                 if (use_userdef) {
821                         UserDef *userdef_template = NULL;
822                         /* just avoids missing file warning */
823                         if (BLI_exists(temp_path)) {
824                                 userdef_template = BKE_blendfile_userdef_read(temp_path, NULL);
825                         }
826                         if (userdef_template == NULL) {
827                                 /* we need to have preferences load to overwrite preferences from previous template */
828                                 userdef_template = BKE_blendfile_userdef_read_from_memory(
829                                         datatoc_startup_blend, datatoc_startup_blend_size, NULL);
830                                 read_userdef_from_memory = true;
831                         }
832                         if (userdef_template) {
833                                 BKE_blender_userdef_app_template_data_set_and_free(userdef_template);
834                                 userdef_template = NULL;
835                         }
836                 }
837         }
838
839         if (app_template_override) {
840                 BLI_strncpy(U.app_template, app_template_override, sizeof(U.app_template));
841         }
842
843         /* prevent buggy files that had G_FILE_RELATIVE_REMAP written out by mistake. Screws up autosaves otherwise
844          * can remove this eventually, only in a 2.53 and older, now its not written */
845         G.fileflags &= ~G_FILE_RELATIVE_REMAP;
846         
847         if (use_userdef) {
848                 /* check userdef before open window, keymaps etc */
849                 wm_init_userdef(CTX_data_main(C), read_userdef_from_memory);
850         }
851         
852         /* match the read WM with current WM */
853         wm_window_match_do(C, &wmbase); 
854         WM_check(C); /* opens window(s), checks keymaps */
855
856         G.main->name[0] = '\0';
857
858         if (use_userdef) {
859                 /* When loading factory settings, the reset solid OpenGL lights need to be applied. */
860                 if (!G.background) {
861                         GPU_default_lights();
862                 }
863         }
864
865         /* start with save preference untitled.blend */
866         G.save_over = 0;
867         /* disable auto-play in startup.blend... */
868         G.fileflags &= ~G_FILE_AUTOPLAY;
869
870         wm_file_read_post(C, true, use_userdef);
871
872         return true;
873 }
874
875 /** \name WM History File API
876  * \{ */
877
878 void wm_history_file_read(void)
879 {
880         char name[FILE_MAX];
881         LinkNode *l, *lines;
882         struct RecentFile *recent;
883         const char *line;
884         int num;
885         const char * const cfgdir = BKE_appdir_folder_id(BLENDER_USER_CONFIG, NULL);
886
887         if (!cfgdir) return;
888
889         BLI_make_file_string("/", name, cfgdir, BLENDER_HISTORY_FILE);
890
891         lines = BLI_file_read_as_lines(name);
892
893         BLI_listbase_clear(&G.recent_files);
894
895         /* read list of recent opened files from recent-files.txt to memory */
896         for (l = lines, num = 0; l && (num < U.recent_files); l = l->next) {
897                 line = l->link;
898                 /* don't check if files exist, causes slow startup for remote/external drives */
899                 if (line[0]) {
900                         recent = (RecentFile *)MEM_mallocN(sizeof(RecentFile), "RecentFile");
901                         BLI_addtail(&(G.recent_files), recent);
902                         recent->filepath = BLI_strdup(line);
903                         num++;
904                 }
905         }
906         
907         BLI_file_free_lines(lines);
908 }
909
910 static RecentFile *wm_history_file_new(const char *filepath)
911 {
912         RecentFile *recent = MEM_mallocN(sizeof(RecentFile), "RecentFile");
913         recent->filepath = BLI_strdup(filepath);
914         return recent;
915 }
916
917 static void wm_history_file_free(RecentFile *recent)
918 {
919         BLI_assert(BLI_findindex(&G.recent_files, recent) != -1);
920         MEM_freeN(recent->filepath);
921         BLI_freelinkN(&G.recent_files, recent);
922 }
923
924 static RecentFile *wm_file_history_find(const char *filepath)
925 {
926         return BLI_findstring_ptr(&G.recent_files, filepath, offsetof(RecentFile, filepath));
927 }
928
929 /**
930  * Write #BLENDER_HISTORY_FILE as-is, without checking the environment
931  * (thats handled by #wm_history_file_update).
932  */
933 static void wm_history_file_write(void)
934 {
935         const char *user_config_dir;
936         char name[FILE_MAX];
937         FILE *fp;
938
939         /* will be NULL in background mode */
940         user_config_dir = BKE_appdir_folder_id_create(BLENDER_USER_CONFIG, NULL);
941         if (!user_config_dir)
942                 return;
943
944         BLI_make_file_string("/", name, user_config_dir, BLENDER_HISTORY_FILE);
945
946         fp = BLI_fopen(name, "w");
947         if (fp) {
948                 struct RecentFile *recent;
949                 for (recent = G.recent_files.first; recent; recent = recent->next) {
950                         fprintf(fp, "%s\n", recent->filepath);
951                 }
952                 fclose(fp);
953         }
954 }
955
956 /**
957  * Run after saving a file to refresh the #BLENDER_HISTORY_FILE list.
958  */
959 static void wm_history_file_update(void)
960 {
961         RecentFile *recent;
962
963         /* no write history for recovered startup files */
964         if (G.main->name[0] == 0)
965                 return;
966
967         recent = G.recent_files.first;
968         /* refresh recent-files.txt of recent opened files, when current file was changed */
969         if (!(recent) || (BLI_path_cmp(recent->filepath, G.main->name) != 0)) {
970
971                 recent = wm_file_history_find(G.main->name);
972                 if (recent) {
973                         BLI_remlink(&G.recent_files, recent);
974                 }
975                 else {
976                         RecentFile *recent_next;
977                         for (recent = BLI_findlink(&G.recent_files, U.recent_files - 1); recent; recent = recent_next) {
978                                 recent_next = recent->next;
979                                 wm_history_file_free(recent);
980                         }
981                         recent = wm_history_file_new(G.main->name);
982                 }
983
984                 /* add current file to the beginning of list */
985                 BLI_addhead(&(G.recent_files), recent);
986
987                 /* write current file to recent-files.txt */
988                 wm_history_file_write();
989
990                 /* also update most recent files on System */
991                 GHOST_addToSystemRecentFiles(G.main->name);
992         }
993 }
994
995 /** \} */
996
997
998 /* screen can be NULL */
999 static ImBuf *blend_file_thumb(Scene *scene, bScreen *screen, BlendThumbnail **thumb_pt)
1000 {
1001         /* will be scaled down, but gives some nice oversampling */
1002         ImBuf *ibuf;
1003         BlendThumbnail *thumb;
1004         char err_out[256] = "unknown";
1005
1006         /* screen if no camera found */
1007         ScrArea *sa = NULL;
1008         ARegion *ar = NULL;
1009         View3D *v3d = NULL;
1010
1011         /* In case we are given a valid thumbnail data, just generate image from it. */
1012         if (*thumb_pt) {
1013                 thumb = *thumb_pt;
1014                 return BKE_main_thumbnail_to_imbuf(NULL, thumb);
1015         }
1016
1017         /* scene can be NULL if running a script at startup and calling the save operator */
1018         if (G.background || scene == NULL)
1019                 return NULL;
1020
1021         if ((scene->camera == NULL) && (screen != NULL)) {
1022                 sa = BKE_screen_find_big_area(screen, SPACE_VIEW3D, 0);
1023                 ar = BKE_area_find_region_type(sa, RGN_TYPE_WINDOW);
1024                 if (ar) {
1025                         v3d = sa->spacedata.first;
1026                 }
1027         }
1028
1029         if (scene->camera == NULL && v3d == NULL) {
1030                 return NULL;
1031         }
1032
1033         /* gets scaled to BLEN_THUMB_SIZE */
1034         if (scene->camera) {
1035                 ibuf = ED_view3d_draw_offscreen_imbuf_simple(
1036                         scene, scene->camera,
1037                         BLEN_THUMB_SIZE * 2, BLEN_THUMB_SIZE * 2,
1038                         IB_rect, V3D_OFSDRAW_NONE, OB_SOLID, R_ALPHAPREMUL, 0, NULL,
1039                         NULL, NULL, err_out);
1040         }
1041         else {
1042                 ibuf = ED_view3d_draw_offscreen_imbuf(
1043                         scene, v3d, ar,
1044                         BLEN_THUMB_SIZE * 2, BLEN_THUMB_SIZE * 2,
1045                         IB_rect, V3D_OFSDRAW_NONE, R_ALPHAPREMUL, 0, NULL,
1046                         NULL, NULL, err_out);
1047         }
1048
1049         if (ibuf) {
1050                 float aspect = (scene->r.xsch * scene->r.xasp) / (scene->r.ysch * scene->r.yasp);
1051
1052                 /* dirty oversampling */
1053                 IMB_scaleImBuf(ibuf, BLEN_THUMB_SIZE, BLEN_THUMB_SIZE);
1054
1055                 /* add pretty overlay */
1056                 IMB_thumb_overlay_blend(ibuf->rect, ibuf->x, ibuf->y, aspect);
1057                 
1058                 thumb = BKE_main_thumbnail_from_imbuf(NULL, ibuf);
1059         }
1060         else {
1061                 /* '*thumb_pt' needs to stay NULL to prevent a bad thumbnail from being handled */
1062                 fprintf(stderr, "blend_file_thumb failed to create thumbnail: %s\n", err_out);
1063                 thumb = NULL;
1064         }
1065         
1066         /* must be freed by caller */
1067         *thumb_pt = thumb;
1068         
1069         return ibuf;
1070 }
1071
1072 /* easy access from gdb */
1073 bool write_crash_blend(void)
1074 {
1075         char path[FILE_MAX];
1076         int fileflags = G.fileflags & ~(G_FILE_HISTORY); /* don't do file history on crash file */
1077
1078         BLI_strncpy(path, G.main->name, sizeof(path));
1079         BLI_replace_extension(path, sizeof(path), "_crash.blend");
1080         if (BLO_write_file(G.main, path, fileflags, NULL, NULL)) {
1081                 printf("written: %s\n", path);
1082                 return 1;
1083         }
1084         else {
1085                 printf("failed: %s\n", path);
1086                 return 0;
1087         }
1088 }
1089
1090 /**
1091  * \see #wm_homefile_write_exec wraps #BLO_write_file in a similar way.
1092  */
1093 static int wm_file_write(bContext *C, const char *filepath, int fileflags, ReportList *reports)
1094 {
1095         Library *li;
1096         int len;
1097         int ret = -1;
1098         BlendThumbnail *thumb, *main_thumb;
1099         ImBuf *ibuf_thumb = NULL;
1100
1101         len = strlen(filepath);
1102         
1103         if (len == 0) {
1104                 BKE_report(reports, RPT_ERROR, "Path is empty, cannot save");
1105                 return ret;
1106         }
1107
1108         if (len >= FILE_MAX) {
1109                 BKE_report(reports, RPT_ERROR, "Path too long, cannot save");
1110                 return ret;
1111         }
1112         
1113         /* Check if file write permission is ok */
1114         if (BLI_exists(filepath) && !BLI_file_is_writable(filepath)) {
1115                 BKE_reportf(reports, RPT_ERROR, "Cannot save blend file, path '%s' is not writable", filepath);
1116                 return ret;
1117         }
1118
1119         /* note: used to replace the file extension (to ensure '.blend'),
1120          * no need to now because the operator ensures,
1121          * its handy for scripts to save to a predefined name without blender editing it */
1122         
1123         /* send the OnSave event */
1124         for (li = G.main->library.first; li; li = li->id.next) {
1125                 if (BLI_path_cmp(li->filepath, filepath) == 0) {
1126                         BKE_reportf(reports, RPT_ERROR, "Cannot overwrite used library '%.240s'", filepath);
1127                         return ret;
1128                 }
1129         }
1130
1131         /* Call pre-save callbacks befores writing preview, that way you can generate custom file thumbnail... */
1132         BLI_callback_exec(G.main, NULL, BLI_CB_EVT_SAVE_PRE);
1133
1134         /* blend file thumbnail */
1135         /* save before exit_editmode, otherwise derivedmeshes for shared data corrupt #27765) */
1136         /* Main now can store a .blend thumbnail, usefull for background mode or thumbnail customization. */
1137         main_thumb = thumb = CTX_data_main(C)->blen_thumb;
1138         if ((U.flag & USER_SAVE_PREVIEWS) && BLI_thread_is_main()) {
1139                 ibuf_thumb = blend_file_thumb(CTX_data_scene(C), CTX_wm_screen(C), &thumb);
1140         }
1141
1142         /* operator now handles overwrite checks */
1143
1144         if (G.fileflags & G_AUTOPACK) {
1145                 packAll(G.main, reports, false);
1146         }
1147
1148         /* don't forget not to return without! */
1149         WM_cursor_wait(1);
1150         
1151         ED_editors_flush_edits(C, false);
1152
1153         fileflags |= G_FILE_HISTORY; /* write file history */
1154
1155         /* first time saving */
1156         /* XXX temp solution to solve bug, real fix coming (ton) */
1157         if ((G.main->name[0] == '\0') && !(fileflags & G_FILE_SAVE_COPY)) {
1158                 BLI_strncpy(G.main->name, filepath, sizeof(G.main->name));
1159         }
1160
1161         /* XXX temp solution to solve bug, real fix coming (ton) */
1162         G.main->recovered = 0;
1163         
1164         if (BLO_write_file(CTX_data_main(C), filepath, fileflags, reports, thumb)) {
1165                 const bool do_history = (G.background == false) && (CTX_wm_manager(C)->op_undo_depth == 0);
1166
1167                 if (!(fileflags & G_FILE_SAVE_COPY)) {
1168                         G.relbase_valid = 1;
1169                         BLI_strncpy(G.main->name, filepath, sizeof(G.main->name));  /* is guaranteed current file */
1170         
1171                         G.save_over = 1; /* disable untitled.blend convention */
1172                 }
1173
1174                 SET_FLAG_FROM_TEST(G.fileflags, fileflags & G_FILE_COMPRESS, G_FILE_COMPRESS);
1175                 SET_FLAG_FROM_TEST(G.fileflags, fileflags & G_FILE_AUTOPLAY, G_FILE_AUTOPLAY);
1176
1177                 /* prevent background mode scripts from clobbering history */
1178                 if (do_history) {
1179                         wm_history_file_update();
1180                 }
1181
1182                 BLI_callback_exec(G.main, NULL, BLI_CB_EVT_SAVE_POST);
1183
1184                 /* run this function after because the file cant be written before the blend is */
1185                 if (ibuf_thumb) {
1186                         IMB_thumb_delete(filepath, THB_FAIL); /* without this a failed thumb overrides */
1187                         ibuf_thumb = IMB_thumb_create(filepath, THB_LARGE, THB_SOURCE_BLEND, ibuf_thumb);
1188                 }
1189
1190                 ret = 0;  /* Success. */
1191         }
1192
1193         if (ibuf_thumb) {
1194                 IMB_freeImBuf(ibuf_thumb);
1195         }
1196         if (thumb && thumb != main_thumb) {
1197                 MEM_freeN(thumb);
1198         }
1199
1200         WM_cursor_wait(0);
1201
1202         return ret;
1203 }
1204
1205 /************************ autosave ****************************/
1206
1207 void wm_autosave_location(char *filepath)
1208 {
1209         const int pid = abs(getpid());
1210         char path[1024];
1211 #ifdef WIN32
1212         const char *savedir;
1213 #endif
1214
1215         if (G.main && G.relbase_valid) {
1216                 const char *basename = BLI_path_basename(G.main->name);
1217                 int len = strlen(basename) - 6;
1218                 BLI_snprintf(path, sizeof(path), "%.*s.blend", len, basename);
1219         }
1220         else {
1221                 BLI_snprintf(path, sizeof(path), "%d.blend", pid);
1222         }
1223
1224 #ifdef WIN32
1225         /* XXX Need to investigate how to handle default location of '/tmp/'
1226          * This is a relative directory on Windows, and it may be
1227          * found. Example:
1228          * Blender installed on D:\ drive, D:\ drive has D:\tmp\
1229          * Now, BLI_exists() will find '/tmp/' exists, but
1230          * BLI_make_file_string will create string that has it most likely on C:\
1231          * through get_default_root().
1232          * If there is no C:\tmp autosave fails. */
1233         if (!BLI_exists(BKE_tempdir_base())) {
1234                 savedir = BKE_appdir_folder_id_create(BLENDER_USER_AUTOSAVE, NULL);
1235                 BLI_make_file_string("/", filepath, savedir, path);
1236                 return;
1237         }
1238 #endif
1239
1240         BLI_make_file_string("/", filepath, BKE_tempdir_base(), path);
1241 }
1242
1243 void WM_autosave_init(wmWindowManager *wm)
1244 {
1245         wm_autosave_timer_ended(wm);
1246
1247         if (U.flag & USER_AUTOSAVE)
1248                 wm->autosavetimer = WM_event_add_timer(wm, NULL, TIMERAUTOSAVE, U.savetime * 60.0);
1249 }
1250
1251 void wm_autosave_timer(const bContext *C, wmWindowManager *wm, wmTimer *UNUSED(wt))
1252 {
1253         wmWindow *win;
1254         wmEventHandler *handler;
1255         char filepath[FILE_MAX];
1256         
1257         WM_event_remove_timer(wm, NULL, wm->autosavetimer);
1258
1259         /* if a modal operator is running, don't autosave, but try again in 10 seconds */
1260         for (win = wm->windows.first; win; win = win->next) {
1261                 for (handler = win->modalhandlers.first; handler; handler = handler->next) {
1262                         if (handler->op) {
1263                                 wm->autosavetimer = WM_event_add_timer(wm, NULL, TIMERAUTOSAVE, 10.0);
1264                                 if (G.debug) {
1265                                         printf("Skipping auto-save, modal operator running, retrying in ten seconds...\n");
1266                                 }
1267                                 return;
1268                         }
1269                 }
1270         }
1271
1272         wm_autosave_location(filepath);
1273
1274         if (U.uiflag & USER_GLOBALUNDO) {
1275                 /* fast save of last undobuffer, now with UI */
1276                 struct MemFile *memfile = ED_undosys_stack_memfile_get_active(wm->undo_stack);
1277                 if (memfile) {
1278                         BLO_memfile_write_file(memfile, filepath);
1279                 }
1280         }
1281         else {
1282                 /*  save as regular blend file */
1283                 int fileflags = G.fileflags & ~(G_FILE_COMPRESS | G_FILE_AUTOPLAY | G_FILE_HISTORY);
1284
1285                 ED_editors_flush_edits(C, false);
1286
1287                 /* Error reporting into console */
1288                 BLO_write_file(CTX_data_main(C), filepath, fileflags, NULL, NULL);
1289         }
1290         /* do timer after file write, just in case file write takes a long time */
1291         wm->autosavetimer = WM_event_add_timer(wm, NULL, TIMERAUTOSAVE, U.savetime * 60.0);
1292 }
1293
1294 void wm_autosave_timer_ended(wmWindowManager *wm)
1295 {
1296         if (wm->autosavetimer) {
1297                 WM_event_remove_timer(wm, NULL, wm->autosavetimer);
1298                 wm->autosavetimer = NULL;
1299         }
1300 }
1301
1302 void wm_autosave_delete(void)
1303 {
1304         char filename[FILE_MAX];
1305         
1306         wm_autosave_location(filename);
1307
1308         if (BLI_exists(filename)) {
1309                 char str[FILE_MAX];
1310                 BLI_make_file_string("/", str, BKE_tempdir_base(), BLENDER_QUIT_FILE);
1311
1312                 /* if global undo; remove tempsave, otherwise rename */
1313                 if (U.uiflag & USER_GLOBALUNDO) BLI_delete(filename, false, false);
1314                 else BLI_rename(filename, str);
1315         }
1316 }
1317
1318 void wm_autosave_read(bContext *C, ReportList *reports)
1319 {
1320         char filename[FILE_MAX];
1321
1322         wm_autosave_location(filename);
1323         WM_file_read(C, filename, reports);
1324 }
1325
1326
1327 /** \name Initialize WM_OT_open_xxx properties
1328  *
1329  * Check if load_ui was set by the caller.
1330  * Fall back to user preference when file flags not specified.
1331  *
1332  * \{ */
1333
1334 void wm_open_init_load_ui(wmOperator *op, bool use_prefs)
1335 {
1336         PropertyRNA *prop = RNA_struct_find_property(op->ptr, "load_ui");
1337         if (!RNA_property_is_set(op->ptr, prop)) {
1338                 bool value = use_prefs ?
1339                              ((U.flag & USER_FILENOUI) == 0) :
1340                              ((G.fileflags & G_FILE_NO_UI) == 0);
1341
1342                 RNA_property_boolean_set(op->ptr, prop, value);
1343         }
1344 }
1345
1346 void wm_open_init_use_scripts(wmOperator *op, bool use_prefs)
1347 {
1348         PropertyRNA *prop = RNA_struct_find_property(op->ptr, "use_scripts");
1349         if (!RNA_property_is_set(op->ptr, prop)) {
1350                 /* use G_SCRIPT_AUTOEXEC rather than the userpref because this means if
1351                  * the flag has been disabled from the command line, then opening
1352                  * from the menu wont enable this setting. */
1353                 bool value = use_prefs ?
1354                              ((U.flag & USER_SCRIPT_AUTOEXEC_DISABLE) == 0) :
1355                              ((G.f & G_SCRIPT_AUTOEXEC) != 0);
1356
1357                 RNA_property_boolean_set(op->ptr, prop, value);
1358         }
1359 }
1360
1361 /** \} */
1362
1363 void WM_file_tag_modified(void)
1364 {
1365         wmWindowManager *wm = G.main->wm.first;
1366         if (wm->file_saved) {
1367                 wm->file_saved = 0;
1368                 /* notifier that data changed, for save-over warning or header */
1369                 WM_main_add_notifier(NC_WM | ND_DATACHANGED, NULL);
1370         }
1371 }
1372
1373 /** \name Preferences/startup save & load.
1374  *
1375  * \{ */
1376
1377 /**
1378  * \see #wm_file_write wraps #BLO_write_file in a similar way.
1379  */
1380 static int wm_homefile_write_exec(bContext *C, wmOperator *op)
1381 {
1382         wmWindowManager *wm = CTX_wm_manager(C);
1383         wmWindow *win = CTX_wm_window(C);
1384         char filepath[FILE_MAX];
1385         int fileflags;
1386
1387         const char *app_template = U.app_template[0] ? U.app_template : NULL;
1388         const char * const cfgdir = BKE_appdir_folder_id_create(BLENDER_USER_CONFIG, app_template);
1389         if (cfgdir == NULL) {
1390                 BKE_report(op->reports, RPT_ERROR, "Unable to create user config path");
1391                 return OPERATOR_CANCELLED;
1392         }
1393
1394         BLI_callback_exec(G.main, NULL, BLI_CB_EVT_SAVE_PRE);
1395
1396         /* check current window and close it if temp */
1397         if (win && win->screen->temp)
1398                 wm_window_close(C, wm, win);
1399
1400         /* update keymaps in user preferences */
1401         WM_keyconfig_update(wm);
1402
1403         BLI_path_join(filepath, sizeof(filepath), cfgdir, BLENDER_STARTUP_FILE, NULL);
1404
1405         printf("trying to save homefile at %s ", filepath);
1406
1407         ED_editors_flush_edits(C, false);
1408
1409         /*  force save as regular blend file */
1410         fileflags = G.fileflags & ~(G_FILE_COMPRESS | G_FILE_AUTOPLAY | G_FILE_HISTORY);
1411
1412         if (BLO_write_file(CTX_data_main(C), filepath, fileflags | G_FILE_USERPREFS, op->reports, NULL) == 0) {
1413                 printf("fail\n");
1414                 return OPERATOR_CANCELLED;
1415         }
1416
1417         printf("ok\n");
1418
1419         G.save_over = 0;
1420
1421         BLI_callback_exec(G.main, NULL, BLI_CB_EVT_SAVE_POST);
1422
1423         return OPERATOR_FINISHED;
1424 }
1425
1426 void WM_OT_save_homefile(wmOperatorType *ot)
1427 {
1428         ot->name = "Save Startup File";
1429         ot->idname = "WM_OT_save_homefile";
1430         ot->description = "Make the current file the default .blend file, includes preferences";
1431
1432         ot->invoke = WM_operator_confirm;
1433         ot->exec = wm_homefile_write_exec;
1434 }
1435
1436 static int wm_userpref_autoexec_add_exec(bContext *UNUSED(C), wmOperator *UNUSED(op))
1437 {
1438         bPathCompare *path_cmp = MEM_callocN(sizeof(bPathCompare), "bPathCompare");
1439         BLI_addtail(&U.autoexec_paths, path_cmp);
1440         return OPERATOR_FINISHED;
1441 }
1442
1443 void WM_OT_userpref_autoexec_path_add(wmOperatorType *ot)
1444 {
1445         ot->name = "Add Autoexec Path";
1446         ot->idname = "WM_OT_userpref_autoexec_path_add";
1447         ot->description = "Add path to exclude from autoexecution";
1448
1449         ot->exec = wm_userpref_autoexec_add_exec;
1450
1451         ot->flag = OPTYPE_INTERNAL;
1452 }
1453
1454 static int wm_userpref_autoexec_remove_exec(bContext *UNUSED(C), wmOperator *op)
1455 {
1456         const int index = RNA_int_get(op->ptr, "index");
1457         bPathCompare *path_cmp = BLI_findlink(&U.autoexec_paths, index);
1458         if (path_cmp) {
1459                 BLI_freelinkN(&U.autoexec_paths, path_cmp);
1460         }
1461         return OPERATOR_FINISHED;
1462 }
1463
1464 void WM_OT_userpref_autoexec_path_remove(wmOperatorType *ot)
1465 {
1466         ot->name = "Remove Autoexec Path";
1467         ot->idname = "WM_OT_userpref_autoexec_path_remove";
1468         ot->description = "Remove path to exclude from autoexecution";
1469
1470         ot->exec = wm_userpref_autoexec_remove_exec;
1471
1472         ot->flag = OPTYPE_INTERNAL;
1473
1474         RNA_def_int(ot->srna, "index", 0, 0, INT_MAX, "Index", "", 0, 1000);
1475 }
1476
1477 /* Only save the prefs block. operator entry */
1478 static int wm_userpref_write_exec(bContext *C, wmOperator *op)
1479 {
1480         wmWindowManager *wm = CTX_wm_manager(C);
1481         char filepath[FILE_MAX];
1482         const char *cfgdir;
1483         bool ok = true;
1484
1485         /* update keymaps in user preferences */
1486         WM_keyconfig_update(wm);
1487
1488         if ((cfgdir = BKE_appdir_folder_id_create(BLENDER_USER_CONFIG, NULL))) {
1489                 bool ok_write;
1490                 BLI_path_join(filepath, sizeof(filepath), cfgdir, BLENDER_USERPREF_FILE, NULL);
1491                 printf("trying to save userpref at %s ", filepath);
1492
1493                 if (U.app_template[0]) {
1494                         ok_write = BKE_blendfile_userdef_write_app_template(filepath, op->reports);
1495                 }
1496                 else {
1497                         ok_write = BKE_blendfile_userdef_write(filepath, op->reports);
1498                 }
1499
1500                 if (ok_write) {
1501                         printf("ok\n");
1502                 }
1503                 else {
1504                         printf("fail\n");
1505                         ok = false;
1506                 }
1507         }
1508         else {
1509                 BKE_report(op->reports, RPT_ERROR, "Unable to create userpref path");
1510         }
1511
1512         if (U.app_template[0]) {
1513                 if ((cfgdir = BKE_appdir_folder_id_create(BLENDER_USER_CONFIG, U.app_template))) {
1514                         /* Also save app-template prefs */
1515                         BLI_path_join(filepath, sizeof(filepath), cfgdir, BLENDER_USERPREF_FILE, NULL);
1516                         printf("trying to save app-template userpref at %s ", filepath);
1517                         if (BKE_blendfile_userdef_write(filepath, op->reports) != 0) {
1518                                 printf("ok\n");
1519                         }
1520                         else {
1521                                 printf("fail\n");
1522                                 ok = false;
1523                         }
1524                 }
1525                 else {
1526                         BKE_report(op->reports, RPT_ERROR, "Unable to create app-template userpref path");
1527                         ok = false;
1528                 }
1529         }
1530
1531         return ok ? OPERATOR_FINISHED : OPERATOR_CANCELLED;
1532 }
1533
1534 void WM_OT_save_userpref(wmOperatorType *ot)
1535 {
1536         ot->name = "Save User Settings";
1537         ot->idname = "WM_OT_save_userpref";
1538         ot->description = "Save user preferences separately, overrides startup file preferences";
1539
1540         ot->invoke = WM_operator_confirm;
1541         ot->exec = wm_userpref_write_exec;
1542 }
1543
1544 static int wm_history_file_read_exec(bContext *UNUSED(C), wmOperator *UNUSED(op))
1545 {
1546         ED_file_read_bookmarks();
1547         wm_history_file_read();
1548         return OPERATOR_FINISHED;
1549 }
1550
1551 void WM_OT_read_history(wmOperatorType *ot)
1552 {
1553         ot->name = "Reload History File";
1554         ot->idname = "WM_OT_read_history";
1555         ot->description = "Reloads history and bookmarks";
1556
1557         ot->invoke = WM_operator_confirm;
1558         ot->exec = wm_history_file_read_exec;
1559
1560         /* this operator is only used for loading settings from a previous blender install */
1561         ot->flag = OPTYPE_INTERNAL;
1562 }
1563
1564 static int wm_homefile_read_exec(bContext *C, wmOperator *op)
1565 {
1566         const bool use_factory_settings = (STREQ(op->type->idname, "WM_OT_read_factory_settings"));
1567         bool use_userdef = false;
1568         char filepath_buf[FILE_MAX];
1569         const char *filepath = NULL;
1570
1571         if (!use_factory_settings) {
1572                 PropertyRNA *prop = RNA_struct_find_property(op->ptr, "filepath");
1573
1574                 /* This can be used when loading of a start-up file should only change
1575                  * the scene content but keep the blender UI as it is. */
1576                 wm_open_init_load_ui(op, true);
1577                 SET_FLAG_FROM_TEST(G.fileflags, !RNA_boolean_get(op->ptr, "load_ui"), G_FILE_NO_UI);
1578
1579                 if (RNA_property_is_set(op->ptr, prop)) {
1580                         RNA_property_string_get(op->ptr, prop, filepath_buf);
1581                         filepath = filepath_buf;
1582                         if (BLI_access(filepath, R_OK)) {
1583                                 BKE_reportf(op->reports, RPT_ERROR, "Can't read alternative start-up file: '%s'", filepath);
1584                                 return OPERATOR_CANCELLED;
1585                         }
1586                 }
1587         }
1588         else {
1589                 /* always load UI for factory settings (prefs will re-init) */
1590                 G.fileflags &= ~G_FILE_NO_UI;
1591                 /* Always load preferences with factory settings. */
1592                 use_userdef = true;
1593         }
1594
1595         char app_template_buf[sizeof(U.app_template)];
1596         const char *app_template;
1597         PropertyRNA *prop_app_template = RNA_struct_find_property(op->ptr, "app_template");
1598         const bool use_splash = !use_factory_settings && RNA_boolean_get(op->ptr, "use_splash");
1599         const bool use_empty_data = RNA_boolean_get(op->ptr, "use_empty");
1600
1601         if (prop_app_template && RNA_property_is_set(op->ptr, prop_app_template)) {
1602                 RNA_property_string_get(op->ptr, prop_app_template, app_template_buf);
1603                 app_template = app_template_buf;
1604
1605                 /* Always load preferences when switching templates. */
1606                 use_userdef = true;
1607         }
1608         else {
1609                 app_template = NULL;
1610         }
1611
1612         if (wm_homefile_read(C, op->reports, use_factory_settings, use_empty_data, use_userdef, filepath, app_template)) {
1613                 if (use_splash) {
1614                         WM_init_splash(C);
1615                 }
1616                 return OPERATOR_FINISHED;
1617         }
1618         else {
1619                 return OPERATOR_CANCELLED;
1620         }
1621 }
1622
1623 void WM_OT_read_homefile(wmOperatorType *ot)
1624 {
1625         PropertyRNA *prop;
1626         ot->name = "Reload Start-Up File";
1627         ot->idname = "WM_OT_read_homefile";
1628         ot->description = "Open the default file (doesn't save the current file)";
1629
1630         ot->invoke = WM_operator_confirm;
1631         ot->exec = wm_homefile_read_exec;
1632
1633         prop = RNA_def_string_file_path(ot->srna, "filepath", NULL,
1634                                         FILE_MAX, "File Path",
1635                                         "Path to an alternative start-up file");
1636         RNA_def_property_flag(prop, PROP_HIDDEN);
1637
1638         /* So scripts can use an alternative start-up file without the UI */
1639         prop = RNA_def_boolean(ot->srna, "load_ui", true, "Load UI",
1640                                "Load user interface setup from the .blend file");
1641         RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
1642
1643         prop = RNA_def_boolean(ot->srna, "use_empty", false, "Empty", "");
1644         RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
1645
1646         /* So the splash can be kept open after loading a file (for templates). */
1647         prop = RNA_def_boolean(ot->srna, "use_splash", false, "Splash", "");
1648         RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
1649
1650         prop = RNA_def_string(ot->srna, "app_template", "Template", sizeof(U.app_template), "", "");
1651         RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
1652
1653         /* omit poll to run in background mode */
1654 }
1655
1656 void WM_OT_read_factory_settings(wmOperatorType *ot)
1657 {
1658         PropertyRNA *prop;
1659
1660         ot->name = "Load Factory Settings";
1661         ot->idname = "WM_OT_read_factory_settings";
1662         ot->description = "Load default file and user preferences";
1663
1664         ot->invoke = WM_operator_confirm;
1665         ot->exec = wm_homefile_read_exec;
1666
1667         prop = RNA_def_string(ot->srna, "app_template", "Template", sizeof(U.app_template), "", "");
1668         RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
1669
1670         prop = RNA_def_boolean(ot->srna, "use_empty", false, "Empty", "");
1671         RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
1672
1673         /* omit poll to run in background mode */
1674 }
1675
1676 /** \} */
1677
1678 /** \name Open main .blend file.
1679  *
1680  * \{ */
1681
1682 /**
1683  * Wrap #WM_file_read, shared by file reading operators.
1684  */
1685 static bool wm_file_read_opwrap(bContext *C, const char *filepath, ReportList *reports,
1686                                 const bool autoexec_init)
1687 {
1688         bool success;
1689
1690         /* XXX wm in context is not set correctly after WM_file_read -> crash */
1691         /* do it before for now, but is this correct with multiple windows? */
1692         WM_event_add_notifier(C, NC_WINDOW, NULL);
1693
1694         if (autoexec_init) {
1695                 WM_file_autoexec_init(filepath);
1696         }
1697
1698         success = WM_file_read(C, filepath, reports);
1699
1700         return success;
1701 }
1702
1703 /* currently fits in a pointer */
1704 struct FileRuntime {
1705         bool is_untrusted;
1706 };
1707
1708 static int wm_open_mainfile_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1709 {
1710         const char *openname = G.main->name;
1711
1712         if (CTX_wm_window(C) == NULL) {
1713                 /* in rare cases this could happen, when trying to invoke in background
1714                  * mode on load for example. Don't use poll for this because exec()
1715                  * can still run without a window */
1716                 BKE_report(op->reports, RPT_ERROR, "Context window not set");
1717                 return OPERATOR_CANCELLED;
1718         }
1719
1720         /* if possible, get the name of the most recently used .blend file */
1721         if (G.recent_files.first) {
1722                 struct RecentFile *recent = G.recent_files.first;
1723                 openname = recent->filepath;
1724         }
1725
1726         RNA_string_set(op->ptr, "filepath", openname);
1727         wm_open_init_load_ui(op, true);
1728         wm_open_init_use_scripts(op, true);
1729         op->customdata = NULL;
1730
1731         WM_event_add_fileselect(C, op);
1732
1733         return OPERATOR_RUNNING_MODAL;
1734 }
1735
1736 static int wm_open_mainfile_exec(bContext *C, wmOperator *op)
1737 {
1738         char filepath[FILE_MAX];
1739         bool success;
1740
1741         RNA_string_get(op->ptr, "filepath", filepath);
1742
1743         /* re-use last loaded setting so we can reload a file without changing */
1744         wm_open_init_load_ui(op, false);
1745         wm_open_init_use_scripts(op, false);
1746
1747         if (RNA_boolean_get(op->ptr, "load_ui"))
1748                 G.fileflags &= ~G_FILE_NO_UI;
1749         else
1750                 G.fileflags |= G_FILE_NO_UI;
1751
1752         if (RNA_boolean_get(op->ptr, "use_scripts"))
1753                 G.f |= G_SCRIPT_AUTOEXEC;
1754         else
1755                 G.f &= ~G_SCRIPT_AUTOEXEC;
1756
1757         success = wm_file_read_opwrap(C, filepath, op->reports, !(G.f & G_SCRIPT_AUTOEXEC));
1758
1759         /* for file open also popup for warnings, not only errors */
1760         BKE_report_print_level_set(op->reports, RPT_WARNING);
1761
1762         if (success) {
1763                 return OPERATOR_FINISHED;
1764         }
1765         else {
1766                 return OPERATOR_CANCELLED;
1767         }
1768 }
1769
1770 static bool wm_open_mainfile_check(bContext *UNUSED(C), wmOperator *op)
1771 {
1772         struct FileRuntime *file_info = (struct FileRuntime *)&op->customdata;
1773         PropertyRNA *prop = RNA_struct_find_property(op->ptr, "use_scripts");
1774         bool is_untrusted = false;
1775         char path[FILE_MAX];
1776         char *lslash;
1777
1778         RNA_string_get(op->ptr, "filepath", path);
1779
1780         /* get the dir */
1781         lslash = (char *)BLI_last_slash(path);
1782         if (lslash) *(lslash + 1) = '\0';
1783
1784         if ((U.flag & USER_SCRIPT_AUTOEXEC_DISABLE) == 0) {
1785                 if (BKE_autoexec_match(path) == true) {
1786                         RNA_property_boolean_set(op->ptr, prop, false);
1787                         is_untrusted = true;
1788                 }
1789         }
1790
1791         if (file_info) {
1792                 file_info->is_untrusted = is_untrusted;
1793         }
1794
1795         return is_untrusted;
1796 }
1797
1798 static void wm_open_mainfile_ui(bContext *UNUSED(C), wmOperator *op)
1799 {
1800         struct FileRuntime *file_info = (struct FileRuntime *)&op->customdata;
1801         uiLayout *layout = op->layout;
1802         uiLayout *col = op->layout;
1803         const char *autoexec_text;
1804
1805         uiItemR(layout, op->ptr, "load_ui", 0, NULL, ICON_NONE);
1806
1807         col = uiLayoutColumn(layout, false);
1808         if (file_info->is_untrusted) {
1809                 autoexec_text = IFACE_("Trusted Source [Untrusted Path]");
1810                 uiLayoutSetActive(col, false);
1811                 uiLayoutSetEnabled(col, false);
1812         }
1813         else {
1814                 autoexec_text = IFACE_("Trusted Source");
1815         }
1816
1817         uiItemR(col, op->ptr, "use_scripts", 0, autoexec_text, ICON_NONE);
1818 }
1819
1820 void WM_OT_open_mainfile(wmOperatorType *ot)
1821 {
1822         ot->name = "Open Blender File";
1823         ot->idname = "WM_OT_open_mainfile";
1824         ot->description = "Open a Blender file";
1825
1826         ot->invoke = wm_open_mainfile_invoke;
1827         ot->exec = wm_open_mainfile_exec;
1828         ot->check = wm_open_mainfile_check;
1829         ot->ui = wm_open_mainfile_ui;
1830         /* omit window poll so this can work in background mode */
1831
1832         WM_operator_properties_filesel(
1833                 ot, FILE_TYPE_FOLDER | FILE_TYPE_BLENDER, FILE_BLENDER, FILE_OPENFILE,
1834                 WM_FILESEL_FILEPATH, FILE_DEFAULTDISPLAY, FILE_SORT_ALPHA);
1835
1836         RNA_def_boolean(ot->srna, "load_ui", true, "Load UI", "Load user interface setup in the .blend file");
1837         RNA_def_boolean(ot->srna, "use_scripts", true, "Trusted Source",
1838                         "Allow .blend file to execute scripts automatically, default available from system preferences");
1839 }
1840
1841 /** \} */
1842
1843 /** \name Reload (revert) main .blend file.
1844  *
1845  * \{ */
1846
1847 static int wm_revert_mainfile_exec(bContext *C, wmOperator *op)
1848 {
1849         bool success;
1850         char filepath[FILE_MAX];
1851
1852         wm_open_init_use_scripts(op, false);
1853
1854         if (RNA_boolean_get(op->ptr, "use_scripts"))
1855                 G.f |= G_SCRIPT_AUTOEXEC;
1856         else
1857                 G.f &= ~G_SCRIPT_AUTOEXEC;
1858
1859         BLI_strncpy(filepath, G.main->name, sizeof(filepath));
1860         success = wm_file_read_opwrap(C, filepath, op->reports, !(G.f & G_SCRIPT_AUTOEXEC));
1861
1862         if (success) {
1863                 return OPERATOR_FINISHED;
1864         }
1865         else {
1866                 return OPERATOR_CANCELLED;
1867         }
1868 }
1869
1870 static int wm_revert_mainfile_poll(bContext *UNUSED(C))
1871 {
1872         return G.relbase_valid;
1873 }
1874
1875 void WM_OT_revert_mainfile(wmOperatorType *ot)
1876 {
1877         ot->name = "Revert";
1878         ot->idname = "WM_OT_revert_mainfile";
1879         ot->description = "Reload the saved file";
1880         ot->invoke = WM_operator_confirm;
1881
1882         RNA_def_boolean(ot->srna, "use_scripts", true, "Trusted Source",
1883                         "Allow .blend file to execute scripts automatically, default available from system preferences");
1884
1885         ot->exec = wm_revert_mainfile_exec;
1886         ot->poll = wm_revert_mainfile_poll;
1887 }
1888
1889 /** \} */
1890
1891 /** \name Recover last session & auto-save.
1892  *
1893  * \{ */
1894
1895 void WM_recover_last_session(bContext *C, ReportList *reports)
1896 {
1897         char filepath[FILE_MAX];
1898
1899         BLI_make_file_string("/", filepath, BKE_tempdir_base(), BLENDER_QUIT_FILE);
1900         /* if reports==NULL, it's called directly without operator, we add a quick check here */
1901         if (reports || BLI_exists(filepath)) {
1902                 G.fileflags |= G_FILE_RECOVER;
1903
1904                 wm_file_read_opwrap(C, filepath, reports, true);
1905
1906                 G.fileflags &= ~G_FILE_RECOVER;
1907
1908                 /* XXX bad global... fixme */
1909                 if (G.main->name[0])
1910                         G.file_loaded = 1;      /* prevents splash to show */
1911                 else {
1912                         G.relbase_valid = 0;
1913                         G.save_over = 0;    /* start with save preference untitled.blend */
1914                 }
1915
1916         }
1917 }
1918
1919 static int wm_recover_last_session_exec(bContext *C, wmOperator *op)
1920 {
1921         WM_recover_last_session(C, op->reports);
1922         return OPERATOR_FINISHED;
1923 }
1924
1925 void WM_OT_recover_last_session(wmOperatorType *ot)
1926 {
1927         ot->name = "Recover Last Session";
1928         ot->idname = "WM_OT_recover_last_session";
1929         ot->description = "Open the last closed file (\"" BLENDER_QUIT_FILE "\")";
1930         ot->invoke = WM_operator_confirm;
1931
1932         ot->exec = wm_recover_last_session_exec;
1933 }
1934
1935 static int wm_recover_auto_save_exec(bContext *C, wmOperator *op)
1936 {
1937         char filepath[FILE_MAX];
1938         bool success;
1939
1940         RNA_string_get(op->ptr, "filepath", filepath);
1941
1942         G.fileflags |= G_FILE_RECOVER;
1943
1944         success = wm_file_read_opwrap(C, filepath, op->reports, true);
1945
1946         G.fileflags &= ~G_FILE_RECOVER;
1947
1948         if (success) {
1949                 return OPERATOR_FINISHED;
1950         }
1951         else {
1952                 return OPERATOR_CANCELLED;
1953         }
1954 }
1955
1956 static int wm_recover_auto_save_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1957 {
1958         char filename[FILE_MAX];
1959
1960         wm_autosave_location(filename);
1961         RNA_string_set(op->ptr, "filepath", filename);
1962         WM_event_add_fileselect(C, op);
1963
1964         return OPERATOR_RUNNING_MODAL;
1965 }
1966
1967 void WM_OT_recover_auto_save(wmOperatorType *ot)
1968 {
1969         ot->name = "Recover Auto Save";
1970         ot->idname = "WM_OT_recover_auto_save";
1971         ot->description = "Open an automatically saved file to recover it";
1972
1973         ot->exec = wm_recover_auto_save_exec;
1974         ot->invoke = wm_recover_auto_save_invoke;
1975
1976         WM_operator_properties_filesel(
1977                 ot, FILE_TYPE_BLENDER, FILE_BLENDER, FILE_OPENFILE,
1978                 WM_FILESEL_FILEPATH, FILE_LONGDISPLAY, FILE_SORT_TIME);
1979 }
1980
1981 /** \} */
1982
1983 /** \name Save main .blend file.
1984  *
1985  * \{ */
1986
1987 static void wm_filepath_default(char *filepath)
1988 {
1989         if (G.save_over == false) {
1990                 BLI_ensure_filename(filepath, FILE_MAX, "untitled.blend");
1991         }
1992 }
1993
1994 static void save_set_compress(wmOperator *op)
1995 {
1996         PropertyRNA *prop;
1997
1998         prop = RNA_struct_find_property(op->ptr, "compress");
1999         if (!RNA_property_is_set(op->ptr, prop)) {
2000                 if (G.save_over) {  /* keep flag for existing file */
2001                         RNA_property_boolean_set(op->ptr, prop, (G.fileflags & G_FILE_COMPRESS) != 0);
2002                 }
2003                 else {  /* use userdef for new file */
2004                         RNA_property_boolean_set(op->ptr, prop, (U.flag & USER_FILECOMPRESS) != 0);
2005                 }
2006         }
2007 }
2008
2009 static void save_set_filepath(wmOperator *op)
2010 {
2011         PropertyRNA *prop;
2012         char name[FILE_MAX];
2013
2014         prop = RNA_struct_find_property(op->ptr, "filepath");
2015         if (!RNA_property_is_set(op->ptr, prop)) {
2016                 /* if not saved before, get the name of the most recently used .blend file */
2017                 if (G.main->name[0] == 0 && G.recent_files.first) {
2018                         struct RecentFile *recent = G.recent_files.first;
2019                         BLI_strncpy(name, recent->filepath, FILE_MAX);
2020                 }
2021                 else {
2022                         BLI_strncpy(name, G.main->name, FILE_MAX);
2023                 }
2024
2025                 wm_filepath_default(name);
2026                 RNA_property_string_set(op->ptr, prop, name);
2027         }
2028 }
2029
2030 static int wm_save_as_mainfile_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
2031 {
2032
2033         save_set_compress(op);
2034         save_set_filepath(op);
2035
2036         WM_event_add_fileselect(C, op);
2037
2038         return OPERATOR_RUNNING_MODAL;
2039 }
2040
2041 /* function used for WM_OT_save_mainfile too */
2042 static int wm_save_as_mainfile_exec(bContext *C, wmOperator *op)
2043 {
2044         char path[FILE_MAX];
2045         int fileflags;
2046
2047         save_set_compress(op);
2048
2049         if (RNA_struct_property_is_set(op->ptr, "filepath")) {
2050                 RNA_string_get(op->ptr, "filepath", path);
2051         }
2052         else {
2053                 BLI_strncpy(path, G.main->name, FILE_MAX);
2054                 wm_filepath_default(path);
2055         }
2056
2057         fileflags = G.fileflags & ~G_FILE_USERPREFS;
2058
2059         /* set compression flag */
2060         SET_FLAG_FROM_TEST(
2061                 fileflags, RNA_boolean_get(op->ptr, "compress"),
2062                 G_FILE_COMPRESS);
2063         SET_FLAG_FROM_TEST(
2064                 fileflags, RNA_boolean_get(op->ptr, "relative_remap"),
2065                 G_FILE_RELATIVE_REMAP);
2066         SET_FLAG_FROM_TEST(
2067                 fileflags,
2068                 (RNA_struct_property_is_set(op->ptr, "copy") &&
2069                  RNA_boolean_get(op->ptr, "copy")),
2070                 G_FILE_SAVE_COPY);
2071
2072 #ifdef USE_BMESH_SAVE_AS_COMPAT
2073         SET_FLAG_FROM_TEST(
2074                 fileflags,
2075                 (RNA_struct_find_property(op->ptr, "use_mesh_compat") &&
2076                  RNA_boolean_get(op->ptr, "use_mesh_compat")),
2077                 G_FILE_MESH_COMPAT);
2078 #else
2079 #  error "don't remove by accident"
2080 #endif
2081
2082         if (wm_file_write(C, path, fileflags, op->reports) != 0)
2083                 return OPERATOR_CANCELLED;
2084
2085         WM_event_add_notifier(C, NC_WM | ND_FILESAVE, NULL);
2086
2087         if (RNA_boolean_get(op->ptr, "exit")) {
2088                 wm_exit_schedule_delayed(C);
2089         }
2090
2091         return OPERATOR_FINISHED;
2092 }
2093
2094 /* function used for WM_OT_save_mainfile too */
2095 static bool blend_save_check(bContext *UNUSED(C), wmOperator *op)
2096 {
2097         char filepath[FILE_MAX];
2098         RNA_string_get(op->ptr, "filepath", filepath);
2099         if (!BLO_has_bfile_extension(filepath)) {
2100                 /* some users would prefer BLI_replace_extension(),
2101                  * we keep getting nitpicking bug reports about this - campbell */
2102                 BLI_ensure_extension(filepath, FILE_MAX, ".blend");
2103                 RNA_string_set(op->ptr, "filepath", filepath);
2104                 return true;
2105         }
2106         return false;
2107 }
2108
2109 void WM_OT_save_as_mainfile(wmOperatorType *ot)
2110 {
2111         PropertyRNA *prop;
2112
2113         ot->name = "Save As Blender File";
2114         ot->idname = "WM_OT_save_as_mainfile";
2115         ot->description = "Save the current file in the desired location";
2116
2117         ot->invoke = wm_save_as_mainfile_invoke;
2118         ot->exec = wm_save_as_mainfile_exec;
2119         ot->check = blend_save_check;
2120         /* omit window poll so this can work in background mode */
2121
2122         WM_operator_properties_filesel(
2123                 ot, FILE_TYPE_FOLDER | FILE_TYPE_BLENDER, FILE_BLENDER, FILE_SAVE,
2124                 WM_FILESEL_FILEPATH, FILE_DEFAULTDISPLAY, FILE_SORT_ALPHA);
2125         RNA_def_boolean(ot->srna, "compress", false, "Compress", "Write compressed .blend file");
2126         RNA_def_boolean(ot->srna, "relative_remap", true, "Remap Relative",
2127                         "Remap relative paths when saving in a different directory");
2128         prop = RNA_def_boolean(ot->srna, "copy", false, "Save Copy",
2129                         "Save a copy of the actual working state but does not make saved file active");
2130         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
2131 #ifdef USE_BMESH_SAVE_AS_COMPAT
2132         RNA_def_boolean(ot->srna, "use_mesh_compat", false, "Legacy Mesh Format",
2133                         "Save using legacy mesh format (no ngons) - WARNING: only saves tris and quads, other ngons will "
2134                         "be lost (no implicit triangulation)");
2135 #endif
2136 }
2137
2138 static int wm_save_mainfile_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
2139 {
2140         int ret;
2141
2142         /* cancel if no active window */
2143         if (CTX_wm_window(C) == NULL)
2144                 return OPERATOR_CANCELLED;
2145
2146         save_set_compress(op);
2147         save_set_filepath(op);
2148
2149         /* if we're saving for the first time and prefer relative paths - any existing paths will be absolute,
2150          * enable the option to remap paths to avoid confusion [#37240] */
2151         if ((G.relbase_valid == false) && (U.flag & USER_RELPATHS)) {
2152                 PropertyRNA *prop = RNA_struct_find_property(op->ptr, "relative_remap");
2153                 if (!RNA_property_is_set(op->ptr, prop)) {
2154                         RNA_property_boolean_set(op->ptr, prop, true);
2155                 }
2156         }
2157
2158         if (G.save_over) {
2159                 char path[FILE_MAX];
2160
2161                 RNA_string_get(op->ptr, "filepath", path);
2162                 if (RNA_boolean_get(op->ptr, "check_existing") && BLI_exists(path)) {
2163                         ret = WM_operator_confirm_message_ex(C, op, IFACE_("Save Over?"), ICON_QUESTION, path);
2164                 }
2165                 else {
2166                         ret = wm_save_as_mainfile_exec(C, op);
2167                         /* Without this there is no feedback the file was saved. */
2168                         BKE_reportf(op->reports, RPT_INFO, "Saved \"%s\"", BLI_path_basename(path));
2169                 }
2170         }
2171         else {
2172                 WM_event_add_fileselect(C, op);
2173                 ret = OPERATOR_RUNNING_MODAL;
2174         }
2175
2176         return ret;
2177 }
2178
2179 void WM_OT_save_mainfile(wmOperatorType *ot)
2180 {
2181         ot->name = "Save Blender File";
2182         ot->idname = "WM_OT_save_mainfile";
2183         ot->description = "Save the current Blender file";
2184
2185         ot->invoke = wm_save_mainfile_invoke;
2186         ot->exec = wm_save_as_mainfile_exec;
2187         ot->check = blend_save_check;
2188         /* omit window poll so this can work in background mode */
2189
2190         PropertyRNA *prop;
2191         WM_operator_properties_filesel(
2192                 ot, FILE_TYPE_FOLDER | FILE_TYPE_BLENDER, FILE_BLENDER, FILE_SAVE,
2193                 WM_FILESEL_FILEPATH, FILE_DEFAULTDISPLAY, FILE_SORT_ALPHA);
2194         RNA_def_boolean(ot->srna, "compress", false, "Compress", "Write compressed .blend file");
2195         RNA_def_boolean(ot->srna, "relative_remap", false, "Remap Relative",
2196                         "Remap relative paths when saving in a different directory");
2197
2198         prop = RNA_def_boolean(ot->srna, "exit", false, "Exit", "Exit Blender after saving");
2199         RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
2200 }
2201
2202 /** \} */