]> git.saurik.com Git - wxWidgets.git/blob - src/common/filename.cpp
Removed wxPATH_NORM_CASE from Normalize or files won't be written
[wxWidgets.git] / src / common / filename.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/filename.cpp
3 // Purpose: wxFileName - encapsulates a file path
4 // Author: Robert Roebling, Vadim Zeitlin
5 // Modified by:
6 // Created: 28.12.2000
7 // RCS-ID: $Id$
8 // Copyright: (c) 2000 Robert Roebling
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
11
12 /*
13 Here are brief descriptions of the filename formats supported by this class:
14
15 wxPATH_UNIX: standard Unix format, used under Darwin as well, absolute file
16 names have the form:
17 /dir1/dir2/.../dirN/filename, "." and ".." stand for the
18 current and parent directory respectively, "~" is parsed as the
19 user HOME and "~username" as the HOME of that user
20
21 wxPATH_DOS: DOS/Windows format, absolute file names have the form:
22 drive:\dir1\dir2\...\dirN\filename.ext where drive is a single
23 letter. "." and ".." as for Unix but no "~".
24
25 There are also UNC names of the form \\share\fullpath
26
27 wxPATH_MAC: Mac OS 8/9 and Mac OS X under CodeWarrior 7 format, absolute file
28 names have the form
29 volume:dir1:...:dirN:filename
30 and the relative file names are either
31 :dir1:...:dirN:filename
32 or just
33 filename
34 (although :filename works as well).
35 Since the volume is just part of the file path, it is not
36 treated like a separate entity as it is done under DOS and
37 VMS, it is just treated as another dir.
38
39 wxPATH_VMS: VMS native format, absolute file names have the form
40 <device>:[dir1.dir2.dir3]file.txt
41 or
42 <device>:[000000.dir1.dir2.dir3]file.txt
43
44 the <device> is the physical device (i.e. disk). 000000 is the
45 root directory on the device which can be omitted.
46
47 Note that VMS uses different separators unlike Unix:
48 : always after the device. If the path does not contain : than
49 the default (the device of the current directory) is assumed.
50 [ start of directory specyfication
51 . separator between directory and subdirectory
52 ] between directory and file
53 */
54
55 // ============================================================================
56 // declarations
57 // ============================================================================
58
59 // ----------------------------------------------------------------------------
60 // headers
61 // ----------------------------------------------------------------------------
62
63 #ifdef __GNUG__
64 #pragma implementation "filename.h"
65 #endif
66
67 // For compilers that support precompilation, includes "wx.h".
68 #include "wx/wxprec.h"
69
70 #ifdef __BORLANDC__
71 #pragma hdrstop
72 #endif
73
74 #ifndef WX_PRECOMP
75 #include "wx/intl.h"
76 #include "wx/log.h"
77 #include "wx/file.h"
78 #endif
79
80 #include "wx/filename.h"
81 #include "wx/tokenzr.h"
82 #include "wx/config.h" // for wxExpandEnvVars
83 #include "wx/utils.h"
84 #include "wx/file.h"
85 //#include "wx/dynlib.h" // see GetLongPath below, code disabled.
86
87 // For GetShort/LongPathName
88 #ifdef __WIN32__
89 #include <windows.h>
90 #include "wx/msw/winundef.h"
91 #endif
92
93 #if defined(__WXMAC__)
94 #include "wx/mac/private.h" // includes mac headers
95 #endif
96
97 // utime() is POSIX so should normally be available on all Unices
98 #ifdef __UNIX_LIKE__
99 #include <sys/types.h>
100 #include <utime.h>
101 #include <sys/stat.h>
102 #include <unistd.h>
103 #endif
104
105 #ifdef __DJGPP__
106 #include <unistd.h>
107 #endif
108
109 #ifdef __MWERKS__
110 #include <stat.h>
111 #include <unistd.h>
112 #include <unix.h>
113 #endif
114
115 #ifdef __WATCOMC__
116 #include <io.h>
117 #include <sys/utime.h>
118 #include <sys/stat.h>
119 #endif
120
121 #ifdef __VISAGECPP__
122 #ifndef MAX_PATH
123 #define MAX_PATH 256
124 #endif
125 #endif
126
127 // ----------------------------------------------------------------------------
128 // private classes
129 // ----------------------------------------------------------------------------
130
131 // small helper class which opens and closes the file - we use it just to get
132 // a file handle for the given file name to pass it to some Win32 API function
133 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
134
135 class wxFileHandle
136 {
137 public:
138 wxFileHandle(const wxString& filename)
139 {
140 m_hFile = ::CreateFile
141 (
142 filename, // name
143 GENERIC_READ, // access mask
144 0, // no sharing
145 NULL, // no secutity attr
146 OPEN_EXISTING, // creation disposition
147 0, // no flags
148 NULL // no template file
149 );
150
151 if ( m_hFile == INVALID_HANDLE_VALUE )
152 {
153 wxLogSysError(_("Failed to open '%s' for reading"),
154 filename.c_str());
155 }
156 }
157
158 ~wxFileHandle()
159 {
160 if ( m_hFile != INVALID_HANDLE_VALUE )
161 {
162 if ( !::CloseHandle(m_hFile) )
163 {
164 wxLogSysError(_("Failed to close file handle"));
165 }
166 }
167 }
168
169 // return TRUE only if the file could be opened successfully
170 bool IsOk() const { return m_hFile != INVALID_HANDLE_VALUE; }
171
172 // get the handle
173 operator HANDLE() const { return m_hFile; }
174
175 private:
176 HANDLE m_hFile;
177 };
178
179 #endif // __WIN32__
180
181 // ----------------------------------------------------------------------------
182 // private functions
183 // ----------------------------------------------------------------------------
184
185 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
186
187 // convert between wxDateTime and FILETIME which is a 64-bit value representing
188 // the number of 100-nanosecond intervals since January 1, 1601.
189
190 // the number of milliseconds between the Unix Epoch (January 1, 1970) and the
191 // FILETIME reference point (January 1, 1601)
192 static const wxLongLong FILETIME_EPOCH_OFFSET = wxLongLong(0xa97, 0x30b66800);
193
194 static void ConvertFileTimeToWx(wxDateTime *dt, const FILETIME &ft)
195 {
196 wxLongLong ll(ft.dwHighDateTime, ft.dwLowDateTime);
197
198 // convert 100ns to ms
199 ll /= 10000;
200
201 // move it to our Epoch
202 ll -= FILETIME_EPOCH_OFFSET;
203
204 *dt = wxDateTime(ll);
205 }
206
207 static void ConvertWxToFileTime(FILETIME *ft, const wxDateTime& dt)
208 {
209 // do the reverse of ConvertFileTimeToWx()
210 wxLongLong ll = dt.GetValue();
211 ll *= 10000;
212 ll += FILETIME_EPOCH_OFFSET;
213
214 ft->dwHighDateTime = ll.GetHi();
215 ft->dwLowDateTime = ll.GetLo();
216 }
217
218 #endif // __WIN32__
219
220 // ============================================================================
221 // implementation
222 // ============================================================================
223
224 // ----------------------------------------------------------------------------
225 // wxFileName construction
226 // ----------------------------------------------------------------------------
227
228 void wxFileName::Assign( const wxFileName &filepath )
229 {
230 m_volume = filepath.GetVolume();
231 m_dirs = filepath.GetDirs();
232 m_name = filepath.GetName();
233 m_ext = filepath.GetExt();
234 m_relative = filepath.IsRelative();
235 }
236
237 void wxFileName::Assign(const wxString& volume,
238 const wxString& path,
239 const wxString& name,
240 const wxString& ext,
241 wxPathFormat format )
242 {
243 SetPath( path, format );
244
245 m_volume = volume;
246 m_ext = ext;
247 m_name = name;
248 }
249
250 void wxFileName::SetPath( const wxString &path, wxPathFormat format )
251 {
252 wxPathFormat my_format = GetFormat( format );
253 wxString my_path = path;
254
255 m_dirs.Clear();
256
257 if (!my_path.empty())
258 {
259 // 1) Determine if the path is relative or absolute.
260
261 switch (my_format)
262 {
263 case wxPATH_MAC:
264 m_relative = ( my_path[0u] == wxT(':') );
265 // We then remove a leading ":". The reason is in our
266 // storage form for relative paths:
267 // ":dir:file.txt" actually means "./dir/file.txt" in
268 // DOS notation and should get stored as
269 // (relative) (dir) (file.txt)
270 // "::dir:file.txt" actually means "../dir/file.txt"
271 // stored as (relative) (..) (dir) (file.txt)
272 // This is important only for the Mac as an empty dir
273 // actually means <UP>, whereas under DOS, double
274 // slashes can be ignored: "\\\\" is the same as "\\".
275 if (m_relative)
276 my_path.Remove( 0, 1 );
277 break;
278 case wxPATH_VMS:
279 // TODO: what is the relative path format here?
280 m_relative = FALSE;
281 break;
282 case wxPATH_UNIX:
283 m_relative = ( my_path[0u] != wxT('/') );
284 break;
285 case wxPATH_DOS:
286 m_relative = ( (my_path[0u] != wxT('/')) && (my_path[0u] != wxT('\\')) );
287 break;
288 default:
289 wxFAIL_MSG( wxT("error") );
290 break;
291 }
292
293 // 2) Break up the path into its members. If the original path
294 // was just "/" or "\\", m_dirs will be empty. We know from
295 // the m_relative field, if this means "nothing" or "root dir".
296
297 wxStringTokenizer tn( my_path, GetPathSeparators(my_format) );
298
299 while ( tn.HasMoreTokens() )
300 {
301 wxString token = tn.GetNextToken();
302
303 // Remove empty token under DOS and Unix, interpret them
304 // as .. under Mac.
305 if (token.empty())
306 {
307 if (my_format == wxPATH_MAC)
308 m_dirs.Add( wxT("..") );
309 // else ignore
310 }
311 else
312 {
313 m_dirs.Add( token );
314 }
315 }
316 }
317 else
318 {
319 m_relative = TRUE;
320 }
321 }
322
323 void wxFileName::Assign(const wxString& fullpath,
324 wxPathFormat format)
325 {
326 wxString volume, path, name, ext;
327 SplitPath(fullpath, &volume, &path, &name, &ext, format);
328
329 Assign(volume, path, name, ext, format);
330 }
331
332 void wxFileName::Assign(const wxString& fullpathOrig,
333 const wxString& fullname,
334 wxPathFormat format)
335 {
336 // always recognize fullpath as directory, even if it doesn't end with a
337 // slash
338 wxString fullpath = fullpathOrig;
339 if ( !wxEndsWithPathSeparator(fullpath) )
340 {
341 fullpath += GetPathSeparators(format)[0u];
342 }
343
344 wxString volume, path, name, ext;
345
346 // do some consistency checks in debug mode: the name should be really just
347 // the filename and the path should be really just a path
348 #ifdef __WXDEBUG__
349 wxString pathDummy, nameDummy, extDummy;
350
351 SplitPath(fullname, &pathDummy, &name, &ext, format);
352
353 wxASSERT_MSG( pathDummy.empty(),
354 _T("the file name shouldn't contain the path") );
355
356 SplitPath(fullpath, &volume, &path, &nameDummy, &extDummy, format);
357
358 wxASSERT_MSG( nameDummy.empty() && extDummy.empty(),
359 _T("the path shouldn't contain file name nor extension") );
360
361 #else // !__WXDEBUG__
362 SplitPath(fullname, NULL /* no path */, &name, &ext, format);
363 SplitPath(fullpath, &volume, &path, NULL, NULL, format);
364 #endif // __WXDEBUG__/!__WXDEBUG__
365
366 Assign(volume, path, name, ext, format);
367 }
368
369 void wxFileName::AssignDir(const wxString& dir, wxPathFormat format)
370 {
371 Assign(dir, _T(""), format);
372 }
373
374 void wxFileName::Clear()
375 {
376 m_dirs.Clear();
377
378 m_volume =
379 m_name =
380 m_ext = wxEmptyString;
381 }
382
383 /* static */
384 wxFileName wxFileName::FileName(const wxString& file)
385 {
386 return wxFileName(file);
387 }
388
389 /* static */
390 wxFileName wxFileName::DirName(const wxString& dir)
391 {
392 wxFileName fn;
393 fn.AssignDir(dir);
394 return fn;
395 }
396
397 // ----------------------------------------------------------------------------
398 // existence tests
399 // ----------------------------------------------------------------------------
400
401 bool wxFileName::FileExists()
402 {
403 return wxFileName::FileExists( GetFullPath() );
404 }
405
406 bool wxFileName::FileExists( const wxString &file )
407 {
408 return ::wxFileExists( file );
409 }
410
411 bool wxFileName::DirExists()
412 {
413 return wxFileName::DirExists( GetFullPath() );
414 }
415
416 bool wxFileName::DirExists( const wxString &dir )
417 {
418 return ::wxDirExists( dir );
419 }
420
421 // ----------------------------------------------------------------------------
422 // CWD and HOME stuff
423 // ----------------------------------------------------------------------------
424
425 void wxFileName::AssignCwd(const wxString& volume)
426 {
427 AssignDir(wxFileName::GetCwd(volume));
428 }
429
430 /* static */
431 wxString wxFileName::GetCwd(const wxString& volume)
432 {
433 // if we have the volume, we must get the current directory on this drive
434 // and to do this we have to chdir to this volume - at least under Windows,
435 // I don't know how to get the current drive on another volume elsewhere
436 // (TODO)
437 wxString cwdOld;
438 if ( !volume.empty() )
439 {
440 cwdOld = wxGetCwd();
441 SetCwd(volume + GetVolumeSeparator());
442 }
443
444 wxString cwd = ::wxGetCwd();
445
446 if ( !volume.empty() )
447 {
448 SetCwd(cwdOld);
449 }
450
451 return cwd;
452 }
453
454 bool wxFileName::SetCwd()
455 {
456 return wxFileName::SetCwd( GetFullPath() );
457 }
458
459 bool wxFileName::SetCwd( const wxString &cwd )
460 {
461 return ::wxSetWorkingDirectory( cwd );
462 }
463
464 void wxFileName::AssignHomeDir()
465 {
466 AssignDir(wxFileName::GetHomeDir());
467 }
468
469 wxString wxFileName::GetHomeDir()
470 {
471 return ::wxGetHomeDir();
472 }
473
474 void wxFileName::AssignTempFileName(const wxString& prefix, wxFile *fileTemp)
475 {
476 wxString tempname = CreateTempFileName(prefix, fileTemp);
477 if ( tempname.empty() )
478 {
479 // error, failed to get temp file name
480 Clear();
481 }
482 else // ok
483 {
484 Assign(tempname);
485 }
486 }
487
488 /* static */
489 wxString
490 wxFileName::CreateTempFileName(const wxString& prefix, wxFile *fileTemp)
491 {
492 wxString path, dir, name;
493
494 // use the directory specified by the prefix
495 SplitPath(prefix, &dir, &name, NULL /* extension */);
496
497 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
498
499 #ifdef __WIN32__
500 if ( dir.empty() )
501 {
502 if ( !::GetTempPath(MAX_PATH, wxStringBuffer(dir, MAX_PATH + 1)) )
503 {
504 wxLogLastError(_T("GetTempPath"));
505 }
506
507 if ( dir.empty() )
508 {
509 // GetTempFileName() fails if we pass it an empty string
510 dir = _T('.');
511 }
512 }
513
514 if ( !::GetTempFileName(dir, name, 0, wxStringBuffer(path, MAX_PATH + 1)) )
515 {
516 wxLogLastError(_T("GetTempFileName"));
517
518 path.clear();
519 }
520 #else // Win16
521 if ( !::GetTempFileName(NULL, prefix, 0, wxStringBuffer(path, 1025)) )
522 {
523 path.clear();
524 }
525 #endif // Win32/16
526
527 #elif defined(__WXPM__)
528 // for now just create a file
529 //
530 // future enhancements can be to set some extended attributes for file
531 // systems OS/2 supports that have them (HPFS, FAT32) and security
532 // (HPFS386)
533 static const wxChar *szMktempSuffix = wxT("XXX");
534 path << dir << _T('/') << name << szMktempSuffix;
535
536 // Temporarily remove - MN
537 #ifndef __WATCOMC__
538 ::DosCreateDir(wxStringBuffer(path, MAX_PATH), NULL);
539 #endif
540
541 #else // !Windows, !OS/2
542 if ( dir.empty() )
543 {
544 #if defined(__WXMAC__) && !defined(__DARWIN__)
545 dir = wxMacFindFolder( (short) kOnSystemDisk, kTemporaryFolderType, kCreateFolder ) ;
546 #else // !Mac
547 dir = wxGetenv(_T("TMP"));
548 if ( dir.empty() )
549 {
550 dir = wxGetenv(_T("TEMP"));
551 }
552
553 if ( dir.empty() )
554 {
555 // default
556 #ifdef __DOS__
557 dir = _T(".");
558 #else
559 dir = _T("/tmp");
560 #endif
561 }
562 #endif // Mac/!Mac
563 }
564
565 path = dir;
566
567 if ( !wxEndsWithPathSeparator(dir) &&
568 (name.empty() || !wxIsPathSeparator(name[0u])) )
569 {
570 path += wxFILE_SEP_PATH;
571 }
572
573 path += name;
574
575 #if defined(HAVE_MKSTEMP)
576 // scratch space for mkstemp()
577 path += _T("XXXXXX");
578
579 // can use the cast here because the length doesn't change and the string
580 // is not shared
581 int fdTemp = mkstemp((char *)path.mb_str());
582 if ( fdTemp == -1 )
583 {
584 // this might be not necessary as mkstemp() on most systems should have
585 // already done it but it doesn't hurt neither...
586 path.clear();
587 }
588 else // mkstemp() succeeded
589 {
590 // avoid leaking the fd
591 if ( fileTemp )
592 {
593 fileTemp->Attach(fdTemp);
594 }
595 else
596 {
597 close(fdTemp);
598 }
599 }
600 #else // !HAVE_MKSTEMP
601
602 #ifdef HAVE_MKTEMP
603 // same as above
604 path += _T("XXXXXX");
605
606 if ( !mktemp((char *)path.mb_str()) )
607 {
608 path.clear();
609 }
610 #else // !HAVE_MKTEMP (includes __DOS__)
611 // generate the unique file name ourselves
612 #ifndef __DOS__
613 path << (unsigned int)getpid();
614 #endif
615
616 wxString pathTry;
617
618 static const size_t numTries = 1000;
619 for ( size_t n = 0; n < numTries; n++ )
620 {
621 // 3 hex digits is enough for numTries == 1000 < 4096
622 pathTry = path + wxString::Format(_T("%.03x"), n);
623 if ( !wxFile::Exists(pathTry) )
624 {
625 break;
626 }
627
628 pathTry.clear();
629 }
630
631 path = pathTry;
632 #endif // HAVE_MKTEMP/!HAVE_MKTEMP
633
634 if ( !path.empty() )
635 {
636 }
637 #endif // HAVE_MKSTEMP/!HAVE_MKSTEMP
638
639 #endif // Windows/!Windows
640
641 if ( path.empty() )
642 {
643 wxLogSysError(_("Failed to create a temporary file name"));
644 }
645 else if ( fileTemp && !fileTemp->IsOpened() )
646 {
647 // open the file - of course, there is a race condition here, this is
648 // why we always prefer using mkstemp()...
649 //
650 // NB: GetTempFileName() under Windows creates the file, so using
651 // write_excl there would fail
652 if ( !fileTemp->Open(path,
653 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
654 wxFile::write,
655 #else
656 wxFile::write_excl,
657 #endif
658 wxS_IRUSR | wxS_IWUSR) )
659 {
660 // FIXME: If !ok here should we loop and try again with another
661 // file name? That is the standard recourse if open(O_EXCL)
662 // fails, though of course it should be protected against
663 // possible infinite looping too.
664
665 wxLogError(_("Failed to open temporary file."));
666
667 path.clear();
668 }
669 }
670
671 return path;
672 }
673
674 // ----------------------------------------------------------------------------
675 // directory operations
676 // ----------------------------------------------------------------------------
677
678 bool wxFileName::Mkdir( int perm, bool full )
679 {
680 return wxFileName::Mkdir( GetFullPath(), perm, full );
681 }
682
683 bool wxFileName::Mkdir( const wxString &dir, int perm, bool full )
684 {
685 if (full)
686 {
687 wxFileName filename(dir);
688 wxArrayString dirs = filename.GetDirs();
689 dirs.Add(filename.GetName());
690
691 size_t count = dirs.GetCount();
692 size_t i;
693 wxString currPath;
694 int noErrors = 0;
695 for ( i = 0; i < count; i++ )
696 {
697 currPath += dirs[i];
698
699 if (currPath.Last() == wxT(':'))
700 {
701 // Can't create a root directory so continue to next dir
702 currPath += wxFILE_SEP_PATH;
703 continue;
704 }
705
706 if (!DirExists(currPath))
707 if (!wxMkdir(currPath, perm))
708 noErrors ++;
709
710 if ( (i < (count-1)) )
711 currPath += wxFILE_SEP_PATH;
712 }
713
714 return (noErrors == 0);
715
716 }
717 else
718 return ::wxMkdir( dir, perm );
719 }
720
721 bool wxFileName::Rmdir()
722 {
723 return wxFileName::Rmdir( GetFullPath() );
724 }
725
726 bool wxFileName::Rmdir( const wxString &dir )
727 {
728 return ::wxRmdir( dir );
729 }
730
731 // ----------------------------------------------------------------------------
732 // path normalization
733 // ----------------------------------------------------------------------------
734
735 bool wxFileName::Normalize(wxPathNormalize flags,
736 const wxString& cwd,
737 wxPathFormat format)
738 {
739 // the existing path components
740 wxArrayString dirs = GetDirs();
741
742 // the path to prepend in front to make the path absolute
743 wxFileName curDir;
744
745 format = GetFormat(format);
746
747 // make the path absolute
748 if ( (flags & wxPATH_NORM_ABSOLUTE) && m_relative )
749 {
750 if ( cwd.empty() )
751 {
752 curDir.AssignCwd(GetVolume());
753 }
754 else // cwd provided
755 {
756 curDir.AssignDir(cwd);
757 }
758
759 #if 0
760 // the path may be not absolute because it doesn't have the volume name
761 // but in this case we shouldn't modify the directory components of it
762 // but just set the current volume
763 if ( !HasVolume() && curDir.HasVolume() )
764 {
765 SetVolume(curDir.GetVolume());
766
767 if ( IsAbsolute() )
768 {
769 // yes, it was the case - we don't need curDir then
770 curDir.Clear();
771 }
772 }
773 #endif
774 m_relative = FALSE;
775 }
776
777 // handle ~ stuff under Unix only
778 if ( (format == wxPATH_UNIX) && (flags & wxPATH_NORM_TILDE) )
779 {
780 if ( !dirs.IsEmpty() )
781 {
782 wxString dir = dirs[0u];
783 if ( !dir.empty() && dir[0u] == _T('~') )
784 {
785 curDir.AssignDir(wxGetUserHome(dir.c_str() + 1));
786
787 dirs.RemoveAt(0u);
788 }
789 }
790 }
791
792 // transform relative path into abs one
793 if ( curDir.IsOk() )
794 {
795 wxArrayString dirsNew = curDir.GetDirs();
796 size_t count = dirs.GetCount();
797 for ( size_t n = 0; n < count; n++ )
798 {
799 dirsNew.Add(dirs[n]);
800 }
801
802 dirs = dirsNew;
803 }
804
805 // now deal with ".", ".." and the rest
806 m_dirs.Empty();
807 size_t count = dirs.GetCount();
808 for ( size_t n = 0; n < count; n++ )
809 {
810 wxString dir = dirs[n];
811
812 if ( flags & wxPATH_NORM_DOTS )
813 {
814 if ( dir == wxT(".") )
815 {
816 // just ignore
817 continue;
818 }
819
820 if ( dir == wxT("..") )
821 {
822 if ( m_dirs.IsEmpty() )
823 {
824 wxLogError(_("The path '%s' contains too many \"..\"!"),
825 GetFullPath().c_str());
826 return FALSE;
827 }
828
829 m_dirs.RemoveAt(m_dirs.GetCount() - 1);
830 continue;
831 }
832 }
833
834 if ( flags & wxPATH_NORM_ENV_VARS )
835 {
836 dir = wxExpandEnvVars(dir);
837 }
838
839 if ( (flags & wxPATH_NORM_CASE) && !IsCaseSensitive(format) )
840 {
841 dir.MakeLower();
842 }
843
844 m_dirs.Add(dir);
845 }
846
847 if ( (flags & wxPATH_NORM_CASE) && !IsCaseSensitive(format) )
848 {
849 // VZ: expand env vars here too?
850
851 m_name.MakeLower();
852 m_ext.MakeLower();
853 }
854
855 #if defined(__WIN32__)
856 if ( (flags & wxPATH_NORM_LONG) && (format == wxPATH_DOS) )
857 {
858 Assign(GetLongPath());
859 }
860 #endif // Win32
861
862 return TRUE;
863 }
864
865 bool wxFileName::MakeRelativeTo(const wxString& pathBase, wxPathFormat format)
866 {
867 wxFileName fnBase(pathBase, format);
868
869 // get cwd only once - small time saving
870 wxString cwd = wxGetCwd();
871 Normalize(wxPATH_NORM_ALL, cwd, format);
872 fnBase.Normalize(wxPATH_NORM_ALL, cwd, format);
873
874 bool withCase = IsCaseSensitive(format);
875
876 // we can't do anything if the files live on different volumes
877 if ( !GetVolume().IsSameAs(fnBase.GetVolume(), withCase) )
878 {
879 // nothing done
880 return FALSE;
881 }
882
883 // same drive, so we don't need our volume
884 m_volume.clear();
885
886 // remove common directories starting at the top
887 while ( !m_dirs.IsEmpty() && !fnBase.m_dirs.IsEmpty() &&
888 m_dirs[0u].IsSameAs(fnBase.m_dirs[0u], withCase) )
889 {
890 m_dirs.RemoveAt(0);
891 fnBase.m_dirs.RemoveAt(0);
892 }
893
894 // add as many ".." as needed
895 size_t count = fnBase.m_dirs.GetCount();
896 for ( size_t i = 0; i < count; i++ )
897 {
898 m_dirs.Insert(wxT(".."), 0u);
899 }
900
901 m_relative = TRUE;
902
903 // we were modified
904 return TRUE;
905 }
906
907 // ----------------------------------------------------------------------------
908 // filename kind tests
909 // ----------------------------------------------------------------------------
910
911 bool wxFileName::SameAs(const wxFileName &filepath, wxPathFormat format)
912 {
913 wxFileName fn1 = *this,
914 fn2 = filepath;
915
916 // get cwd only once - small time saving
917 wxString cwd = wxGetCwd();
918 fn1.Normalize(wxPATH_NORM_ALL, cwd, format);
919 fn2.Normalize(wxPATH_NORM_ALL, cwd, format);
920
921 if ( fn1.GetFullPath() == fn2.GetFullPath() )
922 return TRUE;
923
924 // TODO: compare inodes for Unix, this works even when filenames are
925 // different but files are the same (symlinks) (VZ)
926
927 return FALSE;
928 }
929
930 /* static */
931 bool wxFileName::IsCaseSensitive( wxPathFormat format )
932 {
933 // only Unix filenames are truely case-sensitive
934 return GetFormat(format) == wxPATH_UNIX;
935 }
936
937 /* static */
938 wxString wxFileName::GetVolumeSeparator(wxPathFormat format)
939 {
940 wxString sepVol;
941
942 if ( (GetFormat(format) == wxPATH_DOS) ||
943 (GetFormat(format) == wxPATH_VMS) )
944 {
945 sepVol = wxFILE_SEP_DSK;
946 }
947 //else: leave empty
948
949 return sepVol;
950 }
951
952 /* static */
953 wxString wxFileName::GetPathSeparators(wxPathFormat format)
954 {
955 wxString seps;
956 switch ( GetFormat(format) )
957 {
958 case wxPATH_DOS:
959 // accept both as native APIs do but put the native one first as
960 // this is the one we use in GetFullPath()
961 seps << wxFILE_SEP_PATH_DOS << wxFILE_SEP_PATH_UNIX;
962 break;
963
964 default:
965 wxFAIL_MSG( _T("unknown wxPATH_XXX style") );
966 // fall through
967
968 case wxPATH_UNIX:
969 seps = wxFILE_SEP_PATH_UNIX;
970 break;
971
972 case wxPATH_MAC:
973 seps = wxFILE_SEP_PATH_MAC;
974 break;
975
976 case wxPATH_VMS:
977 seps = wxFILE_SEP_PATH_VMS;
978 break;
979 }
980
981 return seps;
982 }
983
984 /* static */
985 bool wxFileName::IsPathSeparator(wxChar ch, wxPathFormat format)
986 {
987 // wxString::Find() doesn't work as expected with NUL - it will always find
988 // it, so it is almost surely a bug if this function is called with NUL arg
989 wxASSERT_MSG( ch != _T('\0'), _T("shouldn't be called with NUL") );
990
991 return GetPathSeparators(format).Find(ch) != wxNOT_FOUND;
992 }
993
994 bool wxFileName::IsWild( wxPathFormat format )
995 {
996 // FIXME: this is probably false for Mac and this is surely wrong for most
997 // of Unix shells (think about "[...]")
998 (void)format;
999 return m_name.find_first_of(_T("*?")) != wxString::npos;
1000 }
1001
1002 // ----------------------------------------------------------------------------
1003 // path components manipulation
1004 // ----------------------------------------------------------------------------
1005
1006 void wxFileName::AppendDir( const wxString &dir )
1007 {
1008 m_dirs.Add( dir );
1009 }
1010
1011 void wxFileName::PrependDir( const wxString &dir )
1012 {
1013 m_dirs.Insert( dir, 0 );
1014 }
1015
1016 void wxFileName::InsertDir( int before, const wxString &dir )
1017 {
1018 m_dirs.Insert( dir, before );
1019 }
1020
1021 void wxFileName::RemoveDir( int pos )
1022 {
1023 m_dirs.Remove( (size_t)pos );
1024 }
1025
1026 // ----------------------------------------------------------------------------
1027 // accessors
1028 // ----------------------------------------------------------------------------
1029
1030 void wxFileName::SetFullName(const wxString& fullname)
1031 {
1032 SplitPath(fullname, NULL /* no path */, &m_name, &m_ext);
1033 }
1034
1035 wxString wxFileName::GetFullName() const
1036 {
1037 wxString fullname = m_name;
1038 if ( !m_ext.empty() )
1039 {
1040 fullname << wxFILE_SEP_EXT << m_ext;
1041 }
1042
1043 return fullname;
1044 }
1045
1046 wxString wxFileName::GetPath( bool add_separator, wxPathFormat format ) const
1047 {
1048 format = GetFormat( format );
1049
1050 wxString fullpath;
1051
1052 // the leading character
1053 if ( format == wxPATH_MAC && m_relative )
1054 {
1055 fullpath += wxFILE_SEP_PATH_MAC;
1056 }
1057 else if ( format == wxPATH_DOS )
1058 {
1059 if (!m_relative)
1060 fullpath += wxFILE_SEP_PATH_DOS;
1061 }
1062 else if ( format == wxPATH_UNIX )
1063 {
1064 if (!m_relative)
1065 fullpath += wxFILE_SEP_PATH_UNIX;
1066 }
1067
1068 // then concatenate all the path components using the path separator
1069 size_t dirCount = m_dirs.GetCount();
1070 if ( dirCount )
1071 {
1072 if ( format == wxPATH_VMS )
1073 {
1074 fullpath += wxT('[');
1075 }
1076
1077
1078 for ( size_t i = 0; i < dirCount; i++ )
1079 {
1080 // TODO: What to do with ".." under VMS
1081
1082 switch (format)
1083 {
1084 case wxPATH_MAC:
1085 {
1086 if (m_dirs[i] == wxT("."))
1087 break;
1088 if (m_dirs[i] != wxT("..")) // convert back from ".." to nothing
1089 fullpath += m_dirs[i];
1090 fullpath += wxT(':');
1091 break;
1092 }
1093 case wxPATH_DOS:
1094 {
1095 fullpath += m_dirs[i];
1096 fullpath += wxT('\\');
1097 break;
1098 }
1099 case wxPATH_UNIX:
1100 {
1101 fullpath += m_dirs[i];
1102 fullpath += wxT('/');
1103 break;
1104 }
1105 case wxPATH_VMS:
1106 {
1107 if (m_dirs[i] != wxT("..")) // convert back from ".." to nothing
1108 fullpath += m_dirs[i];
1109 if (i == dirCount-1)
1110 fullpath += wxT(']');
1111 else
1112 fullpath += wxT('.');
1113 break;
1114 }
1115 default:
1116 {
1117 wxFAIL_MSG( wxT("error") );
1118 }
1119 }
1120 }
1121 }
1122
1123
1124
1125 return fullpath;
1126 }
1127
1128 wxString wxFileName::GetFullPath( wxPathFormat format ) const
1129 {
1130 format = GetFormat(format);
1131
1132 wxString fullpath;
1133
1134 // first put the volume
1135 if ( !m_volume.empty() )
1136 {
1137 {
1138 // Special Windows UNC paths hack, part 2: undo what we did in
1139 // SplitPath() and make an UNC path if we have a drive which is not a
1140 // single letter (hopefully the network shares can't be one letter only
1141 // although I didn't find any authoritative docs on this)
1142 if ( format == wxPATH_DOS && m_volume.length() > 1 )
1143 {
1144 fullpath << wxFILE_SEP_PATH_DOS << wxFILE_SEP_PATH_DOS << m_volume;
1145 }
1146 else if ( format == wxPATH_DOS || format == wxPATH_VMS )
1147 {
1148 fullpath << m_volume << GetVolumeSeparator(format);
1149 }
1150 // else ignore
1151 }
1152 }
1153
1154 // the leading character
1155 if ( format == wxPATH_MAC && m_relative )
1156 {
1157 fullpath += wxFILE_SEP_PATH_MAC;
1158 }
1159 else if ( format == wxPATH_DOS )
1160 {
1161 if (!m_relative)
1162 fullpath += wxFILE_SEP_PATH_DOS;
1163 }
1164 else if ( format == wxPATH_UNIX )
1165 {
1166 if (!m_relative)
1167 fullpath += wxFILE_SEP_PATH_UNIX;
1168 }
1169
1170 // then concatenate all the path components using the path separator
1171 size_t dirCount = m_dirs.GetCount();
1172 if ( dirCount )
1173 {
1174 if ( format == wxPATH_VMS )
1175 {
1176 fullpath += wxT('[');
1177 }
1178
1179
1180 for ( size_t i = 0; i < dirCount; i++ )
1181 {
1182 // TODO: What to do with ".." under VMS
1183
1184 switch (format)
1185 {
1186 case wxPATH_MAC:
1187 {
1188 if (m_dirs[i] == wxT("."))
1189 break;
1190 if (m_dirs[i] != wxT("..")) // convert back from ".." to nothing
1191 fullpath += m_dirs[i];
1192 fullpath += wxT(':');
1193 break;
1194 }
1195 case wxPATH_DOS:
1196 {
1197 fullpath += m_dirs[i];
1198 fullpath += wxT('\\');
1199 break;
1200 }
1201 case wxPATH_UNIX:
1202 {
1203 fullpath += m_dirs[i];
1204 fullpath += wxT('/');
1205 break;
1206 }
1207 case wxPATH_VMS:
1208 {
1209 if (m_dirs[i] != wxT("..")) // convert back from ".." to nothing
1210 fullpath += m_dirs[i];
1211 if (i == dirCount-1)
1212 fullpath += wxT(']');
1213 else
1214 fullpath += wxT('.');
1215 break;
1216 }
1217 default:
1218 {
1219 wxFAIL_MSG( wxT("error") );
1220 }
1221 }
1222 }
1223 }
1224
1225 // finally add the file name and extension
1226 fullpath += GetFullName();
1227
1228 return fullpath;
1229 }
1230
1231 // Return the short form of the path (returns identity on non-Windows platforms)
1232 wxString wxFileName::GetShortPath() const
1233 {
1234 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__)
1235 wxString path(GetFullPath());
1236 wxString pathOut;
1237 DWORD sz = ::GetShortPathName(path, NULL, 0);
1238 bool ok = sz != 0;
1239 if ( ok )
1240 {
1241 ok = ::GetShortPathName
1242 (
1243 path,
1244 pathOut.GetWriteBuf(sz),
1245 sz
1246 ) != 0;
1247 pathOut.UngetWriteBuf();
1248 }
1249 if (ok)
1250 return pathOut;
1251
1252 return path;
1253 #else
1254 return GetFullPath();
1255 #endif
1256 }
1257
1258 // Return the long form of the path (returns identity on non-Windows platforms)
1259 wxString wxFileName::GetLongPath() const
1260 {
1261 wxString pathOut,
1262 path = GetFullPath();
1263
1264 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1265 bool success = FALSE;
1266
1267 // VZ: this code was disabled, why?
1268 #if 0 // wxUSE_DYNAMIC_LOADER
1269 typedef DWORD (*GET_LONG_PATH_NAME)(const wxChar *, wxChar *, DWORD);
1270
1271 static bool s_triedToLoad = FALSE;
1272
1273 if ( !s_triedToLoad )
1274 {
1275 s_triedToLoad = TRUE;
1276 wxDynamicLibrary dllKernel(_T("kernel32"));
1277 if ( dllKernel.IsLoaded() )
1278 {
1279 // may succeed or fail depending on the Windows version
1280 static GET_LONG_PATH_NAME s_pfnGetLongPathName = NULL;
1281 #ifdef _UNICODE
1282 s_pfnGetLongPathName = (GET_LONG_PATH_NAME) dllKernel.GetSymbol(_T("GetLongPathNameW"));
1283 #else
1284 s_pfnGetLongPathName = (GET_LONG_PATH_NAME) dllKernel.GetSymbol(_T("GetLongPathNameA"));
1285 #endif
1286
1287 if ( s_pfnGetLongPathName )
1288 {
1289 DWORD dwSize = (*s_pfnGetLongPathName)(path, NULL, 0);
1290 bool ok = dwSize > 0;
1291
1292 if ( ok )
1293 {
1294 DWORD sz = (*s_pfnGetLongPathName)(path, NULL, 0);
1295 ok = sz != 0;
1296 if ( ok )
1297 {
1298 ok = (*s_pfnGetLongPathName)
1299 (
1300 path,
1301 pathOut.GetWriteBuf(sz),
1302 sz
1303 ) != 0;
1304 pathOut.UngetWriteBuf();
1305
1306 success = TRUE;
1307 }
1308 }
1309 }
1310 }
1311 }
1312 if (success)
1313 return pathOut;
1314 #endif // wxUSE_DYNAMIC_LOADER
1315
1316 if (!success)
1317 {
1318 // The OS didn't support GetLongPathName, or some other error.
1319 // We need to call FindFirstFile on each component in turn.
1320
1321 WIN32_FIND_DATA findFileData;
1322 HANDLE hFind;
1323 pathOut = wxEmptyString;
1324
1325 wxArrayString dirs = GetDirs();
1326 dirs.Add(GetFullName());
1327
1328 wxString tmpPath;
1329
1330 size_t count = dirs.GetCount();
1331 for ( size_t i = 0; i < count; i++ )
1332 {
1333 // We're using pathOut to collect the long-name path, but using a
1334 // temporary for appending the last path component which may be
1335 // short-name
1336 tmpPath = pathOut + dirs[i];
1337
1338 if ( tmpPath.empty() )
1339 continue;
1340
1341 if ( tmpPath.Last() == wxT(':') )
1342 {
1343 // Can't pass a drive and root dir to FindFirstFile,
1344 // so continue to next dir
1345 tmpPath += wxFILE_SEP_PATH;
1346 pathOut = tmpPath;
1347 continue;
1348 }
1349
1350 hFind = ::FindFirstFile(tmpPath, &findFileData);
1351 if (hFind == INVALID_HANDLE_VALUE)
1352 {
1353 // Error: return immediately with the original path
1354 return path;
1355 }
1356
1357 pathOut += findFileData.cFileName;
1358 if ( (i < (count-1)) )
1359 pathOut += wxFILE_SEP_PATH;
1360
1361 ::FindClose(hFind);
1362 }
1363 }
1364 #else // !Win32
1365 pathOut = path;
1366 #endif // Win32/!Win32
1367
1368 return pathOut;
1369 }
1370
1371 wxPathFormat wxFileName::GetFormat( wxPathFormat format )
1372 {
1373 if (format == wxPATH_NATIVE)
1374 {
1375 #if defined(__WXMSW__) || defined(__WXPM__) || defined(__DOS__)
1376 format = wxPATH_DOS;
1377 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1378 format = wxPATH_MAC;
1379 #elif defined(__VMS)
1380 format = wxPATH_VMS;
1381 #else
1382 format = wxPATH_UNIX;
1383 #endif
1384 }
1385 return format;
1386 }
1387
1388 // ----------------------------------------------------------------------------
1389 // path splitting function
1390 // ----------------------------------------------------------------------------
1391
1392 /* static */
1393 void wxFileName::SplitPath(const wxString& fullpathWithVolume,
1394 wxString *pstrVolume,
1395 wxString *pstrPath,
1396 wxString *pstrName,
1397 wxString *pstrExt,
1398 wxPathFormat format)
1399 {
1400 format = GetFormat(format);
1401
1402 wxString fullpath = fullpathWithVolume;
1403
1404 // under VMS the end of the path is ']', not the path separator used to
1405 // separate the components
1406 wxString sepPath = format == wxPATH_VMS ? wxString(_T(']'))
1407 : GetPathSeparators(format);
1408
1409 // special Windows UNC paths hack: transform \\share\path into share:path
1410 if ( format == wxPATH_DOS )
1411 {
1412 if ( fullpath.length() >= 4 &&
1413 fullpath[0u] == wxFILE_SEP_PATH_DOS &&
1414 fullpath[1u] == wxFILE_SEP_PATH_DOS )
1415 {
1416 fullpath.erase(0, 2);
1417
1418 size_t posFirstSlash = fullpath.find_first_of(sepPath);
1419 if ( posFirstSlash != wxString::npos )
1420 {
1421 fullpath[posFirstSlash] = wxFILE_SEP_DSK;
1422
1423 // UNC paths are always absolute, right? (FIXME)
1424 fullpath.insert(posFirstSlash + 1, wxFILE_SEP_PATH_DOS);
1425 }
1426 }
1427 }
1428
1429 // We separate the volume here
1430 if ( format == wxPATH_DOS || format == wxPATH_VMS )
1431 {
1432 wxString sepVol = GetVolumeSeparator(format);
1433
1434 size_t posFirstColon = fullpath.find_first_of(sepVol);
1435 if ( posFirstColon != wxString::npos )
1436 {
1437 if ( pstrVolume )
1438 {
1439 *pstrVolume = fullpath.Left(posFirstColon);
1440 }
1441
1442 // remove the volume name and the separator from the full path
1443 fullpath.erase(0, posFirstColon + sepVol.length());
1444 }
1445 }
1446
1447 // find the positions of the last dot and last path separator in the path
1448 size_t posLastDot = fullpath.find_last_of(wxFILE_SEP_EXT);
1449 size_t posLastSlash = fullpath.find_last_of(sepPath);
1450
1451 if ( (posLastDot != wxString::npos) &&
1452 ((format == wxPATH_UNIX) || (format == wxPATH_VMS)) )
1453 {
1454 if ( (posLastDot == 0) ||
1455 (fullpath[posLastDot - 1] == sepPath[0u] ) )
1456 {
1457 // under Unix and VMS, dot may be (and commonly is) the first
1458 // character of the filename, don't treat the entire filename as
1459 // extension in this case
1460 posLastDot = wxString::npos;
1461 }
1462 }
1463
1464 // if we do have a dot and a slash, check that the dot is in the name part
1465 if ( (posLastDot != wxString::npos) &&
1466 (posLastSlash != wxString::npos) &&
1467 (posLastDot < posLastSlash) )
1468 {
1469 // the dot is part of the path, not the start of the extension
1470 posLastDot = wxString::npos;
1471 }
1472
1473 // now fill in the variables provided by user
1474 if ( pstrPath )
1475 {
1476 if ( posLastSlash == wxString::npos )
1477 {
1478 // no path at all
1479 pstrPath->Empty();
1480 }
1481 else
1482 {
1483 // take everything up to the path separator but take care to make
1484 // the path equal to something like '/', not empty, for the files
1485 // immediately under root directory
1486 size_t len = posLastSlash;
1487
1488 // this rule does not apply to mac since we do not start with colons (sep)
1489 // except for relative paths
1490 if ( !len && format != wxPATH_MAC)
1491 len++;
1492
1493 *pstrPath = fullpath.Left(len);
1494
1495 // special VMS hack: remove the initial bracket
1496 if ( format == wxPATH_VMS )
1497 {
1498 if ( (*pstrPath)[0u] == _T('[') )
1499 pstrPath->erase(0, 1);
1500 }
1501 }
1502 }
1503
1504 if ( pstrName )
1505 {
1506 // take all characters starting from the one after the last slash and
1507 // up to, but excluding, the last dot
1508 size_t nStart = posLastSlash == wxString::npos ? 0 : posLastSlash + 1;
1509 size_t count;
1510 if ( posLastDot == wxString::npos )
1511 {
1512 // take all until the end
1513 count = wxString::npos;
1514 }
1515 else if ( posLastSlash == wxString::npos )
1516 {
1517 count = posLastDot;
1518 }
1519 else // have both dot and slash
1520 {
1521 count = posLastDot - posLastSlash - 1;
1522 }
1523
1524 *pstrName = fullpath.Mid(nStart, count);
1525 }
1526
1527 if ( pstrExt )
1528 {
1529 if ( posLastDot == wxString::npos )
1530 {
1531 // no extension
1532 pstrExt->Empty();
1533 }
1534 else
1535 {
1536 // take everything after the dot
1537 *pstrExt = fullpath.Mid(posLastDot + 1);
1538 }
1539 }
1540 }
1541
1542 /* static */
1543 void wxFileName::SplitPath(const wxString& fullpath,
1544 wxString *path,
1545 wxString *name,
1546 wxString *ext,
1547 wxPathFormat format)
1548 {
1549 wxString volume;
1550 SplitPath(fullpath, &volume, path, name, ext, format);
1551
1552 if ( path && !volume.empty() )
1553 {
1554 path->Prepend(volume + GetVolumeSeparator(format));
1555 }
1556 }
1557
1558 // ----------------------------------------------------------------------------
1559 // time functions
1560 // ----------------------------------------------------------------------------
1561
1562 bool wxFileName::SetTimes(const wxDateTime *dtCreate,
1563 const wxDateTime *dtAccess,
1564 const wxDateTime *dtMod)
1565 {
1566 #if defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
1567 if ( !dtAccess && !dtMod )
1568 {
1569 // can't modify the creation time anyhow, don't try
1570 return TRUE;
1571 }
1572
1573 // if dtAccess or dtMod is not specified, use the other one (which must be
1574 // non NULL because of the test above) for both times
1575 utimbuf utm;
1576 utm.actime = dtAccess ? dtAccess->GetTicks() : dtMod->GetTicks();
1577 utm.modtime = dtMod ? dtMod->GetTicks() : dtAccess->GetTicks();
1578 if ( utime(GetFullPath(), &utm) == 0 )
1579 {
1580 return TRUE;
1581 }
1582 #elif defined(__WIN32__)
1583 wxFileHandle fh(GetFullPath());
1584 if ( fh.IsOk() )
1585 {
1586 FILETIME ftAccess, ftCreate, ftWrite;
1587
1588 if ( dtCreate )
1589 ConvertWxToFileTime(&ftCreate, *dtCreate);
1590 if ( dtAccess )
1591 ConvertWxToFileTime(&ftAccess, *dtAccess);
1592 if ( dtMod )
1593 ConvertWxToFileTime(&ftWrite, *dtMod);
1594
1595 if ( ::SetFileTime(fh,
1596 dtCreate ? &ftCreate : NULL,
1597 dtAccess ? &ftAccess : NULL,
1598 dtMod ? &ftWrite : NULL) )
1599 {
1600 return TRUE;
1601 }
1602 }
1603 #else // other platform
1604 #endif // platforms
1605
1606 wxLogSysError(_("Failed to modify file times for '%s'"),
1607 GetFullPath().c_str());
1608
1609 return FALSE;
1610 }
1611
1612 bool wxFileName::Touch()
1613 {
1614 #if defined(__UNIX_LIKE__)
1615 // under Unix touching file is simple: just pass NULL to utime()
1616 if ( utime(GetFullPath(), NULL) == 0 )
1617 {
1618 return TRUE;
1619 }
1620
1621 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
1622
1623 return FALSE;
1624 #else // other platform
1625 wxDateTime dtNow = wxDateTime::Now();
1626
1627 return SetTimes(NULL /* don't change create time */, &dtNow, &dtNow);
1628 #endif // platforms
1629 }
1630
1631 bool wxFileName::GetTimes(wxDateTime *dtAccess,
1632 wxDateTime *dtMod,
1633 wxDateTime *dtChange) const
1634 {
1635 #if defined(__UNIX_LIKE__) || defined(__WXMAC__) || (defined(__DOS__) && defined(__WATCOMC__))
1636 wxStructStat stBuf;
1637 if ( wxStat(GetFullPath(), &stBuf) == 0 )
1638 {
1639 if ( dtAccess )
1640 dtAccess->Set(stBuf.st_atime);
1641 if ( dtMod )
1642 dtMod->Set(stBuf.st_mtime);
1643 if ( dtChange )
1644 dtChange->Set(stBuf.st_ctime);
1645
1646 return TRUE;
1647 }
1648 #elif defined(__WIN32__)
1649 wxFileHandle fh(GetFullPath());
1650 if ( fh.IsOk() )
1651 {
1652 FILETIME ftAccess, ftCreate, ftWrite;
1653
1654 if ( ::GetFileTime(fh,
1655 dtMod ? &ftCreate : NULL,
1656 dtAccess ? &ftAccess : NULL,
1657 dtChange ? &ftWrite : NULL) )
1658 {
1659 if ( dtMod )
1660 ConvertFileTimeToWx(dtMod, ftCreate);
1661 if ( dtAccess )
1662 ConvertFileTimeToWx(dtAccess, ftAccess);
1663 if ( dtChange )
1664 ConvertFileTimeToWx(dtChange, ftWrite);
1665
1666 return TRUE;
1667 }
1668 }
1669 #else // other platform
1670 #endif // platforms
1671
1672 wxLogSysError(_("Failed to retrieve file times for '%s'"),
1673 GetFullPath().c_str());
1674
1675 return FALSE;
1676 }
1677
1678 #ifdef __WXMAC__
1679
1680 const short kMacExtensionMaxLength = 16 ;
1681 typedef struct
1682 {
1683 char m_ext[kMacExtensionMaxLength] ;
1684 OSType m_type ;
1685 OSType m_creator ;
1686 } MacDefaultExtensionRecord ;
1687
1688 #include "wx/dynarray.h"
1689 WX_DECLARE_OBJARRAY(MacDefaultExtensionRecord, MacDefaultExtensionArray) ;
1690 #include "wx/arrimpl.cpp"
1691 WX_DEFINE_OBJARRAY(MacDefaultExtensionArray) ;
1692
1693 MacDefaultExtensionArray gMacDefaultExtensions ;
1694 bool gMacDefaultExtensionsInited = false ;
1695
1696 static void MacEnsureDefaultExtensionsLoaded()
1697 {
1698 if ( !gMacDefaultExtensionsInited )
1699 {
1700 // load the default extensions
1701 MacDefaultExtensionRecord defaults[] =
1702 {
1703 { "txt" , 'TEXT' , 'ttxt' } ,
1704
1705 } ;
1706 // we could load the pc exchange prefs here too
1707
1708 for ( int i = 0 ; i < WXSIZEOF( defaults ) ; ++i )
1709 {
1710 gMacDefaultExtensions.Add( defaults[i] ) ;
1711 }
1712 gMacDefaultExtensionsInited = true ;
1713 }
1714 }
1715 bool wxFileName::MacSetTypeAndCreator( wxUint32 type , wxUint32 creator )
1716 {
1717 FInfo fndrInfo ;
1718 FSSpec spec ;
1719 wxMacFilename2FSSpec(GetFullPath(),&spec) ;
1720 OSErr err = FSpGetFInfo( &spec , &fndrInfo ) ;
1721 wxCHECK( err == noErr , false ) ;
1722
1723 fndrInfo.fdType = type ;
1724 fndrInfo.fdCreator = creator ;
1725 FSpSetFInfo( &spec , &fndrInfo ) ;
1726 return true ;
1727 }
1728
1729 bool wxFileName::MacGetTypeAndCreator( wxUint32 *type , wxUint32 *creator )
1730 {
1731 FInfo fndrInfo ;
1732 FSSpec spec ;
1733 wxMacFilename2FSSpec(GetFullPath(),&spec) ;
1734 OSErr err = FSpGetFInfo( &spec , &fndrInfo ) ;
1735 wxCHECK( err == noErr , false ) ;
1736
1737 *type = fndrInfo.fdType ;
1738 *creator = fndrInfo.fdCreator ;
1739 return true ;
1740 }
1741
1742 bool wxFileName::MacSetDefaultTypeAndCreator()
1743 {
1744 wxUint32 type , creator ;
1745 if ( wxFileName::MacFindDefaultTypeAndCreator(GetExt() , &type ,
1746 &creator ) )
1747 {
1748 return MacSetTypeAndCreator( type , creator ) ;
1749 }
1750 return false;
1751 }
1752
1753 bool wxFileName::MacFindDefaultTypeAndCreator( const wxString& ext , wxUint32 *type , wxUint32 *creator )
1754 {
1755 MacEnsureDefaultExtensionsLoaded() ;
1756 wxString extl = ext.Lower() ;
1757 for( int i = gMacDefaultExtensions.Count() - 1 ; i >= 0 ; --i )
1758 {
1759 if ( gMacDefaultExtensions.Item(i).m_ext == extl )
1760 {
1761 *type = gMacDefaultExtensions.Item(i).m_type ;
1762 *creator = gMacDefaultExtensions.Item(i).m_creator ;
1763 return true ;
1764 }
1765 }
1766 return false ;
1767 }
1768
1769 void wxFileName::MacRegisterDefaultTypeAndCreator( const wxString& ext , wxUint32 type , wxUint32 creator )
1770 {
1771 MacEnsureDefaultExtensionsLoaded() ;
1772 MacDefaultExtensionRecord rec ;
1773 rec.m_type = type ;
1774 rec.m_creator = creator ;
1775 strncpy( rec.m_ext , ext.Lower().c_str() , kMacExtensionMaxLength ) ;
1776 gMacDefaultExtensions.Add( rec ) ;
1777 }
1778 #endif
1779