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