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