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