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