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