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