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