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