7a528e419959db0ab61aea8f99fa635173b455b4
[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                 /* when loading startup.blend's, we can be left with a blank path */
399                 if (G.main->name[0]) {
400                         G.save_over = 1;
401                 }
402                 else {
403                         G.save_over = 0;
404                         G.relbase_valid = 0;
405                 }
406
407                 /* this flag is initialized by the operator but overwritten on read.
408                  * need to re-enable it here else drivers + registered scripts wont work. */
409                 if (G.f != G_f) {
410                         const int flags_keep = (G_SCRIPT_AUTOEXEC | G_SCRIPT_OVERRIDE_PREF);
411                         G.f = (G.f & ~flags_keep) | (G_f & flags_keep);
412                 }
413
414                 /* match the read WM with current WM */
415                 wm_window_match_do(C, &wmbase);
416                 WM_check(C); /* opens window(s), checks keymaps */
417
418                 if (retval == BKE_READ_FILE_OK_USERPREFS) {
419                         /* in case a userdef is read from regular .blend */
420                         wm_init_userdef(C);
421                 }
422                 
423                 if (retval != BKE_READ_FILE_FAIL) {
424                         if (do_history) {
425                                 write_history();
426                         }
427                 }
428
429
430                 WM_event_add_notifier(C, NC_WM | ND_FILEREAD, NULL);
431 //              refresh_interface_font();
432
433                 CTX_wm_window_set(C, CTX_wm_manager(C)->windows.first);
434
435                 ED_editors_init(C);
436                 DAG_on_visible_update(CTX_data_main(C), TRUE);
437
438 #ifdef WITH_PYTHON
439                 /* run any texts that were loaded in and flagged as modules */
440                 BPY_driver_reset();
441                 BPY_app_handlers_reset(FALSE);
442                 BPY_modules_load_user(C);
443 #endif
444
445                 /* important to do before NULL'ing the context */
446                 BLI_callback_exec(CTX_data_main(C), NULL, BLI_CB_EVT_LOAD_POST);
447
448                 if (!G.background) {
449                         /* in background mode this makes it hard to load
450                          * a blend file and do anything since the screen
451                          * won't be set to a valid value again */
452                         CTX_wm_window_set(C, NULL); /* exits queues */
453                 }
454
455 #if 0
456                 /* gives popups on windows but not linux, bug in report API
457                  * but disable for now to stop users getting annoyed  */
458                 /* TODO, make this show in header info window */
459                 {
460                         Scene *sce;
461                         for (sce = G.main->scene.first; sce; sce = sce->id.next) {
462                                 if (sce->r.engine[0] &&
463                                     BLI_findstring(&R_engines, sce->r.engine, offsetof(RenderEngineType, idname)) == NULL)
464                                 {
465                                         BKE_reportf(reports, RPT_ERROR, "Engine '%s' not available for scene '%s' "
466                                                     "(an addon may need to be installed or enabled)",
467                                                     sce->r.engine, sce->id.name + 2);
468                                 }
469                         }
470                 }
471 #endif
472
473                 BKE_reset_undo();
474                 BKE_write_undo(C, "original");  /* save current state */
475         }
476         else if (retval == BKE_READ_EXOTIC_OK_OTHER)
477                 BKE_write_undo(C, "Import file");
478         else if (retval == BKE_READ_EXOTIC_FAIL_OPEN) {
479                 BKE_reportf(reports, RPT_ERROR, "Cannot read file '%s': %s", filepath,
480                             errno ? strerror(errno) : TIP_("unable to open the file"));
481         }
482         else if (retval == BKE_READ_EXOTIC_FAIL_FORMAT) {
483                 BKE_reportf(reports, RPT_ERROR, "File format is not supported in file '%s'", filepath);
484         }
485         else if (retval == BKE_READ_EXOTIC_FAIL_PATH) {
486                 BKE_reportf(reports, RPT_ERROR, "File path '%s' invalid", filepath);
487         }
488         else {
489                 BKE_reportf(reports, RPT_ERROR, "Unknown error loading '%s'", filepath);
490                 BLI_assert(!"invalid 'retval'");
491         }
492
493         WM_cursor_wait(0);
494
495 }
496
497
498 /* called on startup,  (context entirely filled with NULLs) */
499 /* or called for 'New File' */
500 /* both startup.blend and userpref.blend are checked */
501 int wm_homefile_read(bContext *C, ReportList *UNUSED(reports), short from_memory)
502 {
503         ListBase wmbase;
504         char startstr[FILE_MAX];
505         char prefstr[FILE_MAX];
506         int success = 0;
507
508         BLI_callback_exec(CTX_data_main(C), NULL, BLI_CB_EVT_LOAD_PRE);
509
510         G.relbase_valid = 0;
511         if (!from_memory) {
512                 const char * const cfgdir = BLI_get_folder(BLENDER_USER_CONFIG, NULL);
513                 if (cfgdir) {
514                         BLI_make_file_string(G.main->name, startstr, cfgdir, BLENDER_STARTUP_FILE);
515                         BLI_make_file_string(G.main->name, prefstr, cfgdir, BLENDER_USERPREF_FILE);
516                 }
517                 else {
518                         startstr[0] = '\0';
519                         prefstr[0] = '\0';
520                         from_memory = 1;
521                 }
522         }
523         
524         /* prevent loading no UI */
525         G.fileflags &= ~G_FILE_NO_UI;
526         
527         /* put aside screens to match with persistent windows later */
528         wm_window_match_init(C, &wmbase); 
529         
530         if (!from_memory) {
531                 if (BLI_exists(startstr)) {
532                         success = (BKE_read_file(C, startstr, NULL) != BKE_READ_FILE_FAIL);
533                 }
534
535                 if (U.themes.first == NULL) {
536                         if (G.debug & G_DEBUG)
537                                 printf("\nNote: No (valid) '%s' found, fall back to built-in default.\n\n", startstr);
538                         success = 0;
539                 }
540         }
541
542         if (success == 0) {
543                 success = BKE_read_file_from_memory(C, datatoc_startup_blend, datatoc_startup_blend_size, NULL);
544                 if (wmbase.first == NULL) wm_clear_default_size(C);
545
546 #ifdef WITH_PYTHON_SECURITY /* not default */
547                 /* use alternative setting for security nuts
548                  * otherwise we'd need to patch the binary blob - startup.blend.c */
549                 U.flag |= USER_SCRIPT_AUTOEXEC_DISABLE;
550 #endif
551         }
552         
553         /* check new prefs only after startup.blend was finished */
554         if (!from_memory && BLI_exists(prefstr)) {
555                 int done = BKE_read_file_userdef(prefstr, NULL);
556                 if (done) printf("Read new prefs: %s\n", prefstr);
557         }
558         
559         /* prevent buggy files that had G_FILE_RELATIVE_REMAP written out by mistake. Screws up autosaves otherwise
560          * can remove this eventually, only in a 2.53 and older, now its not written */
561         G.fileflags &= ~G_FILE_RELATIVE_REMAP;
562         
563         /* check userdef before open window, keymaps etc */
564         wm_init_userdef(C);
565         
566         /* match the read WM with current WM */
567         wm_window_match_do(C, &wmbase); 
568         WM_check(C); /* opens window(s), checks keymaps */
569
570         G.main->name[0] = '\0';
571
572         /* When loading factory settings, the reset solid OpenGL lights need to be applied. */
573         if (!G.background) GPU_default_lights();
574         
575         /* XXX */
576         G.save_over = 0;    // start with save preference untitled.blend
577         G.fileflags &= ~G_FILE_AUTOPLAY;    /*  disable autoplay in startup.blend... */
578
579 //      refresh_interface_font();
580         
581 //      undo_editmode_clear();
582         BKE_reset_undo();
583         BKE_write_undo(C, "original");  /* save current state */
584
585         ED_editors_init(C);
586         DAG_on_visible_update(CTX_data_main(C), TRUE);
587
588 #ifdef WITH_PYTHON
589         if (CTX_py_init_get(C)) {
590                 /* sync addons, these may have changed from the defaults */
591                 BPY_string_exec(C, "__import__('addon_utils').reset_all()");
592
593                 BPY_driver_reset();
594                 BPY_app_handlers_reset(FALSE);
595                 BPY_modules_load_user(C);
596         }
597 #endif
598
599         /* important to do before NULL'ing the context */
600         BLI_callback_exec(CTX_data_main(C), NULL, BLI_CB_EVT_LOAD_POST);
601
602         WM_event_add_notifier(C, NC_WM | ND_FILEREAD, NULL);
603
604         /* in background mode the scene will stay NULL */
605         if (!G.background) {
606                 CTX_wm_window_set(C, NULL); /* exits queues */
607         }
608
609         return TRUE;
610 }
611
612 int wm_history_read_exec(bContext *UNUSED(C), wmOperator *UNUSED(op))
613 {
614         /* TODO, read bookmarks */
615         wm_read_history();
616         return OPERATOR_FINISHED;
617 }
618
619 int wm_homefile_read_exec(bContext *C, wmOperator *op)
620 {
621         int from_memory = strcmp(op->type->idname, "WM_OT_read_factory_settings") == 0;
622         return wm_homefile_read(C, op->reports, from_memory) ? OPERATOR_FINISHED : OPERATOR_CANCELLED;
623 }
624
625 void wm_read_history(void)
626 {
627         char name[FILE_MAX];
628         LinkNode *l, *lines;
629         struct RecentFile *recent;
630         char *line;
631         int num;
632         const char * const cfgdir = BLI_get_folder(BLENDER_USER_CONFIG, NULL);
633
634         if (!cfgdir) return;
635
636         BLI_make_file_string("/", name, cfgdir, BLENDER_HISTORY_FILE);
637
638         lines = BLI_file_read_as_lines(name);
639
640         G.recent_files.first = G.recent_files.last = NULL;
641
642         /* read list of recent opened files from recent-files.txt to memory */
643         for (l = lines, num = 0; l && (num < U.recent_files); l = l->next) {
644                 line = l->link;
645                 if (line[0] && BLI_exists(line)) {
646                         recent = (RecentFile *)MEM_mallocN(sizeof(RecentFile), "RecentFile");
647                         BLI_addtail(&(G.recent_files), recent);
648                         recent->filepath = BLI_strdup(line);
649                         num++;
650                 }
651         }
652         
653         BLI_file_free_lines(lines);
654 }
655
656 static void write_history(void)
657 {
658         struct RecentFile *recent, *next_recent;
659         char name[FILE_MAX];
660         const char *user_config_dir;
661         FILE *fp;
662         int i;
663
664         /* no write history for recovered startup files */
665         if (G.main->name[0] == 0)
666                 return;
667         
668         /* will be NULL in background mode */
669         user_config_dir = BLI_get_folder_create(BLENDER_USER_CONFIG, NULL);
670         if (!user_config_dir)
671                 return;
672
673         BLI_make_file_string("/", name, user_config_dir, BLENDER_HISTORY_FILE);
674
675         recent = G.recent_files.first;
676         /* refresh recent-files.txt of recent opened files, when current file was changed */
677         if (!(recent) || (BLI_path_cmp(recent->filepath, G.main->name) != 0)) {
678                 fp = BLI_fopen(name, "w");
679                 if (fp) {
680                         /* add current file to the beginning of list */
681                         recent = (RecentFile *)MEM_mallocN(sizeof(RecentFile), "RecentFile");
682                         recent->filepath = BLI_strdup(G.main->name);
683                         BLI_addhead(&(G.recent_files), recent);
684                         /* write current file to recent-files.txt */
685                         fprintf(fp, "%s\n", recent->filepath);
686                         recent = recent->next;
687                         i = 1;
688                         /* write rest of recent opened files to recent-files.txt */
689                         while ((i < U.recent_files) && (recent)) {
690                                 /* this prevents to have duplicities in list */
691                                 if (BLI_path_cmp(recent->filepath, G.main->name) != 0) {
692                                         fprintf(fp, "%s\n", recent->filepath);
693                                         recent = recent->next;
694                                 }
695                                 else {
696                                         next_recent = recent->next;
697                                         MEM_freeN(recent->filepath);
698                                         BLI_freelinkN(&(G.recent_files), recent);
699                                         recent = next_recent;
700                                 }
701                                 i++;
702                         }
703                         fclose(fp);
704                 }
705
706                 /* also update most recent files on System */
707                 GHOST_addToSystemRecentFiles(G.main->name);
708         }
709 }
710
711 /* screen can be NULL */
712 static ImBuf *blend_file_thumb(Scene *scene, bScreen *screen, int **thumb_pt)
713 {
714         /* will be scaled down, but gives some nice oversampling */
715         ImBuf *ibuf;
716         int *thumb;
717         char err_out[256] = "unknown";
718
719         /* screen if no camera found */
720         ScrArea *sa = NULL;
721         ARegion *ar = NULL;
722         View3D *v3d = NULL;
723
724         *thumb_pt = NULL;
725
726         /* scene can be NULL if running a script at startup and calling the save operator */
727         if (G.background || scene == NULL)
728                 return NULL;
729
730         if ((scene->camera == NULL) && (screen != NULL)) {
731                 sa = BKE_screen_find_big_area(screen, SPACE_VIEW3D, 0);
732                 ar = BKE_area_find_region_type(sa, RGN_TYPE_WINDOW);
733                 if (ar) {
734                         v3d = sa->spacedata.first;
735                 }
736         }
737
738         if (scene->camera == NULL && v3d == NULL) {
739                 return NULL;
740         }
741
742         /* gets scaled to BLEN_THUMB_SIZE */
743         if (scene->camera) {
744                 ibuf = ED_view3d_draw_offscreen_imbuf_simple(scene, scene->camera,
745                                                              BLEN_THUMB_SIZE * 2, BLEN_THUMB_SIZE * 2,
746                                                              IB_rect, OB_SOLID, FALSE, FALSE, R_ADDSKY, err_out);
747         }
748         else {
749                 ibuf = ED_view3d_draw_offscreen_imbuf(scene, v3d, ar, BLEN_THUMB_SIZE * 2, BLEN_THUMB_SIZE * 2,
750                                                       IB_rect, FALSE, R_ADDSKY, err_out);
751         }
752
753         if (ibuf) {
754                 float aspect = (scene->r.xsch * scene->r.xasp) / (scene->r.ysch * scene->r.yasp);
755
756                 /* dirty oversampling */
757                 IMB_scaleImBuf(ibuf, BLEN_THUMB_SIZE, BLEN_THUMB_SIZE);
758
759                 /* add pretty overlay */
760                 IMB_overlayblend_thumb(ibuf->rect, ibuf->x, ibuf->y, aspect);
761                 
762                 /* first write into thumb buffer */
763                 thumb = MEM_mallocN(((2 + (BLEN_THUMB_SIZE * BLEN_THUMB_SIZE))) * sizeof(int), "write_file thumb");
764
765                 thumb[0] = BLEN_THUMB_SIZE;
766                 thumb[1] = BLEN_THUMB_SIZE;
767
768                 memcpy(thumb + 2, ibuf->rect, BLEN_THUMB_SIZE * BLEN_THUMB_SIZE * sizeof(int));
769         }
770         else {
771                 /* '*thumb_pt' needs to stay NULL to prevent a bad thumbnail from being handled */
772                 fprintf(stderr, "blend_file_thumb failed to create thumbnail: %s\n", err_out);
773                 thumb = NULL;
774         }
775         
776         /* must be freed by caller */
777         *thumb_pt = thumb;
778         
779         return ibuf;
780 }
781
782 /* easy access from gdb */
783 int write_crash_blend(void)
784 {
785         char path[FILE_MAX];
786         int fileflags = G.fileflags & ~(G_FILE_HISTORY); /* don't do file history on crash file */
787
788         BLI_strncpy(path, G.main->name, sizeof(path));
789         BLI_replace_extension(path, sizeof(path), "_crash.blend");
790         if (BLO_write_file(G.main, path, fileflags, NULL, NULL)) {
791                 printf("written: %s\n", path);
792                 return 1;
793         }
794         else {
795                 printf("failed: %s\n", path);
796                 return 0;
797         }
798 }
799
800 int wm_file_write(bContext *C, const char *target, int fileflags, ReportList *reports)
801 {
802         Library *li;
803         int len;
804         char filepath[FILE_MAX];
805         int *thumb = NULL;
806         ImBuf *ibuf_thumb = NULL;
807
808         len = strlen(target);
809         
810         if (len == 0) {
811                 BKE_report(reports, RPT_ERROR, "Path is empty, cannot save");
812                 return -1;
813         }
814
815         if (len >= FILE_MAX) {
816                 BKE_report(reports, RPT_ERROR, "Path too long, cannot save");
817                 return -1;
818         }
819  
820         BLI_strncpy(filepath, target, FILE_MAX);
821         BLI_replace_extension(filepath, FILE_MAX, ".blend");
822         /* don't use 'target' anymore */
823         
824         /* send the OnSave event */
825         for (li = G.main->library.first; li; li = li->id.next) {
826                 if (BLI_path_cmp(li->filepath, filepath) == 0) {
827                         BKE_reportf(reports, RPT_ERROR, "Cannot overwrite used library '%.240s'", filepath);
828                         return -1;
829                 }
830         }
831
832         /* blend file thumbnail */
833         /* save before exit_editmode, otherwise derivedmeshes for shared data corrupt #27765) */
834         if ((U.flag & USER_SAVE_PREVIEWS) && BLI_thread_is_main()) {
835                 ibuf_thumb = blend_file_thumb(CTX_data_scene(C), CTX_wm_screen(C), &thumb);
836         }
837
838         BLI_callback_exec(G.main, NULL, BLI_CB_EVT_SAVE_PRE);
839
840         /* operator now handles overwrite checks */
841
842         if (G.fileflags & G_AUTOPACK) {
843                 packAll(G.main, reports);
844         }
845
846         ED_object_editmode_load(CTX_data_edit_object(C));
847         ED_sculpt_force_update(C);
848
849         /* don't forget not to return without! */
850         WM_cursor_wait(1);
851         
852         fileflags |= G_FILE_HISTORY; /* write file history */
853
854         /* first time saving */
855         /* XXX temp solution to solve bug, real fix coming (ton) */
856         if (G.main->name[0] == 0)
857                 BLI_strncpy(G.main->name, filepath, sizeof(G.main->name));
858         
859         /* XXX temp solution to solve bug, real fix coming (ton) */
860         G.main->recovered = 0;
861         
862         if (BLO_write_file(CTX_data_main(C), filepath, fileflags, reports, thumb)) {
863                 if (!(fileflags & G_FILE_SAVE_COPY)) {
864                         G.relbase_valid = 1;
865                         BLI_strncpy(G.main->name, filepath, sizeof(G.main->name));  /* is guaranteed current file */
866         
867                         G.save_over = 1; /* disable untitled.blend convention */
868                 }
869
870                 if (fileflags & G_FILE_COMPRESS) G.fileflags |= G_FILE_COMPRESS;
871                 else G.fileflags &= ~G_FILE_COMPRESS;
872                 
873                 if (fileflags & G_FILE_AUTOPLAY) G.fileflags |= G_FILE_AUTOPLAY;
874                 else G.fileflags &= ~G_FILE_AUTOPLAY;
875
876                 /* prevent background mode scripts from clobbering history */
877                 if (!G.background) {
878                         write_history();
879                 }
880
881                 BLI_callback_exec(G.main, NULL, BLI_CB_EVT_SAVE_POST);
882
883                 /* run this function after because the file cant be written before the blend is */
884                 if (ibuf_thumb) {
885                         IMB_thumb_delete(filepath, THB_FAIL); /* without this a failed thumb overrides */
886                         ibuf_thumb = IMB_thumb_create(filepath, THB_NORMAL, THB_SOURCE_BLEND, ibuf_thumb);
887                         IMB_freeImBuf(ibuf_thumb);
888                 }
889
890                 if (thumb) MEM_freeN(thumb);
891         }
892         else {
893                 if (ibuf_thumb) IMB_freeImBuf(ibuf_thumb);
894                 if (thumb) MEM_freeN(thumb);
895                 
896                 WM_cursor_wait(0);
897                 return -1;
898         }
899
900         WM_cursor_wait(0);
901         
902         return 0;
903 }
904
905 /* operator entry */
906 int wm_homefile_write_exec(bContext *C, wmOperator *op)
907 {
908         wmWindowManager *wm = CTX_wm_manager(C);
909         wmWindow *win = CTX_wm_window(C);
910         char filepath[FILE_MAX];
911         int fileflags;
912
913         /* check current window and close it if temp */
914         if (win->screen->temp)
915                 wm_window_close(C, wm, win);
916         
917         /* update keymaps in user preferences */
918         WM_keyconfig_update(wm);
919         
920         BLI_make_file_string("/", filepath, BLI_get_folder_create(BLENDER_USER_CONFIG, NULL), BLENDER_STARTUP_FILE);
921         printf("trying to save homefile at %s ", filepath);
922         
923         /*  force save as regular blend file */
924         fileflags = G.fileflags & ~(G_FILE_COMPRESS | G_FILE_AUTOPLAY | G_FILE_LOCK | G_FILE_SIGN | G_FILE_HISTORY);
925
926         if (BLO_write_file(CTX_data_main(C), filepath, fileflags | G_FILE_USERPREFS, op->reports, NULL) == 0) {
927                 printf("fail\n");
928                 return OPERATOR_CANCELLED;
929         }
930         
931         printf("ok\n");
932
933         G.save_over = 0;
934
935         return OPERATOR_FINISHED;
936 }
937
938 /* Only save the prefs block. operator entry */
939 int wm_userpref_write_exec(bContext *C, wmOperator *op)
940 {
941         wmWindowManager *wm = CTX_wm_manager(C);
942         char filepath[FILE_MAX];
943         
944         /* update keymaps in user preferences */
945         WM_keyconfig_update(wm);
946         
947         BLI_make_file_string("/", filepath, BLI_get_folder_create(BLENDER_USER_CONFIG, NULL), BLENDER_USERPREF_FILE);
948         printf("trying to save userpref at %s ", filepath);
949         
950         if (BKE_write_file_userdef(filepath, op->reports) == 0) {
951                 printf("fail\n");
952                 return OPERATOR_CANCELLED;
953         }
954         
955         printf("ok\n");
956         
957         return OPERATOR_FINISHED;
958 }
959
960 /************************ autosave ****************************/
961
962 void wm_autosave_location(char *filepath)
963 {
964         char pidstr[32];
965 #ifdef WIN32
966         const char *savedir;
967 #endif
968
969         BLI_snprintf(pidstr, sizeof(pidstr), "%d.blend", abs(getpid()));
970
971 #ifdef WIN32
972         /* XXX Need to investigate how to handle default location of '/tmp/'
973          * This is a relative directory on Windows, and it may be
974          * found. Example:
975          * Blender installed on D:\ drive, D:\ drive has D:\tmp\
976          * Now, BLI_exists() will find '/tmp/' exists, but
977          * BLI_make_file_string will create string that has it most likely on C:\
978          * through get_default_root().
979          * If there is no C:\tmp autosave fails. */
980         if (!BLI_exists(BLI_temporary_dir())) {
981                 savedir = BLI_get_folder_create(BLENDER_USER_AUTOSAVE, NULL);
982                 BLI_make_file_string("/", filepath, savedir, pidstr);
983                 return;
984         }
985 #endif
986
987         BLI_make_file_string("/", filepath, BLI_temporary_dir(), pidstr);
988 }
989
990 void WM_autosave_init(wmWindowManager *wm)
991 {
992         wm_autosave_timer_ended(wm);
993
994         if (U.flag & USER_AUTOSAVE)
995                 wm->autosavetimer = WM_event_add_timer(wm, NULL, TIMERAUTOSAVE, U.savetime * 60.0);
996 }
997
998 void wm_autosave_timer(const bContext *C, wmWindowManager *wm, wmTimer *UNUSED(wt))
999 {
1000         wmWindow *win;
1001         wmEventHandler *handler;
1002         char filepath[FILE_MAX];
1003         
1004         Scene *scene = CTX_data_scene(C);
1005
1006         WM_event_remove_timer(wm, NULL, wm->autosavetimer);
1007
1008         /* if a modal operator is running, don't autosave, but try again in 10 seconds */
1009         for (win = wm->windows.first; win; win = win->next) {
1010                 for (handler = win->modalhandlers.first; handler; handler = handler->next) {
1011                         if (handler->op) {
1012                                 wm->autosavetimer = WM_event_add_timer(wm, NULL, TIMERAUTOSAVE, 10.0);
1013                                 return;
1014                         }
1015                 }
1016         }
1017
1018         if (scene) {
1019                 Object *ob = OBACT;
1020
1021                 if (ob && ob->mode & OB_MODE_SCULPT)
1022                         multires_force_update(ob);
1023         }
1024
1025         wm_autosave_location(filepath);
1026
1027         if (U.uiflag & USER_GLOBALUNDO) {
1028                 /* fast save of last undobuffer, now with UI */
1029                 BKE_undo_save_file(filepath);
1030         }
1031         else {
1032                 /*  save as regular blend file */
1033                 int fileflags = G.fileflags & ~(G_FILE_COMPRESS | G_FILE_AUTOPLAY | G_FILE_LOCK | G_FILE_SIGN | G_FILE_HISTORY);
1034
1035                 /* no error reporting to console */
1036                 BLO_write_file(CTX_data_main(C), filepath, fileflags, NULL, NULL);
1037         }
1038         /* do timer after file write, just in case file write takes a long time */
1039         wm->autosavetimer = WM_event_add_timer(wm, NULL, TIMERAUTOSAVE, U.savetime * 60.0);
1040 }
1041
1042 void wm_autosave_timer_ended(wmWindowManager *wm)
1043 {
1044         if (wm->autosavetimer) {
1045                 WM_event_remove_timer(wm, NULL, wm->autosavetimer);
1046                 wm->autosavetimer = NULL;
1047         }
1048 }
1049
1050 void wm_autosave_delete(void)
1051 {
1052         char filename[FILE_MAX];
1053         
1054         wm_autosave_location(filename);
1055
1056         if (BLI_exists(filename)) {
1057                 char str[FILE_MAX];
1058                 BLI_make_file_string("/", str, BLI_temporary_dir(), BLENDER_QUIT_FILE);
1059
1060                 /* if global undo; remove tempsave, otherwise rename */
1061                 if (U.uiflag & USER_GLOBALUNDO) BLI_delete(filename, false, false);
1062                 else BLI_rename(filename, str);
1063         }
1064 }
1065
1066 void wm_autosave_read(bContext *C, ReportList *reports)
1067 {
1068         char filename[FILE_MAX];
1069
1070         wm_autosave_location(filename);
1071         WM_file_read(C, filename, reports);
1072 }
1073
1074
1075
1076