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