2a73e02ab68018407417d4d3a685aa5fd717ecfd
[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          {
663             result = false;
664             break;
665          }
666          if( (ch!='\n') && (ch!='\r') && (ch!=' ') && (ch!=',') && (ch!='\t'))
667             break;
668          if(Eof()) break;
669       }
670       if(result)
671       {
672          for(c=0; c<max-1; c++)
673          {
674             if(!quoted && ((ch=='\n')||(ch=='\r')||(ch==' ')||(ch==',')||(ch=='\t')))
675             {
676                result = true;
677                break;
678             }
679             if(ch == '\"')
680             {
681                quoted ^= 1;
682                c--;
683             }
684             else
685                string[c]=ch;
686
687             if(!Getc(&ch))
688             {
689                c++;
690                result = false;
691                break;
692             }
693          }
694          string[c]=0;
695       }
696       return result;
697    }
698
699    int GetValue(void)
700    {
701       char string[32];
702       GetString(string,sizeof(string));
703       return atoi(string);
704    }
705
706    unsigned int GetHexValue(void)
707    {
708       char string[32];
709       GetString(string, sizeof(string));
710       return (uint)strtoul(string, null, 16);
711    }
712
713    float GetFloat(void)
714    {
715       char string[32];
716       GetString(string, sizeof(string));
717       return (float)FloatFromString(string);
718    }
719
720    double GetDouble(void)
721    {
722       char string[32];
723       GetString(string, sizeof(string));
724       return FloatFromString(string);
725    }
726
727    property void * input { set { input = value; } get { return input; } }
728    property void * output { set { output = value; } get { return output; } }
729    property bool buffered
730    {
731       set
732       {
733          FILE_set_buffered(input, output, value);
734       }
735    }
736    property bool eof { get { return Eof(); } }
737
738    int GetLineEx(char *s, int max, bool *hasNewLineChar)
739    {
740       int c = 0;
741       s[c] = '\0';
742
743       if(!Eof())
744       {
745          char ch = '\0';
746          while(c < max - 1)
747          {
748             if(/*!Peek() || */ !Getc(&ch))
749                break;
750             if(ch == '\n')
751                break;
752             if(ch != '\r')
753                s[c++] = ch;
754          }
755          if(hasNewLineChar)
756             *hasNewLineChar = (ch == '\n');
757       }
758       s[c] = '\0';
759       return c;
760    }
761
762    bool CopyTo(const char * outputFileName)
763    {
764       bool result = false;
765       File f = FileOpen(outputFileName, write);
766       if(f)
767       {
768          byte buffer[65536];
769
770          result = true;
771          Seek(0, start);
772          while(!Eof())
773          {
774             uint count = Read(buffer, 1, sizeof(buffer));
775             if(count && !f.Write(buffer, 1, count))
776             {
777                result = false;
778                break;
779             }
780          }
781          delete f;
782       }
783       Seek(0, start);
784       return result;
785    }
786
787 #if 0
788    virtual bool Open(const char * fileName, FileOpenMode mode)
789    {
790       bool result = false;
791       if(this)
792       {
793          FILE_FileOpen(fileName, mode, &input, &output);
794
795          //file.mode = mode;
796          if(!input && !output);
797          else
798          {
799             openCount++;
800             result = true;
801             // TESTING ENABLING FILE BUFFERING BY DEFAULT... DOCUMENT ANY ISSUE
802             /*
803             if(file.input)
804                setvbuf(file.input, null, _IONBF, 0);
805             else
806                setvbuf(file.output, null, _IONBF, 0);
807             */
808          }
809          //if(!result)
810          {
811             /* TOFIX:
812             LogErrorCode((mode == Read || mode == ReadWrite) ?
813                ERR_FILE_NOT_FOUND : ERR_FILE_WRITE_FAILED, fileName);
814             */
815          }
816       }
817       return result;
818    }
819 #endif
820
821    virtual void Close()
822    {
823       CloseOutput();
824       CloseInput();
825    }
826 }
827
828 #if defined(__WIN32__)
829 default extern intptr_t stdinHandle;
830 default extern intptr_t stdoutHandle;
831 #endif
832
833 public class ConsoleFile : File
834 {
835    input = eC_stdin();
836    output = eC_stdout();
837
838 #if defined(__WIN32__)
839    void CloseInput()
840    {
841       CloseHandle((HANDLE)stdinHandle);
842    }
843    /*
844    void CloseOutput()
845    {
846       CloseHandle((HANDLE)stdoutHandle);
847    }*/
848 #endif
849
850    ~ConsoleFile()
851    {
852       input = null;
853       output = null;
854    }
855 };
856
857 public class FileAttribs : bool
858 {
859 public:
860    bool isFile:1, isArchive:1, isHidden:1, isReadOnly:1, isSystem:1, isTemporary:1, isDirectory:1;
861    bool isDrive:1, isCDROM:1, isRemote:1, isRemovable:1, isServer:1, isShare:1;
862    // property bool { };
863 };
864
865 #ifdef ECERE_BOOTSTRAP
866 public class SecSince1970 : int64;
867 #endif
868
869 public struct FileStats
870 {
871    FileAttribs attribs;
872    FileSize size;
873    SecSince1970 accessed;
874    SecSince1970 modified;
875    SecSince1970 created;
876 };
877
878 #if defined(__WIN32__)
879
880 // --- FileName functions ---
881
882 default TimeStamp Win32FileTimeToTimeStamp(FILETIME * fileTime)
883 {
884    // TIME_ZONE_INFORMATION tz = { 0 };
885    SYSTEMTIME st, lt;
886    DateTime t;
887
888    FileTimeToSystemTime(fileTime, &lt);
889
890    /*
891    GetTimeZoneInformation(&tz);
892    tz.Bias = 0;
893    _TzSpecificLocalTimeToSystemTime(&tz, &lt, &st);
894    */
895    st = lt;
896
897    t.year = st.wYear;
898    t.month = (Month)(st.wMonth - 1);
899    t.day = st.wDay;
900    t.hour = st.wHour;
901    t.minute = st.wMinute;
902    t.second = st.wSecond;
903    return t;
904 }
905
906 default void TimeStampToWin32FileTime(TimeStamp t, FILETIME * fileTime)
907 {
908    // TIME_ZONE_INFORMATION tz = { 0 };
909    SYSTEMTIME st, lt;
910    DateTime tm;
911
912    tm = t;
913
914    st.wYear = (short)tm.year;
915    st.wMonth = (short)(tm.month + 1);
916    st.wDay = (short)tm.day;
917    st.wHour = (short)tm.hour;
918    st.wMinute = (short)tm.minute;
919    st.wSecond = (short)tm.second;
920    st.wMilliseconds = 0;
921    st.wDayOfWeek = 0;
922
923    /*
924    GetTimeZoneInformation(&tz);
925    tz.Bias = 0;
926    SystemTimeToTzSpecificLocalTime(&tz, &st, &lt);
927    */
928
929    lt = st;
930    SystemTimeToFileTime(&lt, fileTime);
931 }
932 /*
933 default TimeStamp Win32FileTimeToTimeStamp(FILETIME * fileTime);
934 default void TimeStampToWin32FileTime(TimeStamp t, FILETIME * fileTime);
935 */
936 default bool WinReviveNetworkResource(uint16 * _wfileName);
937
938 #endif
939
940 public FileAttribs FileExists(const char * fileName)
941 {
942 #if !defined(ECERE_BOOTSTRAP)
943    char archiveName[MAX_LOCATION];
944    const char * archiveFile;
945    if(SplitArchivePath(fileName, archiveName, &archiveFile))
946    {
947       return EARFileSystem::Exists(archiveName, archiveFile);
948    }
949    else if(strstr(fileName, "http://") == fileName)
950    {
951       return FileAttribs { isFile = true };
952    }
953    else
954 #endif
955       return FILE_FileExists(fileName);
956 }
957
958 static int openCount;
959
960 public File FileOpen(const char * fileName, FileOpenMode mode)
961 {
962    File result = null;
963    if(fileName)
964    {
965 #if !defined(ECERE_BOOTSTRAP)
966       char archiveName[MAX_LOCATION];
967       const char * archiveFile;
968       if(SplitArchivePath(fileName, archiveName, &archiveFile))
969       {
970          result = EARFileSystem::Open(archiveName, archiveFile, mode);
971       }
972 #if !defined(ECERE_VANILLA) && !defined(ECERE_NONET)
973       else if(strstr(fileName, "http://") == fileName || strstr(fileName, "https://"))
974       {
975          result = FileOpenURL(fileName);
976       }
977 #endif
978       else
979 #endif
980       if(strstr(fileName, "File://") == fileName)
981       {
982          result = (File)(uintptr)strtoull(fileName+7, null, 16);
983          if(result)
984          {
985             if(result._class && eClass_IsDerived(result._class, class(File)))
986             {
987                if(!result._refCount) incref result;
988                incref result;
989                result.Seek(0, start);
990             }
991             else
992                result = null;
993          }
994       }
995       else
996       {
997          File file = File {};
998          if(file)
999          {
1000             FILE_FileOpen(fileName, mode, &file.input, &file.output);
1001
1002             //file.mode = mode;
1003             if(!file.input && !file.output);
1004             else
1005             {
1006                openCount++;
1007                result = file;
1008                // TESTING ENABLING FILE BUFFERING BY DEFAULT... DOCUMENT ANY ISSUE
1009                /*
1010                if(file.input)
1011                   setvbuf(file.input, null, _IONBF, 0);
1012                else
1013                   setvbuf(file.output, null, _IONBF, 0);
1014                */
1015             }
1016             if(!result)
1017             {
1018                delete file;
1019                /* TOFIX:
1020                LogErrorCode((mode == Read || mode == ReadWrite) ?
1021                   ERR_FILE_NOT_FOUND : ERR_FILE_WRITE_FAILED, fileName);
1022                */
1023             }
1024          }
1025       }
1026    }
1027    return result;
1028 }
1029
1030 public void FileFixCase(char * file)
1031 {
1032    FILE_FileFixCase(file);
1033 }
1034
1035 #if !defined(ECERE_BOOTSTRAP)
1036 public bool FileTruncate(const char * fileName, FileSize size)
1037 {
1038 #if defined(__WIN32__)
1039    uint16 * _wfileName = UTF8toUTF16(fileName, null);
1040    int f = _wopen(_wfileName, _O_RDWR|_O_CREAT, _S_IREAD|_S_IWRITE);
1041    bool result = false;
1042    if(f != -1)
1043    {
1044       if(!_chsize(f, size))
1045          result = true;
1046       _close(f);
1047    }
1048    delete _wfileName;
1049    return result;
1050 #else
1051    return truncate(fileName, size) == 0;
1052 #endif
1053 }
1054 #endif
1055
1056 public bool FileGetSize(const char * fileName, FileSize * size)
1057 {
1058    bool result = false;
1059    if(size)
1060    {
1061       *size = 0;
1062       if(fileName)
1063       {
1064 #if !defined(ECERE_BOOTSTRAP)
1065          char archiveName[MAX_LOCATION];
1066          const char * archiveFile;
1067          if(SplitArchivePath(fileName, archiveName, &archiveFile))
1068             return EARFileSystem::GetSize(archiveName, archiveFile, size);
1069          else
1070 #endif
1071             result = FILE_FileGetSize(fileName, size);
1072       }
1073    }
1074    return result;
1075 }
1076
1077 public bool FileGetStats(const char * fileName, FileStats stats)
1078 {
1079    bool result = false;
1080    if(stats && fileName)
1081    {
1082 #if !defined(ECERE_BOOTSTRAP)
1083       char archiveName[MAX_LOCATION];
1084       const char * archiveFile;
1085       if(SplitArchivePath(fileName, archiveName, &archiveFile))
1086          result = EARFileSystem::Stats(archiveName, archiveFile, stats);
1087       else
1088 #endif
1089          return FILE_FileGetStats(fileName, stats);
1090    }
1091    return result;
1092 }
1093
1094 #ifndef ECERE_BOOTSTRAP
1095
1096 public bool FileSetAttribs(const char * fileName, FileAttribs attribs)
1097 {
1098 #ifdef __WIN32__
1099    uint winAttribs = 0;
1100    uint16 * _wfileName = UTF8toUTF16(fileName, null);
1101
1102    if(attribs.isHidden)   winAttribs |= FILE_ATTRIBUTE_HIDDEN;
1103    if(attribs.isReadOnly) winAttribs |= FILE_ATTRIBUTE_READONLY;
1104
1105    SetFileAttributes(_wfileName, winAttribs);
1106    delete _wfileName;
1107 #endif
1108    return true;
1109 }
1110
1111 public bool FileSetTime(const char * fileName, TimeStamp created, TimeStamp accessed, TimeStamp modified)
1112 {
1113    bool result = false;
1114    TimeStamp currentTime = time(null);
1115    if(!created)  created = currentTime;
1116    if(!accessed) accessed = currentTime;
1117    if(!modified) modified = currentTime;
1118    if(fileName)
1119    {
1120 #ifdef __WIN32__
1121       uint16 * _wfileName = UTF8toUTF16(fileName, null);
1122       HANDLE hFile = CreateFile(_wfileName, GENERIC_WRITE|GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, null,
1123          OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, null);
1124       delete _wfileName;
1125       if(hFile != INVALID_HANDLE_VALUE)
1126       {
1127          FILETIME c, a, m;
1128
1129          TimeStampToWin32FileTime(created, &c);
1130          TimeStampToWin32FileTime(accessed, &a);
1131          TimeStampToWin32FileTime(modified, &m);
1132
1133          /*
1134          {
1135             uint cc,aa,mm;
1136
1137             cc = Win32FileTimeToTimeStamp(&c);
1138             aa = Win32FileTimeToTimeStamp(&a);
1139             mm = Win32FileTimeToTimeStamp(&m);
1140          }
1141          */
1142
1143          if(SetFileTime(hFile, &c, &a, &m))
1144             result = true;
1145
1146          CloseHandle(hFile);
1147       }
1148 #else
1149       struct utimbuf t = { (int)accessed, (int)modified };
1150       if(!utime(fileName, &t))
1151          result = true;
1152 #endif
1153    }
1154    return result;
1155 }
1156
1157 /****************************************************************************
1158  Directory Listing
1159 ****************************************************************************/
1160 // Directory Description for file listing
1161 private class Dir : struct
1162 {
1163 #if defined(__WIN32__)
1164    HANDLE fHandle;
1165
1166    int resource;
1167    NETRESOURCE * resources;
1168    int numResources;
1169
1170    int workGroup;
1171    NETRESOURCE * workGroups;
1172    int numWorkGroups;
1173 #else
1174    DIR * d;
1175 #endif
1176    char name[MAX_LOCATION];
1177 };
1178
1179 static FileDesc FileFind(const char * path, const char * extensions)
1180 {
1181    FileDesc result = null;
1182    FileDesc file;
1183
1184    if((file = FileDesc {}))
1185    {
1186       char archiveName[MAX_LOCATION];
1187       const char * archiveFile;
1188       if(SplitArchivePath(path, archiveName, &archiveFile))
1189       {
1190          if(EARFileSystem::Find(file, archiveName, archiveFile))
1191          {
1192             file.system = class(EARFileSystem);
1193             result = file;
1194          }
1195       }
1196       else
1197       {
1198          Dir d;
1199
1200          if((d = file.dir = Dir {}))
1201          {
1202 #if defined(__WIN32__)
1203             if(!strcmp(path, "/"))
1204             {
1205                int c;
1206                uint drives = 0xFFFFFFFF;
1207                d.fHandle = (HANDLE)(uintptr)drives; //GetLogicalDrives();
1208                for(c = 0; c<26; c++)
1209                   if(((uint)(uintptr)d.fHandle) & (1<<c))
1210                   {
1211                      char volume[MAX_FILENAME] = "";
1212                      uint16 _wvolume[MAX_FILENAME];
1213                      int driveType;
1214                      uint16 _wfilePath[4];
1215
1216                      strcpy(d.name, path);
1217                      file.stats.attribs = FileAttribs { isDirectory = true, isDrive = true };
1218                      _wfilePath[0] = file.path[0] = (char)('A' + c);
1219                      _wfilePath[1] = file.path[1] = ':';
1220                      _wfilePath[2] = file.path[2] = '\\';
1221                      _wfilePath[3] = file.path[3] = '\0';
1222                      file.stats.size = 0;
1223                      file.stats.accessed = file.stats.created = file.stats.modified = 0;
1224                      driveType = GetDriveType(_wfilePath);
1225                      switch(driveType)
1226                      {
1227                         case DRIVE_REMOVABLE: file.stats.attribs.isRemovable = true; break;
1228                         case DRIVE_REMOTE:    file.stats.attribs.isRemote = true; break;
1229                         case DRIVE_CDROM:     file.stats.attribs.isCDROM = true; break;
1230                      }
1231                      drives ^= (1<<c);
1232                      if(driveType == DRIVE_NO_ROOT_DIR) continue;
1233
1234                      if(driveType != DRIVE_REMOVABLE && driveType != DRIVE_REMOTE &&
1235                         GetVolumeInformation(_wfilePath, _wvolume, MAX_FILENAME - 1, null, null, null, null, 0))
1236                      {
1237                         file.path[2] = '\0';
1238                         UTF16toUTF8Buffer(_wvolume, volume, MAX_FILENAME);
1239                         sprintf(file.name, "%s [%s]", file.path, volume);
1240                      }
1241                      else
1242                      {
1243                         file.path[2] = '\0';
1244                         strcpy(file.name, file.path);
1245                      }
1246                      result = file;
1247                      break;
1248                   }
1249                d.fHandle = (HANDLE)(uintptr) drives;
1250                d.resource = 0;
1251             }
1252             else if(path[0] != '\\' || path[1] != '\\' || strstr(path+2, "\\"))
1253             {
1254                WIN32_FIND_DATA winFile;
1255                uint16 dir[MAX_PATH];
1256
1257                UTF8toUTF16Buffer(path, dir, MAX_LOCATION);
1258                if(path[0]) wcscat(dir, L"\\");
1259                wcscat(dir, L"*.*");
1260
1261                d.fHandle = FindFirstFile(dir, &winFile);
1262                if(d.fHandle == INVALID_HANDLE_VALUE && WinReviveNetworkResource(dir))
1263                   d.fHandle = FindFirstFile(dir, &winFile);
1264                if(d.fHandle != INVALID_HANDLE_VALUE)
1265                {
1266                   UTF16toUTF8Buffer(winFile.cFileName, file.name, MAX_FILENAME);
1267                   strcpy(file.path, path);
1268                   PathCat(file.path, file.name);
1269                   /*if(path[0])
1270                      strcat(file.path, DIR_SEPS);
1271                   strcat(file.path, file.name);*/
1272                   // file.sizeHigh = winFile.nFileSizeHigh;
1273                   file.stats.size = winFile.nFileSizeLow;
1274
1275                   file.stats.attribs = FileAttribs { };
1276                   file.stats.attribs.isArchive   = (winFile.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE)   ? true : false;
1277                   file.stats.attribs.isHidden    = (winFile.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)    ? true : false;
1278                   file.stats.attribs.isReadOnly  = (winFile.dwFileAttributes & FILE_ATTRIBUTE_READONLY)  ? true : false;
1279                   file.stats.attribs.isSystem    = (winFile.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)    ? true : false;
1280                   file.stats.attribs.isTemporary = (winFile.dwFileAttributes & FILE_ATTRIBUTE_TEMPORARY) ? true : false;
1281                   file.stats.attribs.isDirectory = (winFile.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? true : false;
1282                   file.stats.attribs.isFile = !(winFile.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
1283                   strcpy(d.name, path);
1284
1285                   file.stats.accessed = Win32FileTimeToTimeStamp(&winFile.ftLastAccessTime);
1286                   file.stats.modified = Win32FileTimeToTimeStamp(&winFile.ftLastWriteTime);
1287                   file.stats.created  = Win32FileTimeToTimeStamp(&winFile.ftCreationTime);
1288                   result = file;
1289                }
1290             }
1291             else
1292             {
1293                HANDLE handle = 0;
1294                DWORD count = 0xFFFFFFFF;
1295                DWORD size = 512 * sizeof(NETRESOURCE);
1296                NETRESOURCE * buffer = (NETRESOURCE *)new0 byte[size];
1297                NETRESOURCE nr = {0};
1298
1299                d.fHandle = null;
1300                nr.dwScope       = RESOURCE_GLOBALNET;
1301                nr.dwType        = RESOURCETYPE_DISK;
1302                nr.lpProvider = (uint16 *)L"Microsoft Windows Network";
1303
1304                strcpy(d.name, path);
1305                if(path[2])
1306                {
1307                   nr.lpRemoteName = UTF8toUTF16(path, null);
1308
1309                   // Server
1310                   WNetOpenEnum(RESOURCE_GLOBALNET, RESOURCETYPE_DISK, 0, &nr, &handle);
1311                   if(!handle)
1312                   {
1313                      WinReviveNetworkResource(nr.lpRemoteName);
1314                      WNetOpenEnum(RESOURCE_GLOBALNET, RESOURCETYPE_DISK, 0, &nr, &handle);
1315                   }
1316
1317                   if(handle)
1318                   {
1319                      while(true)
1320                      {
1321                         int returnCode = WNetEnumResource(handle, &count, buffer, &size);
1322                         if(returnCode != ERROR_MORE_DATA)
1323                            break;
1324                         count = 0xFFFFFFFF;
1325                         buffer = (NETRESOURCE *)renew0 buffer byte[size];
1326                      }
1327                      WNetCloseEnum(handle);
1328                   }
1329
1330                   delete nr.lpRemoteName;
1331                   if(count > 0)
1332                   {
1333                      file.stats.attribs = FileAttribs { isDirectory = true, isShare = true };
1334                      file.stats.size = 0;
1335                      file.stats.accessed = file.stats.created = file.stats.modified = 0;
1336
1337                      UTF16toUTF8Buffer(buffer->lpRemoteName, file.path, MAX_LOCATION);
1338                      GetLastDirectory(file.path, file.name);
1339
1340                      result = file;
1341                      d.resources = buffer;
1342                      d.numResources = count;
1343                      d.resource = 1;
1344                   }
1345                   else
1346                      delete buffer;
1347                }
1348                else
1349                {
1350                   int c;
1351                   nr.lpProvider = (uint16 *)L"Microsoft Windows Network";
1352
1353                   // Entire Network
1354                   WNetOpenEnum(RESOURCE_GLOBALNET, RESOURCETYPE_DISK, 0, &nr, &handle);
1355                   while(true)
1356                   {
1357                      int returnCode = WNetEnumResource(handle, &count, buffer, &size);
1358                      if(returnCode != ERROR_MORE_DATA)
1359                         break;
1360                      count = 0xFFFFFFFF;
1361                      buffer = (NETRESOURCE *)renew0 buffer byte[size];
1362                   }
1363                   WNetCloseEnum(handle);
1364
1365                   for(c = 0; c<count; c++)
1366                   {
1367                      NETRESOURCE * resources;
1368                      DWORD countInGroup = 0xFFFFFFFF;
1369
1370                      size = 512 * sizeof(NETRESOURCE);
1371                      resources = (NETRESOURCE *)new0 byte[size];
1372
1373                      // Entire Network
1374                      WNetOpenEnum(RESOURCE_GLOBALNET, RESOURCETYPE_DISK, 0, &buffer[c], &handle);
1375                      while(true)
1376                      {
1377                         int returnCode = WNetEnumResource(handle, &countInGroup, resources, &size);
1378                         if(returnCode != ERROR_MORE_DATA)
1379                            break;
1380                         countInGroup = 0xFFFFFFFF;
1381                         resources = (NETRESOURCE *)renew0 resources byte[size];
1382                      }
1383                      WNetCloseEnum(handle);
1384
1385                      if(countInGroup)
1386                      {
1387                         file.stats.attribs = FileAttribs { isDirectory = true, isServer = true };
1388                         file.stats.size = 0;
1389                         file.stats.accessed = file.stats.created = file.stats.modified = 0;
1390
1391                         UTF16toUTF8Buffer(resources->lpRemoteName, file.path, MAX_LOCATION);
1392                         strlwr(file.path);
1393                         file.path[2] = (char)toupper(file.path[2]);
1394                         GetLastDirectory(file.path, file.name);
1395
1396                         result = file;
1397
1398                         d.resources = resources;
1399                         d.numResources = countInGroup;
1400                         d.resource = 1;
1401
1402                         d.workGroups = buffer;
1403                         d.numWorkGroups = count;
1404                         d.workGroup = c;
1405                         break;
1406                      }
1407                      else
1408                         delete resources;
1409                   }
1410                   if(c >= count && buffer) delete buffer;
1411                }
1412             }
1413 #else
1414             struct dirent *de;
1415             struct stat s;
1416
1417             d.d = opendir((path && path[0]) ? path : ".");
1418             if(d.d && (de = readdir(d.d)))
1419             {
1420                if(path[0])
1421                {
1422                   strcpy(file.path, path);
1423                   if(path[1])
1424                      strcat(file.path, DIR_SEPS);
1425                }
1426                strcpy(file.name,de->d_name);
1427                strcat(file.path, file.name);
1428                if(!stat(file.path, &s))
1429                {
1430                   file.stats.attribs = (s.st_mode&S_IFDIR) ? FileAttribs { isDirectory = true } : FileAttribs { isFile = true };
1431                   file.stats.size = (FileSize)s.st_size;
1432                   file.stats.accessed = s.st_atime;
1433                   file.stats.modified = s.st_mtime;
1434                   file.stats.created = s.st_ctime;
1435                }
1436                strcpy(d.name, path);
1437
1438                result = file;
1439             }
1440 #endif
1441          }
1442
1443          if(!result)
1444             delete d;
1445       }
1446       if(!result)
1447          delete file;
1448    }
1449    if(result)
1450    {
1451       while(result && !result.Validate(extensions))
1452          result = result.FindNext(extensions);
1453    }
1454    return result;
1455 }
1456
1457 private class FileDesc : struct
1458 {
1459    FileStats stats;
1460    char name[MAX_FILENAME];
1461    char path[MAX_LOCATION];
1462
1463    subclass(FileSystem) system;
1464    Dir dir;
1465
1466    bool Validate(const char * extensions)
1467    {
1468       if(strcmp(name, "..") && strcmp(name, ".") && strcmp(name, ""))
1469       {
1470          if(extensions && !stats.attribs.isDirectory)
1471          {
1472             char extension[MAX_EXTENSION], compared[MAX_EXTENSION];
1473             int c;
1474
1475             GetExtension(name, extension);
1476             for(c = 0; extensions[c];)
1477             {
1478                int len = 0;
1479                char ch;
1480                for(;(ch = extensions[c]) && !IS_ALUNDER(ch); c++);
1481                for(;(ch = extensions[c]) &&  IS_ALUNDER(ch); c++)
1482                   compared[len++] = ch;
1483                compared[len] = '\0';
1484
1485                if(!strcmpi(extension, compared))
1486                   return true;
1487             }
1488          }
1489          else
1490             return true;
1491       }
1492       return false;
1493    }
1494
1495    FileDesc FindNext(const char * extensions)
1496    {
1497       FileDesc result = null;
1498
1499       Dir d = dir;
1500
1501       name[0] = '.';
1502       name[1] = '\0';
1503       while(!Validate(extensions))
1504       {
1505          result = null;
1506
1507          if(system)
1508          {
1509             if(system.FindNext(this))
1510                result = this;
1511             else
1512                break;
1513          }
1514          else
1515          {
1516 #if defined(__WIN32__)
1517             if(!strcmp(d.name, "/"))
1518             {
1519                int c;
1520                uint drives = (uint)(uintptr)d.fHandle;
1521                for(c = 0; c<26; c++)
1522                {
1523                   if(drives & (1<<c))
1524                   {
1525                      char volume[MAX_FILENAME] = "";
1526                      int driveType;
1527                      uint16 _wpath[4];
1528                      uint16 _wvolume[MAX_FILENAME];
1529
1530                      stats.attribs = FileAttribs { isDirectory = true, isDrive = true };
1531                      stats.size = 0;
1532                      stats.accessed = stats.created = stats.modified = 0;
1533                      _wpath[0] = path[0] = (char)('A' + c);
1534                      _wpath[1] = path[1] = ':';
1535                      _wpath[2] = path[2] = '\\';
1536                      _wpath[3] = path[3] = 0;
1537                      driveType = GetDriveType(_wpath);
1538                      drives ^= (1<<c);
1539
1540                      switch(driveType)
1541                      {
1542                         case DRIVE_REMOVABLE: stats.attribs.isRemovable = true; break;
1543                         case DRIVE_REMOTE:    stats.attribs.isRemote = true;    break;
1544                         case DRIVE_CDROM:     stats.attribs.isCDROM = true;     break;
1545                      }
1546                      if(driveType == DRIVE_NO_ROOT_DIR)
1547                      {
1548                         uint16 remoteName[1024];
1549                         int status;
1550                         DWORD size = 1024;
1551                         _wpath[2] = 0;
1552
1553                         status = WNetGetConnection(_wpath, remoteName, &size);
1554                         if(status != ERROR_CONNECTION_UNAVAIL)
1555                            continue;
1556
1557                         _wpath[2] = '\\';
1558                         _wpath[3] = 0;
1559                      }
1560
1561                      if(driveType != DRIVE_REMOVABLE && driveType != DRIVE_REMOTE &&
1562                         GetVolumeInformation(_wpath, _wvolume, MAX_FILENAME - 1, null, null, null, null, 0))
1563                      {
1564                         UTF16toUTF8Buffer(_wvolume, volume, MAX_FILENAME);
1565                         path[2] = '\0';
1566                         sprintf(name, "%s [%s]", path, volume);
1567                      }
1568                      else
1569                      {
1570                         path[2] = '\0';
1571                         strcpy(name, path);
1572                      }
1573                      result = this;
1574                      break;
1575                   }
1576                }
1577                d.fHandle = (HANDLE)(uintptr) drives;
1578                break;
1579             }
1580             else if(d.name[0] != '\\' || d.name[1] != '\\' || strstr(d.name+2, "\\"))
1581             {
1582                WIN32_FIND_DATA winFile;
1583                if(FindNextFile(d.fHandle, &winFile))
1584                {
1585                   UTF16toUTF8Buffer(winFile.cFileName, name, MAX_FILENAME);
1586                   stats.attribs = FileAttribs { };
1587                   stats.attribs.isArchive   = (winFile.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE)   ? true : false;
1588                   stats.attribs.isHidden    = (winFile.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)    ? true : false;
1589                   stats.attribs.isReadOnly  = (winFile.dwFileAttributes & FILE_ATTRIBUTE_READONLY)  ? true : false;
1590                   stats.attribs.isSystem    = (winFile.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)    ? true : false;
1591                   stats.attribs.isTemporary = (winFile.dwFileAttributes & FILE_ATTRIBUTE_TEMPORARY) ? true : false;
1592                   stats.attribs.isDirectory = (winFile.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? true : false;
1593                   stats.attribs.isFile      = !(winFile.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
1594                   stats.size = winFile.nFileSizeLow;
1595
1596                   stats.accessed = Win32FileTimeToTimeStamp(&winFile.ftLastAccessTime);
1597                   stats.modified = Win32FileTimeToTimeStamp(&winFile.ftLastWriteTime);
1598                   stats.created  = Win32FileTimeToTimeStamp(&winFile.ftCreationTime);
1599
1600                   strcpy(path, d.name);
1601                   PathCat(path, name);
1602                   /*if(d.name[0])
1603                      strcat(path, DIR_SEPS);
1604                   strcat(path, name);*/
1605                   result = this;
1606                }
1607                else
1608                   break;
1609             }
1610             else
1611             {
1612                if(d.name[2])
1613                {
1614                   if(d.resource < d.numResources)
1615                   {
1616                      stats.attribs = FileAttribs { isDirectory = true, isShare = true };
1617                      stats.size = 0;
1618                      stats.accessed = stats.created = stats.modified = 0;
1619
1620                      UTF16toUTF8Buffer(d.resources[d.resource].lpRemoteName, path, MAX_LOCATION);
1621                      GetLastDirectory(path, name);
1622
1623                      result = this;
1624
1625                      d.resource++;
1626                   }
1627                   else
1628                   {
1629                      delete d.resources;
1630                      break;
1631                   }
1632                }
1633                else
1634                {
1635                   int c;
1636                   for(c = d.workGroup; c<d.numWorkGroups; c++)
1637                   {
1638                      if(c != d.workGroup)
1639                      {
1640                         DWORD countInGroup = 0xFFFFFFFF;
1641                         HANDLE handle;
1642                         NETRESOURCE * resources;
1643                         DWORD size = 512 * sizeof(NETRESOURCE);
1644
1645                         resources = (NETRESOURCE *)new0 byte[size];
1646                         // Entire Network
1647                         WNetOpenEnum(RESOURCE_GLOBALNET, RESOURCETYPE_DISK, 0, &d.workGroups[c], &handle);
1648                         while(true)
1649                         {
1650                            int returnCode = WNetEnumResource(handle, &countInGroup, resources, &size);
1651                            if(returnCode != ERROR_MORE_DATA)
1652                               break;
1653                            countInGroup = 0xFFFFFFFF;
1654                            resources = (NETRESOURCE *)renew0 resources byte[size];
1655
1656                         }
1657                         WNetCloseEnum(handle);
1658                         d.numResources = countInGroup;
1659                         d.resources = resources;
1660                         d.resource = 0;
1661                      }
1662
1663                      if(d.resource < d.numResources)
1664                      {
1665                         stats.attribs = FileAttribs { isDirectory = true, isServer = true };
1666                         stats.size = 0;
1667                         stats.accessed = stats.created = stats.modified = 0;
1668
1669                         UTF16toUTF8Buffer(d.resources[d.resource].lpRemoteName, path, MAX_LOCATION);
1670                         strlwr(path);
1671                         path[2] = (char)toupper(path[2]);
1672                         GetLastDirectory(path, name);
1673
1674                         result = this;
1675
1676                         d.resource++;
1677                         break;
1678                      }
1679                      else
1680                      {
1681                         if(d.resources)
1682                            delete d.resources;
1683                      }
1684                   }
1685                   d.workGroup = c;
1686                   if(d.workGroup == d.numWorkGroups && d.resource == d.numResources)
1687                   {
1688                      delete d.workGroups;
1689                      break;
1690                   }
1691                }
1692             }
1693 #else
1694             struct dirent *de;
1695             struct stat s;
1696
1697             de = readdir(d.d);
1698             if(de)
1699             {
1700                strcpy(name,de->d_name);
1701                strcpy(path, d.name);
1702                if(d.name[0] && d.name[1])
1703                   strcat(path, DIR_SEPS);
1704                strcat(path, name);
1705                if(!stat(path, &s))
1706                {
1707                   stats.attribs = FileAttribs { };
1708                   stats.attribs = (s.st_mode&S_IFDIR) ? FileAttribs { isDirectory = true } : FileAttribs { isFile = true };
1709                   stats.size = (FileSize)s.st_size;
1710                   stats.accessed = s.st_atime;
1711                   stats.modified = s.st_mtime;
1712                   stats.created = s.st_ctime;
1713                }
1714                result = this;
1715             }
1716             else
1717                break;
1718 #endif
1719          }
1720       }
1721       if(!result)
1722          CloseDir();
1723       return result;
1724    }
1725
1726    void CloseDir(void)
1727    {
1728       if(system)
1729          system.CloseDir(this);
1730       else
1731       {
1732          Dir d = dir;
1733          if(d)
1734          {
1735 #if defined(__WIN32__)
1736             if(d.fHandle && strcmp(d.name, "/"))
1737                FindClose(d.fHandle);
1738 #else
1739             closedir(d.d);
1740 #endif
1741             delete d;
1742          }
1743       }
1744       delete this;
1745    }
1746 }
1747
1748 public struct FileListing
1749 {
1750 public:
1751    const char * directory;
1752    const char * extensions;
1753
1754    bool Find()
1755    {
1756       if(desc)
1757          desc = desc.FindNext(extensions);
1758       else
1759          desc = FileFind(directory, extensions);
1760       if(desc)
1761          return true;
1762       return false;
1763    }
1764
1765    void Stop()
1766    {
1767       if(desc)
1768          desc.CloseDir();
1769       desc = null;
1770    }
1771
1772    property const char * name { get { return desc ? desc.name : null; } };
1773    property const char * path { get { return desc ? desc.path : null; } };
1774    property FileStats stats { get { value = desc ? desc.stats : FileStats { }; } };
1775
1776 private:
1777    FileDesc desc;
1778 };
1779 #endif
1780
1781 public File CreateTemporaryFile(char * tempFileName, const char * template)
1782 {
1783 #ifndef ECERE_BOOTSTRAP // quick fix for now
1784    File f;
1785 #if defined(__unix__) || defined(__APPLE__)
1786    char buffer[MAX_FILENAME];
1787    int fd;
1788    strcpy(buffer, "/tmp/");
1789    strcat(buffer, template);
1790    //strcpy(buffer, template);
1791    strcat(buffer, "XXXXXX");
1792    // mktemp(buffer);
1793    fd = mkstemp(buffer);
1794    strcpy(tempFileName, buffer);
1795    f = { };
1796    f.output = f.input = fdopen(fd, "r+");
1797 #else
1798    char tempPath[MAX_LOCATION];
1799    GetTempPathA(MAX_LOCATION, tempPath);     // TODO: Patch this whole thing to support Unicode temp path
1800    GetTempFileNameA(tempPath, template, 0, tempFileName);
1801    f = FileOpen(tempFileName, readWrite);
1802 #endif
1803    return f;
1804 #else
1805    return null;
1806 #endif
1807 }
1808
1809 #undef DeleteFile
1810
1811 public void CreateTemporaryDir(char * tempFileName, const char * template)
1812 {
1813 #ifndef ECERE_BOOTSTRAP // quick fix for now
1814 #if defined(__unix__) || defined(__APPLE__)
1815    char buffer[MAX_FILENAME];
1816    strcpy(buffer, "/tmp/");
1817    strcat(buffer, template);
1818    //strcpy(buffer, template);
1819    strcat(buffer, "XXXXXX");
1820    // mkstemp(buffer);
1821    mkdtemp(buffer);
1822    strcpy(tempFileName, buffer);
1823 #else
1824    char tempPath[MAX_LOCATION];
1825    GetTempPathA(MAX_LOCATION, tempPath);     // TODO: Patch this whole thing to support Unicode temp path
1826    GetTempFileNameA(tempPath, template, 0, tempFileName);
1827    DeleteFile(tempFileName);
1828    MakeDir(tempFileName);
1829 #endif
1830 #endif
1831 }
1832
1833 public void MakeSlashPath(char * p)
1834 {
1835    FileFixCase(p);
1836    if(__runtimePlatform == win32)
1837       ChangeCh(p, '\\', '/');
1838 }
1839
1840 public void MakeSystemPath(char * p)
1841 {
1842    FileFixCase(p);
1843 }
1844
1845 public char * CopySystemPath(const char * p)
1846 {
1847    char * d = CopyString(p);
1848    if(d)
1849       MakeSystemPath(d);
1850    return d;
1851 }
1852
1853 public char * CopyUnixPath(const char * p)
1854 {
1855    char * d = CopyString(p);
1856    if(d)
1857       MakeSlashPath(d);
1858    return d;
1859 }
1860
1861 public char * GetSystemPathBuffer(char * d, const char * p)
1862 {
1863    if(d != p)
1864       strcpy(d, p ? p : "");
1865    MakeSystemPath(d);
1866    return d;
1867 }
1868
1869 public char * GetSlashPathBuffer(char * d, const char * p)
1870 {
1871    if(d != p)
1872       strcpy(d, p ? p : "");
1873    MakeSlashPath(d);
1874    return d;
1875 }