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