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