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