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