]> git.saurik.com Git - wxWidgets.git/blob - src/common/filename.cpp
added wxFileName::MakeRelativeTo() and the tests/docs for it
[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 :::file is not yet supported. TODO.
36
37 wxPATH_VMS: VMS native format, absolute file names have the form
38 <device>:[dir1.dir2.dir3]file.txt
39 or
40 <device>:[000000.dir1.dir2.dir3]file.txt
41
42 the <device> is the physical device (i.e. disk). 000000 is the
43 root directory on the device which can be omitted.
44
45 Note that VMS uses different separators unlike Unix:
46 : always after the device. If the path does not contain : than
47 the default (the device of the current directory) is assumed.
48 [ start of directory specyfication
49 . separator between directory and subdirectory
50 ] between directory and file
51 */
52
53 // ============================================================================
54 // declarations
55 // ============================================================================
56
57 // ----------------------------------------------------------------------------
58 // headers
59 // ----------------------------------------------------------------------------
60
61 #ifdef __GNUG__
62 #pragma implementation "filename.h"
63 #endif
64
65 // For compilers that support precompilation, includes "wx.h".
66 #include "wx/wxprec.h"
67
68 #ifdef __BORLANDC__
69 #pragma hdrstop
70 #endif
71
72 #ifndef WX_PRECOMP
73 #include "wx/intl.h"
74 #include "wx/log.h"
75 #endif
76
77 #include "wx/filename.h"
78 #include "wx/tokenzr.h"
79 #include "wx/config.h" // for wxExpandEnvVars
80 #include "wx/utils.h"
81
82 #if wxUSE_DYNLIB_CLASS
83 #include "wx/dynlib.h"
84 #endif
85
86 // For GetShort/LongPathName
87 #ifdef __WIN32__
88 #include <windows.h>
89
90 #include "wx/msw/winundef.h"
91 #endif
92
93 // utime() is POSIX so should normally be available on all Unices
94 #ifdef __UNIX_LIKE__
95 #include <sys/types.h>
96 #include <utime.h>
97 #include <sys/stat.h>
98 #include <unistd.h>
99 #endif
100
101 #ifdef __MWERKS__
102 #include <stat.h>
103 #include <unistd.h>
104 #include <unix.h>
105 #endif
106
107 // ----------------------------------------------------------------------------
108 // private classes
109 // ----------------------------------------------------------------------------
110
111 // small helper class which opens and closes the file - we use it just to get
112 // a file handle for the given file name to pass it to some Win32 API function
113 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
114
115 class wxFileHandle
116 {
117 public:
118 wxFileHandle(const wxString& filename)
119 {
120 m_hFile = ::CreateFile
121 (
122 filename, // name
123 GENERIC_READ, // access mask
124 0, // no sharing
125 NULL, // no secutity attr
126 OPEN_EXISTING, // creation disposition
127 0, // no flags
128 NULL // no template file
129 );
130
131 if ( m_hFile == INVALID_HANDLE_VALUE )
132 {
133 wxLogSysError(_("Failed to open '%s' for reading"),
134 filename.c_str());
135 }
136 }
137
138 ~wxFileHandle()
139 {
140 if ( m_hFile != INVALID_HANDLE_VALUE )
141 {
142 if ( !::CloseHandle(m_hFile) )
143 {
144 wxLogSysError(_("Failed to close file handle"));
145 }
146 }
147 }
148
149 // return TRUE only if the file could be opened successfully
150 bool IsOk() const { return m_hFile != INVALID_HANDLE_VALUE; }
151
152 // get the handle
153 operator HANDLE() const { return m_hFile; }
154
155 private:
156 HANDLE m_hFile;
157 };
158
159 #endif // __WIN32__
160
161 // ----------------------------------------------------------------------------
162 // private functions
163 // ----------------------------------------------------------------------------
164
165 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
166
167 // convert between wxDateTime and FILETIME which is a 64-bit value representing
168 // the number of 100-nanosecond intervals since January 1, 1601.
169
170 // the number of milliseconds between the Unix Epoch (January 1, 1970) and the
171 // FILETIME reference point (January 1, 1601)
172 static const wxLongLong FILETIME_EPOCH_OFFSET = wxLongLong(0xa97, 0x30b66800);
173
174 static void ConvertFileTimeToWx(wxDateTime *dt, const FILETIME &ft)
175 {
176 wxLongLong ll(ft.dwHighDateTime, ft.dwLowDateTime);
177
178 // convert 100ns to ms
179 ll /= 10000;
180
181 // move it to our Epoch
182 ll -= FILETIME_EPOCH_OFFSET;
183
184 *dt = wxDateTime(ll);
185 }
186
187 static void ConvertWxToFileTime(FILETIME *ft, const wxDateTime& dt)
188 {
189 // do the reverse of ConvertFileTimeToWx()
190 wxLongLong ll = dt.GetValue();
191 ll *= 10000;
192 ll += FILETIME_EPOCH_OFFSET;
193
194 ft->dwHighDateTime = ll.GetHi();
195 ft->dwLowDateTime = ll.GetLo();
196 }
197
198 #endif // __WIN32__
199
200 // ============================================================================
201 // implementation
202 // ============================================================================
203
204 // ----------------------------------------------------------------------------
205 // wxFileName construction
206 // ----------------------------------------------------------------------------
207
208 void wxFileName::Assign( const wxFileName &filepath )
209 {
210 m_volume = filepath.GetVolume();
211 m_dirs = filepath.GetDirs();
212 m_name = filepath.GetName();
213 m_ext = filepath.GetExt();
214 }
215
216 void wxFileName::Assign(const wxString& volume,
217 const wxString& path,
218 const wxString& name,
219 const wxString& ext,
220 wxPathFormat format )
221 {
222 wxStringTokenizer tn(path, GetPathSeparators(format));
223
224 m_dirs.Clear();
225 while ( tn.HasMoreTokens() )
226 {
227 wxString token = tn.GetNextToken();
228
229 // if the path starts with a slash, we do need the first empty dir
230 // entry to be able to tell later that it was an absolute path, but
231 // otherwise ignore the double slashes
232 if ( m_dirs.IsEmpty() || !token.IsEmpty() )
233 m_dirs.Add( token );
234 }
235
236 m_volume = volume;
237 m_ext = ext;
238 m_name = name;
239 }
240
241 void wxFileName::Assign(const wxString& fullpath,
242 wxPathFormat format)
243 {
244 wxString volume, path, name, ext;
245 SplitPath(fullpath, &volume, &path, &name, &ext, format);
246
247 Assign(volume, path, name, ext, format);
248 }
249
250 void wxFileName::Assign(const wxString& fullpathOrig,
251 const wxString& fullname,
252 wxPathFormat format)
253 {
254 // always recognize fullpath as directory, even if it doesn't end with a
255 // slash
256 wxString fullpath = fullpathOrig;
257 if ( !wxEndsWithPathSeparator(fullpath) )
258 {
259 fullpath += GetPathSeparators(format)[0u];
260 }
261
262 wxString volume, path, name, ext;
263
264 // do some consistency checks in debug mode: the name should be really just
265 // the filename and the path should be realyl just a path
266 #ifdef __WXDEBUG__
267 wxString pathDummy, nameDummy, extDummy;
268
269 SplitPath(fullname, &pathDummy, &name, &ext, format);
270
271 wxASSERT_MSG( pathDummy.empty(),
272 _T("the file name shouldn't contain the path") );
273
274 SplitPath(fullpath, &volume, &path, &nameDummy, &extDummy, format);
275
276 wxASSERT_MSG( nameDummy.empty() && extDummy.empty(),
277 _T("the path shouldn't contain file name nor extension") );
278
279 #else // !__WXDEBUG__
280 SplitPath(fullname, NULL /* no path */, &name, &ext, format);
281 SplitPath(fullpath, &volume, &path, NULL, NULL, format);
282 #endif // __WXDEBUG__/!__WXDEBUG__
283
284 Assign(volume, path, name, ext, format);
285 }
286
287 void wxFileName::AssignDir(const wxString& dir, wxPathFormat format)
288 {
289 Assign(dir, _T(""), format);
290 }
291
292 void wxFileName::Clear()
293 {
294 m_dirs.Clear();
295
296 m_volume =
297 m_name =
298 m_ext = wxEmptyString;
299 }
300
301 /* static */
302 wxFileName wxFileName::FileName(const wxString& file)
303 {
304 return wxFileName(file);
305 }
306
307 /* static */
308 wxFileName wxFileName::DirName(const wxString& dir)
309 {
310 wxFileName fn;
311 fn.AssignDir(dir);
312 return fn;
313 }
314
315 // ----------------------------------------------------------------------------
316 // existence tests
317 // ----------------------------------------------------------------------------
318
319 bool wxFileName::FileExists()
320 {
321 return wxFileName::FileExists( GetFullPath() );
322 }
323
324 bool wxFileName::FileExists( const wxString &file )
325 {
326 return ::wxFileExists( file );
327 }
328
329 bool wxFileName::DirExists()
330 {
331 return wxFileName::DirExists( GetFullPath() );
332 }
333
334 bool wxFileName::DirExists( const wxString &dir )
335 {
336 return ::wxDirExists( dir );
337 }
338
339 // ----------------------------------------------------------------------------
340 // CWD and HOME stuff
341 // ----------------------------------------------------------------------------
342
343 void wxFileName::AssignCwd(const wxString& volume)
344 {
345 AssignDir(wxFileName::GetCwd(volume));
346 }
347
348 /* static */
349 wxString wxFileName::GetCwd(const wxString& volume)
350 {
351 // if we have the volume, we must get the current directory on this drive
352 // and to do this we have to chdir to this volume - at least under Windows,
353 // I don't know how to get the current drive on another volume elsewhere
354 // (TODO)
355 wxString cwdOld;
356 if ( !volume.empty() )
357 {
358 cwdOld = wxGetCwd();
359 SetCwd(volume + GetVolumeSeparator());
360 }
361
362 wxString cwd = ::wxGetCwd();
363
364 if ( !volume.empty() )
365 {
366 SetCwd(cwdOld);
367 }
368
369 return cwd;
370 }
371
372 bool wxFileName::SetCwd()
373 {
374 return wxFileName::SetCwd( GetFullPath() );
375 }
376
377 bool wxFileName::SetCwd( const wxString &cwd )
378 {
379 return ::wxSetWorkingDirectory( cwd );
380 }
381
382 void wxFileName::AssignHomeDir()
383 {
384 AssignDir(wxFileName::GetHomeDir());
385 }
386
387 wxString wxFileName::GetHomeDir()
388 {
389 return ::wxGetHomeDir();
390 }
391
392 void wxFileName::AssignTempFileName( const wxString& prefix )
393 {
394 wxString tempname = CreateTempFileName(prefix);
395 if ( tempname.empty() )
396 {
397 // error, failed to get temp file name
398 Clear();
399 }
400 else // ok
401 {
402 Assign(tempname);
403 }
404 }
405
406 /* static */
407 wxString wxFileName::CreateTempFileName(const wxString& prefix)
408 {
409 wxString path, dir, name;
410
411 // use the directory specified by the prefix
412 SplitPath(prefix, &dir, &name, NULL /* extension */);
413
414 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
415
416 #ifdef __WIN32__
417 if ( dir.empty() )
418 {
419 if ( !::GetTempPath(MAX_PATH, wxStringBuffer(dir, MAX_PATH + 1)) )
420 {
421 wxLogLastError(_T("GetTempPath"));
422 }
423
424 if ( dir.empty() )
425 {
426 // GetTempFileName() fails if we pass it an empty string
427 dir = _T('.');
428 }
429 }
430
431 if ( !::GetTempFileName(dir, name, 0, wxStringBuffer(path, MAX_PATH + 1)) )
432 {
433 wxLogLastError(_T("GetTempFileName"));
434
435 path.clear();
436 }
437 #else // Win16
438 if ( !::GetTempFileName(NULL, prefix, 0, wxStringBuffer(path, 1025)) )
439 {
440 path.clear();
441 }
442 #endif // Win32/16
443
444 #elif defined(__WXPM__)
445 // for now just create a file
446 //
447 // future enhancements can be to set some extended attributes for file
448 // systems OS/2 supports that have them (HPFS, FAT32) and security
449 // (HPFS386)
450 static const wxChar *szMktempSuffix = wxT("XXX");
451 path << dir << _T('/') << name << szMktempSuffix;
452
453 // Temporarily remove - MN
454 #ifndef __WATCOMC__
455 ::DosCreateDir(wxStringBuffer(MAX_PATH), NULL);
456 #endif
457
458 #else // !Windows, !OS/2
459 if ( dir.empty() )
460 {
461 dir = wxGetenv(_T("TMP"));
462 if ( path.empty() )
463 {
464 dir = wxGetenv(_T("TEMP"));
465 }
466
467 if ( dir.empty() )
468 {
469 // default
470 dir = _T("/tmp");
471 }
472 }
473
474 path = dir;
475
476 if ( !wxEndsWithPathSeparator(dir) &&
477 (name.empty() || !wxIsPathSeparator(name[0u])) )
478 {
479 path += _T('/');
480 }
481
482 path += name;
483
484 #ifdef HAVE_MKSTEMP
485 // scratch space for mkstemp()
486 path += _T("XXXXXX");
487
488 // can use the cast here because the length doesn't change and the string
489 // is not shared
490 if ( mkstemp((char *)path.mb_str()) == -1 )
491 {
492 // this might be not necessary as mkstemp() on most systems should have
493 // already done it but it doesn't hurt neither...
494 path.clear();
495 }
496 //else: file already created
497 #else // !HAVE_MKSTEMP
498
499 #ifdef HAVE_MKTEMP
500 // same as above
501 path += _T("XXXXXX");
502
503 if ( !mktemp((char *)path.mb_str()) )
504 {
505 path.clear();
506 }
507 #else // !HAVE_MKTEMP
508 // generate the unique file name ourselves
509 path << (unsigned int)getpid();
510
511 wxString pathTry;
512
513 static const size_t numTries = 1000;
514 for ( size_t n = 0; n < numTries; n++ )
515 {
516 // 3 hex digits is enough for numTries == 1000 < 4096
517 pathTry = path + wxString::Format(_T("%.03x"), n);
518 if ( !wxFile::Exists(pathTry) )
519 {
520 break;
521 }
522
523 pathTry.clear();
524 }
525
526 path = pathTry;
527 #endif // HAVE_MKTEMP/!HAVE_MKTEMP
528
529 if ( !path.empty() )
530 {
531 // create the file - of course, there is a race condition here, this is
532 // why we always prefer using mkstemp()...
533 wxFile file;
534 if ( !file.Open(path, wxFile::write_excl, wxS_IRUSR | wxS_IWUSR) )
535 {
536 // FIXME: If !ok here should we loop and try again with another
537 // file name? That is the standard recourse if open(O_EXCL)
538 // fails, though of course it should be protected against
539 // possible infinite looping too.
540
541 wxLogError(_("Failed to open temporary file."));
542
543 path.clear();
544 }
545 }
546 #endif // HAVE_MKSTEMP/!HAVE_MKSTEMP
547
548 #endif // Windows/!Windows
549
550 if ( path.empty() )
551 {
552 wxLogSysError(_("Failed to create a temporary file name"));
553 }
554
555 return path;
556 }
557
558 // ----------------------------------------------------------------------------
559 // directory operations
560 // ----------------------------------------------------------------------------
561
562 bool wxFileName::Mkdir( int perm, bool full )
563 {
564 return wxFileName::Mkdir( GetFullPath(), perm, full );
565 }
566
567 bool wxFileName::Mkdir( const wxString &dir, int perm, bool full )
568 {
569 if (full)
570 {
571 wxFileName filename(dir);
572 wxArrayString dirs = filename.GetDirs();
573 dirs.Add(filename.GetName());
574
575 size_t count = dirs.GetCount();
576 size_t i;
577 wxString currPath;
578 int noErrors = 0;
579 for ( i = 0; i < count; i++ )
580 {
581 currPath += dirs[i];
582
583 if (currPath.Last() == wxT(':'))
584 {
585 // Can't create a root directory so continue to next dir
586 currPath += wxFILE_SEP_PATH;
587 continue;
588 }
589
590 if (!DirExists(currPath))
591 if (!wxMkdir(currPath, perm))
592 noErrors ++;
593
594 if ( (i < (count-1)) )
595 currPath += wxFILE_SEP_PATH;
596 }
597
598 return (noErrors == 0);
599
600 }
601 else
602 return ::wxMkdir( dir, perm );
603 }
604
605 bool wxFileName::Rmdir()
606 {
607 return wxFileName::Rmdir( GetFullPath() );
608 }
609
610 bool wxFileName::Rmdir( const wxString &dir )
611 {
612 return ::wxRmdir( dir );
613 }
614
615 // ----------------------------------------------------------------------------
616 // path normalization
617 // ----------------------------------------------------------------------------
618
619 bool wxFileName::Normalize(wxPathNormalize flags,
620 const wxString& cwd,
621 wxPathFormat format)
622 {
623 // the existing path components
624 wxArrayString dirs = GetDirs();
625
626 // the path to prepend in front to make the path absolute
627 wxFileName curDir;
628
629 format = GetFormat(format);
630
631 // make the path absolute
632 if ( (flags & wxPATH_NORM_ABSOLUTE) && !IsAbsolute() )
633 {
634 if ( cwd.empty() )
635 {
636 curDir.AssignCwd(GetVolume());
637 }
638 else // cwd provided
639 {
640 curDir.AssignDir(cwd);
641 }
642
643 // the path may be not absolute because it doesn't have the volume name
644 // but in this case we shouldn't modify the directory components of it
645 // but just set the current volume
646 if ( !HasVolume() && curDir.HasVolume() )
647 {
648 SetVolume(curDir.GetVolume());
649
650 if ( IsAbsolute() )
651 {
652 // yes, it was the case - we don't need curDir then
653 curDir.Clear();
654 }
655 }
656 }
657
658 // handle ~ stuff under Unix only
659 if ( (format == wxPATH_UNIX) && (flags & wxPATH_NORM_TILDE) )
660 {
661 if ( !dirs.IsEmpty() )
662 {
663 wxString dir = dirs[0u];
664 if ( !dir.empty() && dir[0u] == _T('~') )
665 {
666 curDir.AssignDir(wxGetUserHome(dir.c_str() + 1));
667
668 dirs.RemoveAt(0u);
669 }
670 }
671 }
672
673 // transform relative path into abs one
674 if ( curDir.IsOk() )
675 {
676 wxArrayString dirsNew = curDir.GetDirs();
677 size_t count = dirs.GetCount();
678 for ( size_t n = 0; n < count; n++ )
679 {
680 dirsNew.Add(dirs[n]);
681 }
682
683 dirs = dirsNew;
684 }
685
686 // now deal with ".", ".." and the rest
687 m_dirs.Empty();
688 size_t count = dirs.GetCount();
689 for ( size_t n = 0; n < count; n++ )
690 {
691 wxString dir = dirs[n];
692
693 if ( flags & wxPATH_NORM_DOTS )
694 {
695 if ( dir == wxT(".") )
696 {
697 // just ignore
698 continue;
699 }
700
701 if ( dir == wxT("..") )
702 {
703 if ( m_dirs.IsEmpty() )
704 {
705 wxLogError(_("The path '%s' contains too many \"..\"!"),
706 GetFullPath().c_str());
707 return FALSE;
708 }
709
710 m_dirs.Remove(m_dirs.GetCount() - 1);
711 continue;
712 }
713 }
714
715 if ( flags & wxPATH_NORM_ENV_VARS )
716 {
717 dir = wxExpandEnvVars(dir);
718 }
719
720 if ( (flags & wxPATH_NORM_CASE) && !IsCaseSensitive(format) )
721 {
722 dir.MakeLower();
723 }
724
725 m_dirs.Add(dir);
726 }
727
728 if ( (flags & wxPATH_NORM_CASE) && !IsCaseSensitive(format) )
729 {
730 // VZ: expand env vars here too?
731
732 m_name.MakeLower();
733 m_ext.MakeLower();
734 }
735
736 #if defined(__WIN32__)
737 if ( (flags & wxPATH_NORM_LONG) && (format == wxPATH_DOS) )
738 {
739 Assign(GetLongPath());
740 }
741 #endif // Win32
742
743 return TRUE;
744 }
745
746 bool wxFileName::MakeRelativeTo(const wxString& pathBase, wxPathFormat format)
747 {
748 wxFileName fnBase(pathBase, format);
749
750 // get cwd only once - small time saving
751 wxString cwd = wxGetCwd();
752 Normalize(wxPATH_NORM_ALL, cwd, format);
753 fnBase.Normalize(wxPATH_NORM_ALL, cwd, format);
754
755 bool withCase = IsCaseSensitive(format);
756
757 // we can't do anything if the files live on different volumes
758 if ( !GetVolume().IsSameAs(fnBase.GetVolume(), withCase) )
759 {
760 // nothing done
761 return FALSE;
762 }
763
764 // same drive, so we don't need our volume
765 m_volume.clear();
766
767 // remove common directories starting at the top
768 while ( !m_dirs.IsEmpty() && !fnBase.m_dirs.IsEmpty() &&
769 m_dirs[0u].IsSameAs(fnBase.m_dirs[0u], withCase) )
770 {
771 m_dirs.Remove(0u);
772 fnBase.m_dirs.Remove(0u);
773 }
774
775 // add as many ".." as needed
776 size_t count = fnBase.m_dirs.GetCount();
777 for ( size_t i = 0; i < count; i++ )
778 {
779 m_dirs.Insert(wxT(".."), 0u);
780 }
781
782 // we were modified
783 return TRUE;
784 }
785
786 // ----------------------------------------------------------------------------
787 // filename kind tests
788 // ----------------------------------------------------------------------------
789
790 bool wxFileName::SameAs(const wxFileName &filepath, wxPathFormat format)
791 {
792 wxFileName fn1 = *this,
793 fn2 = filepath;
794
795 // get cwd only once - small time saving
796 wxString cwd = wxGetCwd();
797 fn1.Normalize(wxPATH_NORM_ALL, cwd, format);
798 fn2.Normalize(wxPATH_NORM_ALL, cwd, format);
799
800 if ( fn1.GetFullPath() == fn2.GetFullPath() )
801 return TRUE;
802
803 // TODO: compare inodes for Unix, this works even when filenames are
804 // different but files are the same (symlinks) (VZ)
805
806 return FALSE;
807 }
808
809 /* static */
810 bool wxFileName::IsCaseSensitive( wxPathFormat format )
811 {
812 // only Unix filenames are truely case-sensitive
813 return GetFormat(format) == wxPATH_UNIX;
814 }
815
816 bool wxFileName::IsAbsolute( wxPathFormat format )
817 {
818 // if we have no path, we can't be an abs filename
819 if ( m_dirs.IsEmpty() )
820 {
821 return FALSE;
822 }
823
824 format = GetFormat(format);
825
826 if ( format == wxPATH_UNIX )
827 {
828 const wxString& str = m_dirs[0u];
829 if ( str.empty() )
830 {
831 // the path started with '/', it's an absolute one
832 return TRUE;
833 }
834
835 // the path is absolute if it starts with a path separator or
836 // with "~" or "~user"
837 wxChar ch = str[0u];
838
839 return IsPathSeparator(ch, format) || ch == _T('~');
840 }
841 else // !Unix
842 {
843 // must have the drive
844 if ( m_volume.empty() )
845 return FALSE;
846
847 switch ( format )
848 {
849 default:
850 wxFAIL_MSG( _T("unknown wxPATH_XXX style") );
851 // fall through
852
853 case wxPATH_DOS:
854 return m_dirs[0u].empty();
855
856 case wxPATH_VMS:
857 // TODO: what is the relative path format here?
858 return TRUE;
859
860 case wxPATH_MAC:
861 return !m_dirs[0u].empty();
862 }
863 }
864 }
865
866 /* static */
867 wxString wxFileName::GetVolumeSeparator(wxPathFormat format)
868 {
869 wxString sepVol;
870
871 if ( GetFormat(format) != wxPATH_UNIX )
872 {
873 // so far it is the same for all systems which have it
874 sepVol = wxFILE_SEP_DSK;
875 }
876 //else: leave empty, no volume separators under Unix
877
878 return sepVol;
879 }
880
881 /* static */
882 wxString wxFileName::GetPathSeparators(wxPathFormat format)
883 {
884 wxString seps;
885 switch ( GetFormat(format) )
886 {
887 case wxPATH_DOS:
888 // accept both as native APIs do but put the native one first as
889 // this is the one we use in GetFullPath()
890 seps << wxFILE_SEP_PATH_DOS << wxFILE_SEP_PATH_UNIX;
891 break;
892
893 default:
894 wxFAIL_MSG( _T("unknown wxPATH_XXX style") );
895 // fall through
896
897 case wxPATH_UNIX:
898 seps = wxFILE_SEP_PATH_UNIX;
899 break;
900
901 case wxPATH_MAC:
902 seps = wxFILE_SEP_PATH_MAC;
903 break;
904
905 case wxPATH_VMS:
906 seps = wxFILE_SEP_PATH_VMS;
907 break;
908 }
909
910 return seps;
911 }
912
913 /* static */
914 bool wxFileName::IsPathSeparator(wxChar ch, wxPathFormat format)
915 {
916 // wxString::Find() doesn't work as expected with NUL - it will always find
917 // it, so it is almost surely a bug if this function is called with NUL arg
918 wxASSERT_MSG( ch != _T('\0'), _T("shouldn't be called with NUL") );
919
920 return GetPathSeparators(format).Find(ch) != wxNOT_FOUND;
921 }
922
923 bool wxFileName::IsWild( wxPathFormat format )
924 {
925 // FIXME: this is probably false for Mac and this is surely wrong for most
926 // of Unix shells (think about "[...]")
927 (void)format;
928 return m_name.find_first_of(_T("*?")) != wxString::npos;
929 }
930
931 // ----------------------------------------------------------------------------
932 // path components manipulation
933 // ----------------------------------------------------------------------------
934
935 void wxFileName::AppendDir( const wxString &dir )
936 {
937 m_dirs.Add( dir );
938 }
939
940 void wxFileName::PrependDir( const wxString &dir )
941 {
942 m_dirs.Insert( dir, 0 );
943 }
944
945 void wxFileName::InsertDir( int before, const wxString &dir )
946 {
947 m_dirs.Insert( dir, before );
948 }
949
950 void wxFileName::RemoveDir( int pos )
951 {
952 m_dirs.Remove( (size_t)pos );
953 }
954
955 // ----------------------------------------------------------------------------
956 // accessors
957 // ----------------------------------------------------------------------------
958
959 void wxFileName::SetFullName(const wxString& fullname)
960 {
961 SplitPath(fullname, NULL /* no path */, &m_name, &m_ext);
962 }
963
964 wxString wxFileName::GetFullName() const
965 {
966 wxString fullname = m_name;
967 if ( !m_ext.empty() )
968 {
969 fullname << wxFILE_SEP_EXT << m_ext;
970 }
971
972 return fullname;
973 }
974
975 wxString wxFileName::GetPath( bool add_separator, wxPathFormat format ) const
976 {
977 format = GetFormat( format );
978
979 wxString ret;
980 size_t count = m_dirs.GetCount();
981 for ( size_t i = 0; i < count; i++ )
982 {
983 ret += m_dirs[i];
984 if ( add_separator || (i < count) )
985 ret += wxFILE_SEP_PATH;
986 }
987
988 return ret;
989 }
990
991 wxString wxFileName::GetFullPath( wxPathFormat format ) const
992 {
993 format = GetFormat(format);
994
995 wxString fullpath;
996
997 // first put the volume
998 if ( !m_volume.empty() )
999 {
1000 // special Windows UNC paths hack, part 2: undo what we did in
1001 // SplitPath() and make an UNC path if we have a drive which is not a
1002 // single letter (hopefully the network shares can't be one letter only
1003 // although I didn't find any authoritative docs on this)
1004 if ( format == wxPATH_DOS && m_volume.length() > 1 )
1005 {
1006 fullpath << wxFILE_SEP_PATH_DOS << wxFILE_SEP_PATH_DOS << m_volume;
1007 }
1008 else // !UNC
1009 {
1010 fullpath << m_volume << GetVolumeSeparator(format);
1011 }
1012 }
1013
1014 // then concatenate all the path components using the path separator
1015 size_t dirCount = m_dirs.GetCount();
1016 if ( dirCount )
1017 {
1018 // under Mac, we must have a path separator in the beginning of the
1019 // relative path - otherwise it would be parsed as an absolute one
1020 if ( format == wxPATH_MAC && m_volume.empty() && !m_dirs[0].empty() )
1021 {
1022 fullpath += wxFILE_SEP_PATH_MAC;
1023 }
1024
1025 wxChar chPathSep = GetPathSeparators(format)[0u];
1026 if ( format == wxPATH_VMS )
1027 {
1028 fullpath += _T('[');
1029 }
1030
1031 for ( size_t i = 0; i < dirCount; i++ )
1032 {
1033 // under VMS, we shouldn't have a leading dot
1034 if ( i && (format != wxPATH_VMS || !m_dirs[i - 1].empty()) )
1035 fullpath += chPathSep;
1036
1037 fullpath += m_dirs[i];
1038 }
1039
1040 if ( format == wxPATH_VMS )
1041 {
1042 fullpath += _T(']');
1043 }
1044 else // !VMS
1045 {
1046 // separate the file name from the last directory, notice that we
1047 // intentionally do it even if the name and extension are empty as
1048 // this allows us to distinguish the directories from the file
1049 // names (the directories have the trailing slash)
1050 fullpath += chPathSep;
1051 }
1052 }
1053
1054 // finally add the file name and extension
1055 fullpath += GetFullName();
1056
1057 return fullpath;
1058 }
1059
1060 // Return the short form of the path (returns identity on non-Windows platforms)
1061 wxString wxFileName::GetShortPath() const
1062 {
1063 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__)
1064 wxString path(GetFullPath());
1065 wxString pathOut;
1066 DWORD sz = ::GetShortPathName(path, NULL, 0);
1067 bool ok = sz != 0;
1068 if ( ok )
1069 {
1070 ok = ::GetShortPathName
1071 (
1072 path,
1073 pathOut.GetWriteBuf(sz),
1074 sz
1075 ) != 0;
1076 pathOut.UngetWriteBuf();
1077 }
1078 if (ok)
1079 return pathOut;
1080
1081 return path;
1082 #else
1083 return GetFullPath();
1084 #endif
1085 }
1086
1087 // Return the long form of the path (returns identity on non-Windows platforms)
1088 wxString wxFileName::GetLongPath() const
1089 {
1090 wxString pathOut,
1091 path = GetFullPath();
1092
1093 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1094 bool success = FALSE;
1095
1096 // VZ: this code was disabled, why?
1097 #if 0 // wxUSE_DYNLIB_CLASS
1098 typedef DWORD (*GET_LONG_PATH_NAME)(const wxChar *, wxChar *, DWORD);
1099
1100 static bool s_triedToLoad = FALSE;
1101
1102 if ( !s_triedToLoad )
1103 {
1104 s_triedToLoad = TRUE;
1105 wxDllType dllKernel = wxDllLoader::LoadLibrary(_T("kernel32"));
1106 if ( dllKernel )
1107 {
1108 // may succeed or fail depending on the Windows version
1109 static GET_LONG_PATH_NAME s_pfnGetLongPathName = NULL;
1110 #ifdef _UNICODE
1111 s_pfnGetLongPathName = (GET_LONG_PATH_NAME) wxDllLoader::GetSymbol(dllKernel, _T("GetLongPathNameW"));
1112 #else
1113 s_pfnGetLongPathName = (GET_LONG_PATH_NAME) wxDllLoader::GetSymbol(dllKernel, _T("GetLongPathNameA"));
1114 #endif
1115
1116 wxDllLoader::UnloadLibrary(dllKernel);
1117
1118 if ( s_pfnGetLongPathName )
1119 {
1120 DWORD dwSize = (*s_pfnGetLongPathName)(path, NULL, 0);
1121 bool ok = dwSize > 0;
1122
1123 if ( ok )
1124 {
1125 DWORD sz = (*s_pfnGetLongPathName)(path, NULL, 0);
1126 ok = sz != 0;
1127 if ( ok )
1128 {
1129 ok = (*s_pfnGetLongPathName)
1130 (
1131 path,
1132 pathOut.GetWriteBuf(sz),
1133 sz
1134 ) != 0;
1135 pathOut.UngetWriteBuf();
1136
1137 success = TRUE;
1138 }
1139 }
1140 }
1141 }
1142 }
1143 if (success)
1144 return pathOut;
1145 #endif // wxUSE_DYNLIB_CLASS
1146
1147 if (!success)
1148 {
1149 // The OS didn't support GetLongPathName, or some other error.
1150 // We need to call FindFirstFile on each component in turn.
1151
1152 WIN32_FIND_DATA findFileData;
1153 HANDLE hFind;
1154 pathOut = wxEmptyString;
1155
1156 wxArrayString dirs = GetDirs();
1157 dirs.Add(GetFullName());
1158
1159 wxString tmpPath;
1160
1161 size_t count = dirs.GetCount();
1162 for ( size_t i = 0; i < count; i++ )
1163 {
1164 // We're using pathOut to collect the long-name path, but using a
1165 // temporary for appending the last path component which may be
1166 // short-name
1167 tmpPath = pathOut + dirs[i];
1168
1169 if ( tmpPath.empty() )
1170 continue;
1171
1172 if ( tmpPath.Last() == wxT(':') )
1173 {
1174 // Can't pass a drive and root dir to FindFirstFile,
1175 // so continue to next dir
1176 tmpPath += wxFILE_SEP_PATH;
1177 pathOut = tmpPath;
1178 continue;
1179 }
1180
1181 hFind = ::FindFirstFile(tmpPath, &findFileData);
1182 if (hFind == INVALID_HANDLE_VALUE)
1183 {
1184 // Error: return immediately with the original path
1185 return path;
1186 }
1187
1188 pathOut += findFileData.cFileName;
1189 if ( (i < (count-1)) )
1190 pathOut += wxFILE_SEP_PATH;
1191
1192 ::FindClose(hFind);
1193 }
1194 }
1195 #else // !Win32
1196 pathOut = path;
1197 #endif // Win32/!Win32
1198
1199 return pathOut;
1200 }
1201
1202 wxPathFormat wxFileName::GetFormat( wxPathFormat format )
1203 {
1204 if (format == wxPATH_NATIVE)
1205 {
1206 #if defined(__WXMSW__) || defined(__WXPM__)
1207 format = wxPATH_DOS;
1208 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1209 format = wxPATH_MAC;
1210 #elif defined(__VMS)
1211 format = wxPATH_VMS;
1212 #else
1213 format = wxPATH_UNIX;
1214 #endif
1215 }
1216 return format;
1217 }
1218
1219 // ----------------------------------------------------------------------------
1220 // path splitting function
1221 // ----------------------------------------------------------------------------
1222
1223 /* static */
1224 void wxFileName::SplitPath(const wxString& fullpathWithVolume,
1225 wxString *pstrVolume,
1226 wxString *pstrPath,
1227 wxString *pstrName,
1228 wxString *pstrExt,
1229 wxPathFormat format)
1230 {
1231 format = GetFormat(format);
1232
1233 wxString fullpath = fullpathWithVolume;
1234
1235 // under VMS the end of the path is ']', not the path separator used to
1236 // separate the components
1237 wxString sepPath = format == wxPATH_VMS ? wxString(_T(']'))
1238 : GetPathSeparators(format);
1239
1240 // special Windows UNC paths hack: transform \\share\path into share:path
1241 if ( format == wxPATH_DOS )
1242 {
1243 if ( fullpath.length() >= 4 &&
1244 fullpath[0u] == wxFILE_SEP_PATH_DOS &&
1245 fullpath[1u] == wxFILE_SEP_PATH_DOS )
1246 {
1247 fullpath.erase(0, 2);
1248
1249 size_t posFirstSlash = fullpath.find_first_of(sepPath);
1250 if ( posFirstSlash != wxString::npos )
1251 {
1252 fullpath[posFirstSlash] = wxFILE_SEP_DSK;
1253
1254 // UNC paths are always absolute, right? (FIXME)
1255 fullpath.insert(posFirstSlash + 1, wxFILE_SEP_PATH_DOS);
1256 }
1257 }
1258 }
1259
1260 // do we have the volume name in the beginning?
1261 wxString sepVol = GetVolumeSeparator(format);
1262 if ( !sepVol.empty() )
1263 {
1264 size_t posFirstColon = fullpath.find_first_of(sepVol);
1265 if ( posFirstColon != wxString::npos )
1266 {
1267 if ( pstrVolume )
1268 {
1269 *pstrVolume = fullpath.Left(posFirstColon);
1270 }
1271
1272 // remove the volume name and the separator from the full path
1273 fullpath.erase(0, posFirstColon + sepVol.length());
1274 }
1275 }
1276
1277 // find the positions of the last dot and last path separator in the path
1278 size_t posLastDot = fullpath.find_last_of(wxFILE_SEP_EXT);
1279 size_t posLastSlash = fullpath.find_last_of(sepPath);
1280
1281 if ( (posLastDot != wxString::npos) &&
1282 ((format == wxPATH_UNIX) || (format == wxPATH_VMS)) )
1283 {
1284 if ( (posLastDot == 0) ||
1285 (fullpath[posLastDot - 1] == sepPath[0u] ) )
1286 {
1287 // under Unix and VMS, dot may be (and commonly is) the first
1288 // character of the filename, don't treat the entire filename as
1289 // extension in this case
1290 posLastDot = wxString::npos;
1291 }
1292 }
1293
1294 // if we do have a dot and a slash, check that the dot is in the name part
1295 if ( (posLastDot != wxString::npos) &&
1296 (posLastSlash != wxString::npos) &&
1297 (posLastDot < posLastSlash) )
1298 {
1299 // the dot is part of the path, not the start of the extension
1300 posLastDot = wxString::npos;
1301 }
1302
1303 // now fill in the variables provided by user
1304 if ( pstrPath )
1305 {
1306 if ( posLastSlash == wxString::npos )
1307 {
1308 // no path at all
1309 pstrPath->Empty();
1310 }
1311 else
1312 {
1313 // take everything up to the path separator but take care to make
1314 // tha path equal to something like '/', not empty, for the files
1315 // immediately under root directory
1316 size_t len = posLastSlash;
1317 if ( !len )
1318 len++;
1319
1320 *pstrPath = fullpath.Left(len);
1321
1322 // special VMS hack: remove the initial bracket
1323 if ( format == wxPATH_VMS )
1324 {
1325 if ( (*pstrPath)[0u] == _T('[') )
1326 pstrPath->erase(0, 1);
1327 }
1328 }
1329 }
1330
1331 if ( pstrName )
1332 {
1333 // take all characters starting from the one after the last slash and
1334 // up to, but excluding, the last dot
1335 size_t nStart = posLastSlash == wxString::npos ? 0 : posLastSlash + 1;
1336 size_t count;
1337 if ( posLastDot == wxString::npos )
1338 {
1339 // take all until the end
1340 count = wxString::npos;
1341 }
1342 else if ( posLastSlash == wxString::npos )
1343 {
1344 count = posLastDot;
1345 }
1346 else // have both dot and slash
1347 {
1348 count = posLastDot - posLastSlash - 1;
1349 }
1350
1351 *pstrName = fullpath.Mid(nStart, count);
1352 }
1353
1354 if ( pstrExt )
1355 {
1356 if ( posLastDot == wxString::npos )
1357 {
1358 // no extension
1359 pstrExt->Empty();
1360 }
1361 else
1362 {
1363 // take everything after the dot
1364 *pstrExt = fullpath.Mid(posLastDot + 1);
1365 }
1366 }
1367 }
1368
1369 /* static */
1370 void wxFileName::SplitPath(const wxString& fullpath,
1371 wxString *path,
1372 wxString *name,
1373 wxString *ext,
1374 wxPathFormat format)
1375 {
1376 wxString volume;
1377 SplitPath(fullpath, &volume, path, name, ext, format);
1378
1379 if ( path && !volume.empty() )
1380 {
1381 path->Prepend(volume + GetVolumeSeparator(format));
1382 }
1383 }
1384
1385 // ----------------------------------------------------------------------------
1386 // time functions
1387 // ----------------------------------------------------------------------------
1388
1389 bool wxFileName::SetTimes(const wxDateTime *dtCreate,
1390 const wxDateTime *dtAccess,
1391 const wxDateTime *dtMod)
1392 {
1393 #if defined(__UNIX_LIKE__)
1394 if ( !dtAccess && !dtMod )
1395 {
1396 // can't modify the creation time anyhow, don't try
1397 return TRUE;
1398 }
1399
1400 // if dtAccess or dtMod is not specified, use the other one (which must be
1401 // non NULL because of the test above) for both times
1402 utimbuf utm;
1403 utm.actime = dtAccess ? dtAccess->GetTicks() : dtMod->GetTicks();
1404 utm.modtime = dtMod ? dtMod->GetTicks() : dtAccess->GetTicks();
1405 if ( utime(GetFullPath(), &utm) == 0 )
1406 {
1407 return TRUE;
1408 }
1409 #elif defined(__WIN32__)
1410 wxFileHandle fh(GetFullPath());
1411 if ( fh.IsOk() )
1412 {
1413 FILETIME ftAccess, ftCreate, ftWrite;
1414
1415 if ( dtCreate )
1416 ConvertWxToFileTime(&ftCreate, *dtCreate);
1417 if ( dtAccess )
1418 ConvertWxToFileTime(&ftAccess, *dtAccess);
1419 if ( dtMod )
1420 ConvertWxToFileTime(&ftWrite, *dtMod);
1421
1422 if ( ::SetFileTime(fh,
1423 dtCreate ? &ftCreate : NULL,
1424 dtAccess ? &ftAccess : NULL,
1425 dtMod ? &ftWrite : NULL) )
1426 {
1427 return TRUE;
1428 }
1429 }
1430 #else // other platform
1431 #endif // platforms
1432
1433 wxLogSysError(_("Failed to modify file times for '%s'"),
1434 GetFullPath().c_str());
1435
1436 return FALSE;
1437 }
1438
1439 bool wxFileName::Touch()
1440 {
1441 #if defined(__UNIX_LIKE__)
1442 // under Unix touching file is simple: just pass NULL to utime()
1443 if ( utime(GetFullPath(), NULL) == 0 )
1444 {
1445 return TRUE;
1446 }
1447
1448 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
1449
1450 return FALSE;
1451 #else // other platform
1452 wxDateTime dtNow = wxDateTime::Now();
1453
1454 return SetTimes(NULL /* don't change create time */, &dtNow, &dtNow);
1455 #endif // platforms
1456 }
1457
1458 bool wxFileName::GetTimes(wxDateTime *dtAccess,
1459 wxDateTime *dtMod,
1460 wxDateTime *dtChange) const
1461 {
1462 #if defined(__UNIX_LIKE__)
1463 wxStructStat stBuf;
1464 if ( wxStat(GetFullPath(), &stBuf) == 0 )
1465 {
1466 if ( dtAccess )
1467 dtAccess->Set(stBuf.st_atime);
1468 if ( dtMod )
1469 dtMod->Set(stBuf.st_mtime);
1470 if ( dtChange )
1471 dtChange->Set(stBuf.st_ctime);
1472
1473 return TRUE;
1474 }
1475 #elif defined(__WXMAC__)
1476 wxStructStat stBuf;
1477 if ( wxStat(GetFullPath(), &stBuf) == 0 )
1478 {
1479 if ( dtAccess )
1480 dtAccess->Set(stBuf.st_atime);
1481 if ( dtMod )
1482 dtMod->Set(stBuf.st_mtime);
1483 if ( dtChange )
1484 dtChange->Set(stBuf.st_ctime);
1485
1486 return TRUE;
1487 }
1488 #elif defined(__WIN32__)
1489 wxFileHandle fh(GetFullPath());
1490 if ( fh.IsOk() )
1491 {
1492 FILETIME ftAccess, ftCreate, ftWrite;
1493
1494 if ( ::GetFileTime(fh,
1495 dtMod ? &ftCreate : NULL,
1496 dtAccess ? &ftAccess : NULL,
1497 dtChange ? &ftWrite : NULL) )
1498 {
1499 if ( dtMod )
1500 ConvertFileTimeToWx(dtMod, ftCreate);
1501 if ( dtAccess )
1502 ConvertFileTimeToWx(dtAccess, ftAccess);
1503 if ( dtChange )
1504 ConvertFileTimeToWx(dtChange, ftWrite);
1505
1506 return TRUE;
1507 }
1508 }
1509 #else // other platform
1510 #endif // platforms
1511
1512 wxLogSysError(_("Failed to retrieve file times for '%s'"),
1513 GetFullPath().c_str());
1514
1515 return FALSE;
1516 }
1517