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