Merge from trunk -r 22040:23000.
[blender.git] / source / blender / windowmanager / intern / wm_files.c
1 /**
2  * $Id: wm_files.c
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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, 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 "BLI_winstuff.h"
41 #include <process.h> /* getpid */
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 #include "RNA_define.h"
80
81 #include "ED_datafiles.h"
82 #include "ED_object.h"
83 #include "ED_screen.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 // XXX #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
99 static void writeBlog(void);
100
101 /* To be able to read files without windows closing, opening, moving 
102    we try to prepare for worst case:
103    - active window gets active screen from file 
104    - restoring the screens from non-active windows 
105    Best case is all screens match, in that case they get assigned to proper window  
106 */
107 static void wm_window_match_init(bContext *C, ListBase *wmlist)
108 {
109         wmWindowManager *wm= G.main->wm.first;
110         wmWindow *win;
111         
112         *wmlist= G.main->wm;
113         G.main->wm.first= G.main->wm.last= NULL;
114         
115         /* first wrap up running stuff */
116         /* code copied from wm_init_exit.c */
117         for(wm= wmlist->first; wm; wm= wm->id.next) {
118                 
119                 WM_jobs_stop_all(wm);
120                 
121                 for(win= wm->windows.first; win; win= win->next) {
122                 
123                         CTX_wm_window_set(C, win);      /* needed by operator close callbacks */
124                         ED_screen_exit(C, win, win->screen);
125                 }
126         }
127         
128         ED_editors_exit(C);
129         
130 return; 
131         if(wm==NULL) return;
132         if(G.fileflags & G_FILE_NO_UI) return;
133         
134         /* we take apart the used screens from non-active window */
135         for(win= wm->windows.first; win; win= win->next) {
136                 BLI_strncpy(win->screenname, win->screen->id.name, MAX_ID_NAME);
137                 if(win!=wm->winactive) {
138                         BLI_remlink(&G.main->screen, win->screen);
139                         //BLI_addtail(screenbase, win->screen);
140                 }
141         }
142 }
143
144 /* match old WM with new, 4 cases:
145   1- no current wm, no read wm: make new default
146   2- no current wm, but read wm: that's OK, do nothing
147   3- current wm, but not in file: try match screen names
148   4- current wm, and wm in file: try match ghostwin 
149 */
150
151 static void wm_window_match_do(bContext *C, ListBase *oldwmlist)
152 {
153         wmWindowManager *oldwm, *wm;
154         wmWindow *oldwin, *win;
155         
156         /* cases 1 and 2 */
157         if(oldwmlist->first==NULL) {
158                 if(G.main->wm.first); /* nothing todo */
159                 else
160                         wm_add_default(C);
161         }
162         else {
163                 /* cases 3 and 4 */
164                 
165                 /* we've read file without wm..., keep current one entirely alive */
166                 if(G.main->wm.first==NULL) {
167                         bScreen *screen= CTX_wm_screen(C);
168                         
169                         /* match oldwm to new dbase, only old files */
170                         
171                         for(wm= oldwmlist->first; wm; wm= wm->id.next) {
172                                 
173                                 for(win= wm->windows.first; win; win= win->next) {
174                                         /* all windows get active screen from file */
175                                         if(screen->winid==0)
176                                                 win->screen= screen;
177                                         else 
178                                                 win->screen= ED_screen_duplicate(win, screen);
179                                         
180                                         BLI_strncpy(win->screenname, win->screen->id.name+2, 21);
181                                         win->screen->winid= win->winid;
182                                 }
183                         }
184                         
185                         G.main->wm= *oldwmlist;
186                         
187                         /* screens were read from file! */
188                         ED_screens_initialize(G.main->wm.first);
189                 }
190                 else {
191                         /* what if old was 3, and loaded 1? */
192                         /* this code could move to setup_appdata */
193                         oldwm= oldwmlist->first;
194                         wm= G.main->wm.first;
195
196                         /* ensure making new keymaps and set space types */
197                         wm->initialized= 0;
198                         
199                         /* only first wm in list has ghostwins */
200                         for(win= wm->windows.first; win; win= win->next) {
201                                 for(oldwin= oldwm->windows.first; oldwin; oldwin= oldwin->next) {
202                                         
203                                         if(oldwin->winid == win->winid ) {
204                                                 win->ghostwin= oldwin->ghostwin;
205                                                 GHOST_SetWindowUserData(win->ghostwin, win);    /* pointer back */
206                                                 oldwin->ghostwin= NULL;
207                                                 
208                                                 win->eventstate= oldwin->eventstate;
209                                                 oldwin->eventstate= NULL;
210                                                 
211                                                 /* ensure proper screen rescaling */
212                                                 win->sizex= oldwin->sizex;
213                                                 win->sizey= oldwin->sizey;
214                                                 win->posx= oldwin->posx;
215                                                 win->posy= oldwin->posy;
216                                         }
217                                 }
218                         }
219                         wm_close_and_free_all(C, oldwmlist);
220                 }
221         }
222 }
223
224 /* in case UserDef was read, we re-initialize all, and do versioning */
225 static void wm_init_userdef()
226 {
227         UI_init_userdef();
228         MEM_CacheLimiter_set_maximum(U.memcachelimit * 1024 * 1024);
229         sound_init();
230 }
231
232 void WM_read_file(bContext *C, char *name, ReportList *reports)
233 {
234         int retval;
235
236         /* first try to append data from exotic file formats... */
237         /* it throws error box when file doesnt exist and returns -1 */
238         /* note; it should set some error message somewhere... (ton) */
239         retval= BKE_read_exotic(CTX_data_scene(C), name);
240         
241         /* we didn't succeed, now try to read Blender file */
242         if (retval== 0) {
243                 ListBase wmbase;
244
245                 /* put aside screens to match with persistant windows later */
246                 /* also exit screens and editors */
247                 wm_window_match_init(C, &wmbase); 
248                 
249                 retval= BKE_read_file(C, name, NULL, reports);
250                 G.save_over = 1;
251
252                 /* match the read WM with current WM */
253                 wm_window_match_do(C, &wmbase); 
254                 wm_check(C); /* opens window(s), checks keymaps */
255                 
256 // XXX          mainwindow_set_filename_to_title(G.main->name);
257
258                 if(retval==2) wm_init_userdef();        // in case a userdef is read from regular .blend
259                 
260                 if (retval!=0) {
261                         G.relbase_valid = 1;
262                         writeBlog();
263                 }
264
265 // XXX          undo_editmode_clear();
266                 BKE_reset_undo();
267                 BKE_write_undo(C, "original");  /* save current state */
268
269                 WM_event_add_notifier(C, NC_WM|ND_FILEREAD, NULL);
270 //              refresh_interface_font();
271                                            
272                 CTX_wm_window_set(C, NULL); /* exits queues */
273         }
274         else if(retval==1)
275                 BKE_write_undo(C, "Import file");
276         else if(retval == -1) {
277                 if(reports && reports->list.first == NULL)
278                         BKE_report(reports, RPT_ERROR, "Cannot read file.");
279         }
280 }
281
282
283 /* called on startup,  (context entirely filled with NULLs) */
284 /* or called for 'Erase All' */
285 /* op can be NULL */
286 int WM_read_homefile(bContext *C, wmOperator *op)
287 {
288         ListBase wmbase;
289         char tstr[FILE_MAXDIR+FILE_MAXFILE], scestr[FILE_MAXDIR];
290         char *home= BLI_gethome();
291         int from_memory= op?RNA_boolean_get(op->ptr, "factory"):0;
292         int success;
293                 
294         BLI_clean(home);
295         
296         free_ttfont(); /* still weird... what does it here? */
297                 
298         G.relbase_valid = 0;
299         if (!from_memory) {
300                 BLI_make_file_string(G.sce, tstr, home, ".B25.blend");
301         }
302         strcpy(scestr, G.sce);  /* temporary store */
303         
304         /* prevent loading no UI */
305         G.fileflags &= ~G_FILE_NO_UI;
306         
307         /* put aside screens to match with persistant windows later */
308         wm_window_match_init(C, &wmbase); 
309         
310         if (!from_memory && BLI_exists(tstr)) {
311                 success = BKE_read_file(C, tstr, NULL, NULL);
312         } else {
313                 success = BKE_read_file_from_memory(C, datatoc_B_blend, datatoc_B_blend_size, NULL, NULL);
314                 if (wmbase.first == NULL) wm_clear_default_size(C);
315         }
316         
317         /* match the read WM with current WM */
318         wm_window_match_do(C, &wmbase); 
319         wm_check(C); /* opens window(s), checks keymaps */
320
321         strcpy(G.sce, scestr); /* restore */
322         
323         wm_init_userdef();
324         
325         /* When loading factory settings, the reset solid OpenGL lights need to be applied. */
326         GPU_default_lights();
327         
328         /* XXX */
329         G.save_over = 0;        // start with save preference untitled.blend
330         G.fileflags &= ~G_FILE_AUTOPLAY;        /*  disable autoplay in .B.blend... */
331 //      mainwindow_set_filename_to_title("");   // empty string re-initializes title to "Blender"
332         
333 //      refresh_interface_font();
334         
335 //      undo_editmode_clear();
336         BKE_reset_undo();
337         BKE_write_undo(C, "original");  /* save current state */
338         
339         WM_event_add_notifier(C, NC_WM|ND_FILEREAD, NULL);
340         CTX_wm_window_set(C, NULL); /* exits queues */
341
342         return OPERATOR_FINISHED;
343 }
344
345
346 static void get_autosave_location(char buf[FILE_MAXDIR+FILE_MAXFILE])
347 {
348         char pidstr[32];
349 #ifdef WIN32
350         char subdir[9];
351         char savedir[FILE_MAXDIR];
352 #endif
353
354         sprintf(pidstr, "%d.blend", abs(getpid()));
355         
356 #ifdef WIN32
357         if (!BLI_exists(U.tempdir)) {
358                 BLI_strncpy(subdir, "autosave", sizeof(subdir));
359                 BLI_make_file_string("/", savedir, BLI_gethome(), subdir);
360                 
361                 /* create a new autosave dir
362                  * function already checks for existence or not */
363                 BLI_recurdir_fileops(savedir);
364         
365                 BLI_make_file_string("/", buf, savedir, pidstr);
366                 return;
367         }
368 #endif
369         
370         BLI_make_file_string("/", buf, U.tempdir, pidstr);
371 }
372
373 void WM_read_autosavefile(bContext *C)
374 {
375         char tstr[FILE_MAX], scestr[FILE_MAX];
376         int save_over;
377
378         BLI_strncpy(scestr, G.sce, FILE_MAX);   /* temporal store */
379         
380         get_autosave_location(tstr);
381
382         save_over = G.save_over;
383         BKE_read_file(C, tstr, NULL, NULL);
384         G.save_over = save_over;
385         BLI_strncpy(G.sce, scestr, FILE_MAX);
386 }
387
388
389 void read_Blog(void)
390 {
391         char name[FILE_MAX];
392         LinkNode *l, *lines;
393         struct RecentFile *recent;
394         char *line;
395         int num;
396
397         BLI_make_file_string("/", name, BLI_gethome(), ".Blog");
398         lines= BLI_read_file_as_lines(name);
399
400         G.recent_files.first = G.recent_files.last = NULL;
401
402         /* read list of recent opend files from .Blog to memory */
403         for (l= lines, num= 0; l && (num<U.recent_files); l= l->next, num++) {
404                 line = l->link;
405                 if (!BLI_streq(line, "")) {
406                         if (num==0) 
407                                 strcpy(G.sce, line);
408                         
409                         recent = (RecentFile*)MEM_mallocN(sizeof(RecentFile),"RecentFile");
410                         BLI_addtail(&(G.recent_files), recent);
411                         recent->filename = (char*)MEM_mallocN(sizeof(char)*(strlen(line)+1), "name of file");
412                         recent->filename[0] = '\0';
413                         
414                         strcpy(recent->filename, line);
415                 }
416         }
417
418         if(G.sce[0] == 0)
419                 BLI_make_file_string("/", G.sce, BLI_gethome(), "untitled.blend");
420         
421         BLI_free_file_lines(lines);
422
423 }
424
425 static void writeBlog(void)
426 {
427         struct RecentFile *recent, *next_recent;
428         char name[FILE_MAXDIR+FILE_MAXFILE];
429         FILE *fp;
430         int i;
431
432         BLI_make_file_string("/", name, BLI_gethome(), ".Blog");
433
434         recent = G.recent_files.first;
435         /* refresh .Blog of recent opened files, when current file was changed */
436         if(!(recent) || (strcmp(recent->filename, G.sce)!=0)) {
437                 fp= fopen(name, "w");
438                 if (fp) {
439                         /* add current file to the beginning of list */
440                         recent = (RecentFile*)MEM_mallocN(sizeof(RecentFile),"RecentFile");
441                         recent->filename = (char*)MEM_mallocN(sizeof(char)*(strlen(G.sce)+1), "name of file");
442                         recent->filename[0] = '\0';
443                         strcpy(recent->filename, G.sce);
444                         BLI_addhead(&(G.recent_files), recent);
445                         /* write current file to .Blog */
446                         fprintf(fp, "%s\n", recent->filename);
447                         recent = recent->next;
448                         i=1;
449                         /* write rest of recent opened files to .Blog */
450                         while((i<U.recent_files) && (recent)){
451                                 /* this prevents to have duplicities in list */
452                                 if (strcmp(recent->filename, G.sce)!=0) {
453                                         fprintf(fp, "%s\n", recent->filename);
454                                         recent = recent->next;
455                                 }
456                                 else {
457                                         next_recent = recent->next;
458                                         MEM_freeN(recent->filename);
459                                         BLI_freelinkN(&(G.recent_files), recent);
460                                         recent = next_recent;
461                                 }
462                                 i++;
463                         }
464                         fclose(fp);
465                 }
466         }
467 }
468
469 static void do_history(char *name, ReportList *reports)
470 {
471         char tempname1[FILE_MAXDIR+FILE_MAXFILE], tempname2[FILE_MAXDIR+FILE_MAXFILE];
472         int hisnr= U.versions;
473         
474         if(U.versions==0) return;
475         if(strlen(name)<2) return;
476                 
477         while(hisnr > 1) {
478                 sprintf(tempname1, "%s%d", name, hisnr-1);
479                 sprintf(tempname2, "%s%d", name, hisnr);
480         
481                 if(BLI_rename(tempname1, tempname2))
482                         BKE_report(reports, RPT_ERROR, "Unable to make version backup");
483                         
484                 hisnr--;
485         }
486                 
487         /* is needed when hisnr==1 */
488         sprintf(tempname1, "%s%d", name, hisnr);
489         
490         if(BLI_rename(name, tempname1))
491                 BKE_report(reports, RPT_ERROR, "Unable to make version backup");
492 }
493
494 void WM_write_file(bContext *C, char *target, int compress, ReportList *reports)
495 {
496         Library *li;
497         int writeflags, len;
498         char di[FILE_MAX];
499         
500         len = strlen(target);
501         
502         if (len == 0) return;
503         if (len >= FILE_MAX) {
504                 BKE_report(reports, RPT_ERROR, "Path too long, cannot save");
505                 return;
506         }
507  
508         /* send the OnSave event */
509         for (li= G.main->library.first; li; li= li->id.next) {
510                 if (BLI_streq(li->name, target)) {
511                         BKE_report(reports, RPT_ERROR, "Cannot overwrite used library");
512                         return;
513                 }
514         }
515         
516         if (!BLO_has_bfile_extension(target) && (len+6 < FILE_MAX)) {
517                 sprintf(di, "%s.blend", target);
518         } else {
519                 strcpy(di, target);
520         }
521
522 //      if (BLI_exists(di)) {
523 // XXX          if(!saveover(di))
524 // XXX                  return; 
525 //      }
526         
527         if (G.fileflags & G_AUTOPACK) {
528                 packAll(G.main, reports);
529         }
530         
531         ED_object_exit_editmode(C, 0);
532
533         do_history(di, reports);
534         
535         writeflags= G.fileflags;
536
537         /* set compression flag */
538         if(compress) writeflags |= G_FILE_COMPRESS;
539         else writeflags &= ~G_FILE_COMPRESS;
540         
541         if (BLO_write_file(CTX_data_main(C), di, writeflags, reports)) {
542                 strcpy(G.sce, di);
543                 G.relbase_valid = 1;
544                 strcpy(G.main->name, di);       /* is guaranteed current file */
545
546                 G.save_over = 1; /* disable untitled.blend convention */
547
548                 if(compress) G.fileflags |= G_FILE_COMPRESS;
549                 else G.fileflags &= ~G_FILE_COMPRESS;
550                 
551                 writeBlog();
552         }
553
554 // XXX  waitcursor(0);
555 }
556
557 /* operator entry */
558 int WM_write_homefile(bContext *C, wmOperator *op)
559 {
560         wmWindow *win= CTX_wm_window(C);
561         char tstr[FILE_MAXDIR+FILE_MAXFILE];
562         int write_flags;
563         
564         /* check current window and close it if temp */
565         if(win->screen->full == SCREENTEMP) {
566                 wm_window_close(C, win);
567         }
568         
569         BLI_make_file_string("/", tstr, BLI_gethome(), ".B25.blend");
570         
571         /*  force save as regular blend file */
572         write_flags = G.fileflags & ~(G_FILE_COMPRESS | G_FILE_LOCK | G_FILE_SIGN);
573
574         BLO_write_file(CTX_data_main(C), tstr, write_flags, op->reports);
575         
576         G.save_over= 0;
577         
578         return OPERATOR_FINISHED;
579 }
580
581 void WM_write_autosave(bContext *C)
582 {
583         char tstr[FILE_MAXDIR+FILE_MAXFILE];
584         int write_flags;
585         
586         get_autosave_location(tstr);
587
588                 /*  force save as regular blend file */
589         write_flags = G.fileflags & ~(G_FILE_COMPRESS | G_FILE_LOCK | G_FILE_SIGN);
590
591                 /* error reporting to console */
592         BLO_write_file(CTX_data_main(C), tstr, write_flags, NULL);
593 }
594
595 /* if global undo; remove tempsave, otherwise rename */
596 void delete_autosave(void)
597 {
598         char tstr[FILE_MAXDIR+FILE_MAXFILE];
599         
600         get_autosave_location(tstr);
601
602         if (BLI_exists(tstr)) {
603                 char str[FILE_MAXDIR+FILE_MAXFILE];
604                 BLI_make_file_string("/", str, U.tempdir, "quit.blend");
605
606                 if(U.uiflag & USER_GLOBALUNDO) BLI_delete(tstr, 0, 0);
607                 else BLI_rename(tstr, str);
608         }
609 }
610
611 /***/
612