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