]> git.saurik.com Git - wxWidgets.git/blob - src/common/filename.cpp
added GetPath(flags) version to allow retrieving the volume as well
[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, bool full )
739 {
740 return wxFileName::Mkdir( GetFullPath(), perm, full );
741 }
742
743 bool wxFileName::Mkdir( const wxString &dir, int perm, bool full )
744 {
745 if (full)
746 {
747 wxFileName filename(dir);
748 wxArrayString dirs = filename.GetDirs();
749 dirs.Add(filename.GetName());
750
751 size_t count = dirs.GetCount();
752 size_t i;
753 wxString currPath;
754 int noErrors = 0;
755 for ( i = 0; i < count; i++ )
756 {
757 currPath += dirs[i];
758
759 if (currPath.Last() == wxT(':'))
760 {
761 // Can't create a root directory so continue to next dir
762 currPath += wxFILE_SEP_PATH;
763 continue;
764 }
765
766 if (!DirExists(currPath))
767 if (!wxMkdir(currPath, perm))
768 noErrors ++;
769
770 if ( (i < (count-1)) )
771 currPath += wxFILE_SEP_PATH;
772 }
773
774 return (noErrors == 0);
775
776 }
777 else
778 return ::wxMkdir( dir, perm );
779 }
780
781 bool wxFileName::Rmdir()
782 {
783 return wxFileName::Rmdir( GetFullPath() );
784 }
785
786 bool wxFileName::Rmdir( const wxString &dir )
787 {
788 return ::wxRmdir( dir );
789 }
790
791 // ----------------------------------------------------------------------------
792 // path normalization
793 // ----------------------------------------------------------------------------
794
795 bool wxFileName::Normalize(int flags,
796 const wxString& cwd,
797 wxPathFormat format)
798 {
799 // the existing path components
800 wxArrayString dirs = GetDirs();
801
802 // the path to prepend in front to make the path absolute
803 wxFileName curDir;
804
805 format = GetFormat(format);
806
807 // make the path absolute
808 if ( (flags & wxPATH_NORM_ABSOLUTE) && !IsAbsolute(format) )
809 {
810 if ( cwd.empty() )
811 {
812 curDir.AssignCwd(GetVolume());
813 }
814 else // cwd provided
815 {
816 curDir.AssignDir(cwd);
817 }
818
819 // the path may be not absolute because it doesn't have the volume name
820 // but in this case we shouldn't modify the directory components of it
821 // but just set the current volume
822 if ( !HasVolume() && curDir.HasVolume() )
823 {
824 SetVolume(curDir.GetVolume());
825
826 if ( !m_relative )
827 {
828 // yes, it was the case - we don't need curDir then
829 curDir.Clear();
830 }
831 }
832 }
833
834 // handle ~ stuff under Unix only
835 if ( (format == wxPATH_UNIX) && (flags & wxPATH_NORM_TILDE) )
836 {
837 if ( !dirs.IsEmpty() )
838 {
839 wxString dir = dirs[0u];
840 if ( !dir.empty() && dir[0u] == _T('~') )
841 {
842 curDir.AssignDir(wxGetUserHome(dir.c_str() + 1));
843
844 dirs.RemoveAt(0u);
845 }
846 }
847 }
848
849 // transform relative path into abs one
850 if ( curDir.IsOk() )
851 {
852 wxArrayString dirsNew = curDir.GetDirs();
853 size_t count = dirs.GetCount();
854 for ( size_t n = 0; n < count; n++ )
855 {
856 dirsNew.Add(dirs[n]);
857 }
858
859 dirs = dirsNew;
860 }
861
862 // now deal with ".", ".." and the rest
863 m_dirs.Empty();
864 size_t count = dirs.GetCount();
865 for ( size_t n = 0; n < count; n++ )
866 {
867 wxString dir = dirs[n];
868
869 if ( flags & wxPATH_NORM_DOTS )
870 {
871 if ( dir == wxT(".") )
872 {
873 // just ignore
874 continue;
875 }
876
877 if ( dir == wxT("..") )
878 {
879 if ( m_dirs.IsEmpty() )
880 {
881 wxLogError(_("The path '%s' contains too many \"..\"!"),
882 GetFullPath().c_str());
883 return FALSE;
884 }
885
886 m_dirs.RemoveAt(m_dirs.GetCount() - 1);
887 continue;
888 }
889 }
890
891 if ( flags & wxPATH_NORM_ENV_VARS )
892 {
893 dir = wxExpandEnvVars(dir);
894 }
895
896 if ( (flags & wxPATH_NORM_CASE) && !IsCaseSensitive(format) )
897 {
898 dir.MakeLower();
899 }
900
901 m_dirs.Add(dir);
902 }
903
904 if ( (flags & wxPATH_NORM_CASE) && !IsCaseSensitive(format) )
905 {
906 // VZ: expand env vars here too?
907
908 m_name.MakeLower();
909 m_ext.MakeLower();
910 }
911
912 #if defined(__WIN32__)
913 if ( (flags & wxPATH_NORM_LONG) && (format == wxPATH_DOS) )
914 {
915 Assign(GetLongPath());
916 }
917 #endif // Win32
918
919 // we do have the path now
920 m_relative = FALSE;
921
922 return TRUE;
923 }
924
925 // ----------------------------------------------------------------------------
926 // absolute/relative paths
927 // ----------------------------------------------------------------------------
928
929 bool wxFileName::IsAbsolute(wxPathFormat format) const
930 {
931 // if our path doesn't start with a path separator, it's not an absolute
932 // path
933 if ( m_relative )
934 return FALSE;
935
936 if ( !GetVolumeSeparator(format).empty() )
937 {
938 // this format has volumes and an absolute path must have one, it's not
939 // enough to have the full path to bean absolute file under Windows
940 if ( GetVolume().empty() )
941 return FALSE;
942 }
943
944 return TRUE;
945 }
946
947 bool wxFileName::MakeRelativeTo(const wxString& pathBase, wxPathFormat format)
948 {
949 wxFileName fnBase(pathBase, format);
950
951 // get cwd only once - small time saving
952 wxString cwd = wxGetCwd();
953 Normalize(wxPATH_NORM_ALL, cwd, format);
954 fnBase.Normalize(wxPATH_NORM_ALL, cwd, format);
955
956 bool withCase = IsCaseSensitive(format);
957
958 // we can't do anything if the files live on different volumes
959 if ( !GetVolume().IsSameAs(fnBase.GetVolume(), withCase) )
960 {
961 // nothing done
962 return FALSE;
963 }
964
965 // same drive, so we don't need our volume
966 m_volume.clear();
967
968 // remove common directories starting at the top
969 while ( !m_dirs.IsEmpty() && !fnBase.m_dirs.IsEmpty() &&
970 m_dirs[0u].IsSameAs(fnBase.m_dirs[0u], withCase) )
971 {
972 m_dirs.RemoveAt(0);
973 fnBase.m_dirs.RemoveAt(0);
974 }
975
976 // add as many ".." as needed
977 size_t count = fnBase.m_dirs.GetCount();
978 for ( size_t i = 0; i < count; i++ )
979 {
980 m_dirs.Insert(wxT(".."), 0u);
981 }
982
983 if ( format == wxPATH_UNIX || format == wxPATH_DOS )
984 {
985 // a directory made relative with respect to itself is '.' under Unix
986 // and DOS, by definition (but we don't have to insert "./" for the
987 // files)
988 if ( m_dirs.IsEmpty() && IsDir() )
989 {
990 m_dirs.Add(_T('.'));
991 }
992 }
993
994 m_relative = TRUE;
995
996 // we were modified
997 return TRUE;
998 }
999
1000 // ----------------------------------------------------------------------------
1001 // filename kind tests
1002 // ----------------------------------------------------------------------------
1003
1004 bool wxFileName::SameAs(const wxFileName &filepath, wxPathFormat format)
1005 {
1006 wxFileName fn1 = *this,
1007 fn2 = filepath;
1008
1009 // get cwd only once - small time saving
1010 wxString cwd = wxGetCwd();
1011 fn1.Normalize(wxPATH_NORM_ALL, cwd, format);
1012 fn2.Normalize(wxPATH_NORM_ALL, cwd, format);
1013
1014 if ( fn1.GetFullPath() == fn2.GetFullPath() )
1015 return TRUE;
1016
1017 // TODO: compare inodes for Unix, this works even when filenames are
1018 // different but files are the same (symlinks) (VZ)
1019
1020 return FALSE;
1021 }
1022
1023 /* static */
1024 bool wxFileName::IsCaseSensitive( wxPathFormat format )
1025 {
1026 // only Unix filenames are truely case-sensitive
1027 return GetFormat(format) == wxPATH_UNIX;
1028 }
1029
1030 /* static */
1031 wxString wxFileName::GetVolumeSeparator(wxPathFormat format)
1032 {
1033 wxString sepVol;
1034
1035 if ( (GetFormat(format) == wxPATH_DOS) ||
1036 (GetFormat(format) == wxPATH_VMS) )
1037 {
1038 sepVol = wxFILE_SEP_DSK;
1039 }
1040 //else: leave empty
1041
1042 return sepVol;
1043 }
1044
1045 /* static */
1046 wxString wxFileName::GetPathSeparators(wxPathFormat format)
1047 {
1048 wxString seps;
1049 switch ( GetFormat(format) )
1050 {
1051 case wxPATH_DOS:
1052 // accept both as native APIs do but put the native one first as
1053 // this is the one we use in GetFullPath()
1054 seps << wxFILE_SEP_PATH_DOS << wxFILE_SEP_PATH_UNIX;
1055 break;
1056
1057 default:
1058 wxFAIL_MSG( _T("unknown wxPATH_XXX style") );
1059 // fall through
1060
1061 case wxPATH_UNIX:
1062 seps = wxFILE_SEP_PATH_UNIX;
1063 break;
1064
1065 case wxPATH_MAC:
1066 seps = wxFILE_SEP_PATH_MAC;
1067 break;
1068
1069 case wxPATH_VMS:
1070 seps = wxFILE_SEP_PATH_VMS;
1071 break;
1072 }
1073
1074 return seps;
1075 }
1076
1077 /* static */
1078 bool wxFileName::IsPathSeparator(wxChar ch, wxPathFormat format)
1079 {
1080 // wxString::Find() doesn't work as expected with NUL - it will always find
1081 // it, so it is almost surely a bug if this function is called with NUL arg
1082 wxASSERT_MSG( ch != _T('\0'), _T("shouldn't be called with NUL") );
1083
1084 return GetPathSeparators(format).Find(ch) != wxNOT_FOUND;
1085 }
1086
1087 // ----------------------------------------------------------------------------
1088 // path components manipulation
1089 // ----------------------------------------------------------------------------
1090
1091 void wxFileName::AppendDir( const wxString &dir )
1092 {
1093 m_dirs.Add( dir );
1094 }
1095
1096 void wxFileName::PrependDir( const wxString &dir )
1097 {
1098 m_dirs.Insert( dir, 0 );
1099 }
1100
1101 void wxFileName::InsertDir( int before, const wxString &dir )
1102 {
1103 m_dirs.Insert( dir, before );
1104 }
1105
1106 void wxFileName::RemoveDir( int pos )
1107 {
1108 m_dirs.Remove( (size_t)pos );
1109 }
1110
1111 // ----------------------------------------------------------------------------
1112 // accessors
1113 // ----------------------------------------------------------------------------
1114
1115 void wxFileName::SetFullName(const wxString& fullname)
1116 {
1117 SplitPath(fullname, NULL /* no path */, &m_name, &m_ext);
1118 }
1119
1120 wxString wxFileName::GetFullName() const
1121 {
1122 wxString fullname = m_name;
1123 if ( !m_ext.empty() )
1124 {
1125 fullname << wxFILE_SEP_EXT << m_ext;
1126 }
1127
1128 return fullname;
1129 }
1130
1131 wxString wxFileName::GetPath( int flags, wxPathFormat format ) const
1132 {
1133 format = GetFormat( format );
1134
1135 wxString fullpath;
1136
1137 // return the volume with the path as well if requested
1138 if ( flags & wxPATH_GET_VOLUME )
1139 {
1140 fullpath += wxGetVolumeString(GetVolume(), format);
1141 }
1142
1143 // the leading character
1144 if ( format == wxPATH_MAC )
1145 {
1146 if ( m_relative )
1147 fullpath += wxFILE_SEP_PATH_MAC;
1148 }
1149 else if ( format == wxPATH_DOS )
1150 {
1151 if (!m_relative)
1152 fullpath += wxFILE_SEP_PATH_DOS;
1153 }
1154 else if ( format == wxPATH_UNIX )
1155 {
1156 if (!m_relative)
1157 fullpath += wxFILE_SEP_PATH_UNIX;
1158 }
1159
1160 // then concatenate all the path components using the path separator
1161 size_t dirCount = m_dirs.GetCount();
1162 if ( dirCount )
1163 {
1164 if ( format == wxPATH_VMS )
1165 {
1166 fullpath += wxT('[');
1167 }
1168
1169 for ( size_t i = 0; i < dirCount; i++ )
1170 {
1171 // TODO: What to do with ".." under VMS
1172
1173 switch (format)
1174 {
1175 case wxPATH_MAC:
1176 {
1177 if (m_dirs[i] == wxT("."))
1178 break;
1179 if (m_dirs[i] != wxT("..")) // convert back from ".." to nothing
1180 fullpath += m_dirs[i];
1181 fullpath += wxT(':');
1182 break;
1183 }
1184 case wxPATH_DOS:
1185 {
1186 fullpath += m_dirs[i];
1187 fullpath += wxT('\\');
1188 break;
1189 }
1190 case wxPATH_UNIX:
1191 {
1192 fullpath += m_dirs[i];
1193 fullpath += wxT('/');
1194 break;
1195 }
1196 case wxPATH_VMS:
1197 {
1198 if (m_dirs[i] != wxT("..")) // convert back from ".." to nothing
1199 fullpath += m_dirs[i];
1200 if (i == dirCount-1)
1201 fullpath += wxT(']');
1202 else
1203 fullpath += wxT('.');
1204 break;
1205 }
1206 default:
1207 {
1208 wxFAIL_MSG( wxT("error") );
1209 }
1210 }
1211 }
1212 }
1213
1214 if ( (flags & wxPATH_GET_SEPARATOR) && !fullpath.empty() )
1215 {
1216 fullpath += GetPathSeparator(format);
1217 }
1218
1219 return fullpath;
1220 }
1221
1222 wxString wxFileName::GetFullPath( wxPathFormat format ) const
1223 {
1224 format = GetFormat(format);
1225
1226 // first put the volume
1227 wxString fullpath = wxGetVolumeString(m_volume, format);
1228
1229 // the leading character
1230 if ( format == wxPATH_MAC )
1231 {
1232 if ( m_relative )
1233 fullpath += wxFILE_SEP_PATH_MAC;
1234 }
1235 else if ( format == wxPATH_DOS )
1236 {
1237 if ( !m_relative )
1238 fullpath += wxFILE_SEP_PATH_DOS;
1239 }
1240 else if ( format == wxPATH_UNIX )
1241 {
1242 if ( !m_relative )
1243 {
1244 // normally the absolute file names starts with a slash with one
1245 // exception: file names like "~/foo.bar" don't have it
1246 if ( m_dirs.IsEmpty() || m_dirs[0u] != _T('~') )
1247 {
1248 fullpath += wxFILE_SEP_PATH_UNIX;
1249 }
1250 }
1251 }
1252
1253 // then concatenate all the path components using the path separator
1254 size_t dirCount = m_dirs.GetCount();
1255 if ( dirCount )
1256 {
1257 if ( format == wxPATH_VMS )
1258 {
1259 fullpath += wxT('[');
1260 }
1261
1262
1263 for ( size_t i = 0; i < dirCount; i++ )
1264 {
1265 // TODO: What to do with ".." under VMS
1266
1267 switch (format)
1268 {
1269 case wxPATH_MAC:
1270 {
1271 if (m_dirs[i] == wxT("."))
1272 break;
1273 if (m_dirs[i] != wxT("..")) // convert back from ".." to nothing
1274 fullpath += m_dirs[i];
1275 fullpath += wxT(':');
1276 break;
1277 }
1278 case wxPATH_DOS:
1279 {
1280 fullpath += m_dirs[i];
1281 fullpath += wxT('\\');
1282 break;
1283 }
1284 case wxPATH_UNIX:
1285 {
1286 fullpath += m_dirs[i];
1287 fullpath += wxT('/');
1288 break;
1289 }
1290 case wxPATH_VMS:
1291 {
1292 if (m_dirs[i] != wxT("..")) // convert back from ".." to nothing
1293 fullpath += m_dirs[i];
1294 if (i == dirCount-1)
1295 fullpath += wxT(']');
1296 else
1297 fullpath += wxT('.');
1298 break;
1299 }
1300 default:
1301 {
1302 wxFAIL_MSG( wxT("error") );
1303 }
1304 }
1305 }
1306 }
1307
1308 // finally add the file name and extension
1309 fullpath += GetFullName();
1310
1311 return fullpath;
1312 }
1313
1314 // Return the short form of the path (returns identity on non-Windows platforms)
1315 wxString wxFileName::GetShortPath() const
1316 {
1317 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__)
1318 wxString path(GetFullPath());
1319 wxString pathOut;
1320 DWORD sz = ::GetShortPathName(path, NULL, 0);
1321 bool ok = sz != 0;
1322 if ( ok )
1323 {
1324 ok = ::GetShortPathName
1325 (
1326 path,
1327 pathOut.GetWriteBuf(sz),
1328 sz
1329 ) != 0;
1330 pathOut.UngetWriteBuf();
1331 }
1332 if (ok)
1333 return pathOut;
1334
1335 return path;
1336 #else
1337 return GetFullPath();
1338 #endif
1339 }
1340
1341 // Return the long form of the path (returns identity on non-Windows platforms)
1342 wxString wxFileName::GetLongPath() const
1343 {
1344 wxString pathOut,
1345 path = GetFullPath();
1346
1347 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1348 bool success = FALSE;
1349
1350 #if wxUSE_DYNAMIC_LOADER
1351 typedef DWORD (*GET_LONG_PATH_NAME)(const wxChar *, wxChar *, DWORD);
1352
1353 static bool s_triedToLoad = FALSE;
1354
1355 if ( !s_triedToLoad )
1356 {
1357 s_triedToLoad = TRUE;
1358 wxDynamicLibrary dllKernel(_T("kernel32"));
1359 if ( dllKernel.IsLoaded() )
1360 {
1361 // may succeed or fail depending on the Windows version
1362 static GET_LONG_PATH_NAME s_pfnGetLongPathName = NULL;
1363 #ifdef _UNICODE
1364 s_pfnGetLongPathName = (GET_LONG_PATH_NAME) dllKernel.GetSymbol(_T("GetLongPathNameW"));
1365 #else
1366 s_pfnGetLongPathName = (GET_LONG_PATH_NAME) dllKernel.GetSymbol(_T("GetLongPathNameA"));
1367 #endif
1368
1369 if ( s_pfnGetLongPathName )
1370 {
1371 DWORD dwSize = (*s_pfnGetLongPathName)(path, NULL, 0);
1372 bool ok = dwSize > 0;
1373
1374 if ( ok )
1375 {
1376 DWORD sz = (*s_pfnGetLongPathName)(path, NULL, 0);
1377 ok = sz != 0;
1378 if ( ok )
1379 {
1380 ok = (*s_pfnGetLongPathName)
1381 (
1382 path,
1383 pathOut.GetWriteBuf(sz),
1384 sz
1385 ) != 0;
1386 pathOut.UngetWriteBuf();
1387
1388 success = TRUE;
1389 }
1390 }
1391 }
1392 }
1393 }
1394 if (success)
1395 return pathOut;
1396 #endif // wxUSE_DYNAMIC_LOADER
1397
1398 if (!success)
1399 {
1400 // The OS didn't support GetLongPathName, or some other error.
1401 // We need to call FindFirstFile on each component in turn.
1402
1403 WIN32_FIND_DATA findFileData;
1404 HANDLE hFind;
1405 pathOut = wxEmptyString;
1406
1407 wxArrayString dirs = GetDirs();
1408 dirs.Add(GetFullName());
1409
1410 wxString tmpPath;
1411
1412 size_t count = dirs.GetCount();
1413 for ( size_t i = 0; i < count; i++ )
1414 {
1415 // We're using pathOut to collect the long-name path, but using a
1416 // temporary for appending the last path component which may be
1417 // short-name
1418 tmpPath = pathOut + dirs[i];
1419
1420 if ( tmpPath.empty() )
1421 continue;
1422
1423 if ( tmpPath.Last() == wxT(':') )
1424 {
1425 // Can't pass a drive and root dir to FindFirstFile,
1426 // so continue to next dir
1427 tmpPath += wxFILE_SEP_PATH;
1428 pathOut = tmpPath;
1429 continue;
1430 }
1431
1432 hFind = ::FindFirstFile(tmpPath, &findFileData);
1433 if (hFind == INVALID_HANDLE_VALUE)
1434 {
1435 // Error: return immediately with the original path
1436 return path;
1437 }
1438
1439 pathOut += findFileData.cFileName;
1440 if ( (i < (count-1)) )
1441 pathOut += wxFILE_SEP_PATH;
1442
1443 ::FindClose(hFind);
1444 }
1445 }
1446 #else // !Win32
1447 pathOut = path;
1448 #endif // Win32/!Win32
1449
1450 return pathOut;
1451 }
1452
1453 wxPathFormat wxFileName::GetFormat( wxPathFormat format )
1454 {
1455 if (format == wxPATH_NATIVE)
1456 {
1457 #if defined(__WXMSW__) || defined(__WXPM__) || defined(__DOS__)
1458 format = wxPATH_DOS;
1459 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1460 format = wxPATH_MAC;
1461 #elif defined(__VMS)
1462 format = wxPATH_VMS;
1463 #else
1464 format = wxPATH_UNIX;
1465 #endif
1466 }
1467 return format;
1468 }
1469
1470 // ----------------------------------------------------------------------------
1471 // path splitting function
1472 // ----------------------------------------------------------------------------
1473
1474 /* static */
1475 void wxFileName::SplitPath(const wxString& fullpathWithVolume,
1476 wxString *pstrVolume,
1477 wxString *pstrPath,
1478 wxString *pstrName,
1479 wxString *pstrExt,
1480 wxPathFormat format)
1481 {
1482 format = GetFormat(format);
1483
1484 wxString fullpath = fullpathWithVolume;
1485
1486 // under VMS the end of the path is ']', not the path separator used to
1487 // separate the components
1488 wxString sepPath = format == wxPATH_VMS ? wxString(_T(']'))
1489 : GetPathSeparators(format);
1490
1491 // special Windows UNC paths hack: transform \\share\path into share:path
1492 if ( format == wxPATH_DOS )
1493 {
1494 if ( fullpath.length() >= 4 &&
1495 fullpath[0u] == wxFILE_SEP_PATH_DOS &&
1496 fullpath[1u] == wxFILE_SEP_PATH_DOS )
1497 {
1498 fullpath.erase(0, 2);
1499
1500 size_t posFirstSlash = fullpath.find_first_of(sepPath);
1501 if ( posFirstSlash != wxString::npos )
1502 {
1503 fullpath[posFirstSlash] = wxFILE_SEP_DSK;
1504
1505 // UNC paths are always absolute, right? (FIXME)
1506 fullpath.insert(posFirstSlash + 1, wxFILE_SEP_PATH_DOS);
1507 }
1508 }
1509 }
1510
1511 // We separate the volume here
1512 if ( format == wxPATH_DOS || format == wxPATH_VMS )
1513 {
1514 wxString sepVol = GetVolumeSeparator(format);
1515
1516 size_t posFirstColon = fullpath.find_first_of(sepVol);
1517 if ( posFirstColon != wxString::npos )
1518 {
1519 if ( pstrVolume )
1520 {
1521 *pstrVolume = fullpath.Left(posFirstColon);
1522 }
1523
1524 // remove the volume name and the separator from the full path
1525 fullpath.erase(0, posFirstColon + sepVol.length());
1526 }
1527 }
1528
1529 // find the positions of the last dot and last path separator in the path
1530 size_t posLastDot = fullpath.find_last_of(wxFILE_SEP_EXT);
1531 size_t posLastSlash = fullpath.find_last_of(sepPath);
1532
1533 if ( (posLastDot != wxString::npos) &&
1534 ((format == wxPATH_UNIX) || (format == wxPATH_VMS)) )
1535 {
1536 if ( (posLastDot == 0) ||
1537 (fullpath[posLastDot - 1] == sepPath[0u] ) )
1538 {
1539 // under Unix and VMS, dot may be (and commonly is) the first
1540 // character of the filename, don't treat the entire filename as
1541 // extension in this case
1542 posLastDot = wxString::npos;
1543 }
1544 }
1545
1546 // if we do have a dot and a slash, check that the dot is in the name part
1547 if ( (posLastDot != wxString::npos) &&
1548 (posLastSlash != wxString::npos) &&
1549 (posLastDot < posLastSlash) )
1550 {
1551 // the dot is part of the path, not the start of the extension
1552 posLastDot = wxString::npos;
1553 }
1554
1555 // now fill in the variables provided by user
1556 if ( pstrPath )
1557 {
1558 if ( posLastSlash == wxString::npos )
1559 {
1560 // no path at all
1561 pstrPath->Empty();
1562 }
1563 else
1564 {
1565 // take everything up to the path separator but take care to make
1566 // the path equal to something like '/', not empty, for the files
1567 // immediately under root directory
1568 size_t len = posLastSlash;
1569
1570 // this rule does not apply to mac since we do not start with colons (sep)
1571 // except for relative paths
1572 if ( !len && format != wxPATH_MAC)
1573 len++;
1574
1575 *pstrPath = fullpath.Left(len);
1576
1577 // special VMS hack: remove the initial bracket
1578 if ( format == wxPATH_VMS )
1579 {
1580 if ( (*pstrPath)[0u] == _T('[') )
1581 pstrPath->erase(0, 1);
1582 }
1583 }
1584 }
1585
1586 if ( pstrName )
1587 {
1588 // take all characters starting from the one after the last slash and
1589 // up to, but excluding, the last dot
1590 size_t nStart = posLastSlash == wxString::npos ? 0 : posLastSlash + 1;
1591 size_t count;
1592 if ( posLastDot == wxString::npos )
1593 {
1594 // take all until the end
1595 count = wxString::npos;
1596 }
1597 else if ( posLastSlash == wxString::npos )
1598 {
1599 count = posLastDot;
1600 }
1601 else // have both dot and slash
1602 {
1603 count = posLastDot - posLastSlash - 1;
1604 }
1605
1606 *pstrName = fullpath.Mid(nStart, count);
1607 }
1608
1609 if ( pstrExt )
1610 {
1611 if ( posLastDot == wxString::npos )
1612 {
1613 // no extension
1614 pstrExt->Empty();
1615 }
1616 else
1617 {
1618 // take everything after the dot
1619 *pstrExt = fullpath.Mid(posLastDot + 1);
1620 }
1621 }
1622 }
1623
1624 /* static */
1625 void wxFileName::SplitPath(const wxString& fullpath,
1626 wxString *path,
1627 wxString *name,
1628 wxString *ext,
1629 wxPathFormat format)
1630 {
1631 wxString volume;
1632 SplitPath(fullpath, &volume, path, name, ext, format);
1633
1634 if ( path )
1635 {
1636 path->Prepend(wxGetVolumeString(volume, format));
1637 }
1638 }
1639
1640 // ----------------------------------------------------------------------------
1641 // time functions
1642 // ----------------------------------------------------------------------------
1643
1644 bool wxFileName::SetTimes(const wxDateTime *dtAccess,
1645 const wxDateTime *dtMod,
1646 const wxDateTime *dtCreate)
1647 {
1648 #if defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
1649 if ( !dtAccess && !dtMod )
1650 {
1651 // can't modify the creation time anyhow, don't try
1652 return TRUE;
1653 }
1654
1655 // if dtAccess or dtMod is not specified, use the other one (which must be
1656 // non NULL because of the test above) for both times
1657 utimbuf utm;
1658 utm.actime = dtAccess ? dtAccess->GetTicks() : dtMod->GetTicks();
1659 utm.modtime = dtMod ? dtMod->GetTicks() : dtAccess->GetTicks();
1660 if ( utime(GetFullPath(), &utm) == 0 )
1661 {
1662 return TRUE;
1663 }
1664 #elif defined(__WIN32__)
1665 wxFileHandle fh(GetFullPath(), wxFileHandle::Write);
1666 if ( fh.IsOk() )
1667 {
1668 FILETIME ftAccess, ftCreate, ftWrite;
1669
1670 if ( dtCreate )
1671 ConvertWxToFileTime(&ftCreate, *dtCreate);
1672 if ( dtAccess )
1673 ConvertWxToFileTime(&ftAccess, *dtAccess);
1674 if ( dtMod )
1675 ConvertWxToFileTime(&ftWrite, *dtMod);
1676
1677 if ( ::SetFileTime(fh,
1678 dtCreate ? &ftCreate : NULL,
1679 dtAccess ? &ftAccess : NULL,
1680 dtMod ? &ftWrite : NULL) )
1681 {
1682 return TRUE;
1683 }
1684 }
1685 #else // other platform
1686 #endif // platforms
1687
1688 wxLogSysError(_("Failed to modify file times for '%s'"),
1689 GetFullPath().c_str());
1690
1691 return FALSE;
1692 }
1693
1694 bool wxFileName::Touch()
1695 {
1696 #if defined(__UNIX_LIKE__)
1697 // under Unix touching file is simple: just pass NULL to utime()
1698 if ( utime(GetFullPath(), NULL) == 0 )
1699 {
1700 return TRUE;
1701 }
1702
1703 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
1704
1705 return FALSE;
1706 #else // other platform
1707 wxDateTime dtNow = wxDateTime::Now();
1708
1709 return SetTimes(&dtNow, &dtNow, NULL /* don't change create time */);
1710 #endif // platforms
1711 }
1712
1713 bool wxFileName::GetTimes(wxDateTime *dtAccess,
1714 wxDateTime *dtMod,
1715 wxDateTime *dtCreate) const
1716 {
1717 #if defined(__UNIX_LIKE__) || defined(__WXMAC__) || (defined(__DOS__) && defined(__WATCOMC__))
1718 wxStructStat stBuf;
1719 if ( wxStat(GetFullPath(), &stBuf) == 0 )
1720 {
1721 if ( dtAccess )
1722 dtAccess->Set(stBuf.st_atime);
1723 if ( dtMod )
1724 dtMod->Set(stBuf.st_mtime);
1725 if ( dtCreate )
1726 dtCreate->Set(stBuf.st_ctime);
1727
1728 return TRUE;
1729 }
1730 #elif defined(__WIN32__)
1731 wxFileHandle fh(GetFullPath(), wxFileHandle::Read);
1732 if ( fh.IsOk() )
1733 {
1734 FILETIME ftAccess, ftCreate, ftWrite;
1735
1736 if ( ::GetFileTime(fh,
1737 dtMod ? &ftCreate : NULL,
1738 dtAccess ? &ftAccess : NULL,
1739 dtCreate ? &ftWrite : NULL) )
1740 {
1741 if ( dtMod )
1742 ConvertFileTimeToWx(dtMod, ftCreate);
1743 if ( dtAccess )
1744 ConvertFileTimeToWx(dtAccess, ftAccess);
1745 if ( dtCreate )
1746 ConvertFileTimeToWx(dtCreate, ftWrite);
1747
1748 return TRUE;
1749 }
1750 }
1751 #else // other platform
1752 #endif // platforms
1753
1754 wxLogSysError(_("Failed to retrieve file times for '%s'"),
1755 GetFullPath().c_str());
1756
1757 return FALSE;
1758 }
1759
1760 #ifdef __WXMAC__
1761
1762 const short kMacExtensionMaxLength = 16 ;
1763 typedef struct
1764 {
1765 char m_ext[kMacExtensionMaxLength] ;
1766 OSType m_type ;
1767 OSType m_creator ;
1768 } MacDefaultExtensionRecord ;
1769
1770 #include "wx/dynarray.h"
1771 WX_DECLARE_OBJARRAY(MacDefaultExtensionRecord, MacDefaultExtensionArray) ;
1772 #include "wx/arrimpl.cpp"
1773 WX_DEFINE_OBJARRAY(MacDefaultExtensionArray) ;
1774
1775 MacDefaultExtensionArray gMacDefaultExtensions ;
1776 bool gMacDefaultExtensionsInited = false ;
1777
1778 static void MacEnsureDefaultExtensionsLoaded()
1779 {
1780 if ( !gMacDefaultExtensionsInited )
1781 {
1782 // load the default extensions
1783 MacDefaultExtensionRecord defaults[] =
1784 {
1785 { "txt" , 'TEXT' , 'ttxt' } ,
1786
1787 } ;
1788 // we could load the pc exchange prefs here too
1789
1790 for ( int i = 0 ; i < WXSIZEOF( defaults ) ; ++i )
1791 {
1792 gMacDefaultExtensions.Add( defaults[i] ) ;
1793 }
1794 gMacDefaultExtensionsInited = true ;
1795 }
1796 }
1797 bool wxFileName::MacSetTypeAndCreator( wxUint32 type , wxUint32 creator )
1798 {
1799 FInfo fndrInfo ;
1800 FSSpec spec ;
1801 wxMacFilename2FSSpec(GetFullPath(),&spec) ;
1802 OSErr err = FSpGetFInfo( &spec , &fndrInfo ) ;
1803 wxCHECK( err == noErr , false ) ;
1804
1805 fndrInfo.fdType = type ;
1806 fndrInfo.fdCreator = creator ;
1807 FSpSetFInfo( &spec , &fndrInfo ) ;
1808 return true ;
1809 }
1810
1811 bool wxFileName::MacGetTypeAndCreator( wxUint32 *type , wxUint32 *creator )
1812 {
1813 FInfo fndrInfo ;
1814 FSSpec spec ;
1815 wxMacFilename2FSSpec(GetFullPath(),&spec) ;
1816 OSErr err = FSpGetFInfo( &spec , &fndrInfo ) ;
1817 wxCHECK( err == noErr , false ) ;
1818
1819 *type = fndrInfo.fdType ;
1820 *creator = fndrInfo.fdCreator ;
1821 return true ;
1822 }
1823
1824 bool wxFileName::MacSetDefaultTypeAndCreator()
1825 {
1826 wxUint32 type , creator ;
1827 if ( wxFileName::MacFindDefaultTypeAndCreator(GetExt() , &type ,
1828 &creator ) )
1829 {
1830 return MacSetTypeAndCreator( type , creator ) ;
1831 }
1832 return false;
1833 }
1834
1835 bool wxFileName::MacFindDefaultTypeAndCreator( const wxString& ext , wxUint32 *type , wxUint32 *creator )
1836 {
1837 MacEnsureDefaultExtensionsLoaded() ;
1838 wxString extl = ext.Lower() ;
1839 for( int i = gMacDefaultExtensions.Count() - 1 ; i >= 0 ; --i )
1840 {
1841 if ( gMacDefaultExtensions.Item(i).m_ext == extl )
1842 {
1843 *type = gMacDefaultExtensions.Item(i).m_type ;
1844 *creator = gMacDefaultExtensions.Item(i).m_creator ;
1845 return true ;
1846 }
1847 }
1848 return false ;
1849 }
1850
1851 void wxFileName::MacRegisterDefaultTypeAndCreator( const wxString& ext , wxUint32 type , wxUint32 creator )
1852 {
1853 MacEnsureDefaultExtensionsLoaded() ;
1854 MacDefaultExtensionRecord rec ;
1855 rec.m_type = type ;
1856 rec.m_creator = creator ;
1857 strncpy( rec.m_ext , ext.Lower().c_str() , kMacExtensionMaxLength ) ;
1858 gMacDefaultExtensions.Add( rec ) ;
1859 }
1860 #endif