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