Styken's fix for bug # 1035
[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         if (val == 0) coll = 0;
1015         else coll= nr/val;
1016         nr -= coll*val;
1017         
1018         *valy= textrct.ymax-FILESEL_DY+3 - nr*FILESEL_DY;
1019         *valx= coll*collumwidth + textrct.xmin+20;
1020         
1021         if(nr<0 || coll > sfile->collums) return 0;
1022         return 1;
1023 }
1024
1025 static void set_active_file(SpaceFile *sfile, int act)
1026 {
1027         struct direntry *file;
1028         int num, redraw= 0, newflag;
1029         int old=0, newi=0;
1030         
1031         file= sfile->filelist;
1032         if(file==0) return;
1033         
1034         for(num=0; num<sfile->totfile; num++, file++) {
1035                 if(num==act) {
1036                         
1037                         if(selecting && num>1) {
1038                                 newflag= HILITE | (file->flags & ~ACTIVE);
1039                                 if(selecting==ACTIVATE) newflag |= ACTIVE;
1040                         
1041                                 if(file->flags != newflag) redraw|= 1;
1042                                 file->flags= newflag;
1043                         }
1044                         else {
1045                                 if(file->flags & HILITE);
1046                                 else {
1047                                         file->flags |= HILITE;
1048                                         redraw|= 2;
1049                                         newi= num;
1050                                 }
1051                         }
1052                 }
1053                 else {
1054                         if(file->flags & HILITE) {
1055                                 file->flags &= ~HILITE;
1056                                 redraw|= 2;
1057                                 old= num;
1058                         }
1059                 }
1060                         
1061         }
1062         
1063         if(redraw==2) {
1064                 int x, y;
1065                 
1066                 glDrawBuffer(GL_FRONT);
1067
1068                 glScissor(curarea->winrct.xmin, curarea->winrct.ymin, curarea->winx-12, curarea->winy);
1069
1070                 if( calc_filesel_regel(sfile, old, &x, &y) ) {
1071                         regelrect(0, x, y);
1072                         printregel(sfile, sfile->filelist+old, x, y);
1073                 }
1074                 if( calc_filesel_regel(sfile, newi, &x, &y) ) {
1075                         printregel(sfile, sfile->filelist+newi, x, y);
1076                 }
1077                 
1078                 glScissor(curarea->winrct.xmin, curarea->winrct.ymin, curarea->winx, curarea->winy);
1079
1080                 glFinish();             /* for geforce, to show it in the frontbuffer */
1081                 glDrawBuffer(GL_BACK);
1082         }
1083         else if(redraw) {
1084                 scrarea_queue_winredraw(curarea);
1085         }
1086 }
1087
1088
1089 static void draw_filetext(SpaceFile *sfile)
1090 {
1091         struct direntry *files;
1092         int a, x, y;
1093         short mval[2];
1094         
1095         if(textrct.ymin+10 >= textrct.ymax) return;
1096
1097
1098         /* box */
1099         BIF_ThemeColor(TH_BACK);
1100         glRecti(textrct.xmin,  textrct.ymin,  textrct.xmax,  textrct.ymax);
1101
1102         /* collums */
1103         x= textrct.xmin+collumwidth;
1104         for(a=1; a<sfile->collums; a++, x+= collumwidth) {
1105                 cpack(0x303030);
1106                 sdrawline(x,  textrct.ymin,  x,  textrct.ymax); 
1107                 cpack(0xB0B0B0);
1108                 sdrawline(x+1,  textrct.ymin,  x+1,  textrct.ymax); 
1109         }
1110
1111         if(sfile->filelist==0) return;
1112         
1113         /* test: if mouse is not in area: clear HILITE */
1114         getmouseco_areawin(mval);
1115
1116         if(mval[0]<0 || mval[0]>curarea->winx) {
1117                 files= sfile->filelist+sfile->ofs;
1118                 for(a= sfile->ofs; a<sfile->totfile; a++, files++) files->flags &= ~HILITE;
1119         }
1120         
1121         files= sfile->filelist+sfile->ofs;
1122         for(a= sfile->ofs; a<sfile->totfile; a++, files++) {
1123         
1124                 if( calc_filesel_regel(sfile, a, &x, &y)==0 ) break;
1125                 
1126                 printregel(sfile, files, x, y);
1127         }
1128
1129         /* clear drawing errors, with text at the right hand side: */
1130         BIF_ThemeColor(TH_HEADER);
1131         glRecti(textrct.xmax,  textrct.ymin,  textrct.xmax+10,  textrct.ymax);
1132         uiEmboss(textrct.xmin, textrct.ymin, textrct.xmax, textrct.ymax, 1);
1133 }
1134
1135 void drawfilespace(ScrArea *sa, void *spacedata)
1136 {
1137         SpaceFile *sfile;
1138         uiBlock *block;
1139         float col[3];
1140         int act, loadbutton;
1141         short mval[2];
1142         char name[20];
1143         char *menu;
1144
1145         myortho2(-0.375, sa->winx-0.375, -0.375, sa->winy-0.375);
1146
1147         BIF_GetThemeColor3fv(TH_HEADER, col);   // basic undrawn color is border
1148         glClearColor(col[0], col[1], col[2], 0.0); 
1149         glClear(GL_COLOR_BUFFER_BIT);
1150
1151         sfile= curarea->spacedata.first;        
1152         if(sfile->filelist==0) {
1153                 read_dir(sfile);
1154                 
1155                 calc_file_rcts(sfile);
1156                 
1157                 /* calculate act */ 
1158                 getmouseco_areawin(mval);
1159                 act= find_active_file(sfile, mval[0], mval[1]);
1160                 if(act>=0 && act<sfile->totfile)
1161                         sfile->filelist[act].flags |= HILITE;
1162         }
1163         else calc_file_rcts(sfile);
1164
1165         /* HEADER */
1166         sprintf(name, "win %d", curarea->win);
1167         block= uiNewBlock(&curarea->uiblocks, name, UI_EMBOSS, UI_HELV, curarea->win);
1168         
1169         uiSetButLock( sfile->type==FILE_MAIN && sfile->returnfunc, NULL);
1170
1171         /* space available for load/save buttons? */
1172         loadbutton= MAX2(80, 20+BMF_GetStringWidth(G.font, sfile->title));
1173         if(textrct.xmax-textrct.xmin > loadbutton+20) {
1174                 if(sfile->title[0]==0) loadbutton= 0;
1175         }
1176         else loadbutton= 0;
1177
1178         uiDefBut(block, TEX,        1,"",       textrct.xmin, filebuty1, textrct.xmax-textrct.xmin-loadbutton, 21, sfile->file, 0.0, (float)FILE_MAXFILE-1, 0, 0, "");
1179         uiDefBut(block, TEX,        2,"",       textrct.xmin, filebuty2, textrct.xmax-textrct.xmin-loadbutton, 21, sfile->dir, 0.0, (float)FILE_MAXFILE-1, 0, 0, "");
1180         if(loadbutton) {
1181                 uiSetCurFont(block, UI_HELV);
1182                 uiDefBut(block, BUT,        5, sfile->title,    textrct.xmax-loadbutton, filebuty2, loadbutton, 21, sfile->dir, 0.0, (float)FILE_MAXFILE-1, 0, 0, "");
1183                 uiDefBut(block, BUT,        6, "Cancel",        textrct.xmax-loadbutton, filebuty1, loadbutton, 21, sfile->file, 0.0, (float)FILE_MAXFILE-1, 0, 0, "");
1184         }
1185
1186         menu= fsmenu_build_menu();
1187         if(menu[0])     // happens when no .Bfs is there, and first time browse
1188                 uiDefButS(block, MENU,  3, menu, scrollrct.xmin, filebuty1, scrollrct.xmax-scrollrct.xmin, 21, &sfile->menu, 0, 0, 0, 0, "");
1189         MEM_freeN(menu);
1190
1191         uiDefBut(block, BUT,            4, "P", scrollrct.xmin, filebuty2, scrollrct.xmax-scrollrct.xmin, 21, 0, 0, 0, 0, 0, "Move to the parent directory (PKEY)");
1192
1193         uiDrawBlock(block);
1194
1195         draw_filescroll(sfile);
1196         draw_filetext(sfile);
1197         
1198         /* others diskfree etc ? */
1199         scrarea_queue_headredraw(curarea);      
1200         
1201         myortho2(-0.375, (float)(sa->winx)-0.375, -0.375, (float)(sa->winy)-0.375);
1202         draw_area_emboss(sa);
1203         
1204         curarea->win_swap= WIN_BACK_OK;
1205 }
1206
1207 static void do_filescroll(SpaceFile *sfile)
1208 {
1209         short mval[2], oldy, yo;
1210         
1211         calc_file_rcts(sfile);
1212         
1213         filescrollselect= 1;
1214         /* for beauty */
1215
1216         glDrawBuffer(GL_FRONT);
1217         draw_filescroll(sfile);
1218         glDrawBuffer(GL_BACK);
1219         
1220         getmouseco_areawin(mval);
1221         oldy= yo= mval[1];
1222         
1223         while(get_mbut()&L_MOUSE) {
1224                 getmouseco_areawin(mval);
1225                 
1226                 if(yo!=mval[1]) {
1227                         int dy= floor(0.5+((float)(oldy-mval[1]))*pixels_to_ofs);
1228                         
1229                         if(dy) {
1230                                 sfile->ofs+= dy;
1231                                 if(sfile->ofs<0) {
1232                                         sfile->ofs= 0;
1233                                         oldy= mval[1];
1234                                 }
1235                                 else oldy= floor(0.5+ (float)oldy - (float)dy/pixels_to_ofs);
1236         
1237                                 scrarea_do_windraw(curarea);
1238                                 screen_swapbuffers();
1239         
1240                         }
1241                         
1242                         yo= mval[1];
1243                 }
1244                 else BIF_wait_for_statechange();
1245         }
1246         filescrollselect= 0;
1247
1248         /* for beauty */
1249         glDrawBuffer(GL_FRONT);
1250         draw_filescroll(sfile);
1251         glDrawBuffer(GL_BACK);
1252         
1253 }
1254
1255 static void do_filescrollwheel(SpaceFile *sfile, int move)
1256 {
1257         // by phase
1258         int lines, rt;
1259
1260         calc_file_rcts(sfile);
1261
1262         lines = (int)(textrct.ymax-textrct.ymin)/FILESEL_DY;
1263         rt = lines * sfile->collums;
1264
1265         if(sfile->totfile > rt) {
1266                 sfile->ofs+= move;
1267                 if( sfile->ofs + rt > sfile->totfile + 1)
1268                         sfile->ofs = sfile->totfile - rt + 1;
1269         }
1270
1271         if(sfile->ofs<0) {
1272                 sfile->ofs= 0;
1273         }
1274 }
1275
1276 void activate_fileselect(int type, char *title, char *file, void (*func)(char *))
1277 {
1278         SpaceFile *sfile;
1279         char group[24], name[FILE_MAXDIR], temp[FILE_MAXDIR];
1280         
1281         if(curarea==0) return;
1282         if(curarea->win==0) return;
1283         
1284         newspace(curarea, SPACE_FILE);
1285         scrarea_queue_winredraw(curarea);
1286         
1287         /* sometime double, when area already is SPACE_FILE with a different file name */
1288         addqueue(curarea->headwin, CHANGED, 1);
1289         
1290
1291         name[2]= 0;
1292         strcpy(name, file);
1293         
1294         sfile= curarea->spacedata.first;
1295         /* sfile wants a (*)(short), but get (*)(char*) */
1296         sfile->returnfunc= func;
1297         sfile->type= type;
1298         sfile->ofs= 0;
1299         /* sfile->act is used for databrowse: double names of library objects */
1300         sfile->act= -1;
1301         
1302         if(BLI_convertstringcode(name, G.sce, G.scene->r.cfra)) sfile->flag |= FILE_STRINGCODE;
1303         else sfile->flag &= ~FILE_STRINGCODE;
1304
1305         if(type==FILE_MAIN) {
1306                 char *groupname;
1307                 
1308                 strcpy(sfile->file, name+2);
1309
1310                 groupname = BLO_idcode_to_name( GS(name) );
1311                 if (groupname) {
1312                         strcpy(sfile->dir, groupname);
1313                         strcat(sfile->dir, "/");
1314                 }
1315
1316                 /* free all */
1317                 if(sfile->libfiledata) BLO_blendhandle_close(sfile->libfiledata);
1318                 sfile->libfiledata= 0;
1319                 
1320                 freefilelist(sfile);
1321         }
1322         else if(type==FILE_LOADLIB) {
1323                 strcpy(sfile->dir, name);
1324                 if( is_a_library(sfile, temp, group) ) {
1325                         /* to force a reload of the library-filelist */
1326                         if(sfile->libfiledata==0) {
1327                                 freefilelist(sfile);
1328                         }
1329                 }
1330                 else {
1331                         split_sfile(sfile, name);
1332                         if(sfile->libfiledata) BLO_blendhandle_close(sfile->libfiledata);
1333                         sfile->libfiledata= 0;
1334                 }
1335         }
1336         else {  /* FILE_BLENDER */
1337                 split_sfile(sfile, name);       /* test filelist too */
1338                 
1339                 /* free: filelist and libfiledata became incorrect */
1340                 if(sfile->libfiledata) BLO_blendhandle_close(sfile->libfiledata);
1341                 sfile->libfiledata= 0;
1342         }
1343         BLI_strncpy(sfile->title, title, sizeof(sfile->title));
1344         filetoname= 1;
1345 }
1346
1347 void activate_imageselect(int type, char *title, char *file, void (*func)(char *))
1348 {
1349         SpaceImaSel *simasel;
1350         char dir[FILE_MAXDIR], name[FILE_MAXFILE];
1351         
1352         if(curarea==0) return;
1353         if(curarea->win==0) return;
1354         
1355         newspace(curarea, SPACE_IMASEL);
1356         
1357         /* sometimes double, when area is already SPACE_FILE with a different file name */
1358         addqueue(curarea->headwin, CHANGED, 1);
1359         addqueue(curarea->win, CHANGED, 1);
1360
1361         name[2]= 0;
1362         strcpy(name, file);
1363
1364         simasel= curarea->spacedata.first;
1365         simasel->returnfunc= func;
1366
1367         if(BLI_convertstringcode(name, G.sce, G.scene->r.cfra)) simasel->mode |= IMS_STRINGCODE;
1368         else simasel->mode &= ~IMS_STRINGCODE;
1369         
1370         BLI_split_dirfile(name, dir, simasel->file);
1371         if(strcmp(dir, simasel->dir)!=0) simasel->fase= 0;
1372         strcpy(simasel->dir, dir);
1373         
1374         BLI_strncpy(simasel->title, title, sizeof(simasel->title));
1375
1376         
1377         
1378         /* filetoname= 1; */
1379 }
1380
1381
1382 void activate_databrowse(ID *id, int idcode, int fromcode, int retval, short *menup, void (*func)(unsigned short))
1383 {
1384         ListBase *lb;
1385         SpaceFile *sfile;
1386         char str[32];
1387         
1388         if(id==0) {
1389                 lb= wich_libbase(G.main, idcode);
1390                 id= lb->last;
1391         }
1392         
1393         if(id) strcpy(str, id->name);
1394         else return;
1395         
1396         activate_fileselect(FILE_MAIN, "SELECT DATABLOCK", str, (void (*) (char*))func);
1397         
1398         sfile= curarea->spacedata.first;
1399         sfile->retval= retval;
1400         sfile->ipotype= fromcode;
1401         sfile->menup= menup;
1402 }
1403
1404 void filesel_prevspace()
1405 {
1406         SpaceFile *sfile;
1407         
1408         sfile= curarea->spacedata.first;
1409         if(sfile->next) {
1410         
1411                 BLI_remlink(&curarea->spacedata, sfile);
1412                 BLI_addtail(&curarea->spacedata, sfile);
1413
1414                 sfile= curarea->spacedata.first;
1415
1416                 if (sfile->spacetype == SPACE_SCRIPT) {
1417                         SpaceScript *sc = (SpaceScript *)sfile;
1418                         if (sc->script) sc->script->flags &=~SCRIPT_FILESEL;
1419                 }
1420
1421                 newspace(curarea, sfile->spacetype);
1422         }
1423         else newspace(curarea, SPACE_INFO);
1424 }
1425
1426 static int countselect(SpaceFile *sfile)
1427 {
1428         int a, count=0;
1429
1430         for(a=0; a<sfile->totfile; a++) {
1431                 if(sfile->filelist[a].flags & ACTIVE) {
1432                         count++;
1433                 }
1434         }
1435         return count;
1436 }
1437
1438 static int getotherdir(void)
1439 {
1440         ScrArea *sa;
1441         SpaceFile *sfile=0;
1442         
1443         sa= G.curscreen->areabase.first;
1444         while(sa) {
1445                 if(sa!=curarea) {
1446                         if(sa->spacetype==SPACE_FILE) {
1447                                 
1448                                 /* already found one */
1449                                 if(sfile) return 0;
1450                 
1451                                 sfile= sa->spacedata.first;
1452
1453                                 if(sfile->type & FILE_UNIX) {
1454                                         otherarea= sa;
1455                                         BLI_make_file_string(G.sce, otherdir, sfile->dir, "");
1456                                 }
1457                                 else sfile= 0;
1458                         }
1459                 }
1460                 sa= sa->next;
1461         }
1462         if(sfile) return 1;
1463         return 0;
1464 }
1465
1466 static void reread_other_fs(void)
1467 {
1468         SpaceFile *sfile;
1469         
1470         /* watch it: only call when getotherdir returned OK */
1471         
1472         sfile= otherarea->spacedata.first;
1473         freefilelist(sfile);
1474         scrarea_queue_winredraw(otherarea);
1475 }
1476
1477
1478 void free_filesel_spec(char *dir)
1479 {
1480         /* all filesels with 'dir' are freed */
1481         bScreen *sc;
1482                 
1483         sc= G.main->screen.first;
1484         while(sc) {
1485                 ScrArea *sa= sc->areabase.first;
1486                 while(sa) {
1487                         SpaceLink  *sl= sa->spacedata.first;
1488                         while(sl) {
1489                                 if(sl->spacetype==SPACE_FILE) {
1490                                         SpaceFile *sfile= (SpaceFile*) sl;
1491                                         if (BLI_streq(sfile->dir, dir)) {
1492                                                 freefilelist(sfile);
1493                                         }
1494                                 }
1495                                 sl= sl->next;
1496                         }
1497                         sa= sa->next;
1498                 }
1499                 sc= sc->id.next;
1500         }
1501 }
1502
1503
1504 static void filesel_execute(SpaceFile *sfile)
1505 {
1506         struct direntry *files;
1507         char name[FILE_MAXDIR];
1508         int a;
1509         
1510         filesel_prevspace();
1511
1512         if(sfile->type==FILE_LOADLIB) {
1513                 do_library_append(sfile);
1514                 
1515                 allqueue(REDRAWALL, 1);
1516         }
1517         else if(sfile->returnfunc) {
1518                 fsmenu_insert_entry(sfile->dir, 1);
1519         
1520                 if(sfile->type==FILE_MAIN) {
1521                         if (sfile->menup) {
1522                                 if(sfile->act>=0) {
1523                                         if(sfile->filelist) {
1524                                                 files= sfile->filelist+sfile->act;
1525                                                 *sfile->menup= files->nr;
1526                                         }       
1527                                         else *sfile->menup= sfile->act+1;
1528                                 }
1529                                 else {
1530                                         *sfile->menup= -1;
1531                                         for(a=0; a<sfile->totfile; a++) {
1532                                                 if( strcmp(sfile->filelist[a].relname, sfile->file)==0) {
1533                                                         *sfile->menup= a+1;
1534                                                         break;
1535                                                 }
1536                                         }
1537                                 }
1538                         }
1539                         sfile->returnfunc((char*) (long)sfile->retval);
1540                 }
1541                 else {
1542                         if(strncmp(sfile->title, "SAVE", 4)==0) free_filesel_spec(sfile->dir);
1543                         
1544                         strcpy(name, sfile->dir);
1545                         strcat(name, sfile->file);
1546                         
1547                         if(sfile->flag & FILE_STRINGCODE) BLI_makestringcode(G.sce, name);
1548
1549                         sfile->returnfunc(name);
1550                 }
1551         }
1552 }
1553
1554 static void do_filesel_buttons(short event, SpaceFile *sfile)
1555 {
1556         char butname[FILE_MAXDIR];
1557         
1558         if (event == 1) {
1559                 if (strchr(sfile->file, '*') || strchr(sfile->file, '?') || strchr(sfile->file, '[')) {
1560                         int i, match = FALSE;
1561                         
1562                         for (i = 2; i < sfile->totfile; i++) {
1563                                 if (fnmatch(sfile->file, sfile->filelist[i].relname, 0) == 0) {
1564                                         sfile->filelist[i].flags |= ACTIVE;
1565                                         match = TRUE;
1566                                 }
1567                         }
1568                         if (match) strcpy(sfile->file, "");
1569                         if(sfile->type==FILE_MAIN) filesel_select_objects(sfile);
1570                         scrarea_queue_winredraw(curarea);
1571                 }
1572         }
1573         else if(event== 2) {
1574                 /* reuse the butname variable */
1575                 checkdir(sfile->dir);
1576
1577                 BLI_make_file_string(G.sce, butname, sfile->dir, "");
1578                 /* strip the trailing slash if its a real dir */
1579                 if (strlen(butname)!=1)
1580                         butname[strlen(butname)-1]=0;
1581                 
1582                 if(sfile->type & FILE_UNIX) {
1583                         if (!BLI_exists(butname)) {
1584                                 if (okee("Makedir")) {
1585                                         BLI_recurdir_fileops(butname);
1586                                         if (!BLI_exists(butname)) parent(sfile);
1587                                 } else parent(sfile);
1588                         }
1589                 }
1590                 freefilelist(sfile);
1591                 sfile->ofs= 0;
1592                 scrarea_queue_winredraw(curarea);
1593         }
1594         else if(event== 3) {
1595                 char *selected= fsmenu_get_entry(sfile->menu-1);
1596                 
1597                 /* which string */
1598                 if (selected) {
1599                         strcpy(sfile->dir, selected);
1600                         BLI_make_exist(sfile->dir);
1601                         checkdir(sfile->dir);
1602                         freefilelist(sfile);
1603                         sfile->ofs= 0;
1604                         scrarea_queue_winredraw(curarea);
1605                 }
1606
1607                 sfile->act= -1;
1608                 
1609         }
1610         else if(event== 4) parent(sfile);
1611         else if(event== 5) {
1612                 if(sfile->type) filesel_execute(sfile);
1613         }
1614         else if(event== 6) filesel_prevspace();
1615         
1616 }
1617
1618 /****/
1619
1620 typedef void (*ReplaceFP)(ID *oldblock, ID *newblock);
1621
1622 static void change_id_link(void *linkpv, void *newlinkv) {
1623         ID **linkp= (ID**) linkpv;
1624         ID *newlink= newlinkv;
1625
1626         if (*linkp) {
1627                 (*linkp)->us--;
1628         }
1629         (*linkp)= newlink;
1630         if (newlink) {
1631                 id_us_plus(newlink);
1632         }
1633 }
1634
1635 static void replace_image(ID *oldblock, ID *newblock) {
1636         Image *oldima= (Image*) oldblock;
1637         Image *newima= (Image*) newblock;
1638         bScreen *sc;
1639         Scene *sce;
1640         Tex *tex;
1641         Mesh *me;
1642
1643         for (tex= G.main->tex.first; tex; tex= tex->id.next) {
1644                 if (tex->env && tex->env->type == ENV_LOAD && tex->env->ima == oldima)
1645                         change_id_link(&tex->env->ima, newima);
1646                 if (tex->ima == oldima)
1647                         change_id_link(&tex->ima, newima);
1648         }
1649
1650         for (sce= G.main->scene.first; sce; sce= sce->id.next) {
1651                 if (sce->ima == oldima)
1652                         change_id_link(&sce->ima, newima);
1653         }
1654
1655         for (sc= G.main->screen.first; sc; sc= sc->id.next) {
1656                 ScrArea *sa;
1657
1658                 for (sa= sc->areabase.first; sa; sa= sa->next) {
1659                         SpaceLink *sl;
1660
1661                         for (sl= sa->spacedata.first; sl; sl= sl->next) {
1662                                 if (sl->spacetype == SPACE_VIEW3D) {
1663                                         View3D *v3d= (View3D*) sl;
1664                                         BGpic *bgp= v3d->bgpic;
1665
1666                                         if (bgp && bgp->ima == oldima) 
1667                                                 change_id_link(&bgp->ima, newima);
1668                                 } else if (sl->spacetype == SPACE_IMAGE) {
1669                                         SpaceImage *sima= (SpaceImage*) sl;
1670                                         
1671                                         if (sima->image == oldima)
1672                                                 change_id_link(&sima->image, newima);
1673                                 }
1674                         }
1675                 }
1676         }
1677
1678         for (me= G.main->mesh.first; me; me= me->id.next) {
1679                 TFace *tfaces= me->tface;
1680
1681                 if (tfaces) {
1682                         int i;
1683
1684                         for (i=0; i<me->totface; i++) {
1685                                 TFace *tf= &tfaces[i];
1686
1687                                 if (tf->tpage == oldima) {
1688                                                 /* not change_id_link, tpage's aren't owners :(
1689                                                  * see hack below.
1690                                                  */
1691                                         tf->tpage= newima;
1692                                 }
1693                         }
1694                 }
1695         }
1696
1697                 /* Nasty hack, necessary because tpages don't act
1698                  * as a user, so there lots of image user count
1699                  * munging occurs... this will ensure the image
1700                  * really dies.
1701                  */
1702         oldima->id.us= 0;
1703 }
1704
1705 static void replace_material(ID *oldblock, ID *newblock)
1706 {
1707         Material *old= (Material*) oldblock;
1708         Material *new= (Material*) newblock;
1709         Material ***matarar;
1710         ID *id;
1711         Object *ob;
1712         int a;
1713         
1714         ob= G.main->object.first;
1715         while(ob) {
1716                 if(ob->totcol && ob->id.lib==0) {
1717                         matarar= give_matarar(ob);
1718                         for(a=1; a<=ob->totcol; a++) {
1719                                 if(ob->mat[a-1] == old) {
1720                                         if(old) old->id.us--;
1721                                         id_us_plus((ID *)new);
1722                                         ob->mat[a-1]= new;
1723                                 }
1724                                 id= ob->data;
1725                                 if( (*matarar)[a-1] == old  && id->lib==0) {
1726                                         if(old) old->id.us--;
1727                                         id_us_plus((ID *)new);
1728                                         (*matarar)[a-1]= new;
1729                                 }
1730                         }
1731                 }
1732                 ob= ob->id.next;
1733         }
1734 }
1735
1736 static ReplaceFP get_id_replace_function(int idcode) {
1737         switch (idcode) {
1738         case ID_MA:
1739                 return &replace_material;
1740         case ID_IM:
1741                 return &replace_image;
1742         default:
1743                 return NULL;
1744         }
1745 }
1746
1747 static void databrowse_replace(SpaceFile *sfile, int idcode)
1748 {
1749         ReplaceFP replace_func= get_id_replace_function(idcode);
1750
1751         if (!replace_func) {
1752                 error("Replacing %s blocks is unsupported", BLO_idcode_to_name(idcode));
1753         } else if (sfile->act==-1) {
1754                 error("Select target with leftmouse");
1755         } else {
1756                 ID *target= (ID*) sfile->filelist[sfile->act].poin;
1757
1758                 if (target) {
1759                         char buf[128];
1760
1761                         sprintf(buf, "Replace with %s: %s", BLO_idcode_to_name(idcode), target->name+2);
1762
1763                         if (okee(buf)) {
1764                                 int i;
1765
1766                                 for (i = 0; i <sfile->totfile; i++)
1767                                         if ((sfile->filelist[i].flags&ACTIVE) && sfile->filelist[i].poin!=target)
1768                                                 replace_func(sfile->filelist[i].poin, target);
1769                         }
1770                 }
1771         }
1772
1773         freefilelist(sfile);
1774         scrarea_queue_winredraw(curarea);
1775 }
1776
1777 static void fs_fake_users(SpaceFile *sfile)
1778 {
1779         ID *id;
1780         int a;
1781         
1782         /* only for F4 DATABROWSE */
1783         if(sfile->returnfunc) return;
1784         
1785         for(a=0; a<sfile->totfile; a++) {
1786                 if(sfile->filelist[a].flags & ACTIVE) {
1787                         id= (ID *)sfile->filelist[a].poin;
1788                         if(id) {
1789                                 if( id->flag & LIB_FAKEUSER) {
1790                                         id->flag -= LIB_FAKEUSER;
1791                                         id->us--;
1792                                 }
1793                                 else {
1794                                         id->flag |= LIB_FAKEUSER;
1795                                         id->us++;
1796                                 }
1797                         }
1798                 }
1799         }
1800         freefilelist(sfile);
1801         scrarea_queue_winredraw(curarea);
1802 }
1803
1804
1805 static int get_hilited_entry(SpaceFile *sfile)
1806 {
1807         int a;
1808
1809         for(a=0; a<sfile->totfile; a++) {
1810                 if(sfile->filelist[a].flags & HILITE) {
1811                         return a;
1812                 }
1813         }
1814         return -1;
1815 }
1816
1817
1818 void winqreadfilespace(ScrArea *sa, void *spacedata, BWinEvent *evt)
1819 {
1820         unsigned short event= evt->event;
1821         short val= evt->val;
1822         static int acto=0;
1823         SpaceFile *sfile;
1824         int act, do_draw= 0, i, test, ret = 0;
1825         short qual, mval[2];
1826         char str[FILE_MAXDIR+FILE_MAXFILE+12];
1827         
1828         sfile= curarea->spacedata.first;
1829         if(sfile==0) return;
1830         if(sfile->filelist==0) {
1831                 /* but do buttons */
1832                 if(val && event==LEFTMOUSE) {
1833                         /* FrontbufferButs(TRUE); */
1834                         /* event= DoButtons(); */
1835                         /* FrontbufferButs(FALSE); */
1836                                         /*  NIET de headerbuttons! */
1837                         /* if(event) do_filesel_buttons(event, sfile); */
1838                 }
1839                 return;
1840         }
1841         
1842         if(curarea->win==0) return;
1843         calc_file_rcts(sfile);
1844         getmouseco_areawin(mval);
1845
1846         /* prevent looping */
1847         if(selecting && !(get_mbut() & R_MOUSE)) selecting= 0;
1848
1849         if(val) {
1850
1851                 if( event!=RETKEY && event!=PADENTER)
1852                         if( uiDoBlocks(&curarea->uiblocks, event)!=UI_NOTHING ) event= 0;
1853
1854                 switch(event) {
1855                 
1856                 case UI_BUT_EVENT:
1857                         do_filesel_buttons(val, sfile);
1858                         break;          
1859                 
1860                 case WHEELDOWNMOUSE:
1861                         do_filescrollwheel(sfile, U.wheellinescroll);
1862                         act= find_active_file(sfile, mval[0], mval[1]);
1863                         set_active_file(sfile, act);
1864                         do_draw= 1;
1865                         break;
1866                 case WHEELUPMOUSE:
1867                         do_filescrollwheel(sfile, -U.wheellinescroll);
1868                         act= find_active_file(sfile, mval[0], mval[1]);
1869                         set_active_file(sfile, act);
1870                         do_draw= 1;
1871                         break;
1872
1873                 case LEFTMOUSE:
1874                 case MIDDLEMOUSE:
1875                         if(mval[0]>scrollrct.xmin && mval[0]<scrollrct.xmax && mval[1]>scrollrct.ymin && mval[1]<scrollrct.ymax) {
1876                                 do_filescroll(sfile);
1877                         }
1878                         else if(mval[0]>textrct.xmin && mval[0]<textrct.xmax && mval[1]>textrct.ymin && mval[1]<textrct.ymax) {
1879                                 
1880                                 /* sfile->act is used in databrowse: double names of library objects */
1881                                 
1882                                 sfile->act= act= find_active_file(sfile, mval[0], mval[1]);
1883                                 
1884                                 if(act>=0 && act<sfile->totfile) {
1885                                         if(S_ISDIR(sfile->filelist[act].type)) {
1886                                                 strcat(sfile->dir, sfile->filelist[act].relname);
1887                                                 strcat(sfile->dir,"/");
1888                                                 checkdir(sfile->dir);
1889                                                 freefilelist(sfile);
1890                                                 sfile->ofs= 0;
1891                                                 do_draw= 1;
1892                                         }
1893                                         else {
1894                                                 if( strcmp(sfile->file, sfile->filelist[act].relname)) {
1895                                                         do_draw= 1;
1896                                                         strcpy(sfile->file, sfile->filelist[act].relname);
1897                                                 }
1898                                                 if(event==MIDDLEMOUSE && sfile->type) filesel_execute(sfile);
1899                                         }
1900                                 }
1901                         }
1902                         else {
1903                                 /* FrontbufferButs(TRUE); */
1904                                 /* event= DoButtons(); */
1905                                 /* FrontbufferButs(FALSE); */
1906                                         /*  NOT the headerbuttons! */
1907                                 /* if(event) do_filesel_buttons(event, sfile);   */
1908                         }
1909                         break;
1910                 case RIGHTMOUSE:
1911                         act= find_active_file(sfile, mval[0], mval[1]);
1912                         acto= act;
1913                         if(act>=0 && act<sfile->totfile) {
1914
1915                                 if (sfile->filelist[act].flags & ACTIVE) {
1916                                         sfile->filelist[act].flags &= ~ACTIVE;
1917                                         selecting = INACTIVATE;
1918                                 }
1919                                 else {
1920                                         test= sfile->filelist[act].relname[0];
1921                                         if (act>=2 || test!='.') sfile->filelist[act].flags |= ACTIVE;
1922                                         
1923                                         selecting = ACTIVATE;
1924                                 }
1925                                 do_draw= 1;
1926                         }
1927                         break;
1928                 case MOUSEY:
1929                         act= find_active_file(sfile, mval[0], mval[1]);
1930                         if (act!=acto) {
1931                                 set_active_file(sfile, act);
1932                         }
1933                         if(selecting && act!=acto) {
1934                                         
1935                                 while(1) {
1936                                         if (acto >= 2 && acto < sfile->totfile) {
1937                                                 if (selecting == ACTIVATE) sfile->filelist[acto].flags |= ACTIVE;
1938                                                 else if (selecting == INACTIVATE) sfile->filelist[acto].flags &= ~ACTIVE;
1939                                         }
1940                                         if (acto < act) acto++;
1941                                         else if (acto > act) acto--;
1942                                         else break;
1943                                         
1944                                 }
1945
1946                         }
1947                         acto= act;
1948                         break;
1949                 
1950                 case PAGEUPKEY:
1951                         sfile->ofs-= page_ofs;
1952                         do_draw= 1;
1953                         break;
1954                 case PAGEDOWNKEY:
1955                         sfile->ofs+= page_ofs;
1956                         do_draw= 1;
1957                         break;
1958                 case HOMEKEY:
1959                         sfile->ofs= 0;
1960                         do_draw= 1;
1961                         break;
1962                 case ENDKEY:
1963                         sfile->ofs= sfile->totfile;
1964                         do_draw= 1;
1965                         break;
1966                 
1967                 case AKEY:
1968                         swapselect_file(sfile);
1969                         if(sfile->type==FILE_MAIN) filesel_select_objects(sfile);
1970                         do_draw= 1;
1971                         break;
1972                         
1973                 case BKEY:
1974                 case CKEY:
1975                 case LKEY:
1976                         if(event==LKEY && sfile->type==FILE_MAIN && (G.qual & LR_CTRLKEY)) {
1977                                 databrowse_replace(sfile, groupname_to_code(sfile->dir));
1978                                 break;
1979                         }
1980                         /* pass */
1981                 case MKEY:
1982                         if(sfile->type==FILE_MAIN) break;
1983
1984                         if(!countselect(sfile)) {
1985                                 error("No files selected");
1986                                 break;
1987                         }
1988                         
1989                         if(!getotherdir()) {
1990                                 error("No second fileselect");
1991                                 break;
1992                         }
1993                         
1994                         if (!strcmp(sfile->dir, otherdir)) {
1995                                 error("Same directories");
1996                                 break;
1997                         }
1998
1999                         if(event==BKEY) sprintf(str, "Backup to %s", otherdir);
2000                         else if(event==CKEY) sprintf(str, "Copy to %s", otherdir);
2001                         else if(event==LKEY) sprintf(str, "Linked copy to %s", otherdir);
2002                         else if(event==MKEY) sprintf(str, "Move to %s", otherdir);
2003                                         
2004                         if (!okee(str)) break;
2005
2006                         for (i = 0; i<sfile->totfile; i++){
2007                                 if (sfile->filelist[i].flags & ACTIVE) {                        
2008                                         BLI_make_file_string(G.sce, str, sfile->dir, sfile->filelist[i].relname);
2009
2010                                         if(event==BKEY) ret= BLI_backup(sfile->filelist[i].relname, sfile->dir, otherdir);
2011                                         else if(event==CKEY) ret= BLI_copy_fileops(str, otherdir);
2012                                         else if(event==LKEY) ret= BLI_link(str, otherdir);
2013                                         else if(event==MKEY) ret= BLI_move(str, otherdir);
2014
2015                                         if (ret) {error("Command failed, see console"); break;}
2016                                         else sfile->filelist[i].flags &= ~ACTIVE;
2017                                 }
2018                         }
2019                         do_draw= 1;
2020                         if(event==BKEY || event==MKEY) 
2021                                 freefilelist(sfile);
2022                                 
2023                         reread_other_fs();
2024                         
2025                         break;
2026
2027                 case XKEY:
2028                         test = get_hilited_entry(sfile);
2029
2030                         if (test != -1 && !(S_ISDIR(sfile->filelist[test].type))){
2031                                 BLI_make_file_string(G.sce, str, sfile->dir, sfile->filelist[test].relname);
2032
2033                                 if( okee("Remove %s", str) ) {
2034                                         ret = BLI_delete(str, 0, 0);
2035                                         if (ret) {
2036                                                 error("Command failed, see console");
2037                                         } else {
2038                                                 freefilelist(sfile);
2039                                                 do_draw= 1;
2040                                         }
2041                                 }
2042                         }
2043                         break;
2044
2045                 case RKEY:
2046                         if(sfile->type==FILE_MAIN) {
2047                                 databrowse_replace(sfile, groupname_to_code(sfile->dir));
2048                                 break;
2049                         }
2050                         /* pass to TKEY! */
2051                         
2052                 case TKEY:
2053                         if(sfile->type==FILE_MAIN) break;
2054                         
2055                         if(!countselect(sfile)) {
2056                                 error("No files selected");
2057                                 break;
2058                         }
2059
2060                         if(event==TKEY) sprintf(str, "Touch");
2061                         else if(event==RKEY) sprintf(str, "Remove from %s", sfile->dir);
2062                         
2063                         qual= G.qual;   /* because after okee() you released the SHIFT */
2064                         if (!okee(str)) break;
2065                         
2066                         for (i = 0; i <sfile->totfile; i++) {
2067                                 if (sfile->filelist[i].flags & ACTIVE) {
2068                                         BLI_make_file_string(G.sce, str, sfile->dir, sfile->filelist[i].relname);
2069
2070                                         if(event==TKEY) ret= BLI_touch(str);
2071                                         else if(event==RKEY) {
2072                                                 if(qual & LR_SHIFTKEY) ret= BLI_delete(str, 0, 1);
2073                                                 else if(S_ISDIR(sfile->filelist[i].type)) ret= BLI_delete(str, 1, 0);
2074                                                 else ret= BLI_delete(str, 0, 0);
2075                                         }
2076
2077                                         if (ret) {error("Command failed, see console"); break;}
2078                                         else sfile->filelist[i].flags &= ~ACTIVE;
2079                                 }
2080                         }
2081                         do_draw= 1;
2082                         freefilelist(sfile);
2083
2084                         break;
2085                                 
2086                 case PKEY:
2087                         if(G.qual & LR_SHIFTKEY) {
2088                                 extern char bprogname[];        /* usiblender.c */
2089                         
2090                                 sprintf(str, "%s -a \"%s%s\"", bprogname, sfile->dir, sfile->file);
2091                                 system(str);
2092                         }
2093                         else 
2094                                 parent(sfile);
2095                                 
2096                         break;
2097
2098                 case IKEY:
2099                         if(sfile->type==FILE_MAIN) break;
2100                         
2101                         sprintf(str, "$IMAGEEDITOR %s%s", sfile->dir, sfile->file);
2102                         system(str);
2103                         break;
2104                 
2105                 case EKEY:
2106                         if(sfile->type==FILE_MAIN) break;
2107                         
2108                         sprintf(str, "$WINEDITOR %s%s", sfile->dir, sfile->file);
2109                         system(str);
2110                         break;
2111                 
2112                 case FKEY:
2113                         if(sfile->type==FILE_MAIN) {
2114                                 fs_fake_users(sfile);
2115                         }
2116                         break;
2117                                 
2118                 case PADPLUSKEY:
2119                 case EQUALKEY:
2120                         if (G.qual & LR_CTRLKEY) BLI_newname(sfile->file, +100);
2121                         else if (G.qual & LR_SHIFTKEY) BLI_newname(sfile->file, +10);
2122                         else BLI_newname(sfile->file, +1);
2123                         
2124                         do_draw= 1;
2125                         break;
2126                         
2127                 case PADMINUS:
2128                 case MINUSKEY:
2129                         if (G.qual & LR_CTRLKEY) BLI_newname(sfile->file, -100);
2130                         else if (G.qual & LR_SHIFTKEY) BLI_newname(sfile->file, -10);
2131                         else BLI_newname(sfile->file, -1);
2132                         
2133                         do_draw= 1;
2134                         break;
2135                         
2136                 case BACKSLASHKEY:
2137                 case SLASHKEY:
2138                         if(sfile->type==FILE_MAIN) break;
2139
2140 #ifdef WIN32
2141                         strcpy(sfile->dir, "\\");
2142 #else
2143                         strcpy(sfile->dir, "/");
2144 #endif
2145                         freefilelist(sfile);
2146                         sfile->ofs= 0;
2147                         do_draw= 1;
2148                         break;
2149                 case PERIODKEY:
2150                         freefilelist(sfile);
2151                         do_draw= 1;
2152                         break;
2153                 case ESCKEY:
2154                         filesel_prevspace();
2155                         break;
2156                 case PADENTER:
2157                 case RETKEY:
2158                         if(sfile->type) filesel_execute(sfile);
2159                         break;
2160                 }
2161         }
2162         else if(event==RIGHTMOUSE) {
2163                 selecting = NOTACTIVE;
2164                 if(sfile->type==FILE_MAIN) filesel_select_objects(sfile);
2165         }
2166         else if(event==LEFTMOUSE) {
2167                 if(sfile->type==FILE_MAIN) active_file_object(sfile);
2168         }
2169
2170                 /* XXX, stupid patch, curarea can become undone
2171                  * because of file loading... fixme zr
2172                  */
2173         if(do_draw && curarea) scrarea_queue_winredraw(curarea);
2174 }
2175
2176
2177
2178
2179 /* ************* LIBRARY FILESEL ******************* */
2180
2181 static int groupname_to_code(char *group)
2182 {
2183         char buf[32];
2184         char *lslash;
2185         
2186         strcpy(buf, group);
2187         lslash= BLI_last_slash(buf);
2188         if (lslash)
2189                 lslash[0]= '\0';
2190
2191         return BLO_idcode_from_name(buf);
2192 }
2193
2194 static int is_a_library(SpaceFile *sfile, char *dir, char *group)
2195 {
2196         /* return ok when a blenderfile, in dir is the filename,
2197          * in group the type of libdata
2198          */
2199         int len;
2200         char *fd;
2201         
2202         strcpy(dir, sfile->dir);
2203         len= strlen(dir);
2204         if(len<7) return 0;
2205         if( dir[len-1] != '/' && dir[len-1] != '\\') return 0;
2206         
2207         group[0]= 0;
2208         dir[len-1]= 0;
2209
2210         /* Find the last slash */
2211         fd= (strrchr(dir, '/')>strrchr(dir, '\\'))?strrchr(dir, '/'):strrchr(dir, '\\');
2212
2213         if(fd==0) return 0;
2214         *fd= 0;
2215         if(BLO_has_bfile_extension(fd+1)) {
2216                 *fd= '/';
2217         }
2218         else {
2219                 strcpy(group, fd+1);
2220                         
2221                 /* Find the last slash */
2222                 fd= (strrchr(dir, '/')>strrchr(dir, '\\'))?strrchr(dir, '/'):strrchr(dir, '\\');
2223                 if (!fd || !BLO_has_bfile_extension(fd+1)) return 0;
2224         }
2225         return 1;
2226 }
2227
2228 static void do_library_append(SpaceFile *sfile)
2229 {
2230         char dir[FILE_MAXDIR], group[32];
2231         
2232         if ( is_a_library(sfile, dir, group)==0 ) {
2233                 error("Not a library");
2234         } else if (!sfile->libfiledata) {
2235                 error("Library not loaded");
2236         } else if (group[0]==0) {
2237                 error("Nothing indicated");
2238         } else if (BLI_streq(G.main->name, dir)) {
2239                 error("Cannot use current file as library");
2240         } else {
2241                 Object *ob;
2242                 int idcode = groupname_to_code(group);
2243                 
2244                 BLO_library_append(sfile, dir, idcode);
2245
2246                 /* DISPLISTS */
2247                 ob= G.main->object.first;
2248                 set_displist_onlyzero(1);
2249                 while(ob) {
2250                         if(ob->id.lib) {
2251                                 if(ob->type==OB_FONT) {
2252                                         Curve *cu= ob->data;
2253                                         if(cu->nurb.first==0) text_to_curve(ob, 0);
2254                                 }
2255                                 makeDispList(ob);
2256                         }
2257                         else if(ob->type==OB_MESH && ob->parent && ob->parent->type==OB_LATTICE ) {
2258                                 makeDispList(ob);
2259                         }
2260                         
2261                         ob= ob->id.next;
2262                 }
2263                 set_displist_onlyzero(0);
2264         
2265                 /* in sfile->dir is the whole lib name */
2266                 strcpy(G.lib, sfile->dir);
2267                 
2268                 if((sfile->flag & FILE_LINK)==0) all_local();
2269         }
2270 }
2271
2272 static void library_to_filelist(SpaceFile *sfile)
2273 {
2274         char dir[FILE_MAXDIR], group[24];
2275         int ok, i, nnames, idcode;
2276         LinkNode *l, *names;
2277         
2278         /* name test */
2279         ok= is_a_library(sfile, dir, group);
2280         if (!ok) {
2281                 /* free */
2282                 if(sfile->libfiledata) BLO_blendhandle_close(sfile->libfiledata);
2283                 sfile->libfiledata= 0;
2284                 return;
2285         }
2286         
2287         /* there we go */
2288         /* for the time being only read filedata when libfiledata==0 */
2289         if (sfile->libfiledata==0) {
2290                 sfile->libfiledata= BLO_blendhandle_from_file(dir);
2291                 if(sfile->libfiledata==0) return;
2292         }
2293         
2294         idcode= groupname_to_code(group);
2295         if (idcode) {
2296                 names= BLO_blendhandle_get_datablock_names(sfile->libfiledata, idcode);
2297         } else {
2298                 names= BLO_blendhandle_get_linkable_groups(sfile->libfiledata);
2299         }
2300         
2301         nnames= BLI_linklist_length(names);
2302
2303         sfile->totfile= nnames + 2;
2304         sfile->filelist= malloc(sfile->totfile * sizeof(*sfile->filelist));
2305         memset(sfile->filelist, 0, sfile->totfile * sizeof(*sfile->filelist));
2306
2307         sfile->filelist[0].relname= strdup(".");
2308         sfile->filelist[0].type |= S_IFDIR;
2309         sfile->filelist[1].relname= strdup("..");
2310         sfile->filelist[1].type |= S_IFDIR;
2311                 
2312         for (i=0, l= names; i<nnames; i++, l= l->next) {
2313                 char *blockname= l->link;
2314
2315                 sfile->filelist[i + 2].relname= blockname;
2316                 if (!idcode)
2317                         sfile->filelist[i + 2].type |= S_IFDIR;
2318         }
2319                 
2320         BLI_linklist_free(names, NULL);
2321         
2322         qsort(sfile->filelist, sfile->totfile, sizeof(struct direntry), compare_name);
2323         
2324         sfile->maxnamelen= 0;
2325         for(i=0; i<sfile->totfile; i++) {
2326                 int len = BMF_GetStringWidth(G.font, sfile->filelist[i].relname);
2327                 if (len > sfile->maxnamelen)
2328                         sfile->maxnamelen = len;
2329         }
2330 }
2331
2332 /* ******************* DATA SELECT ********************* */
2333
2334 static void filesel_select_objects(SpaceFile *sfile)
2335 {
2336         Object *ob;
2337         Base *base;
2338         Scene *sce;
2339         int a;
2340         
2341         /* only when F4 DATABROWSE */
2342         if(sfile->returnfunc) return;
2343         
2344         if( strcmp(sfile->dir, "Object/")==0 ) {
2345                 for(a=0; a<sfile->totfile; a++) {
2346                         
2347                         ob= (Object *)sfile->filelist[a].poin;
2348                         
2349                         if(ob) {
2350                                 if(sfile->filelist[a].flags & ACTIVE) ob->flag |= SELECT;
2351                                 else ob->flag &= ~SELECT;
2352                         }
2353
2354                 }
2355                 base= FIRSTBASE;
2356                 while(base) {
2357                         base->flag= base->object->flag;
2358                         base= base->next;
2359                 }
2360                 allqueue(REDRAWVIEW3D, 0);
2361         }
2362         else if( strcmp(sfile->dir, "Scene/")==0 ) {
2363                 
2364                 for(a=0; a<sfile->totfile; a++) {
2365                         
2366                         sce= (Scene *)sfile->filelist[a].poin;
2367                         if(sce) {
2368                                 if(sfile->filelist[a].flags & ACTIVE) sce->r.scemode |= R_BG_RENDER;
2369                                 else sce->r.scemode &= ~R_BG_RENDER;
2370                         }
2371
2372                 }
2373                 allqueue(REDRAWBUTSSCENE, 0);
2374         }
2375 }
2376
2377 static void active_file_object(SpaceFile *sfile)
2378 {
2379         Object *ob;
2380         
2381         /* only when F4 DATABROWSE */
2382         if(sfile->returnfunc) return;
2383         
2384         if( strcmp(sfile->dir, "Object/")==0 ) {
2385                 if(sfile->act >= 0) {
2386                         
2387                         ob= (Object *)sfile->filelist[sfile->act].poin;
2388                         
2389                         if(ob) {
2390                                 set_active_object(ob);
2391                                 if(BASACT && BASACT->object==ob) {
2392                                         BASACT->flag |= SELECT;
2393                                         sfile->filelist[sfile->act].flags |= ACTIVE;
2394                                         allqueue(REDRAWVIEW3D, 0);
2395                                         scrarea_queue_winredraw(curarea);
2396                                 }
2397                         }
2398                 }
2399         }
2400 }
2401
2402
2403 void main_to_filelist(SpaceFile *sfile)
2404 {
2405         ID *id;
2406         struct direntry *files, *firstlib = NULL;
2407         ListBase *lb;
2408         int a, fake, idcode, len, ok, totlib, totbl;
2409
2410         if(sfile->dir[0]=='/') sfile->dir[0]= 0;
2411         
2412         if(sfile->dir[0]) {
2413                 idcode= groupname_to_code(sfile->dir);
2414                 if(idcode==0) sfile->dir[0]= 0;
2415         }
2416         
2417         if( sfile->dir[0]==0) {
2418                 
2419                 /* make directories */
2420                 sfile->totfile= 22;
2421                 sfile->filelist= (struct direntry *)malloc(sfile->totfile * sizeof(struct direntry));
2422                 
2423                 for(a=0; a<sfile->totfile; a++) {
2424                         memset( &(sfile->filelist[a]), 0 , sizeof(struct direntry));
2425                         sfile->filelist[a].type |= S_IFDIR;
2426                 }
2427                 
2428                 sfile->filelist[0].relname= strdup("..");
2429                 sfile->filelist[1].relname= strdup(".");
2430                 sfile->filelist[2].relname= strdup("Scene");
2431                 sfile->filelist[3].relname= strdup("Object");
2432                 sfile->filelist[4].relname= strdup("Mesh");
2433                 sfile->filelist[5].relname= strdup("Curve");
2434                 sfile->filelist[6].relname= strdup("Metaball");
2435                 sfile->filelist[7].relname= strdup("Material");
2436                 sfile->filelist[8].relname= strdup("Texture");
2437                 sfile->filelist[9].relname= strdup("Image");
2438                 sfile->filelist[10].relname= strdup("Ika");
2439                 sfile->filelist[11].relname= strdup("Wave");
2440                 sfile->filelist[12].relname= strdup("Lattice");
2441                 sfile->filelist[13].relname= strdup("Lamp");
2442                 sfile->filelist[14].relname= strdup("Camera");
2443                 sfile->filelist[15].relname= strdup("Ipo");
2444                 sfile->filelist[16].relname= strdup("World");
2445                 sfile->filelist[17].relname= strdup("Screen");
2446                 sfile->filelist[18].relname= strdup("VFont");
2447                 sfile->filelist[19].relname= strdup("Text");
2448                 sfile->filelist[20].relname= strdup("Armature");
2449                 sfile->filelist[21].relname= strdup("Action");
2450                 qsort(sfile->filelist, sfile->totfile, sizeof(struct direntry), compare_name);
2451         }
2452         else {
2453
2454                 /* make files */
2455                 idcode= groupname_to_code(sfile->dir);
2456                 
2457                 lb= wich_libbase(G.main, idcode );
2458                 if(lb==0) return;
2459                 
2460                 id= lb->first;
2461                 sfile->totfile= 0;
2462                 while(id) {
2463                         
2464                         if(sfile->returnfunc && idcode==ID_IP) {
2465                                 if(sfile->ipotype== ((Ipo *)id)->blocktype) sfile->totfile++;
2466                         }
2467                         else sfile->totfile++;
2468                         
2469                         id= id->next;
2470                 }
2471                 
2472                 if(sfile->returnfunc==0) sfile->totfile+= 2;
2473                 sfile->filelist= (struct direntry *)malloc(sfile->totfile * sizeof(struct direntry));
2474                 
2475                 files= sfile->filelist;
2476                 
2477                 if(sfile->returnfunc==0) {
2478                         memset( &(sfile->filelist[0]), 0 , sizeof(struct direntry));
2479                         sfile->filelist[0].relname= strdup(".");
2480                         sfile->filelist[0].type |= S_IFDIR;
2481                         memset( &(sfile->filelist[1]), 0 , sizeof(struct direntry));
2482                         sfile->filelist[1].relname= strdup("..");
2483                         sfile->filelist[1].type |= S_IFDIR;
2484                 
2485                         files+= 2;
2486                 }
2487                 
2488                 id= lb->first;
2489                 totlib= totbl= 0;
2490                 
2491                 while(id) {
2492                         
2493                         ok= 0;
2494                         if(sfile->returnfunc && idcode==ID_IP) {
2495                                 if(sfile->ipotype== ((Ipo *)id)->blocktype) ok= 1;
2496                         }
2497                         else ok= 1;
2498                         
2499                         if(ok) {
2500                 
2501                                 memset( files, 0 , sizeof(struct direntry));
2502                                 files->relname= strdup(id->name+2);
2503                                 
2504                                 if(sfile->returnfunc==0) { /* F4 DATA BROWSE */
2505                                         if(idcode==ID_OB) {
2506                                                 if( ((Object *)id)->flag & SELECT) files->flags |= ACTIVE;
2507                                         }
2508                                         else if(idcode==ID_SCE) {
2509                                                 if( ((Scene *)id)->r.scemode & R_BG_RENDER) files->flags |= ACTIVE;
2510                                         }
2511                                 }
2512                                 files->nr= totbl+1;
2513                                 files->poin= id;
2514                                 fake= id->flag & LIB_FAKEUSER;
2515                                 
2516                                 if(id->lib && fake) sprintf(files->extra, "LF %d", id->us);
2517                                 else if(id->lib) sprintf(files->extra, "L    %d", id->us);
2518                                 else if(fake) sprintf(files->extra, "F    %d", id->us);
2519                                 else sprintf(files->extra, "      %d", id->us);
2520                                 
2521                                 if(id->lib) {
2522                                         if(totlib==0) firstlib= files;
2523                                         totlib++;
2524                                 }
2525                                 
2526                                 files++;
2527                                 totbl++;
2528                         }
2529                         
2530                         id= id->next;
2531                 }
2532                 
2533                 /* only qsort of libraryblokken */
2534                 if(totlib>1) {
2535                         qsort(firstlib, totlib, sizeof(struct direntry), compare_name);
2536                 }
2537         }
2538
2539         sfile->maxnamelen= 0;
2540         for(a=0; a<sfile->totfile; a++) {
2541                 len = BMF_GetStringWidth(G.font, sfile->filelist[a].relname);
2542                 if (len > sfile->maxnamelen) sfile->maxnamelen = len;
2543                 
2544                 if(filetoname) {
2545                         if( strcmp(sfile->file, sfile->filelist[a].relname)==0) {
2546                                 sfile->ofs= a-( sfile->collums*(curarea->winy-FILESELHEAD-10)/(2*FILESEL_DY));
2547                                 filetoname= 0;
2548                                 if(sfile->returnfunc) sfile->filelist[a].flags |= ACTIVE;
2549                         }
2550                 }
2551         }
2552 }
2553
2554
2555 void clever_numbuts_filesel()
2556 {
2557         SpaceFile *sfile;
2558         char orgname[FILE_MAXDIR+FILE_MAXFILE+12];
2559         char filename[FILE_MAXDIR+FILE_MAXFILE+12];
2560         char newname[FILE_MAXDIR+FILE_MAXFILE+12];
2561         int test;
2562         int len;
2563         
2564         sfile= curarea->spacedata.first;
2565
2566         if(sfile->type==FILE_MAIN) return;
2567         
2568         len = 110;
2569         test = get_hilited_entry(sfile);
2570
2571         if (test != -1 && !(S_ISDIR(sfile->filelist[test].type))){
2572                 BLI_make_file_string(G.sce, orgname, sfile->dir, sfile->filelist[test].relname);
2573                 strcpy(filename, sfile->filelist[test].relname);
2574                 
2575                 add_numbut(0, TEX, "", 0, len, filename, "Rename File");
2576
2577                 if( do_clever_numbuts("Rename File", 1, REDRAW) ) {
2578                         BLI_make_file_string(G.sce, newname, sfile->dir, filename);
2579
2580                         if( strcmp(orgname, newname) != 0 ) {
2581                                 BLI_rename(orgname, newname);
2582                                 freefilelist(sfile);
2583                         }
2584                 }
2585
2586                 scrarea_queue_winredraw(curarea);
2587         }
2588 }
2589