3d10a76641709ca425c275df2da77a7584fdb8f1
[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 #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                 /* TODO, make this show in header info window */
344                 {
345                         Scene *sce;
346                         for(sce= G.main->scene.first; sce; sce= sce->id.next) {
347                                 if(sce->r.engine[0] && BLI_findstring(&R_engines, sce->r.engine, offsetof(RenderEngineType, idname)) == NULL) {
348                                         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);
349                                 }
350                         }
351                 }
352
353
354                 // XXX          undo_editmode_clear();
355                 BKE_reset_undo();
356                 BKE_write_undo(C, "original");  /* save current state */
357                 
358         }
359         else if(retval == BKE_READ_EXOTIC_OK_OTHER)
360                 BKE_write_undo(C, "Import file");
361         else if(retval == BKE_READ_EXOTIC_FAIL_OPEN) {
362                 BKE_reportf(reports, RPT_ERROR, "Can't read file: \"%s\", %s.", name, errno ? strerror(errno) : "Unable to open the file");
363         }
364         else if(retval == BKE_READ_EXOTIC_FAIL_FORMAT) {
365                 BKE_reportf(reports, RPT_ERROR, "File format is not supported in file: \"%s\".", name);
366         }
367         else if(retval == BKE_READ_EXOTIC_FAIL_PATH) {
368                 BKE_reportf(reports, RPT_ERROR, "File path invalid: \"%s\".", name);
369         }
370         else {
371                 BKE_reportf(reports, RPT_ERROR, "Unknown error loading: \"%s\".", name);
372                 BLI_assert(!"invalid 'retval'");
373         }
374
375         WM_cursor_wait(0);
376
377 }
378
379
380 /* called on startup,  (context entirely filled with NULLs) */
381 /* or called for 'New File' */
382 /* op can be NULL */
383 int WM_read_homefile(bContext *C, ReportList *reports, short from_memory)
384 {
385         ListBase wmbase;
386         char tstr[FILE_MAXDIR+FILE_MAXFILE];
387         int success= 0;
388         
389         free_ttfont(); /* still weird... what does it here? */
390                 
391         G.relbase_valid = 0;
392         if (!from_memory) {
393                 char *cfgdir = BLI_get_folder(BLENDER_USER_CONFIG, NULL);
394                 if (cfgdir) {
395                         BLI_make_file_string(G.main->name, tstr, cfgdir, BLENDER_STARTUP_FILE);
396                 } else {
397                         tstr[0] = '\0';
398                         from_memory = 1;
399                         BKE_report(reports, RPT_INFO, "Config directory with "STRINGIFY(BLENDER_STARTUP_FILE)" file not found.");
400                 }
401         }
402         
403         /* prevent loading no UI */
404         G.fileflags &= ~G_FILE_NO_UI;
405         
406         /* put aside screens to match with persistant windows later */
407         wm_window_match_init(C, &wmbase); 
408         
409         if (!from_memory && BLI_exists(tstr)) {
410                 success = (BKE_read_file(C, tstr, NULL) != BKE_READ_FILE_FAIL);
411                 
412                 if(U.themes.first==NULL) {
413                         printf("\nError: No valid "STRINGIFY(BLENDER_STARTUP_FILE)", fall back to built-in default.\n\n");
414                         success = 0;
415                 }
416         }
417         if(success==0) {
418                 success = BKE_read_file_from_memory(C, datatoc_startup_blend, datatoc_startup_blend_size, NULL);
419                 if (wmbase.first == NULL) wm_clear_default_size(C);
420         }
421         
422         /* prevent buggy files that had G_FILE_RELATIVE_REMAP written out by mistake. Screws up autosaves otherwise
423          * can remove this eventually, only in a 2.53 and older, now its not written */
424         G.fileflags &= ~G_FILE_RELATIVE_REMAP;
425
426         /* match the read WM with current WM */
427         wm_window_match_do(C, &wmbase); 
428         WM_check(C); /* opens window(s), checks keymaps */
429
430         G.main->name[0]= '\0';
431
432         wm_init_userdef(C);
433         
434         /* When loading factory settings, the reset solid OpenGL lights need to be applied. */
435         if (!G.background) GPU_default_lights();
436         
437         /* XXX */
438         G.save_over = 0;        // start with save preference untitled.blend
439         G.fileflags &= ~G_FILE_AUTOPLAY;        /*  disable autoplay in startup.blend... */
440 //      mainwindow_set_filename_to_title("");   // empty string re-initializes title to "Blender"
441         
442 //      refresh_interface_font();
443         
444 //      undo_editmode_clear();
445         BKE_reset_undo();
446         BKE_write_undo(C, "original");  /* save current state */
447
448         ED_editors_init(C);
449         DAG_on_visible_update(CTX_data_main(C), TRUE);
450
451 #ifdef WITH_PYTHON
452         if(CTX_py_init_get(C)) {
453                 /* sync addons, these may have changed from the defaults */
454                 BPY_string_exec(C, "__import__('addon_utils').reset_all()");
455
456                 BPY_driver_reset();
457                 BPY_modules_load_user(C);
458         }
459 #endif
460
461         WM_event_add_notifier(C, NC_WM|ND_FILEREAD, NULL);
462
463         /* in background mode the scene will stay NULL */
464         if(!G.background) {
465                 CTX_wm_window_set(C, NULL); /* exits queues */
466         }
467
468         return TRUE;
469 }
470
471 int WM_read_homefile_exec(bContext *C, wmOperator *op)
472 {
473         int from_memory= strcmp(op->type->idname, "WM_OT_read_factory_settings") == 0;
474         return WM_read_homefile(C, op->reports, from_memory) ? OPERATOR_FINISHED : OPERATOR_CANCELLED;
475 }
476
477 void WM_read_history(void)
478 {
479         char name[FILE_MAX];
480         LinkNode *l, *lines;
481         struct RecentFile *recent;
482         char *line;
483         int num;
484         char *cfgdir = BLI_get_folder(BLENDER_CONFIG, NULL);
485
486         if (!cfgdir) return;
487
488         BLI_make_file_string("/", name, cfgdir, BLENDER_HISTORY_FILE);
489
490         lines= BLI_read_file_as_lines(name);
491
492         G.recent_files.first = G.recent_files.last = NULL;
493
494         /* read list of recent opend files from recent-files.txt to memory */
495         for (l= lines, num= 0; l && (num<U.recent_files); l= l->next) {
496                 line = l->link;
497                 if (line[0] && BLI_exists(line)) {
498                         recent = (RecentFile*)MEM_mallocN(sizeof(RecentFile),"RecentFile");
499                         BLI_addtail(&(G.recent_files), recent);
500                         recent->filepath = BLI_strdup(line);
501                         num++;
502                 }
503         }
504         
505         BLI_free_file_lines(lines);
506
507 }
508
509 static void write_history(void)
510 {
511         struct RecentFile *recent, *next_recent;
512         char name[FILE_MAXDIR+FILE_MAXFILE];
513         char *user_config_dir;
514         FILE *fp;
515         int i;
516
517         /* will be NULL in background mode */
518         user_config_dir = BLI_get_folder_create(BLENDER_USER_CONFIG, NULL);
519         if(!user_config_dir)
520                 return;
521
522         BLI_make_file_string("/", name, user_config_dir, BLENDER_HISTORY_FILE);
523
524         recent = G.recent_files.first;
525         /* refresh recent-files.txt of recent opened files, when current file was changed */
526         if(!(recent) || (BLI_path_cmp(recent->filepath, G.main->name)!=0)) {
527                 fp= fopen(name, "w");
528                 if (fp) {
529                         /* add current file to the beginning of list */
530                         recent = (RecentFile*)MEM_mallocN(sizeof(RecentFile),"RecentFile");
531                         recent->filepath = BLI_strdup(G.main->name);
532                         BLI_addhead(&(G.recent_files), recent);
533                         /* write current file to recent-files.txt */
534                         fprintf(fp, "%s\n", recent->filepath);
535                         recent = recent->next;
536                         i=1;
537                         /* write rest of recent opened files to recent-files.txt */
538                         while((i<U.recent_files) && (recent)){
539                                 /* this prevents to have duplicities in list */
540                                 if (BLI_path_cmp(recent->filepath, G.main->name)!=0) {
541                                         fprintf(fp, "%s\n", recent->filepath);
542                                         recent = recent->next;
543                                 }
544                                 else {
545                                         next_recent = recent->next;
546                                         MEM_freeN(recent->filepath);
547                                         BLI_freelinkN(&(G.recent_files), recent);
548                                         recent = next_recent;
549                                 }
550                                 i++;
551                         }
552                         fclose(fp);
553                 }
554
555                 /* also update most recent files on System */
556                 GHOST_addToSystemRecentFiles(G.main->name);
557         }
558 }
559
560 static void do_history(char *name, ReportList *reports)
561 {
562         char tempname1[FILE_MAXDIR+FILE_MAXFILE], tempname2[FILE_MAXDIR+FILE_MAXFILE];
563         int hisnr= U.versions;
564         
565         if(U.versions==0) return;
566         if(strlen(name)<2) return;
567                 
568         while(hisnr > 1) {
569                 BLI_snprintf(tempname1, sizeof(tempname1), "%s%d", name, hisnr-1);
570                 BLI_snprintf(tempname2, sizeof(tempname2), "%s%d", name, hisnr);
571         
572                 if(BLI_rename(tempname1, tempname2))
573                         BKE_report(reports, RPT_ERROR, "Unable to make version backup");
574                         
575                 hisnr--;
576         }
577
578         /* is needed when hisnr==1 */
579         BLI_snprintf(tempname1, sizeof(tempname1), "%s%d", name, hisnr);
580
581         if(BLI_rename(name, tempname1))
582                 BKE_report(reports, RPT_ERROR, "Unable to make version backup");
583 }
584
585 static ImBuf *blend_file_thumb(Scene *scene, int **thumb_pt)
586 {
587         /* will be scaled down, but gives some nice oversampling */
588         ImBuf *ibuf;
589         int *thumb;
590         char err_out[256]= "unknown";
591
592         *thumb_pt= NULL;
593         
594         if(G.background || scene->camera==NULL)
595                 return NULL;
596
597         /* gets scaled to BLEN_THUMB_SIZE */
598         ibuf= ED_view3d_draw_offscreen_imbuf_simple(scene, BLEN_THUMB_SIZE * 2, BLEN_THUMB_SIZE * 2, IB_rect, OB_SOLID, err_out);
599         
600         if(ibuf) {              
601                 float aspect= (scene->r.xsch*scene->r.xasp) / (scene->r.ysch*scene->r.yasp);
602
603                 /* dirty oversampling */
604                 IMB_scaleImBuf(ibuf, BLEN_THUMB_SIZE, BLEN_THUMB_SIZE);
605
606                 /* add pretty overlay */
607                 IMB_overlayblend_thumb(ibuf->rect, ibuf->x, ibuf->y, aspect);
608                 
609                 /* first write into thumb buffer */
610                 thumb= MEM_mallocN(((2 + (BLEN_THUMB_SIZE * BLEN_THUMB_SIZE))) * sizeof(int), "write_file thumb");
611
612                 thumb[0] = BLEN_THUMB_SIZE;
613                 thumb[1] = BLEN_THUMB_SIZE;
614
615                 memcpy(thumb + 2, ibuf->rect, BLEN_THUMB_SIZE * BLEN_THUMB_SIZE * sizeof(int));
616         }
617         else {
618                 /* '*thumb_pt' needs to stay NULL to prevent a bad thumbnail from being handled */
619                 fprintf(stderr, "blend_file_thumb failed to create thumbnail: %s\n", err_out);
620                 thumb= NULL;
621         }
622         
623         /* must be freed by caller */
624         *thumb_pt= thumb;
625         
626         return ibuf;
627 }
628
629 /* easy access from gdb */
630 int write_crash_blend(void)
631 {
632         char path[FILE_MAX];
633         BLI_strncpy(path, G.main->name, sizeof(path));
634         BLI_replace_extension(path, sizeof(path), "_crash.blend");
635         if(BLO_write_file(G.main, path, G.fileflags, NULL, NULL)) {
636                 printf("written: %s\n", path);
637                 return 1;
638         }
639         else {
640                 printf("failed: %s\n", path);
641                 return 0;
642         }
643 }
644
645 int WM_write_file(bContext *C, const char *target, int fileflags, ReportList *reports, int copy)
646 {
647         Library *li;
648         int len;
649         char di[FILE_MAX];
650
651         int *thumb= NULL;
652         ImBuf *ibuf_thumb= NULL;
653
654         len = strlen(target);
655         
656         if (len == 0) {
657                 BKE_report(reports, RPT_ERROR, "Path is empty, cannot save");
658                 return -1;
659         }
660
661         if (len >= FILE_MAX) {
662                 BKE_report(reports, RPT_ERROR, "Path too long, cannot save");
663                 return -1;
664         }
665  
666         BLI_strncpy(di, target, FILE_MAX);
667         BLI_replace_extension(di, FILE_MAX, ".blend");
668         /* dont use 'target' anymore */
669         
670         /* send the OnSave event */
671         for (li= G.main->library.first; li; li= li->id.next) {
672                 if (BLI_path_cmp(li->filepath, di) == 0) {
673                         BKE_reportf(reports, RPT_ERROR, "Can't overwrite used library '%.200s'", di);
674                         return -1;
675                 }
676         }
677
678         /* operator now handles overwrite checks */
679
680         if (G.fileflags & G_AUTOPACK) {
681                 packAll(G.main, reports);
682         }
683         
684         ED_object_exit_editmode(C, EM_DO_UNDO);
685         ED_sculpt_force_update(C);
686
687         /* don't forget not to return without! */
688         WM_cursor_wait(1);
689         
690         /* blend file thumbnail */
691         ibuf_thumb= blend_file_thumb(CTX_data_scene(C), &thumb);
692
693         /* rename to .blend1, do this as last before write */
694         do_history(di, reports);
695
696         if (BLO_write_file(CTX_data_main(C), di, fileflags, reports, thumb)) {
697                 if(!copy) {
698                         G.relbase_valid = 1;
699                         BLI_strncpy(G.main->name, di, sizeof(G.main->name));    /* is guaranteed current file */
700         
701                         G.save_over = 1; /* disable untitled.blend convention */
702                 }
703
704                 if(fileflags & G_FILE_COMPRESS) G.fileflags |= G_FILE_COMPRESS;
705                 else G.fileflags &= ~G_FILE_COMPRESS;
706                 
707                 if(fileflags & G_FILE_AUTOPLAY) G.fileflags |= G_FILE_AUTOPLAY;
708                 else G.fileflags &= ~G_FILE_AUTOPLAY;
709
710                 write_history();
711
712                 /* run this function after because the file cant be written before the blend is */
713                 if (ibuf_thumb) {
714                         ibuf_thumb= IMB_thumb_create(di, THB_NORMAL, THB_SOURCE_BLEND, ibuf_thumb);
715                         IMB_freeImBuf(ibuf_thumb);
716                 }
717
718                 if(thumb) MEM_freeN(thumb);
719         }
720         else {
721                 if(ibuf_thumb) IMB_freeImBuf(ibuf_thumb);
722                 if(thumb) MEM_freeN(thumb);
723                 
724                 WM_cursor_wait(0);
725                 return -1;
726         }
727
728         WM_cursor_wait(0);
729         
730         return 0;
731 }
732
733 /* operator entry */
734 int WM_write_homefile(bContext *C, wmOperator *op)
735 {
736         wmWindowManager *wm= CTX_wm_manager(C);
737         wmWindow *win= CTX_wm_window(C);
738         char tstr[FILE_MAXDIR+FILE_MAXFILE];
739         int fileflags;
740         
741         /* check current window and close it if temp */
742         if(win->screen->temp)
743                 wm_window_close(C, wm, win);
744         
745         BLI_make_file_string("/", tstr, BLI_get_folder_create(BLENDER_USER_CONFIG, NULL), BLENDER_STARTUP_FILE);
746         printf("trying to save homefile at %s ", tstr);
747         
748         /*  force save as regular blend file */
749         fileflags = G.fileflags & ~(G_FILE_COMPRESS | G_FILE_AUTOPLAY | G_FILE_LOCK | G_FILE_SIGN);
750
751         if(BLO_write_file(CTX_data_main(C), tstr, fileflags, op->reports, NULL) == 0) {
752                 printf("fail\n");
753                 return OPERATOR_CANCELLED;
754         }
755         
756         printf("ok\n");
757
758         G.save_over= 0;
759
760         return OPERATOR_FINISHED;
761 }
762
763 /************************ autosave ****************************/
764
765 void wm_autosave_location(char *filename)
766 {
767         char pidstr[32];
768 #ifdef WIN32
769         char *savedir;
770 #endif
771
772         BLI_snprintf(pidstr, sizeof(pidstr), "%d.blend", abs(getpid()));
773
774 #ifdef WIN32
775         /* XXX Need to investigate how to handle default location of '/tmp/'
776          * This is a relative directory on Windows, and it may be
777          * found. Example:
778          * Blender installed on D:\ drive, D:\ drive has D:\tmp\
779          * Now, BLI_exists() will find '/tmp/' exists, but
780          * BLI_make_file_string will create string that has it most likely on C:\
781          * through get_default_root().
782          * If there is no C:\tmp autosave fails. */
783         if (!BLI_exists(U.tempdir)) {
784                 savedir = BLI_get_folder_create(BLENDER_USER_AUTOSAVE, NULL);
785                 BLI_make_file_string("/", filename, savedir, pidstr);
786                 return;
787         }
788 #endif
789         
790         BLI_make_file_string("/", filename, U.tempdir, pidstr);
791 }
792
793 void WM_autosave_init(wmWindowManager *wm)
794 {
795         wm_autosave_timer_ended(wm);
796
797         if(U.flag & USER_AUTOSAVE)
798                 wm->autosavetimer= WM_event_add_timer(wm, NULL, TIMERAUTOSAVE, U.savetime*60.0);
799 }
800
801 void wm_autosave_timer(const bContext *C, wmWindowManager *wm, wmTimer *UNUSED(wt))
802 {
803         wmWindow *win;
804         wmEventHandler *handler;
805         char filename[FILE_MAX];
806         int fileflags;
807
808         WM_event_remove_timer(wm, NULL, wm->autosavetimer);
809
810         /* if a modal operator is running, don't autosave, but try again in 10 seconds */
811         for(win=wm->windows.first; win; win=win->next) {
812                 for(handler=win->modalhandlers.first; handler; handler=handler->next) {
813                         if(handler->op) {
814                                 wm->autosavetimer= WM_event_add_timer(wm, NULL, TIMERAUTOSAVE, 10.0);
815                                 return;
816                         }
817                 }
818         }
819         
820         wm_autosave_location(filename);
821
822         /*  force save as regular blend file */
823         fileflags = G.fileflags & ~(G_FILE_COMPRESS|G_FILE_AUTOPLAY |G_FILE_LOCK|G_FILE_SIGN);
824
825         /* no error reporting to console */
826         BLO_write_file(CTX_data_main(C), filename, fileflags, NULL, NULL);
827
828         /* do timer after file write, just in case file write takes a long time */
829         wm->autosavetimer= WM_event_add_timer(wm, NULL, TIMERAUTOSAVE, U.savetime*60.0);
830 }
831
832 void wm_autosave_timer_ended(wmWindowManager *wm)
833 {
834         if(wm->autosavetimer) {
835                 WM_event_remove_timer(wm, NULL, wm->autosavetimer);
836                 wm->autosavetimer= NULL;
837         }
838 }
839
840 void wm_autosave_delete(void)
841 {
842         char filename[FILE_MAX];
843         
844         wm_autosave_location(filename);
845
846         if(BLI_exists(filename)) {
847                 char str[FILE_MAXDIR+FILE_MAXFILE];
848                 BLI_make_file_string("/", str, U.tempdir, "quit.blend");
849
850                 /* if global undo; remove tempsave, otherwise rename */
851                 if(U.uiflag & USER_GLOBALUNDO) BLI_delete(filename, 0, 0);
852                 else BLI_rename(filename, str);
853         }
854 }
855
856 void wm_autosave_read(bContext *C, ReportList *reports)
857 {
858         char filename[FILE_MAX];
859
860         wm_autosave_location(filename);
861         WM_read_file(C, filename, reports);
862 }
863