Cleanup: Nuke moar G.main usages...
[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();
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)
427 {
428         ReportList *reports = NULL;
429         Scene *sce;
430
431         for (sce = G.main->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         bool addons_loaded = false;
459         wmWindowManager *wm = CTX_wm_manager(C);
460
461         if (!G.background) {
462                 /* remove windows which failed to be added via WM_check */
463                 wm_window_ghostwindows_remove_invalid(C, wm);
464         }
465
466         CTX_wm_window_set(C, wm->windows.first);
467
468         ED_editors_init(C);
469         DAG_on_visible_update(CTX_data_main(C), true);
470
471 #ifdef WITH_PYTHON
472         if (is_startup_file) {
473                 /* possible python hasn't been initialized */
474                 if (CTX_py_init_get(C)) {
475                         if (use_userdef) {
476                                 /* Only run when we have a template path found. */
477                                 if (BKE_appdir_app_template_any()) {
478                                         BPY_execute_string(C, "__import__('bl_app_template_utils').reset()");
479                                 }
480                                 /* sync addons, these may have changed from the defaults */
481                                 BPY_execute_string(C, "__import__('addon_utils').reset_all()");
482                         }
483                         BPY_python_reset(C);
484                         addons_loaded = true;
485                 }
486         }
487         else {
488                 /* run any texts that were loaded in and flagged as modules */
489                 BPY_python_reset(C);
490                 addons_loaded = true;
491         }
492 #else
493         UNUSED_VARS(use_userdef);
494 #endif  /* WITH_PYTHON */
495
496         WM_operatortype_last_properties_clear_all();
497
498         /* important to do before NULL'ing the context */
499         BLI_callback_exec(CTX_data_main(C), NULL, BLI_CB_EVT_VERSION_UPDATE);
500         BLI_callback_exec(CTX_data_main(C), NULL, BLI_CB_EVT_LOAD_POST);
501
502         /* Would otherwise be handled by event loop.
503          *
504          * Disabled for startup file, since it causes problems when PyDrivers are used in the startup file.
505          * While its possible state of startup file may be wrong,
506          * in this case users nearly always load a file to replace the startup file. */
507         if (G.background && (is_startup_file == false)) {
508                 Main *bmain = CTX_data_main(C);
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);
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, CTX_data_main(C));
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(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                         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                         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 = CTX_data_main(C)->blen_thumb;
1150         if ((U.flag & USER_SAVE_PREVIEWS) && BLI_thread_is_main()) {
1151                 ibuf_thumb = blend_file_thumb(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         wmWindowManager *wm = CTX_wm_manager(C);
1395         wmWindow *win = CTX_wm_window(C);
1396         char filepath[FILE_MAX];
1397         int fileflags;
1398
1399         const char *app_template = U.app_template[0] ? U.app_template : NULL;
1400         const char * const cfgdir = BKE_appdir_folder_id_create(BLENDER_USER_CONFIG, app_template);
1401         if (cfgdir == NULL) {
1402                 BKE_report(op->reports, RPT_ERROR, "Unable to create user config path");
1403                 return OPERATOR_CANCELLED;
1404         }
1405
1406         BLI_callback_exec(G.main, NULL, BLI_CB_EVT_SAVE_PRE);
1407
1408         /* check current window and close it if temp */
1409         if (win && win->screen->temp)
1410                 wm_window_close(C, wm, win);
1411
1412         /* update keymaps in user preferences */
1413         WM_keyconfig_update(wm);
1414
1415         BLI_path_join(filepath, sizeof(filepath), cfgdir, BLENDER_STARTUP_FILE, NULL);
1416
1417         printf("trying to save homefile at %s ", filepath);
1418
1419         ED_editors_flush_edits(C, false);
1420
1421         /*  force save as regular blend file */
1422         fileflags = G.fileflags & ~(G_FILE_COMPRESS | G_FILE_AUTOPLAY | G_FILE_HISTORY);
1423
1424         if (BLO_write_file(CTX_data_main(C), filepath, fileflags | G_FILE_USERPREFS, op->reports, NULL) == 0) {
1425                 printf("fail\n");
1426                 return OPERATOR_CANCELLED;
1427         }
1428
1429         printf("ok\n");
1430
1431         G.save_over = 0;
1432
1433         BLI_callback_exec(G.main, NULL, BLI_CB_EVT_SAVE_POST);
1434
1435         return OPERATOR_FINISHED;
1436 }
1437
1438 void WM_OT_save_homefile(wmOperatorType *ot)
1439 {
1440         ot->name = "Save Startup File";
1441         ot->idname = "WM_OT_save_homefile";
1442         ot->description = "Make the current file the default .blend file, includes preferences";
1443
1444         ot->invoke = WM_operator_confirm;
1445         ot->exec = wm_homefile_write_exec;
1446 }
1447
1448 static int wm_userpref_autoexec_add_exec(bContext *UNUSED(C), wmOperator *UNUSED(op))
1449 {
1450         bPathCompare *path_cmp = MEM_callocN(sizeof(bPathCompare), "bPathCompare");
1451         BLI_addtail(&U.autoexec_paths, path_cmp);
1452         return OPERATOR_FINISHED;
1453 }
1454
1455 void WM_OT_userpref_autoexec_path_add(wmOperatorType *ot)
1456 {
1457         ot->name = "Add Autoexec Path";
1458         ot->idname = "WM_OT_userpref_autoexec_path_add";
1459         ot->description = "Add path to exclude from autoexecution";
1460
1461         ot->exec = wm_userpref_autoexec_add_exec;
1462
1463         ot->flag = OPTYPE_INTERNAL;
1464 }
1465
1466 static int wm_userpref_autoexec_remove_exec(bContext *UNUSED(C), wmOperator *op)
1467 {
1468         const int index = RNA_int_get(op->ptr, "index");
1469         bPathCompare *path_cmp = BLI_findlink(&U.autoexec_paths, index);
1470         if (path_cmp) {
1471                 BLI_freelinkN(&U.autoexec_paths, path_cmp);
1472         }
1473         return OPERATOR_FINISHED;
1474 }
1475
1476 void WM_OT_userpref_autoexec_path_remove(wmOperatorType *ot)
1477 {
1478         ot->name = "Remove Autoexec Path";
1479         ot->idname = "WM_OT_userpref_autoexec_path_remove";
1480         ot->description = "Remove path to exclude from autoexecution";
1481
1482         ot->exec = wm_userpref_autoexec_remove_exec;
1483
1484         ot->flag = OPTYPE_INTERNAL;
1485
1486         RNA_def_int(ot->srna, "index", 0, 0, INT_MAX, "Index", "", 0, 1000);
1487 }
1488
1489 /* Only save the prefs block. operator entry */
1490 static int wm_userpref_write_exec(bContext *C, wmOperator *op)
1491 {
1492         wmWindowManager *wm = CTX_wm_manager(C);
1493         char filepath[FILE_MAX];
1494         const char *cfgdir;
1495         bool ok = true;
1496
1497         /* update keymaps in user preferences */
1498         WM_keyconfig_update(wm);
1499
1500         if ((cfgdir = BKE_appdir_folder_id_create(BLENDER_USER_CONFIG, NULL))) {
1501                 bool ok_write;
1502                 BLI_path_join(filepath, sizeof(filepath), cfgdir, BLENDER_USERPREF_FILE, NULL);
1503                 printf("trying to save userpref at %s ", filepath);
1504
1505                 if (U.app_template[0]) {
1506                         ok_write = BKE_blendfile_userdef_write_app_template(filepath, op->reports);
1507                 }
1508                 else {
1509                         ok_write = BKE_blendfile_userdef_write(filepath, op->reports);
1510                 }
1511
1512                 if (ok_write) {
1513                         printf("ok\n");
1514                 }
1515                 else {
1516                         printf("fail\n");
1517                         ok = false;
1518                 }
1519         }
1520         else {
1521                 BKE_report(op->reports, RPT_ERROR, "Unable to create userpref path");
1522         }
1523
1524         if (U.app_template[0]) {
1525                 if ((cfgdir = BKE_appdir_folder_id_create(BLENDER_USER_CONFIG, U.app_template))) {
1526                         /* Also save app-template prefs */
1527                         BLI_path_join(filepath, sizeof(filepath), cfgdir, BLENDER_USERPREF_FILE, NULL);
1528                         printf("trying to save app-template userpref at %s ", filepath);
1529                         if (BKE_blendfile_userdef_write(filepath, op->reports) != 0) {
1530                                 printf("ok\n");
1531                         }
1532                         else {
1533                                 printf("fail\n");
1534                                 ok = false;
1535                         }
1536                 }
1537                 else {
1538                         BKE_report(op->reports, RPT_ERROR, "Unable to create app-template userpref path");
1539                         ok = false;
1540                 }
1541         }
1542
1543         return ok ? OPERATOR_FINISHED : OPERATOR_CANCELLED;
1544 }
1545
1546 void WM_OT_save_userpref(wmOperatorType *ot)
1547 {
1548         ot->name = "Save User Settings";
1549         ot->idname = "WM_OT_save_userpref";
1550         ot->description = "Save user preferences separately, overrides startup file preferences";
1551
1552         ot->invoke = WM_operator_confirm;
1553         ot->exec = wm_userpref_write_exec;
1554 }
1555
1556 static int wm_history_file_read_exec(bContext *UNUSED(C), wmOperator *UNUSED(op))
1557 {
1558         ED_file_read_bookmarks();
1559         wm_history_file_read();
1560         return OPERATOR_FINISHED;
1561 }
1562
1563 void WM_OT_read_history(wmOperatorType *ot)
1564 {
1565         ot->name = "Reload History File";
1566         ot->idname = "WM_OT_read_history";
1567         ot->description = "Reloads history and bookmarks";
1568
1569         ot->invoke = WM_operator_confirm;
1570         ot->exec = wm_history_file_read_exec;
1571
1572         /* this operator is only used for loading settings from a previous blender install */
1573         ot->flag = OPTYPE_INTERNAL;
1574 }
1575
1576 static int wm_homefile_read_exec(bContext *C, wmOperator *op)
1577 {
1578         const bool use_factory_settings = (STREQ(op->type->idname, "WM_OT_read_factory_settings"));
1579         bool use_userdef = false;
1580         char filepath_buf[FILE_MAX];
1581         const char *filepath = NULL;
1582
1583         if (!use_factory_settings) {
1584                 PropertyRNA *prop = RNA_struct_find_property(op->ptr, "filepath");
1585
1586                 /* This can be used when loading of a start-up file should only change
1587                  * the scene content but keep the blender UI as it is. */
1588                 wm_open_init_load_ui(op, true);
1589                 SET_FLAG_FROM_TEST(G.fileflags, !RNA_boolean_get(op->ptr, "load_ui"), G_FILE_NO_UI);
1590
1591                 if (RNA_property_is_set(op->ptr, prop)) {
1592                         RNA_property_string_get(op->ptr, prop, filepath_buf);
1593                         filepath = filepath_buf;
1594                         if (BLI_access(filepath, R_OK)) {
1595                                 BKE_reportf(op->reports, RPT_ERROR, "Can't read alternative start-up file: '%s'", filepath);
1596                                 return OPERATOR_CANCELLED;
1597                         }
1598                 }
1599         }
1600         else {
1601                 /* always load UI for factory settings (prefs will re-init) */
1602                 G.fileflags &= ~G_FILE_NO_UI;
1603                 /* Always load preferences with factory settings. */
1604                 use_userdef = true;
1605         }
1606
1607         char app_template_buf[sizeof(U.app_template)];
1608         const char *app_template;
1609         PropertyRNA *prop_app_template = RNA_struct_find_property(op->ptr, "app_template");
1610         const bool use_splash = !use_factory_settings && RNA_boolean_get(op->ptr, "use_splash");
1611         const bool use_empty_data = RNA_boolean_get(op->ptr, "use_empty");
1612
1613         if (prop_app_template && RNA_property_is_set(op->ptr, prop_app_template)) {
1614                 RNA_property_string_get(op->ptr, prop_app_template, app_template_buf);
1615                 app_template = app_template_buf;
1616
1617                 /* Always load preferences when switching templates. */
1618                 use_userdef = true;
1619         }
1620         else {
1621                 app_template = NULL;
1622         }
1623
1624         if (wm_homefile_read(C, op->reports, use_factory_settings, use_empty_data, use_userdef, filepath, app_template)) {
1625                 if (use_splash) {
1626                         WM_init_splash(C);
1627                 }
1628                 return OPERATOR_FINISHED;
1629         }
1630         else {
1631                 return OPERATOR_CANCELLED;
1632         }
1633 }
1634
1635 void WM_OT_read_homefile(wmOperatorType *ot)
1636 {
1637         PropertyRNA *prop;
1638         ot->name = "Reload Start-Up File";
1639         ot->idname = "WM_OT_read_homefile";
1640         ot->description = "Open the default file (doesn't save the current file)";
1641
1642         ot->invoke = WM_operator_confirm;
1643         ot->exec = wm_homefile_read_exec;
1644
1645         prop = RNA_def_string_file_path(ot->srna, "filepath", NULL,
1646                                         FILE_MAX, "File Path",
1647                                         "Path to an alternative start-up file");
1648         RNA_def_property_flag(prop, PROP_HIDDEN);
1649
1650         /* So scripts can use an alternative start-up file without the UI */
1651         prop = RNA_def_boolean(ot->srna, "load_ui", true, "Load UI",
1652                                "Load user interface setup from the .blend file");
1653         RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
1654
1655         prop = RNA_def_boolean(ot->srna, "use_empty", false, "Empty", "");
1656         RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
1657
1658         /* So the splash can be kept open after loading a file (for templates). */
1659         prop = RNA_def_boolean(ot->srna, "use_splash", false, "Splash", "");
1660         RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
1661
1662         prop = RNA_def_string(ot->srna, "app_template", "Template", sizeof(U.app_template), "", "");
1663         RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
1664
1665         /* omit poll to run in background mode */
1666 }
1667
1668 void WM_OT_read_factory_settings(wmOperatorType *ot)
1669 {
1670         PropertyRNA *prop;
1671
1672         ot->name = "Load Factory Settings";
1673         ot->idname = "WM_OT_read_factory_settings";
1674         ot->description = "Load default file and user preferences";
1675
1676         ot->invoke = WM_operator_confirm;
1677         ot->exec = wm_homefile_read_exec;
1678
1679         prop = RNA_def_string(ot->srna, "app_template", "Template", sizeof(U.app_template), "", "");
1680         RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
1681
1682         prop = RNA_def_boolean(ot->srna, "use_empty", false, "Empty", "");
1683         RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
1684
1685         /* omit poll to run in background mode */
1686 }
1687
1688 /** \} */
1689
1690 /** \name Open main .blend file.
1691  *
1692  * \{ */
1693
1694 /**
1695  * Wrap #WM_file_read, shared by file reading operators.
1696  */
1697 static bool wm_file_read_opwrap(bContext *C, const char *filepath, ReportList *reports,
1698                                 const bool autoexec_init)
1699 {
1700         bool success;
1701
1702         /* XXX wm in context is not set correctly after WM_file_read -> crash */
1703         /* do it before for now, but is this correct with multiple windows? */
1704         WM_event_add_notifier(C, NC_WINDOW, NULL);
1705
1706         if (autoexec_init) {
1707                 WM_file_autoexec_init(filepath);
1708         }
1709
1710         success = WM_file_read(C, filepath, reports);
1711
1712         return success;
1713 }
1714
1715 /* currently fits in a pointer */
1716 struct FileRuntime {
1717         bool is_untrusted;
1718 };
1719
1720 static int wm_open_mainfile_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1721 {
1722         Main *bmain = CTX_data_main(C);
1723         const char *openname = BKE_main_blendfile_path(bmain);
1724
1725         if (CTX_wm_window(C) == NULL) {
1726                 /* in rare cases this could happen, when trying to invoke in background
1727                  * mode on load for example. Don't use poll for this because exec()
1728                  * can still run without a window */
1729                 BKE_report(op->reports, RPT_ERROR, "Context window not set");
1730                 return OPERATOR_CANCELLED;
1731         }
1732
1733         /* if possible, get the name of the most recently used .blend file */
1734         if (G.recent_files.first) {
1735                 struct RecentFile *recent = G.recent_files.first;
1736                 openname = recent->filepath;
1737         }
1738
1739         RNA_string_set(op->ptr, "filepath", openname);
1740         wm_open_init_load_ui(op, true);
1741         wm_open_init_use_scripts(op, true);
1742         op->customdata = NULL;
1743
1744         WM_event_add_fileselect(C, op);
1745
1746         return OPERATOR_RUNNING_MODAL;
1747 }
1748
1749 static int wm_open_mainfile_exec(bContext *C, wmOperator *op)
1750 {
1751         char filepath[FILE_MAX];
1752         bool success;
1753
1754         RNA_string_get(op->ptr, "filepath", filepath);
1755
1756         /* re-use last loaded setting so we can reload a file without changing */
1757         wm_open_init_load_ui(op, false);
1758         wm_open_init_use_scripts(op, false);
1759
1760         if (RNA_boolean_get(op->ptr, "load_ui"))
1761                 G.fileflags &= ~G_FILE_NO_UI;
1762         else
1763                 G.fileflags |= G_FILE_NO_UI;
1764
1765         if (RNA_boolean_get(op->ptr, "use_scripts"))
1766                 G.f |= G_SCRIPT_AUTOEXEC;
1767         else
1768                 G.f &= ~G_SCRIPT_AUTOEXEC;
1769
1770         success = wm_file_read_opwrap(C, filepath, op->reports, !(G.f & G_SCRIPT_AUTOEXEC));
1771
1772         /* for file open also popup for warnings, not only errors */
1773         BKE_report_print_level_set(op->reports, RPT_WARNING);
1774
1775         if (success) {
1776                 return OPERATOR_FINISHED;
1777         }
1778         else {
1779                 return OPERATOR_CANCELLED;
1780         }
1781 }
1782
1783 static bool wm_open_mainfile_check(bContext *UNUSED(C), wmOperator *op)
1784 {
1785         struct FileRuntime *file_info = (struct FileRuntime *)&op->customdata;
1786         PropertyRNA *prop = RNA_struct_find_property(op->ptr, "use_scripts");
1787         bool is_untrusted = false;
1788         char path[FILE_MAX];
1789         char *lslash;
1790
1791         RNA_string_get(op->ptr, "filepath", path);
1792
1793         /* get the dir */
1794         lslash = (char *)BLI_last_slash(path);
1795         if (lslash) *(lslash + 1) = '\0';
1796
1797         if ((U.flag & USER_SCRIPT_AUTOEXEC_DISABLE) == 0) {
1798                 if (BKE_autoexec_match(path) == true) {
1799                         RNA_property_boolean_set(op->ptr, prop, false);
1800                         is_untrusted = true;
1801                 }
1802         }
1803
1804         if (file_info) {
1805                 file_info->is_untrusted = is_untrusted;
1806         }
1807
1808         return is_untrusted;
1809 }
1810
1811 static void wm_open_mainfile_ui(bContext *UNUSED(C), wmOperator *op)
1812 {
1813         struct FileRuntime *file_info = (struct FileRuntime *)&op->customdata;
1814         uiLayout *layout = op->layout;
1815         uiLayout *col = op->layout;
1816         const char *autoexec_text;
1817
1818         uiItemR(layout, op->ptr, "load_ui", 0, NULL, ICON_NONE);
1819
1820         col = uiLayoutColumn(layout, false);
1821         if (file_info->is_untrusted) {
1822                 autoexec_text = IFACE_("Trusted Source [Untrusted Path]");
1823                 uiLayoutSetActive(col, false);
1824                 uiLayoutSetEnabled(col, false);
1825         }
1826         else {
1827                 autoexec_text = IFACE_("Trusted Source");
1828         }
1829
1830         uiItemR(col, op->ptr, "use_scripts", 0, autoexec_text, ICON_NONE);
1831 }
1832
1833 void WM_OT_open_mainfile(wmOperatorType *ot)
1834 {
1835         ot->name = "Open Blender File";
1836         ot->idname = "WM_OT_open_mainfile";
1837         ot->description = "Open a Blender file";
1838
1839         ot->invoke = wm_open_mainfile_invoke;
1840         ot->exec = wm_open_mainfile_exec;
1841         ot->check = wm_open_mainfile_check;
1842         ot->ui = wm_open_mainfile_ui;
1843         /* omit window poll so this can work in background mode */
1844
1845         WM_operator_properties_filesel(
1846                 ot, FILE_TYPE_FOLDER | FILE_TYPE_BLENDER, FILE_BLENDER, FILE_OPENFILE,
1847                 WM_FILESEL_FILEPATH, FILE_DEFAULTDISPLAY, FILE_SORT_ALPHA);
1848
1849         RNA_def_boolean(ot->srna, "load_ui", true, "Load UI", "Load user interface setup in the .blend file");
1850         RNA_def_boolean(ot->srna, "use_scripts", true, "Trusted Source",
1851                         "Allow .blend file to execute scripts automatically, default available from system preferences");
1852 }
1853
1854 /** \} */
1855
1856 /** \name Reload (revert) main .blend file.
1857  *
1858  * \{ */
1859
1860 static int wm_revert_mainfile_exec(bContext *C, wmOperator *op)
1861 {
1862         Main *bmain = CTX_data_main(C);
1863         bool success;
1864         char filepath[FILE_MAX];
1865
1866         wm_open_init_use_scripts(op, false);
1867
1868         if (RNA_boolean_get(op->ptr, "use_scripts"))
1869                 G.f |= G_SCRIPT_AUTOEXEC;
1870         else
1871                 G.f &= ~G_SCRIPT_AUTOEXEC;
1872
1873         BLI_strncpy(filepath, BKE_main_blendfile_path(bmain), sizeof(filepath));
1874         success = wm_file_read_opwrap(C, filepath, op->reports, !(G.f & G_SCRIPT_AUTOEXEC));
1875
1876         if (success) {
1877                 return OPERATOR_FINISHED;
1878         }
1879         else {
1880                 return OPERATOR_CANCELLED;
1881         }
1882 }
1883
1884 static int wm_revert_mainfile_poll(bContext *UNUSED(C))
1885 {
1886         return G.relbase_valid;
1887 }
1888
1889 void WM_OT_revert_mainfile(wmOperatorType *ot)
1890 {
1891         ot->name = "Revert";
1892         ot->idname = "WM_OT_revert_mainfile";
1893         ot->description = "Reload the saved file";
1894         ot->invoke = WM_operator_confirm;
1895
1896         RNA_def_boolean(ot->srna, "use_scripts", true, "Trusted Source",
1897                         "Allow .blend file to execute scripts automatically, default available from system preferences");
1898
1899         ot->exec = wm_revert_mainfile_exec;
1900         ot->poll = wm_revert_mainfile_poll;
1901 }
1902
1903 /** \} */
1904
1905 /** \name Recover last session & auto-save.
1906  *
1907  * \{ */
1908
1909 void WM_recover_last_session(bContext *C, ReportList *reports)
1910 {
1911         Main *bmain = CTX_data_main(C);
1912         char filepath[FILE_MAX];
1913
1914         BLI_make_file_string("/", filepath, BKE_tempdir_base(), BLENDER_QUIT_FILE);
1915         /* if reports==NULL, it's called directly without operator, we add a quick check here */
1916         if (reports || BLI_exists(filepath)) {
1917                 G.fileflags |= G_FILE_RECOVER;
1918
1919                 wm_file_read_opwrap(C, filepath, reports, true);
1920
1921                 G.fileflags &= ~G_FILE_RECOVER;
1922
1923                 /* XXX bad global... fixme */
1924                 if (BKE_main_blendfile_path(bmain)[0] != '\0') {
1925                         G.file_loaded = 1;      /* prevents splash to show */
1926                 }
1927                 else {
1928                         G.relbase_valid = 0;
1929                         G.save_over = 0;    /* start with save preference untitled.blend */
1930                 }
1931
1932         }
1933 }
1934
1935 static int wm_recover_last_session_exec(bContext *C, wmOperator *op)
1936 {
1937         WM_recover_last_session(C, op->reports);
1938         return OPERATOR_FINISHED;
1939 }
1940
1941 void WM_OT_recover_last_session(wmOperatorType *ot)
1942 {
1943         ot->name = "Recover Last Session";
1944         ot->idname = "WM_OT_recover_last_session";
1945         ot->description = "Open the last closed file (\"" BLENDER_QUIT_FILE "\")";
1946         ot->invoke = WM_operator_confirm;
1947
1948         ot->exec = wm_recover_last_session_exec;
1949 }
1950
1951 static int wm_recover_auto_save_exec(bContext *C, wmOperator *op)
1952 {
1953         char filepath[FILE_MAX];
1954         bool success;
1955
1956         RNA_string_get(op->ptr, "filepath", filepath);
1957
1958         G.fileflags |= G_FILE_RECOVER;
1959
1960         success = wm_file_read_opwrap(C, filepath, op->reports, true);
1961
1962         G.fileflags &= ~G_FILE_RECOVER;
1963
1964         if (success) {
1965                 return OPERATOR_FINISHED;
1966         }
1967         else {
1968                 return OPERATOR_CANCELLED;
1969         }
1970 }
1971
1972 static int wm_recover_auto_save_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1973 {
1974         char filename[FILE_MAX];
1975
1976         wm_autosave_location(filename);
1977         RNA_string_set(op->ptr, "filepath", filename);
1978         WM_event_add_fileselect(C, op);
1979
1980         return OPERATOR_RUNNING_MODAL;
1981 }
1982
1983 void WM_OT_recover_auto_save(wmOperatorType *ot)
1984 {
1985         ot->name = "Recover Auto Save";
1986         ot->idname = "WM_OT_recover_auto_save";
1987         ot->description = "Open an automatically saved file to recover it";
1988
1989         ot->exec = wm_recover_auto_save_exec;
1990         ot->invoke = wm_recover_auto_save_invoke;
1991
1992         WM_operator_properties_filesel(
1993                 ot, FILE_TYPE_BLENDER, FILE_BLENDER, FILE_OPENFILE,
1994                 WM_FILESEL_FILEPATH, FILE_LONGDISPLAY, FILE_SORT_TIME);
1995 }
1996
1997 /** \} */
1998
1999 /** \name Save main .blend file.
2000  *
2001  * \{ */
2002
2003 static void wm_filepath_default(char *filepath)
2004 {
2005         if (G.save_over == false) {
2006                 BLI_ensure_filename(filepath, FILE_MAX, "untitled.blend");
2007         }
2008 }
2009
2010 static void save_set_compress(wmOperator *op)
2011 {
2012         PropertyRNA *prop;
2013
2014         prop = RNA_struct_find_property(op->ptr, "compress");
2015         if (!RNA_property_is_set(op->ptr, prop)) {
2016                 if (G.save_over) {  /* keep flag for existing file */
2017                         RNA_property_boolean_set(op->ptr, prop, (G.fileflags & G_FILE_COMPRESS) != 0);
2018                 }
2019                 else {  /* use userdef for new file */
2020                         RNA_property_boolean_set(op->ptr, prop, (U.flag & USER_FILECOMPRESS) != 0);
2021                 }
2022         }
2023 }
2024
2025 static void save_set_filepath(bContext *C, wmOperator *op)
2026 {
2027         Main *bmain = CTX_data_main(C);
2028         PropertyRNA *prop;
2029         char name[FILE_MAX];
2030
2031         prop = RNA_struct_find_property(op->ptr, "filepath");
2032         if (!RNA_property_is_set(op->ptr, prop)) {
2033                 /* if not saved before, get the name of the most recently used .blend file */
2034                 if (BKE_main_blendfile_path(bmain)[0] == '\0' && G.recent_files.first) {
2035                         struct RecentFile *recent = G.recent_files.first;
2036                         BLI_strncpy(name, recent->filepath, FILE_MAX);
2037                 }
2038                 else {
2039                         BLI_strncpy(name, bmain->name, FILE_MAX);
2040                 }
2041
2042                 wm_filepath_default(name);
2043                 RNA_property_string_set(op->ptr, prop, name);
2044         }
2045 }
2046
2047 static int wm_save_as_mainfile_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
2048 {
2049
2050         save_set_compress(op);
2051         save_set_filepath(C, op);
2052
2053         WM_event_add_fileselect(C, op);
2054
2055         return OPERATOR_RUNNING_MODAL;
2056 }
2057
2058 /* function used for WM_OT_save_mainfile too */
2059 static int wm_save_as_mainfile_exec(bContext *C, wmOperator *op)
2060 {
2061         Main *bmain = CTX_data_main(C);
2062         char path[FILE_MAX];
2063         int fileflags;
2064
2065         save_set_compress(op);
2066
2067         if (RNA_struct_property_is_set(op->ptr, "filepath")) {
2068                 RNA_string_get(op->ptr, "filepath", path);
2069         }
2070         else {
2071                 BLI_strncpy(path, BKE_main_blendfile_path(bmain), FILE_MAX);
2072                 wm_filepath_default(path);
2073         }
2074
2075         fileflags = G.fileflags & ~G_FILE_USERPREFS;
2076
2077         /* set compression flag */
2078         SET_FLAG_FROM_TEST(
2079                 fileflags, RNA_boolean_get(op->ptr, "compress"),
2080                 G_FILE_COMPRESS);
2081         SET_FLAG_FROM_TEST(
2082                 fileflags, RNA_boolean_get(op->ptr, "relative_remap"),
2083                 G_FILE_RELATIVE_REMAP);
2084         SET_FLAG_FROM_TEST(
2085                 fileflags,
2086                 (RNA_struct_property_is_set(op->ptr, "copy") &&
2087                  RNA_boolean_get(op->ptr, "copy")),
2088                 G_FILE_SAVE_COPY);
2089
2090 #ifdef USE_BMESH_SAVE_AS_COMPAT
2091         SET_FLAG_FROM_TEST(
2092                 fileflags,
2093                 (RNA_struct_find_property(op->ptr, "use_mesh_compat") &&
2094                  RNA_boolean_get(op->ptr, "use_mesh_compat")),
2095                 G_FILE_MESH_COMPAT);
2096 #else
2097 #  error "don't remove by accident"
2098 #endif
2099
2100         if (wm_file_write(C, path, fileflags, op->reports) != 0)
2101                 return OPERATOR_CANCELLED;
2102
2103         WM_event_add_notifier(C, NC_WM | ND_FILESAVE, NULL);
2104
2105         if (RNA_boolean_get(op->ptr, "exit")) {
2106                 wm_exit_schedule_delayed(C);
2107         }
2108
2109         return OPERATOR_FINISHED;
2110 }
2111
2112 /* function used for WM_OT_save_mainfile too */
2113 static bool blend_save_check(bContext *UNUSED(C), wmOperator *op)
2114 {
2115         char filepath[FILE_MAX];
2116         RNA_string_get(op->ptr, "filepath", filepath);
2117         if (!BLO_has_bfile_extension(filepath)) {
2118                 /* some users would prefer BLI_replace_extension(),
2119                  * we keep getting nitpicking bug reports about this - campbell */
2120                 BLI_ensure_extension(filepath, FILE_MAX, ".blend");
2121                 RNA_string_set(op->ptr, "filepath", filepath);
2122                 return true;
2123         }
2124         return false;
2125 }
2126
2127 void WM_OT_save_as_mainfile(wmOperatorType *ot)
2128 {
2129         PropertyRNA *prop;
2130
2131         ot->name = "Save As Blender File";
2132         ot->idname = "WM_OT_save_as_mainfile";
2133         ot->description = "Save the current file in the desired location";
2134
2135         ot->invoke = wm_save_as_mainfile_invoke;
2136         ot->exec = wm_save_as_mainfile_exec;
2137         ot->check = blend_save_check;
2138         /* omit window poll so this can work in background mode */
2139
2140         WM_operator_properties_filesel(
2141                 ot, FILE_TYPE_FOLDER | FILE_TYPE_BLENDER, FILE_BLENDER, FILE_SAVE,
2142                 WM_FILESEL_FILEPATH, FILE_DEFAULTDISPLAY, FILE_SORT_ALPHA);
2143         RNA_def_boolean(ot->srna, "compress", false, "Compress", "Write compressed .blend file");
2144         RNA_def_boolean(ot->srna, "relative_remap", true, "Remap Relative",
2145                         "Remap relative paths when saving in a different directory");
2146         prop = RNA_def_boolean(ot->srna, "copy", false, "Save Copy",
2147                         "Save a copy of the actual working state but does not make saved file active");
2148         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
2149 #ifdef USE_BMESH_SAVE_AS_COMPAT
2150         RNA_def_boolean(ot->srna, "use_mesh_compat", false, "Legacy Mesh Format",
2151                         "Save using legacy mesh format (no ngons) - WARNING: only saves tris and quads, other ngons will "
2152                         "be lost (no implicit triangulation)");
2153 #endif
2154 }
2155
2156 static int wm_save_mainfile_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
2157 {
2158         int ret;
2159
2160         /* cancel if no active window */
2161         if (CTX_wm_window(C) == NULL)
2162                 return OPERATOR_CANCELLED;
2163
2164         save_set_compress(op);
2165         save_set_filepath(C, op);
2166
2167         /* if we're saving for the first time and prefer relative paths - any existing paths will be absolute,
2168          * enable the option to remap paths to avoid confusion [#37240] */
2169         if ((G.relbase_valid == false) && (U.flag & USER_RELPATHS)) {
2170                 PropertyRNA *prop = RNA_struct_find_property(op->ptr, "relative_remap");
2171                 if (!RNA_property_is_set(op->ptr, prop)) {
2172                         RNA_property_boolean_set(op->ptr, prop, true);
2173                 }
2174         }
2175
2176         if (G.save_over) {
2177                 char path[FILE_MAX];
2178
2179                 RNA_string_get(op->ptr, "filepath", path);
2180                 if (RNA_boolean_get(op->ptr, "check_existing") && BLI_exists(path)) {
2181                         ret = WM_operator_confirm_message_ex(C, op, IFACE_("Save Over?"), ICON_QUESTION, path);
2182                 }
2183                 else {
2184                         ret = wm_save_as_mainfile_exec(C, op);
2185                         /* Without this there is no feedback the file was saved. */
2186                         BKE_reportf(op->reports, RPT_INFO, "Saved \"%s\"", BLI_path_basename(path));
2187                 }
2188         }
2189         else {
2190                 WM_event_add_fileselect(C, op);
2191                 ret = OPERATOR_RUNNING_MODAL;
2192         }
2193
2194         return ret;
2195 }
2196
2197 void WM_OT_save_mainfile(wmOperatorType *ot)
2198 {
2199         ot->name = "Save Blender File";
2200         ot->idname = "WM_OT_save_mainfile";
2201         ot->description = "Save the current Blender file";
2202
2203         ot->invoke = wm_save_mainfile_invoke;
2204         ot->exec = wm_save_as_mainfile_exec;
2205         ot->check = blend_save_check;
2206         /* omit window poll so this can work in background mode */
2207
2208         PropertyRNA *prop;
2209         WM_operator_properties_filesel(
2210                 ot, FILE_TYPE_FOLDER | FILE_TYPE_BLENDER, FILE_BLENDER, FILE_SAVE,
2211                 WM_FILESEL_FILEPATH, FILE_DEFAULTDISPLAY, FILE_SORT_ALPHA);
2212         RNA_def_boolean(ot->srna, "compress", false, "Compress", "Write compressed .blend file");
2213         RNA_def_boolean(ot->srna, "relative_remap", false, "Remap Relative",
2214                         "Remap relative paths when saving in a different directory");
2215
2216         prop = RNA_def_boolean(ot->srna, "exit", false, "Exit", "Exit Blender after saving");
2217         RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
2218 }
2219
2220 /** \} */