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