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