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