Correction for recent commit clearing font cache
[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.
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 <process.h> /* getpid */
50 #  include "BLI_winstuff.h"
51 #else
52 #  include <unistd.h> /* getpid */
53 #endif
54
55 #include "MEM_guardedalloc.h"
56 #include "MEM_CacheLimiterC-Api.h"
57
58 #include "BLI_blenlib.h"
59 #include "BLI_linklist.h"
60 #include "BLI_utildefines.h"
61 #include "BLI_threads.h"
62 #include "BLI_callbacks.h"
63
64 #include "BLF_translation.h"
65
66 #include "DNA_anim_types.h"
67 #include "DNA_object_types.h"
68 #include "DNA_space_types.h"
69 #include "DNA_userdef_types.h"
70 #include "DNA_scene_types.h"
71 #include "DNA_screen_types.h"
72 #include "DNA_windowmanager_types.h"
73
74 #include "BKE_autoexec.h"
75 #include "BKE_blender.h"
76 #include "BKE_context.h"
77 #include "BKE_depsgraph.h"
78 #include "BKE_DerivedMesh.h"
79 #include "BKE_font.h"
80 #include "BKE_global.h"
81 #include "BKE_library.h"
82 #include "BKE_main.h"
83 #include "BKE_multires.h"
84 #include "BKE_packedFile.h"
85 #include "BKE_report.h"
86 #include "BKE_sound.h"
87 #include "BKE_screen.h"
88 #include "BKE_texture.h"
89
90
91 #include "BLO_readfile.h"
92 #include "BLO_writefile.h"
93
94 #include "RNA_access.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_object.h"
103 #include "ED_screen.h"
104 #include "ED_sculpt.h"
105 #include "ED_view3d.h"
106 #include "ED_util.h"
107
108 #include "RE_pipeline.h" /* only to report missing engine */
109
110 #include "GHOST_C-api.h"
111 #include "GHOST_Path-api.h"
112
113 #include "UI_interface.h"
114 #include "UI_view2d.h"
115
116 #include "GPU_draw.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 void write_history(void);
130
131 /* To be able to read files without windows closing, opening, moving
132  * we try to prepare for worst case:
133  * - active window gets active screen from file
134  * - restoring the screens from non-active windows
135  * Best case is all screens match, in that case they get assigned to proper window
136  */
137 static void wm_window_match_init(bContext *C, ListBase *wmlist)
138 {
139         wmWindowManager *wm;
140         wmWindow *win, *active_win;
141         
142         *wmlist = G.main->wm;
143         G.main->wm.first = G.main->wm.last = NULL;
144         
145         active_win = CTX_wm_window(C);
146
147         /* first wrap up running stuff */
148         /* code copied from wm_init_exit.c */
149         for (wm = wmlist->first; wm; wm = wm->id.next) {
150                 
151                 WM_jobs_kill_all(wm);
152                 
153                 for (win = wm->windows.first; win; win = win->next) {
154                 
155                         CTX_wm_window_set(C, win);  /* needed by operator close callbacks */
156                         WM_event_remove_handlers(C, &win->handlers);
157                         WM_event_remove_handlers(C, &win->modalhandlers);
158                         ED_screen_exit(C, win, win->screen);
159                 }
160         }
161         
162         /* reset active window */
163         CTX_wm_window_set(C, active_win);
164
165         ED_editors_exit(C);
166
167         /* just had return; here from r12991, this code could just get removed?*/
168 #if 0
169         if (wm == NULL) return;
170         if (G.fileflags & G_FILE_NO_UI) return;
171         
172         /* we take apart the used screens from non-active window */
173         for (win = wm->windows.first; win; win = win->next) {
174                 BLI_strncpy(win->screenname, win->screen->id.name, MAX_ID_NAME);
175                 if (win != wm->winactive) {
176                         BLI_remlink(&G.main->screen, win->screen);
177                         //BLI_addtail(screenbase, win->screen);
178                 }
179         }
180 #endif
181 }
182
183 /* match old WM with new, 4 cases:
184  * 1- no current wm, no read wm: make new default
185  * 2- no current wm, but read wm: that's OK, do nothing
186  * 3- current wm, but not in file: try match screen names
187  * 4- current wm, and wm in file: try match ghostwin
188  */
189
190 static void wm_window_match_do(bContext *C, ListBase *oldwmlist)
191 {
192         wmWindowManager *oldwm, *wm;
193         wmWindow *oldwin, *win;
194         
195         /* cases 1 and 2 */
196         if (oldwmlist->first == NULL) {
197                 if (G.main->wm.first) {
198                         /* nothing todo */
199                 }
200                 else {
201                         wm_add_default(C);
202                 }
203         }
204         else {
205                 /* cases 3 and 4 */
206                 
207                 /* we've read file without wm..., keep current one entirely alive */
208                 if (G.main->wm.first == NULL) {
209                         bScreen *screen = NULL;
210
211                         /* when loading without UI, no matching needed */
212                         if (!(G.fileflags & G_FILE_NO_UI) && (screen = CTX_wm_screen(C))) {
213
214                                 /* match oldwm to new dbase, only old files */
215                                 for (wm = oldwmlist->first; wm; wm = wm->id.next) {
216                                         
217                                         for (win = wm->windows.first; win; win = win->next) {
218                                                 /* all windows get active screen from file */
219                                                 if (screen->winid == 0)
220                                                         win->screen = screen;
221                                                 else 
222                                                         win->screen = ED_screen_duplicate(win, screen);
223                                                 
224                                                 BLI_strncpy(win->screenname, win->screen->id.name + 2, sizeof(win->screenname));
225                                                 win->screen->winid = win->winid;
226                                         }
227                                 }
228                         }
229                         
230                         G.main->wm = *oldwmlist;
231                         
232                         /* screens were read from file! */
233                         ED_screens_initialize(G.main->wm.first);
234                 }
235                 else {
236                         /* what if old was 3, and loaded 1? */
237                         /* this code could move to setup_appdata */
238                         oldwm = oldwmlist->first;
239                         wm = G.main->wm.first;
240
241                         /* preserve key configurations in new wm, to preserve their keymaps */
242                         wm->keyconfigs = oldwm->keyconfigs;
243                         wm->addonconf = oldwm->addonconf;
244                         wm->defaultconf = oldwm->defaultconf;
245                         wm->userconf = oldwm->userconf;
246
247                         oldwm->keyconfigs.first = oldwm->keyconfigs.last = NULL;
248                         oldwm->addonconf = NULL;
249                         oldwm->defaultconf = NULL;
250                         oldwm->userconf = NULL;
251
252                         /* ensure making new keymaps and set space types */
253                         wm->initialized = 0;
254                         wm->winactive = NULL;
255                         
256                         /* only first wm in list has ghostwins */
257                         for (win = wm->windows.first; win; win = win->next) {
258                                 for (oldwin = oldwm->windows.first; oldwin; oldwin = oldwin->next) {
259                                         
260                                         if (oldwin->winid == win->winid) {
261                                                 win->ghostwin = oldwin->ghostwin;
262                                                 win->active = oldwin->active;
263                                                 if (win->active)
264                                                         wm->winactive = win;
265
266                                                 if (!G.background) /* file loading in background mode still calls this */
267                                                         GHOST_SetWindowUserData(win->ghostwin, win);    /* pointer back */
268
269                                                 oldwin->ghostwin = NULL;
270                                                 
271                                                 win->eventstate = oldwin->eventstate;
272                                                 oldwin->eventstate = NULL;
273                                                 
274                                                 /* ensure proper screen rescaling */
275                                                 win->sizex = oldwin->sizex;
276                                                 win->sizey = oldwin->sizey;
277                                                 win->posx = oldwin->posx;
278                                                 win->posy = oldwin->posy;
279                                         }
280                                 }
281                         }
282                         wm_close_and_free_all(C, oldwmlist);
283                 }
284         }
285 }
286
287 /* in case UserDef was read, we re-initialize all, and do versioning */
288 static void wm_init_userdef(bContext *C, const bool from_memory)
289 {
290         /* versioning is here */
291         UI_init_userdef();
292         
293         MEM_CacheLimiter_set_maximum(((size_t)U.memcachelimit) * 1024 * 1024);
294         sound_init(CTX_data_main(C));
295
296         /* needed so loading a file from the command line respects user-pref [#26156] */
297         if (U.flag & USER_FILENOUI) G.fileflags |= G_FILE_NO_UI;
298         else G.fileflags &= ~G_FILE_NO_UI;
299
300         /* set the python auto-execute setting from user prefs */
301         /* enabled by default, unless explicitly enabled in the command line which overrides */
302         if ((G.f & G_SCRIPT_OVERRIDE_PREF) == 0) {
303                 if ((U.flag & USER_SCRIPT_AUTOEXEC_DISABLE) == 0) G.f |=  G_SCRIPT_AUTOEXEC;
304                 else G.f &= ~G_SCRIPT_AUTOEXEC;
305         }
306
307         /* avoid re-saving for every small change to our prefs, allow overrides */
308         if (from_memory) {
309                 UI_init_userdef_factory();
310         }
311
312         /* update tempdir from user preferences */
313         BLI_init_temporary_dir(U.tempdir);
314
315         BKE_userdef_state();
316 }
317
318
319
320 /* return codes */
321 #define BKE_READ_EXOTIC_FAIL_PATH       -3 /* file format is not supported */
322 #define BKE_READ_EXOTIC_FAIL_FORMAT     -2 /* file format is not supported */
323 #define BKE_READ_EXOTIC_FAIL_OPEN       -1 /* Can't open the file */
324 #define BKE_READ_EXOTIC_OK_BLEND         0 /* .blend file */
325 #define BKE_READ_EXOTIC_OK_OTHER         1 /* other supported formats */
326
327
328 /* intended to check for non-blender formats but for now it only reads blends */
329 static int wm_read_exotic(Scene *UNUSED(scene), const char *name)
330 {
331         int len;
332         gzFile gzfile;
333         char header[7];
334         int retval;
335
336         /* make sure we're not trying to read a directory.... */
337
338         len = strlen(name);
339         if (len > 0 && ELEM(name[len - 1], '/', '\\')) {
340                 retval = BKE_READ_EXOTIC_FAIL_PATH;
341         }
342         else {
343                 gzfile = BLI_gzopen(name, "rb");
344                 if (gzfile == NULL) {
345                         retval = BKE_READ_EXOTIC_FAIL_OPEN;
346                 }
347                 else {
348                         len = gzread(gzfile, header, sizeof(header));
349                         gzclose(gzfile);
350                         if (len == sizeof(header) && strncmp(header, "BLENDER", 7) == 0) {
351                                 retval = BKE_READ_EXOTIC_OK_BLEND;
352                         }
353                         else {
354 #if 0           /* historic stuff - no longer used */
355                                 WM_cursor_wait(TRUE);
356
357                                 if (is_foo_format(name)) {
358                                         read_foo(name);
359                                         retval = BKE_READ_EXOTIC_OK_OTHER;
360                                 }
361                                 else
362 #endif
363                                 {
364                                         retval = BKE_READ_EXOTIC_FAIL_FORMAT;
365                                 }
366 #if 0
367                                 WM_cursor_wait(FALSE);
368 #endif
369                         }
370                 }
371         }
372
373         return retval;
374 }
375
376 void WM_file_autoexec_init(const char *filepath)
377 {
378         if (G.f & G_SCRIPT_OVERRIDE_PREF) {
379                 return;
380         }
381
382         if (G.f & G_SCRIPT_AUTOEXEC) {
383                 char path[FILE_MAX];
384                 BLI_split_dir_part(filepath, path, sizeof(path));
385                 if (BKE_autoexec_match(path)) {
386                         G.f &= ~G_SCRIPT_AUTOEXEC;
387                 }
388         }
389 }
390
391 void WM_file_read(bContext *C, const char *filepath, ReportList *reports)
392 {
393         int retval;
394
395         /* so we can get the error message */
396         errno = 0;
397
398         WM_cursor_wait(1);
399
400         BLI_callback_exec(CTX_data_main(C), NULL, BLI_CB_EVT_LOAD_PRE);
401
402         UI_view2d_zoom_cache_reset();
403
404         /* first try to append data from exotic file formats... */
405         /* it throws error box when file doesn't exist and returns -1 */
406         /* note; it should set some error message somewhere... (ton) */
407         retval = wm_read_exotic(CTX_data_scene(C), filepath);
408         
409         /* we didn't succeed, now try to read Blender file */
410         if (retval == BKE_READ_EXOTIC_OK_BLEND) {
411                 int G_f = G.f;
412                 ListBase wmbase;
413
414                 /* assume automated tasks with background, don't write recent file list */
415                 const int do_history = (G.background == FALSE) && (CTX_wm_manager(C)->op_undo_depth == 0);
416
417                 /* put aside screens to match with persistent windows later */
418                 /* also exit screens and editors */
419                 wm_window_match_init(C, &wmbase); 
420                 
421                 /* confusing this global... */
422                 G.relbase_valid = 1;
423                 retval = BKE_read_file(C, filepath, reports);
424                 /* when loading startup.blend's, we can be left with a blank path */
425                 if (G.main->name[0]) {
426                         G.save_over = 1;
427                 }
428                 else {
429                         G.save_over = 0;
430                         G.relbase_valid = 0;
431                 }
432
433                 /* this flag is initialized by the operator but overwritten on read.
434                  * need to re-enable it here else drivers + registered scripts wont work. */
435                 if (G.f != G_f) {
436                         const int flags_keep = (G_SCRIPT_AUTOEXEC | G_SCRIPT_OVERRIDE_PREF);
437                         G.f = (G.f & ~flags_keep) | (G_f & flags_keep);
438                 }
439
440                 /* match the read WM with current WM */
441                 wm_window_match_do(C, &wmbase);
442                 WM_check(C); /* opens window(s), checks keymaps */
443
444                 if (retval == BKE_READ_FILE_OK_USERPREFS) {
445                         /* in case a userdef is read from regular .blend */
446                         wm_init_userdef(C, false);
447                 }
448                 
449                 if (retval != BKE_READ_FILE_FAIL) {
450                         if (do_history) {
451                                 write_history();
452                         }
453                 }
454
455
456                 WM_event_add_notifier(C, NC_WM | ND_FILEREAD, NULL);
457 //              refresh_interface_font();
458
459                 CTX_wm_window_set(C, CTX_wm_manager(C)->windows.first);
460
461                 ED_editors_init(C);
462                 DAG_on_visible_update(CTX_data_main(C), TRUE);
463
464 #ifdef WITH_PYTHON
465                 /* run any texts that were loaded in and flagged as modules */
466                 BPY_python_reset(C);
467 #endif
468
469                 /* important to do before NULL'ing the context */
470                 BLI_callback_exec(CTX_data_main(C), NULL, BLI_CB_EVT_LOAD_POST);
471
472                 if (!G.background) {
473                         /* in background mode this makes it hard to load
474                          * a blend file and do anything since the screen
475                          * won't be set to a valid value again */
476                         CTX_wm_window_set(C, NULL); /* exits queues */
477                 }
478
479 #if 0
480                 /* gives popups on windows but not linux, bug in report API
481                  * but disable for now to stop users getting annoyed  */
482                 /* TODO, make this show in header info window */
483                 {
484                         Scene *sce;
485                         for (sce = G.main->scene.first; sce; sce = sce->id.next) {
486                                 if (sce->r.engine[0] &&
487                                     BLI_findstring(&R_engines, sce->r.engine, offsetof(RenderEngineType, idname)) == NULL)
488                                 {
489                                         BKE_reportf(reports, RPT_ERROR, "Engine '%s' not available for scene '%s' "
490                                                     "(an addon may need to be installed or enabled)",
491                                                     sce->r.engine, sce->id.name + 2);
492                                 }
493                         }
494                 }
495 #endif
496
497                 BKE_reset_undo();
498                 BKE_write_undo(C, "original");  /* save current state */
499         }
500         else if (retval == BKE_READ_EXOTIC_OK_OTHER)
501                 BKE_write_undo(C, "Import file");
502         else if (retval == BKE_READ_EXOTIC_FAIL_OPEN) {
503                 BKE_reportf(reports, RPT_ERROR, "Cannot read file '%s': %s", filepath,
504                             errno ? strerror(errno) : TIP_("unable to open the file"));
505         }
506         else if (retval == BKE_READ_EXOTIC_FAIL_FORMAT) {
507                 BKE_reportf(reports, RPT_ERROR, "File format is not supported in file '%s'", filepath);
508         }
509         else if (retval == BKE_READ_EXOTIC_FAIL_PATH) {
510                 BKE_reportf(reports, RPT_ERROR, "File path '%s' invalid", filepath);
511         }
512         else {
513                 BKE_reportf(reports, RPT_ERROR, "Unknown error loading '%s'", filepath);
514                 BLI_assert(!"invalid 'retval'");
515         }
516
517         WM_cursor_wait(0);
518
519 }
520
521
522 /* called on startup,  (context entirely filled with NULLs) */
523 /* or called for 'New File' */
524 /* both startup.blend and userpref.blend are checked */
525 /* the optional paramater custom_file points to an alterntive startup page */
526 /* custom_file can be NULL */
527 int wm_homefile_read(bContext *C, ReportList *reports, bool from_memory, const char *custom_file)
528 {
529         ListBase wmbase;
530         char startstr[FILE_MAX];
531         char prefstr[FILE_MAX];
532         int success = 0;
533
534         /* Indicates whether user prefereneces were really load from memory.
535          *
536          * This is used for versioning code, and for this we can not rely on from_memory
537          * passed via argument. This is because there might be configuration folder
538          * exists but it might not have userpref.blend and in this case we fallback to
539          * reading home file from memory.
540          *
541          * And in this case versioning code is to be run.
542          */
543         bool read_userdef_from_memory = true;
544
545         /* options exclude eachother */
546         BLI_assert((from_memory && custom_file) == 0);
547
548         BLI_callback_exec(CTX_data_main(C), NULL, BLI_CB_EVT_LOAD_PRE);
549
550         UI_view2d_zoom_cache_reset();
551
552         G.relbase_valid = 0;
553         if (!from_memory) {
554                 const char * const cfgdir = BLI_get_folder(BLENDER_USER_CONFIG, NULL);
555                 if (custom_file) {
556                         BLI_strncpy(startstr, custom_file, FILE_MAX);
557
558                         if (cfgdir) {
559                                 BLI_make_file_string(G.main->name, prefstr, cfgdir, BLENDER_USERPREF_FILE);
560                         }
561                         else {
562                                 prefstr[0] = '\0';
563                         }
564                 }
565                 else if (cfgdir) {
566                         BLI_make_file_string(G.main->name, startstr, cfgdir, BLENDER_STARTUP_FILE);
567                         BLI_make_file_string(G.main->name, prefstr, cfgdir, BLENDER_USERPREF_FILE);
568                 }
569                 else {
570                         startstr[0] = '\0';
571                         prefstr[0] = '\0';
572                         from_memory = 1;
573                 }
574         }
575         
576         /* prevent loading no UI */
577         G.fileflags &= ~G_FILE_NO_UI;
578         
579         /* put aside screens to match with persistent windows later */
580         wm_window_match_init(C, &wmbase);
581         
582         if (!from_memory) {
583                 if (BLI_access(startstr, R_OK) == 0) {
584                         success = (BKE_read_file(C, startstr, NULL) != BKE_READ_FILE_FAIL);
585                 }
586                 if (U.themes.first == NULL) {
587                         if (G.debug & G_DEBUG)
588                                 printf("\nNote: No (valid) '%s' found, fall back to built-in default.\n\n", startstr);
589                         success = 0;
590                 }
591         }
592
593         if (success == 0 && custom_file && reports) {
594                 BKE_reportf(reports, RPT_ERROR, "Could not read '%s'", custom_file);
595                 /*We can not return from here because wm is already reset*/
596         }
597
598         if (success == 0) {
599                 success = BKE_read_file_from_memory(C, datatoc_startup_blend, datatoc_startup_blend_size, NULL, true);
600                 if (wmbase.first == NULL) wm_clear_default_size(C);
601                 BLI_init_temporary_dir(U.tempdir);
602
603 #ifdef WITH_PYTHON_SECURITY
604                 /* use alternative setting for security nuts
605                  * otherwise we'd need to patch the binary blob - startup.blend.c */
606                 U.flag |= USER_SCRIPT_AUTOEXEC_DISABLE;
607 #endif
608         }
609         
610         /* check new prefs only after startup.blend was finished */
611         if (!from_memory && BLI_exists(prefstr)) {
612                 int done = BKE_read_file_userdef(prefstr, NULL);
613                 if (done) {
614                         read_userdef_from_memory = false;
615                         printf("Read new prefs: %s\n", prefstr);
616                 }
617         }
618         
619         /* prevent buggy files that had G_FILE_RELATIVE_REMAP written out by mistake. Screws up autosaves otherwise
620          * can remove this eventually, only in a 2.53 and older, now its not written */
621         G.fileflags &= ~G_FILE_RELATIVE_REMAP;
622         
623         /* check userdef before open window, keymaps etc */
624         wm_init_userdef(C, read_userdef_from_memory);
625         
626         /* match the read WM with current WM */
627         wm_window_match_do(C, &wmbase); 
628         WM_check(C); /* opens window(s), checks keymaps */
629
630         G.main->name[0] = '\0';
631
632         /* When loading factory settings, the reset solid OpenGL lights need to be applied. */
633         if (!G.background) GPU_default_lights();
634         
635         /* XXX */
636         G.save_over = 0;    // start with save preference untitled.blend
637         G.fileflags &= ~G_FILE_AUTOPLAY;    /*  disable autoplay in startup.blend... */
638
639 //      refresh_interface_font();
640         
641 //      undo_editmode_clear();
642         BKE_reset_undo();
643         BKE_write_undo(C, "original");  /* save current state */
644
645         ED_editors_init(C);
646         DAG_on_visible_update(CTX_data_main(C), TRUE);
647
648 #ifdef WITH_PYTHON
649         if (CTX_py_init_get(C)) {
650                 /* sync addons, these may have changed from the defaults */
651                 BPY_string_exec(C, "__import__('addon_utils').reset_all()");
652
653                 BPY_python_reset(C);
654         }
655 #endif
656
657         /* important to do before NULL'ing the context */
658         BLI_callback_exec(CTX_data_main(C), NULL, BLI_CB_EVT_LOAD_POST);
659
660         WM_event_add_notifier(C, NC_WM | ND_FILEREAD, NULL);
661
662         /* in background mode the scene will stay NULL */
663         if (!G.background) {
664                 CTX_wm_window_set(C, NULL); /* exits queues */
665         }
666
667         return TRUE;
668 }
669
670 int wm_history_read_exec(bContext *UNUSED(C), wmOperator *UNUSED(op))
671 {
672         ED_file_read_bookmarks();
673         wm_read_history();
674         return OPERATOR_FINISHED;
675 }
676
677 int wm_homefile_read_exec(bContext *C, wmOperator *op)
678 {
679         const bool from_memory = (STREQ(op->type->idname, "WM_OT_read_factory_settings"));
680         char filepath_buf[FILE_MAX];
681         const char *filepath = NULL;
682
683         if (!from_memory) {
684                 PropertyRNA *prop = RNA_struct_find_property(op->ptr, "filepath");
685                 if (RNA_property_is_set(op->ptr, prop)) {
686                         RNA_property_string_get(op->ptr, prop, filepath_buf);
687                         filepath = filepath_buf;
688                         if (BLI_access(filepath, R_OK)) {
689                                 BKE_reportf(op->reports, RPT_ERROR, "Can't read alternative start-up file: '%s'", filepath);
690                                 return OPERATOR_CANCELLED;
691                         }
692                 }
693         }
694
695         return wm_homefile_read(C, op->reports, from_memory, filepath) ? OPERATOR_FINISHED : OPERATOR_CANCELLED;
696 }
697
698 void wm_read_history(void)
699 {
700         char name[FILE_MAX];
701         LinkNode *l, *lines;
702         struct RecentFile *recent;
703         char *line;
704         int num;
705         const char * const cfgdir = BLI_get_folder(BLENDER_USER_CONFIG, NULL);
706
707         if (!cfgdir) return;
708
709         BLI_make_file_string("/", name, cfgdir, BLENDER_HISTORY_FILE);
710
711         lines = BLI_file_read_as_lines(name);
712
713         G.recent_files.first = G.recent_files.last = NULL;
714
715         /* read list of recent opened files from recent-files.txt to memory */
716         for (l = lines, num = 0; l && (num < U.recent_files); l = l->next) {
717                 line = l->link;
718                 if (line[0] && BLI_exists(line)) {
719                         recent = (RecentFile *)MEM_mallocN(sizeof(RecentFile), "RecentFile");
720                         BLI_addtail(&(G.recent_files), recent);
721                         recent->filepath = BLI_strdup(line);
722                         num++;
723                 }
724         }
725         
726         BLI_file_free_lines(lines);
727 }
728
729 static void write_history(void)
730 {
731         struct RecentFile *recent, *next_recent;
732         char name[FILE_MAX];
733         const char *user_config_dir;
734         FILE *fp;
735         int i;
736
737         /* no write history for recovered startup files */
738         if (G.main->name[0] == 0)
739                 return;
740         
741         /* will be NULL in background mode */
742         user_config_dir = BLI_get_folder_create(BLENDER_USER_CONFIG, NULL);
743         if (!user_config_dir)
744                 return;
745
746         BLI_make_file_string("/", name, user_config_dir, BLENDER_HISTORY_FILE);
747
748         recent = G.recent_files.first;
749         /* refresh recent-files.txt of recent opened files, when current file was changed */
750         if (!(recent) || (BLI_path_cmp(recent->filepath, G.main->name) != 0)) {
751                 fp = BLI_fopen(name, "w");
752                 if (fp) {
753                         /* add current file to the beginning of list */
754                         recent = (RecentFile *)MEM_mallocN(sizeof(RecentFile), "RecentFile");
755                         recent->filepath = BLI_strdup(G.main->name);
756                         BLI_addhead(&(G.recent_files), recent);
757                         /* write current file to recent-files.txt */
758                         fprintf(fp, "%s\n", recent->filepath);
759                         recent = recent->next;
760                         i = 1;
761                         /* write rest of recent opened files to recent-files.txt */
762                         while ((i < U.recent_files) && (recent)) {
763                                 /* this prevents to have duplicities in list */
764                                 if (BLI_path_cmp(recent->filepath, G.main->name) != 0) {
765                                         fprintf(fp, "%s\n", recent->filepath);
766                                         recent = recent->next;
767                                 }
768                                 else {
769                                         next_recent = recent->next;
770                                         MEM_freeN(recent->filepath);
771                                         BLI_freelinkN(&(G.recent_files), recent);
772                                         recent = next_recent;
773                                 }
774                                 i++;
775                         }
776                         fclose(fp);
777                 }
778
779                 /* also update most recent files on System */
780                 GHOST_addToSystemRecentFiles(G.main->name);
781         }
782 }
783
784 /* screen can be NULL */
785 static ImBuf *blend_file_thumb(Scene *scene, bScreen *screen, int **thumb_pt)
786 {
787         /* will be scaled down, but gives some nice oversampling */
788         ImBuf *ibuf;
789         int *thumb;
790         char err_out[256] = "unknown";
791
792         /* screen if no camera found */
793         ScrArea *sa = NULL;
794         ARegion *ar = NULL;
795         View3D *v3d = NULL;
796
797         *thumb_pt = NULL;
798
799         /* scene can be NULL if running a script at startup and calling the save operator */
800         if (G.background || scene == NULL)
801                 return NULL;
802
803         if ((scene->camera == NULL) && (screen != NULL)) {
804                 sa = BKE_screen_find_big_area(screen, SPACE_VIEW3D, 0);
805                 ar = BKE_area_find_region_type(sa, RGN_TYPE_WINDOW);
806                 if (ar) {
807                         v3d = sa->spacedata.first;
808                 }
809         }
810
811         if (scene->camera == NULL && v3d == NULL) {
812                 return NULL;
813         }
814
815         /* gets scaled to BLEN_THUMB_SIZE */
816         if (scene->camera) {
817                 ibuf = ED_view3d_draw_offscreen_imbuf_simple(scene, scene->camera,
818                                                              BLEN_THUMB_SIZE * 2, BLEN_THUMB_SIZE * 2,
819                                                              IB_rect, OB_SOLID, FALSE, FALSE, R_ADDSKY, err_out);
820         }
821         else {
822                 ibuf = ED_view3d_draw_offscreen_imbuf(scene, v3d, ar, BLEN_THUMB_SIZE * 2, BLEN_THUMB_SIZE * 2,
823                                                       IB_rect, FALSE, R_ADDSKY, err_out);
824         }
825
826         if (ibuf) {
827                 float aspect = (scene->r.xsch * scene->r.xasp) / (scene->r.ysch * scene->r.yasp);
828
829                 /* dirty oversampling */
830                 IMB_scaleImBuf(ibuf, BLEN_THUMB_SIZE, BLEN_THUMB_SIZE);
831
832                 /* add pretty overlay */
833                 IMB_overlayblend_thumb(ibuf->rect, ibuf->x, ibuf->y, aspect);
834                 
835                 /* first write into thumb buffer */
836                 thumb = MEM_mallocN(((2 + (BLEN_THUMB_SIZE * BLEN_THUMB_SIZE))) * sizeof(int), "write_file thumb");
837
838                 thumb[0] = BLEN_THUMB_SIZE;
839                 thumb[1] = BLEN_THUMB_SIZE;
840
841                 memcpy(thumb + 2, ibuf->rect, BLEN_THUMB_SIZE * BLEN_THUMB_SIZE * sizeof(int));
842         }
843         else {
844                 /* '*thumb_pt' needs to stay NULL to prevent a bad thumbnail from being handled */
845                 fprintf(stderr, "blend_file_thumb failed to create thumbnail: %s\n", err_out);
846                 thumb = NULL;
847         }
848         
849         /* must be freed by caller */
850         *thumb_pt = thumb;
851         
852         return ibuf;
853 }
854
855 /* easy access from gdb */
856 bool write_crash_blend(void)
857 {
858         char path[FILE_MAX];
859         int fileflags = G.fileflags & ~(G_FILE_HISTORY); /* don't do file history on crash file */
860
861         BLI_strncpy(path, G.main->name, sizeof(path));
862         BLI_replace_extension(path, sizeof(path), "_crash.blend");
863         if (BLO_write_file(G.main, path, fileflags, NULL, NULL)) {
864                 printf("written: %s\n", path);
865                 return 1;
866         }
867         else {
868                 printf("failed: %s\n", path);
869                 return 0;
870         }
871 }
872
873 /**
874  * Flush any temp data from object editing to DNA before writing the blend file to disk.
875  */
876 static void write_flush_editdata(bContext *C)
877 {
878         Object *obedit;
879
880         obedit = CTX_data_edit_object(C);
881
882         if (obedit) {
883                 ED_object_editmode_load(obedit);
884         }
885
886         ED_sculpt_force_update(C);
887 }
888
889 /**
890  * \see #wm_homefile_write_exec wraps #BLO_write_file in a similar way.
891  */
892 int wm_file_write(bContext *C, const char *filepath, int fileflags, ReportList *reports)
893 {
894         Library *li;
895         int len;
896         int *thumb = NULL;
897         ImBuf *ibuf_thumb = NULL;
898
899         len = strlen(filepath);
900         
901         if (len == 0) {
902                 BKE_report(reports, RPT_ERROR, "Path is empty, cannot save");
903                 return -1;
904         }
905
906         if (len >= FILE_MAX) {
907                 BKE_report(reports, RPT_ERROR, "Path too long, cannot save");
908                 return -1;
909         }
910         
911         /* Check if file write permission is ok */
912         if (BLI_exists(filepath) && !BLI_file_is_writable(filepath)) {
913                 BKE_reportf(reports, RPT_ERROR, "Cannot save blend file, path '%s' is not writable", filepath);
914                 return -1;
915         }
916  
917         /* note: used to replace the file extension (to ensure '.blend'),
918          * no need to now because the operator ensures,
919          * its handy for scripts to save to a predefined name without blender editing it */
920         
921         /* send the OnSave event */
922         for (li = G.main->library.first; li; li = li->id.next) {
923                 if (BLI_path_cmp(li->filepath, filepath) == 0) {
924                         BKE_reportf(reports, RPT_ERROR, "Cannot overwrite used library '%.240s'", filepath);
925                         return -1;
926                 }
927         }
928
929         /* blend file thumbnail */
930         /* save before exit_editmode, otherwise derivedmeshes for shared data corrupt #27765) */
931         if ((U.flag & USER_SAVE_PREVIEWS) && BLI_thread_is_main()) {
932                 ibuf_thumb = blend_file_thumb(CTX_data_scene(C), CTX_wm_screen(C), &thumb);
933         }
934
935         BLI_callback_exec(G.main, NULL, BLI_CB_EVT_SAVE_PRE);
936
937         /* operator now handles overwrite checks */
938
939         if (G.fileflags & G_AUTOPACK) {
940                 packAll(G.main, reports);
941         }
942
943         /* don't forget not to return without! */
944         WM_cursor_wait(1);
945         
946         write_flush_editdata(C);
947
948         fileflags |= G_FILE_HISTORY; /* write file history */
949
950         /* first time saving */
951         /* XXX temp solution to solve bug, real fix coming (ton) */
952         if ((G.main->name[0] == '\0') && !(fileflags & G_FILE_SAVE_COPY)) {
953                 BLI_strncpy(G.main->name, filepath, sizeof(G.main->name));
954         }
955
956         /* XXX temp solution to solve bug, real fix coming (ton) */
957         G.main->recovered = 0;
958         
959         if (BLO_write_file(CTX_data_main(C), filepath, fileflags, reports, thumb)) {
960                 if (!(fileflags & G_FILE_SAVE_COPY)) {
961                         G.relbase_valid = 1;
962                         BLI_strncpy(G.main->name, filepath, sizeof(G.main->name));  /* is guaranteed current file */
963         
964                         G.save_over = 1; /* disable untitled.blend convention */
965                 }
966
967                 if (fileflags & G_FILE_COMPRESS) G.fileflags |= G_FILE_COMPRESS;
968                 else G.fileflags &= ~G_FILE_COMPRESS;
969                 
970                 if (fileflags & G_FILE_AUTOPLAY) G.fileflags |= G_FILE_AUTOPLAY;
971                 else G.fileflags &= ~G_FILE_AUTOPLAY;
972
973                 /* prevent background mode scripts from clobbering history */
974                 if (!G.background) {
975                         write_history();
976                 }
977
978                 BLI_callback_exec(G.main, NULL, BLI_CB_EVT_SAVE_POST);
979
980                 /* run this function after because the file cant be written before the blend is */
981                 if (ibuf_thumb) {
982                         IMB_thumb_delete(filepath, THB_FAIL); /* without this a failed thumb overrides */
983                         ibuf_thumb = IMB_thumb_create(filepath, THB_NORMAL, THB_SOURCE_BLEND, ibuf_thumb);
984                         IMB_freeImBuf(ibuf_thumb);
985                 }
986
987                 if (thumb) MEM_freeN(thumb);
988         }
989         else {
990                 if (ibuf_thumb) IMB_freeImBuf(ibuf_thumb);
991                 if (thumb) MEM_freeN(thumb);
992                 
993                 WM_cursor_wait(0);
994                 return -1;
995         }
996
997         WM_cursor_wait(0);
998         
999         return 0;
1000 }
1001
1002 /**
1003  * \see #wm_file_write wraps #BLO_write_file in a similar way.
1004  */
1005 int wm_homefile_write_exec(bContext *C, wmOperator *op)
1006 {
1007         wmWindowManager *wm = CTX_wm_manager(C);
1008         wmWindow *win = CTX_wm_window(C);
1009         char filepath[FILE_MAX];
1010         int fileflags;
1011
1012         /* check current window and close it if temp */
1013         if (win && win->screen->temp)
1014                 wm_window_close(C, wm, win);
1015         
1016         /* update keymaps in user preferences */
1017         WM_keyconfig_update(wm);
1018         
1019         BLI_make_file_string("/", filepath, BLI_get_folder_create(BLENDER_USER_CONFIG, NULL), BLENDER_STARTUP_FILE);
1020         printf("trying to save homefile at %s ", filepath);
1021         
1022         write_flush_editdata(C);
1023
1024         /*  force save as regular blend file */
1025         fileflags = G.fileflags & ~(G_FILE_COMPRESS | G_FILE_AUTOPLAY | G_FILE_LOCK | G_FILE_SIGN | G_FILE_HISTORY);
1026
1027         if (BLO_write_file(CTX_data_main(C), filepath, fileflags | G_FILE_USERPREFS, op->reports, NULL) == 0) {
1028                 printf("fail\n");
1029                 return OPERATOR_CANCELLED;
1030         }
1031         
1032         printf("ok\n");
1033
1034         G.save_over = 0;
1035
1036         return OPERATOR_FINISHED;
1037 }
1038
1039 /* Only save the prefs block. operator entry */
1040 int wm_userpref_write_exec(bContext *C, wmOperator *op)
1041 {
1042         wmWindowManager *wm = CTX_wm_manager(C);
1043         char filepath[FILE_MAX];
1044         
1045         /* update keymaps in user preferences */
1046         WM_keyconfig_update(wm);
1047         
1048         BLI_make_file_string("/", filepath, BLI_get_folder_create(BLENDER_USER_CONFIG, NULL), BLENDER_USERPREF_FILE);
1049         printf("trying to save userpref at %s ", filepath);
1050         
1051         if (BKE_write_file_userdef(filepath, op->reports) == 0) {
1052                 printf("fail\n");
1053                 return OPERATOR_CANCELLED;
1054         }
1055         
1056         printf("ok\n");
1057         
1058         return OPERATOR_FINISHED;
1059 }
1060
1061 /************************ autosave ****************************/
1062
1063 void wm_autosave_location(char *filepath)
1064 {
1065         char pidstr[32];
1066 #ifdef WIN32
1067         const char *savedir;
1068 #endif
1069
1070         BLI_snprintf(pidstr, sizeof(pidstr), "%d.blend", abs(getpid()));
1071
1072 #ifdef WIN32
1073         /* XXX Need to investigate how to handle default location of '/tmp/'
1074          * This is a relative directory on Windows, and it may be
1075          * found. Example:
1076          * Blender installed on D:\ drive, D:\ drive has D:\tmp\
1077          * Now, BLI_exists() will find '/tmp/' exists, but
1078          * BLI_make_file_string will create string that has it most likely on C:\
1079          * through get_default_root().
1080          * If there is no C:\tmp autosave fails. */
1081         if (!BLI_exists(BLI_temporary_dir())) {
1082                 savedir = BLI_get_folder_create(BLENDER_USER_AUTOSAVE, NULL);
1083                 BLI_make_file_string("/", filepath, savedir, pidstr);
1084                 return;
1085         }
1086 #endif
1087
1088         BLI_make_file_string("/", filepath, BLI_temporary_dir(), pidstr);
1089 }
1090
1091 void WM_autosave_init(wmWindowManager *wm)
1092 {
1093         wm_autosave_timer_ended(wm);
1094
1095         if (U.flag & USER_AUTOSAVE)
1096                 wm->autosavetimer = WM_event_add_timer(wm, NULL, TIMERAUTOSAVE, U.savetime * 60.0);
1097 }
1098
1099 void wm_autosave_timer(const bContext *C, wmWindowManager *wm, wmTimer *UNUSED(wt))
1100 {
1101         wmWindow *win;
1102         wmEventHandler *handler;
1103         char filepath[FILE_MAX];
1104         
1105         Scene *scene = CTX_data_scene(C);
1106
1107         WM_event_remove_timer(wm, NULL, wm->autosavetimer);
1108
1109         /* if a modal operator is running, don't autosave, but try again in 10 seconds */
1110         for (win = wm->windows.first; win; win = win->next) {
1111                 for (handler = win->modalhandlers.first; handler; handler = handler->next) {
1112                         if (handler->op) {
1113                                 wm->autosavetimer = WM_event_add_timer(wm, NULL, TIMERAUTOSAVE, 10.0);
1114                                 return;
1115                         }
1116                 }
1117         }
1118
1119         if (scene) {
1120                 Object *ob = OBACT;
1121
1122                 if (ob && ob->mode & OB_MODE_SCULPT)
1123                         multires_force_update(ob);
1124         }
1125
1126         wm_autosave_location(filepath);
1127
1128         if (U.uiflag & USER_GLOBALUNDO) {
1129                 /* fast save of last undobuffer, now with UI */
1130                 BKE_undo_save_file(filepath);
1131         }
1132         else {
1133                 /*  save as regular blend file */
1134                 int fileflags = G.fileflags & ~(G_FILE_COMPRESS | G_FILE_AUTOPLAY | G_FILE_LOCK | G_FILE_SIGN | G_FILE_HISTORY);
1135
1136                 /* no error reporting to console */
1137                 BLO_write_file(CTX_data_main(C), filepath, fileflags, NULL, NULL);
1138         }
1139         /* do timer after file write, just in case file write takes a long time */
1140         wm->autosavetimer = WM_event_add_timer(wm, NULL, TIMERAUTOSAVE, U.savetime * 60.0);
1141 }
1142
1143 void wm_autosave_timer_ended(wmWindowManager *wm)
1144 {
1145         if (wm->autosavetimer) {
1146                 WM_event_remove_timer(wm, NULL, wm->autosavetimer);
1147                 wm->autosavetimer = NULL;
1148         }
1149 }
1150
1151 void wm_autosave_delete(void)
1152 {
1153         char filename[FILE_MAX];
1154         
1155         wm_autosave_location(filename);
1156
1157         if (BLI_exists(filename)) {
1158                 char str[FILE_MAX];
1159                 BLI_make_file_string("/", str, BLI_temporary_dir(), BLENDER_QUIT_FILE);
1160
1161                 /* if global undo; remove tempsave, otherwise rename */
1162                 if (U.uiflag & USER_GLOBALUNDO) BLI_delete(filename, false, false);
1163                 else BLI_rename(filename, str);
1164         }
1165 }
1166
1167 void wm_autosave_read(bContext *C, ReportList *reports)
1168 {
1169         char filename[FILE_MAX];
1170
1171         wm_autosave_location(filename);
1172         WM_file_read(C, filename, reports);
1173 }
1174