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