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