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