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