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