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