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