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