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