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