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