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