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