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