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