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