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