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