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