486a3b269fb57766978a9a82961868e1b163d678
[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 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(char * fileName);
96 bool FILE_FileGetSize(char * fileName, FileSize * size);
97 bool FILE_FileGetStats(char * fileName, FileStats stats);
98 void FILE_FileFixCase(char * file);
99 void FILE_FileOpen(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    char * OnGetString(char * string, void * fieldData, bool * needClass)
132    {
133       PrintSize(string, this, 2);
134       return string;
135    }
136
137    bool OnGetDataFromString(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    char * OnGetString(char * string, void * fieldData, bool * needClass)
167    {
168       PrintBigSize(string, this, 2);
169       return string;
170    }
171
172    bool OnGetDataFromString(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(char * archive, char * name, FileOpenMode mode);
191
192    // Query on names
193    virtual FileAttribs ::Exists(char * archive, char * fileName);
194    virtual bool ::GetSize(char * archive, char * fileName, FileSize * size);
195    virtual bool ::Stats(char * archive, char * fileName, FileStats stats);
196    virtual void ::FixCase(char * archive, char * fileName);
197
198    // File Listing
199    virtual bool ::Find(FileDesc file, char * archive, char * name);
200    virtual bool ::FindNext(FileDesc file);
201    virtual void ::CloseDir(FileDesc file);
202
203    // Archive manipulation
204    virtual Archive ::OpenArchive(char * fileName, ArchiveOpenFlags create);
205    virtual bool ::QuerySize(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(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(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    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                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                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                uint 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, 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       uint size, cSize;
405
406       this = null;
407
408       size.OnUnserialize(channel);
409       if(size != MAXDWORD)
410       {
411          byte * compressed;
412          cSize.OnUnserialize(channel);
413
414          compressed = new byte[cSize];
415          if(compressed)
416          {
417             if(channel.ReadData(compressed, cSize) == cSize)
418             {
419                byte * uncompressed = new byte[size];
420                if(uncompressed || !size)
421                {
422                   this = TempFile { };
423                   uncompress(uncompressed, &size, compressed, cSize);
424                   Write(uncompressed, 1, size);
425                   Seek(0, start);
426
427                   delete uncompressed;
428                }
429             }
430             delete compressed;
431          }
432       }
433
434       /*
435       byte data[4096];
436       uint c;
437
438       size.OnUnserialize(channel);
439       if(size != MAXDWORD)
440       {
441          this = TempFile { };
442          for(c = 0; c<size; c += sizeof(data))
443          {
444             uint count = Min(size - c, sizeof(data));
445             channel.ReadData(data, count);
446             Write(data, 1, count);
447          }
448          Seek(0, start);
449       }
450       else
451          this = null;
452       */
453    }
454 #endif
455
456 public:
457
458    // Virtual Methods
459    virtual bool Seek(int pos, FileSeekMode mode)
460    {
461       uint fmode = SEEK_SET;
462       switch(mode)
463       {
464          case start: fmode = SEEK_SET; break;
465          case end: fmode = SEEK_END; break;
466          case current: fmode = SEEK_CUR; break;
467       }
468       return fseek(input ? input : output, pos, fmode) != EOF;
469    }
470
471    virtual uint Tell(void)
472    {
473       return (uint)(input ? ftell(input) : ftell(output));
474    }
475
476    virtual int Read(void * buffer, uint size, uint count)
477    {
478       return input ? (int)fread(buffer, size, count, input) : 0;
479    }
480
481    virtual int Write(void * buffer, uint size, uint count)
482    {
483       return output ? (int)fwrite(buffer, size, count, output) : 0;
484    }
485
486    // UNICODE OR NOT?
487    virtual bool Getc(char * ch)
488    {
489       int ich = fgetc(input);
490       if(ich != EOF)
491       {
492          if(ch) *ch = (char)ich;
493          return true;
494       }
495       return false;
496    }
497
498    virtual bool Putc(char ch)
499    {
500       return (fputc((int)ch, output) == EOF) ? false : true;
501    }
502
503    virtual bool Puts(const char * string)
504    {
505       bool result = false;
506       if(output)
507       {
508          result = (fputs(string, output) == EOF) ? false : true;
509          // TODO: Check if any repercusions of commenting out fflush here
510          // This is what broke the debugger in 0.44d2 , it is required for outputting things to the DualPipe
511          // Added an explicit flush call in DualPipe::Puts
512          // fflush(output);
513       }
514       return result;
515    }
516
517    virtual bool Eof(void)
518    {
519       return input ? feof(input) : true;
520    }
521    
522    virtual bool Truncate(FileSize size)
523    {
524    #ifdef ECERE_BOOTSTRAP
525       fprintf(stderr, "WARNING:  File::Truncate unimplemented in ecereBootstrap.\n");
526       return false;
527    #else
528    #if defined(__WIN32__)
529       return output ? (_chsize(fileno(output), size) == 0) : false;
530    #else
531       return output ? (ftruncate(fileno(output), size) == 0) : false;
532    #endif   
533    #endif
534    }
535
536    virtual uint GetSize(void)
537    {
538       return FILE_GetSize(input);
539    }
540    
541    virtual void CloseInput(void)
542    {
543       if(input)
544       {
545          fclose(input);
546          if(output == input)
547             output = null;
548          input = null;
549       }
550    }
551
552    virtual void CloseOutput(void)
553    {
554       if(output)
555       {
556          fclose(output);
557          if(input == output)
558             input = null;
559          output = null;
560       }
561    }
562
563    virtual bool Lock(FileLock type, uint64 start, uint64 length, bool wait)
564    {
565       return FILE_Lock(input, output, type, start, length, wait);
566    }
567
568    virtual bool Unlock(uint64 start, uint64 length, bool wait)
569    {
570       return Lock(unlocked, start, length, wait);
571    }
572
573    // Normal Methods
574    int Printf(char * format, ...)
575    {
576       int result = 0;
577       if(format)
578       {
579          char text[MAX_F_STRING];
580          va_list args;
581          va_start(args, format);
582          vsnprintf(text, sizeof(text), format, args);
583          text[sizeof(text)-1] = 0;
584          if(Puts(text))
585             result = strlen(text);
586          va_end(args);
587       }
588       return result;
589    }
590
591    public void PrintLn(typed_object object, ...)
592    {
593       va_list args;
594       char buffer[4096];
595       va_start(args, object);
596       PrintStdArgsToBuffer(buffer, sizeof(buffer), object, args);
597       Puts(buffer);
598       Putc('\n');
599       va_end(args);
600    }
601
602    public void Print(typed_object object, ...)
603    {
604       va_list args;
605       char buffer[4096];
606       va_start(args, object);
607       PrintStdArgsToBuffer(buffer, sizeof(buffer), object, args);
608       Puts(buffer);
609       va_end(args);
610    }
611
612    bool Flush(void)
613    {
614       fflush(output);
615       return true;
616    }
617
618    bool GetLine(char *s, int max)
619    {
620       int c = 0;
621       bool result = true;
622       s[c]=0;
623
624       if(Eof())
625       {
626          result = false;
627       }
628       else
629       {
630          while(c<max-1)
631          {
632             char ch = 0;
633          
634             if(/*!Peek() || */ !Getc(&ch))
635             {
636                result = false;
637                break;
638             }
639             if(ch =='\n') 
640                break;
641             if(ch !='\r')
642                s[c++]=ch;
643          }
644       }
645       s[c]=0;
646       return result || c > 1;
647    }
648
649    // Strings and numbers separated by spaces, commas, tabs, or CR/LF, handling quotes
650    bool GetString(char * string, int max)
651    {
652       int c;
653       char ch;
654       bool quoted = false;
655       bool result = true;
656
657       *string = 0;
658       while(true)
659       {
660          if(!Getc(&ch))
661             result = false;
662          if( (ch!='\n') && (ch!='\r') && (ch!=' ') && (ch!=',') && (ch!='\t'))
663             break;
664          if(Eof()) break;
665       }
666       if(result)
667       {
668          for(c=0; c<max-1; c++)
669          {
670             if(!quoted && ((ch=='\n')||(ch=='\r')||(ch==' ')||(ch==',')||(ch=='\t')))
671             {
672                result = true;
673                break;
674             }
675             if(ch == '\"')
676             {
677                quoted ^= 1;
678                c--;
679             }
680             else
681                string[c]=ch;
682
683             if(!Getc(&ch)) 
684             {
685                c++;
686                result = false;
687                break;            
688             }
689          }
690          string[c]=0;
691       }
692       return result;
693    }
694
695    int GetValue(void)
696    {
697       char string[32];
698       GetString(string,sizeof(string));
699       return atoi(string);
700    }
701
702    unsigned int GetHexValue(void)
703    {
704       char string[32];
705       GetString(string, sizeof(string));
706       return (uint)strtoul(string, null, 16);
707    }
708
709    float GetFloat(void)
710    {
711       char string[32];
712       GetString(string, sizeof(string));
713       return (float)FloatFromString(string);
714    }
715
716    double GetDouble(void)
717    {
718       char string[32];
719       GetString(string, sizeof(string));
720       return FloatFromString(string);
721    }
722
723    property void * input { set { input = value; } get { return input; } }
724    property void * output { set { output = value; } get { return output; } }
725    property bool buffered
726    {
727       set
728       {
729          FILE_set_buffered(input, output, value);
730       }      
731    }
732    property bool eof { get { return Eof(); } }
733
734    int GetLineEx(char *s, int max, bool *hasNewLineChar)
735    {
736       int c = 0;
737       s[c] = '\0';
738
739       if(!Eof())
740       {
741          char ch = '\0';
742          while(c < max - 1)
743          {
744             if(/*!Peek() || */ !Getc(&ch))
745                break;
746             if(ch == '\n')
747                break;
748             if(ch != '\r')
749                s[c++] = ch;
750          }
751          if(hasNewLineChar)
752             *hasNewLineChar = (ch == '\n');
753       }
754       s[c] = '\0';
755       return c;
756    }
757
758    bool CopyTo(char * outputFileName)
759    {
760       bool result = false;
761       File f = FileOpen(outputFileName, write);
762       if(f)
763       {
764          byte buffer[65536];
765
766          result = true;
767          Seek(0, start);
768          while(!Eof())
769          {
770             uint count = Read(buffer, 1, sizeof(buffer));
771             if(count && !f.Write(buffer, 1, count))
772             {
773                result = false;
774                break;
775             }
776          }
777          delete f;
778       }
779       Seek(0, start);
780       return result;
781    }
782
783 #if 0
784    virtual bool Open(char * fileName, FileOpenMode mode)
785    {
786       bool result = false;
787       if(this)
788       {
789          FILE_FileOpen(fileName, mode, &input, &output);
790
791          //file.mode = mode;
792          if(!input && !output);
793          else
794          {
795             openCount++;
796             result = true;
797             // TESTING ENABLING FILE BUFFERING BY DEFAULT... DOCUMENT ANY ISSUE
798             /*
799             if(file.input)
800                setvbuf(file.input, null, _IONBF, 0);
801             else
802                setvbuf(file.output, null, _IONBF, 0);
803             */
804          }
805          //if(!result)
806          {
807             /* TOFIX:
808             LogErrorCode((mode == Read || mode == ReadWrite) ? 
809                ERR_FILE_NOT_FOUND : ERR_FILE_WRITE_FAILED, fileName);
810             */
811          }
812       }
813       return result;
814    }
815 #endif
816
817    virtual void Close()
818    {
819       CloseOutput();
820       CloseInput();
821    }
822 }
823
824 #if defined(__WIN32__)
825 default extern intptr_t stdinHandle;
826 default extern intptr_t stdoutHandle;
827 #endif
828
829 public class ConsoleFile : File
830 {
831    input = eC_stdin();
832    output = eC_stdout();
833
834 #if defined(__WIN32__)
835    void CloseInput()
836    {
837       CloseHandle((HANDLE)stdinHandle);
838    }
839    /*
840    void CloseOutput()
841    {
842       CloseHandle((HANDLE)stdoutHandle);
843    }*/
844 #endif
845
846    ~ConsoleFile()
847    {
848       input = null;
849       output = null;
850    }
851 };
852
853 public class FileAttribs : bool
854 {
855 public:
856    bool isFile:1, isArchive:1, isHidden:1, isReadOnly:1, isSystem:1, isTemporary:1, isDirectory:1;
857    bool isDrive:1, isCDROM:1, isRemote:1, isRemovable:1, isServer:1, isShare:1;
858    // property bool { };
859 };
860
861 public struct FileStats
862 {
863    FileAttribs attribs;
864    FileSize size;
865    SecSince1970 accessed;
866    SecSince1970 modified;
867    SecSince1970 created;
868 };
869
870 #if defined(__WIN32__)
871
872 // --- FileName functions ---
873
874 default TimeStamp Win32FileTimeToTimeStamp(FILETIME * fileTime)
875 {
876    // TIME_ZONE_INFORMATION tz = { 0 };
877    SYSTEMTIME st, lt;
878    DateTime t;
879
880    FileTimeToSystemTime(fileTime, &lt);
881
882    /*
883    GetTimeZoneInformation(&tz);
884    tz.Bias = 0;
885    _TzSpecificLocalTimeToSystemTime(&tz, &lt, &st);
886    */
887    st = lt;
888
889    t.year = st.wYear;
890    t.month = (Month)(st.wMonth - 1);
891    t.day = st.wDay;
892    t.hour = st.wHour;
893    t.minute = st.wMinute;
894    t.second = st.wSecond;
895    return t;
896 }
897
898 default void TimeStampToWin32FileTime(TimeStamp t, FILETIME * fileTime)
899 {
900    // TIME_ZONE_INFORMATION tz = { 0 };
901    SYSTEMTIME st, lt;
902    DateTime tm;
903    
904    tm = t;
905
906    st.wYear = (short)tm.year;
907    st.wMonth = (short)tm.month + 1;
908    st.wDay = (short)tm.day;
909    st.wHour = (short)tm.hour;
910    st.wMinute = (short)tm.minute;
911    st.wSecond = (short)tm.second;
912    st.wMilliseconds = 0;
913    st.wDayOfWeek = 0;
914
915    /*
916    GetTimeZoneInformation(&tz);
917    tz.Bias = 0;
918    SystemTimeToTzSpecificLocalTime(&tz, &st, &lt);
919    */
920
921    lt = st;
922    SystemTimeToFileTime(&lt, fileTime);
923 }
924 /*
925 default TimeStamp Win32FileTimeToTimeStamp(FILETIME * fileTime);
926 default void TimeStampToWin32FileTime(TimeStamp t, FILETIME * fileTime);
927 */
928 default bool WinReviveNetworkResource(uint16 * _wfileName);
929
930 #endif
931
932 public FileAttribs FileExists(char * fileName)
933 {
934    char archiveName[MAX_LOCATION], * archiveFile;
935 #if !defined(ECERE_BOOTSTRAP)
936    if(SplitArchivePath(fileName, archiveName, &archiveFile))
937    {
938       return EARFileSystem::Exists(archiveName, archiveFile);
939    }
940    else if(strstr(fileName, "http://") == fileName)
941    {
942       return FileAttribs { isFile = true };
943    }
944    else
945 #endif
946       return FILE_FileExists(fileName);
947 }
948
949 static int openCount;
950
951 public File FileOpen(char * fileName, FileOpenMode mode)
952 {
953    File result = null;
954    if(fileName)
955    {
956       char archiveName[MAX_LOCATION], * archiveFile;
957 #if !defined(ECERE_BOOTSTRAP)
958       if(SplitArchivePath(fileName, archiveName, &archiveFile))
959       {
960          result = EARFileSystem::Open(archiveName, archiveFile, mode);
961       }
962 #if !defined(ECERE_VANILLA) && !defined(ECERE_NONET)
963       else if(strstr(fileName, "http://") == fileName)
964       {
965          result = FileOpenURL(fileName);
966       }
967 #endif
968       else
969 #endif
970       if(strstr(fileName, "File://") == fileName)
971       {
972          result = (File)(uintptr)strtoull(fileName+7, null, 16);
973          if(result)
974          {
975             if(result._class && eClass_IsDerived(result._class, class(File)))
976             {
977                if(!result._refCount) incref result;
978                incref result;
979                result.Seek(0, start);
980             }
981             else
982                result = null;
983          }
984       }
985       else
986       {
987          File file = File {};
988          if(file)
989          {
990             FILE_FileOpen(fileName, mode, &file.input, &file.output);
991
992             //file.mode = mode;
993             if(!file.input && !file.output);
994             else
995             {
996                openCount++;
997                result = file;
998                // TESTING ENABLING FILE BUFFERING BY DEFAULT... DOCUMENT ANY ISSUE
999                /*
1000                if(file.input)
1001                   setvbuf(file.input, null, _IONBF, 0);
1002                else
1003                   setvbuf(file.output, null, _IONBF, 0);
1004                */
1005             }
1006             if(!result)
1007             {
1008                delete file;
1009                /* TOFIX:
1010                LogErrorCode((mode == Read || mode == ReadWrite) ? 
1011                   ERR_FILE_NOT_FOUND : ERR_FILE_WRITE_FAILED, fileName);
1012                */
1013             }
1014          }
1015       }
1016    }
1017    return result;
1018 }
1019
1020 public void FileFixCase(char * file)
1021 {
1022    FILE_FileFixCase(file);
1023 }
1024
1025 #if !defined(ECERE_BOOTSTRAP)
1026 public bool FileTruncate(char * fileName, FileSize size)
1027 {
1028 #if defined(__WIN32__)
1029    uint16 * _wfileName = UTF8toUTF16(fileName, null);
1030    int f = _wopen(_wfileName, _O_RDWR|_O_CREAT, _S_IREAD|_S_IWRITE);
1031    bool result = false;
1032    if(f != -1)
1033    {
1034       if(!_chsize(f, size))
1035          result = true;
1036       _close(f);
1037    }
1038    delete _wfileName;
1039    return result;
1040 #else
1041    return truncate(fileName, size) == 0;
1042 #endif
1043 }
1044 #endif
1045
1046 public bool FileGetSize(char * fileName, FileSize * size)
1047 {
1048    bool result = false;
1049    if(size)
1050    {
1051       *size = 0;
1052       if(fileName)
1053       {
1054 #if !defined(ECERE_BOOTSTRAP)
1055          char archiveName[MAX_LOCATION], * archiveFile;
1056          if(SplitArchivePath(fileName, archiveName, &archiveFile))
1057             return EARFileSystem::GetSize(archiveName, archiveFile, size);
1058          else
1059 #endif
1060             result = FILE_FileGetSize(fileName, size);
1061       }
1062    }
1063    return result;
1064 }
1065
1066 public bool FileGetStats(char * fileName, FileStats stats)
1067 {
1068    bool result = false;
1069    if(stats && fileName)
1070    {
1071 #if !defined(ECERE_BOOTSTRAP)
1072       char archiveName[MAX_LOCATION], * archiveFile;
1073       if(SplitArchivePath(fileName, archiveName, &archiveFile))
1074          result = EARFileSystem::Stats(archiveName, archiveFile, stats);
1075       else
1076 #endif
1077          return FILE_FileGetStats(fileName, stats);
1078    }
1079    return result;
1080 }
1081
1082 #ifndef ECERE_BOOTSTRAP
1083
1084 public bool FileSetAttribs(char * fileName, FileAttribs attribs)
1085 {
1086 #ifdef __WIN32__
1087    uint winAttribs = 0;
1088    uint16 * _wfileName = UTF8toUTF16(fileName, null);
1089
1090    if(attribs.isHidden)   winAttribs |= FILE_ATTRIBUTE_HIDDEN;
1091    if(attribs.isReadOnly) winAttribs |= FILE_ATTRIBUTE_READONLY;
1092
1093    SetFileAttributes(_wfileName, winAttribs);
1094    delete _wfileName;
1095 #endif
1096    return true;
1097 }
1098
1099 public bool FileSetTime(char * fileName, TimeStamp created, TimeStamp accessed, TimeStamp modified)
1100 {
1101    bool result = false;
1102    TimeStamp currentTime = time(null);
1103    if(!created)  created = currentTime;
1104    if(!accessed) accessed = currentTime;
1105    if(!modified) modified = currentTime;
1106    if(fileName)
1107    {
1108 #ifdef __WIN32__
1109       uint16 * _wfileName = UTF8toUTF16(fileName, null);
1110       HANDLE hFile = CreateFile(_wfileName, GENERIC_WRITE|GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, null,
1111          OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, null);
1112       delete _wfileName;
1113       if(hFile != INVALID_HANDLE_VALUE)
1114       {
1115          FILETIME c, a, m;
1116       
1117          TimeStampToWin32FileTime(created, &c);
1118          TimeStampToWin32FileTime(accessed, &a);
1119          TimeStampToWin32FileTime(modified, &m);
1120
1121          /*
1122          {
1123             uint cc,aa,mm;
1124
1125             cc = Win32FileTimeToTimeStamp(&c);
1126             aa = Win32FileTimeToTimeStamp(&a);
1127             mm = Win32FileTimeToTimeStamp(&m);
1128          }
1129          */
1130                   
1131          if(SetFileTime(hFile, &c, &a, &m))
1132             result = true;
1133
1134          CloseHandle(hFile);
1135       }
1136 #else
1137       struct utimbuf t = { (int)accessed, (int)modified };
1138       if(!utime(fileName, &t))
1139          result = true;
1140 #endif
1141    }
1142    return result;
1143 }
1144
1145 /****************************************************************************
1146  Directory Listing
1147 ****************************************************************************/
1148 // Directory Description for file listing
1149 private class Dir : struct
1150 {
1151 #if defined(__WIN32__)
1152    HANDLE fHandle;
1153
1154    int resource;
1155    NETRESOURCE * resources;
1156    int numResources;
1157
1158    int workGroup;
1159    NETRESOURCE * workGroups;
1160    int numWorkGroups;
1161 #else
1162    DIR * d;
1163 #endif
1164    char name[MAX_LOCATION];
1165 };
1166
1167 static FileDesc FileFind(char * path, char * extensions)
1168 {
1169    FileDesc result = null;
1170    FileDesc file;
1171
1172    if((file = FileDesc {}))
1173    {
1174       char archiveName[MAX_LOCATION], * archiveFile;
1175       if(SplitArchivePath(path, archiveName, &archiveFile))
1176       {
1177          if(EARFileSystem::Find(file, archiveName, archiveFile))
1178          {
1179             file.system = class(EARFileSystem);
1180             result = file;
1181          }
1182       }
1183       else
1184       {
1185          Dir d;
1186       
1187          if((d = file.dir = Dir {}))
1188          {
1189 #if defined(__WIN32__)
1190             if(!strcmp(path, "/"))
1191             {
1192                int c;
1193                uint drives = 0xFFFFFFFF;
1194                d.fHandle = (HANDLE)drives; //GetLogicalDrives();
1195                for(c = 0; c<26; c++)
1196                   if(((uint)d.fHandle) & (1<<c))
1197                   {
1198                      char volume[MAX_FILENAME] = "";
1199                      uint16 _wvolume[MAX_FILENAME];
1200                      int driveType;
1201                      uint16 _wfilePath[4];
1202
1203                      strcpy(d.name, path);
1204                      file.stats.attribs = FileAttribs { isDirectory = true, isDrive = true };
1205                      _wfilePath[0] = file.path[0] = (char)('A' + c);
1206                      _wfilePath[1] = file.path[1] = ':';
1207                      _wfilePath[2] = file.path[2] = '\\';
1208                      _wfilePath[3] = file.path[3] = '\0';
1209                      file.stats.size = 0;
1210                      file.stats.accessed = file.stats.created = file.stats.modified = 0;
1211                      driveType = GetDriveType(_wfilePath);
1212                      switch(driveType)
1213                      {
1214                         case DRIVE_REMOVABLE: file.stats.attribs.isRemovable = true; break;
1215                         case DRIVE_REMOTE:    file.stats.attribs.isRemote = true; break;
1216                         case DRIVE_CDROM:     file.stats.attribs.isCDROM = true; break;
1217                      }
1218                      drives ^= (1<<c);
1219                      if(driveType == DRIVE_NO_ROOT_DIR) continue;
1220                   
1221                      if(driveType != DRIVE_REMOVABLE && driveType != DRIVE_REMOTE && 
1222                         GetVolumeInformation(_wfilePath, _wvolume, MAX_FILENAME - 1, null, null, null, null, 0))
1223                      {
1224                         file.path[2] = '\0';
1225                         UTF16toUTF8Buffer(_wvolume, volume, MAX_FILENAME);
1226                         sprintf(file.name, "%s [%s]", file.path, volume);
1227                      }
1228                      else
1229                      {
1230                         file.path[2] = '\0';
1231                         strcpy(file.name, file.path);
1232                      }
1233                      result = file;
1234                      break;
1235                   }
1236                d.fHandle = (HANDLE) drives;
1237                d.resource = 0;
1238             }
1239             else if(path[0] != '\\' || path[1] != '\\' || strstr(path+2, "\\"))
1240             {
1241                WIN32_FIND_DATA winFile;
1242                uint16 dir[MAX_PATH];
1243
1244                UTF8toUTF16Buffer(path, dir, MAX_LOCATION);
1245                if(path[0]) wcscat(dir, L"\\");
1246                wcscat(dir, L"*.*");
1247
1248                d.fHandle = FindFirstFile(dir, &winFile);
1249                if(d.fHandle == INVALID_HANDLE_VALUE && WinReviveNetworkResource(dir))
1250                   d.fHandle = FindFirstFile(dir, &winFile);
1251                if(d.fHandle != INVALID_HANDLE_VALUE)
1252                {
1253                   UTF16toUTF8Buffer(winFile.cFileName, file.name, MAX_FILENAME);
1254                   strcpy(file.path, path);
1255                   PathCat(file.path, file.name);
1256                   /*if(path[0])
1257                      strcat(file.path, DIR_SEPS);
1258                   strcat(file.path, file.name);*/
1259                   // file.sizeHigh = winFile.nFileSizeHigh;
1260                   file.stats.size = winFile.nFileSizeLow;
1261
1262                   file.stats.attribs = FileAttribs { };
1263                   file.stats.attribs.isArchive   = (winFile.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE)   ? true : false;
1264                   file.stats.attribs.isHidden    = (winFile.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)    ? true : false;
1265                   file.stats.attribs.isReadOnly  = (winFile.dwFileAttributes & FILE_ATTRIBUTE_READONLY)  ? true : false;
1266                   file.stats.attribs.isSystem    = (winFile.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)    ? true : false;
1267                   file.stats.attribs.isTemporary = (winFile.dwFileAttributes & FILE_ATTRIBUTE_TEMPORARY) ? true : false;
1268                   file.stats.attribs.isDirectory = (winFile.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? true : false;
1269                   file.stats.attribs.isFile = !(winFile.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
1270                   strcpy(d.name, path);
1271
1272                   file.stats.accessed = Win32FileTimeToTimeStamp(&winFile.ftLastAccessTime);
1273                   file.stats.modified = Win32FileTimeToTimeStamp(&winFile.ftLastWriteTime);
1274                   file.stats.created  = Win32FileTimeToTimeStamp(&winFile.ftCreationTime);
1275                   result = file;
1276                }
1277             }
1278             else
1279             {
1280                HANDLE handle = 0;
1281                int count = 0xFFFFFFFF;
1282                uint size = 512 * sizeof(NETRESOURCE);
1283                NETRESOURCE * buffer = (NETRESOURCE *)new0 byte[size];
1284                NETRESOURCE nr = {0};
1285
1286                d.fHandle = null;
1287                nr.dwScope       = RESOURCE_GLOBALNET;
1288                nr.dwType        = RESOURCETYPE_DISK;
1289                nr.lpProvider = L"Microsoft Windows Network";
1290
1291                strcpy(d.name, path);
1292                if(path[2])
1293                {
1294                   nr.lpRemoteName = UTF8toUTF16(path, null);
1295
1296                   // Server
1297                   WNetOpenEnum(RESOURCE_GLOBALNET, RESOURCETYPE_DISK, 0, &nr, &handle);
1298                   if(!handle)
1299                   {
1300                      WinReviveNetworkResource(nr.lpRemoteName);
1301                      WNetOpenEnum(RESOURCE_GLOBALNET, RESOURCETYPE_DISK, 0, &nr, &handle);
1302                   }
1303
1304                   if(handle)
1305                   {
1306                      while(true)
1307                      {
1308                         int returnCode = WNetEnumResource(handle, &count, buffer, &size);
1309                         if(returnCode != ERROR_MORE_DATA)
1310                            break;
1311                         count = 0xFFFFFFFF;
1312                         buffer = (NETRESOURCE *)renew0 buffer byte[size];
1313                      }
1314                      WNetCloseEnum(handle);
1315                   }
1316
1317                   delete nr.lpRemoteName;
1318                   if(count > 0)
1319                   {
1320                      file.stats.attribs = FileAttribs { isDirectory = true, isShare = true };
1321                      file.stats.size = 0;
1322                      file.stats.accessed = file.stats.created = file.stats.modified = 0;
1323
1324                      UTF16toUTF8Buffer(buffer->lpRemoteName, file.path, MAX_LOCATION);
1325                      GetLastDirectory(file.path, file.name);
1326
1327                      result = file;
1328                      d.resources = buffer;
1329                      d.numResources = count;
1330                      d.resource = 1;
1331                   }
1332                   else
1333                      delete buffer;
1334                }
1335                else
1336                {
1337                   int c;
1338                   nr.lpProvider = L"Microsoft Windows Network";
1339
1340                   // Entire Network
1341                   WNetOpenEnum(RESOURCE_GLOBALNET, RESOURCETYPE_DISK, 0, &nr, &handle);
1342                   while(true)
1343                   {
1344                      int returnCode = WNetEnumResource(handle, &count, buffer, &size);
1345                      if(returnCode != ERROR_MORE_DATA)
1346                         break;
1347                      count = 0xFFFFFFFF;
1348                      buffer = (NETRESOURCE *)renew0 buffer byte[size];
1349                   }
1350                   WNetCloseEnum(handle);
1351
1352                   for(c = 0; c<count; c++)
1353                   {
1354                      NETRESOURCE * resources;
1355                      int countInGroup = 0xFFFFFFFF;
1356
1357                      size = 512 * sizeof(NETRESOURCE);
1358                      resources = (NETRESOURCE *)new0 byte[size];
1359                   
1360                      // Entire Network
1361                      WNetOpenEnum(RESOURCE_GLOBALNET, RESOURCETYPE_DISK, 0, &buffer[c], &handle);
1362                      while(true)
1363                      {
1364                         int returnCode = WNetEnumResource(handle, &countInGroup, resources, &size);
1365                         if(returnCode != ERROR_MORE_DATA)
1366                            break;
1367                         countInGroup = 0xFFFFFFFF;
1368                         resources = (NETRESOURCE *)renew0 resources byte[size];
1369                      }
1370                      WNetCloseEnum(handle);
1371
1372                      if(countInGroup)
1373                      {
1374                         file.stats.attribs = FileAttribs { isDirectory = true, isServer = true };
1375                         file.stats.size = 0;
1376                         file.stats.accessed = file.stats.created = file.stats.modified = 0;
1377
1378                         UTF16toUTF8Buffer(resources->lpRemoteName, file.path, MAX_LOCATION);
1379                         strlwr(file.path);
1380                         file.path[2] = (char)toupper(file.path[2]);
1381                         GetLastDirectory(file.path, file.name);
1382
1383                         result = file;
1384
1385                         d.resources = resources;
1386                         d.numResources = countInGroup;
1387                         d.resource = 1;
1388
1389                         d.workGroups = buffer;
1390                         d.numWorkGroups = count;
1391                         d.workGroup = c;
1392                         break;
1393                      }
1394                      else
1395                         delete resources;
1396                   }
1397                   if(c >= count && buffer) delete buffer;
1398                }
1399             }
1400 #else
1401             struct dirent *de;
1402             struct stat s;
1403
1404             d.d = opendir((path && path[0]) ? path : ".");
1405             if(d.d && (de = readdir(d.d)))
1406             {
1407                if(path[0])
1408                {
1409                   strcpy(file.path, path);
1410                   if(path[1])
1411                      strcat(file.path, DIR_SEPS);
1412                }
1413                strcpy(file.name,de->d_name);
1414                strcat(file.path, file.name);
1415                if(!stat(file.path, &s))
1416                {
1417                   file.stats.attribs = (s.st_mode&S_IFDIR) ? FileAttribs { isDirectory = true } : FileAttribs { isFile = true };
1418                   file.stats.size = (FileSize)s.st_size;
1419                   file.stats.accessed = s.st_atime;
1420                   file.stats.modified = s.st_mtime;
1421                   file.stats.created = s.st_ctime;
1422                }
1423                strcpy(d.name, path);
1424
1425                result = file;
1426             }
1427 #endif
1428          }
1429
1430          if(!result)
1431             delete d;
1432       }
1433       if(!result)
1434          delete file;
1435    }
1436    if(result)
1437    {
1438       while(result && !result.Validate(extensions))
1439          result = result.FindNext(extensions);
1440    }
1441    return result;
1442 }
1443
1444 private class FileDesc : struct
1445 {
1446    FileStats stats;
1447    char name[MAX_FILENAME];
1448    char path[MAX_LOCATION];
1449
1450    subclass(FileSystem) system;
1451    Dir dir;
1452
1453    bool Validate(char * extensions)
1454    {
1455       if(strcmp(name, "..") && strcmp(name, ".") && strcmp(name, ""))
1456       {
1457          if(extensions && !stats.attribs.isDirectory)
1458          {
1459             char extension[MAX_EXTENSION], compared[MAX_EXTENSION];
1460             int c;
1461
1462             GetExtension(name, extension);
1463             for(c = 0; extensions[c];)
1464             {
1465                int len = 0;
1466                char ch;
1467                for(;(ch = extensions[c]) && !IS_ALUNDER(ch); c++);
1468                for(;(ch = extensions[c]) &&  IS_ALUNDER(ch); c++)
1469                   compared[len++] = ch;
1470                compared[len] = '\0';
1471
1472                if(!strcmpi(extension, compared))
1473                   return true;
1474             }
1475          }
1476          else
1477             return true;
1478       }
1479       return false;
1480    }
1481
1482    FileDesc FindNext(char * extensions)
1483    {
1484       FileDesc result = null;
1485
1486       Dir d = dir;
1487
1488       name[0] = '.';
1489       name[1] = '\0';
1490       while(!Validate(extensions))
1491       {
1492          result = null;
1493
1494          if(system)
1495          {
1496             if(system.FindNext(this))
1497                result = this;
1498             else
1499                break;
1500          }
1501          else
1502          {
1503 #if defined(__WIN32__)
1504             if(!strcmp(d.name, "/"))
1505             {
1506                int c;
1507                uint drives = (uint)d.fHandle;
1508                for(c = 0; c<26; c++)
1509                {
1510                   if(drives & (1<<c))
1511                   {
1512                      char volume[MAX_FILENAME] = "";
1513                      int driveType;
1514                      uint16 _wpath[4];
1515                      uint16 _wvolume[MAX_FILENAME];
1516
1517                      stats.attribs = FileAttribs { isDirectory = true, isDrive = true };
1518                      stats.size = 0;
1519                      stats.accessed = stats.created = stats.modified = 0;
1520                      _wpath[0] = path[0] = (char)('A' + c);
1521                      _wpath[1] = path[1] = ':';
1522                      _wpath[2] = path[2] = '\\';
1523                      _wpath[3] = path[3] = 0;
1524                      driveType = GetDriveType(_wpath);
1525                      drives ^= (1<<c);
1526
1527                      switch(driveType)
1528                      {
1529                         case DRIVE_REMOVABLE: stats.attribs.isRemovable = true; break;
1530                         case DRIVE_REMOTE:    stats.attribs.isRemote = true;    break;
1531                         case DRIVE_CDROM:     stats.attribs.isCDROM = true;     break;
1532                      }
1533                      if(driveType == DRIVE_NO_ROOT_DIR)
1534                      {
1535                         uint16 remoteName[1024];
1536                         int status;
1537                         int size = 1024;
1538                         _wpath[2] = 0;
1539
1540                         status = WNetGetConnection(_wpath, remoteName, &size);
1541                         if(status != ERROR_CONNECTION_UNAVAIL)
1542                            continue;
1543
1544                         _wpath[2] = '\\';
1545                         _wpath[3] = 0;
1546                      }
1547
1548                      if(driveType != DRIVE_REMOVABLE && driveType != DRIVE_REMOTE && 
1549                         GetVolumeInformation(_wpath, _wvolume, MAX_FILENAME - 1, null, null, null, null, 0))
1550                      {
1551                         UTF16toUTF8Buffer(_wvolume, volume, MAX_FILENAME);
1552                         path[2] = '\0';
1553                         sprintf(name, "%s [%s]", path, volume);
1554                      }
1555                      else
1556                      {
1557                         path[2] = '\0';
1558                         strcpy(name, path);
1559                      }
1560                      result = this;
1561                      break;
1562                   }
1563                }
1564                d.fHandle = (HANDLE) drives;
1565                break;
1566             }
1567             else if(d.name[0] != '\\' || d.name[1] != '\\' || strstr(d.name+2, "\\"))
1568             {
1569                WIN32_FIND_DATA winFile;
1570                if(FindNextFile(d.fHandle, &winFile))
1571                {
1572                   UTF16toUTF8Buffer(winFile.cFileName, name, MAX_FILENAME);
1573                   stats.attribs = FileAttribs { };
1574                   stats.attribs.isArchive   = (winFile.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE)   ? true : false;
1575                   stats.attribs.isHidden    = (winFile.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)    ? true : false;
1576                   stats.attribs.isReadOnly  = (winFile.dwFileAttributes & FILE_ATTRIBUTE_READONLY)  ? true : false;
1577                   stats.attribs.isSystem    = (winFile.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)    ? true : false;
1578                   stats.attribs.isTemporary = (winFile.dwFileAttributes & FILE_ATTRIBUTE_TEMPORARY) ? true : false;
1579                   stats.attribs.isDirectory = (winFile.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? true : false;
1580                   stats.attribs.isFile      = !(winFile.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
1581                   stats.size = winFile.nFileSizeLow;
1582
1583                   stats.accessed = Win32FileTimeToTimeStamp(&winFile.ftLastAccessTime);
1584                   stats.modified = Win32FileTimeToTimeStamp(&winFile.ftLastWriteTime);
1585                   stats.created  = Win32FileTimeToTimeStamp(&winFile.ftCreationTime);
1586
1587                   strcpy(path, d.name);
1588                   PathCat(path, name);
1589                   /*if(d.name[0])
1590                      strcat(path, DIR_SEPS);
1591                   strcat(path, name);*/
1592                   result = this;
1593                }
1594                else
1595                   break;
1596             }
1597             else
1598             {
1599                if(d.name[2])
1600                {
1601                   if(d.resource < d.numResources)
1602                   {
1603                      stats.attribs = FileAttribs { isDirectory = true, isShare = true };
1604                      stats.size = 0;
1605                      stats.accessed = stats.created = stats.modified = 0;
1606
1607                      UTF16toUTF8Buffer(d.resources[d.resource].lpRemoteName, path, MAX_LOCATION);
1608                      GetLastDirectory(path, name);
1609
1610                      result = this;
1611
1612                      d.resource++;
1613                   }
1614                   else
1615                   {
1616                      delete d.resources;
1617                      break;
1618                   }
1619                }
1620                else
1621                {
1622                   int c;
1623                   for(c = d.workGroup; c<d.numWorkGroups; c++)
1624                   {
1625                      if(c != d.workGroup)
1626                      {
1627                         int countInGroup = 0xFFFFFFFF;
1628                         HANDLE handle;
1629                         NETRESOURCE * resources;
1630                         uint size = 512 * sizeof(NETRESOURCE);
1631
1632                         resources = (NETRESOURCE *)new0 byte[size];
1633                         // Entire Network
1634                         WNetOpenEnum(RESOURCE_GLOBALNET, RESOURCETYPE_DISK, 0, &d.workGroups[c], &handle);
1635                         while(true)
1636                         {
1637                            int returnCode = WNetEnumResource(handle, &countInGroup, resources, &size);
1638                            if(returnCode != ERROR_MORE_DATA)
1639                               break;
1640                            countInGroup = 0xFFFFFFFF;
1641                            resources = (NETRESOURCE *)renew0 resources byte[size];
1642                            
1643                         }
1644                         WNetCloseEnum(handle);
1645                         d.numResources = countInGroup;
1646                         d.resources = resources;
1647                         d.resource = 0;
1648                      }
1649
1650                      if(d.resource < d.numResources)
1651                      {
1652                         stats.attribs = FileAttribs { isDirectory = true, isServer = true };
1653                         stats.size = 0;
1654                         stats.accessed = stats.created = stats.modified = 0;
1655
1656                         UTF16toUTF8Buffer(d.resources[d.resource].lpRemoteName, path, MAX_LOCATION);
1657                         strlwr(path);
1658                         path[2] = (char)toupper(path[2]);
1659                         GetLastDirectory(path, name);
1660
1661                         result = this;
1662
1663                         d.resource++;
1664                         break;
1665                      }
1666                      else
1667                      {
1668                         if(d.resources) 
1669                            delete d.resources;
1670                      }
1671                   }
1672                   d.workGroup = c;
1673                   if(d.workGroup == d.numWorkGroups && d.resource == d.numResources)
1674                   {
1675                      delete d.workGroups;
1676                      break;
1677                   }
1678                }
1679             }
1680 #else
1681             struct dirent *de;
1682             struct stat s;
1683
1684             de = readdir(d.d);
1685             if(de)
1686             {
1687                strcpy(name,de->d_name);
1688                strcpy(path, d.name);
1689                if(d.name[0] && d.name[1])
1690                   strcat(path, DIR_SEPS);
1691                strcat(path, name);
1692                if(!stat(path, &s))
1693                {
1694                   stats.attribs = FileAttribs { };
1695                   stats.attribs = (s.st_mode&S_IFDIR) ? FileAttribs { isDirectory = true } : FileAttribs { isFile = true };
1696                   stats.size = (FileSize)s.st_size;
1697                   stats.accessed = s.st_atime;
1698                   stats.modified = s.st_mtime;
1699                   stats.created = s.st_ctime;
1700                }
1701                result = this;
1702             }
1703             else
1704                break;
1705 #endif
1706          }
1707       }
1708       if(!result)
1709          CloseDir();
1710       return result;
1711    }
1712
1713    void CloseDir(void)
1714    {
1715       if(system)
1716          system.CloseDir(this);
1717       else
1718       {
1719          Dir d = dir;
1720          if(d)
1721          {
1722 #if defined(__WIN32__)
1723             if(d.fHandle && strcmp(d.name, "/"))
1724                FindClose(d.fHandle);
1725 #else
1726             closedir(d.d);
1727 #endif
1728             delete d;
1729          }
1730       }
1731       delete this;
1732    }
1733 }
1734
1735 public struct FileListing
1736 {
1737 public:
1738    char * directory;
1739    char * extensions;
1740
1741    bool Find()
1742    {
1743       bool result = false;
1744       if(desc)
1745          desc = desc.FindNext(extensions);
1746       else
1747          desc = FileFind(directory, extensions);
1748       if(desc)
1749          return true;
1750       return false;
1751    }
1752
1753    void Stop()
1754    {
1755       if(desc)
1756          desc.CloseDir();
1757       desc = null;
1758    }
1759
1760    property char * name { get { return (char *)(desc ? desc.name : null); } };
1761    property char * path { get { return (char *)(desc ? desc.path : null); } };
1762    property FileStats stats { get { value = desc ? desc.stats : FileStats { }; } };
1763
1764 private:
1765    FileDesc desc;
1766 };
1767 #endif
1768
1769 public File CreateTemporaryFile(char * tempFileName, char * template)
1770 {
1771 #ifndef ECERE_BOOTSTRAP // quick fix for now
1772    File f;
1773 #if defined(__unix__) || defined(__APPLE__)
1774    char buffer[MAX_FILENAME];
1775    int fd;
1776    strcpy(buffer, "/tmp/");
1777    strcat(buffer, template);
1778    //strcpy(buffer, template);
1779    strcat(buffer, "XXXXXX");
1780    // mktemp(buffer);
1781    fd = mkstemp(buffer);   
1782    strcpy(tempFileName, buffer);
1783    f = { };
1784    f.output = f.input = fdopen(fd, "r+");
1785 #else
1786    char tempPath[MAX_LOCATION];
1787    GetTempPathA(MAX_LOCATION, tempPath);     // TODO: Patch this whole thing to support Unicode temp path
1788    GetTempFileNameA(tempPath, template, 0, tempFileName);
1789    f = FileOpen(tempFileName, readWrite);
1790 #endif   
1791    return f;
1792 #endif
1793 }
1794
1795 #undef DeleteFile
1796
1797 public void CreateTemporaryDir(char * tempFileName, char * template)
1798 {
1799 #ifndef ECERE_BOOTSTRAP // quick fix for now
1800 #if defined(__unix__) || defined(__APPLE__)
1801    char buffer[MAX_FILENAME];
1802    strcpy(buffer, "/tmp/");
1803    strcat(buffer, template);
1804    //strcpy(buffer, template);
1805    strcat(buffer, "XXXXXX");
1806    // mkstemp(buffer);
1807    mkdtemp(buffer);
1808    strcpy(tempFileName, buffer);
1809 #else
1810    char tempPath[MAX_LOCATION];
1811    GetTempPathA(MAX_LOCATION, tempPath);     // TODO: Patch this whole thing to support Unicode temp path
1812    GetTempFileNameA(tempPath, template, 0, tempFileName);
1813    DeleteFile(tempFileName);
1814    MakeDir(tempFileName);
1815 #endif
1816 #endif
1817 }
1818
1819 public void MakeSlashPath(char * p)
1820 {
1821    FileFixCase(p);
1822 #ifdef WIN32
1823    ChangeCh(p, '\\', '/');
1824 #endif
1825 }
1826
1827 public void MakeSystemPath(char * p)
1828 {
1829    FileFixCase(p);
1830 }
1831
1832 public char * CopySystemPath(char * p)
1833 {
1834    char * d = CopyString(p);
1835    if(d)
1836       MakeSystemPath(d);
1837    return d;
1838 }
1839
1840 public char * CopyUnixPath(char * p)
1841 {
1842    char * d = CopyString(p);
1843    if(d)
1844       MakeSlashPath(d);
1845    return d;
1846 }
1847
1848 public char * GetSystemPathBuffer(char * d, char * p)
1849 {
1850    if(d != p)
1851       strcpy(d, p ? p : "");
1852    MakeSystemPath(d);
1853    return d;
1854 }
1855
1856 public char * GetSlashPathBuffer(char * d, char * p)
1857 {
1858    if(d != p)
1859       strcpy(d, p ? p : "");
1860    MakeSlashPath(d);
1861    return d;
1862 }