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