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