Merge with trunk, revision 28446 - 28528.
[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         /* placed up here because of crappy
29          * winsock stuff.
30          */
31 #include <stdio.h>
32 #include <string.h>
33
34 #ifdef WIN32
35 #include <windows.h> /* need to include windows.h so _WIN32_IE is defined  */
36 #ifndef _WIN32_IE
37 #define _WIN32_IE 0x0400 /* minimal requirements for SHGetSpecialFolderPath on MINGW MSVC has this defined already */
38 #endif
39 #include <shlobj.h> /* for SHGetSpecialFolderPath, has to be done before BLI_winstuff because 'near' is disabled through BLI_windstuff */
40 #include <process.h> /* getpid */
41 #include "BLI_winstuff.h"
42 #else
43 #include <unistd.h> /* getpid */
44 #endif
45
46 #include "MEM_guardedalloc.h"
47 #include "MEM_CacheLimiterC-Api.h"
48
49 #include "BLI_blenlib.h"
50 #include "BLI_linklist.h"
51
52 #include "DNA_anim_types.h"
53 #include "DNA_ipo_types.h" // XXX old animation system
54 #include "DNA_object_types.h"
55 #include "DNA_space_types.h"
56 #include "DNA_userdef_types.h"
57 #include "DNA_scene_types.h"
58 #include "DNA_screen_types.h"
59 #include "DNA_windowmanager_types.h"
60
61 #include "BKE_blender.h"
62 #include "BKE_context.h"
63 #include "BKE_DerivedMesh.h"
64 #include "BKE_exotic.h"
65 #include "BKE_font.h"
66 #include "BKE_global.h"
67 #include "BKE_library.h"
68 #include "BKE_main.h"
69 #include "BKE_packedFile.h"
70 #include "BKE_report.h"
71 #include "BKE_sound.h"
72 #include "BKE_texture.h"
73 #include "BKE_utildefines.h"
74
75 #include "BLO_readfile.h"
76 #include "BLO_writefile.h"
77
78 #include "RNA_access.h"
79
80 #include "ED_datafiles.h"
81 #include "ED_object.h"
82 #include "ED_screen.h"
83 #include "ED_sculpt.h"
84 #include "ED_util.h"
85
86 #include "GHOST_C-api.h"
87
88 #include "UI_interface.h"
89
90 #include "GPU_draw.h"
91
92 #include "BPY_extern.h"
93
94 #include "WM_api.h"
95 #include "WM_types.h"
96 #include "wm.h"
97 #include "wm_window.h"
98 #include "wm_event_system.h"
99
100 static void writeBlog(void);
101
102 /* To be able to read files without windows closing, opening, moving 
103    we try to prepare for worst case:
104    - active window gets active screen from file 
105    - restoring the screens from non-active windows 
106    Best case is all screens match, in that case they get assigned to proper window  
107 */
108 static void wm_window_match_init(bContext *C, ListBase *wmlist)
109 {
110         wmWindowManager *wm= G.main->wm.first;
111         wmWindow *win, *active_win;
112         
113         *wmlist= G.main->wm;
114         G.main->wm.first= G.main->wm.last= NULL;
115         
116         active_win = CTX_wm_window(C);
117
118         /* first wrap up running stuff */
119         /* code copied from wm_init_exit.c */
120         for(wm= wmlist->first; wm; wm= wm->id.next) {
121                 
122                 WM_jobs_stop_all(wm);
123                 
124                 for(win= wm->windows.first; win; win= win->next) {
125                 
126                         CTX_wm_window_set(C, win);      /* needed by operator close callbacks */
127                         WM_event_remove_handlers(C, &win->handlers);
128                         WM_event_remove_handlers(C, &win->modalhandlers);
129                         ED_screen_exit(C, win, win->screen);
130                 }
131         }
132         
133         /* reset active window */
134         CTX_wm_window_set(C, active_win);
135
136         ED_editors_exit(C);
137         
138 return; 
139         if(wm==NULL) return;
140         if(G.fileflags & G_FILE_NO_UI) return;
141         
142         /* we take apart the used screens from non-active window */
143         for(win= wm->windows.first; win; win= win->next) {
144                 BLI_strncpy(win->screenname, win->screen->id.name, MAX_ID_NAME);
145                 if(win!=wm->winactive) {
146                         BLI_remlink(&G.main->screen, win->screen);
147                         //BLI_addtail(screenbase, win->screen);
148                 }
149         }
150 }
151
152 /* match old WM with new, 4 cases:
153   1- no current wm, no read wm: make new default
154   2- no current wm, but read wm: that's OK, do nothing
155   3- current wm, but not in file: try match screen names
156   4- current wm, and wm in file: try match ghostwin 
157 */
158
159 static void wm_window_match_do(bContext *C, ListBase *oldwmlist)
160 {
161         wmWindowManager *oldwm, *wm;
162         wmWindow *oldwin, *win;
163         
164         /* cases 1 and 2 */
165         if(oldwmlist->first==NULL) {
166                 if(G.main->wm.first); /* nothing todo */
167                 else
168                         wm_add_default(C);
169         }
170         else {
171                 /* cases 3 and 4 */
172                 
173                 /* we've read file without wm..., keep current one entirely alive */
174                 if(G.main->wm.first==NULL) {
175                         bScreen *screen= CTX_wm_screen(C);
176                         
177                         /* match oldwm to new dbase, only old files */
178                         
179                         for(wm= oldwmlist->first; wm; wm= wm->id.next) {
180                                 
181                                 for(win= wm->windows.first; win; win= win->next) {
182                                         /* all windows get active screen from file */
183                                         if(screen->winid==0)
184                                                 win->screen= screen;
185                                         else 
186                                                 win->screen= ED_screen_duplicate(win, screen);
187                                         
188                                         BLI_strncpy(win->screenname, win->screen->id.name+2, 21);
189                                         win->screen->winid= win->winid;
190                                 }
191                         }
192                         
193                         G.main->wm= *oldwmlist;
194                         
195                         /* screens were read from file! */
196                         ED_screens_initialize(G.main->wm.first);
197                 }
198                 else {
199                         /* what if old was 3, and loaded 1? */
200                         /* this code could move to setup_appdata */
201                         oldwm= oldwmlist->first;
202                         wm= G.main->wm.first;
203
204                         /* ensure making new keymaps and set space types */
205                         wm->initialized= 0;
206                         wm->winactive= NULL;
207                         
208                         /* only first wm in list has ghostwins */
209                         for(win= wm->windows.first; win; win= win->next) {
210                                 for(oldwin= oldwm->windows.first; oldwin; oldwin= oldwin->next) {
211                                         
212                                         if(oldwin->winid == win->winid ) {
213                                                 win->ghostwin= oldwin->ghostwin;
214                                                 win->active= oldwin->active;
215                                                 if(win->active)
216                                                         wm->winactive= win;
217
218                                                 GHOST_SetWindowUserData(win->ghostwin, win);    /* pointer back */
219                                                 oldwin->ghostwin= NULL;
220                                                 
221                                                 win->eventstate= oldwin->eventstate;
222                                                 oldwin->eventstate= NULL;
223                                                 
224                                                 /* ensure proper screen rescaling */
225                                                 win->sizex= oldwin->sizex;
226                                                 win->sizey= oldwin->sizey;
227                                                 win->posx= oldwin->posx;
228                                                 win->posy= oldwin->posy;
229                                         }
230                                 }
231                         }
232                         wm_close_and_free_all(C, oldwmlist);
233                 }
234         }
235 }
236
237 /* in case UserDef was read, we re-initialize all, and do versioning */
238 static void wm_init_userdef(bContext *C)
239 {
240         extern char btempdir[];
241
242         UI_init_userdef();
243         MEM_CacheLimiter_set_maximum(U.memcachelimit * 1024 * 1024);
244         sound_init(CTX_data_main(C));
245
246         /* set the python auto-execute setting from user prefs */
247         /* disabled by default, unless explicitly enabled in the command line */
248         if ((U.flag & USER_SCRIPT_AUTOEXEC_DISABLE) == 0) G.f |=  G_SCRIPT_AUTOEXEC;
249
250         if(U.tempdir[0]) strncpy(btempdir, U.tempdir, FILE_MAXDIR+FILE_MAXFILE);
251 }
252
253 void WM_read_file(bContext *C, char *name, ReportList *reports)
254 {
255         int retval;
256
257         /* first try to append data from exotic file formats... */
258         /* it throws error box when file doesnt exist and returns -1 */
259         /* note; it should set some error message somewhere... (ton) */
260         retval= BKE_read_exotic(CTX_data_scene(C), name);
261         
262         /* we didn't succeed, now try to read Blender file */
263         if (retval== 0) {
264                 int G_f= G.f;
265                 ListBase wmbase;
266
267                 /* put aside screens to match with persistant windows later */
268                 /* also exit screens and editors */
269                 wm_window_match_init(C, &wmbase); 
270                 
271                 retval= BKE_read_file(C, name, NULL, reports);
272                 G.save_over = 1;
273
274                 /* this flag is initialized by the operator but overwritten on read.
275                  * need to re-enable it here else drivers + registered scripts wont work. */
276                 if(G_f & G_SCRIPT_AUTOEXEC) G.f |= G_SCRIPT_AUTOEXEC;
277                 else                                            G.f &= ~G_SCRIPT_AUTOEXEC;
278
279                 /* match the read WM with current WM */
280                 wm_window_match_do(C, &wmbase);
281                 WM_check(C); /* opens window(s), checks keymaps */
282                 
283 // XXX          mainwindow_set_filename_to_title(G.main->name);
284
285                 if(retval==2) wm_init_userdef(C);       // in case a userdef is read from regular .blend
286                 
287                 if (retval!=0) {
288                         G.relbase_valid = 1;
289                         writeBlog();
290                 }
291
292 // XXX          undo_editmode_clear();
293                 BKE_reset_undo();
294                 BKE_write_undo(C, "original");  /* save current state */
295
296                 WM_event_add_notifier(C, NC_WM|ND_FILEREAD, NULL);
297 //              refresh_interface_font();
298
299                 CTX_wm_window_set(C, CTX_wm_manager(C)->windows.first);
300                 ED_editors_init(C);
301
302 #ifndef DISABLE_PYTHON
303                 /* run any texts that were loaded in and flagged as modules */
304                 BPY_load_user_modules(C);
305 #endif
306                 CTX_wm_window_set(C, NULL); /* exits queues */
307         }
308         else if(retval==1)
309                 BKE_write_undo(C, "Import file");
310         else if(retval == -1) {
311                 if(reports)
312                         BKE_reportf(reports, RPT_ERROR, "Can't read file \"%s\".", name);
313         }
314 }
315
316
317 /* called on startup,  (context entirely filled with NULLs) */
318 /* or called for 'New File' */
319 /* op can be NULL */
320 int WM_read_homefile(bContext *C, wmOperator *op)
321 {
322         ListBase wmbase;
323         char tstr[FILE_MAXDIR+FILE_MAXFILE], scestr[FILE_MAXDIR];
324         char *home= BLI_gethome();
325         int from_memory= op?RNA_boolean_get(op->ptr, "factory"):0;
326         int success;
327                 
328         BLI_clean(home);
329         
330         free_ttfont(); /* still weird... what does it here? */
331                 
332         G.relbase_valid = 0;
333         if (!from_memory) {
334                 BLI_make_file_string(G.sce, tstr, home, ".B25.blend");
335         }
336         strcpy(scestr, G.sce);  /* temporary store */
337         
338         /* prevent loading no UI */
339         G.fileflags &= ~G_FILE_NO_UI;
340         
341         /* put aside screens to match with persistant windows later */
342         wm_window_match_init(C, &wmbase); 
343         
344         if (!from_memory && BLI_exists(tstr)) {
345                 success = BKE_read_file(C, tstr, NULL, NULL);
346         } else {
347                 success = BKE_read_file_from_memory(C, datatoc_B_blend, datatoc_B_blend_size, NULL, NULL);
348                 if (wmbase.first == NULL) wm_clear_default_size(C);
349         }
350         
351         /* match the read WM with current WM */
352         wm_window_match_do(C, &wmbase); 
353         WM_check(C); /* opens window(s), checks keymaps */
354
355         strcpy(G.sce, scestr); /* restore */
356         
357         wm_init_userdef(C);
358         
359         /* When loading factory settings, the reset solid OpenGL lights need to be applied. */
360         if (!G.background) GPU_default_lights();
361         
362         /* XXX */
363         G.save_over = 0;        // start with save preference untitled.blend
364         G.fileflags &= ~G_FILE_AUTOPLAY;        /*  disable autoplay in .B.blend... */
365 //      mainwindow_set_filename_to_title("");   // empty string re-initializes title to "Blender"
366         
367 //      refresh_interface_font();
368         
369 //      undo_editmode_clear();
370         BKE_reset_undo();
371         BKE_write_undo(C, "original");  /* save current state */
372
373         ED_editors_init(C);
374         
375         WM_event_add_notifier(C, NC_WM|ND_FILEREAD, NULL);
376         CTX_wm_window_set(C, NULL); /* exits queues */
377
378         return OPERATOR_FINISHED;
379 }
380
381
382 void read_Blog(void)
383 {
384         char name[FILE_MAX];
385         LinkNode *l, *lines;
386         struct RecentFile *recent;
387         char *line;
388         int num;
389
390         BLI_make_file_string("/", name, BLI_gethome(), ".Blog");
391         lines= BLI_read_file_as_lines(name);
392
393         G.recent_files.first = G.recent_files.last = NULL;
394
395         /* read list of recent opend files from .Blog to memory */
396         for (l= lines, num= 0; l && (num<U.recent_files); l= l->next) {
397                 line = l->link;
398                 if (line[0] && BLI_exists(line)) {
399                         if (num==0) 
400                                 strcpy(G.sce, line); /* note: this seems highly dodgy since the file isnt actually read. please explain. - campbell */
401                         
402                         recent = (RecentFile*)MEM_mallocN(sizeof(RecentFile),"RecentFile");
403                         BLI_addtail(&(G.recent_files), recent);
404                         recent->filename = (char*)MEM_mallocN(sizeof(char)*(strlen(line)+1), "name of file");
405                         recent->filename[0] = '\0';
406                         
407                         strcpy(recent->filename, line);
408                         num++;
409                 }
410         }
411
412         if(G.sce[0] == 0)
413                 BLI_make_file_string("/", G.sce, BLI_gethome(), "untitled.blend");
414         
415         BLI_free_file_lines(lines);
416
417 }
418
419 static void writeBlog(void)
420 {
421         struct RecentFile *recent, *next_recent;
422         char name[FILE_MAXDIR+FILE_MAXFILE];
423         FILE *fp;
424         int i;
425
426         BLI_make_file_string("/", name, BLI_gethome(), ".Blog");
427
428         recent = G.recent_files.first;
429         /* refresh .Blog of recent opened files, when current file was changed */
430         if(!(recent) || (strcmp(recent->filename, G.sce)!=0)) {
431                 fp= fopen(name, "w");
432                 if (fp) {
433                         /* add current file to the beginning of list */
434                         recent = (RecentFile*)MEM_mallocN(sizeof(RecentFile),"RecentFile");
435                         recent->filename = (char*)MEM_mallocN(sizeof(char)*(strlen(G.sce)+1), "name of file");
436                         recent->filename[0] = '\0';
437                         strcpy(recent->filename, G.sce);
438                         BLI_addhead(&(G.recent_files), recent);
439                         /* write current file to .Blog */
440                         fprintf(fp, "%s\n", recent->filename);
441                         recent = recent->next;
442                         i=1;
443                         /* write rest of recent opened files to .Blog */
444                         while((i<U.recent_files) && (recent)){
445                                 /* this prevents to have duplicities in list */
446                                 if (strcmp(recent->filename, G.sce)!=0) {
447                                         fprintf(fp, "%s\n", recent->filename);
448                                         recent = recent->next;
449                                 }
450                                 else {
451                                         next_recent = recent->next;
452                                         MEM_freeN(recent->filename);
453                                         BLI_freelinkN(&(G.recent_files), recent);
454                                         recent = next_recent;
455                                 }
456                                 i++;
457                         }
458                         fclose(fp);
459                 }
460         }
461 }
462
463 static void do_history(char *name, ReportList *reports)
464 {
465         char tempname1[FILE_MAXDIR+FILE_MAXFILE], tempname2[FILE_MAXDIR+FILE_MAXFILE];
466         int hisnr= U.versions;
467         
468         if(U.versions==0) return;
469         if(strlen(name)<2) return;
470                 
471         while(hisnr > 1) {
472                 sprintf(tempname1, "%s%d", name, hisnr-1);
473                 sprintf(tempname2, "%s%d", name, hisnr);
474         
475                 if(BLI_rename(tempname1, tempname2))
476                         BKE_report(reports, RPT_ERROR, "Unable to make version backup");
477                         
478                 hisnr--;
479         }
480                 
481         /* is needed when hisnr==1 */
482         sprintf(tempname1, "%s%d", name, hisnr);
483         
484         if(BLI_rename(name, tempname1))
485                 BKE_report(reports, RPT_ERROR, "Unable to make version backup");
486 }
487
488 int WM_write_file(bContext *C, char *target, int fileflags, ReportList *reports)
489 {
490         Library *li;
491         int len;
492         char di[FILE_MAX];
493         
494         len = strlen(target);
495         
496         if (len == 0) {
497                 BKE_report(reports, RPT_ERROR, "Path is empty, cannot save");
498                 return -1;
499         }
500
501         if (len >= FILE_MAX) {
502                 BKE_report(reports, RPT_ERROR, "Path too long, cannot save");
503                 return -1;
504         }
505  
506         /* send the OnSave event */
507         for (li= G.main->library.first; li; li= li->id.next) {
508                 if (BLI_streq(li->name, target)) {
509                         BKE_report(reports, RPT_ERROR, "Cannot overwrite used library");
510                         return -1;
511                 }
512         }
513         
514         if (!BLO_has_bfile_extension(target) && (len+6 < FILE_MAX)) {
515                 sprintf(di, "%s.blend", target);
516         } else {
517                 strcpy(di, target);
518         }
519
520 //      if (BLI_exists(di)) {
521 // XXX          if(!saveover(di))
522 // XXX                  return; 
523 //      }
524         
525         if (G.fileflags & G_AUTOPACK) {
526                 packAll(G.main, reports);
527         }
528         
529         ED_object_exit_editmode(C, EM_DO_UNDO);
530         ED_sculpt_force_update(C);
531
532         do_history(di, reports);
533         
534         if (BLO_write_file(CTX_data_main(C), di, fileflags, reports)) {
535                 strcpy(G.sce, di);
536                 G.relbase_valid = 1;
537                 strcpy(G.main->name, di);       /* is guaranteed current file */
538
539                 G.save_over = 1; /* disable untitled.blend convention */
540
541                 if(fileflags & G_FILE_COMPRESS) G.fileflags |= G_FILE_COMPRESS;
542                 else G.fileflags &= ~G_FILE_COMPRESS;
543                 
544                 if(fileflags & G_FILE_AUTOPLAY) G.fileflags |= G_FILE_AUTOPLAY;
545                 else G.fileflags &= ~G_FILE_AUTOPLAY;
546
547                 writeBlog();
548         } else {
549                 return -1;
550         }
551
552 // XXX  waitcursor(0);
553         return 0;
554 }
555
556 /* operator entry */
557 int WM_write_homefile(bContext *C, wmOperator *op)
558 {
559         wmWindowManager *wm= CTX_wm_manager(C);
560         wmWindow *win= CTX_wm_window(C);
561         char tstr[FILE_MAXDIR+FILE_MAXFILE];
562         int fileflags;
563         
564         /* check current window and close it if temp */
565         if(win->screen->full == SCREENTEMP)
566                 wm_window_close(C, wm, win);
567         
568         BLI_make_file_string("/", tstr, BLI_gethome(), ".B25.blend");
569         
570         /*  force save as regular blend file */
571         fileflags = G.fileflags & ~(G_FILE_COMPRESS | G_FILE_AUTOPLAY | G_FILE_LOCK | G_FILE_SIGN);
572
573         BLO_write_file(CTX_data_main(C), tstr, fileflags, op->reports);
574         
575         G.save_over= 0;
576         
577         return OPERATOR_FINISHED;
578 }
579
580 /************************ autosave ****************************/
581
582 void wm_autosave_location(char *filename)
583 {
584         char pidstr[32];
585 #ifdef WIN32
586         char subdir[9];
587         char savedir[FILE_MAXDIR];
588 #endif
589
590         sprintf(pidstr, "%d.blend", abs(getpid()));
591         
592 #ifdef WIN32
593         if (!BLI_exists(U.tempdir)) {
594                 BLI_strncpy(subdir, "autosave", sizeof(subdir));
595                 BLI_make_file_string("/", savedir, BLI_gethome(), subdir);
596                 
597                 /* create a new autosave dir
598                  * function already checks for existence or not */
599                 BLI_recurdir_fileops(savedir);
600         
601                 BLI_make_file_string("/", filename, savedir, pidstr);
602                 return;
603         }
604 #endif
605         
606         BLI_make_file_string("/", filename, U.tempdir, pidstr);
607 }
608
609 void WM_autosave_init(wmWindowManager *wm)
610 {
611         wm_autosave_timer_ended(wm);
612
613         if(U.flag & USER_AUTOSAVE)
614                 wm->autosavetimer= WM_event_add_timer(wm, NULL, TIMERAUTOSAVE, U.savetime*60.0);
615 }
616
617 void wm_autosave_timer(const bContext *C, wmWindowManager *wm, wmTimer *wt)
618 {
619         wmWindow *win;
620         wmEventHandler *handler;
621         char filename[FILE_MAX];
622         int fileflags;
623
624         WM_event_remove_timer(wm, NULL, wm->autosavetimer);
625
626         /* if a modal operator is running, don't autosave, but try again in 10 seconds */
627         for(win=wm->windows.first; win; win=win->next) {
628                 for(handler=win->modalhandlers.first; handler; handler=handler->next) {
629                         if(handler->op) {
630                                 wm->autosavetimer= WM_event_add_timer(wm, NULL, TIMERAUTOSAVE, 10.0);
631                                 return;
632                         }
633                 }
634         }
635         
636         wm_autosave_location(filename);
637
638         /*  force save as regular blend file */
639         fileflags = G.fileflags & ~(G_FILE_COMPRESS|G_FILE_AUTOPLAY |G_FILE_LOCK|G_FILE_SIGN);
640
641         /* no error reporting to console */
642         BLO_write_file(CTX_data_main(C), filename, fileflags, NULL);
643
644         /* do timer after file write, just in case file write takes a long time */
645         wm->autosavetimer= WM_event_add_timer(wm, NULL, TIMERAUTOSAVE, U.savetime*60.0);
646 }
647
648 void wm_autosave_timer_ended(wmWindowManager *wm)
649 {
650         if(wm->autosavetimer) {
651                 WM_event_remove_timer(wm, NULL, wm->autosavetimer);
652                 wm->autosavetimer= NULL;
653         }
654 }
655
656 void wm_autosave_delete(void)
657 {
658         char filename[FILE_MAX];
659         
660         wm_autosave_location(filename);
661
662         if(BLI_exists(filename)) {
663                 char str[FILE_MAXDIR+FILE_MAXFILE];
664                 BLI_make_file_string("/", str, U.tempdir, "quit.blend");
665
666                 /* if global undo; remove tempsave, otherwise rename */
667                 if(U.uiflag & USER_GLOBALUNDO) BLI_delete(filename, 0, 0);
668                 else BLI_rename(filename, str);
669         }
670 }
671
672 void wm_autosave_read(bContext *C, ReportList *reports)
673 {
674         char filename[FILE_MAX];
675
676         wm_autosave_location(filename);
677         WM_read_file(C, filename, reports);
678 }
679