Wednesday sync orange with bf-blender
[blender.git] / source / blender / src / filesel.c
1 /**
2  * $Id$
3  *
4  * ***** BEGIN GPL/BL DUAL 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. The Blender
10  * Foundation also sells licenses for use in proprietary software under
11  * the Blender License.  See http://www.blender.org/BL/ for information
12  * about this.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software Foundation,
21  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22  *
23  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
24  * All rights reserved.
25  *
26  * The Original Code is: all of this file.
27  *
28  * Contributor(s): none yet.
29  *
30  * ***** END GPL/BL DUAL LICENSE BLOCK *****
31  */
32
33 #include <stdlib.h>
34 #include <string.h>
35 #include <math.h>
36
37 #ifdef WIN32
38 #include <io.h>
39 #include <direct.h>
40 #include "BLI_winstuff.h"
41 #else
42 #include <unistd.h>
43 #include <sys/times.h>
44 #endif   
45
46 #include <sys/stat.h>
47 #include <sys/types.h>
48 #include "MEM_guardedalloc.h"
49
50 #include "BMF_Api.h"
51
52 #include "BLI_blenlib.h"
53 #include "BLI_arithb.h"
54 #include "BLI_linklist.h"
55 #include "BLI_storage_types.h"
56 #include "BLI_dynstr.h"
57
58 #include "IMB_imbuf.h"
59
60 #include "DNA_armature_types.h"
61 #include "DNA_action_types.h"
62 #include "DNA_curve_types.h"
63 #include "DNA_image_types.h"
64 #include "DNA_ipo_types.h"
65 #include "DNA_material_types.h"
66 #include "DNA_mesh_types.h"
67 #include "DNA_object_types.h"
68 #include "DNA_texture_types.h"
69 #include "DNA_space_types.h"
70 #include "DNA_scene_types.h"
71 #include "DNA_screen_types.h"
72 #include "DNA_userdef_types.h"
73 #include "DNA_vfont_types.h"
74 #include "DNA_view3d_types.h"
75
76 #include "BKE_action.h"
77 #include "BKE_constraint.h"
78 #include "BKE_curve.h"
79 #include "BKE_depsgraph.h"
80 #include "BKE_font.h"
81 #include "BKE_global.h"
82 #include "BKE_library.h"
83 #include "BKE_main.h"
84 #include "BKE_material.h"
85 #include "BKE_utildefines.h"
86
87 #include "BIF_gl.h"
88 #include "BIF_interface.h"
89 #include "BIF_toolbox.h"
90 #include "BIF_mywindow.h"
91 #include "BIF_editview.h"
92 #include "BIF_space.h"
93 #include "BIF_screen.h"
94 #include "BIF_resources.h"
95
96 #include "BLO_readfile.h"
97
98 #include "BDR_editcurve.h"
99 #include "BDR_editobject.h"
100
101 #include "BPI_script.h"
102 #include "BSE_filesel.h"
103 #include "BSE_view.h"
104
105 #include "mydevice.h"
106 #include "blendef.h"
107 #include "nla.h"
108
109 #include "BIF_fsmenu.h"  /* include ourselves */
110
111 #if defined WIN32 || defined __BeOS
112         int fnmatch(){return 0;}
113 #else
114         #include <fnmatch.h>
115 #endif
116
117 #ifndef WIN32
118 #include <sys/param.h>
119 #endif
120
121 #define FILESELHEAD             60
122 #define FILESEL_DY              16
123
124 /* for events */
125 #define NOTACTIVE                       0
126 #define ACTIVATE                        1
127 #define INACTIVATE                      2
128 /* for state of file */
129 #define ACTIVE                          2
130
131 #define STARTSWITH(x, y) (strncmp(x, y, sizeof(x) - 1) == 0)
132
133 static int is_a_library(SpaceFile *sfile, char *dir, char *group);
134 static void do_library_append(SpaceFile *sfile);
135 static void library_to_filelist(SpaceFile *sfile);
136 static void filesel_select_objects(struct SpaceFile *sfile);
137 static void active_file_object(struct SpaceFile *sfile);
138 static int groupname_to_code(char *group);
139
140 extern void countall(void);
141
142 /* local globals */
143
144 static rcti scrollrct, textrct, bar;
145 static int filebuty1, filebuty2, page_ofs, collumwidth, selecting=0;
146 static int filetoname= 0;
147 static float pixels_to_ofs;
148 static char otherdir[FILE_MAXDIR];
149 static ScrArea *otherarea;
150
151 /* FSMENU HANDLING */
152
153         /* FSMenuEntry's without paths indicate seperators */
154 typedef struct _FSMenuEntry FSMenuEntry;
155 struct _FSMenuEntry {
156         FSMenuEntry *next;
157
158         char *path;
159 };
160
161 static FSMenuEntry *fsmenu= 0;
162
163 int fsmenu_get_nentries(void)
164 {
165         FSMenuEntry *fsme;
166         int count= 0;
167
168         for (fsme= fsmenu; fsme; fsme= fsme->next) 
169                 count++;
170
171         return count;
172 }
173 int fsmenu_is_entry_a_seperator(int idx)
174 {
175         FSMenuEntry *fsme;
176
177         for (fsme= fsmenu; fsme && idx; fsme= fsme->next)
178                 idx--;
179
180         return (fsme && !fsme->path)?1:0;
181 }
182 char *fsmenu_get_entry(int idx)
183 {
184         FSMenuEntry *fsme;
185
186         for (fsme= fsmenu; fsme && idx; fsme= fsme->next)
187                 idx--;
188
189         return fsme?fsme->path:NULL;
190 }
191 char *fsmenu_build_menu(void)
192 {
193         DynStr *ds= BLI_dynstr_new();
194         FSMenuEntry *fsme;
195         char *menustr;
196
197         for (fsme= fsmenu; fsme; fsme= fsme->next) {
198                 if (!fsme->path) {
199                                 /* clean consecutive seperators and ignore trailing ones */
200                         if (fsme->next) {
201                                 if (fsme->next->path) {
202                                         BLI_dynstr_append(ds, "%l|");
203                                 } else {
204                                         FSMenuEntry *next= fsme->next;
205                                         fsme->next= next->next;
206                                         MEM_freeN(next);
207                                 }
208                         }
209                 } else {
210                         BLI_dynstr_append(ds, fsme->path);
211                         if (fsme->next) BLI_dynstr_append(ds, "|");
212                 }
213         }
214
215         menustr= BLI_dynstr_get_cstring(ds);
216         BLI_dynstr_free(ds);
217         return menustr;
218 }
219 static FSMenuEntry *fsmenu_get_last_separator(void) 
220 {
221         FSMenuEntry *fsme, *lsep=NULL;
222
223         for (fsme= fsmenu; fsme; fsme= fsme->next)
224                 if (!fsme->path)
225                         lsep= fsme;
226
227         return lsep;
228 }
229 void fsmenu_insert_entry(char *path, int sorted)
230 {
231         FSMenuEntry *prev= fsmenu_get_last_separator();
232         FSMenuEntry *fsme= prev?prev->next:fsmenu;
233
234         for (; fsme; prev= fsme, fsme= fsme->next) {
235                 if (fsme->path) {
236                         if (BLI_streq(path, fsme->path)) {
237                                 return;
238                         } else if (sorted && strcmp(path, fsme->path)<0) {
239                                 break;
240                         }
241                 }
242         }
243         
244         fsme= MEM_mallocN(sizeof(*fsme), "fsme");
245         fsme->path= BLI_strdup(path);
246
247         if (prev) {
248                 fsme->next= prev->next;
249                 prev->next= fsme;
250         } else {
251                 fsme->next= fsmenu;
252                 fsmenu= fsme;
253         }
254 }
255 void fsmenu_append_seperator(void)
256 {
257         if (fsmenu) {
258                 FSMenuEntry *fsme= fsmenu;
259
260                 while (fsme->next) fsme= fsme->next;
261
262                 fsme->next= MEM_mallocN(sizeof(*fsme), "fsme");
263                 fsme->next->next= NULL;
264                 fsme->next->path= NULL;
265         }
266 }
267 void fsmenu_remove_entry(int idx)
268 {
269         FSMenuEntry *prev= NULL, *fsme= fsmenu;
270
271         for (fsme= fsmenu; fsme && idx; prev= fsme, fsme= fsme->next)
272                 if (fsme->path)
273                         idx--;
274
275         if (fsme) {
276                 if (prev) {
277                         prev->next= fsme->next;
278                 } else {
279                         fsmenu= fsme->next;
280                 }
281
282                 MEM_freeN(fsme->path);
283                 MEM_freeN(fsme);
284         }
285 }
286 void fsmenu_free(void)
287 {
288         FSMenuEntry *fsme= fsmenu;
289
290         while (fsme) {
291                 FSMenuEntry *n= fsme->next;
292
293                 if (fsme->path) MEM_freeN(fsme->path);
294                 MEM_freeN(fsme);
295
296                 fsme= n;
297         }
298 }
299
300 /* ******************* SORT ******************* */
301
302 static int compare_name(const void *a1, const void *a2)
303 {
304         const struct direntry *entry1=a1, *entry2=a2;
305
306         /* type is is equal to stat.st_mode */
307
308         if (S_ISDIR(entry1->type)){
309                 if (S_ISDIR(entry2->type)==0) return (-1);
310         } else{
311                 if (S_ISDIR(entry2->type)) return (1);
312         }
313         if (S_ISREG(entry1->type)){
314                 if (S_ISREG(entry2->type)==0) return (-1);
315         } else{
316                 if (S_ISREG(entry2->type)) return (1);
317         }
318         if ((entry1->type & S_IFMT) < (entry2->type & S_IFMT)) return (-1);
319         if ((entry1->type & S_IFMT) > (entry2->type & S_IFMT)) return (1);
320         
321         /* make sure "." and ".." are always first */
322         if( strcmp(entry1->relname, ".")==0 ) return (-1);
323         if( strcmp(entry2->relname, ".")==0 ) return (1);
324         if( strcmp(entry1->relname, "..")==0 ) return (-1);
325         
326         return (BLI_strcasecmp(entry1->relname,entry2->relname));
327 }
328
329 static int compare_date(const void *a1, const void *a2) 
330 {
331         const struct direntry *entry1=a1, *entry2=a2;
332         
333         /* type is equal to stat.st_mode */
334
335         if (S_ISDIR(entry1->type)){
336                 if (S_ISDIR(entry2->type)==0) return (-1);
337         } else{
338                 if (S_ISDIR(entry2->type)) return (1);
339         }
340         if (S_ISREG(entry1->type)){
341                 if (S_ISREG(entry2->type)==0) return (-1);
342         } else{
343                 if (S_ISREG(entry2->type)) return (1);
344         }
345         if ((entry1->type & S_IFMT) < (entry2->type & S_IFMT)) return (-1);
346         if ((entry1->type & S_IFMT) > (entry2->type & S_IFMT)) return (1);
347
348         /* make sure "." and ".." are always first */
349         if( strcmp(entry1->relname, ".")==0 ) return (-1);
350         if( strcmp(entry2->relname, ".")==0 ) return (1);
351         if( strcmp(entry1->relname, "..")==0 ) return (-1);
352         
353         if ( entry1->s.st_mtime < entry2->s.st_mtime) return 1;
354         if ( entry1->s.st_mtime > entry2->s.st_mtime) return -1;
355         
356         else return BLI_strcasecmp(entry1->relname,entry2->relname);
357 }
358
359 static int compare_size(const void *a1, const void *a2) 
360 {
361         const struct direntry *entry1=a1, *entry2=a2;
362
363         /* type is equal to stat.st_mode */
364
365         if (S_ISDIR(entry1->type)){
366                 if (S_ISDIR(entry2->type)==0) return (-1);
367         } else{
368                 if (S_ISDIR(entry2->type)) return (1);
369         }
370         if (S_ISREG(entry1->type)){
371                 if (S_ISREG(entry2->type)==0) return (-1);
372         } else{
373                 if (S_ISREG(entry2->type)) return (1);
374         }
375         if ((entry1->type & S_IFMT) < (entry2->type & S_IFMT)) return (-1);
376         if ((entry1->type & S_IFMT) > (entry2->type & S_IFMT)) return (1);
377
378         /* make sure "." and ".." are always first */
379         if( strcmp(entry1->relname, ".")==0 ) return (-1);
380         if( strcmp(entry2->relname, ".")==0 ) return (1);
381         if( strcmp(entry1->relname, "..")==0 ) return (-1);
382         
383         if ( entry1->s.st_size < entry2->s.st_size) return 1;
384         if ( entry1->s.st_size > entry2->s.st_size) return -1;
385         else return BLI_strcasecmp(entry1->relname,entry2->relname);
386 }
387
388 static int compare_extension(const void *a1, const void *a2) {
389         const struct direntry *entry1=a1, *entry2=a2;
390         char *sufix1, *sufix2;
391         char *nil="";
392
393         if (!(sufix1= strstr (entry1->relname, ".blend.gz"))) 
394                 sufix1= strrchr (entry1->relname, '.');
395         if (!(sufix2= strstr (entry2->relname, ".blend.gz")))
396                 sufix2= strrchr (entry2->relname, '.');
397         if (!sufix1) sufix1= nil;
398         if (!sufix2) sufix2= nil;
399
400         /* type is is equal to stat.st_mode */
401
402         if (S_ISDIR(entry1->type)){
403                 if (S_ISDIR(entry2->type)==0) return (-1);
404         } else{
405                 if (S_ISDIR(entry2->type)) return (1);
406         }
407         if (S_ISREG(entry1->type)){
408                 if (S_ISREG(entry2->type)==0) return (-1);
409         } else{
410                 if (S_ISREG(entry2->type)) return (1);
411         }
412         if ((entry1->type & S_IFMT) < (entry2->type & S_IFMT)) return (-1);
413         if ((entry1->type & S_IFMT) > (entry2->type & S_IFMT)) return (1);
414         
415         /* make sure "." and ".." are always first */
416         if( strcmp(entry1->relname, ".")==0 ) return (-1);
417         if( strcmp(entry2->relname, ".")==0 ) return (1);
418         if( strcmp(entry1->relname, "..")==0 ) return (-1);
419         if( strcmp(entry2->relname, "..")==0 ) return (-1);
420         
421         return (BLI_strcasecmp(sufix1, sufix2));
422 }
423
424 /* **************************************** */
425
426 void clear_global_filesel_vars()
427 {
428         selecting= 0;
429 }
430
431
432 void filesel_statistics(SpaceFile *sfile, int *totfile, int *selfile, float *totlen, float *sellen)
433 {
434         double len;
435         int a;
436         
437         *totfile= *selfile= 0;
438         *totlen= *sellen= 0;
439         
440         if(sfile->filelist==0) return;
441         
442         for(a=0; a<sfile->totfile; a++) {
443                 if( (sfile->filelist[a].type & S_IFDIR)==0 ) {
444                         (*totfile) ++;
445
446                         len = sfile->filelist[a].s.st_size;
447                         (*totlen) += (float)(len/1048576.0);            
448
449                         if(sfile->filelist[a].flags & ACTIVE) {
450                                 (*selfile) ++;
451                                 (*sellen) += (float)(len/1048576.0);
452                         }
453                 }
454         }
455 }
456
457 /* *************** HELP FUNCTIONS ******************* */
458
459
460 /* not called when browsing .blend itself */
461 void test_flags_file(SpaceFile *sfile)
462 {
463         struct direntry *file;
464         int num;
465
466         file= sfile->filelist;
467         
468         for(num=0; num<sfile->totfile; num++, file++) {
469                 file->flags= 0;
470                 file->type= file->s.st_mode;    /* restore the mess below */ 
471
472                         /* Don't check extensions for directories */ 
473                 if (file->type & S_IFDIR)
474                         continue;
475                         
476                 if(sfile->type==FILE_BLENDER || sfile->type==FILE_LOADLIB) {
477                         if(BLO_has_bfile_extension(file->relname)) {
478                                 file->flags |= BLENDERFILE;
479                                 
480                                 if(sfile->type==FILE_LOADLIB) {
481                                         char name[FILE_MAXDIR+FILE_MAXFILE];
482                                         strcpy(name, sfile->dir);
483                                         strcat(name, file->relname);
484                                         
485                                         /* prevent current file being used as acceptable dir */
486                                         if (BLI_streq(G.main->name, name)==0) {
487                                                 file->type &= ~S_IFMT;
488                                                 file->type |= S_IFDIR;
489                                         }
490                                 }
491                         }
492                 } else if (sfile->type==FILE_SPECIAL){
493                         if(BLI_testextensie(file->relname, ".py")) {
494                                 file->flags |= PYSCRIPTFILE;                    
495                         } else if( BLI_testextensie(file->relname, ".ttf")
496                                         || BLI_testextensie(file->relname, ".ttc")
497                                         || BLI_testextensie(file->relname, ".pfb")
498                                         || BLI_testextensie(file->relname, ".otf")
499                                         || BLI_testextensie(file->relname, ".otc")) {
500                                 file->flags |= FTFONTFILE;                      
501                         } else if (G.have_libtiff &&
502                                         (BLI_testextensie(file->relname, ".tif")
503                                         ||      BLI_testextensie(file->relname, ".tiff"))) {
504                                         file->flags |= IMAGEFILE;                       
505                         } else if (G.have_quicktime){
506                                 if(             BLI_testextensie(file->relname, ".jpg")
507                                         ||      BLI_testextensie(file->relname, ".jpeg")
508                                         ||      BLI_testextensie(file->relname, ".hdr")
509                                         ||      BLI_testextensie(file->relname, ".tga")
510                                         ||      BLI_testextensie(file->relname, ".rgb")
511                                         ||      BLI_testextensie(file->relname, ".bmp")
512                                         ||      BLI_testextensie(file->relname, ".png")
513                                         ||      BLI_testextensie(file->relname, ".iff")
514                                         ||      BLI_testextensie(file->relname, ".lbm")
515                                         ||      BLI_testextensie(file->relname, ".gif")
516                                         ||      BLI_testextensie(file->relname, ".psd")
517                                         ||      BLI_testextensie(file->relname, ".tif")
518                                         ||      BLI_testextensie(file->relname, ".tiff")
519                                         ||      BLI_testextensie(file->relname, ".pct")
520                                         ||      BLI_testextensie(file->relname, ".pict")
521                                         ||      BLI_testextensie(file->relname, ".pntg") //macpaint
522                                         ||      BLI_testextensie(file->relname, ".qtif")
523                                         ||      BLI_testextensie(file->relname, ".sgi")) {
524                                         file->flags |= IMAGEFILE;                       
525                                 }
526                                 else if(BLI_testextensie(file->relname, ".avi")
527                                         ||      BLI_testextensie(file->relname, ".flc")
528                                         ||      BLI_testextensie(file->relname, ".mov")
529                                         ||      BLI_testextensie(file->relname, ".movie")
530                                         ||      BLI_testextensie(file->relname, ".mv")) {
531                                         file->flags |= MOVIEFILE;                       
532                                 }
533                         } else { // no quicktime
534                                 if(BLI_testextensie(file->relname, ".jpg")
535                                         ||      BLI_testextensie(file->relname, ".hdr")
536                                         ||      BLI_testextensie(file->relname, ".tga")
537                                         ||      BLI_testextensie(file->relname, ".rgb")
538                                         ||      BLI_testextensie(file->relname, ".bmp")
539                                         ||      BLI_testextensie(file->relname, ".png")
540                                         ||      BLI_testextensie(file->relname, ".iff")
541                                         ||      BLI_testextensie(file->relname, ".lbm")
542                                         ||      BLI_testextensie(file->relname, ".sgi")) {
543                                         file->flags |= IMAGEFILE;                       
544                                 }
545                                 else if(BLI_testextensie(file->relname, ".avi")
546                                         ||      BLI_testextensie(file->relname, ".mv")) {
547                                         file->flags |= MOVIEFILE;                       
548                                 }
549                                 else if(BLI_testextensie(file->relname, ".wav")) {
550                                         file->flags |= SOUNDFILE;
551                                 }                               
552                         }
553                 }
554         }       
555 }
556
557
558 void sort_filelist(SpaceFile *sfile)
559 {
560         struct direntry *file;
561         int num;/*  , act= 0; */
562         
563         switch(sfile->sort) {
564         case FILE_SORTALPHA:
565                 qsort(sfile->filelist, sfile->totfile, sizeof(struct direntry), compare_name);  
566                 break;
567         case FILE_SORTDATE:
568                 qsort(sfile->filelist, sfile->totfile, sizeof(struct direntry), compare_date);  
569                 break;
570         case FILE_SORTSIZE:
571                 qsort(sfile->filelist, sfile->totfile, sizeof(struct direntry), compare_size);  
572                 break;
573         case FILE_SORTEXTENS:
574                 qsort(sfile->filelist, sfile->totfile, sizeof(struct direntry), compare_extension);     
575         }
576         
577         sfile->act= -1;
578
579         file= sfile->filelist;
580         for(num=0; num<sfile->totfile; num++, file++) {
581                 file->flags &= ~HILITE;
582         }
583
584 }
585
586 void read_dir(SpaceFile *sfile)
587 {
588         int num, len;
589         char wdir[FILE_MAXDIR];
590
591         /* sfile->act is used for example in databrowse: double names of library objects */
592         sfile->act= -1;
593
594         if(sfile->type==FILE_MAIN) {
595                 main_to_filelist(sfile);
596                 return;
597         }
598         else if(sfile->type==FILE_LOADLIB) {
599                 library_to_filelist(sfile);
600                 if(sfile->libfiledata) return;
601         }
602
603         BLI_hide_dot_files(sfile->flag & FILE_HIDE_DOT);
604         
605         BLI_getwdN(wdir);
606         sfile->totfile= BLI_getdir(sfile->dir, &(sfile->filelist));
607         chdir(wdir);
608         
609         if(sfile->sort!=FILE_SORTALPHA) sort_filelist(sfile);
610         
611         sfile->maxnamelen= 0;
612
613         for (num=0; num<sfile->totfile; num++) {
614                 
615                 len = BMF_GetStringWidth(G.font, sfile->filelist[num].relname);
616                 if (len > sfile->maxnamelen) sfile->maxnamelen = len;
617                 
618                 if(filetoname) {
619                         if(strcmp(sfile->file, sfile->filelist[num].relname)==0) {
620                                 
621                                 sfile->ofs= num-( sfile->collums*(curarea->winy-FILESELHEAD-20)/(2*FILESEL_DY));
622                                 filetoname= 0;
623                         }
624                 }
625         }
626         test_flags_file(sfile);
627         
628         filetoname= 0;
629 }
630
631 void freefilelist(SpaceFile *sfile)
632 {
633         int num;
634
635         num= sfile->totfile-1;
636
637         if (sfile->filelist==0) return;
638         
639         for(; num>=0; num--){
640                 MEM_freeN(sfile->filelist[num].relname);
641                 
642                 if (sfile->filelist[num].string) MEM_freeN(sfile->filelist[num].string);
643         }
644         free(sfile->filelist);
645         sfile->filelist= 0;
646 }
647
648 static void split_sfile(SpaceFile *sfile, char *s1)
649 {
650         char string[FILE_MAXDIR+FILE_MAXFILE], dir[FILE_MAXDIR], file[FILE_MAXFILE];
651
652         strcpy(string, s1);
653
654         BLI_split_dirfile(string, dir, file);
655         
656         if(sfile->filelist) {
657                 if(strcmp(dir, sfile->dir)!=0) {
658                         freefilelist(sfile);
659                 }
660                 else test_flags_file(sfile);
661         }
662         strcpy(sfile->file, file);
663                 
664         BLI_make_file_string(G.sce, sfile->dir, dir, "");
665 }
666
667
668 void parent(SpaceFile *sfile)
669 {
670         short a;
671         char *dir;
672         
673         /* if databrowse: no parent */
674         if(sfile->type==FILE_MAIN && sfile->returnfunc) return;
675
676         dir= sfile->dir;
677         
678 #ifdef WIN32
679         if( (a = strlen(dir)) ) {                               /* remove all '/' at the end */
680                 while(dir[a-1] == '\\') {
681                         a--;
682                         dir[a] = 0;
683                         if (a<=0) break;
684                 }
685         }
686         if( (a = strlen(dir)) ) {                               /* then remove all until '/' */
687                 while(dir[a-1] != '\\') {
688                         a--;
689                         dir[a] = 0;
690                         if (a<=0) break;
691                 }
692         }
693         if( (a = strlen(dir)) ) {
694                 if (dir[a-1] != '\\') strcat(dir,"\\");
695         }
696         else if(sfile->type!=FILE_MAIN) strcpy(dir,"\\");
697 #else
698         if( (a = strlen(dir)) ) {                               /* remove all '/' at the end */
699                 while(dir[a-1] == '/') {
700                         a--;
701                         dir[a] = 0;
702                         if (a<=0) break;
703                 }
704         }
705         if( (a = strlen(dir)) ) {                               /* then remove until '/' */
706                 while(dir[a-1] != '/') {
707                         a--;
708                         dir[a] = 0;
709                         if (a<=0) break;
710                 }
711         }
712         if ( (a = strlen(dir)) ) {
713                 if (dir[a-1] != '/') strcat(dir,"/");
714         }
715         else if(sfile->type!=FILE_MAIN) strcpy(dir,"/");
716 #endif
717         
718         /* to be sure */
719         BLI_make_exist(sfile->dir);
720
721         freefilelist(sfile);
722         sfile->ofs= 0;
723         scrarea_queue_winredraw(curarea);
724 }
725
726 void swapselect_file(SpaceFile *sfile)
727 {
728         struct direntry *file;
729         int num, act= 0;
730         
731         file= sfile->filelist;
732         for(num=0; num<sfile->totfile; num++, file++) {
733                 if(file->flags & ACTIVE) {
734                         act= 1;
735                         break;
736                 }
737         }
738         file= sfile->filelist+2;
739         for(num=2; num<sfile->totfile; num++, file++) {
740                 if(act) file->flags &= ~ACTIVE;
741                 else file->flags |= ACTIVE;
742         }
743 }
744
745 static int find_active_file(SpaceFile *sfile, short x, short y)
746 {
747         int ofs;
748         
749         if(y > textrct.ymax) y= textrct.ymax;
750         if(y <= textrct.ymin) y= textrct.ymin+1;
751         
752         ofs= (x-textrct.xmin)/collumwidth;
753         if(ofs<0) ofs= 0;
754         ofs*= (textrct.ymax-textrct.ymin);
755
756         return sfile->ofs+ (ofs+textrct.ymax-y)/FILESEL_DY;
757         
758 }
759
760
761 /* ********************** DRAW ******************************* */
762
763 static void calc_file_rcts(SpaceFile *sfile)
764 {
765         int tot, h, len;
766         float fac, start, totfile;
767         
768         scrollrct.xmin= 15;
769         scrollrct.xmax= 35;
770         scrollrct.ymin= 10;
771         scrollrct.ymax= curarea->winy-10-FILESELHEAD;
772         
773         textrct.xmin= scrollrct.xmax+10;
774         textrct.xmax= curarea->winx-10;
775         textrct.ymin= scrollrct.ymin;
776         textrct.ymax= scrollrct.ymax;
777         
778         if(textrct.xmax-textrct.xmin <60) textrct.xmax= textrct.xmin+60;
779         
780         len= (textrct.ymax-textrct.ymin) % FILESEL_DY;
781         textrct.ymin+= len;
782         scrollrct.ymin+= len;
783         
784         filebuty1= curarea->winy-FILESELHEAD;
785         filebuty2= filebuty1+FILESELHEAD/2 -6;
786         
787         
788         /* amount of collums */
789         len= sfile->maxnamelen+25;
790         
791         if(sfile->type==FILE_MAIN) len+= 100;
792         else if(sfile->flag & FILE_SHOWSHORT) len+= 100;
793         else len+= 380;
794         
795         sfile->collums= (textrct.xmax-textrct.xmin)/len;
796         
797         if(sfile->collums<1) sfile->collums= 1;
798         else if(sfile->collums>8) sfile->collums= 8;
799
800         /* this flag aint yet defined in user menu, needed? */
801 //      if((U.flag & USER_FSCOLLUM)==0) sfile->collums= 1;
802         
803         collumwidth= (textrct.xmax-textrct.xmin)/sfile->collums;
804         
805
806         totfile= sfile->totfile + 0.5f;
807
808         tot= (int)(FILESEL_DY*totfile);
809         if(tot) fac= ((float)sfile->collums*(scrollrct.ymax-scrollrct.ymin))/( (float)tot);
810         else fac= 1.0;
811         
812         if(sfile->ofs<0) sfile->ofs= 0;
813         
814         if(tot) start= ( (float)sfile->ofs)/(totfile);
815         else start= 0.0;
816         if(fac>1.0) fac= 1.0f;
817
818         if(start+fac>1.0) {
819                 sfile->ofs= (short)ceil((1.0-fac)*totfile);
820                 start= ( (float)sfile->ofs)/(totfile);
821                 fac= 1.0f-start;
822         }
823
824         bar.xmin= scrollrct.xmin+2;
825         bar.xmax= scrollrct.xmax-2;
826         h= (scrollrct.ymax-scrollrct.ymin)-4;
827         bar.ymax= (int)(scrollrct.ymax-2- start*h);
828         bar.ymin= (int)(bar.ymax- fac*h);
829
830         pixels_to_ofs= (totfile)/(float)(h+3);
831         page_ofs= (int)(fac*totfile);
832 }
833
834 int filescrollselect= 0;
835
836 static void draw_filescroll(SpaceFile *sfile)
837 {
838
839         if(scrollrct.ymin+10 >= scrollrct.ymax) return;
840         
841         BIF_ThemeColor(TH_BACK);
842         glRecti(scrollrct.xmin,  scrollrct.ymin,  scrollrct.xmax,  scrollrct.ymax);
843
844         uiEmboss(scrollrct.xmin, scrollrct.ymin, scrollrct.xmax, scrollrct.ymax, 1);
845
846         BIF_ThemeColor(TH_HEADER);
847         glRecti(bar.xmin+2,  bar.ymin+2,  bar.xmax-2,  bar.ymax-2);
848
849         uiEmboss(bar.xmin+2, bar.ymin+2, bar.xmax-2, bar.ymax-2, filescrollselect);
850         
851 }
852
853 static void linerect(int id, int x, int y)
854 {
855         if(id & ACTIVE) {
856                 if(id & HILITE) BIF_ThemeColorShade(TH_HILITE, 20);
857                 else BIF_ThemeColor(TH_HILITE);
858         }
859         else if(id & HILITE) BIF_ThemeColorShade(TH_BACK, 20);
860         else BIF_ThemeColor(TH_BACK);
861         
862         glRects(x-17,  y-3,  x+collumwidth-21,  y+11);
863
864 }
865
866 static void print_line(SpaceFile *sfile, struct direntry *files, int x, int y)
867 {
868         int boxcol=0;
869         char *s;
870
871         boxcol= files->flags & (HILITE + ACTIVE);
872
873         if(boxcol) {
874                 linerect(boxcol, x, y);
875         }
876
877         // this is where the little boxes in the file view are being drawn according to the file type
878         if(files->flags & BLENDERFILE) {
879                 cpack(0xA0A0);
880                 glRects(x-14,  y,  x-8,  y+7);
881         }
882         else if(files->flags & PSXFILE) {
883                 cpack(0xA060B0);
884                 glRects(x-14,  y,  x-8,  y+7);
885         }
886         else if(files->flags & IMAGEFILE) {
887                 cpack(0xF08040);
888                 glRects(x-14,  y,  x-8,  y+7);
889         }
890         else if(files->flags & MOVIEFILE) {
891                 cpack(0x70A070);
892                 glRects(x-14,  y,  x-8,  y+7);
893         }
894         else if(files->flags & PYSCRIPTFILE) {
895                 cpack(0x4477dd);
896                 glRects(x-14,  y,  x-8,  y+7);
897         }
898         else if(files->flags & SOUNDFILE) {
899                 cpack(0xa0a000);
900                 glRects(x-14,  y,  x-8,  y+7);
901         }       
902         else if(files->flags & FTFONTFILE) {
903                 cpack(0xff2371);
904                 glRects(x-14,  y,  x-8,  y+7);
905         }
906         
907         if(S_ISDIR(files->type)) BIF_ThemeColor(TH_TEXT_HI);
908         else BIF_ThemeColor(TH_TEXT);
909
910         s = files->string;
911         if(s) {
912                 glRasterPos2i(x,  y);
913                 BMF_DrawString(G.font, files->relname);
914                 
915                 x += sfile->maxnamelen + 100;
916
917                 glRasterPos2i(x - BMF_GetStringWidth(G.font, files->size),  y);
918                 BMF_DrawString(G.font, files->size);
919
920                 if(sfile->flag & FILE_SHOWSHORT) return;
921
922 #ifndef WIN32
923                 /* rwx rwx rwx */
924                         x += 20; glRasterPos2i(x, y); 
925                         BMF_DrawString(G.font, files->mode1); 
926                 
927                         x += 30; glRasterPos2i(x, y); 
928                         BMF_DrawString(G.font, files->mode2); 
929                 
930                         x += 30; glRasterPos2i(x, y); 
931                         BMF_DrawString(G.font, files->mode3); 
932                 
933                 /* owner time date */
934                         x += 30; glRasterPos2i(x, y); 
935                         BMF_DrawString(G.font, files->owner); 
936 #endif
937                 
938                         x += 60; glRasterPos2i(x, y); 
939                         BMF_DrawString(G.font, files->time); 
940                 
941                         x += 50; glRasterPos2i(x, y); 
942                         BMF_DrawString(G.font, files->date); 
943         }
944         else {
945                 glRasterPos2i(x,  y);
946                 BMF_DrawString(G.font, files->relname);
947                 
948                 if(files->nr) { /* extra info */
949                         x+= sfile->maxnamelen+20;
950                         glRasterPos2i(x,  y);
951                         BMF_DrawString(G.font, files->extra);
952                 }
953         }
954 }
955
956
957 static int calc_filesel_line(SpaceFile *sfile, int nr, int *valx, int *valy)
958 {
959         /* get screen coordinate of a line */
960         int val, coll;
961
962         nr-= sfile->ofs;
963
964         /* amount of lines */
965         val= (textrct.ymax-textrct.ymin)/FILESEL_DY;
966         if (val == 0) coll = 0;
967         else coll= nr/val;
968         nr -= coll*val;
969         
970         *valy= textrct.ymax-FILESEL_DY+3 - nr*FILESEL_DY;
971         *valx= coll*collumwidth + textrct.xmin+20;
972         
973         if(nr<0 || coll > sfile->collums) return 0;
974         return 1;
975 }
976
977 static void set_active_file(SpaceFile *sfile, int act)
978 {
979         struct direntry *file;
980         int num, redraw= 0;
981         unsigned int newflag;
982         int old=0, newi=0;
983         
984         file= sfile->filelist;
985         if(file==0) return;
986         
987         for(num=0; num<sfile->totfile; num++, file++) {
988                 if(num==act) {
989                         
990                         if(selecting && num>1) {
991                                 newflag= HILITE | (file->flags & ~ACTIVE);
992                                 if(selecting==ACTIVATE) newflag |= ACTIVE;
993                         
994                                 if(file->flags != newflag) redraw|= 1;
995                                 file->flags= newflag;
996                         }
997                         else {
998                                 if(file->flags & HILITE);
999                                 else {
1000                                         file->flags |= HILITE;
1001                                         redraw|= 2;
1002                                         newi= num;
1003                                 }
1004                         }
1005                 }
1006                 else {
1007                         if(file->flags & HILITE) {
1008                                 file->flags &= ~HILITE;
1009                                 redraw|= 2;
1010                                 old= num;
1011                         }
1012                 }
1013                         
1014         }
1015         // removed frontbuffer draw here
1016         if(redraw) {
1017                 scrarea_queue_winredraw(curarea);
1018         }
1019 }
1020
1021
1022 static void draw_filetext(SpaceFile *sfile)
1023 {
1024         struct direntry *files;
1025         int a, x, y;
1026         short mval[2];
1027         
1028         if(textrct.ymin+10 >= textrct.ymax) return;
1029
1030
1031         /* box */
1032         BIF_ThemeColor(TH_BACK);
1033         glRecti(textrct.xmin,  textrct.ymin,  textrct.xmax,  textrct.ymax);
1034
1035         /* collums */
1036         x= textrct.xmin+collumwidth;
1037         for(a=1; a<sfile->collums; a++, x+= collumwidth) {
1038                 cpack(0x303030);
1039                 sdrawline(x,  textrct.ymin,  x,  textrct.ymax); 
1040                 cpack(0xB0B0B0);
1041                 sdrawline(x+1,  textrct.ymin,  x+1,  textrct.ymax); 
1042         }
1043
1044         if(sfile->filelist==0) return;
1045         
1046         /* test: if mouse is not in area: clear HILITE */
1047         getmouseco_areawin(mval);
1048
1049         if(mval[0]<0 || mval[0]>curarea->winx) {
1050                 files= sfile->filelist+sfile->ofs;
1051                 for(a= sfile->ofs; a<sfile->totfile; a++, files++) files->flags &= ~HILITE;
1052         }
1053         
1054         files= sfile->filelist+sfile->ofs;
1055         for(a= sfile->ofs; a<sfile->totfile; a++, files++) {
1056         
1057                 if( calc_filesel_line(sfile, a, &x, &y)==0 ) break;
1058                 print_line(sfile, files, x, y);
1059         }
1060
1061         /* clear drawing errors, with text at the right hand side: */
1062         BIF_ThemeColor(TH_HEADER);
1063         glRecti(textrct.xmax,  textrct.ymin,  textrct.xmax+10,  textrct.ymax);
1064         uiEmboss(textrct.xmin, textrct.ymin, textrct.xmax, textrct.ymax, 1);
1065 }
1066
1067 void drawfilespace(ScrArea *sa, void *spacedata)
1068 {
1069         SpaceFile *sfile;
1070         uiBlock *block;
1071         float col[3];
1072         int act, loadbutton;
1073         short mval[2];
1074         char name[20];
1075         char *menu;
1076
1077         myortho2(-0.375, sa->winx-0.375, -0.375, sa->winy-0.375);
1078
1079         BIF_GetThemeColor3fv(TH_HEADER, col);   // basic undrawn color is border
1080         glClearColor(col[0], col[1], col[2], 0.0); 
1081         glClear(GL_COLOR_BUFFER_BIT);
1082
1083         sfile= sa->spacedata.first;     
1084         if(sfile->filelist==NULL) {
1085                 read_dir(sfile);
1086                 
1087                 calc_file_rcts(sfile);
1088                 
1089                 /* calculate act */ 
1090                 getmouseco_areawin(mval);
1091                 act= find_active_file(sfile, mval[0], mval[1]);
1092                 if(act>=0 && act<sfile->totfile)
1093                         sfile->filelist[act].flags |= HILITE;
1094         }
1095         else calc_file_rcts(sfile);
1096
1097         /* HEADER */
1098         sprintf(name, "win %d", sa->win);
1099         block= uiNewBlock(&sa->uiblocks, name, UI_EMBOSS, UI_HELV, sa->win);
1100         
1101         uiSetButLock( sfile->type==FILE_MAIN && sfile->returnfunc, NULL);
1102
1103         /* space available for load/save buttons? */
1104         loadbutton= MAX2(80, 20+BMF_GetStringWidth(G.font, sfile->title));
1105         if(textrct.xmax-textrct.xmin > loadbutton+20) {
1106                 if(sfile->title[0]==0) loadbutton= 0;
1107         }
1108         else loadbutton= 0;
1109
1110         uiDefBut(block, TEX,1,"",       textrct.xmin, filebuty1, textrct.xmax-textrct.xmin-loadbutton, 21, sfile->file, 0.0, (float)FILE_MAXFILE-1, 0, 0, "");
1111         uiDefBut(block, TEX,2,"",       textrct.xmin, filebuty2, textrct.xmax-textrct.xmin-loadbutton, 21, sfile->dir, 0.0, (float)FILE_MAXFILE-1, 0, 0, "");
1112
1113         if(loadbutton) {
1114                 uiSetCurFont(block, UI_HELV);
1115                 uiDefBut(block, BUT,        5, sfile->title,    textrct.xmax-loadbutton, filebuty2, loadbutton, 21, sfile->dir, 0.0, (float)FILE_MAXFILE-1, 0, 0, "");
1116                 uiDefBut(block, BUT,        6, "Cancel",        textrct.xmax-loadbutton, filebuty1, loadbutton, 21, sfile->file, 0.0, (float)FILE_MAXFILE-1, 0, 0, "");
1117         }
1118
1119         menu= fsmenu_build_menu();
1120         if(menu[0])     // happens when no .Bfs is there, and first time browse
1121                 uiDefButS(block, MENU,  3, menu, scrollrct.xmin, filebuty1, scrollrct.xmax-scrollrct.xmin, 21, &sfile->menu, 0, 0, 0, 0, "");
1122         MEM_freeN(menu);
1123
1124         uiDefBut(block, BUT,            4, "P", scrollrct.xmin, filebuty2, scrollrct.xmax-scrollrct.xmin, 21, 0, 0, 0, 0, 0, "Move to the parent directory (PKEY)");
1125
1126         uiDrawBlock(block);
1127
1128         draw_filescroll(sfile);
1129         draw_filetext(sfile);
1130         
1131         /* others diskfree etc ? */
1132         scrarea_queue_headredraw(sa);   
1133         
1134         myortho2(-0.375, (float)(sa->winx)-0.375, -0.375, (float)(sa->winy)-0.375);
1135         draw_area_emboss(sa);
1136         
1137         sa->win_swap= WIN_BACK_OK;
1138 }
1139
1140 static void do_filescroll(SpaceFile *sfile)
1141 {
1142         short mval[2], oldy, yo;
1143         
1144         calc_file_rcts(sfile);
1145         
1146         filescrollselect= 1;
1147         
1148         /* for beauty */
1149         scrarea_do_windraw(curarea);
1150         screen_swapbuffers();
1151         
1152         getmouseco_areawin(mval);
1153         oldy= yo= mval[1];
1154         
1155         while(get_mbut()&L_MOUSE) {
1156                 getmouseco_areawin(mval);
1157                 
1158                 if(yo!=mval[1]) {
1159                         int dy= floor(0.5+((float)(oldy-mval[1]))*pixels_to_ofs);
1160                         
1161                         if(dy) {
1162                                 sfile->ofs+= dy;
1163                                 if(sfile->ofs<0) {
1164                                         sfile->ofs= 0;
1165                                         oldy= mval[1];
1166                                 }
1167                                 else oldy= floor(0.5+ (float)oldy - (float)dy/pixels_to_ofs);
1168         
1169                                 scrarea_do_windraw(curarea);
1170                                 screen_swapbuffers();
1171         
1172                         }
1173                         
1174                         yo= mval[1];
1175                 }
1176                 else BIF_wait_for_statechange();
1177         }
1178         filescrollselect= 0;
1179
1180         /* for beauty */
1181         scrarea_do_windraw(curarea);
1182         screen_swapbuffers();
1183         
1184 }
1185
1186 static void do_filescrollwheel(SpaceFile *sfile, int move)
1187 {
1188         // by phase
1189         int lines, rt;
1190
1191         calc_file_rcts(sfile);
1192
1193         lines = (int)(textrct.ymax-textrct.ymin)/FILESEL_DY;
1194         rt = lines * sfile->collums;
1195
1196         if(sfile->totfile > rt) {
1197                 sfile->ofs+= move;
1198                 if( sfile->ofs + rt > sfile->totfile + 1)
1199                         sfile->ofs = sfile->totfile - rt + 1;
1200         }
1201
1202         if(sfile->ofs<0) {
1203                 sfile->ofs= 0;
1204         }
1205 }
1206
1207 void activate_fileselect(int type, char *title, char *file, void (*func)(char *))
1208 {
1209         SpaceFile *sfile;
1210         char group[24], name[FILE_MAXDIR], temp[FILE_MAXDIR];
1211         
1212         if(curarea==0) return;
1213         if(curarea->win==0) return;
1214         
1215         newspace(curarea, SPACE_FILE);
1216         scrarea_queue_winredraw(curarea);
1217         
1218         /* sometime double, when area already is SPACE_FILE with a different file name */
1219         if(curarea->headwin) addqueue(curarea->headwin, CHANGED, 1);
1220
1221         name[2]= 0;
1222         strcpy(name, file);
1223         
1224         sfile= curarea->spacedata.first;
1225         /* sfile wants a (*)(short), but get (*)(char*) */
1226         sfile->returnfunc= func;
1227         sfile->type= type;
1228         sfile->ofs= 0;
1229         /* sfile->act is used for databrowse: double names of library objects */
1230         sfile->act= -1;
1231         
1232         if(BLI_convertstringcode(name, G.sce, G.scene->r.cfra)) sfile->flag |= FILE_STRINGCODE;
1233         else sfile->flag &= ~FILE_STRINGCODE;
1234
1235         if (U.uiflag & USER_HIDE_DOT)
1236                 sfile->flag |= FILE_HIDE_DOT;
1237
1238         if(type==FILE_MAIN) {
1239                 char *groupname;
1240                 
1241                 strcpy(sfile->file, name+2);
1242
1243                 groupname = BLO_idcode_to_name( GS(name) );
1244                 if (groupname) {
1245                         strcpy(sfile->dir, groupname);
1246                         strcat(sfile->dir, "/");
1247                 }
1248
1249                 /* free all */
1250                 if(sfile->libfiledata) BLO_blendhandle_close(sfile->libfiledata);
1251                 sfile->libfiledata= 0;
1252                 
1253                 freefilelist(sfile);
1254         }
1255         else if(type==FILE_LOADLIB) {
1256                 strcpy(sfile->dir, name);
1257                 if( is_a_library(sfile, temp, group) ) {
1258                         /* force a reload of the library-filelist */
1259                         freefilelist(sfile);
1260                 }
1261                 else {
1262                         split_sfile(sfile, name);
1263                         if(sfile->libfiledata) BLO_blendhandle_close(sfile->libfiledata);
1264                         sfile->libfiledata= NULL;
1265                 }
1266         }
1267         else {  /* FILE_BLENDER */
1268                 split_sfile(sfile, name);       /* test filelist too */
1269                 BLI_cleanup_dir(G.sce, sfile->dir);
1270
1271                 /* free: filelist and libfiledata became incorrect */
1272                 if(sfile->libfiledata) BLO_blendhandle_close(sfile->libfiledata);
1273                 sfile->libfiledata= 0;
1274         }
1275         BLI_strncpy(sfile->title, title, sizeof(sfile->title));
1276         filetoname= 1;
1277 }
1278
1279 void activate_imageselect(int type, char *title, char *file, void (*func)(char *))
1280 {
1281         SpaceImaSel *simasel;
1282         char dir[FILE_MAXDIR], name[FILE_MAXFILE];
1283         
1284         if(curarea==0) return;
1285         if(curarea->win==0) return;
1286         
1287         newspace(curarea, SPACE_IMASEL);
1288         
1289         /* sometimes double, when area is already SPACE_FILE with a different file name */
1290         addqueue(curarea->headwin, CHANGED, 1);
1291         addqueue(curarea->win, CHANGED, 1);
1292
1293         name[2]= 0;
1294         strcpy(name, file);
1295
1296         simasel= curarea->spacedata.first;
1297         simasel->returnfunc= func;
1298
1299         if(BLI_convertstringcode(name, G.sce, G.scene->r.cfra)) simasel->mode |= IMS_STRINGCODE;
1300         else simasel->mode &= ~IMS_STRINGCODE;
1301         
1302         BLI_split_dirfile(name, dir, simasel->file);
1303         BLI_cleanup_dir(G.sce, simasel->dir);
1304         if(strcmp(dir, simasel->dir)!=0) simasel->fase= 0;
1305         strcpy(simasel->dir, dir);
1306         
1307         BLI_strncpy(simasel->title, title, sizeof(simasel->title));
1308
1309         
1310         
1311         /* filetoname= 1; */
1312 }
1313
1314
1315 void activate_databrowse(ID *id, int idcode, int fromcode, int retval, short *menup, void (*func)(unsigned short))
1316 {
1317         ListBase *lb;
1318         SpaceFile *sfile;
1319         char str[32];
1320         
1321         if(id==NULL) {
1322                 lb= wich_libbase(G.main, idcode);
1323                 id= lb->first;
1324         }
1325         
1326         if(id) strcpy(str, id->name);
1327         else return;
1328         
1329         activate_fileselect(FILE_MAIN, "SELECT DATABLOCK", str, (void (*) (char*))func);
1330         
1331         sfile= curarea->spacedata.first;
1332         sfile->retval= retval;
1333         sfile->ipotype= fromcode;
1334         sfile->menup= menup;
1335 }
1336
1337 void filesel_prevspace()
1338 {
1339         SpaceFile *sfile;
1340         
1341         sfile= curarea->spacedata.first;
1342         if(sfile->next) {
1343         
1344                 BLI_remlink(&curarea->spacedata, sfile);
1345                 BLI_addtail(&curarea->spacedata, sfile);
1346
1347                 sfile= curarea->spacedata.first;
1348
1349                 if (sfile->spacetype == SPACE_SCRIPT) {
1350                         SpaceScript *sc = (SpaceScript *)sfile;
1351                         if (sc->script) sc->script->flags &=~SCRIPT_FILESEL;
1352                 }
1353
1354                 newspace(curarea, sfile->spacetype);
1355         }
1356         else newspace(curarea, SPACE_INFO);
1357 }
1358
1359 static int countselect(SpaceFile *sfile)
1360 {
1361         int a, count=0;
1362
1363         for(a=0; a<sfile->totfile; a++) {
1364                 if(sfile->filelist[a].flags & ACTIVE) {
1365                         count++;
1366                 }
1367         }
1368         return count;
1369 }
1370
1371 static int getotherdir(void)
1372 {
1373         ScrArea *sa;
1374         SpaceFile *sfile=0;
1375         
1376         sa= G.curscreen->areabase.first;
1377         while(sa) {
1378                 if(sa!=curarea) {
1379                         if(sa->spacetype==SPACE_FILE) {
1380                                 
1381                                 /* already found one */
1382                                 if(sfile) return 0;
1383                 
1384                                 sfile= sa->spacedata.first;
1385
1386                                 if(sfile->type & FILE_UNIX) {
1387                                         otherarea= sa;
1388                                         BLI_make_file_string(G.sce, otherdir, sfile->dir, "");
1389                                 }
1390                                 else sfile= 0;
1391                         }
1392                 }
1393                 sa= sa->next;
1394         }
1395         if(sfile) return 1;
1396         return 0;
1397 }
1398
1399 static void reread_other_fs(void)
1400 {
1401         SpaceFile *sfile;
1402         
1403         /* watch it: only call when getotherdir returned OK */
1404         
1405         sfile= otherarea->spacedata.first;
1406         freefilelist(sfile);
1407         scrarea_queue_winredraw(otherarea);
1408 }
1409
1410
1411 void free_filesel_spec(char *dir)
1412 {
1413         /* all filesels with 'dir' are freed */
1414         bScreen *sc;
1415                 
1416         sc= G.main->screen.first;
1417         while(sc) {
1418                 ScrArea *sa= sc->areabase.first;
1419                 while(sa) {
1420                         SpaceLink  *sl= sa->spacedata.first;
1421                         while(sl) {
1422                                 if(sl->spacetype==SPACE_FILE) {
1423                                         SpaceFile *sfile= (SpaceFile*) sl;
1424                                         if (BLI_streq(sfile->dir, dir)) {
1425                                                 freefilelist(sfile);
1426                                         }
1427                                 }
1428                                 sl= sl->next;
1429                         }
1430                         sa= sa->next;
1431                 }
1432                 sc= sc->id.next;
1433         }
1434 }
1435
1436
1437 static void filesel_execute(SpaceFile *sfile)
1438 {
1439         struct direntry *files;
1440         char name[FILE_MAXDIR];
1441         int a;
1442         
1443         filesel_prevspace();
1444
1445         if(sfile->type==FILE_LOADLIB) {
1446                 do_library_append(sfile);
1447                 BIF_undo_push("Append from file");
1448                 allqueue(REDRAWALL, 1);
1449         }
1450         else if(sfile->returnfunc) {
1451                 fsmenu_insert_entry(sfile->dir, 1);
1452         
1453                 if(sfile->type==FILE_MAIN) { /* DATABROWSE */
1454                         if (sfile->menup) {     /* with value pointing to ID block index */
1455                                 int notfound = 1;
1456
1457                                 /*      Need special handling since hiding .* datablocks means that
1458                                         sfile->act is no longer the same as files->nr.
1459
1460                                         Also, toggle HIDE_DOT on and off can make sfile->act not longer
1461                                         correct (meaning it doesn't point to the correct item in the filelist.
1462                                         
1463                                         sfile->file is always correct, so first with check if, for the item
1464                                         corresponding to sfile->act, the name is the same.
1465
1466                                         If it isn't (or if sfile->act is not good), go over filelist and take
1467                                         the correct one.
1468
1469                                         This means that selecting a datablock than hiding it makes it
1470                                         unselectable. Not really a problem.
1471
1472                                         - theeth
1473                                  */
1474
1475                                 *sfile->menup= -1;
1476
1477                                 if(sfile->act>=0) {
1478                                         if(sfile->filelist) {
1479                                                 files= sfile->filelist+sfile->act;
1480                                                 if ( strcmp(files->relname, sfile->file)==0) {
1481                                                         notfound = 0;
1482                                                         *sfile->menup= files->nr;
1483                                                 }
1484                                         }       
1485                                 }
1486                                 if (notfound) {
1487                                         for(a=0; a<sfile->totfile; a++) {
1488                                                 if( strcmp(sfile->filelist[a].relname, sfile->file)==0) {
1489                                                         *sfile->menup= sfile->filelist[a].nr;
1490                                                         break;
1491                                                 }
1492                                         }
1493                                 }
1494                         }
1495                         sfile->returnfunc((char*) (long)sfile->retval);
1496                 }
1497                 else {
1498                         if(strncmp(sfile->title, "Save", 4)==0) free_filesel_spec(sfile->dir);
1499                         if(strncmp(sfile->title, "Export", 6)==0) free_filesel_spec(sfile->dir);
1500                         
1501                         strcpy(name, sfile->dir);
1502                         strcat(name, sfile->file);
1503                         
1504                         if(sfile->flag & FILE_STRINGCODE) BLI_makestringcode(G.sce, name);
1505
1506                         sfile->returnfunc(name);
1507                 }
1508         }
1509 }
1510
1511 static void do_filesel_buttons(short event, SpaceFile *sfile)
1512 {
1513         char butname[FILE_MAXDIR];
1514         
1515         if (event == 1) {
1516                 if (strchr(sfile->file, '*') || strchr(sfile->file, '?') || strchr(sfile->file, '[')) {
1517                         int i, match = FALSE;
1518                         
1519                         for (i = 2; i < sfile->totfile; i++) {
1520                                 if (fnmatch(sfile->file, sfile->filelist[i].relname, 0) == 0) {
1521                                         sfile->filelist[i].flags |= ACTIVE;
1522                                         match = TRUE;
1523                                 }
1524                         }
1525                         if (match) strcpy(sfile->file, "");
1526                         if(sfile->type==FILE_MAIN) filesel_select_objects(sfile);
1527                         scrarea_queue_winredraw(curarea);
1528                 }
1529         }
1530         else if(event== 2) {
1531                 /* reuse the butname variable */
1532                 BLI_cleanup_dir(G.sce, sfile->dir);
1533
1534                 BLI_make_file_string(G.sce, butname, sfile->dir, "");
1535                 /* strip the trailing slash if its a real dir */
1536                 if (strlen(butname)!=1)
1537                         butname[strlen(butname)-1]=0;
1538                 
1539                 if(sfile->type & FILE_UNIX) {
1540                         if (!BLI_exists(butname)) {
1541                                 if (okee("Makedir")) {
1542                                         BLI_recurdir_fileops(butname);
1543                                         if (!BLI_exists(butname)) parent(sfile);
1544                                 } else parent(sfile);
1545                         }
1546                 }
1547                 freefilelist(sfile);
1548                 sfile->ofs= 0;
1549                 scrarea_queue_winredraw(curarea);
1550         }
1551         else if(event== 3) {
1552                 char *selected= fsmenu_get_entry(sfile->menu-1);
1553                 
1554                 /* which string */
1555                 if (selected) {
1556                         strcpy(sfile->dir, selected);
1557                         BLI_make_exist(sfile->dir);
1558                         BLI_cleanup_dir(G.sce, sfile->dir);
1559                         freefilelist(sfile);
1560                         sfile->ofs= 0;
1561                         scrarea_queue_winredraw(curarea);
1562                 }
1563
1564                 sfile->act= -1;
1565                 
1566         }
1567         else if(event== 4) parent(sfile);
1568         else if(event== 5) {
1569                 if(sfile->type) filesel_execute(sfile);
1570         }
1571         else if(event== 6) filesel_prevspace();
1572         
1573 }
1574
1575 /****/
1576
1577 typedef void (*ReplaceFP)(ID *oldblock, ID *newblock);
1578
1579 static void change_id_link(void *linkpv, void *newlinkv) {
1580         ID **linkp= (ID**) linkpv;
1581         ID *newlink= newlinkv;
1582
1583         if (*linkp) {
1584                 (*linkp)->us--;
1585         }
1586         (*linkp)= newlink;
1587         if (newlink) {
1588                 id_us_plus(newlink);
1589         }
1590 }
1591
1592 static void replace_image(ID *oldblock, ID *newblock) {
1593         Image *oldima= (Image*) oldblock;
1594         Image *newima= (Image*) newblock;
1595         bScreen *sc;
1596         Scene *sce;
1597         Tex *tex;
1598         Mesh *me;
1599
1600         for (tex= G.main->tex.first; tex; tex= tex->id.next) {
1601                 if (tex->env && tex->env->type == ENV_LOAD && tex->env->ima == oldima)
1602                         change_id_link(&tex->env->ima, newima);
1603                 if (tex->ima == oldima)
1604                         change_id_link(&tex->ima, newima);
1605         }
1606
1607         for (sce= G.main->scene.first; sce; sce= sce->id.next) {
1608                 if (sce->ima == oldima)
1609                         change_id_link(&sce->ima, newima);
1610         }
1611
1612         for (sc= G.main->screen.first; sc; sc= sc->id.next) {
1613                 ScrArea *sa;
1614
1615                 for (sa= sc->areabase.first; sa; sa= sa->next) {
1616                         SpaceLink *sl;
1617
1618                         for (sl= sa->spacedata.first; sl; sl= sl->next) {
1619                                 if (sl->spacetype == SPACE_VIEW3D) {
1620                                         View3D *v3d= (View3D*) sl;
1621                                         BGpic *bgp= v3d->bgpic;
1622
1623                                         if (bgp && bgp->ima == oldima) 
1624                                                 change_id_link(&bgp->ima, newima);
1625                                 } else if (sl->spacetype == SPACE_IMAGE) {
1626                                         SpaceImage *sima= (SpaceImage*) sl;
1627                                         
1628                                         if (sima->image == oldima)
1629                                                 change_id_link(&sima->image, newima);
1630                                 }
1631                         }
1632                 }
1633         }
1634
1635         for (me= G.main->mesh.first; me; me= me->id.next) {
1636                 TFace *tfaces= me->tface;
1637
1638                 if (tfaces) {
1639                         int i;
1640
1641                         for (i=0; i<me->totface; i++) {
1642                                 TFace *tf= &tfaces[i];
1643
1644                                 if (tf->tpage == oldima) {
1645                                                 /* not change_id_link, tpage's aren't owners :(
1646                                                  * see hack below.
1647                                                  */
1648                                         tf->tpage= newima;
1649                                 }
1650                         }
1651                 }
1652         }
1653
1654                 /* Nasty hack, necessary because tpages don't act
1655                  * as a user, so there lots of image user count
1656                  * munging occurs... this will ensure the image
1657                  * really dies.
1658                  */
1659         oldima->id.us= 0;
1660 }
1661
1662 static void replace_material(ID *oldblock, ID *newblock)
1663 {
1664         Material *old= (Material*) oldblock;
1665         Material *new= (Material*) newblock;
1666         Material ***matarar;
1667         ID *id;
1668         Object *ob;
1669         int a;
1670         
1671         ob= G.main->object.first;
1672         while(ob) {
1673                 if(ob->totcol && ob->id.lib==0) {
1674                         matarar= give_matarar(ob);
1675                         for(a=1; a<=ob->totcol; a++) {
1676                                 if(ob->mat[a-1] == old) {
1677                                         if(old) old->id.us--;
1678                                         id_us_plus((ID *)new);
1679                                         ob->mat[a-1]= new;
1680                                 }
1681                                 id= ob->data;
1682                                 if( (*matarar)[a-1] == old  && id->lib==0) {
1683                                         if(old) old->id.us--;
1684                                         id_us_plus((ID *)new);
1685                                         (*matarar)[a-1]= new;
1686                                 }
1687                         }
1688                 }
1689                 ob= ob->id.next;
1690         }
1691 }
1692
1693 static ReplaceFP get_id_replace_function(int idcode) {
1694         switch (idcode) {
1695         case ID_MA:
1696                 return &replace_material;
1697         case ID_IM:
1698                 return &replace_image;
1699         default:
1700                 return NULL;
1701         }
1702 }
1703
1704 static void databrowse_replace(SpaceFile *sfile, int idcode)
1705 {
1706         ReplaceFP replace_func= get_id_replace_function(idcode);
1707
1708         if (!replace_func) {
1709                 error("Replacing %s blocks is unsupported", BLO_idcode_to_name(idcode));
1710         } else if (sfile->act==-1) {
1711                 error("Select target with leftmouse");
1712         } else {
1713                 ID *target= (ID*) sfile->filelist[sfile->act].poin;
1714
1715                 if (target) {
1716                         char buf[128];
1717
1718                         sprintf(buf, "Replace with %s: %s", BLO_idcode_to_name(idcode), target->name+2);
1719
1720                         if (okee(buf)) {
1721                                 int i;
1722
1723                                 for (i = 0; i <sfile->totfile; i++)
1724                                         if ((sfile->filelist[i].flags&ACTIVE) && sfile->filelist[i].poin!=target)
1725                                                 replace_func(sfile->filelist[i].poin, target);
1726                         }
1727                 }
1728         }
1729
1730         freefilelist(sfile);
1731         scrarea_queue_winredraw(curarea);
1732 }
1733
1734 static void fs_fake_users(SpaceFile *sfile)
1735 {
1736         ID *id;
1737         int a;
1738         
1739         /* only for F4 DATABROWSE */
1740         if(sfile->returnfunc) return;
1741         
1742         for(a=0; a<sfile->totfile; a++) {
1743                 if(sfile->filelist[a].flags & ACTIVE) {
1744                         id= (ID *)sfile->filelist[a].poin;
1745                         if(id) {
1746                                 if( id->flag & LIB_FAKEUSER) {
1747                                         id->flag -= LIB_FAKEUSER;
1748                                         id->us--;
1749                                 }
1750                                 else {
1751                                         id->flag |= LIB_FAKEUSER;
1752                                         id->us++;
1753                                 }
1754                         }
1755                 }
1756         }
1757         freefilelist(sfile);
1758         scrarea_queue_winredraw(curarea);
1759 }
1760
1761
1762 static int get_hilited_entry(SpaceFile *sfile)
1763 {
1764         int a;
1765
1766         for(a=0; a<sfile->totfile; a++) {
1767                 if(sfile->filelist[a].flags & HILITE) {
1768                         return a;
1769                 }
1770         }
1771         return -1;
1772 }
1773
1774
1775 void winqreadfilespace(ScrArea *sa, void *spacedata, BWinEvent *evt)
1776 {
1777         unsigned short event= evt->event;
1778         short val= evt->val;
1779         static int acto=0;
1780         SpaceFile *sfile;
1781         int act, do_draw= 0, i, test, ret = 0;
1782         short qual, mval[2];
1783         char str[FILE_MAXDIR+FILE_MAXFILE+12];
1784         
1785         sfile= curarea->spacedata.first;
1786         if(sfile==0) return;
1787         if(sfile->filelist==0) {
1788                 return;
1789         }
1790         
1791         if(curarea->win==0) return;
1792         calc_file_rcts(sfile);
1793         getmouseco_areawin(mval);
1794
1795         /* prevent looping */
1796         if(selecting && !(get_mbut() & R_MOUSE)) selecting= 0;
1797
1798         if(val) {
1799
1800                 if( event!=RETKEY && event!=PADENTER)
1801                         if( uiDoBlocks(&curarea->uiblocks, event)!=UI_NOTHING ) event= 0;
1802
1803                 switch(event) {
1804                 
1805                 case UI_BUT_EVENT:
1806                         do_filesel_buttons(val, sfile);
1807                         break;          
1808                 
1809                 case WHEELDOWNMOUSE:
1810                         do_filescrollwheel(sfile, U.wheellinescroll);
1811                         act= find_active_file(sfile, mval[0], mval[1]);
1812                         set_active_file(sfile, act);
1813                         do_draw= 1;
1814                         break;
1815                 case WHEELUPMOUSE:
1816                         do_filescrollwheel(sfile, -U.wheellinescroll);
1817                         act= find_active_file(sfile, mval[0], mval[1]);
1818                         set_active_file(sfile, act);
1819                         do_draw= 1;
1820                         break;
1821
1822                 case LEFTMOUSE:
1823                 case MIDDLEMOUSE:
1824                         if(mval[0]>scrollrct.xmin && mval[0]<scrollrct.xmax && mval[1]>scrollrct.ymin && mval[1]<scrollrct.ymax) {
1825                                 do_filescroll(sfile);
1826                         }
1827                         else if(mval[0]>textrct.xmin && mval[0]<textrct.xmax && mval[1]>textrct.ymin && mval[1]<textrct.ymax) {
1828                                 
1829                                 /* sfile->act is used in databrowse: double names of library objects */
1830                                 
1831                                 sfile->act= act= find_active_file(sfile, mval[0], mval[1]);
1832                                 
1833                                 if(act>=0 && act<sfile->totfile) {
1834                                         if(S_ISDIR(sfile->filelist[act].type)) {
1835                                                 strcat(sfile->dir, sfile->filelist[act].relname);
1836                                                 strcat(sfile->dir,"/");
1837                                                 BLI_cleanup_dir(G.sce, sfile->dir);
1838                                                 freefilelist(sfile);
1839                                                 sfile->ofs= 0;
1840                                                 do_draw= 1;
1841                                         }
1842                                         else {
1843                                                 if( strcmp(sfile->file, sfile->filelist[act].relname)) {
1844                                                         do_draw= 1;
1845                                                         strcpy(sfile->file, sfile->filelist[act].relname);
1846                                                 }
1847                                                 if(event==MIDDLEMOUSE && sfile->type) filesel_execute(sfile);
1848                                         }
1849                                 }
1850                         }
1851                         break;
1852                 case RIGHTMOUSE:
1853                         act= find_active_file(sfile, mval[0], mval[1]);
1854                         acto= act;
1855                         if(act>=0 && act<sfile->totfile) {
1856
1857                                 if (sfile->filelist[act].flags & ACTIVE) {
1858                                         sfile->filelist[act].flags &= ~ACTIVE;
1859                                         selecting = INACTIVATE;
1860                                 }
1861                                 else {
1862                                         test= sfile->filelist[act].relname[0];
1863                                         if (act>=2 || test!='.') sfile->filelist[act].flags |= ACTIVE;
1864                                         
1865                                         selecting = ACTIVATE;
1866                                 }
1867                                 do_draw= 1;
1868                         }
1869                         break;
1870                 case MOUSEY:
1871                         act= find_active_file(sfile, mval[0], mval[1]);
1872                         if (act!=acto) {
1873                                 set_active_file(sfile, act);
1874                         }
1875                         if(selecting && act!=acto) {
1876                                         
1877                                 while(1) {
1878                                         if (acto >= 2 && acto < sfile->totfile) {
1879                                                 if (selecting == ACTIVATE) sfile->filelist[acto].flags |= ACTIVE;
1880                                                 else if (selecting == INACTIVATE) sfile->filelist[acto].flags &= ~ACTIVE;
1881                                         }
1882                                         if (acto < act) acto++;
1883                                         else if (acto > act) acto--;
1884                                         else break;
1885                                         
1886                                 }
1887
1888                         }
1889                         acto= act;
1890                         break;
1891                 
1892                 case PAGEUPKEY:
1893                         sfile->ofs-= page_ofs;
1894                         do_draw= 1;
1895                         break;
1896                 case PAGEDOWNKEY:
1897                         sfile->ofs+= page_ofs;
1898                         do_draw= 1;
1899                         break;
1900                 case HOMEKEY:
1901                         sfile->ofs= 0;
1902                         do_draw= 1;
1903                         break;
1904                 case ENDKEY:
1905                         sfile->ofs= sfile->totfile;
1906                         do_draw= 1;
1907                         break;
1908                 
1909                 case AKEY:
1910                         swapselect_file(sfile);
1911                         if(sfile->type==FILE_MAIN) filesel_select_objects(sfile);
1912                         do_draw= 1;
1913                         break;
1914                         
1915                 case BKEY:
1916                 case CKEY:
1917                 case LKEY:
1918                         if(event==LKEY && sfile->type==FILE_MAIN && (G.qual & LR_CTRLKEY)) {
1919                                 databrowse_replace(sfile, groupname_to_code(sfile->dir));
1920                                 break;
1921                         }
1922                         /* pass */
1923                 case MKEY:
1924                         if(sfile->type==FILE_MAIN) break;
1925
1926                         if(!countselect(sfile)) {
1927                                 error("No files selected");
1928                                 break;
1929                         }
1930                         
1931                         if(!getotherdir()) {
1932                                 error("No second fileselect");
1933                                 break;
1934                         }
1935                         
1936                         if (!strcmp(sfile->dir, otherdir)) {
1937                                 error("Same directories");
1938                                 break;
1939                         }
1940
1941                         if(event==BKEY) sprintf(str, "Backup to %s", otherdir);
1942                         else if(event==CKEY) sprintf(str, "Copy to %s", otherdir);
1943                         else if(event==LKEY) sprintf(str, "Linked copy to %s", otherdir);
1944                         else if(event==MKEY) sprintf(str, "Move to %s", otherdir);
1945                                         
1946                         if (!okee(str)) break;
1947
1948                         for (i = 0; i<sfile->totfile; i++){
1949                                 if (sfile->filelist[i].flags & ACTIVE) {                        
1950                                         BLI_make_file_string(G.sce, str, sfile->dir, sfile->filelist[i].relname);
1951
1952                                         if(event==BKEY) ret= BLI_backup(sfile->filelist[i].relname, sfile->dir, otherdir);
1953                                         else if(event==CKEY) ret= BLI_copy_fileops(str, otherdir);
1954                                         else if(event==LKEY) ret= BLI_link(str, otherdir);
1955                                         else if(event==MKEY) ret= BLI_move(str, otherdir);
1956
1957                                         if (ret) {error("Command failed, see console"); break;}
1958                                         else sfile->filelist[i].flags &= ~ACTIVE;
1959                                 }
1960                         }
1961                         do_draw= 1;
1962                         if(event==BKEY || event==MKEY) 
1963                                 freefilelist(sfile);
1964                                 
1965                         reread_other_fs();
1966                         
1967                         break;
1968
1969                 case XKEY:
1970                         test = get_hilited_entry(sfile);
1971
1972                         if (test != -1 && !(S_ISDIR(sfile->filelist[test].type))){
1973                                 BLI_make_file_string(G.sce, str, sfile->dir, sfile->filelist[test].relname);
1974
1975                                 if( okee("Remove %s", str) ) {
1976                                         ret = BLI_delete(str, 0, 0);
1977                                         if (ret) {
1978                                                 error("Command failed, see console");
1979                                         } else {
1980                                                 freefilelist(sfile);
1981                                                 do_draw= 1;
1982                                         }
1983                                 }
1984                         }
1985                         break;
1986
1987                 case RKEY:
1988                         if(sfile->type==FILE_MAIN) {
1989                                 databrowse_replace(sfile, groupname_to_code(sfile->dir));
1990                                 break;
1991                         }
1992                         /* pass to TKEY! */
1993                         
1994                 case TKEY:
1995                         if(sfile->type==FILE_MAIN) break;
1996                         
1997                         if(!countselect(sfile)) {
1998                                 error("No files selected");
1999                                 break;
2000                         }
2001
2002                         if(event==TKEY) sprintf(str, "Touch");
2003                         else if(event==RKEY) sprintf(str, "Remove from %s", sfile->dir);
2004                         
2005                         qual= G.qual;   /* because after okee() you released the SHIFT */
2006                         if (!okee(str)) break;
2007                         
2008                         for (i = 0; i <sfile->totfile; i++) {
2009                                 if (sfile->filelist[i].flags & ACTIVE) {
2010                                         BLI_make_file_string(G.sce, str, sfile->dir, sfile->filelist[i].relname);
2011
2012                                         if(event==TKEY) ret= BLI_touch(str);
2013                                         else if(event==RKEY) {
2014                                                 if(qual & LR_SHIFTKEY) ret= BLI_delete(str, 0, 1);
2015                                                 else if(S_ISDIR(sfile->filelist[i].type)) ret= BLI_delete(str, 1, 0);
2016                                                 else ret= BLI_delete(str, 0, 0);
2017                                         }
2018
2019                                         if (ret) {error("Command failed, see console"); break;}
2020                                         else sfile->filelist[i].flags &= ~ACTIVE;
2021                                 }
2022                         }
2023                         do_draw= 1;
2024                         freefilelist(sfile);
2025
2026                         break;
2027                                 
2028                 case PKEY:
2029                         if(G.qual & LR_SHIFTKEY) {
2030                                 extern char bprogname[];        /* usiblender.c */
2031                         
2032                                 sprintf(str, "%s -a \"%s%s\"", bprogname, sfile->dir, sfile->file);
2033                                 system(str);
2034                         }
2035                         else 
2036                                 parent(sfile);
2037                                 
2038                         break;
2039
2040                 case IKEY:
2041                         if(sfile->type==FILE_MAIN) break;
2042                         
2043                         sprintf(str, "$IMAGEEDITOR %s%s", sfile->dir, sfile->file);
2044                         system(str);
2045                         break;
2046                 
2047                 case EKEY:
2048                         if(sfile->type==FILE_MAIN) break;
2049                         
2050                         sprintf(str, "$WINEDITOR %s%s", sfile->dir, sfile->file);
2051                         system(str);
2052                         break;
2053                 
2054                 case FKEY:
2055                         if(sfile->type==FILE_MAIN) {
2056                                 fs_fake_users(sfile);
2057                         }
2058                         break;
2059                                 
2060                 case PADPLUSKEY:
2061                 case EQUALKEY:
2062                         if (G.qual & LR_CTRLKEY) BLI_newname(sfile->file, +100);
2063                         else if (G.qual & LR_SHIFTKEY) BLI_newname(sfile->file, +10);
2064                         else BLI_newname(sfile->file, +1);
2065                         
2066                         do_draw= 1;
2067                         break;
2068                         
2069                 case PADMINUS:
2070                 case MINUSKEY:
2071                         if (G.qual & LR_CTRLKEY) BLI_newname(sfile->file, -100);
2072                         else if (G.qual & LR_SHIFTKEY) BLI_newname(sfile->file, -10);
2073                         else BLI_newname(sfile->file, -1);
2074                         
2075                         do_draw= 1;
2076                         break;
2077                         
2078                 case BACKSLASHKEY:
2079                 case SLASHKEY:
2080                         if(sfile->type==FILE_MAIN) break;
2081
2082 #ifdef WIN32
2083                         strcpy(sfile->dir, "\\");
2084 #else
2085                         strcpy(sfile->dir, "/");
2086 #endif
2087                         freefilelist(sfile);
2088                         sfile->ofs= 0;
2089                         do_draw= 1;
2090                         break;
2091                 case PERIODKEY:
2092                         freefilelist(sfile);
2093                         do_draw= 1;
2094                         break;
2095                 case ESCKEY:
2096                         filesel_prevspace();
2097                         break;
2098                 case PADENTER:
2099                 case RETKEY:
2100                         if(sfile->type) filesel_execute(sfile);
2101                         break;
2102                 }
2103         }
2104         else if(event==RIGHTMOUSE) {
2105                 selecting = NOTACTIVE;
2106                 if(sfile->type==FILE_MAIN) filesel_select_objects(sfile);
2107         }
2108         else if(event==LEFTMOUSE) {
2109                 if(sfile->type==FILE_MAIN) active_file_object(sfile);
2110         }
2111
2112                 /* XXX, stupid patch, curarea can become undone
2113                  * because of file loading... fixme zr
2114                  */
2115         if(do_draw && curarea) scrarea_queue_winredraw(curarea);
2116 }
2117
2118
2119
2120
2121 /* ************* LIBRARY FILESEL ******************* */
2122
2123 static int groupname_to_code(char *group)
2124 {
2125         char buf[32];
2126         char *lslash;
2127         
2128         BLI_strncpy(buf, group, 31);
2129         lslash= BLI_last_slash(buf);
2130         if (lslash)
2131                 lslash[0]= '\0';
2132
2133         return BLO_idcode_from_name(buf);
2134 }
2135
2136 static int is_a_library(SpaceFile *sfile, char *dir, char *group)
2137 {
2138         /* return ok when a blenderfile, in dir is the filename,
2139          * in group the type of libdata
2140          */
2141         int len;
2142         char *fd;
2143         
2144         strcpy(dir, sfile->dir);
2145         len= strlen(dir);
2146         if(len<7) return 0;
2147         if( dir[len-1] != '/' && dir[len-1] != '\\') return 0;
2148                 
2149         group[0]= 0;
2150         dir[len-1]= 0;
2151
2152         /* Find the last slash */
2153         fd= (strrchr(dir, '/')>strrchr(dir, '\\'))?strrchr(dir, '/'):strrchr(dir, '\\');
2154
2155         if(fd==0) return 0;
2156         *fd= 0;
2157         if(BLO_has_bfile_extension(fd+1)) {
2158                 *fd= '/';
2159         }
2160         else {
2161                 strcpy(group, fd+1);
2162                         
2163                 /* Find the last slash */
2164                 fd= (strrchr(dir, '/')>strrchr(dir, '\\'))?strrchr(dir, '/'):strrchr(dir, '\\');
2165                 if (!fd || !BLO_has_bfile_extension(fd+1)) return 0;
2166         }
2167         return 1;
2168 }
2169
2170 /* orange hack... :) */
2171 static void do_sync_pose(Library *lib)
2172 {
2173         Object *ob, *obt;
2174         Base *base;
2175         bArmature *arm;
2176         
2177         /* find the armature and the pose from library */
2178         for(ob= G.main->object.first; ob; ob= ob->id.next)
2179                 if(ob->type==OB_ARMATURE && ob->id.lib==lib)
2180                         break;
2181         
2182         if(ob==NULL || ob->pose==NULL) {
2183                 error("No pose appended");
2184                 return;
2185         }
2186         
2187         arm= ob->data;
2188
2189         /* for all visible objects in this scene */
2190         for(base= G.scene->base.first; base; base= base->next) {
2191                 if((base->flag & SELECT)) {
2192                         obt= base->object;
2193                         if(obt->type==OB_ARMATURE && obt->pose && ob!=obt) {
2194                                 char str[128];
2195                                 
2196                                 sprintf(str, "Replace Object %s", obt->id.name);
2197                                 if(okee(str)) {
2198                                         bPoseChannel *chan;
2199                                         bArmature *oldarm= obt->data;
2200                                         
2201                                         /* link armature */
2202                                         oldarm->id.us--;
2203                                         obt->data= arm;
2204                                         arm->id.us++;
2205                                         
2206                                         /* link pose */
2207                                         free_pose_channels(obt->pose);
2208                                         MEM_freeN(obt->pose);
2209                                         copy_pose(&obt->pose, ob->pose, 1);
2210                                         
2211                                         /* relink */
2212                                         ob->id.newid= &obt->id;
2213                                         for (chan = obt->pose->chanbase.first; chan; chan=chan->next){
2214                                                 relink_constraints(&chan->constraints);
2215                                         }
2216                                         
2217                                         obt->pose->flag |= POSE_RECALC;
2218                                         obt->recalc |= OB_RECALC_DATA;
2219                                 }
2220                         }
2221                 }
2222         }
2223
2224         /* prevent saving in file, unlink from scene */
2225         for(base= G.scene->base.first; base; base= base->next) {
2226                 if(base->object==ob)
2227                         break;
2228         }
2229         
2230         if(base) {
2231                 free_and_unlink_base(base);
2232         }
2233
2234         DAG_scene_sort(G.scene);        // for accidentally appended other objects
2235 }
2236
2237 static void do_library_append(SpaceFile *sfile)
2238 {
2239         Library *lib;
2240         char dir[FILE_MAXDIR], group[32];
2241         
2242         if ( is_a_library(sfile, dir, group)==0 ) {
2243                 error("Not a library");
2244         } else if (!sfile->libfiledata) {
2245                 error("Library not loaded");
2246         } else if (group[0]==0) {
2247                 error("Nothing indicated");
2248         } else if (BLI_streq(G.main->name, dir)) {
2249                 error("Cannot use current file as library");
2250         } else {
2251                 Object *ob;
2252                 int idcode = groupname_to_code(group);
2253                 
2254                 BLO_library_append(sfile, dir, idcode); /* warning; if relative, it changes the *dir to relative path */
2255
2256                 /* DISPLISTS? */
2257                 ob= G.main->object.first;
2258                 while(ob) {
2259                         if(ob->id.lib) {
2260                                 ob->recalc |= OB_RECALC;
2261                         }
2262                         ob= ob->id.next;
2263                 }
2264         
2265                 /* and now find the latest append lib file */
2266                 lib= G.main->library.first;
2267                 while(lib) {
2268                         if (BLI_streq(dir, lib->name)) break;
2269                         lib= lib->id.next;
2270                 }
2271                 
2272                 if(lib) {
2273                         if(sfile->flag & FILE_SYNCPOSE)
2274                                 do_sync_pose(lib);
2275                         if((sfile->flag & FILE_LINK)==0) 
2276                                 all_local(lib);
2277                 }
2278                 
2279                 /* in sfile->dir is the whole lib name */
2280                 strcpy(G.lib, sfile->dir);
2281                 
2282         }
2283 }
2284
2285 static void library_to_filelist(SpaceFile *sfile)
2286 {
2287         LinkNode *l, *names;
2288         int ok, i, nnames, idcode;
2289         char filename[FILE_MAXDIR+FILE_MAXFILE];
2290         char dir[FILE_MAXDIR], group[24];
2291         
2292         /* name test */
2293         ok= is_a_library(sfile, dir, group);
2294         if (!ok) {
2295                 /* free */
2296                 if(sfile->libfiledata) BLO_blendhandle_close(sfile->libfiledata);
2297                 sfile->libfiledata= 0;
2298                 return;
2299         }
2300         
2301         BLI_strncpy(filename, G.sce, sizeof(filename)); // G.sce = last file loaded, for UI
2302         
2303         /* there we go */
2304         /* for the time being only read filedata when libfiledata==0 */
2305         if (sfile->libfiledata==0) {
2306                 sfile->libfiledata= BLO_blendhandle_from_file(dir);     // this sets G.sce, we dont want it
2307                 
2308                 if(sfile->libfiledata==0) return;
2309         }
2310         
2311         idcode= groupname_to_code(group);
2312
2313                 // memory for strings is passed into filelist[i].relname
2314                 // and free'd in freefilelist
2315         if (idcode) {
2316                 names= BLO_blendhandle_get_datablock_names(sfile->libfiledata, idcode);
2317         } else {
2318                 names= BLO_blendhandle_get_linkable_groups(sfile->libfiledata);
2319         }
2320         
2321         nnames= BLI_linklist_length(names);
2322
2323         sfile->totfile= nnames + 2;
2324         sfile->filelist= malloc(sfile->totfile * sizeof(*sfile->filelist));
2325         memset(sfile->filelist, 0, sfile->totfile * sizeof(*sfile->filelist));
2326
2327         sfile->filelist[0].relname= BLI_strdup(".");
2328         sfile->filelist[0].type |= S_IFDIR;
2329         sfile->filelist[1].relname= BLI_strdup("..");
2330         sfile->filelist[1].type |= S_IFDIR;
2331                 
2332         for (i=0, l= names; i<nnames; i++, l= l->next) {
2333                 char *blockname= BLI_strdup(l->link); 
2334
2335                 sfile->filelist[i + 2].relname= blockname;
2336                 if (!idcode)
2337                         sfile->filelist[i + 2].type |= S_IFDIR;
2338         }
2339                 
2340         BLI_linklist_free(names, free);
2341         
2342         qsort(sfile->filelist, sfile->totfile, sizeof(struct direntry), compare_name);
2343         
2344         sfile->maxnamelen= 0;
2345         for(i=0; i<sfile->totfile; i++) {
2346                 int len = BMF_GetStringWidth(G.font, sfile->filelist[i].relname);
2347                 if (len > sfile->maxnamelen)
2348                         sfile->maxnamelen = len;
2349         }
2350         
2351         BLI_strncpy(G.sce, filename, sizeof(filename)); // prevent G.sce to change
2352
2353 }
2354
2355 /* ******************* DATA SELECT ********************* */
2356
2357 static void filesel_select_objects(SpaceFile *sfile)
2358 {
2359         Object *ob;
2360         Base *base;
2361         Scene *sce;
2362         int a;
2363         
2364         /* only when F4 DATABROWSE */
2365         if(sfile->returnfunc) return;
2366         
2367         if( strcmp(sfile->dir, "Object/")==0 ) {
2368                 for(a=0; a<sfile->totfile; a++) {
2369                         
2370                         ob= (Object *)sfile->filelist[a].poin;
2371                         
2372                         if(ob) {
2373                                 if(sfile->filelist[a].flags & ACTIVE) ob->flag |= SELECT;
2374                                 else ob->flag &= ~SELECT;
2375                         }
2376
2377                 }
2378                 base= FIRSTBASE;
2379                 while(base) {
2380                         base->flag= base->object->flag;
2381                         base= base->next;
2382                 }
2383                 countall();
2384                 allqueue(REDRAWVIEW3D, 0);
2385                 allqueue(REDRAWOOPS, 0);
2386         }
2387         else if( strcmp(sfile->dir, "Scene/")==0 ) {
2388                 
2389                 for(a=0; a<sfile->totfile; a++) {
2390                         
2391                         sce= (Scene *)sfile->filelist[a].poin;
2392                         if(sce) {
2393                                 if(sfile->filelist[a].flags & ACTIVE) sce->r.scemode |= R_BG_RENDER;
2394                                 else sce->r.scemode &= ~R_BG_RENDER;
2395                         }
2396
2397                 }
2398                 allqueue(REDRAWBUTSSCENE, 0);
2399         }
2400 }
2401
2402 static void active_file_object(SpaceFile *sfile)
2403 {
2404         Object *ob;
2405         
2406         /* only when F4 DATABROWSE */
2407         if(sfile->returnfunc) return;
2408         
2409         if( strcmp(sfile->dir, "Object/")==0 ) {
2410                 if(sfile->act >= 0) {
2411                         
2412                         ob= (Object *)sfile->filelist[sfile->act].poin;
2413                         
2414                         if(ob) {
2415                                 set_active_object(ob);
2416                                 if(BASACT && BASACT->object==ob) {
2417                                         BASACT->flag |= SELECT;
2418                                         sfile->filelist[sfile->act].flags |= ACTIVE;
2419                                         allqueue(REDRAWVIEW3D, 0);
2420                                         allqueue(REDRAWOOPS, 0);
2421                                         scrarea_queue_winredraw(curarea);
2422                                 }
2423                         }
2424                 }
2425         }
2426 }
2427
2428
2429 void main_to_filelist(SpaceFile *sfile)
2430 {
2431         ID *id;
2432         struct direntry *files, *firstlib = NULL;
2433         ListBase *lb;
2434         int a, fake, idcode, len, ok, totlib, totbl;
2435         short hide = 0;
2436
2437         if (sfile->flag & FILE_HIDE_DOT)
2438                 hide = 1;
2439
2440         if(sfile->dir[0]=='/') sfile->dir[0]= 0;
2441         
2442         if(sfile->dir[0]) {
2443                 idcode= groupname_to_code(sfile->dir);
2444                 if(idcode==0) sfile->dir[0]= 0;
2445         }
2446         
2447         if( sfile->dir[0]==0) {
2448                 
2449                 /* make directories */
2450                 sfile->totfile= 23;
2451                 sfile->filelist= (struct direntry *)malloc(sfile->totfile * sizeof(struct direntry));
2452                 
2453                 for(a=0; a<sfile->totfile; a++) {
2454                         memset( &(sfile->filelist[a]), 0 , sizeof(struct direntry));
2455                         sfile->filelist[a].type |= S_IFDIR;
2456                 }
2457                 
2458                 sfile->filelist[0].relname= BLI_strdup("..");
2459                 sfile->filelist[1].relname= BLI_strdup(".");
2460                 sfile->filelist[2].relname= BLI_strdup("Scene");
2461                 sfile->filelist[3].relname= BLI_strdup("Group");
2462                 sfile->filelist[4].relname= BLI_strdup("Object");
2463                 sfile->filelist[5].relname= BLI_strdup("Mesh");
2464                 sfile->filelist[6].relname= BLI_strdup("Curve");
2465                 sfile->filelist[7].relname= BLI_strdup("Metaball");
2466                 sfile->filelist[8].relname= BLI_strdup("Material");
2467                 sfile->filelist[9].relname= BLI_strdup("Texture");
2468                 sfile->filelist[10].relname= BLI_strdup("Image");
2469                 sfile->filelist[11].relname= BLI_strdup("Wave");
2470                 sfile->filelist[12].relname= BLI_strdup("Lattice");
2471                 sfile->filelist[13].relname= BLI_strdup("Lamp");
2472                 sfile->filelist[14].relname= BLI_strdup("Camera");
2473                 sfile->filelist[15].relname= BLI_strdup("Ipo");
2474                 sfile->filelist[16].relname= BLI_strdup("World");
2475                 sfile->filelist[17].relname= BLI_strdup("Screen");
2476                 sfile->filelist[18].relname= BLI_strdup("VFont");
2477                 sfile->filelist[19].relname= BLI_strdup("Text");
2478                 sfile->filelist[20].relname= BLI_strdup("Armature");
2479                 sfile->filelist[21].relname= BLI_strdup("Action");
2480                 sfile->filelist[22].relname= BLI_strdup("NodeTree");
2481                 
2482                 qsort(sfile->filelist, sfile->totfile, sizeof(struct direntry), compare_name);
2483         }
2484         else {
2485
2486                 /* make files */
2487                 idcode= groupname_to_code(sfile->dir);
2488                 
2489                 lb= wich_libbase(G.main, idcode );
2490                 if(lb==0) return;
2491                 
2492                 id= lb->first;
2493                 sfile->totfile= 0;
2494                 while(id) {
2495                         if(sfile->returnfunc && idcode==ID_IP) {
2496                                 if(sfile->ipotype== ((Ipo *)id)->blocktype) sfile->totfile++;
2497                         }
2498                         else if (hide==0 || id->name[2] != '.')
2499                                 sfile->totfile++;
2500
2501                         id= id->next;
2502                 }
2503                 
2504                 if(sfile->returnfunc==0) sfile->totfile+= 2;
2505                 sfile->filelist= (struct direntry *)malloc(sfile->totfile * sizeof(struct direntry));
2506                 
2507                 files= sfile->filelist;
2508                 
2509                 if(sfile->returnfunc==0) {
2510                         memset( &(sfile->filelist[0]), 0 , sizeof(struct direntry));
2511                         sfile->filelist[0].relname= BLI_strdup(".");
2512                         sfile->filelist[0].type |= S_IFDIR;
2513                         memset( &(sfile->filelist[1]), 0 , sizeof(struct direntry));
2514                         sfile->filelist[1].relname= BLI_strdup("..");
2515                         sfile->filelist[1].type |= S_IFDIR;
2516                 
2517                         files+= 2;
2518                 }
2519                 
2520                 id= lb->first;
2521                 totlib= totbl= 0;
2522                 
2523                 while(id) {
2524                         
2525                         ok= 0;
2526                         if(sfile->returnfunc && idcode==ID_IP) {
2527                                 if(sfile->ipotype== ((Ipo *)id)->blocktype) ok= 1;
2528                         }
2529                         else ok= 1;
2530                         
2531                         if(ok) {
2532                 
2533                                 if (hide==0 || id->name[2] != '.') {
2534                                         memset( files, 0 , sizeof(struct direntry));
2535                                         if(id->lib==NULL)
2536                                                 files->relname= BLI_strdup(id->name+2);
2537                                         else {
2538                                                 files->relname= MEM_mallocN(FILE_MAXDIR+FILE_MAXFILE+32, "filename for lib");
2539                                                 sprintf(files->relname, "%s | %s", id->lib->name, id->name+2);
2540                                         }
2541                                         
2542                                         if(sfile->returnfunc==0) { /* F4 DATA BROWSE */
2543                                                 if(idcode==ID_OB) {
2544                                                         if( ((Object *)id)->flag & SELECT) files->flags |= ACTIVE;
2545                                                 }
2546                                                 else if(idcode==ID_SCE) {
2547                                                         if( ((Scene *)id)->r.scemode & R_BG_RENDER) files->flags |= ACTIVE;
2548                                                 }
2549                                         }
2550                                         files->nr= totbl+1;
2551                                         files->poin= id;
2552                                         fake= id->flag & LIB_FAKEUSER;
2553                                         
2554                                         if(id->lib && fake) sprintf(files->extra, "LF %d", id->us);
2555                                         else if(id->lib) sprintf(files->extra, "L    %d", id->us);
2556                                         else if(fake) sprintf(files->extra, "F    %d", id->us);
2557                                         else sprintf(files->extra, "      %d", id->us);
2558                                         
2559                                         if(id->lib) {
2560                                                 if(totlib==0) firstlib= files;
2561                                                 totlib++;
2562                                         }
2563                                         
2564                                         files++;
2565                                 }
2566                                 totbl++;
2567                         }
2568                         
2569                         id= id->next;
2570                 }
2571                 
2572                 /* only qsort of libraryblokken */
2573                 if(totlib>1) {
2574                         qsort(firstlib, totlib, sizeof(struct direntry), compare_name);
2575                 }
2576         }
2577
2578         sfile->maxnamelen= 0;
2579         for(a=0; a<sfile->totfile; a++) {
2580                 len = BMF_GetStringWidth(G.font, sfile->filelist[a].relname);
2581                 if (len > sfile->maxnamelen) sfile->maxnamelen = len;
2582                 
2583                 if(filetoname) {
2584                         if( strcmp(sfile->file, sfile->filelist[a].relname)==0) {
2585                                 sfile->ofs= a-( sfile->collums*(curarea->winy-FILESELHEAD-10)/(2*FILESEL_DY));
2586                                 filetoname= 0;
2587                                 if(sfile->returnfunc) sfile->filelist[a].flags |= ACTIVE;
2588                         }
2589                 }
2590         }
2591 }
2592
2593
2594 void clever_numbuts_filesel()
2595 {
2596         SpaceFile *sfile;
2597         char orgname[FILE_MAXDIR+FILE_MAXFILE+12];
2598         char filename[FILE_MAXDIR+FILE_MAXFILE+12];
2599         char newname[FILE_MAXDIR+FILE_MAXFILE+12];
2600         int test;
2601         int len;
2602         
2603         sfile= curarea->spacedata.first;
2604
2605         if(sfile->type==FILE_MAIN) return;
2606         
2607         len = 110;
2608         test = get_hilited_entry(sfile);
2609
2610         if (test != -1 && !(S_ISDIR(sfile->filelist[test].type))){
2611                 BLI_make_file_string(G.sce, orgname, sfile->dir, sfile->filelist[test].relname);
2612                 strcpy(filename, sfile->filelist[test].relname);
2613                 
2614                 add_numbut(0, TEX, "", 0, len, filename, "Rename File");
2615
2616                 if( do_clever_numbuts("Rename File", 1, REDRAW) ) {
2617                         BLI_make_file_string(G.sce, newname, sfile->dir, filename);
2618
2619                         if( strcmp(orgname, newname) != 0 ) {
2620                                 BLI_rename(orgname, newname);
2621                                 freefilelist(sfile);
2622                         }
2623                 }
2624
2625                 scrarea_queue_winredraw(curarea);
2626         }
2627 }
2628