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