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