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