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