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