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