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