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