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