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