added function BLI_filepathsize - so you dont have to open the file to get its size.
[blender.git] / source / blender / blenlib / intern / storage.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  * Reorganised mar-01 nzc
32  * Some really low-level file thingies.
33  */
34
35 #include <sys/types.h>
36 #include <stdio.h>
37 #include <stdlib.h>     
38
39 #ifdef WIN32
40 #include "BLI_winstuff.h"
41 #include <sys/types.h>
42 #include <io.h>
43 #include <direct.h>
44 #endif
45
46 #ifndef WIN32
47 #include <dirent.h>
48 #endif
49
50 #include <time.h>
51 #include <sys/stat.h>
52
53 #if !defined(linux) && (defined(__sgi) || defined(__sun__) || defined(__sun) || defined(__sparc) || defined(__sparc__))
54 #include <sys/statfs.h>
55 #endif
56
57 #if defined (__FreeBSD__) || defined (__OpenBSD__) || defined (__NetBSD__)
58 #include <sys/param.h>
59 #include <sys/mount.h>
60 #endif
61
62 #if defined(linux) || defined(__CYGWIN32__) || defined(__hpux)
63 #include <sys/vfs.h>
64 #endif
65
66 #ifdef __BeOS
67 struct statfs {
68         int f_bsize;
69         int f_bfree;
70 };
71 #endif
72
73 #ifdef __APPLE__
74 /* For statfs */
75 #include <sys/param.h>
76 #include <sys/mount.h>
77 #endif /* __APPLE__ */
78
79
80 #include <fcntl.h>
81 #if !defined(__BeOS) && !defined(WIN32)
82 #include <sys/mtio.h>                   /* tape comando's */
83 #endif
84 #include <string.h>                     /* strcpy etc.. */
85
86 #ifndef WIN32
87 #include <sys/ioctl.h>
88 #include <unistd.h>                     /*  */
89 #include <pwd.h>
90 #endif
91
92 #if !defined(__FreeBSD__) && !defined(__APPLE__)
93 #include <malloc.h>
94 #endif
95
96 /* lib includes */
97 #include "MEM_guardedalloc.h"
98
99 #include "DNA_listBase.h"
100 #include "BLI_blenlib.h"
101 #include "BLI_storage.h"
102 #include "BLI_storage_types.h"
103
104 #include "BLI_util.h"
105 #include "BLI_linklist.h"
106
107 #include "BKE_utildefines.h"
108
109 /* vars: */
110 static int totnum,actnum;
111 static struct direntry *files;
112
113 static struct ListBase dirbase_={
114         0,0};
115 static struct ListBase *dirbase = &dirbase_;
116
117
118 char *BLI_getwdN(char *dir)
119 {
120         char *pwd;
121
122         if (dir) {
123                 pwd = getenv("PWD");
124                 if (pwd){
125                         strcpy(dir, pwd);
126                         return(dir);
127                 }
128                 /* 160 is FILE_MAXDIR in filesel.c */
129                 return( getcwd(dir, 160) );
130         }
131         return(0);
132 }
133
134
135 int BLI_compare(struct direntry *entry1, struct direntry *entry2)
136 {
137         /* type is equal to stat.st_mode */
138
139         if (S_ISDIR(entry1->type)){
140                 if (S_ISDIR(entry2->type)==0) return (-1);
141         } else{
142                 if (S_ISDIR(entry2->type)) return (1);
143         }
144         if (S_ISREG(entry1->type)){
145                 if (S_ISREG(entry2->type)==0) return (-1);
146         } else{
147                 if (S_ISREG(entry2->type)) return (1);
148         }
149         if ((entry1->type & S_IFMT) < (entry2->type & S_IFMT)) return (-1);
150         if ((entry1->type & S_IFMT) > (entry2->type & S_IFMT)) return (1);
151         
152         /* make sure "." and ".." are always first */
153         if( strcmp(entry1->relname, ".")==0 ) return (-1);
154         if( strcmp(entry2->relname, ".")==0 ) return (1);
155         if( strcmp(entry1->relname, "..")==0 ) return (-1);
156         
157         return (BLI_strcasecmp(entry1->relname,entry2->relname));
158 }
159
160
161 double BLI_diskfree(char *dir)
162 {
163 #ifdef WIN32
164         DWORD sectorspc, bytesps, freec, clusters;
165         char tmp[4];
166         
167         tmp[0]='\\'; tmp[1]=0; /* Just a failsafe */
168         if (dir[0]=='/' || dir[0]=='\\') {
169                 tmp[0]='\\';
170                 tmp[1]=0;
171         } else if (dir[1]==':') {
172                 tmp[0]=dir[0];
173                 tmp[1]=':';
174                 tmp[2]='\\';
175                 tmp[3]=0;
176         }
177
178         GetDiskFreeSpace(tmp,&sectorspc, &bytesps, &freec, &clusters);
179
180         return (double) (freec*bytesps*sectorspc);
181 #else
182         struct statfs disk;
183         char name[FILE_MAXDIR],*slash;
184         int len = strlen(dir);
185         
186         if (len >= FILE_MAXDIR) /* path too long */
187                 return -1;
188         
189         strcpy(name,dir);
190
191         if(len){
192                 slash = strrchr(name,'/');
193                 if (slash) slash[1] = 0;
194         } else strcpy(name,"/");
195
196 #if defined (__FreeBSD__) || defined (linux) || defined (__OpenBSD__) || defined (__APPLE__) 
197         if (statfs(name, &disk)) return(-1);
198 #endif
199 #ifdef __BeOS
200         return -1;
201 #endif
202 #if !defined(linux) && (defined (__sgi) || defined (__sun__) || defined (__sun) || defined(__sparc) || defined(__sparc__))
203
204         if (statfs(name, &disk, sizeof(struct statfs), 0)){
205                 /* printf("diskfree: Couldn't get information about %s.\n",dir); */
206                 return(-1);
207         }
208 #endif
209
210         return ( ((double) disk.f_bsize) * ((double) disk.f_bfree));
211 #endif
212 }
213
214 static int hide_dot= 0;
215
216 void BLI_hide_dot_files(int set)
217 {
218         if(set) hide_dot= 1;
219         else hide_dot= 0;
220 }
221
222 void BLI_builddir(char *dirname, char *relname)
223 {
224         struct dirent *fname;
225         struct dirlink *dlink;
226         int rellen, newnum = 0, seen_ = 0, seen__ = 0;
227         char buf[256];
228         DIR *dir;
229
230         strcpy(buf,relname);
231         rellen=strlen(relname);
232
233         if (rellen){
234                 buf[rellen]='/';
235                 rellen++;
236         }
237
238         if (chdir(dirname) == -1){
239                 perror(dirname);
240                 return;
241         }
242
243         if ( (dir = (DIR *)opendir(".")) ){
244                 while ((fname = (struct dirent*) readdir(dir)) != NULL) {
245                         
246                         if(hide_dot && fname->d_name[0]=='.' && fname->d_name[1]!='.' && fname->d_name[1]!=0);
247                         else {
248                                 
249                                 dlink = (struct dirlink *)malloc(sizeof(struct dirlink));
250                                 if (dlink){
251                                         strcpy(buf+rellen,fname->d_name);
252         
253                                         dlink->name = BLI_strdup(buf);
254         
255                                         if (dlink->name[0] == '.') {
256                                                 if (dlink->name[1] == 0) seen_ = 1;
257                                                 else if (dlink->name[1] == '.') {
258                                                         if (dlink->name[2] == 0) seen__ = 1;
259                                                 }
260                                         }
261                                         BLI_addhead(dirbase,dlink);
262                                         newnum++;
263                                 }
264                         }
265                 }
266                 
267                 if (newnum){
268 #ifndef WIN32           
269                         if (seen_ == 0) {       /* Cachefs PATCH */
270                                 dlink = (struct dirlink *)malloc(sizeof(struct dirlink));
271                                 strcpy(buf+rellen,"./.");
272                                 dlink->name = BLI_strdup(buf);
273                                 BLI_addhead(dirbase,dlink);
274                                 newnum++;
275                         }
276                         if (seen__ == 0) {      /* MAC PATCH */
277                                 dlink = (struct dirlink *)malloc(sizeof(struct dirlink));
278                                 strcpy(buf+rellen,"./..");
279                                 dlink->name = BLI_strdup(buf);
280                                 BLI_addhead(dirbase,dlink);
281                                 newnum++;
282                         }
283 #else // WIN32
284                         if (seen_ == 0) {       /* should only happen for root paths like "C:\" */
285                                 dlink = (struct dirlink *)malloc(sizeof(struct dirlink));
286                                 strcpy(buf+rellen,".");
287                                 dlink->name = BLI_strdup(buf);
288                                 BLI_addhead(dirbase,dlink);
289                                 newnum++;
290                         }
291 #endif                  
292
293                         if (files) files=(struct direntry *)realloc(files,(totnum+newnum) * sizeof(struct direntry));
294                         else files=(struct direntry *)malloc(newnum * sizeof(struct direntry));
295
296                         if (files){
297                                 dlink = (struct dirlink *) dirbase->first;
298                                 while(dlink){
299                                         memset(&files[actnum], 0 , sizeof(struct direntry));
300                                         files[actnum].relname = dlink->name;
301                                         stat(dlink->name,&files[actnum].s);
302                                         files[actnum].type=files[actnum].s.st_mode;
303                                         files[actnum].flags = 0;
304                                         totnum++;
305                                         actnum++;
306                                         dlink = dlink->next;
307                                 }
308                         } else{
309                                 printf("Couldn't get memory for dir\n");
310                                 exit(1);
311                         }
312
313                         BLI_freelist(dirbase);
314                         if (files) qsort(files, actnum, sizeof(struct direntry), (int (*)(const void *,const void*))BLI_compare);
315                 } else {
316                         printf("%s empty directory\n",dirname);
317                 }
318
319                 closedir(dir);
320         } else {
321                 printf("%s non-existant directory\n",dirname);
322         }
323 }
324
325 void BLI_adddirstrings()
326 {
327         char datum[100];
328         char buf[250];
329         char size[250];
330         static char * types[8] = {"---", "--x", "-w-", "-wx", "r--", "r-x", "rw-", "rwx"};
331         int num, mode;
332         int num1, num2, num3, num4;
333 #ifdef WIN32
334         __int64 st_size;
335 #else
336         long long st_size;
337 #endif
338         
339         struct direntry * file;
340         struct tm *tm;
341         time_t zero= 0;
342
343         file = &files[0];
344         
345         for(num=0;num<actnum;num++){
346 #ifdef WIN32
347                 mode = 0;
348                 strcpy(file->mode1, types[0]);
349                 strcpy(file->mode2, types[0]);
350                 strcpy(file->mode3, types[0]);
351 #else
352                 mode = file->s.st_mode;
353
354                 strcpy(file->mode1, types[(mode & 0700) >> 6]);
355                 strcpy(file->mode2, types[(mode & 0070) >> 3]);
356                 strcpy(file->mode3, types[(mode & 0007)]);
357                 
358                 if (((mode & S_ISGID) == S_ISGID) && (file->mode2[2]=='-'))file->mode2[2]='l';
359
360                 if (mode & (S_ISUID | S_ISGID)){
361                         if (file->mode1[2]=='x') file->mode1[2]='s';
362                         else file->mode1[2]='S';
363
364                         if (file->mode2[2]=='x')file->mode2[2]='s';
365                 }
366
367                 if (mode & S_ISVTX){
368                         if (file->mode3[2] == 'x') file->mode3[2] = 't';
369                         else file->mode3[2] = 'T';
370                 }
371 #endif
372
373 #ifdef WIN32
374                 strcpy(files[num].owner,"user");
375 #else
376                 {
377                         struct passwd *pwuser;
378                         pwuser = getpwuid(files[num].s.st_uid);
379                         if ( pwuser ) {
380                         strcpy(files[num].owner, pwuser->pw_name);
381                         } else {
382                                 sprintf(files[num].owner, "%d", files[num].s.st_uid);
383             }
384                 }
385 #endif
386
387                 tm= localtime(&files[num].s.st_mtime);
388                 // prevent impossible dates in windows
389                 if(tm==NULL) tm= localtime(&zero);
390                 strftime(files[num].time, 8, "%H:%M", tm);
391                 strftime(files[num].date, 16, "%d-%b-%y", tm);
392
393                 /*
394                  * Seems st_size is signed 32-bit value in *nix and Windows.  This
395                  * will buy us some time until files get bigger than 4GB or until
396                  * everyone starts using __USE_FILE_OFFSET64 or equivalent.
397                  */
398                 st_size= (unsigned int)files[num].s.st_size;
399                 
400                 num1= st_size % 1000;
401                 num2= st_size/1000;
402                 num2= num2 % 1000;
403                 num3= st_size/(1000*1000);
404                 num3= num3 % 1000;
405                 num4= st_size/(1000*1000*1000);
406                 num4= num4 % 1000;
407
408                 if(num4) sprintf(files[num].size, "%3d %03d %03d %03d", num4, num3, num2, num1);
409                 else if(num3) sprintf(files[num].size, "%7d %03d %03d", num3, num2, num1);
410                 else if(num2) sprintf(files[num].size, "%11d %03d", num2, num1);
411                 else if(num1) sprintf(files[num].size, "%15d", num1);
412                 else sprintf(files[num].size, "0");
413
414                 strftime(datum, 32, "%d-%b-%y %H:%M", tm);
415
416                 if (st_size < 1000) {
417                         sprintf(size, "%10d", (int) st_size);
418                 } else if (st_size < 1000 * 1000) {
419                         sprintf(size, "%6d %03d", (int) (st_size / 1000), (int) (st_size % 1000));
420                 } else if (st_size < 100 * 1000 * 1000) {
421                         sprintf(size, "%2d %03d %03d", (int) (st_size / (1000 * 1000)), (int) ((st_size / 1000) % 1000), (int) ( st_size % 1000));
422                 } else {
423                         sprintf(size, "> %4.1f M", (double) (st_size / (1024.0 * 1024.0)));
424                         sprintf(size, "%10d", (int) st_size);
425                 }
426
427                 sprintf(buf,"%s %s %10s %s", files[num].date, files[num].time, size,
428                         files[num].relname);
429
430                 sprintf(buf,"%s %s %s %7s %s %s %10s %s", file->mode1, file->mode2, file->mode3, files[num].owner, files[num].date, files[num].time, size,
431                         files[num].relname);
432
433                 files[num].string=MEM_mallocN(strlen(buf)+1, "filestring");
434                 if (files[num].string){
435                         strcpy(files[num].string,buf);
436                 }
437
438                 file++;
439         }
440 }
441
442 unsigned int BLI_getdir(char *dirname,  struct direntry **filelist)
443 {
444         // reset global variables
445         // memory stored in files is free()'d in
446         // filesel.c:freefilelist()
447
448         actnum = totnum = 0;
449         files = 0;
450
451         BLI_builddir(dirname,"");
452         BLI_adddirstrings();
453
454         if (files) {
455                 *(filelist) = files;
456         } else {
457                 // keep blender happy. Blender stores this in a variable
458                 // where 0 has special meaning.....
459                 *(filelist) = files = malloc(sizeof(struct direntry));
460         }
461
462         return(actnum);
463 }
464
465
466 int BLI_filesize(int file)
467 {
468         struct stat buf;
469
470         if (file <= 0) return (-1);
471         fstat(file, &buf);
472         return (buf.st_size);
473 }
474
475 int BLI_filepathsize(const char *path)
476 {
477         int size, file = open(path, O_BINARY|O_RDONLY);
478         
479         if (file <= 0)
480                 return -1;
481         
482         size = BLI_filesize(file);
483         close(file);
484         return size;
485 }
486
487
488 int BLI_exist(char *name)
489 {
490         struct stat st;
491 #ifdef WIN32
492         /*  in Windows stat doesn't recognize dir ending on a slash 
493                 To not break code where the ending slash is expected we
494                 don't mess with the argument name directly here - elubie */
495         char tmp[FILE_MAXDIR+FILE_MAXFILE];
496         int len;
497         BLI_strncpy(tmp, name, FILE_MAXDIR+FILE_MAXFILE);
498         len = strlen(tmp);
499         if (len > 3 && ( tmp[len-1]=='\\' || tmp[len-1]=='/') ) tmp[len-1] = '\0';
500         if (stat(tmp,&st)) return(0);
501 #else
502         if (stat(name,&st)) return(0);  
503 #endif
504         return(st.st_mode);
505 }
506
507 LinkNode *BLI_read_file_as_lines(char *name)
508 {
509         FILE *fp= fopen(name, "r");
510         LinkNode *lines= NULL;
511         char *buf;
512         int size;
513
514         if (!fp) return NULL;
515                 
516         fseek(fp, 0, SEEK_END);
517         size= ftell(fp);
518         fseek(fp, 0, SEEK_SET);
519
520         buf= malloc(size);
521         if (buf) {
522                 int i, last= 0;
523                 
524                         /* 
525                          * size = because on win32 reading
526                          * all the bytes in the file will return
527                          * less bytes because of crnl changes.
528                          */
529                 size= fread(buf, 1, size, fp);
530                 for (i=0; i<=size; i++) {
531                         if (i==size || buf[i]=='\n') {
532                                 char *line= BLI_strdupn(&buf[last], i-last);
533
534                                 BLI_linklist_prepend(&lines, line);
535                                 last= i+1;
536                         }
537                 }
538                 
539                 free(buf);
540         }
541         
542         fclose(fp);
543         
544         BLI_linklist_reverse(&lines);
545         return lines;
546 }
547
548 void BLI_free_file_lines(LinkNode *lines)
549 {
550         BLI_linklist_free(lines, (void(*)(void*)) MEM_freeN);
551 }