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