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