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