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