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