]> git.saurik.com Git - wxWidgets.git/blob - src/common/filename.cpp
fixed the menu bug introduced by the previous commit
[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(int 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, wxPathFormat format ) const
1047 {
1048 // Should add_seperator parameter be used?
1049
1050 format = GetFormat( format );
1051
1052 wxString fullpath;
1053
1054 // the leading character
1055 if ( format == wxPATH_MAC && m_relative )
1056 {
1057 fullpath += wxFILE_SEP_PATH_MAC;
1058 }
1059 else if ( format == wxPATH_DOS )
1060 {
1061 if (!m_relative)
1062 fullpath += wxFILE_SEP_PATH_DOS;
1063 }
1064 else if ( format == wxPATH_UNIX )
1065 {
1066 if (!m_relative)
1067 fullpath += wxFILE_SEP_PATH_UNIX;
1068 }
1069
1070 // then concatenate all the path components using the path separator
1071 size_t dirCount = m_dirs.GetCount();
1072 if ( dirCount )
1073 {
1074 if ( format == wxPATH_VMS )
1075 {
1076 fullpath += wxT('[');
1077 }
1078
1079
1080 for ( size_t i = 0; i < dirCount; i++ )
1081 {
1082 // TODO: What to do with ".." under VMS
1083
1084 switch (format)
1085 {
1086 case wxPATH_MAC:
1087 {
1088 if (m_dirs[i] == wxT("."))
1089 break;
1090 if (m_dirs[i] != wxT("..")) // convert back from ".." to nothing
1091 fullpath += m_dirs[i];
1092 fullpath += wxT(':');
1093 break;
1094 }
1095 case wxPATH_DOS:
1096 {
1097 fullpath += m_dirs[i];
1098 fullpath += wxT('\\');
1099 break;
1100 }
1101 case wxPATH_UNIX:
1102 {
1103 fullpath += m_dirs[i];
1104 fullpath += wxT('/');
1105 break;
1106 }
1107 case wxPATH_VMS:
1108 {
1109 if (m_dirs[i] != wxT("..")) // convert back from ".." to nothing
1110 fullpath += m_dirs[i];
1111 if (i == dirCount-1)
1112 fullpath += wxT(']');
1113 else
1114 fullpath += wxT('.');
1115 break;
1116 }
1117 default:
1118 {
1119 wxFAIL_MSG( wxT("error") );
1120 }
1121 }
1122 }
1123 }
1124
1125
1126
1127 return fullpath;
1128 }
1129
1130 wxString wxFileName::GetFullPath( wxPathFormat format ) const
1131 {
1132 format = GetFormat(format);
1133
1134 wxString fullpath;
1135
1136 // first put the volume
1137 if ( !m_volume.empty() )
1138 {
1139 {
1140 // Special Windows UNC paths hack, part 2: undo what we did in
1141 // SplitPath() and make an UNC path if we have a drive which is not a
1142 // single letter (hopefully the network shares can't be one letter only
1143 // although I didn't find any authoritative docs on this)
1144 if ( format == wxPATH_DOS && m_volume.length() > 1 )
1145 {
1146 fullpath << wxFILE_SEP_PATH_DOS << wxFILE_SEP_PATH_DOS << m_volume;
1147 }
1148 else if ( format == wxPATH_DOS || format == wxPATH_VMS )
1149 {
1150 fullpath << m_volume << GetVolumeSeparator(format);
1151 }
1152 // else ignore
1153 }
1154 }
1155
1156 // the leading character
1157 if ( format == wxPATH_MAC && m_relative )
1158 {
1159 fullpath += wxFILE_SEP_PATH_MAC;
1160 }
1161 else if ( format == wxPATH_DOS )
1162 {
1163 if (!m_relative)
1164 fullpath += wxFILE_SEP_PATH_DOS;
1165 }
1166 else if ( format == wxPATH_UNIX )
1167 {
1168 if (!m_relative)
1169 fullpath += wxFILE_SEP_PATH_UNIX;
1170 }
1171
1172 // then concatenate all the path components using the path separator
1173 size_t dirCount = m_dirs.GetCount();
1174 if ( dirCount )
1175 {
1176 if ( format == wxPATH_VMS )
1177 {
1178 fullpath += wxT('[');
1179 }
1180
1181
1182 for ( size_t i = 0; i < dirCount; i++ )
1183 {
1184 // TODO: What to do with ".." under VMS
1185
1186 switch (format)
1187 {
1188 case wxPATH_MAC:
1189 {
1190 if (m_dirs[i] == wxT("."))
1191 break;
1192 if (m_dirs[i] != wxT("..")) // convert back from ".." to nothing
1193 fullpath += m_dirs[i];
1194 fullpath += wxT(':');
1195 break;
1196 }
1197 case wxPATH_DOS:
1198 {
1199 fullpath += m_dirs[i];
1200 fullpath += wxT('\\');
1201 break;
1202 }
1203 case wxPATH_UNIX:
1204 {
1205 fullpath += m_dirs[i];
1206 fullpath += wxT('/');
1207 break;
1208 }
1209 case wxPATH_VMS:
1210 {
1211 if (m_dirs[i] != wxT("..")) // convert back from ".." to nothing
1212 fullpath += m_dirs[i];
1213 if (i == dirCount-1)
1214 fullpath += wxT(']');
1215 else
1216 fullpath += wxT('.');
1217 break;
1218 }
1219 default:
1220 {
1221 wxFAIL_MSG( wxT("error") );
1222 }
1223 }
1224 }
1225 }
1226
1227 // finally add the file name and extension
1228 fullpath += GetFullName();
1229
1230 return fullpath;
1231 }
1232
1233 // Return the short form of the path (returns identity on non-Windows platforms)
1234 wxString wxFileName::GetShortPath() const
1235 {
1236 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__)
1237 wxString path(GetFullPath());
1238 wxString pathOut;
1239 DWORD sz = ::GetShortPathName(path, NULL, 0);
1240 bool ok = sz != 0;
1241 if ( ok )
1242 {
1243 ok = ::GetShortPathName
1244 (
1245 path,
1246 pathOut.GetWriteBuf(sz),
1247 sz
1248 ) != 0;
1249 pathOut.UngetWriteBuf();
1250 }
1251 if (ok)
1252 return pathOut;
1253
1254 return path;
1255 #else
1256 return GetFullPath();
1257 #endif
1258 }
1259
1260 // Return the long form of the path (returns identity on non-Windows platforms)
1261 wxString wxFileName::GetLongPath() const
1262 {
1263 wxString pathOut,
1264 path = GetFullPath();
1265
1266 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1267 bool success = FALSE;
1268
1269 // VZ: this code was disabled, why?
1270 #if 0 // wxUSE_DYNAMIC_LOADER
1271 typedef DWORD (*GET_LONG_PATH_NAME)(const wxChar *, wxChar *, DWORD);
1272
1273 static bool s_triedToLoad = FALSE;
1274
1275 if ( !s_triedToLoad )
1276 {
1277 s_triedToLoad = TRUE;
1278 wxDynamicLibrary dllKernel(_T("kernel32"));
1279 if ( dllKernel.IsLoaded() )
1280 {
1281 // may succeed or fail depending on the Windows version
1282 static GET_LONG_PATH_NAME s_pfnGetLongPathName = NULL;
1283 #ifdef _UNICODE
1284 s_pfnGetLongPathName = (GET_LONG_PATH_NAME) dllKernel.GetSymbol(_T("GetLongPathNameW"));
1285 #else
1286 s_pfnGetLongPathName = (GET_LONG_PATH_NAME) dllKernel.GetSymbol(_T("GetLongPathNameA"));
1287 #endif
1288
1289 if ( s_pfnGetLongPathName )
1290 {
1291 DWORD dwSize = (*s_pfnGetLongPathName)(path, NULL, 0);
1292 bool ok = dwSize > 0;
1293
1294 if ( ok )
1295 {
1296 DWORD sz = (*s_pfnGetLongPathName)(path, NULL, 0);
1297 ok = sz != 0;
1298 if ( ok )
1299 {
1300 ok = (*s_pfnGetLongPathName)
1301 (
1302 path,
1303 pathOut.GetWriteBuf(sz),
1304 sz
1305 ) != 0;
1306 pathOut.UngetWriteBuf();
1307
1308 success = TRUE;
1309 }
1310 }
1311 }
1312 }
1313 }
1314 if (success)
1315 return pathOut;
1316 #endif // wxUSE_DYNAMIC_LOADER
1317
1318 if (!success)
1319 {
1320 // The OS didn't support GetLongPathName, or some other error.
1321 // We need to call FindFirstFile on each component in turn.
1322
1323 WIN32_FIND_DATA findFileData;
1324 HANDLE hFind;
1325 pathOut = wxEmptyString;
1326
1327 wxArrayString dirs = GetDirs();
1328 dirs.Add(GetFullName());
1329
1330 wxString tmpPath;
1331
1332 size_t count = dirs.GetCount();
1333 for ( size_t i = 0; i < count; i++ )
1334 {
1335 // We're using pathOut to collect the long-name path, but using a
1336 // temporary for appending the last path component which may be
1337 // short-name
1338 tmpPath = pathOut + dirs[i];
1339
1340 if ( tmpPath.empty() )
1341 continue;
1342
1343 if ( tmpPath.Last() == wxT(':') )
1344 {
1345 // Can't pass a drive and root dir to FindFirstFile,
1346 // so continue to next dir
1347 tmpPath += wxFILE_SEP_PATH;
1348 pathOut = tmpPath;
1349 continue;
1350 }
1351
1352 hFind = ::FindFirstFile(tmpPath, &findFileData);
1353 if (hFind == INVALID_HANDLE_VALUE)
1354 {
1355 // Error: return immediately with the original path
1356 return path;
1357 }
1358
1359 pathOut += findFileData.cFileName;
1360 if ( (i < (count-1)) )
1361 pathOut += wxFILE_SEP_PATH;
1362
1363 ::FindClose(hFind);
1364 }
1365 }
1366 #else // !Win32
1367 pathOut = path;
1368 #endif // Win32/!Win32
1369
1370 return pathOut;
1371 }
1372
1373 wxPathFormat wxFileName::GetFormat( wxPathFormat format )
1374 {
1375 if (format == wxPATH_NATIVE)
1376 {
1377 #if defined(__WXMSW__) || defined(__WXPM__) || defined(__DOS__)
1378 format = wxPATH_DOS;
1379 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1380 format = wxPATH_MAC;
1381 #elif defined(__VMS)
1382 format = wxPATH_VMS;
1383 #else
1384 format = wxPATH_UNIX;
1385 #endif
1386 }
1387 return format;
1388 }
1389
1390 // ----------------------------------------------------------------------------
1391 // path splitting function
1392 // ----------------------------------------------------------------------------
1393
1394 /* static */
1395 void wxFileName::SplitPath(const wxString& fullpathWithVolume,
1396 wxString *pstrVolume,
1397 wxString *pstrPath,
1398 wxString *pstrName,
1399 wxString *pstrExt,
1400 wxPathFormat format)
1401 {
1402 format = GetFormat(format);
1403
1404 wxString fullpath = fullpathWithVolume;
1405
1406 // under VMS the end of the path is ']', not the path separator used to
1407 // separate the components
1408 wxString sepPath = format == wxPATH_VMS ? wxString(_T(']'))
1409 : GetPathSeparators(format);
1410
1411 // special Windows UNC paths hack: transform \\share\path into share:path
1412 if ( format == wxPATH_DOS )
1413 {
1414 if ( fullpath.length() >= 4 &&
1415 fullpath[0u] == wxFILE_SEP_PATH_DOS &&
1416 fullpath[1u] == wxFILE_SEP_PATH_DOS )
1417 {
1418 fullpath.erase(0, 2);
1419
1420 size_t posFirstSlash = fullpath.find_first_of(sepPath);
1421 if ( posFirstSlash != wxString::npos )
1422 {
1423 fullpath[posFirstSlash] = wxFILE_SEP_DSK;
1424
1425 // UNC paths are always absolute, right? (FIXME)
1426 fullpath.insert(posFirstSlash + 1, wxFILE_SEP_PATH_DOS);
1427 }
1428 }
1429 }
1430
1431 // We separate the volume here
1432 if ( format == wxPATH_DOS || format == wxPATH_VMS )
1433 {
1434 wxString sepVol = GetVolumeSeparator(format);
1435
1436 size_t posFirstColon = fullpath.find_first_of(sepVol);
1437 if ( posFirstColon != wxString::npos )
1438 {
1439 if ( pstrVolume )
1440 {
1441 *pstrVolume = fullpath.Left(posFirstColon);
1442 }
1443
1444 // remove the volume name and the separator from the full path
1445 fullpath.erase(0, posFirstColon + sepVol.length());
1446 }
1447 }
1448
1449 // find the positions of the last dot and last path separator in the path
1450 size_t posLastDot = fullpath.find_last_of(wxFILE_SEP_EXT);
1451 size_t posLastSlash = fullpath.find_last_of(sepPath);
1452
1453 if ( (posLastDot != wxString::npos) &&
1454 ((format == wxPATH_UNIX) || (format == wxPATH_VMS)) )
1455 {
1456 if ( (posLastDot == 0) ||
1457 (fullpath[posLastDot - 1] == sepPath[0u] ) )
1458 {
1459 // under Unix and VMS, dot may be (and commonly is) the first
1460 // character of the filename, don't treat the entire filename as
1461 // extension in this case
1462 posLastDot = wxString::npos;
1463 }
1464 }
1465
1466 // if we do have a dot and a slash, check that the dot is in the name part
1467 if ( (posLastDot != wxString::npos) &&
1468 (posLastSlash != wxString::npos) &&
1469 (posLastDot < posLastSlash) )
1470 {
1471 // the dot is part of the path, not the start of the extension
1472 posLastDot = wxString::npos;
1473 }
1474
1475 // now fill in the variables provided by user
1476 if ( pstrPath )
1477 {
1478 if ( posLastSlash == wxString::npos )
1479 {
1480 // no path at all
1481 pstrPath->Empty();
1482 }
1483 else
1484 {
1485 // take everything up to the path separator but take care to make
1486 // the path equal to something like '/', not empty, for the files
1487 // immediately under root directory
1488 size_t len = posLastSlash;
1489
1490 // this rule does not apply to mac since we do not start with colons (sep)
1491 // except for relative paths
1492 if ( !len && format != wxPATH_MAC)
1493 len++;
1494
1495 *pstrPath = fullpath.Left(len);
1496
1497 // special VMS hack: remove the initial bracket
1498 if ( format == wxPATH_VMS )
1499 {
1500 if ( (*pstrPath)[0u] == _T('[') )
1501 pstrPath->erase(0, 1);
1502 }
1503 }
1504 }
1505
1506 if ( pstrName )
1507 {
1508 // take all characters starting from the one after the last slash and
1509 // up to, but excluding, the last dot
1510 size_t nStart = posLastSlash == wxString::npos ? 0 : posLastSlash + 1;
1511 size_t count;
1512 if ( posLastDot == wxString::npos )
1513 {
1514 // take all until the end
1515 count = wxString::npos;
1516 }
1517 else if ( posLastSlash == wxString::npos )
1518 {
1519 count = posLastDot;
1520 }
1521 else // have both dot and slash
1522 {
1523 count = posLastDot - posLastSlash - 1;
1524 }
1525
1526 *pstrName = fullpath.Mid(nStart, count);
1527 }
1528
1529 if ( pstrExt )
1530 {
1531 if ( posLastDot == wxString::npos )
1532 {
1533 // no extension
1534 pstrExt->Empty();
1535 }
1536 else
1537 {
1538 // take everything after the dot
1539 *pstrExt = fullpath.Mid(posLastDot + 1);
1540 }
1541 }
1542 }
1543
1544 /* static */
1545 void wxFileName::SplitPath(const wxString& fullpath,
1546 wxString *path,
1547 wxString *name,
1548 wxString *ext,
1549 wxPathFormat format)
1550 {
1551 wxString volume;
1552 SplitPath(fullpath, &volume, path, name, ext, format);
1553
1554 if ( path && !volume.empty() )
1555 {
1556 path->Prepend(volume + GetVolumeSeparator(format));
1557 }
1558 }
1559
1560 // ----------------------------------------------------------------------------
1561 // time functions
1562 // ----------------------------------------------------------------------------
1563
1564 bool wxFileName::SetTimes(const wxDateTime *dtCreate,
1565 const wxDateTime *dtAccess,
1566 const wxDateTime *dtMod)
1567 {
1568 #if defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
1569 if ( !dtAccess && !dtMod )
1570 {
1571 // can't modify the creation time anyhow, don't try
1572 return TRUE;
1573 }
1574
1575 // if dtAccess or dtMod is not specified, use the other one (which must be
1576 // non NULL because of the test above) for both times
1577 utimbuf utm;
1578 utm.actime = dtAccess ? dtAccess->GetTicks() : dtMod->GetTicks();
1579 utm.modtime = dtMod ? dtMod->GetTicks() : dtAccess->GetTicks();
1580 if ( utime(GetFullPath(), &utm) == 0 )
1581 {
1582 return TRUE;
1583 }
1584 #elif defined(__WIN32__)
1585 wxFileHandle fh(GetFullPath());
1586 if ( fh.IsOk() )
1587 {
1588 FILETIME ftAccess, ftCreate, ftWrite;
1589
1590 if ( dtCreate )
1591 ConvertWxToFileTime(&ftCreate, *dtCreate);
1592 if ( dtAccess )
1593 ConvertWxToFileTime(&ftAccess, *dtAccess);
1594 if ( dtMod )
1595 ConvertWxToFileTime(&ftWrite, *dtMod);
1596
1597 if ( ::SetFileTime(fh,
1598 dtCreate ? &ftCreate : NULL,
1599 dtAccess ? &ftAccess : NULL,
1600 dtMod ? &ftWrite : NULL) )
1601 {
1602 return TRUE;
1603 }
1604 }
1605 #else // other platform
1606 #endif // platforms
1607
1608 wxLogSysError(_("Failed to modify file times for '%s'"),
1609 GetFullPath().c_str());
1610
1611 return FALSE;
1612 }
1613
1614 bool wxFileName::Touch()
1615 {
1616 #if defined(__UNIX_LIKE__)
1617 // under Unix touching file is simple: just pass NULL to utime()
1618 if ( utime(GetFullPath(), NULL) == 0 )
1619 {
1620 return TRUE;
1621 }
1622
1623 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
1624
1625 return FALSE;
1626 #else // other platform
1627 wxDateTime dtNow = wxDateTime::Now();
1628
1629 return SetTimes(NULL /* don't change create time */, &dtNow, &dtNow);
1630 #endif // platforms
1631 }
1632
1633 bool wxFileName::GetTimes(wxDateTime *dtAccess,
1634 wxDateTime *dtMod,
1635 wxDateTime *dtChange) const
1636 {
1637 #if defined(__UNIX_LIKE__) || defined(__WXMAC__) || (defined(__DOS__) && defined(__WATCOMC__))
1638 wxStructStat stBuf;
1639 if ( wxStat(GetFullPath(), &stBuf) == 0 )
1640 {
1641 if ( dtAccess )
1642 dtAccess->Set(stBuf.st_atime);
1643 if ( dtMod )
1644 dtMod->Set(stBuf.st_mtime);
1645 if ( dtChange )
1646 dtChange->Set(stBuf.st_ctime);
1647
1648 return TRUE;
1649 }
1650 #elif defined(__WIN32__)
1651 wxFileHandle fh(GetFullPath());
1652 if ( fh.IsOk() )
1653 {
1654 FILETIME ftAccess, ftCreate, ftWrite;
1655
1656 if ( ::GetFileTime(fh,
1657 dtMod ? &ftCreate : NULL,
1658 dtAccess ? &ftAccess : NULL,
1659 dtChange ? &ftWrite : NULL) )
1660 {
1661 if ( dtMod )
1662 ConvertFileTimeToWx(dtMod, ftCreate);
1663 if ( dtAccess )
1664 ConvertFileTimeToWx(dtAccess, ftAccess);
1665 if ( dtChange )
1666 ConvertFileTimeToWx(dtChange, ftWrite);
1667
1668 return TRUE;
1669 }
1670 }
1671 #else // other platform
1672 #endif // platforms
1673
1674 wxLogSysError(_("Failed to retrieve file times for '%s'"),
1675 GetFullPath().c_str());
1676
1677 return FALSE;
1678 }
1679
1680 #ifdef __WXMAC__
1681
1682 const short kMacExtensionMaxLength = 16 ;
1683 typedef struct
1684 {
1685 char m_ext[kMacExtensionMaxLength] ;
1686 OSType m_type ;
1687 OSType m_creator ;
1688 } MacDefaultExtensionRecord ;
1689
1690 #include "wx/dynarray.h"
1691 WX_DECLARE_OBJARRAY(MacDefaultExtensionRecord, MacDefaultExtensionArray) ;
1692 #include "wx/arrimpl.cpp"
1693 WX_DEFINE_OBJARRAY(MacDefaultExtensionArray) ;
1694
1695 MacDefaultExtensionArray gMacDefaultExtensions ;
1696 bool gMacDefaultExtensionsInited = false ;
1697
1698 static void MacEnsureDefaultExtensionsLoaded()
1699 {
1700 if ( !gMacDefaultExtensionsInited )
1701 {
1702 // load the default extensions
1703 MacDefaultExtensionRecord defaults[] =
1704 {
1705 { "txt" , 'TEXT' , 'ttxt' } ,
1706
1707 } ;
1708 // we could load the pc exchange prefs here too
1709
1710 for ( int i = 0 ; i < WXSIZEOF( defaults ) ; ++i )
1711 {
1712 gMacDefaultExtensions.Add( defaults[i] ) ;
1713 }
1714 gMacDefaultExtensionsInited = true ;
1715 }
1716 }
1717 bool wxFileName::MacSetTypeAndCreator( wxUint32 type , wxUint32 creator )
1718 {
1719 FInfo fndrInfo ;
1720 FSSpec spec ;
1721 wxMacFilename2FSSpec(GetFullPath(),&spec) ;
1722 OSErr err = FSpGetFInfo( &spec , &fndrInfo ) ;
1723 wxCHECK( err == noErr , false ) ;
1724
1725 fndrInfo.fdType = type ;
1726 fndrInfo.fdCreator = creator ;
1727 FSpSetFInfo( &spec , &fndrInfo ) ;
1728 return true ;
1729 }
1730
1731 bool wxFileName::MacGetTypeAndCreator( wxUint32 *type , wxUint32 *creator )
1732 {
1733 FInfo fndrInfo ;
1734 FSSpec spec ;
1735 wxMacFilename2FSSpec(GetFullPath(),&spec) ;
1736 OSErr err = FSpGetFInfo( &spec , &fndrInfo ) ;
1737 wxCHECK( err == noErr , false ) ;
1738
1739 *type = fndrInfo.fdType ;
1740 *creator = fndrInfo.fdCreator ;
1741 return true ;
1742 }
1743
1744 bool wxFileName::MacSetDefaultTypeAndCreator()
1745 {
1746 wxUint32 type , creator ;
1747 if ( wxFileName::MacFindDefaultTypeAndCreator(GetExt() , &type ,
1748 &creator ) )
1749 {
1750 return MacSetTypeAndCreator( type , creator ) ;
1751 }
1752 return false;
1753 }
1754
1755 bool wxFileName::MacFindDefaultTypeAndCreator( const wxString& ext , wxUint32 *type , wxUint32 *creator )
1756 {
1757 MacEnsureDefaultExtensionsLoaded() ;
1758 wxString extl = ext.Lower() ;
1759 for( int i = gMacDefaultExtensions.Count() - 1 ; i >= 0 ; --i )
1760 {
1761 if ( gMacDefaultExtensions.Item(i).m_ext == extl )
1762 {
1763 *type = gMacDefaultExtensions.Item(i).m_type ;
1764 *creator = gMacDefaultExtensions.Item(i).m_creator ;
1765 return true ;
1766 }
1767 }
1768 return false ;
1769 }
1770
1771 void wxFileName::MacRegisterDefaultTypeAndCreator( const wxString& ext , wxUint32 type , wxUint32 creator )
1772 {
1773 MacEnsureDefaultExtensionsLoaded() ;
1774 MacDefaultExtensionRecord rec ;
1775 rec.m_type = type ;
1776 rec.m_creator = creator ;
1777 strncpy( rec.m_ext , ext.Lower().c_str() , kMacExtensionMaxLength ) ;
1778 gMacDefaultExtensions.Add( rec ) ;
1779 }
1780 #endif