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