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