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