]> git.saurik.com Git - wxWidgets.git/blob - src/common/filename.cpp
Correct fix to the compile time assert under OW. Kudos to Vadim to the tip.
[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 licence
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 Since the volume is just part of the file path, it is not
36 treated like a separate entity as it is done under DOS and
37 VMS, it is just treated as another dir.
38
39 wxPATH_VMS: VMS native format, absolute file names have the form
40 <device>:[dir1.dir2.dir3]file.txt
41 or
42 <device>:[000000.dir1.dir2.dir3]file.txt
43
44 the <device> is the physical device (i.e. disk). 000000 is the
45 root directory on the device which can be omitted.
46
47 Note that VMS uses different separators unlike Unix:
48 : always after the device. If the path does not contain : than
49 the default (the device of the current directory) is assumed.
50 [ start of directory specification
51 . separator between directory and subdirectory
52 ] between directory and file
53 */
54
55 // ============================================================================
56 // declarations
57 // ============================================================================
58
59 // ----------------------------------------------------------------------------
60 // headers
61 // ----------------------------------------------------------------------------
62
63 #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
64 #pragma implementation "filename.h"
65 #endif
66
67 // For compilers that support precompilation, includes "wx.h".
68 #include "wx/wxprec.h"
69
70 #ifdef __BORLANDC__
71 #pragma hdrstop
72 #endif
73
74 #ifndef WX_PRECOMP
75 #include "wx/intl.h"
76 #include "wx/log.h"
77 #include "wx/file.h"
78 #endif
79
80 #include "wx/filename.h"
81 #include "wx/tokenzr.h"
82 #include "wx/config.h" // for wxExpandEnvVars
83 #include "wx/utils.h"
84 #include "wx/file.h"
85 #include "wx/dynlib.h"
86
87 // For GetShort/LongPathName
88 #ifdef __WIN32__
89 #include "wx/msw/wrapwin.h"
90 #if defined(__MINGW32__)
91 #include "wx/msw/gccpriv.h"
92 #endif
93 #endif
94
95 #ifdef __WXWINCE__
96 #include "wx/msw/private.h"
97 #endif
98
99 #if defined(__WXMAC__)
100 #include "wx/mac/private.h" // includes mac headers
101 #endif
102
103 // utime() is POSIX so should normally be available on all Unices
104 #ifdef __UNIX_LIKE__
105 #include <sys/types.h>
106 #include <utime.h>
107 #include <sys/stat.h>
108 #include <unistd.h>
109 #endif
110
111 #ifdef __DJGPP__
112 #include <unistd.h>
113 #endif
114
115 #ifdef __MWERKS__
116 #ifdef __MACH__
117 #include <sys/types.h>
118 #include <utime.h>
119 #include <sys/stat.h>
120 #include <unistd.h>
121 #else
122 #include <stat.h>
123 #include <unistd.h>
124 #include <unix.h>
125 #endif
126 #endif
127
128 #ifdef __WATCOMC__
129 #include <io.h>
130 #include <sys/utime.h>
131 #include <sys/stat.h>
132 #endif
133
134 #ifdef __VISAGECPP__
135 #ifndef MAX_PATH
136 #define MAX_PATH 256
137 #endif
138 #endif
139
140 #ifdef __EMX__
141 #include <os2.h>
142 #define MAX_PATH _MAX_PATH
143 #endif
144
145 // ----------------------------------------------------------------------------
146 // private classes
147 // ----------------------------------------------------------------------------
148
149 // small helper class which opens and closes the file - we use it just to get
150 // a file handle for the given file name to pass it to some Win32 API function
151 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
152
153 class wxFileHandle
154 {
155 public:
156 enum OpenMode
157 {
158 Read,
159 Write
160 };
161
162 wxFileHandle(const wxString& filename, OpenMode mode)
163 {
164 m_hFile = ::CreateFile
165 (
166 filename, // name
167 mode == Read ? GENERIC_READ // access mask
168 : GENERIC_WRITE,
169 FILE_SHARE_READ | // sharing mode
170 FILE_SHARE_WRITE, // (allow everything)
171 NULL, // no secutity attr
172 OPEN_EXISTING, // creation disposition
173 0, // no flags
174 NULL // no template file
175 );
176
177 if ( m_hFile == INVALID_HANDLE_VALUE )
178 {
179 wxLogSysError(_("Failed to open '%s' for %s"),
180 filename.c_str(),
181 mode == Read ? _("reading") : _("writing"));
182 }
183 }
184
185 ~wxFileHandle()
186 {
187 if ( m_hFile != INVALID_HANDLE_VALUE )
188 {
189 if ( !::CloseHandle(m_hFile) )
190 {
191 wxLogSysError(_("Failed to close file handle"));
192 }
193 }
194 }
195
196 // return true only if the file could be opened successfully
197 bool IsOk() const { return m_hFile != INVALID_HANDLE_VALUE; }
198
199 // get the handle
200 operator HANDLE() const { return m_hFile; }
201
202 private:
203 HANDLE m_hFile;
204 };
205
206 #endif // __WIN32__
207
208 // ----------------------------------------------------------------------------
209 // private functions
210 // ----------------------------------------------------------------------------
211
212 #if wxUSE_DATETIME && defined(__WIN32__) && !defined(__WXMICROWIN__)
213
214 // convert between wxDateTime and FILETIME which is a 64-bit value representing
215 // the number of 100-nanosecond intervals since January 1, 1601.
216
217 static void ConvertFileTimeToWx(wxDateTime *dt, const FILETIME &ft)
218 {
219 FILETIME ftcopy = ft;
220 FILETIME ftLocal;
221 if ( !::FileTimeToLocalFileTime(&ftcopy, &ftLocal) )
222 {
223 wxLogLastError(_T("FileTimeToLocalFileTime"));
224 }
225
226 SYSTEMTIME st;
227 if ( !::FileTimeToSystemTime(&ftLocal, &st) )
228 {
229 wxLogLastError(_T("FileTimeToSystemTime"));
230 }
231
232 dt->Set(st.wDay, wxDateTime::Month(st.wMonth - 1), st.wYear,
233 st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
234 }
235
236 static void ConvertWxToFileTime(FILETIME *ft, const wxDateTime& dt)
237 {
238 SYSTEMTIME st;
239 st.wDay = dt.GetDay();
240 st.wMonth = (WORD)(dt.GetMonth() + 1);
241 st.wYear = (WORD)dt.GetYear();
242 st.wHour = dt.GetHour();
243 st.wMinute = dt.GetMinute();
244 st.wSecond = dt.GetSecond();
245 st.wMilliseconds = dt.GetMillisecond();
246
247 FILETIME ftLocal;
248 if ( !::SystemTimeToFileTime(&st, &ftLocal) )
249 {
250 wxLogLastError(_T("SystemTimeToFileTime"));
251 }
252
253 if ( !::LocalFileTimeToFileTime(&ftLocal, ft) )
254 {
255 wxLogLastError(_T("LocalFileTimeToFileTime"));
256 }
257 }
258
259 #endif // wxUSE_DATETIME && __WIN32__
260
261 // return a string with the volume par
262 static wxString wxGetVolumeString(const wxString& volume, wxPathFormat format)
263 {
264 wxString path;
265
266 if ( !volume.empty() )
267 {
268 format = wxFileName::GetFormat(format);
269
270 // Special Windows UNC paths hack, part 2: undo what we did in
271 // SplitPath() and make an UNC path if we have a drive which is not a
272 // single letter (hopefully the network shares can't be one letter only
273 // although I didn't find any authoritative docs on this)
274 if ( format == wxPATH_DOS && volume.length() > 1 )
275 {
276 path << wxFILE_SEP_PATH_DOS << wxFILE_SEP_PATH_DOS << volume;
277 }
278 else if ( format == wxPATH_DOS || format == wxPATH_VMS )
279 {
280 path << volume << wxFileName::GetVolumeSeparator(format);
281 }
282 // else ignore
283 }
284
285 return path;
286 }
287
288 // ============================================================================
289 // implementation
290 // ============================================================================
291
292 // ----------------------------------------------------------------------------
293 // wxFileName construction
294 // ----------------------------------------------------------------------------
295
296 void wxFileName::Assign( const wxFileName &filepath )
297 {
298 m_volume = filepath.GetVolume();
299 m_dirs = filepath.GetDirs();
300 m_name = filepath.GetName();
301 m_ext = filepath.GetExt();
302 m_relative = filepath.m_relative;
303 }
304
305 void wxFileName::Assign(const wxString& volume,
306 const wxString& path,
307 const wxString& name,
308 const wxString& ext,
309 wxPathFormat format )
310 {
311 SetPath( path, format );
312
313 m_volume = volume;
314 m_ext = ext;
315 m_name = name;
316 }
317
318 void wxFileName::SetPath( const wxString& pathOrig, wxPathFormat format )
319 {
320 m_dirs.Clear();
321
322 if ( pathOrig.empty() )
323 {
324 // no path at all
325 m_relative = true;
326
327 return;
328 }
329
330 format = GetFormat( format );
331
332 // 0) deal with possible volume part first
333 wxString volume,
334 path;
335 SplitVolume(pathOrig, &volume, &path, format);
336 if ( !volume.empty() )
337 {
338 m_relative = false;
339
340 SetVolume(volume);
341 }
342
343 // 1) Determine if the path is relative or absolute.
344 wxChar leadingChar = path[0u];
345
346 switch (format)
347 {
348 case wxPATH_MAC:
349 m_relative = leadingChar == wxT(':');
350
351 // We then remove a leading ":". The reason is in our
352 // storage form for relative paths:
353 // ":dir:file.txt" actually means "./dir/file.txt" in
354 // DOS notation and should get stored as
355 // (relative) (dir) (file.txt)
356 // "::dir:file.txt" actually means "../dir/file.txt"
357 // stored as (relative) (..) (dir) (file.txt)
358 // This is important only for the Mac as an empty dir
359 // actually means <UP>, whereas under DOS, double
360 // slashes can be ignored: "\\\\" is the same as "\\".
361 if (m_relative)
362 path.erase( 0, 1 );
363 break;
364
365 case wxPATH_VMS:
366 // TODO: what is the relative path format here?
367 m_relative = false;
368 break;
369
370 default:
371 wxFAIL_MSG( _T("Unknown path format") );
372 // !! Fall through !!
373
374 case wxPATH_UNIX:
375 // the paths of the form "~" or "~username" are absolute
376 m_relative = leadingChar != wxT('/') && leadingChar != _T('~');
377 break;
378
379 case wxPATH_DOS:
380 m_relative = !IsPathSeparator(leadingChar, format);
381 break;
382
383 }
384
385 // 2) Break up the path into its members. If the original path
386 // was just "/" or "\\", m_dirs will be empty. We know from
387 // the m_relative field, if this means "nothing" or "root dir".
388
389 wxStringTokenizer tn( path, GetPathSeparators(format) );
390
391 while ( tn.HasMoreTokens() )
392 {
393 wxString token = tn.GetNextToken();
394
395 // Remove empty token under DOS and Unix, interpret them
396 // as .. under Mac.
397 if (token.empty())
398 {
399 if (format == wxPATH_MAC)
400 m_dirs.Add( wxT("..") );
401 // else ignore
402 }
403 else
404 {
405 m_dirs.Add( token );
406 }
407 }
408 }
409
410 void wxFileName::Assign(const wxString& fullpath,
411 wxPathFormat format)
412 {
413 wxString volume, path, name, ext;
414 SplitPath(fullpath, &volume, &path, &name, &ext, format);
415
416 Assign(volume, path, name, ext, format);
417 }
418
419 void wxFileName::Assign(const wxString& fullpathOrig,
420 const wxString& fullname,
421 wxPathFormat format)
422 {
423 // always recognize fullpath as directory, even if it doesn't end with a
424 // slash
425 wxString fullpath = fullpathOrig;
426 if ( !wxEndsWithPathSeparator(fullpath) )
427 {
428 fullpath += GetPathSeparator(format);
429 }
430
431 wxString volume, path, name, ext;
432
433 // do some consistency checks in debug mode: the name should be really just
434 // the filename and the path should be really just a path
435 #ifdef __WXDEBUG__
436 wxString pathDummy, nameDummy, extDummy;
437
438 SplitPath(fullname, &pathDummy, &name, &ext, format);
439
440 wxASSERT_MSG( pathDummy.empty(),
441 _T("the file name shouldn't contain the path") );
442
443 SplitPath(fullpath, &volume, &path, &nameDummy, &extDummy, format);
444
445 wxASSERT_MSG( nameDummy.empty() && extDummy.empty(),
446 _T("the path shouldn't contain file name nor extension") );
447
448 #else // !__WXDEBUG__
449 SplitPath(fullname, NULL /* no path */, &name, &ext, format);
450 SplitPath(fullpath, &volume, &path, NULL, NULL, format);
451 #endif // __WXDEBUG__/!__WXDEBUG__
452
453 Assign(volume, path, name, ext, format);
454 }
455
456 void wxFileName::AssignDir(const wxString& dir, wxPathFormat format)
457 {
458 Assign(dir, _T(""), format);
459 }
460
461 void wxFileName::Clear()
462 {
463 m_dirs.Clear();
464
465 m_volume =
466 m_name =
467 m_ext = wxEmptyString;
468
469 // we don't have any absolute path for now
470 m_relative = true;
471 }
472
473 /* static */
474 wxFileName wxFileName::FileName(const wxString& file, wxPathFormat format)
475 {
476 return wxFileName(file, format);
477 }
478
479 /* static */
480 wxFileName wxFileName::DirName(const wxString& dir, wxPathFormat format)
481 {
482 wxFileName fn;
483 fn.AssignDir(dir, format);
484 return fn;
485 }
486
487 // ----------------------------------------------------------------------------
488 // existence tests
489 // ----------------------------------------------------------------------------
490
491 bool wxFileName::FileExists() const
492 {
493 return wxFileName::FileExists( GetFullPath() );
494 }
495
496 bool wxFileName::FileExists( const wxString &file )
497 {
498 return ::wxFileExists( file );
499 }
500
501 bool wxFileName::DirExists() const
502 {
503 return wxFileName::DirExists( GetFullPath() );
504 }
505
506 bool wxFileName::DirExists( const wxString &dir )
507 {
508 return ::wxDirExists( dir );
509 }
510
511 // ----------------------------------------------------------------------------
512 // CWD and HOME stuff
513 // ----------------------------------------------------------------------------
514
515 void wxFileName::AssignCwd(const wxString& volume)
516 {
517 AssignDir(wxFileName::GetCwd(volume));
518 }
519
520 /* static */
521 wxString wxFileName::GetCwd(const wxString& volume)
522 {
523 // if we have the volume, we must get the current directory on this drive
524 // and to do this we have to chdir to this volume - at least under Windows,
525 // I don't know how to get the current drive on another volume elsewhere
526 // (TODO)
527 wxString cwdOld;
528 if ( !volume.empty() )
529 {
530 cwdOld = wxGetCwd();
531 SetCwd(volume + GetVolumeSeparator());
532 }
533
534 wxString cwd = ::wxGetCwd();
535
536 if ( !volume.empty() )
537 {
538 SetCwd(cwdOld);
539 }
540
541 return cwd;
542 }
543
544 bool wxFileName::SetCwd()
545 {
546 return wxFileName::SetCwd( GetFullPath() );
547 }
548
549 bool wxFileName::SetCwd( const wxString &cwd )
550 {
551 return ::wxSetWorkingDirectory( cwd );
552 }
553
554 void wxFileName::AssignHomeDir()
555 {
556 AssignDir(wxFileName::GetHomeDir());
557 }
558
559 wxString wxFileName::GetHomeDir()
560 {
561 return ::wxGetHomeDir();
562 }
563
564 void wxFileName::AssignTempFileName(const wxString& prefix, wxFile *fileTemp)
565 {
566 wxString tempname = CreateTempFileName(prefix, fileTemp);
567 if ( tempname.empty() )
568 {
569 // error, failed to get temp file name
570 Clear();
571 }
572 else // ok
573 {
574 Assign(tempname);
575 }
576 }
577
578 /* static */
579 wxString
580 wxFileName::CreateTempFileName(const wxString& prefix, wxFile *fileTemp)
581 {
582 wxString path, dir, name;
583
584 // use the directory specified by the prefix
585 SplitPath(prefix, &dir, &name, NULL /* extension */);
586
587 #if defined(__WXWINCE__)
588 if (dir.empty())
589 {
590 // FIXME. Create \temp dir?
591 dir = wxT("\\");
592 }
593 path = dir + wxT("\\") + prefix;
594 int i = 1;
595 while (wxFileExists(path))
596 {
597 path = dir + wxT("\\") + prefix ;
598 path << i;
599 i ++;
600 }
601
602 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
603
604 if ( dir.empty() )
605 {
606 if ( !::GetTempPath(MAX_PATH, wxStringBuffer(dir, MAX_PATH + 1)) )
607 {
608 wxLogLastError(_T("GetTempPath"));
609 }
610
611 if ( dir.empty() )
612 {
613 // GetTempFileName() fails if we pass it an empty string
614 dir = _T('.');
615 }
616 }
617 else // we have a dir to create the file in
618 {
619 // ensure we use only the back slashes as GetTempFileName(), unlike all
620 // the other APIs, is picky and doesn't accept the forward ones
621 dir.Replace(_T("/"), _T("\\"));
622 }
623
624 if ( !::GetTempFileName(dir, name, 0, wxStringBuffer(path, MAX_PATH + 1)) )
625 {
626 wxLogLastError(_T("GetTempFileName"));
627
628 path.clear();
629 }
630
631 #else // !Windows
632 if ( dir.empty() )
633 {
634 #if defined(__WXMAC__) && !defined(__DARWIN__)
635 dir = wxMacFindFolder( (short) kOnSystemDisk, kTemporaryFolderType, kCreateFolder ) ;
636 #else // !Mac
637 dir = wxGetenv(_T("TMP"));
638 if ( dir.empty() )
639 {
640 dir = wxGetenv(_T("TEMP"));
641 }
642
643 if ( dir.empty() )
644 {
645 // default
646 #if defined(__DOS__) || defined(__OS2__)
647 dir = _T(".");
648 #else
649 dir = _T("/tmp");
650 #endif
651 }
652 #endif // Mac/!Mac
653 }
654
655 path = dir;
656
657 if ( !wxEndsWithPathSeparator(dir) &&
658 (name.empty() || !wxIsPathSeparator(name[0u])) )
659 {
660 path += wxFILE_SEP_PATH;
661 }
662
663 path += name;
664
665 #if defined(HAVE_MKSTEMP)
666 // scratch space for mkstemp()
667 path += _T("XXXXXX");
668
669 // we need to copy the path to the buffer in which mkstemp() can modify it
670 wxCharBuffer buf( wxConvFile.cWX2MB( path ) );
671
672 // cast is safe because the string length doesn't change
673 int fdTemp = mkstemp( (char*)(const char*) buf );
674 if ( fdTemp == -1 )
675 {
676 // this might be not necessary as mkstemp() on most systems should have
677 // already done it but it doesn't hurt neither...
678 path.clear();
679 }
680 else // mkstemp() succeeded
681 {
682 path = wxConvFile.cMB2WX( (const char*) buf );
683
684 // avoid leaking the fd
685 if ( fileTemp )
686 {
687 fileTemp->Attach(fdTemp);
688 }
689 else
690 {
691 close(fdTemp);
692 }
693 }
694 #else // !HAVE_MKSTEMP
695
696 #ifdef HAVE_MKTEMP
697 // same as above
698 path += _T("XXXXXX");
699
700 wxCharBuffer buf = wxConvFile.cWX2MB( path );
701 if ( !mktemp( (const char*) buf ) )
702 {
703 path.clear();
704 }
705 else
706 {
707 path = wxConvFile.cMB2WX( (const char*) buf );
708 }
709 #else // !HAVE_MKTEMP (includes __DOS__)
710 // generate the unique file name ourselves
711 #if !defined(__DOS__) && (!defined(__MWERKS__) || defined(__DARWIN__) )
712 path << (unsigned int)getpid();
713 #endif
714
715 wxString pathTry;
716
717 static const size_t numTries = 1000;
718 for ( size_t n = 0; n < numTries; n++ )
719 {
720 // 3 hex digits is enough for numTries == 1000 < 4096
721 pathTry = path + wxString::Format(_T("%.03x"), (unsigned int) n);
722 if ( !wxFile::Exists(pathTry) )
723 {
724 break;
725 }
726
727 pathTry.clear();
728 }
729
730 path = pathTry;
731 #endif // HAVE_MKTEMP/!HAVE_MKTEMP
732
733 if ( !path.empty() )
734 {
735 }
736 #endif // HAVE_MKSTEMP/!HAVE_MKSTEMP
737
738 #endif // Windows/!Windows
739
740 if ( path.empty() )
741 {
742 wxLogSysError(_("Failed to create a temporary file name"));
743 }
744 else if ( fileTemp && !fileTemp->IsOpened() )
745 {
746 // open the file - of course, there is a race condition here, this is
747 // why we always prefer using mkstemp()...
748 //
749 // NB: GetTempFileName() under Windows creates the file, so using
750 // write_excl there would fail
751 if ( !fileTemp->Open(path,
752 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
753 wxFile::write,
754 #else
755 wxFile::write_excl,
756 #endif
757 wxS_IRUSR | wxS_IWUSR) )
758 {
759 // FIXME: If !ok here should we loop and try again with another
760 // file name? That is the standard recourse if open(O_EXCL)
761 // fails, though of course it should be protected against
762 // possible infinite looping too.
763
764 wxLogError(_("Failed to open temporary file."));
765
766 path.clear();
767 }
768 }
769
770 return path;
771 }
772
773 // ----------------------------------------------------------------------------
774 // directory operations
775 // ----------------------------------------------------------------------------
776
777 bool wxFileName::Mkdir( int perm, int flags )
778 {
779 return wxFileName::Mkdir( GetFullPath(), perm, flags );
780 }
781
782 bool wxFileName::Mkdir( const wxString& dir, int perm, int flags )
783 {
784 if ( flags & wxPATH_MKDIR_FULL )
785 {
786 // split the path in components
787 wxFileName filename;
788 filename.AssignDir(dir);
789
790 wxString currPath;
791 if ( filename.HasVolume())
792 {
793 currPath << wxGetVolumeString(filename.GetVolume(), wxPATH_NATIVE);
794 }
795
796 wxArrayString dirs = filename.GetDirs();
797 size_t count = dirs.GetCount();
798 for ( size_t i = 0; i < count; i++ )
799 {
800 if ( i > 0 ||
801 #if defined(__WXMAC__) && !defined(__DARWIN__)
802 // relative pathnames are exactely the other way round under mac...
803 !filename.IsAbsolute()
804 #else
805 filename.IsAbsolute()
806 #endif
807 )
808 currPath += wxFILE_SEP_PATH;
809 currPath += dirs[i];
810
811 if (!DirExists(currPath))
812 {
813 if (!wxMkdir(currPath, perm))
814 {
815 // no need to try creating further directories
816 return false;
817 }
818 }
819 }
820
821 return true;
822
823 }
824
825 return ::wxMkdir( dir, perm );
826 }
827
828 bool wxFileName::Rmdir()
829 {
830 return wxFileName::Rmdir( GetFullPath() );
831 }
832
833 bool wxFileName::Rmdir( const wxString &dir )
834 {
835 return ::wxRmdir( dir );
836 }
837
838 // ----------------------------------------------------------------------------
839 // path normalization
840 // ----------------------------------------------------------------------------
841
842 bool wxFileName::Normalize(int flags,
843 const wxString& cwd,
844 wxPathFormat format)
845 {
846 // deal with env vars renaming first as this may seriously change the path
847 if ( flags & wxPATH_NORM_ENV_VARS )
848 {
849 wxString pathOrig = GetFullPath(format);
850 wxString path = wxExpandEnvVars(pathOrig);
851 if ( path != pathOrig )
852 {
853 Assign(path);
854 }
855 }
856
857
858 // the existing path components
859 wxArrayString dirs = GetDirs();
860
861 // the path to prepend in front to make the path absolute
862 wxFileName curDir;
863
864 format = GetFormat(format);
865
866 // make the path absolute
867 if ( (flags & wxPATH_NORM_ABSOLUTE) && !IsAbsolute(format) )
868 {
869 if ( cwd.empty() )
870 {
871 curDir.AssignCwd(GetVolume());
872 }
873 else // cwd provided
874 {
875 curDir.AssignDir(cwd);
876 }
877
878 // the path may be not absolute because it doesn't have the volume name
879 // but in this case we shouldn't modify the directory components of it
880 // but just set the current volume
881 if ( !HasVolume() && curDir.HasVolume() )
882 {
883 SetVolume(curDir.GetVolume());
884
885 if ( !m_relative )
886 {
887 // yes, it was the case - we don't need curDir then
888 curDir.Clear();
889 }
890 }
891 }
892
893 // handle ~ stuff under Unix only
894 if ( (format == wxPATH_UNIX) && (flags & wxPATH_NORM_TILDE) )
895 {
896 if ( !dirs.IsEmpty() )
897 {
898 wxString dir = dirs[0u];
899 if ( !dir.empty() && dir[0u] == _T('~') )
900 {
901 curDir.AssignDir(wxGetUserHome(dir.c_str() + 1));
902
903 dirs.RemoveAt(0u);
904 }
905 }
906 }
907
908 // transform relative path into abs one
909 if ( curDir.IsOk() )
910 {
911 wxArrayString dirsNew = curDir.GetDirs();
912 size_t count = dirs.GetCount();
913 for ( size_t n = 0; n < count; n++ )
914 {
915 dirsNew.Add(dirs[n]);
916 }
917
918 dirs = dirsNew;
919 }
920
921 // now deal with ".", ".." and the rest
922 m_dirs.Empty();
923 size_t count = dirs.GetCount();
924 for ( size_t n = 0; n < count; n++ )
925 {
926 wxString dir = dirs[n];
927
928 if ( flags & wxPATH_NORM_DOTS )
929 {
930 if ( dir == wxT(".") )
931 {
932 // just ignore
933 continue;
934 }
935
936 if ( dir == wxT("..") )
937 {
938 if ( m_dirs.IsEmpty() )
939 {
940 wxLogError(_("The path '%s' contains too many \"..\"!"),
941 GetFullPath().c_str());
942 return false;
943 }
944
945 m_dirs.RemoveAt(m_dirs.GetCount() - 1);
946 continue;
947 }
948 }
949
950 if ( (flags & wxPATH_NORM_CASE) && !IsCaseSensitive(format) )
951 {
952 dir.MakeLower();
953 }
954
955 m_dirs.Add(dir);
956 }
957
958 #if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
959 if ( (flags & wxPATH_NORM_SHORTCUT) )
960 {
961 wxString filename;
962 if (GetShortcutTarget(GetFullPath(format), filename))
963 {
964 // Repeat this since we may now have a new path
965 if ( (flags & wxPATH_NORM_CASE) && !IsCaseSensitive(format) )
966 {
967 filename.MakeLower();
968 }
969 m_relative = false;
970 Assign(filename);
971 }
972 }
973 #endif
974
975 if ( (flags & wxPATH_NORM_CASE) && !IsCaseSensitive(format) )
976 {
977 // VZ: expand env vars here too?
978
979 m_volume.MakeLower();
980 m_name.MakeLower();
981 m_ext.MakeLower();
982 }
983
984 // we do have the path now
985 //
986 // NB: need to do this before (maybe) calling Assign() below
987 m_relative = false;
988
989 #if defined(__WIN32__)
990 if ( (flags & wxPATH_NORM_LONG) && (format == wxPATH_DOS) )
991 {
992 Assign(GetLongPath());
993 }
994 #endif // Win32
995
996 return true;
997 }
998
999 // ----------------------------------------------------------------------------
1000 // get the shortcut target
1001 // ----------------------------------------------------------------------------
1002
1003 // WinCE (3) doesn't have CLSID_ShellLink, IID_IShellLink definitions.
1004 // The .lnk file is a plain text file so it should be easy to
1005 // make it work. Hint from Google Groups:
1006 // "If you open up a lnk file, you'll see a
1007 // number, followed by a pound sign (#), followed by more text. The
1008 // number is the number of characters that follows the pound sign. The
1009 // characters after the pound sign are the command line (which _can_
1010 // include arguments) to be executed. Any path (e.g. \windows\program
1011 // files\myapp.exe) that includes spaces needs to be enclosed in
1012 // quotation marks."
1013
1014 #if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
1015 // The following lines are necessary under WinCE
1016 // #include "wx/msw/private.h"
1017 // #include <ole2.h>
1018 #include <shlobj.h>
1019 #if defined(__WXWINCE__)
1020 #include <shlguid.h>
1021 #endif
1022
1023 bool wxFileName::GetShortcutTarget(const wxString& shortcutPath, wxString& targetFilename, wxString* arguments)
1024 {
1025 wxString path, file, ext;
1026 wxSplitPath(shortcutPath, & path, & file, & ext);
1027
1028 HRESULT hres;
1029 IShellLink* psl;
1030 bool success = false;
1031
1032 // Assume it's not a shortcut if it doesn't end with lnk
1033 if (ext.Lower() != wxT("lnk"))
1034 return false;
1035
1036 // create a ShellLink object
1037 hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
1038 IID_IShellLink, (LPVOID*) &psl);
1039
1040 if (SUCCEEDED(hres))
1041 {
1042 IPersistFile* ppf;
1043 hres = psl->QueryInterface( IID_IPersistFile, (LPVOID *) &ppf);
1044 if (SUCCEEDED(hres))
1045 {
1046 WCHAR wsz[MAX_PATH];
1047
1048 MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, shortcutPath.mb_str(), -1, wsz,
1049 MAX_PATH);
1050
1051 hres = ppf->Load(wsz, 0);
1052 if (SUCCEEDED(hres))
1053 {
1054 wxChar buf[2048];
1055 // Wrong prototype in early versions
1056 #if defined(__MINGW32__) && !wxCHECK_W32API_VERSION(2, 2)
1057 psl->GetPath((CHAR*) buf, 2048, NULL, SLGP_UNCPRIORITY);
1058 #else
1059 psl->GetPath(buf, 2048, NULL, SLGP_UNCPRIORITY);
1060 #endif
1061 targetFilename = wxString(buf);
1062 success = (shortcutPath != targetFilename);
1063
1064 psl->GetArguments(buf, 2048);
1065 wxString args(buf);
1066 if (!args.IsEmpty() && arguments)
1067 {
1068 *arguments = args;
1069 }
1070 }
1071 }
1072 }
1073 psl->Release();
1074 return success;
1075 }
1076 #endif
1077
1078
1079 // ----------------------------------------------------------------------------
1080 // absolute/relative paths
1081 // ----------------------------------------------------------------------------
1082
1083 bool wxFileName::IsAbsolute(wxPathFormat format) const
1084 {
1085 // if our path doesn't start with a path separator, it's not an absolute
1086 // path
1087 if ( m_relative )
1088 return false;
1089
1090 if ( !GetVolumeSeparator(format).empty() )
1091 {
1092 // this format has volumes and an absolute path must have one, it's not
1093 // enough to have the full path to bean absolute file under Windows
1094 if ( GetVolume().empty() )
1095 return false;
1096 }
1097
1098 return true;
1099 }
1100
1101 bool wxFileName::MakeRelativeTo(const wxString& pathBase, wxPathFormat format)
1102 {
1103 wxFileName fnBase = wxFileName::DirName(pathBase, format);
1104
1105 // get cwd only once - small time saving
1106 wxString cwd = wxGetCwd();
1107 Normalize(wxPATH_NORM_ALL & ~wxPATH_NORM_CASE, cwd, format);
1108 fnBase.Normalize(wxPATH_NORM_ALL & ~wxPATH_NORM_CASE, cwd, format);
1109
1110 bool withCase = IsCaseSensitive(format);
1111
1112 // we can't do anything if the files live on different volumes
1113 if ( !GetVolume().IsSameAs(fnBase.GetVolume(), withCase) )
1114 {
1115 // nothing done
1116 return false;
1117 }
1118
1119 // same drive, so we don't need our volume
1120 m_volume.clear();
1121
1122 // remove common directories starting at the top
1123 while ( !m_dirs.IsEmpty() && !fnBase.m_dirs.IsEmpty() &&
1124 m_dirs[0u].IsSameAs(fnBase.m_dirs[0u], withCase) )
1125 {
1126 m_dirs.RemoveAt(0);
1127 fnBase.m_dirs.RemoveAt(0);
1128 }
1129
1130 // add as many ".." as needed
1131 size_t count = fnBase.m_dirs.GetCount();
1132 for ( size_t i = 0; i < count; i++ )
1133 {
1134 m_dirs.Insert(wxT(".."), 0u);
1135 }
1136
1137 if ( format == wxPATH_UNIX || format == wxPATH_DOS )
1138 {
1139 // a directory made relative with respect to itself is '.' under Unix
1140 // and DOS, by definition (but we don't have to insert "./" for the
1141 // files)
1142 if ( m_dirs.IsEmpty() && IsDir() )
1143 {
1144 m_dirs.Add(_T('.'));
1145 }
1146 }
1147
1148 m_relative = true;
1149
1150 // we were modified
1151 return true;
1152 }
1153
1154 // ----------------------------------------------------------------------------
1155 // filename kind tests
1156 // ----------------------------------------------------------------------------
1157
1158 bool wxFileName::SameAs(const wxFileName& filepath, wxPathFormat format) const
1159 {
1160 wxFileName fn1 = *this,
1161 fn2 = filepath;
1162
1163 // get cwd only once - small time saving
1164 wxString cwd = wxGetCwd();
1165 fn1.Normalize(wxPATH_NORM_ALL | wxPATH_NORM_CASE, cwd, format);
1166 fn2.Normalize(wxPATH_NORM_ALL | wxPATH_NORM_CASE, cwd, format);
1167
1168 if ( fn1.GetFullPath() == fn2.GetFullPath() )
1169 return true;
1170
1171 // TODO: compare inodes for Unix, this works even when filenames are
1172 // different but files are the same (symlinks) (VZ)
1173
1174 return false;
1175 }
1176
1177 /* static */
1178 bool wxFileName::IsCaseSensitive( wxPathFormat format )
1179 {
1180 // only Unix filenames are truely case-sensitive
1181 return GetFormat(format) == wxPATH_UNIX;
1182 }
1183
1184 // If asserts, wxPathFormat has been changed.
1185 wxCOMPILE_TIME_ASSERT(wxPATH_MAX == 5, wxPathFormatChanged);
1186
1187 /* static */
1188 wxString wxFileName::GetForbiddenChars(wxPathFormat format)
1189 {
1190 // Inits to forbidden characters that are common to (almost) all platforms.
1191 wxString strForbiddenChars = wxT("*?");
1192
1193 // If asserts, wxPathFormat has been changed. In case of a new path format
1194 // addition, the following code might have to be updated.
1195 wxCOMPILE_TIME_ASSERT(wxPATH_MAX == 5, wxPathFormatChanged);
1196 switch ( GetFormat(format) )
1197 {
1198 default :
1199 wxFAIL_MSG( wxT("Unknown path format") );
1200 // !! Fall through !!
1201
1202 case wxPATH_UNIX:
1203 break;
1204
1205 case wxPATH_MAC:
1206 // On a Mac even names with * and ? are allowed (Tested with OS
1207 // 9.2.1 and OS X 10.2.5)
1208 strForbiddenChars = wxEmptyString;
1209 break;
1210
1211 case wxPATH_DOS:
1212 strForbiddenChars += wxT("\\/:\"<>|");
1213 break;
1214
1215 case wxPATH_VMS:
1216 break;
1217 }
1218
1219 return strForbiddenChars;
1220 }
1221
1222 /* static */
1223 wxString wxFileName::GetVolumeSeparator(wxPathFormat format)
1224 {
1225 wxString sepVol;
1226
1227 if ( (GetFormat(format) == wxPATH_DOS) ||
1228 (GetFormat(format) == wxPATH_VMS) )
1229 {
1230 sepVol = wxFILE_SEP_DSK;
1231 }
1232 //else: leave empty
1233
1234 return sepVol;
1235 }
1236
1237 /* static */
1238 wxString wxFileName::GetPathSeparators(wxPathFormat format)
1239 {
1240 wxString seps;
1241 switch ( GetFormat(format) )
1242 {
1243 case wxPATH_DOS:
1244 // accept both as native APIs do but put the native one first as
1245 // this is the one we use in GetFullPath()
1246 seps << wxFILE_SEP_PATH_DOS << wxFILE_SEP_PATH_UNIX;
1247 break;
1248
1249 default:
1250 wxFAIL_MSG( _T("Unknown wxPATH_XXX style") );
1251 // fall through
1252
1253 case wxPATH_UNIX:
1254 seps = wxFILE_SEP_PATH_UNIX;
1255 break;
1256
1257 case wxPATH_MAC:
1258 seps = wxFILE_SEP_PATH_MAC;
1259 break;
1260
1261 case wxPATH_VMS:
1262 seps = wxFILE_SEP_PATH_VMS;
1263 break;
1264 }
1265
1266 return seps;
1267 }
1268
1269 /* static */
1270 wxString wxFileName::GetPathTerminators(wxPathFormat format)
1271 {
1272 format = GetFormat(format);
1273
1274 // under VMS the end of the path is ']', not the path separator used to
1275 // separate the components
1276 return format == wxPATH_VMS ? wxString(_T(']')) : GetPathSeparators(format);
1277 }
1278
1279 /* static */
1280 bool wxFileName::IsPathSeparator(wxChar ch, wxPathFormat format)
1281 {
1282 // wxString::Find() doesn't work as expected with NUL - it will always find
1283 // it, so it is almost surely a bug if this function is called with NUL arg
1284 wxASSERT_MSG( ch != _T('\0'), _T("shouldn't be called with NUL") );
1285
1286 return GetPathSeparators(format).Find(ch) != wxNOT_FOUND;
1287 }
1288
1289 // ----------------------------------------------------------------------------
1290 // path components manipulation
1291 // ----------------------------------------------------------------------------
1292
1293 /* static */ bool wxFileName::IsValidDirComponent(const wxString& dir)
1294 {
1295 if ( dir.empty() )
1296 {
1297 wxFAIL_MSG( _T("empty directory passed to wxFileName::InsertDir()") );
1298
1299 return false;
1300 }
1301
1302 const size_t len = dir.length();
1303 for ( size_t n = 0; n < len; n++ )
1304 {
1305 if ( dir[n] == GetVolumeSeparator() || IsPathSeparator(dir[n]) )
1306 {
1307 wxFAIL_MSG( _T("invalid directory component in wxFileName") );
1308
1309 return false;
1310 }
1311 }
1312
1313 return true;
1314 }
1315
1316 void wxFileName::AppendDir( const wxString &dir )
1317 {
1318 if ( IsValidDirComponent(dir) )
1319 m_dirs.Add( dir );
1320 }
1321
1322 void wxFileName::PrependDir( const wxString &dir )
1323 {
1324 InsertDir(0, dir);
1325 }
1326
1327 void wxFileName::InsertDir( int before, const wxString &dir )
1328 {
1329 if ( IsValidDirComponent(dir) )
1330 m_dirs.Insert( dir, before );
1331 }
1332
1333 void wxFileName::RemoveDir( int pos )
1334 {
1335 m_dirs.RemoveAt( (size_t)pos );
1336 }
1337
1338 // ----------------------------------------------------------------------------
1339 // accessors
1340 // ----------------------------------------------------------------------------
1341
1342 void wxFileName::SetFullName(const wxString& fullname)
1343 {
1344 SplitPath(fullname, NULL /* no path */, &m_name, &m_ext);
1345 }
1346
1347 wxString wxFileName::GetFullName() const
1348 {
1349 wxString fullname = m_name;
1350 if ( !m_ext.empty() )
1351 {
1352 fullname << wxFILE_SEP_EXT << m_ext;
1353 }
1354
1355 return fullname;
1356 }
1357
1358 wxString wxFileName::GetPath( int flags, wxPathFormat format ) const
1359 {
1360 format = GetFormat( format );
1361
1362 wxString fullpath;
1363
1364 // return the volume with the path as well if requested
1365 if ( flags & wxPATH_GET_VOLUME )
1366 {
1367 fullpath += wxGetVolumeString(GetVolume(), format);
1368 }
1369
1370 // the leading character
1371 switch ( format )
1372 {
1373 case wxPATH_MAC:
1374 if ( m_relative )
1375 fullpath += wxFILE_SEP_PATH_MAC;
1376 break;
1377
1378 case wxPATH_DOS:
1379 if ( !m_relative )
1380 fullpath += wxFILE_SEP_PATH_DOS;
1381 break;
1382
1383 default:
1384 wxFAIL_MSG( wxT("Unknown path format") );
1385 // fall through
1386
1387 case wxPATH_UNIX:
1388 if ( !m_relative )
1389 {
1390 // normally the absolute file names start with a slash
1391 // with one exception: the ones like "~/foo.bar" don't
1392 // have it
1393 if ( m_dirs.IsEmpty() || m_dirs[0u] != _T('~') )
1394 {
1395 fullpath += wxFILE_SEP_PATH_UNIX;
1396 }
1397 }
1398 break;
1399
1400 case wxPATH_VMS:
1401 // no leading character here but use this place to unset
1402 // wxPATH_GET_SEPARATOR flag: under VMS it doesn't make sense
1403 // as, if I understand correctly, there should never be a dot
1404 // before the closing bracket
1405 flags &= ~wxPATH_GET_SEPARATOR;
1406 }
1407
1408 if ( m_dirs.empty() )
1409 {
1410 // there is nothing more
1411 return fullpath;
1412 }
1413
1414 // then concatenate all the path components using the path separator
1415 if ( format == wxPATH_VMS )
1416 {
1417 fullpath += wxT('[');
1418 }
1419
1420 const size_t dirCount = m_dirs.GetCount();
1421 for ( size_t i = 0; i < dirCount; i++ )
1422 {
1423 switch (format)
1424 {
1425 case wxPATH_MAC:
1426 if ( m_dirs[i] == wxT(".") )
1427 {
1428 // skip appending ':', this shouldn't be done in this
1429 // case as "::" is interpreted as ".." under Unix
1430 continue;
1431 }
1432
1433 // convert back from ".." to nothing
1434 if ( m_dirs[i] != wxT("..") )
1435 fullpath += m_dirs[i];
1436 break;
1437
1438 default:
1439 wxFAIL_MSG( wxT("Unexpected path format") );
1440 // still fall through
1441
1442 case wxPATH_DOS:
1443 case wxPATH_UNIX:
1444 fullpath += m_dirs[i];
1445 break;
1446
1447 case wxPATH_VMS:
1448 // TODO: What to do with ".." under VMS
1449
1450 // convert back from ".." to nothing
1451 if ( m_dirs[i] != wxT("..") )
1452 fullpath += m_dirs[i];
1453 break;
1454 }
1455
1456 if ( (flags & wxPATH_GET_SEPARATOR) || (i != dirCount - 1) )
1457 fullpath += GetPathSeparator(format);
1458 }
1459
1460 if ( format == wxPATH_VMS )
1461 {
1462 fullpath += wxT(']');
1463 }
1464
1465 return fullpath;
1466 }
1467
1468 wxString wxFileName::GetFullPath( wxPathFormat format ) const
1469 {
1470 // we already have a function to get the path
1471 wxString fullpath = GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR,
1472 format);
1473
1474 // now just add the file name and extension to it
1475 fullpath += GetFullName();
1476
1477 return fullpath;
1478 }
1479
1480 // Return the short form of the path (returns identity on non-Windows platforms)
1481 wxString wxFileName::GetShortPath() const
1482 {
1483 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
1484 wxString path(GetFullPath());
1485 wxString pathOut;
1486 DWORD sz = ::GetShortPathName(path, NULL, 0);
1487 bool ok = sz != 0;
1488 if ( ok )
1489 {
1490 ok = ::GetShortPathName
1491 (
1492 path,
1493 wxStringBuffer(pathOut, sz),
1494 sz
1495 ) != 0;
1496 }
1497 if (ok)
1498 return pathOut;
1499
1500 return path;
1501 #else
1502 return GetFullPath();
1503 #endif
1504 }
1505
1506 // Return the long form of the path (returns identity on non-Windows platforms)
1507 wxString wxFileName::GetLongPath() const
1508 {
1509 wxString pathOut,
1510 path = GetFullPath();
1511
1512 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1513 bool success = false;
1514
1515 #if wxUSE_DYNAMIC_LOADER
1516 typedef DWORD (WINAPI *GET_LONG_PATH_NAME)(const wxChar *, wxChar *, DWORD);
1517
1518 static bool s_triedToLoad = false;
1519
1520 if ( !s_triedToLoad )
1521 {
1522 // suppress the errors about missing GetLongPathName[AW]
1523 wxLogNull noLog;
1524
1525 s_triedToLoad = true;
1526 wxDynamicLibrary dllKernel(_T("kernel32"));
1527 if ( dllKernel.IsLoaded() )
1528 {
1529 // may succeed or fail depending on the Windows version
1530 static GET_LONG_PATH_NAME s_pfnGetLongPathName = NULL;
1531 #ifdef _UNICODE
1532 s_pfnGetLongPathName = (GET_LONG_PATH_NAME) dllKernel.GetSymbol(_T("GetLongPathNameW"));
1533 #else
1534 s_pfnGetLongPathName = (GET_LONG_PATH_NAME) dllKernel.GetSymbol(_T("GetLongPathNameA"));
1535 #endif
1536
1537 if ( s_pfnGetLongPathName )
1538 {
1539 DWORD dwSize = (*s_pfnGetLongPathName)(path, NULL, 0);
1540 bool ok = dwSize > 0;
1541
1542 if ( ok )
1543 {
1544 DWORD sz = (*s_pfnGetLongPathName)(path, NULL, 0);
1545 ok = sz != 0;
1546 if ( ok )
1547 {
1548 ok = (*s_pfnGetLongPathName)
1549 (
1550 path,
1551 wxStringBuffer(pathOut, sz),
1552 sz
1553 ) != 0;
1554 success = true;
1555 }
1556 }
1557 }
1558 }
1559 }
1560
1561 if (success)
1562 return pathOut;
1563 #endif // wxUSE_DYNAMIC_LOADER
1564
1565 if (!success)
1566 {
1567 // The OS didn't support GetLongPathName, or some other error.
1568 // We need to call FindFirstFile on each component in turn.
1569
1570 WIN32_FIND_DATA findFileData;
1571 HANDLE hFind;
1572
1573 if ( HasVolume() )
1574 pathOut = GetVolume() +
1575 GetVolumeSeparator(wxPATH_DOS) +
1576 GetPathSeparator(wxPATH_DOS);
1577 else
1578 pathOut = wxEmptyString;
1579
1580 wxArrayString dirs = GetDirs();
1581 dirs.Add(GetFullName());
1582
1583 wxString tmpPath;
1584
1585 size_t count = dirs.GetCount();
1586 for ( size_t i = 0; i < count; i++ )
1587 {
1588 // We're using pathOut to collect the long-name path, but using a
1589 // temporary for appending the last path component which may be
1590 // short-name
1591 tmpPath = pathOut + dirs[i];
1592
1593 if ( tmpPath.empty() )
1594 continue;
1595
1596 // can't see this being necessary? MF
1597 if ( tmpPath.Last() == GetVolumeSeparator(wxPATH_DOS) )
1598 {
1599 // Can't pass a drive and root dir to FindFirstFile,
1600 // so continue to next dir
1601 tmpPath += wxFILE_SEP_PATH;
1602 pathOut = tmpPath;
1603 continue;
1604 }
1605
1606 hFind = ::FindFirstFile(tmpPath, &findFileData);
1607 if (hFind == INVALID_HANDLE_VALUE)
1608 {
1609 // Error: most likely reason is that path doesn't exist, so
1610 // append any unprocessed parts and return
1611 for ( i += 1; i < count; i++ )
1612 tmpPath += wxFILE_SEP_PATH + dirs[i];
1613
1614 return tmpPath;
1615 }
1616
1617 pathOut += findFileData.cFileName;
1618 if ( (i < (count-1)) )
1619 pathOut += wxFILE_SEP_PATH;
1620
1621 ::FindClose(hFind);
1622 }
1623 }
1624 #else // !Win32
1625 pathOut = path;
1626 #endif // Win32/!Win32
1627
1628 return pathOut;
1629 }
1630
1631 wxPathFormat wxFileName::GetFormat( wxPathFormat format )
1632 {
1633 if (format == wxPATH_NATIVE)
1634 {
1635 #if defined(__WXMSW__) || defined(__OS2__) || defined(__DOS__)
1636 format = wxPATH_DOS;
1637 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1638 format = wxPATH_MAC;
1639 #elif defined(__VMS)
1640 format = wxPATH_VMS;
1641 #else
1642 format = wxPATH_UNIX;
1643 #endif
1644 }
1645 return format;
1646 }
1647
1648 // ----------------------------------------------------------------------------
1649 // path splitting function
1650 // ----------------------------------------------------------------------------
1651
1652 /* static */
1653 void
1654 wxFileName::SplitVolume(const wxString& fullpathWithVolume,
1655 wxString *pstrVolume,
1656 wxString *pstrPath,
1657 wxPathFormat format)
1658 {
1659 format = GetFormat(format);
1660
1661 wxString fullpath = fullpathWithVolume;
1662
1663 // special Windows UNC paths hack: transform \\share\path into share:path
1664 if ( format == wxPATH_DOS )
1665 {
1666 if ( fullpath.length() >= 4 &&
1667 fullpath[0u] == wxFILE_SEP_PATH_DOS &&
1668 fullpath[1u] == wxFILE_SEP_PATH_DOS )
1669 {
1670 fullpath.erase(0, 2);
1671
1672 size_t posFirstSlash =
1673 fullpath.find_first_of(GetPathTerminators(format));
1674 if ( posFirstSlash != wxString::npos )
1675 {
1676 fullpath[posFirstSlash] = wxFILE_SEP_DSK;
1677
1678 // UNC paths are always absolute, right? (FIXME)
1679 fullpath.insert(posFirstSlash + 1, 1, wxFILE_SEP_PATH_DOS);
1680 }
1681 }
1682 }
1683
1684 // We separate the volume here
1685 if ( format == wxPATH_DOS || format == wxPATH_VMS )
1686 {
1687 wxString sepVol = GetVolumeSeparator(format);
1688
1689 size_t posFirstColon = fullpath.find_first_of(sepVol);
1690 if ( posFirstColon != wxString::npos )
1691 {
1692 if ( pstrVolume )
1693 {
1694 *pstrVolume = fullpath.Left(posFirstColon);
1695 }
1696
1697 // remove the volume name and the separator from the full path
1698 fullpath.erase(0, posFirstColon + sepVol.length());
1699 }
1700 }
1701
1702 if ( pstrPath )
1703 *pstrPath = fullpath;
1704 }
1705
1706 /* static */
1707 void wxFileName::SplitPath(const wxString& fullpathWithVolume,
1708 wxString *pstrVolume,
1709 wxString *pstrPath,
1710 wxString *pstrName,
1711 wxString *pstrExt,
1712 wxPathFormat format)
1713 {
1714 format = GetFormat(format);
1715
1716 wxString fullpath;
1717 SplitVolume(fullpathWithVolume, pstrVolume, &fullpath, format);
1718
1719 // find the positions of the last dot and last path separator in the path
1720 size_t posLastDot = fullpath.find_last_of(wxFILE_SEP_EXT);
1721 size_t posLastSlash = fullpath.find_last_of(GetPathTerminators(format));
1722
1723 // check whether this dot occurs at the very beginning of a path component
1724 if ( (posLastDot != wxString::npos) &&
1725 (posLastDot == 0 ||
1726 IsPathSeparator(fullpath[posLastDot - 1]) ||
1727 (format == wxPATH_VMS && fullpath[posLastDot - 1] == _T(']'))) )
1728 {
1729 // dot may be (and commonly -- at least under Unix -- is) the first
1730 // character of the filename, don't treat the entire filename as
1731 // extension in this case
1732 posLastDot = wxString::npos;
1733 }
1734
1735 // if we do have a dot and a slash, check that the dot is in the name part
1736 if ( (posLastDot != wxString::npos) &&
1737 (posLastSlash != wxString::npos) &&
1738 (posLastDot < posLastSlash) )
1739 {
1740 // the dot is part of the path, not the start of the extension
1741 posLastDot = wxString::npos;
1742 }
1743
1744 // now fill in the variables provided by user
1745 if ( pstrPath )
1746 {
1747 if ( posLastSlash == wxString::npos )
1748 {
1749 // no path at all
1750 pstrPath->Empty();
1751 }
1752 else
1753 {
1754 // take everything up to the path separator but take care to make
1755 // the path equal to something like '/', not empty, for the files
1756 // immediately under root directory
1757 size_t len = posLastSlash;
1758
1759 // this rule does not apply to mac since we do not start with colons (sep)
1760 // except for relative paths
1761 if ( !len && format != wxPATH_MAC)
1762 len++;
1763
1764 *pstrPath = fullpath.Left(len);
1765
1766 // special VMS hack: remove the initial bracket
1767 if ( format == wxPATH_VMS )
1768 {
1769 if ( (*pstrPath)[0u] == _T('[') )
1770 pstrPath->erase(0, 1);
1771 }
1772 }
1773 }
1774
1775 if ( pstrName )
1776 {
1777 // take all characters starting from the one after the last slash and
1778 // up to, but excluding, the last dot
1779 size_t nStart = posLastSlash == wxString::npos ? 0 : posLastSlash + 1;
1780 size_t count;
1781 if ( posLastDot == wxString::npos )
1782 {
1783 // take all until the end
1784 count = wxString::npos;
1785 }
1786 else if ( posLastSlash == wxString::npos )
1787 {
1788 count = posLastDot;
1789 }
1790 else // have both dot and slash
1791 {
1792 count = posLastDot - posLastSlash - 1;
1793 }
1794
1795 *pstrName = fullpath.Mid(nStart, count);
1796 }
1797
1798 if ( pstrExt )
1799 {
1800 if ( posLastDot == wxString::npos )
1801 {
1802 // no extension
1803 pstrExt->Empty();
1804 }
1805 else
1806 {
1807 // take everything after the dot
1808 *pstrExt = fullpath.Mid(posLastDot + 1);
1809 }
1810 }
1811 }
1812
1813 /* static */
1814 void wxFileName::SplitPath(const wxString& fullpath,
1815 wxString *path,
1816 wxString *name,
1817 wxString *ext,
1818 wxPathFormat format)
1819 {
1820 wxString volume;
1821 SplitPath(fullpath, &volume, path, name, ext, format);
1822
1823 if ( path )
1824 {
1825 path->Prepend(wxGetVolumeString(volume, format));
1826 }
1827 }
1828
1829 // ----------------------------------------------------------------------------
1830 // time functions
1831 // ----------------------------------------------------------------------------
1832
1833 #if wxUSE_DATETIME
1834
1835 bool wxFileName::SetTimes(const wxDateTime *dtAccess,
1836 const wxDateTime *dtMod,
1837 const wxDateTime *dtCreate)
1838 {
1839 #if defined(__WIN32__)
1840 if ( IsDir() )
1841 {
1842 // VZ: please let me know how to do this if you can
1843 wxFAIL_MSG( _T("SetTimes() not implemented for the directories") );
1844 }
1845 else // file
1846 {
1847 wxFileHandle fh(GetFullPath(), wxFileHandle::Write);
1848 if ( fh.IsOk() )
1849 {
1850 FILETIME ftAccess, ftCreate, ftWrite;
1851
1852 if ( dtCreate )
1853 ConvertWxToFileTime(&ftCreate, *dtCreate);
1854 if ( dtAccess )
1855 ConvertWxToFileTime(&ftAccess, *dtAccess);
1856 if ( dtMod )
1857 ConvertWxToFileTime(&ftWrite, *dtMod);
1858
1859 if ( ::SetFileTime(fh,
1860 dtCreate ? &ftCreate : NULL,
1861 dtAccess ? &ftAccess : NULL,
1862 dtMod ? &ftWrite : NULL) )
1863 {
1864 return true;
1865 }
1866 }
1867 }
1868 #elif defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
1869 if ( !dtAccess && !dtMod )
1870 {
1871 // can't modify the creation time anyhow, don't try
1872 return true;
1873 }
1874
1875 // if dtAccess or dtMod is not specified, use the other one (which must be
1876 // non NULL because of the test above) for both times
1877 utimbuf utm;
1878 utm.actime = dtAccess ? dtAccess->GetTicks() : dtMod->GetTicks();
1879 utm.modtime = dtMod ? dtMod->GetTicks() : dtAccess->GetTicks();
1880 if ( utime(GetFullPath().fn_str(), &utm) == 0 )
1881 {
1882 return true;
1883 }
1884 #else // other platform
1885 #endif // platforms
1886
1887 wxLogSysError(_("Failed to modify file times for '%s'"),
1888 GetFullPath().c_str());
1889
1890 return false;
1891 }
1892
1893 bool wxFileName::Touch()
1894 {
1895 #if defined(__UNIX_LIKE__)
1896 // under Unix touching file is simple: just pass NULL to utime()
1897 if ( utime(GetFullPath().fn_str(), NULL) == 0 )
1898 {
1899 return true;
1900 }
1901
1902 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
1903
1904 return false;
1905 #else // other platform
1906 wxDateTime dtNow = wxDateTime::Now();
1907
1908 return SetTimes(&dtNow, &dtNow, NULL /* don't change create time */);
1909 #endif // platforms
1910 }
1911
1912 bool wxFileName::GetTimes(wxDateTime *dtAccess,
1913 wxDateTime *dtMod,
1914 wxDateTime *dtCreate) const
1915 {
1916 #if defined(__WIN32__)
1917 // we must use different methods for the files and directories under
1918 // Windows as CreateFile(GENERIC_READ) doesn't work for the directories and
1919 // CreateFile(FILE_FLAG_BACKUP_SEMANTICS) works -- but only under NT and
1920 // not 9x
1921 bool ok;
1922 FILETIME ftAccess, ftCreate, ftWrite;
1923 if ( IsDir() )
1924 {
1925 // implemented in msw/dir.cpp
1926 extern bool wxGetDirectoryTimes(const wxString& dirname,
1927 FILETIME *, FILETIME *, FILETIME *);
1928
1929 // we should pass the path without the trailing separator to
1930 // wxGetDirectoryTimes()
1931 ok = wxGetDirectoryTimes(GetPath(wxPATH_GET_VOLUME),
1932 &ftAccess, &ftCreate, &ftWrite);
1933 }
1934 else // file
1935 {
1936 wxFileHandle fh(GetFullPath(), wxFileHandle::Read);
1937 if ( fh.IsOk() )
1938 {
1939 ok = ::GetFileTime(fh,
1940 dtCreate ? &ftCreate : NULL,
1941 dtAccess ? &ftAccess : NULL,
1942 dtMod ? &ftWrite : NULL) != 0;
1943 }
1944 else
1945 {
1946 ok = false;
1947 }
1948 }
1949
1950 if ( ok )
1951 {
1952 if ( dtCreate )
1953 ConvertFileTimeToWx(dtCreate, ftCreate);
1954 if ( dtAccess )
1955 ConvertFileTimeToWx(dtAccess, ftAccess);
1956 if ( dtMod )
1957 ConvertFileTimeToWx(dtMod, ftWrite);
1958
1959 return true;
1960 }
1961 #elif defined(__UNIX_LIKE__) || defined(__WXMAC__) || (defined(__DOS__) && defined(__WATCOMC__))
1962 wxStructStat stBuf;
1963 if ( wxStat( GetFullPath().c_str(), &stBuf) == 0 )
1964 {
1965 if ( dtAccess )
1966 dtAccess->Set(stBuf.st_atime);
1967 if ( dtMod )
1968 dtMod->Set(stBuf.st_mtime);
1969 if ( dtCreate )
1970 dtCreate->Set(stBuf.st_ctime);
1971
1972 return true;
1973 }
1974 #else // other platform
1975 #endif // platforms
1976
1977 wxLogSysError(_("Failed to retrieve file times for '%s'"),
1978 GetFullPath().c_str());
1979
1980 return false;
1981 }
1982
1983 #endif // wxUSE_DATETIME
1984
1985 #ifdef __WXMAC__
1986
1987 const short kMacExtensionMaxLength = 16 ;
1988 class MacDefaultExtensionRecord
1989 {
1990 public :
1991 MacDefaultExtensionRecord()
1992 {
1993 m_ext[0] = 0 ;
1994 m_type = m_creator = NULL ;
1995 }
1996 MacDefaultExtensionRecord( const MacDefaultExtensionRecord& from )
1997 {
1998 wxStrcpy( m_ext , from.m_ext ) ;
1999 m_type = from.m_type ;
2000 m_creator = from.m_creator ;
2001 }
2002 MacDefaultExtensionRecord( const wxChar * extension , OSType type , OSType creator )
2003 {
2004 wxStrncpy( m_ext , extension , kMacExtensionMaxLength ) ;
2005 m_ext[kMacExtensionMaxLength] = 0 ;
2006 m_type = type ;
2007 m_creator = creator ;
2008 }
2009 wxChar m_ext[kMacExtensionMaxLength] ;
2010 OSType m_type ;
2011 OSType m_creator ;
2012 } ;
2013
2014 #include "wx/dynarray.h"
2015 WX_DECLARE_OBJARRAY(MacDefaultExtensionRecord, MacDefaultExtensionArray) ;
2016
2017 bool gMacDefaultExtensionsInited = false ;
2018
2019 #include "wx/arrimpl.cpp"
2020
2021 WX_DEFINE_EXPORTED_OBJARRAY(MacDefaultExtensionArray) ;
2022
2023 MacDefaultExtensionArray gMacDefaultExtensions ;
2024
2025 // load the default extensions
2026 MacDefaultExtensionRecord gDefaults[] =
2027 {
2028 MacDefaultExtensionRecord( wxT("txt") , 'TEXT' , 'ttxt' ) ,
2029 MacDefaultExtensionRecord( wxT("tif") , 'TIFF' , '****' ) ,
2030 MacDefaultExtensionRecord( wxT("jpg") , 'JPEG' , '****' ) ,
2031 } ;
2032
2033 static void MacEnsureDefaultExtensionsLoaded()
2034 {
2035 if ( !gMacDefaultExtensionsInited )
2036 {
2037 // we could load the pc exchange prefs here too
2038 for ( size_t i = 0 ; i < WXSIZEOF( gDefaults ) ; ++i )
2039 {
2040 gMacDefaultExtensions.Add( gDefaults[i] ) ;
2041 }
2042 gMacDefaultExtensionsInited = true ;
2043 }
2044 }
2045
2046 bool wxFileName::MacSetTypeAndCreator( wxUint32 type , wxUint32 creator )
2047 {
2048 FSRef fsRef ;
2049 FSCatalogInfo catInfo;
2050 FileInfo *finfo ;
2051
2052 if ( wxMacPathToFSRef( GetFullPath() , &fsRef ) == noErr )
2053 {
2054 if ( FSGetCatalogInfo (&fsRef, kFSCatInfoFinderInfo, &catInfo, NULL, NULL, NULL) == noErr )
2055 {
2056 finfo = (FileInfo*)&catInfo.finderInfo;
2057 finfo->fileType = type ;
2058 finfo->fileCreator = creator ;
2059 FSSetCatalogInfo( &fsRef, kFSCatInfoFinderInfo, &catInfo ) ;
2060 return true ;
2061 }
2062 }
2063 return false ;
2064 }
2065
2066 bool wxFileName::MacGetTypeAndCreator( wxUint32 *type , wxUint32 *creator )
2067 {
2068 FSRef fsRef ;
2069 FSCatalogInfo catInfo;
2070 FileInfo *finfo ;
2071
2072 if ( wxMacPathToFSRef( GetFullPath() , &fsRef ) == noErr )
2073 {
2074 if ( FSGetCatalogInfo (&fsRef, kFSCatInfoFinderInfo, &catInfo, NULL, NULL, NULL) == noErr )
2075 {
2076 finfo = (FileInfo*)&catInfo.finderInfo;
2077 *type = finfo->fileType ;
2078 *creator = finfo->fileCreator ;
2079 return true ;
2080 }
2081 }
2082 return false ;
2083 }
2084
2085 bool wxFileName::MacSetDefaultTypeAndCreator()
2086 {
2087 wxUint32 type , creator ;
2088 if ( wxFileName::MacFindDefaultTypeAndCreator(GetExt() , &type ,
2089 &creator ) )
2090 {
2091 return MacSetTypeAndCreator( type , creator ) ;
2092 }
2093 return false;
2094 }
2095
2096 bool wxFileName::MacFindDefaultTypeAndCreator( const wxString& ext , wxUint32 *type , wxUint32 *creator )
2097 {
2098 MacEnsureDefaultExtensionsLoaded() ;
2099 wxString extl = ext.Lower() ;
2100 for( int i = gMacDefaultExtensions.Count() - 1 ; i >= 0 ; --i )
2101 {
2102 if ( gMacDefaultExtensions.Item(i).m_ext == extl )
2103 {
2104 *type = gMacDefaultExtensions.Item(i).m_type ;
2105 *creator = gMacDefaultExtensions.Item(i).m_creator ;
2106 return true ;
2107 }
2108 }
2109 return false ;
2110 }
2111
2112 void wxFileName::MacRegisterDefaultTypeAndCreator( const wxString& ext , wxUint32 type , wxUint32 creator )
2113 {
2114 MacEnsureDefaultExtensionsLoaded() ;
2115 MacDefaultExtensionRecord rec ;
2116 rec.m_type = type ;
2117 rec.m_creator = creator ;
2118 wxStrncpy( rec.m_ext , ext.Lower().c_str() , kMacExtensionMaxLength ) ;
2119 gMacDefaultExtensions.Add( rec ) ;
2120 }
2121 #endif