ecere:File: added Open(...) and Close() methods. for MyFileClass f {}; f.Open(path...
[sdk] / ecere / src / sys / File.ec
1 namespace sys;
2
3 default:
4 #define uint _uint
5 #define File _File
6 #include <stdio.h>
7 #include <stdarg.h>
8 #include <stdlib.h>
9
10 #define UNICODE
11
12 #define IS_ALUNDER(ch) ((ch) == '_' || isalnum((ch)))
13
14 #if defined(ECERE_BOOTSTRAP)
15 #undef __WIN32__
16 #undef __linux__
17 #undef __APPLE__
18 #undef __UNIX__
19 #endif
20
21 #ifndef ECERE_BOOTSTRAP
22 #if defined(__GNUC__) || defined(__WATCOMC__) || defined(__WIN32__)
23 #include <time.h>
24 #include <sys/types.h>
25 #include <sys/stat.h>
26 #include <fcntl.h>
27 #endif
28
29 #if defined(__unix__) || defined(__APPLE__)
30 #include <utime.h>
31 #endif
32
33 #if defined(__WIN32__) || defined(__WATCOMC__)
34 #include <direct.h>
35 #else
36 #include <dirent.h>
37 #endif
38
39 #if defined(__WIN32__)
40 #define WIN32_LEAN_AND_MEAN
41 #include <windows.h>
42 #include <io.h>
43
44 BOOL WINAPI GetVolumePathName(LPCTSTR lpszFileName,LPTSTR lpszVolumePathName,DWORD cchBufferLength);
45
46 // Missing function...
47 /*
48 #ifndef WNetGetResourceInformation 
49 DWORD APIENTRY WNetGetResourceInformationA(LPNETRESOURCE lpNetResource, LPVOID lpBuffer, LPDWORD lpcbBuffer, LPTSTR* lplpSystem);
50 #ifdef UNICODE
51 #define WNetGetResourceInformation  WNetGetResourceInformationW
52 #else
53 #define WNetGetResourceInformation  WNetGetResourceInformationA
54 #endif
55 #endif
56 */
57
58 #else
59 #include <unistd.h>
60 #endif
61
62
63 #include "zlib.h"
64
65 #endif //#ifndef ECERE_BOOTSTRAP
66 private:
67
68 #undef uint
69 #undef File
70
71 import "System"
72
73 #if !defined(ECERE_VANILLA) && !defined(ECERE_NONET) && !defined(ECERE_BOOTSTRAP)
74 import "HTTPFile"
75 #endif
76
77 import "dataTypes"
78
79 // IMPLEMENTATION OF THESE IS IN _File.c
80 default:
81
82 uint FILE_GetSize(FILE * input);
83 bool FILE_Lock(FILE * input, FILE * output, FileLock type, uint64 start, uint64 length, bool wait);
84 void FILE_set_buffered(FILE * input, FILE * output, bool value);
85 FileAttribs FILE_FileExists(char * fileName);
86 bool FILE_FileGetSize(char * fileName, FileSize * size);
87 bool FILE_FileGetStats(char * fileName, FileStats stats);
88 void FILE_FileFixCase(char * file);
89 void FILE_FileOpen(char * fileName, FileOpenMode mode, FILE ** input, FILE **output);
90
91 private:
92
93 FileSystem httpFileSystem;
94
95 public class FileSize : uint
96 {
97    // defaultAlignment = Right;
98    /*
99    void OnDisplay(Surface surface, int x, int y, int width, void * fieldData, int alignment, DataDisplayFlags displayFlags)
100    {
101       char string[16];
102       int len;
103       eUtils_PrintSize(string, *size, 2);
104       len = strlen(string);
105       surface.WriteTextDots(alignment, x, y, width, string, len);
106    }
107    */
108    int OnCompare(FileSize data2)
109    {
110       int result = 0;
111       if(&this && &data2)
112       {
113          if(this > data2)
114             result = 1;
115          else if(this < data2)
116             result = -1;
117       }
118       return result;
119    }
120
121    char * OnGetString(char * string, void * fieldData, bool * needClass)
122    {
123       PrintSize(string, this, 2);
124       return string;
125    }
126
127    bool OnGetDataFromString(char * string)
128    {
129       char * end;
130       double value = strtod(string, &end);
131       uint multiplier = 1;
132       if(strstr(end, "GB") || strstr(end, "gb")) multiplier = (uint)1024 * 1024 * 1024;
133       else if(strstr(end, "MB") || strstr(end, "mb")) multiplier = (uint)1024 * 1024;
134       else if(strstr(end, "KB") || strstr(end, "kb")) multiplier = 1024;
135
136       this = (uint)(multiplier * value);
137       return true;
138    }
139 };
140
141 class FileSystem
142 {
143    virtual File ::Open(char * archive, char * name, FileOpenMode mode);
144
145    // Query on names
146    virtual FileAttribs ::Exists(char * archive, char * fileName);
147    virtual bool ::GetSize(char * archive, char * fileName, FileSize * size);
148    virtual bool ::Stats(char * archive, char * fileName, FileStats stats);
149    virtual void ::FixCase(char * archive, char * fileName);
150
151    // File Listing
152    virtual bool ::Find(FileDesc file, char * archive, char * name);
153    virtual bool ::FindNext(FileDesc file);
154    virtual void ::CloseDir(FileDesc file);
155
156    // Archive manipulation
157    virtual Archive ::OpenArchive(char * fileName, ArchiveOpenFlags create);
158    virtual bool ::QuerySize(char * fileName, FileSize * size);
159 };
160
161 public enum FileOpenMode { read = 1, write, append, readWrite, writeRead, appendRead };
162 public enum FileSeekMode { start, current, end };
163
164 #if !defined(ECERE_BOOTSTRAP)
165 static FileDialog fileDialog { text = "Select File" };
166 #endif
167
168 public enum FileLock
169 {
170    unlocked = 0,     // LOCK_UN  _SH_DENYNO
171    shared = 1,       // LOCK_SH  _SH_DENYWR
172    exclusive = 2     // LOCK_EX  _SH_DENYRW
173 };
174
175 public class File : IOChannel
176 {
177    FILE * input, * output;
178
179    uint ReadData(byte * bytes, uint numBytes)
180    {
181       return Read(bytes, 1, numBytes);
182    }
183
184    uint WriteData(byte * bytes, uint numBytes)
185    {
186       return Write(bytes, 1, numBytes);
187    }
188
189    ~File()
190    {
191       if(output && output != input)
192       {
193          openCount--;
194          fclose(output);
195       }
196       if(input)
197       {
198          openCount--;
199          fclose(input);
200       }
201       input = null;
202       output = null;
203    }
204
205    bool OnGetDataFromString(char * string)
206    {
207       if(!string[0])
208       {
209          this = null;
210          return true;
211       }
212       else
213       {
214          File f = FileOpen(string, read);
215          if(f)
216          {
217             this = TempFile { };
218             while(!f.Eof())
219             {
220                byte buffer[4096];
221                uint read = f.Read(buffer, 1, sizeof(buffer));
222                Write(buffer, 1, read);
223             }
224             delete f;
225             return true;
226          }
227       }
228       return false;
229    }
230
231    char * OnGetString(char * tempString, void * fieldData, bool * needClass)
232    {
233       if(this)
234       {
235          PrintSize(tempString, GetSize(), 2);
236          return tempString;
237       }
238       return null;
239    }
240
241 #ifndef ECERE_BOOTSTRAP
242    Window OnEdit(DataBox dataBox, DataBox obsolete, int x, int y, int w, int h, void * userData)
243    {
244       Window editData = class::OnEdit(dataBox, obsolete, x + 24, y, w - 48, h, userData);
245       Button load
246       { 
247          dataBox, inactive = true, text = "Imp", hotKey = f2,
248          position = { Max(x + 24, x + w - 24), y }, size = { 24, h };
249
250          bool DataBox::NotifyClicked(Button button, int x, int y, Modifiers mods)
251          {
252             fileDialog.master = rootWindow;
253             fileDialog.filePath = "";
254             fileDialog.type = open;
255
256             if(fileDialog.Modal() == ok)
257             {
258                char * filePath = fileDialog.filePath;
259                File output = null;
260                if(output.OnGetDataFromString(filePath))
261                {
262                   SetData(output, false);
263                   Refresh();
264                }
265             }
266             return true;
267          }
268       };
269       Button save
270       { 
271          dataBox, inactive = true, text = "Exp", hotKey = f2,
272          position = { Max(x + 24, x + w - 48), y }, size = { 24, h };
273
274          bool DataBox::NotifyClicked(Button button, int x, int y, Modifiers mods)
275          {
276             fileDialog.master = rootWindow;
277             fileDialog.type = save;
278             fileDialog.filePath = "";
279             if(fileDialog.Modal() == ok)
280             {
281                char * filePath = fileDialog.filePath;
282                File f = FileOpen(filePath, write);
283                if(f)
284                {
285                   File input = *(void **)data;
286                   input.Seek(0, start);
287                   while(!input.Eof())
288                   {
289                      byte buffer[4096];
290                      uint read = input.Read(buffer, 1, sizeof(buffer));
291                      f.Write(buffer, 1, read);                     
292                   }
293                   delete f;
294                }               
295             }
296             return true;
297          }
298       };
299       load.Create();
300       save.Create();
301       return editData;
302    }
303 #endif //#ifndef ECERE_BOOTSTRAP
304
305 #if !defined(ECERE_VANILLA) && !defined(ECERE_NOARCHIVE) && !defined(ECERE_BOOTSTRAP)
306    void OnSerialize(IOChannel channel)
307    {
308       uint size = this ? GetSize() : MAXDWORD;
309       if(this)
310       {
311          byte * uncompressed = new byte[size];
312          Seek(0, start);
313          if(uncompressed || !size)
314          {
315             uint count = Read(uncompressed, 1,  size);
316             if(count == size)
317             {
318                uint cSize = size + size / 1000 + 12;
319                byte * compressed = new byte[cSize];
320                if(compressed)
321                {
322                   compress2(compressed, &cSize, uncompressed, size, 9);
323
324                   size.OnSerialize(channel);
325                   cSize.OnSerialize(channel);
326                   channel.WriteData(compressed, cSize);
327
328                   delete compressed;
329                }
330             }
331             delete uncompressed;
332          }
333       }
334       else
335          size.OnSerialize(channel);
336
337       /*
338       byte data[4096];
339       uint c;
340       size.OnSerialize(channel);
341
342       // Will add position...
343       if(this)
344       {
345          Seek(0, start);
346          for(c = 0; c<size; c += sizeof(data))
347          {
348             uint count = Read(data, 1, sizeof(data));
349             buffer.WriteData(data, count);
350          }
351       }
352       */
353    }
354
355    void OnUnserialize(IOChannel channel)
356    {
357       uint size, cSize;
358
359       this = null;
360
361       size.OnUnserialize(channel);
362       if(size != MAXDWORD)
363       {
364          byte * compressed;
365          cSize.OnUnserialize(channel);
366
367          compressed = new byte[cSize];
368          if(compressed)
369          {
370             if(channel.ReadData(compressed, cSize) == cSize)
371             {
372                byte * uncompressed = new byte[size];
373                if(uncompressed || !size)
374                {
375                   this = TempFile { };
376                   uncompress(uncompressed, &size, compressed, cSize);
377                   Write(uncompressed, 1, size);
378                   Seek(0, start);
379
380                   delete uncompressed;
381                }
382             }
383             delete compressed;
384          }
385       }
386
387       /*
388       byte data[4096];
389       uint c;
390
391       size.OnUnserialize(channel);
392       if(size != MAXDWORD)
393       {
394          this = TempFile { };
395          for(c = 0; c<size; c += sizeof(data))
396          {
397             uint count = Min(size - c, sizeof(data));
398             channel.ReadData(data, count);
399             Write(data, 1, count);
400          }
401          Seek(0, start);
402       }
403       else
404          this = null;
405       */
406    }
407 #endif
408
409 public:
410
411    // Virtual Methods
412    virtual bool Seek(int pos, FileSeekMode mode)
413    {
414       uint fmode = SEEK_SET;
415       switch(mode)
416       {
417          case start: fmode = SEEK_SET; break;
418          case end: fmode = SEEK_END; break;
419          case current: fmode = SEEK_CUR; break;
420       }
421       return fseek(input ? input : output, pos, fmode) != EOF;
422    }
423
424    virtual uint Tell(void)
425    {
426       return input ? ftell(input) : ftell(output);
427    }
428
429    virtual int Read(void * buffer, uint size, uint count)
430    {
431       return input ? (int)fread(buffer, size, count, input) : 0;
432    }
433
434    virtual int Write(void * buffer, uint size, uint count)
435    {
436       return output ? (int)fwrite(buffer, size, count, output) : 0;
437    }
438
439    // UNICODE OR NOT?
440    virtual bool Getc(char * ch)
441    {
442       int ich = fgetc(input);
443       if(ich != EOF)
444       {
445          if(ch) *ch = (char)ich;
446          return true;
447       }
448       return false;
449    }
450
451    virtual bool Putc(char ch)
452    {
453       return (fputc((int)ch, output) == EOF) ? false : true;
454    }
455
456    virtual bool Puts(const char * string)
457    {
458       bool result = false;
459       if(output)
460       {
461          result = (fputs(string, output) == EOF) ? false : true;
462          // TODO: Check if any repercusions of commenting out fflush here
463          // This is what broke the debugger in 0.44d2 , it is required for outputting things to the DualPipe
464          // Added an explicit flush call in DualPipe::Puts
465          // fflush(output);
466       }
467       return result;
468    }
469
470    virtual bool Eof(void)
471    {
472       return input ? feof(input) : true;
473    }
474    
475    virtual bool Truncate(FileSize size)
476    {
477    #ifdef ECERE_BOOTSTRAP
478       fprintf(stderr, "WARNING:  File::Truncate unimplemented in ecereBootstrap.\n");
479       return false;
480    #else
481    #if defined(__WIN32__)
482       return output ? (_chsize(fileno(output), size) == 0) : false;
483    #else
484       return output ? (ftruncate(fileno(output), size) == 0) : false;
485    #endif   
486    #endif
487    }
488
489    virtual uint GetSize(void)
490    {
491       return FILE_GetSize(input);
492    }
493    
494    virtual void CloseInput(void)
495    {
496       if(input)
497       {
498          fclose(input);
499          if(output == input)
500             output = null;
501          input = null;
502       }
503    }
504
505    virtual void CloseOutput(void)
506    {
507       if(output)
508       {
509          fclose(output);
510          if(input == output)
511             input = null;
512          output = null;
513       }
514    }
515
516    virtual bool Lock(FileLock type, uint64 start, uint64 length, bool wait)
517    {
518       return FILE_Lock(input, output, type, start, length, wait);
519    }
520
521    virtual bool Unlock(uint64 start, uint64 length, bool wait)
522    {
523       return Lock(unlocked, start, length, wait);
524    }
525
526    // Normal Methods
527    int Printf(char * format, ...)
528    {
529       int result = 0;
530       char text[MAX_F_STRING];
531       va_list args;
532       va_start(args, format);
533       vsprintf(text, format, args);
534       if(Puts(text))
535          result = strlen(text);
536       va_end(args);
537       return result;
538    }
539
540    public void PrintLn(typed_object object, ...)
541    {
542       va_list args;
543       char buffer[4096];
544       va_start(args, object);
545       PrintStdArgsToBuffer(buffer, sizeof(buffer), object, args);
546       Puts(buffer);
547       Putc('\n');
548       va_end(args);
549    }
550
551    public void Print(typed_object object, ...)
552    {
553       va_list args;
554       char buffer[4096];
555       va_start(args, object);
556       PrintStdArgsToBuffer(buffer, sizeof(buffer), object, args);
557       Puts(buffer);
558       va_end(args);
559    }
560
561    bool Flush(void)
562    {
563       fflush(output);
564       return true;
565    }
566
567    bool GetLine(char *s, int max)
568    {
569       int c = 0;
570       bool result = true;
571       s[c]=0;
572
573       if(Eof())
574       {
575          result = false;
576       }
577       else
578       {
579          while(c<max-1)
580          {
581             char ch = 0;
582          
583             if(/*!Peek() || */ !Getc(&ch))
584             {
585                result = false;
586                break;
587             }
588             if(ch =='\n') 
589                break;
590             if(ch !='\r')
591                s[c++]=ch;
592          }
593       }
594       s[c]=0;
595       return result || c > 1;
596    }
597
598    // Strings and numbers separated by spaces, commas, tabs, or CR/LF, handling quotes
599    bool GetString(char * string, int max)
600    {
601       int c;
602       char ch;
603       bool quoted = false;
604       bool result = true;
605
606       *string = 0;
607       while(true)
608       {
609          if(!Getc(&ch))
610             result = false;
611          if( (ch!='\n') && (ch!='\r') && (ch!=' ') && (ch!=',') && (ch!='\t'))
612             break;
613          if(Eof()) break;
614       }
615       if(result)
616       {
617          for(c=0; c<max-1; c++)
618          {
619             if(!quoted && ((ch=='\n')||(ch=='\r')||(ch==' ')||(ch==',')||(ch=='\t')))
620             {
621                result = true;
622                break;
623             }
624             if(ch == '\"')
625             {
626                quoted ^= 1;
627                c--;
628             }
629             else
630                string[c]=ch;
631
632             if(!Getc(&ch)) 
633             {
634                c++;
635                result = false;
636                break;            
637             }
638          }
639          string[c]=0;
640       }
641       return result;
642    }
643
644    int GetValue(void)
645    {
646       char string[32];
647       GetString(string,sizeof(string));
648       return atoi(string);
649    }
650
651    unsigned int GetHexValue(void)
652    {
653       char string[32];
654       GetString(string, sizeof(string));
655       return strtoul(string, null, 16);
656    }
657
658    float GetFloat(void)
659    {
660       char string[32];
661       GetString(string, sizeof(string));
662       return (float)FloatFromString(string);
663    }
664
665    double GetDouble(void)
666    {
667       char string[32];
668       GetString(string, sizeof(string));
669       return FloatFromString(string);
670    }
671
672    property void * input { set { input = value; } get { return input; } }
673    property void * output { set { output = value; } get { return output; } }
674    property bool buffered
675    {
676       set
677       {
678          FILE_set_buffered(input, output, value);
679       }      
680    }
681    property bool eof { get { return Eof(); } }
682
683    int GetLineEx(char *s, int max, bool *hasNewLineChar)
684    {
685       int c = 0;
686       s[c] = '\0';
687
688       if(!Eof())
689       {
690          char ch = '\0';
691          while(c < max - 1)
692          {
693             if(/*!Peek() || */ !Getc(&ch))
694                break;
695             if(ch == '\n')
696                break;
697             if(ch != '\r')
698                s[c++] = ch;
699          }
700          if(hasNewLineChar)
701             *hasNewLineChar = (ch == '\n');
702       }
703       s[c] = '\0';
704       return c;
705    }
706
707    bool CopyTo(char * outputFileName)
708    {
709       bool result = false;
710       File f = FileOpen(outputFileName, write);
711       if(f)
712       {
713          byte buffer[65536];
714
715          result = true;
716          Seek(0, start);
717          while(!Eof())
718          {
719             uint count = Read(buffer, 1, sizeof(buffer));
720             if(count && !f.Write(buffer, 1, count))
721             {
722                result = false;
723                break;
724             }
725          }
726       }
727       Seek(0, start);
728       return result;
729    }
730
731    virtual bool Open(char * fileName, FileOpenMode mode)
732    {
733       bool result = false;
734       if(this)
735       {
736          FILE_FileOpen(fileName, mode, &input, &output);
737
738          //file.mode = mode;
739          if(!input && !output);
740          else
741          {
742             openCount++;
743             result = true;
744             // TESTING ENABLING FILE BUFFERING BY DEFAULT... DOCUMENT ANY ISSUE
745             /*
746             if(file.input)
747                setvbuf(file.input, null, _IONBF, 0);
748             else
749                setvbuf(file.output, null, _IONBF, 0);
750             */
751          }
752          //if(!result)
753          {
754             /* TOFIX:
755             LogErrorCode((mode == Read || mode == ReadWrite) ? 
756                ERR_FILE_NOT_FOUND : ERR_FILE_WRITE_FAILED, fileName);
757             */
758          }
759       }
760       return result;
761    }
762
763    virtual void Close()
764    {
765       CloseOutput();
766       CloseInput();
767    }
768 }
769
770 public class ConsoleFile : File
771 {
772    input = stdin;
773    output = stdout;
774    ~ConsoleFile()
775    {
776       input = null;
777       output = null;
778    }
779 };
780
781 public class FileAttribs : bool
782 {
783 public:
784    bool isFile:1, isArchive:1, isHidden:1, isReadOnly:1, isSystem:1, isTemporary:1, isDirectory:1;
785    bool isDrive:1, isCDROM:1, isRemote:1, isRemovable:1, isServer:1, isShare:1;
786    // property bool { };
787 };
788
789 public struct FileStats
790 {
791    FileAttribs attribs;
792    FileSize size;
793    SecSince1970 accessed;
794    SecSince1970 modified;
795    SecSince1970 created;
796 };
797
798 #if defined(__WIN32__)
799
800 // --- FileName functions ---
801
802 default TimeStamp Win32FileTimeToTimeStamp(FILETIME * fileTime)
803 {
804    // TIME_ZONE_INFORMATION tz = { 0 };
805    SYSTEMTIME st, lt;
806    DateTime t;
807
808    FileTimeToSystemTime(fileTime, &lt);
809
810    /*
811    GetTimeZoneInformation(&tz);
812    tz.Bias = 0;
813    _TzSpecificLocalTimeToSystemTime(&tz, &lt, &st);
814    */
815    st = lt;
816
817    t.year = st.wYear;
818    t.month = (Month)(st.wMonth - 1);
819    t.day = st.wDay;
820    t.hour = st.wHour;
821    t.minute = st.wMinute;
822    t.second = st.wSecond;
823    return t;
824 }
825
826 default void TimeStampToWin32FileTime(TimeStamp t, FILETIME * fileTime)
827 {
828    // TIME_ZONE_INFORMATION tz = { 0 };
829    SYSTEMTIME st, lt;
830    DateTime tm;
831    
832    tm = t;
833
834    st.wYear = (short)tm.year;
835    st.wMonth = (short)tm.month + 1;
836    st.wDay = (short)tm.day;
837    st.wHour = (short)tm.hour;
838    st.wMinute = (short)tm.minute;
839    st.wSecond = (short)tm.second;
840    st.wMilliseconds = 0;
841    st.wDayOfWeek = 0;
842
843    /*
844    GetTimeZoneInformation(&tz);
845    tz.Bias = 0;
846    SystemTimeToTzSpecificLocalTime(&tz, &st, &lt);
847    */
848
849    lt = st;
850    SystemTimeToFileTime(&lt, fileTime);
851 }
852 /*
853 default TimeStamp Win32FileTimeToTimeStamp(FILETIME * fileTime);
854 default void TimeStampToWin32FileTime(TimeStamp t, FILETIME * fileTime);
855 */
856 default bool WinReviveNetworkResource(uint16 * _wfileName);
857
858 #endif
859
860 public FileAttribs FileExists(char * fileName)
861 {
862    char archiveName[MAX_LOCATION], * archiveFile;
863 #if !defined(ECERE_BOOTSTRAP)
864    if(SplitArchivePath(fileName, archiveName, &archiveFile))
865    {
866       return EARFileSystem::Exists(archiveName, archiveFile);
867    }
868    else if(strstr(fileName, "http://") == fileName)
869    {
870       return FileAttribs { isFile = true };
871    }
872    else
873 #endif
874       return FILE_FileExists(fileName);
875 }
876
877 static int openCount;
878
879 public File FileOpen(char * fileName, FileOpenMode mode)
880 {
881    File result = null;
882    if(fileName)
883    {
884       char archiveName[MAX_LOCATION], * archiveFile;
885 #if !defined(ECERE_BOOTSTRAP)
886       if(SplitArchivePath(fileName, archiveName, &archiveFile))
887       {
888          result = EARFileSystem::Open(archiveName, archiveFile, mode);
889       }
890 #if !defined(ECERE_VANILLA) && !defined(ECERE_NONET)
891       else if(strstr(fileName, "http://") == fileName)
892       {
893          result = FileOpenURL(fileName);
894       }
895 #endif
896       else
897 #endif
898       if(strstr(fileName, "File://") == fileName)
899       {
900          result = (File)strtoul(fileName+7, null, 16);
901          if(result)
902          {
903             if(result._class && eClass_IsDerived(result._class, class(File)))
904             {
905                if(!result._refCount) incref result;
906                incref result;
907                result.Seek(0, start);
908             }
909             else
910                result = null;
911          }
912       }
913       else
914       {
915          File file = File {};
916          if(file)
917          {
918             if(file.Open(fileName, mode))
919                result = file;
920             else
921                delete file;
922          }
923       }
924    }
925    return result;
926 }
927
928 public void FileFixCase(char * file)
929 {
930    FILE_FileFixCase(file);
931 }
932
933 #if !defined(ECERE_BOOTSTRAP)
934 public bool FileTruncate(char * fileName, FileSize size)
935 {
936 #if defined(__WIN32__)
937    uint16 * _wfileName = UTF8toUTF16(fileName, null);
938    int f = _wopen(_wfileName, _O_RDWR|_O_CREAT, _S_IREAD|_S_IWRITE);
939    bool result = false;
940    if(f != -1)
941    {
942       if(!_chsize(f, size))
943          result = true;
944       _close(f);
945    }
946    delete _wfileName;
947    return result;
948 #else
949    return truncate(fileName, size) == 0;
950 #endif
951 }
952 #endif
953
954 public bool FileGetSize(char * fileName, FileSize * size)
955 {
956    bool result = false;
957    if(size)
958    {
959       *size = 0;
960       if(fileName)
961       {
962 #if !defined(ECERE_BOOTSTRAP)
963          char archiveName[MAX_LOCATION], * archiveFile;
964          if(SplitArchivePath(fileName, archiveName, &archiveFile))
965             return EARFileSystem::GetSize(archiveName, archiveFile, size);
966          else
967 #endif
968             result = FILE_FileGetSize(fileName, size);
969       }
970    }
971    return result;
972 }
973
974 public bool FileGetStats(char * fileName, FileStats stats)
975 {
976    bool result = false;
977    if(stats && fileName)
978    {
979 #if !defined(ECERE_BOOTSTRAP)
980       char archiveName[MAX_LOCATION], * archiveFile;
981       if(SplitArchivePath(fileName, archiveName, &archiveFile))
982          result = EARFileSystem::Stats(archiveName, archiveFile, stats);
983       else
984 #endif
985          return FILE_FileGetStats(fileName, stats);
986    }
987    return result;
988 }
989
990 #ifndef ECERE_BOOTSTRAP
991
992 public bool FileSetAttribs(char * fileName, FileAttribs attribs)
993 {
994 #ifdef __WIN32__
995    uint winAttribs = 0;
996    uint16 * _wfileName = UTF8toUTF16(fileName, null);
997
998    if(attribs.isHidden)   winAttribs |= FILE_ATTRIBUTE_HIDDEN;
999    if(attribs.isReadOnly) winAttribs |= FILE_ATTRIBUTE_READONLY;
1000
1001    SetFileAttributes(_wfileName, winAttribs);
1002    delete _wfileName;
1003 #endif
1004    return true;
1005 }
1006
1007 public bool FileSetTime(char * fileName, TimeStamp created, TimeStamp accessed, TimeStamp modified)
1008 {
1009    bool result = false;
1010    TimeStamp currentTime = time(null);
1011    if(!created)  created = currentTime;
1012    if(!accessed) accessed = currentTime;
1013    if(!modified) modified = currentTime;
1014    if(fileName)
1015    {
1016 #ifdef __WIN32__
1017       uint16 * _wfileName = UTF8toUTF16(fileName, null);
1018       HANDLE hFile = CreateFile(_wfileName, GENERIC_WRITE|GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, null,
1019          OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, null);
1020       delete _wfileName;
1021       if(hFile != INVALID_HANDLE_VALUE)
1022       {
1023          FILETIME c, a, m;
1024       
1025          TimeStampToWin32FileTime(created, &c);
1026          TimeStampToWin32FileTime(accessed, &a);
1027          TimeStampToWin32FileTime(modified, &m);
1028
1029          /*
1030          {
1031             uint cc,aa,mm;
1032
1033             cc = Win32FileTimeToTimeStamp(&c);
1034             aa = Win32FileTimeToTimeStamp(&a);
1035             mm = Win32FileTimeToTimeStamp(&m);
1036          }
1037          */
1038                   
1039          if(SetFileTime(hFile, &c, &a, &m))
1040             result = true;
1041
1042          CloseHandle(hFile);
1043       }
1044 #else
1045       struct utimbuf t = { (int)accessed, (int)modified };
1046       if(!utime(fileName, &t))
1047          result = true;
1048 #endif
1049    }
1050    return result;
1051 }
1052
1053 /****************************************************************************
1054  Directory Listing
1055 ****************************************************************************/
1056 // Directory Description for file listing
1057 private class Dir : struct
1058 {
1059 #if defined(__WIN32__)
1060    HANDLE fHandle;
1061
1062    int resource;
1063    NETRESOURCE * resources;
1064    int numResources;
1065
1066    int workGroup;
1067    NETRESOURCE * workGroups;
1068    int numWorkGroups;
1069 #else
1070    DIR * d;
1071 #endif
1072    char name[MAX_LOCATION];
1073 };
1074
1075 static FileDesc FileFind(char * path, char * extensions)
1076 {
1077    FileDesc result = null;
1078    FileDesc file;
1079
1080    if((file = FileDesc {}))
1081    {
1082       char archiveName[MAX_LOCATION], * archiveFile;
1083       if(SplitArchivePath(path, archiveName, &archiveFile))
1084       {
1085          if(EARFileSystem::Find(file, archiveName, archiveFile))
1086          {
1087             file.system = class(EARFileSystem);
1088             result = file;
1089          }
1090       }
1091       else
1092       {
1093          Dir d;
1094       
1095          if((d = file.dir = Dir {}))
1096          {
1097 #if defined(__WIN32__)
1098             if(!strcmp(path, "/"))
1099             {
1100                int c;
1101                d.fHandle = (void *)0xFFFFFFFF; //GetLogicalDrives();
1102                for(c = 0; c<26; c++)
1103                   if(((uint)d.fHandle) & (1<<c))
1104                   {
1105                      char volume[MAX_FILENAME] = "";
1106                      uint16 _wvolume[MAX_FILENAME];
1107                      int driveType;
1108                      uint16 _wfilePath[4];
1109
1110                      strcpy(d.name, path);
1111                      file.stats.attribs = FileAttribs { isDirectory = true, isDrive = true };
1112                      _wfilePath[0] = file.path[0] = (char)('A' + c);
1113                      _wfilePath[1] = file.path[1] = ':';
1114                      _wfilePath[2] = file.path[2] = '\\';
1115                      _wfilePath[3] = file.path[3] = '\0';
1116                      file.stats.size = 0;
1117                      file.stats.accessed = file.stats.created = file.stats.modified = 0;
1118                      driveType = GetDriveType(_wfilePath);
1119                      switch(driveType)
1120                      {
1121                         case DRIVE_REMOVABLE: file.stats.attribs.isRemovable = true; break;
1122                         case DRIVE_REMOTE:    file.stats.attribs.isRemote = true; break;
1123                         case DRIVE_CDROM:     file.stats.attribs.isCDROM = true; break;
1124                      }
1125                      *((uint *)&d.fHandle) ^= (1<<c);
1126                      if(driveType == DRIVE_NO_ROOT_DIR) continue;
1127                   
1128                      if(driveType != DRIVE_REMOVABLE && driveType != DRIVE_REMOTE && 
1129                         GetVolumeInformation(_wfilePath, _wvolume, MAX_FILENAME - 1, null, null, null, null, 0))
1130                      {
1131                         file.path[2] = '\0';
1132                         UTF16toUTF8Buffer(_wvolume, volume, MAX_FILENAME);
1133                         sprintf(file.name, "%s [%s]", file.path, volume);
1134                      }
1135                      else
1136                      {
1137                         file.path[2] = '\0';
1138                         strcpy(file.name, file.path);
1139                      }
1140                      result = file;
1141                      break;
1142                   }
1143                d.resource = 0;
1144             }
1145             else if(path[0] != '\\' || path[1] != '\\' || strstr(path+2, "\\"))
1146             {
1147                WIN32_FIND_DATA winFile;
1148                uint16 dir[MAX_PATH];
1149
1150                UTF8toUTF16Buffer(path, dir, MAX_LOCATION);
1151                if(path[0]) wcscat(dir, L"\\");
1152                wcscat(dir, L"*.*");
1153
1154                d.fHandle = FindFirstFile(dir, &winFile);
1155                if(d.fHandle == INVALID_HANDLE_VALUE && WinReviveNetworkResource(dir))
1156                   d.fHandle = FindFirstFile(dir, &winFile);
1157                if(d.fHandle != INVALID_HANDLE_VALUE)
1158                {
1159                   UTF16toUTF8Buffer(winFile.cFileName, file.name, MAX_FILENAME);
1160                   strcpy(file.path, path);
1161                   PathCat(file.path, file.name);
1162                   /*if(path[0])
1163                      strcat(file.path, DIR_SEPS);
1164                   strcat(file.path, file.name);*/
1165                   // file.sizeHigh = winFile.nFileSizeHigh;
1166                   file.stats.size = winFile.nFileSizeLow;
1167
1168                   file.stats.attribs = FileAttribs { };
1169                   file.stats.attribs.isArchive   = (winFile.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE)   ? true : false;
1170                   file.stats.attribs.isHidden    = (winFile.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)    ? true : false;
1171                   file.stats.attribs.isReadOnly  = (winFile.dwFileAttributes & FILE_ATTRIBUTE_READONLY)  ? true : false;
1172                   file.stats.attribs.isSystem    = (winFile.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)    ? true : false;
1173                   file.stats.attribs.isTemporary = (winFile.dwFileAttributes & FILE_ATTRIBUTE_TEMPORARY) ? true : false;
1174                   file.stats.attribs.isDirectory = (winFile.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? true : false;
1175                   strcpy(d.name, path);
1176
1177                   file.stats.accessed = Win32FileTimeToTimeStamp(&winFile.ftLastAccessTime);
1178                   file.stats.modified = Win32FileTimeToTimeStamp(&winFile.ftLastWriteTime);
1179                   file.stats.created  = Win32FileTimeToTimeStamp(&winFile.ftCreationTime);
1180                   result = file;
1181                }
1182             }
1183             else
1184             {
1185                HANDLE handle = 0;
1186                int count = 0xFFFFFFFF;
1187                uint size = 512 * sizeof(NETRESOURCE);
1188                NETRESOURCE * buffer = (NETRESOURCE *)new0 byte[size];
1189                NETRESOURCE nr = {0};
1190
1191                d.fHandle = null;
1192                nr.dwScope       = RESOURCE_GLOBALNET;
1193                nr.dwType        = RESOURCETYPE_DISK;
1194                nr.lpProvider = L"Microsoft Windows Network";
1195
1196                strcpy(d.name, path);
1197                if(path[2])
1198                {
1199                   nr.lpRemoteName = UTF8toUTF16(path, null);
1200
1201                   // Server
1202                   WNetOpenEnum(RESOURCE_GLOBALNET, RESOURCETYPE_DISK, 0, &nr, &handle);
1203                   if(!handle)
1204                   {
1205                      WinReviveNetworkResource(nr.lpRemoteName);
1206                      WNetOpenEnum(RESOURCE_GLOBALNET, RESOURCETYPE_DISK, 0, &nr, &handle);
1207                   }
1208
1209                   if(handle)
1210                   {
1211                      while(true)
1212                      {
1213                         int returnCode = WNetEnumResource(handle, &count, buffer, &size);
1214                         if(returnCode != ERROR_MORE_DATA)
1215                            break;
1216                         count = 0xFFFFFFFF;
1217                         buffer = (NETRESOURCE *)renew0 buffer byte[size];
1218                      }
1219                      WNetCloseEnum(handle);
1220                   }
1221
1222                   delete nr.lpRemoteName;
1223                   if(count > 0)
1224                   {
1225                      file.stats.attribs = FileAttribs { isDirectory = true, isShare = true };
1226                      file.stats.size = 0;
1227                      file.stats.accessed = file.stats.created = file.stats.modified = 0;
1228
1229                      UTF16toUTF8Buffer(buffer->lpRemoteName, file.path, MAX_LOCATION);
1230                      GetLastDirectory(file.path, file.name);
1231
1232                      result = file;
1233                      d.resources = buffer;
1234                      d.numResources = count;
1235                      d.resource = 1;
1236                   }
1237                   else
1238                      delete buffer;
1239                }
1240                else
1241                {
1242                   int c;
1243                   nr.lpProvider = L"Microsoft Windows Network";
1244
1245                   // Entire Network
1246                   WNetOpenEnum(RESOURCE_GLOBALNET, RESOURCETYPE_DISK, 0, &nr, &handle);
1247                   while(true)
1248                   {
1249                      int returnCode = WNetEnumResource(handle, &count, buffer, &size);
1250                      if(returnCode != ERROR_MORE_DATA)
1251                         break;
1252                      count = 0xFFFFFFFF;
1253                      buffer = (NETRESOURCE *)renew0 buffer byte[size];
1254                   }
1255                   WNetCloseEnum(handle);
1256
1257                   for(c = 0; c<count; c++)
1258                   {
1259                      NETRESOURCE * resources;
1260                      int countInGroup = 0xFFFFFFFF;
1261
1262                      size = 512 * sizeof(NETRESOURCE);
1263                      resources = (NETRESOURCE *)new0 byte[size];
1264                   
1265                      // Entire Network
1266                      WNetOpenEnum(RESOURCE_GLOBALNET, RESOURCETYPE_DISK, 0, &buffer[c], &handle);
1267                      while(true)
1268                      {
1269                         int returnCode = WNetEnumResource(handle, &countInGroup, resources, &size);
1270                         if(returnCode != ERROR_MORE_DATA)
1271                            break;
1272                         countInGroup = 0xFFFFFFFF;
1273                         resources = (NETRESOURCE *)renew0 resources byte[size];
1274                      }
1275                      WNetCloseEnum(handle);
1276
1277                      if(countInGroup)
1278                      {
1279                         file.stats.attribs = FileAttribs { isDirectory = true, isServer = true };
1280                         file.stats.size = 0;
1281                         file.stats.accessed = file.stats.created = file.stats.modified = 0;
1282
1283                         UTF16toUTF8Buffer(resources->lpRemoteName, file.path, MAX_LOCATION);
1284                         strlwr(file.path);
1285                         file.path[2] = (char)toupper(file.path[2]);
1286                         GetLastDirectory(file.path, file.name);
1287
1288                         result = file;
1289
1290                         d.resources = resources;
1291                         d.numResources = countInGroup;
1292                         d.resource = 1;
1293
1294                         d.workGroups = buffer;
1295                         d.numWorkGroups = count;
1296                         d.workGroup = c;
1297                         break;
1298                      }
1299                      else
1300                         delete resources;
1301                   }
1302                   if(c >= count && buffer) delete buffer;
1303                }
1304             }
1305 #else
1306             struct dirent *de;
1307             struct stat s;
1308
1309             d.d = opendir((path && path[0]) ? path : ".");
1310             if(d.d && (de = readdir(d.d)))
1311             {
1312                if(path[0])
1313                {
1314                   strcpy(file.path, path);
1315                   strcat(file.path, DIR_SEPS);
1316                }
1317                strcpy(file.name,de->d_name);
1318                strcat(file.path, file.name);
1319                stat(file.path, &s);
1320                file.stats.attribs = (s.st_mode&S_IFDIR) ? FileAttribs { isDirectory = true } : FileAttribs { isFile = true };
1321                file.stats.size = s.st_size;
1322                file.stats.accessed = s.st_atime;
1323                file.stats.modified = s.st_mtime;
1324                file.stats.created = s.st_ctime;
1325           
1326                strcpy(d.name, path);
1327
1328                result = file;
1329             }
1330 #endif
1331          }
1332
1333          if(!result)
1334             delete d;
1335       }
1336       if(!result)
1337          delete file;
1338    }
1339    if(result)
1340    {
1341       while(result && !result.Validate(extensions))
1342          result = result.FindNext(extensions);
1343    }
1344    return result;
1345 }
1346
1347 private class FileDesc : struct
1348 {
1349    FileStats stats;
1350    char name[MAX_FILENAME];
1351    char path[MAX_LOCATION];
1352
1353    subclass(FileSystem) system;
1354    Dir dir;
1355
1356    bool Validate(char * extensions)
1357    {
1358       if(strcmp(name, "..") && strcmp(name, ".") && strcmp(name, ""))
1359       {
1360          if(extensions && !stats.attribs.isDirectory)
1361          {
1362             char extension[MAX_EXTENSION], compared[MAX_EXTENSION];
1363             int c;
1364
1365             GetExtension(name, extension);
1366             for(c = 0; extensions[c];)
1367             {
1368                int len = 0;
1369                char ch;
1370                for(;(ch = extensions[c]) && !IS_ALUNDER(ch); c++);
1371                for(;(ch = extensions[c]) &&  IS_ALUNDER(ch); c++)
1372                   compared[len++] = ch;
1373                compared[len] = '\0';
1374
1375                if(!strcmpi(extension, compared))
1376                   return true;
1377             }
1378          }
1379          else
1380             return true;
1381       }
1382       return false;
1383    }
1384
1385    FileDesc FindNext(char * extensions)
1386    {
1387       FileDesc result = null;
1388
1389       Dir d = dir;
1390
1391       name[0] = '.';
1392       name[1] = '\0';
1393       while(!Validate(extensions))
1394       {
1395          result = null;
1396
1397          if(system)
1398          {
1399             if(system.FindNext(this))
1400                result = this;
1401             else
1402                break;
1403          }
1404          else
1405          {
1406 #if defined(__WIN32__)
1407             if(!strcmp(d.name, "/"))
1408             {
1409                int c;
1410                for(c = 0; c<26; c++)
1411                {
1412                   if(((uint)d.fHandle) & (1<<c))
1413                   {
1414                      char volume[MAX_FILENAME] = "";
1415                      int driveType;
1416                      uint16 _wpath[4];
1417                      uint16 _wvolume[MAX_FILENAME];
1418
1419                      stats.attribs = FileAttribs { isDirectory = true, isDrive = true };
1420                      stats.size = 0;
1421                      stats.accessed = stats.created = stats.modified = 0;
1422                      _wpath[0] = path[0] = (char)('A' + c);
1423                      _wpath[1] = path[1] = ':';
1424                      _wpath[2] = path[2] = '\\';
1425                      _wpath[3] = path[3] = 0;
1426                      driveType = GetDriveType(_wpath);
1427                      *((uint *)&d.fHandle) ^= (1<<c);
1428
1429                      switch(driveType)
1430                      {
1431                         case DRIVE_REMOVABLE: stats.attribs.isRemovable = true; break;
1432                         case DRIVE_REMOTE:    stats.attribs.isRemote = true;    break;
1433                         case DRIVE_CDROM:     stats.attribs.isCDROM = true;     break;
1434                      }
1435                      if(driveType == DRIVE_NO_ROOT_DIR)
1436                      {
1437                         uint16 remoteName[1024];
1438                         int status;
1439                         int size = 1024;
1440                         _wpath[2] = 0;
1441
1442                         status = WNetGetConnection(_wpath, remoteName, &size);
1443                         if(status != ERROR_CONNECTION_UNAVAIL)
1444                            continue;
1445
1446                         _wpath[2] = '\\';
1447                         _wpath[3] = 0;
1448                      }
1449
1450                      if(driveType != DRIVE_REMOVABLE && driveType != DRIVE_REMOTE && 
1451                         GetVolumeInformation(_wpath, _wvolume, MAX_FILENAME - 1, null, null, null, null, 0))
1452                      {
1453                         UTF16toUTF8Buffer(_wvolume, volume, MAX_FILENAME);
1454                         path[2] = '\0';
1455                         sprintf(name, "%s [%s]", path, volume);
1456                      }
1457                      else
1458                      {
1459                         path[2] = '\0';
1460                         strcpy(name, path);
1461                      }
1462                      result = this;
1463                      break;
1464                   }
1465                }
1466                break;
1467             }
1468             else if(d.name[0] != '\\' || d.name[1] != '\\' || strstr(d.name+2, "\\"))
1469             {
1470                WIN32_FIND_DATA winFile;
1471                if(FindNextFile(d.fHandle, &winFile))
1472                {
1473                   UTF16toUTF8Buffer(winFile.cFileName, name, MAX_FILENAME);
1474                   stats.attribs = FileAttribs { };
1475                   stats.attribs.isArchive   = (winFile.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE)   ? true : false;
1476                   stats.attribs.isHidden    = (winFile.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)    ? true : false;
1477                   stats.attribs.isReadOnly  = (winFile.dwFileAttributes & FILE_ATTRIBUTE_READONLY)  ? true : false;
1478                   stats.attribs.isSystem    = (winFile.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)    ? true : false;
1479                   stats.attribs.isTemporary = (winFile.dwFileAttributes & FILE_ATTRIBUTE_TEMPORARY) ? true : false;
1480                   stats.attribs.isDirectory = (winFile.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? true : false;
1481                   stats.size = winFile.nFileSizeLow;
1482
1483                   stats.accessed = Win32FileTimeToTimeStamp(&winFile.ftLastAccessTime);
1484                   stats.modified = Win32FileTimeToTimeStamp(&winFile.ftLastWriteTime);
1485                   stats.created  = Win32FileTimeToTimeStamp(&winFile.ftCreationTime);
1486
1487                   strcpy(path, d.name);
1488                   PathCat(path, name);
1489                   /*if(d.name[0])
1490                      strcat(path, DIR_SEPS);
1491                   strcat(path, name);*/
1492                   result = this;
1493                }
1494                else
1495                   break;
1496             }
1497             else
1498             {
1499                if(d.name[2])
1500                {
1501                   if(d.resource < d.numResources)
1502                   {
1503                      stats.attribs = FileAttribs { isDirectory = true, isShare = true };
1504                      stats.size = 0;
1505                      stats.accessed = stats.created = stats.modified = 0;
1506
1507                      UTF16toUTF8Buffer(d.resources[d.resource].lpRemoteName, path, MAX_LOCATION);
1508                      GetLastDirectory(path, name);
1509
1510                      result = this;
1511
1512                      d.resource++;
1513                   }
1514                   else
1515                   {
1516                      delete d.resources;
1517                      break;
1518                   }
1519                }
1520                else
1521                {
1522                   int c;
1523                   for(c = d.workGroup; c<d.numWorkGroups; c++)
1524                   {
1525                      if(c != d.workGroup)
1526                      {
1527                         int countInGroup = 0xFFFFFFFF;
1528                         HANDLE handle;
1529                         NETRESOURCE * resources;
1530                         uint size = 512 * sizeof(NETRESOURCE);
1531
1532                         resources = (NETRESOURCE *)new0 byte[size];
1533                         // Entire Network
1534                         WNetOpenEnum(RESOURCE_GLOBALNET, RESOURCETYPE_DISK, 0, &d.workGroups[c], &handle);
1535                         while(true)
1536                         {
1537                            int returnCode = WNetEnumResource(handle, &countInGroup, resources, &size);
1538                            if(returnCode != ERROR_MORE_DATA)
1539                               break;
1540                            countInGroup = 0xFFFFFFFF;
1541                            resources = (NETRESOURCE *)renew0 resources byte[size];
1542                            
1543                         }
1544                         WNetCloseEnum(handle);
1545                         d.numResources = countInGroup;
1546                         d.resources = resources;
1547                         d.resource = 0;
1548                      }
1549
1550                      if(d.resource < d.numResources)
1551                      {
1552                         stats.attribs = FileAttribs { isDirectory = true, isServer = true };
1553                         stats.size = 0;
1554                         stats.accessed = stats.created = stats.modified = 0;
1555
1556                         UTF16toUTF8Buffer(d.resources[d.resource].lpRemoteName, path, MAX_LOCATION);
1557                         strlwr(path);
1558                         path[2] = (char)toupper(path[2]);
1559                         GetLastDirectory(path, name);
1560
1561                         result = this;
1562
1563                         d.resource++;
1564                         break;
1565                      }
1566                      else
1567                      {
1568                         if(d.resources) 
1569                            delete d.resources;
1570                      }
1571                   }
1572                   d.workGroup = c;
1573                   if(d.workGroup == d.numWorkGroups && d.resource == d.numResources)
1574                   {
1575                      delete d.workGroups;
1576                      break;
1577                   }
1578                }
1579             }
1580 #else
1581             struct dirent *de;
1582             struct stat s;
1583
1584             de = readdir(d.d);
1585             if(de)
1586             {
1587                strcpy(name,de->d_name);
1588                strcpy(path, d.name);
1589                if(d.name[0] && d.name[0])
1590                   strcat(path, DIR_SEPS);
1591                strcat(path, name);
1592                stat(path, &s);
1593                stats.attribs = FileAttribs { };
1594                if(s.st_mode & S_IFDIR) stats.attribs.isDirectory = true;
1595                stats.size = s.st_size;
1596                stats.accessed = s.st_atime;
1597                stats.modified = s.st_mtime;
1598                stats.created = s.st_ctime;
1599                result = this;
1600             }
1601             else
1602                break;
1603 #endif
1604          }
1605       }
1606       if(!result)
1607          CloseDir();
1608       return result;
1609    }
1610
1611    void CloseDir(void)
1612    {
1613       if(system)
1614          system.CloseDir(this);
1615       else
1616       {
1617          Dir d = dir;
1618          if(d)
1619          {
1620 #if defined(__WIN32__)
1621             if(d.fHandle && strcmp(d.name, "/"))
1622                FindClose(d.fHandle);
1623 #else
1624             closedir(d.d);
1625 #endif
1626             delete d;
1627          }
1628       }
1629       delete this;
1630    }
1631 }
1632
1633 public struct FileListing
1634 {
1635 public:
1636    char * directory;
1637    char * extensions;
1638
1639    bool Find()
1640    {
1641       bool result = false;
1642       if(desc)
1643          desc = desc.FindNext(extensions);
1644       else
1645          desc = FileFind(directory, extensions);
1646       if(desc)
1647          return true;
1648       return false;
1649    }
1650
1651    void Stop()
1652    {
1653       if(desc)
1654          desc.CloseDir();
1655       desc = null;
1656    }
1657
1658    property char * name { get { return (char *)(desc ? desc.name : null); } };
1659    property char * path { get { return (char *)(desc ? desc.path : null); } };
1660    property FileStats stats { get { value = desc ? desc.stats : FileStats { }; } };
1661
1662 private:
1663    FileDesc desc;
1664 };
1665 #endif
1666
1667 public File CreateTemporaryFile(char * tempFileName, char * template)
1668 {
1669 #ifndef ECERE_BOOTSTRAP // quick fix for now
1670    File f;
1671 #if defined(__unix__) || defined(__APPLE__)
1672    char buffer[MAX_FILENAME];
1673    int fd;
1674    strcpy(buffer, "/tmp/");
1675    strcat(buffer, template);
1676    //strcpy(buffer, template);
1677    strcat(buffer, "XXXXXX");
1678    // mktemp(buffer);
1679    fd = mkstemp(buffer);   
1680    strcpy(tempFileName, buffer);
1681    f = { };
1682    f.output = f.input = fdopen(fd, "r+");
1683 #else
1684    char tempPath[MAX_LOCATION];
1685    GetTempPathA(MAX_LOCATION, tempPath);     // TODO: Patch this whole thing to support Unicode temp path
1686    GetTempFileNameA(tempPath, template, 0, tempFileName);
1687    f = FileOpen(tempFileName, readWrite);
1688 #endif   
1689    return f;
1690 #endif
1691 }
1692
1693 #undef DeleteFile
1694
1695 public void CreateTemporaryDir(char * tempFileName, char * template)
1696 {
1697 #ifndef ECERE_BOOTSTRAP // quick fix for now
1698 #if defined(__unix__) || defined(__APPLE__)
1699    char buffer[MAX_FILENAME];
1700    strcpy(buffer, "/tmp/");
1701    strcat(buffer, template);
1702    //strcpy(buffer, template);
1703    strcat(buffer, "XXXXXX");
1704    // mkstemp(buffer);
1705    mkdtemp(buffer);
1706    strcpy(tempFileName, buffer);
1707 #else
1708    char tempPath[MAX_LOCATION];
1709    GetTempPathA(MAX_LOCATION, tempPath);     // TODO: Patch this whole thing to support Unicode temp path
1710    GetTempFileNameA(tempPath, template, 0, tempFileName);
1711    DeleteFile(tempFileName);
1712    MakeDir(tempFileName);
1713 #endif
1714 #endif
1715 }