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