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