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