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