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