OW warning fix. Our compile time asserts warns when used within function and dedicate...
[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 // In case of a new path format
1194 // addition, the following code might have to be updated.
1195 switch ( GetFormat(format) )
1196 {
1197 default :
1198 wxFAIL_MSG( wxT("Unknown path format") );
1199 // !! Fall through !!
1200
1201 case wxPATH_UNIX:
1202 break;
1203
1204 case wxPATH_MAC:
1205 // On a Mac even names with * and ? are allowed (Tested with OS
1206 // 9.2.1 and OS X 10.2.5)
1207 strForbiddenChars = wxEmptyString;
1208 break;
1209
1210 case wxPATH_DOS:
1211 strForbiddenChars += wxT("\\/:\"<>|");
1212 break;
1213
1214 case wxPATH_VMS:
1215 break;
1216 }
1217
1218 return strForbiddenChars;
1219 }
1220
1221 /* static */
1222 wxString wxFileName::GetVolumeSeparator(wxPathFormat format)
1223 {
1224 wxString sepVol;
1225
1226 if ( (GetFormat(format) == wxPATH_DOS) ||
1227 (GetFormat(format) == wxPATH_VMS) )
1228 {
1229 sepVol = wxFILE_SEP_DSK;
1230 }
1231 //else: leave empty
1232
1233 return sepVol;
1234 }
1235
1236 /* static */
1237 wxString wxFileName::GetPathSeparators(wxPathFormat format)
1238 {
1239 wxString seps;
1240 switch ( GetFormat(format) )
1241 {
1242 case wxPATH_DOS:
1243 // accept both as native APIs do but put the native one first as
1244 // this is the one we use in GetFullPath()
1245 seps << wxFILE_SEP_PATH_DOS << wxFILE_SEP_PATH_UNIX;
1246 break;
1247
1248 default:
1249 wxFAIL_MSG( _T("Unknown wxPATH_XXX style") );
1250 // fall through
1251
1252 case wxPATH_UNIX:
1253 seps = wxFILE_SEP_PATH_UNIX;
1254 break;
1255
1256 case wxPATH_MAC:
1257 seps = wxFILE_SEP_PATH_MAC;
1258 break;
1259
1260 case wxPATH_VMS:
1261 seps = wxFILE_SEP_PATH_VMS;
1262 break;
1263 }
1264
1265 return seps;
1266 }
1267
1268 /* static */
1269 wxString wxFileName::GetPathTerminators(wxPathFormat format)
1270 {
1271 format = GetFormat(format);
1272
1273 // under VMS the end of the path is ']', not the path separator used to
1274 // separate the components
1275 return format == wxPATH_VMS ? wxString(_T(']')) : GetPathSeparators(format);
1276 }
1277
1278 /* static */
1279 bool wxFileName::IsPathSeparator(wxChar ch, wxPathFormat format)
1280 {
1281 // wxString::Find() doesn't work as expected with NUL - it will always find
1282 // it, so it is almost surely a bug if this function is called with NUL arg
1283 wxASSERT_MSG( ch != _T('\0'), _T("shouldn't be called with NUL") );
1284
1285 return GetPathSeparators(format).Find(ch) != wxNOT_FOUND;
1286 }
1287
1288 // ----------------------------------------------------------------------------
1289 // path components manipulation
1290 // ----------------------------------------------------------------------------
1291
1292 /* static */ bool wxFileName::IsValidDirComponent(const wxString& dir)
1293 {
1294 if ( dir.empty() )
1295 {
1296 wxFAIL_MSG( _T("empty directory passed to wxFileName::InsertDir()") );
1297
1298 return false;
1299 }
1300
1301 const size_t len = dir.length();
1302 for ( size_t n = 0; n < len; n++ )
1303 {
1304 if ( dir[n] == GetVolumeSeparator() || IsPathSeparator(dir[n]) )
1305 {
1306 wxFAIL_MSG( _T("invalid directory component in wxFileName") );
1307
1308 return false;
1309 }
1310 }
1311
1312 return true;
1313 }
1314
1315 void wxFileName::AppendDir( const wxString &dir )
1316 {
1317 if ( IsValidDirComponent(dir) )
1318 m_dirs.Add( dir );
1319 }
1320
1321 void wxFileName::PrependDir( const wxString &dir )
1322 {
1323 InsertDir(0, dir);
1324 }
1325
1326 void wxFileName::InsertDir( int before, const wxString &dir )
1327 {
1328 if ( IsValidDirComponent(dir) )
1329 m_dirs.Insert( dir, before );
1330 }
1331
1332 void wxFileName::RemoveDir( int pos )
1333 {
1334 m_dirs.RemoveAt( (size_t)pos );
1335 }
1336
1337 // ----------------------------------------------------------------------------
1338 // accessors
1339 // ----------------------------------------------------------------------------
1340
1341 void wxFileName::SetFullName(const wxString& fullname)
1342 {
1343 SplitPath(fullname, NULL /* no path */, &m_name, &m_ext);
1344 }
1345
1346 wxString wxFileName::GetFullName() const
1347 {
1348 wxString fullname = m_name;
1349 if ( !m_ext.empty() )
1350 {
1351 fullname << wxFILE_SEP_EXT << m_ext;
1352 }
1353
1354 return fullname;
1355 }
1356
1357 wxString wxFileName::GetPath( int flags, wxPathFormat format ) const
1358 {
1359 format = GetFormat( format );
1360
1361 wxString fullpath;
1362
1363 // return the volume with the path as well if requested
1364 if ( flags & wxPATH_GET_VOLUME )
1365 {
1366 fullpath += wxGetVolumeString(GetVolume(), format);
1367 }
1368
1369 // the leading character
1370 switch ( format )
1371 {
1372 case wxPATH_MAC:
1373 if ( m_relative )
1374 fullpath += wxFILE_SEP_PATH_MAC;
1375 break;
1376
1377 case wxPATH_DOS:
1378 if ( !m_relative )
1379 fullpath += wxFILE_SEP_PATH_DOS;
1380 break;
1381
1382 default:
1383 wxFAIL_MSG( wxT("Unknown path format") );
1384 // fall through
1385
1386 case wxPATH_UNIX:
1387 if ( !m_relative )
1388 {
1389 // normally the absolute file names start with a slash
1390 // with one exception: the ones like "~/foo.bar" don't
1391 // have it
1392 if ( m_dirs.IsEmpty() || m_dirs[0u] != _T('~') )
1393 {
1394 fullpath += wxFILE_SEP_PATH_UNIX;
1395 }
1396 }
1397 break;
1398
1399 case wxPATH_VMS:
1400 // no leading character here but use this place to unset
1401 // wxPATH_GET_SEPARATOR flag: under VMS it doesn't make sense
1402 // as, if I understand correctly, there should never be a dot
1403 // before the closing bracket
1404 flags &= ~wxPATH_GET_SEPARATOR;
1405 }
1406
1407 if ( m_dirs.empty() )
1408 {
1409 // there is nothing more
1410 return fullpath;
1411 }
1412
1413 // then concatenate all the path components using the path separator
1414 if ( format == wxPATH_VMS )
1415 {
1416 fullpath += wxT('[');
1417 }
1418
1419 const size_t dirCount = m_dirs.GetCount();
1420 for ( size_t i = 0; i < dirCount; i++ )
1421 {
1422 switch (format)
1423 {
1424 case wxPATH_MAC:
1425 if ( m_dirs[i] == wxT(".") )
1426 {
1427 // skip appending ':', this shouldn't be done in this
1428 // case as "::" is interpreted as ".." under Unix
1429 continue;
1430 }
1431
1432 // convert back from ".." to nothing
1433 if ( m_dirs[i] != wxT("..") )
1434 fullpath += m_dirs[i];
1435 break;
1436
1437 default:
1438 wxFAIL_MSG( wxT("Unexpected path format") );
1439 // still fall through
1440
1441 case wxPATH_DOS:
1442 case wxPATH_UNIX:
1443 fullpath += m_dirs[i];
1444 break;
1445
1446 case wxPATH_VMS:
1447 // TODO: What to do with ".." under VMS
1448
1449 // convert back from ".." to nothing
1450 if ( m_dirs[i] != wxT("..") )
1451 fullpath += m_dirs[i];
1452 break;
1453 }
1454
1455 if ( (flags & wxPATH_GET_SEPARATOR) || (i != dirCount - 1) )
1456 fullpath += GetPathSeparator(format);
1457 }
1458
1459 if ( format == wxPATH_VMS )
1460 {
1461 fullpath += wxT(']');
1462 }
1463
1464 return fullpath;
1465 }
1466
1467 wxString wxFileName::GetFullPath( wxPathFormat format ) const
1468 {
1469 // we already have a function to get the path
1470 wxString fullpath = GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR,
1471 format);
1472
1473 // now just add the file name and extension to it
1474 fullpath += GetFullName();
1475
1476 return fullpath;
1477 }
1478
1479 // Return the short form of the path (returns identity on non-Windows platforms)
1480 wxString wxFileName::GetShortPath() const
1481 {
1482 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
1483 wxString path(GetFullPath());
1484 wxString pathOut;
1485 DWORD sz = ::GetShortPathName(path, NULL, 0);
1486 bool ok = sz != 0;
1487 if ( ok )
1488 {
1489 ok = ::GetShortPathName
1490 (
1491 path,
1492 wxStringBuffer(pathOut, sz),
1493 sz
1494 ) != 0;
1495 }
1496 if (ok)
1497 return pathOut;
1498
1499 return path;
1500 #else
1501 return GetFullPath();
1502 #endif
1503 }
1504
1505 // Return the long form of the path (returns identity on non-Windows platforms)
1506 wxString wxFileName::GetLongPath() const
1507 {
1508 wxString pathOut,
1509 path = GetFullPath();
1510
1511 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1512 bool success = false;
1513
1514 #if wxUSE_DYNAMIC_LOADER
1515 typedef DWORD (WINAPI *GET_LONG_PATH_NAME)(const wxChar *, wxChar *, DWORD);
1516
1517 static bool s_triedToLoad = false;
1518
1519 if ( !s_triedToLoad )
1520 {
1521 // suppress the errors about missing GetLongPathName[AW]
1522 wxLogNull noLog;
1523
1524 s_triedToLoad = true;
1525 wxDynamicLibrary dllKernel(_T("kernel32"));
1526 if ( dllKernel.IsLoaded() )
1527 {
1528 // may succeed or fail depending on the Windows version
1529 static GET_LONG_PATH_NAME s_pfnGetLongPathName = NULL;
1530 #ifdef _UNICODE
1531 s_pfnGetLongPathName = (GET_LONG_PATH_NAME) dllKernel.GetSymbol(_T("GetLongPathNameW"));
1532 #else
1533 s_pfnGetLongPathName = (GET_LONG_PATH_NAME) dllKernel.GetSymbol(_T("GetLongPathNameA"));
1534 #endif
1535
1536 if ( s_pfnGetLongPathName )
1537 {
1538 DWORD dwSize = (*s_pfnGetLongPathName)(path, NULL, 0);
1539 bool ok = dwSize > 0;
1540
1541 if ( ok )
1542 {
1543 DWORD sz = (*s_pfnGetLongPathName)(path, NULL, 0);
1544 ok = sz != 0;
1545 if ( ok )
1546 {
1547 ok = (*s_pfnGetLongPathName)
1548 (
1549 path,
1550 wxStringBuffer(pathOut, sz),
1551 sz
1552 ) != 0;
1553 success = true;
1554 }
1555 }
1556 }
1557 }
1558 }
1559
1560 if (success)
1561 return pathOut;
1562 #endif // wxUSE_DYNAMIC_LOADER
1563
1564 if (!success)
1565 {
1566 // The OS didn't support GetLongPathName, or some other error.
1567 // We need to call FindFirstFile on each component in turn.
1568
1569 WIN32_FIND_DATA findFileData;
1570 HANDLE hFind;
1571
1572 if ( HasVolume() )
1573 pathOut = GetVolume() +
1574 GetVolumeSeparator(wxPATH_DOS) +
1575 GetPathSeparator(wxPATH_DOS);
1576 else
1577 pathOut = wxEmptyString;
1578
1579 wxArrayString dirs = GetDirs();
1580 dirs.Add(GetFullName());
1581
1582 wxString tmpPath;
1583
1584 size_t count = dirs.GetCount();
1585 for ( size_t i = 0; i < count; i++ )
1586 {
1587 // We're using pathOut to collect the long-name path, but using a
1588 // temporary for appending the last path component which may be
1589 // short-name
1590 tmpPath = pathOut + dirs[i];
1591
1592 if ( tmpPath.empty() )
1593 continue;
1594
1595 // can't see this being necessary? MF
1596 if ( tmpPath.Last() == GetVolumeSeparator(wxPATH_DOS) )
1597 {
1598 // Can't pass a drive and root dir to FindFirstFile,
1599 // so continue to next dir
1600 tmpPath += wxFILE_SEP_PATH;
1601 pathOut = tmpPath;
1602 continue;
1603 }
1604
1605 hFind = ::FindFirstFile(tmpPath, &findFileData);
1606 if (hFind == INVALID_HANDLE_VALUE)
1607 {
1608 // Error: most likely reason is that path doesn't exist, so
1609 // append any unprocessed parts and return
1610 for ( i += 1; i < count; i++ )
1611 tmpPath += wxFILE_SEP_PATH + dirs[i];
1612
1613 return tmpPath;
1614 }
1615
1616 pathOut += findFileData.cFileName;
1617 if ( (i < (count-1)) )
1618 pathOut += wxFILE_SEP_PATH;
1619
1620 ::FindClose(hFind);
1621 }
1622 }
1623 #else // !Win32
1624 pathOut = path;
1625 #endif // Win32/!Win32
1626
1627 return pathOut;
1628 }
1629
1630 wxPathFormat wxFileName::GetFormat( wxPathFormat format )
1631 {
1632 if (format == wxPATH_NATIVE)
1633 {
1634 #if defined(__WXMSW__) || defined(__OS2__) || defined(__DOS__)
1635 format = wxPATH_DOS;
1636 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1637 format = wxPATH_MAC;
1638 #elif defined(__VMS)
1639 format = wxPATH_VMS;
1640 #else
1641 format = wxPATH_UNIX;
1642 #endif
1643 }
1644 return format;
1645 }
1646
1647 // ----------------------------------------------------------------------------
1648 // path splitting function
1649 // ----------------------------------------------------------------------------
1650
1651 /* static */
1652 void
1653 wxFileName::SplitVolume(const wxString& fullpathWithVolume,
1654 wxString *pstrVolume,
1655 wxString *pstrPath,
1656 wxPathFormat format)
1657 {
1658 format = GetFormat(format);
1659
1660 wxString fullpath = fullpathWithVolume;
1661
1662 // special Windows UNC paths hack: transform \\share\path into share:path
1663 if ( format == wxPATH_DOS )
1664 {
1665 if ( fullpath.length() >= 4 &&
1666 fullpath[0u] == wxFILE_SEP_PATH_DOS &&
1667 fullpath[1u] == wxFILE_SEP_PATH_DOS )
1668 {
1669 fullpath.erase(0, 2);
1670
1671 size_t posFirstSlash =
1672 fullpath.find_first_of(GetPathTerminators(format));
1673 if ( posFirstSlash != wxString::npos )
1674 {
1675 fullpath[posFirstSlash] = wxFILE_SEP_DSK;
1676
1677 // UNC paths are always absolute, right? (FIXME)
1678 fullpath.insert(posFirstSlash + 1, 1, wxFILE_SEP_PATH_DOS);
1679 }
1680 }
1681 }
1682
1683 // We separate the volume here
1684 if ( format == wxPATH_DOS || format == wxPATH_VMS )
1685 {
1686 wxString sepVol = GetVolumeSeparator(format);
1687
1688 size_t posFirstColon = fullpath.find_first_of(sepVol);
1689 if ( posFirstColon != wxString::npos )
1690 {
1691 if ( pstrVolume )
1692 {
1693 *pstrVolume = fullpath.Left(posFirstColon);
1694 }
1695
1696 // remove the volume name and the separator from the full path
1697 fullpath.erase(0, posFirstColon + sepVol.length());
1698 }
1699 }
1700
1701 if ( pstrPath )
1702 *pstrPath = fullpath;
1703 }
1704
1705 /* static */
1706 void wxFileName::SplitPath(const wxString& fullpathWithVolume,
1707 wxString *pstrVolume,
1708 wxString *pstrPath,
1709 wxString *pstrName,
1710 wxString *pstrExt,
1711 wxPathFormat format)
1712 {
1713 format = GetFormat(format);
1714
1715 wxString fullpath;
1716 SplitVolume(fullpathWithVolume, pstrVolume, &fullpath, format);
1717
1718 // find the positions of the last dot and last path separator in the path
1719 size_t posLastDot = fullpath.find_last_of(wxFILE_SEP_EXT);
1720 size_t posLastSlash = fullpath.find_last_of(GetPathTerminators(format));
1721
1722 // check whether this dot occurs at the very beginning of a path component
1723 if ( (posLastDot != wxString::npos) &&
1724 (posLastDot == 0 ||
1725 IsPathSeparator(fullpath[posLastDot - 1]) ||
1726 (format == wxPATH_VMS && fullpath[posLastDot - 1] == _T(']'))) )
1727 {
1728 // dot may be (and commonly -- at least under Unix -- is) the first
1729 // character of the filename, don't treat the entire filename as
1730 // extension in this case
1731 posLastDot = wxString::npos;
1732 }
1733
1734 // if we do have a dot and a slash, check that the dot is in the name part
1735 if ( (posLastDot != wxString::npos) &&
1736 (posLastSlash != wxString::npos) &&
1737 (posLastDot < posLastSlash) )
1738 {
1739 // the dot is part of the path, not the start of the extension
1740 posLastDot = wxString::npos;
1741 }
1742
1743 // now fill in the variables provided by user
1744 if ( pstrPath )
1745 {
1746 if ( posLastSlash == wxString::npos )
1747 {
1748 // no path at all
1749 pstrPath->Empty();
1750 }
1751 else
1752 {
1753 // take everything up to the path separator but take care to make
1754 // the path equal to something like '/', not empty, for the files
1755 // immediately under root directory
1756 size_t len = posLastSlash;
1757
1758 // this rule does not apply to mac since we do not start with colons (sep)
1759 // except for relative paths
1760 if ( !len && format != wxPATH_MAC)
1761 len++;
1762
1763 *pstrPath = fullpath.Left(len);
1764
1765 // special VMS hack: remove the initial bracket
1766 if ( format == wxPATH_VMS )
1767 {
1768 if ( (*pstrPath)[0u] == _T('[') )
1769 pstrPath->erase(0, 1);
1770 }
1771 }
1772 }
1773
1774 if ( pstrName )
1775 {
1776 // take all characters starting from the one after the last slash and
1777 // up to, but excluding, the last dot
1778 size_t nStart = posLastSlash == wxString::npos ? 0 : posLastSlash + 1;
1779 size_t count;
1780 if ( posLastDot == wxString::npos )
1781 {
1782 // take all until the end
1783 count = wxString::npos;
1784 }
1785 else if ( posLastSlash == wxString::npos )
1786 {
1787 count = posLastDot;
1788 }
1789 else // have both dot and slash
1790 {
1791 count = posLastDot - posLastSlash - 1;
1792 }
1793
1794 *pstrName = fullpath.Mid(nStart, count);
1795 }
1796
1797 if ( pstrExt )
1798 {
1799 if ( posLastDot == wxString::npos )
1800 {
1801 // no extension
1802 pstrExt->Empty();
1803 }
1804 else
1805 {
1806 // take everything after the dot
1807 *pstrExt = fullpath.Mid(posLastDot + 1);
1808 }
1809 }
1810 }
1811
1812 /* static */
1813 void wxFileName::SplitPath(const wxString& fullpath,
1814 wxString *path,
1815 wxString *name,
1816 wxString *ext,
1817 wxPathFormat format)
1818 {
1819 wxString volume;
1820 SplitPath(fullpath, &volume, path, name, ext, format);
1821
1822 if ( path )
1823 {
1824 path->Prepend(wxGetVolumeString(volume, format));
1825 }
1826 }
1827
1828 // ----------------------------------------------------------------------------
1829 // time functions
1830 // ----------------------------------------------------------------------------
1831
1832 #if wxUSE_DATETIME
1833
1834 bool wxFileName::SetTimes(const wxDateTime *dtAccess,
1835 const wxDateTime *dtMod,
1836 const wxDateTime *dtCreate)
1837 {
1838 #if defined(__WIN32__)
1839 if ( IsDir() )
1840 {
1841 // VZ: please let me know how to do this if you can
1842 wxFAIL_MSG( _T("SetTimes() not implemented for the directories") );
1843 }
1844 else // file
1845 {
1846 wxFileHandle fh(GetFullPath(), wxFileHandle::Write);
1847 if ( fh.IsOk() )
1848 {
1849 FILETIME ftAccess, ftCreate, ftWrite;
1850
1851 if ( dtCreate )
1852 ConvertWxToFileTime(&ftCreate, *dtCreate);
1853 if ( dtAccess )
1854 ConvertWxToFileTime(&ftAccess, *dtAccess);
1855 if ( dtMod )
1856 ConvertWxToFileTime(&ftWrite, *dtMod);
1857
1858 if ( ::SetFileTime(fh,
1859 dtCreate ? &ftCreate : NULL,
1860 dtAccess ? &ftAccess : NULL,
1861 dtMod ? &ftWrite : NULL) )
1862 {
1863 return true;
1864 }
1865 }
1866 }
1867 #elif defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
1868 if ( !dtAccess && !dtMod )
1869 {
1870 // can't modify the creation time anyhow, don't try
1871 return true;
1872 }
1873
1874 // if dtAccess or dtMod is not specified, use the other one (which must be
1875 // non NULL because of the test above) for both times
1876 utimbuf utm;
1877 utm.actime = dtAccess ? dtAccess->GetTicks() : dtMod->GetTicks();
1878 utm.modtime = dtMod ? dtMod->GetTicks() : dtAccess->GetTicks();
1879 if ( utime(GetFullPath().fn_str(), &utm) == 0 )
1880 {
1881 return true;
1882 }
1883 #else // other platform
1884 #endif // platforms
1885
1886 wxLogSysError(_("Failed to modify file times for '%s'"),
1887 GetFullPath().c_str());
1888
1889 return false;
1890 }
1891
1892 bool wxFileName::Touch()
1893 {
1894 #if defined(__UNIX_LIKE__)
1895 // under Unix touching file is simple: just pass NULL to utime()
1896 if ( utime(GetFullPath().fn_str(), NULL) == 0 )
1897 {
1898 return true;
1899 }
1900
1901 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
1902
1903 return false;
1904 #else // other platform
1905 wxDateTime dtNow = wxDateTime::Now();
1906
1907 return SetTimes(&dtNow, &dtNow, NULL /* don't change create time */);
1908 #endif // platforms
1909 }
1910
1911 bool wxFileName::GetTimes(wxDateTime *dtAccess,
1912 wxDateTime *dtMod,
1913 wxDateTime *dtCreate) const
1914 {
1915 #if defined(__WIN32__)
1916 // we must use different methods for the files and directories under
1917 // Windows as CreateFile(GENERIC_READ) doesn't work for the directories and
1918 // CreateFile(FILE_FLAG_BACKUP_SEMANTICS) works -- but only under NT and
1919 // not 9x
1920 bool ok;
1921 FILETIME ftAccess, ftCreate, ftWrite;
1922 if ( IsDir() )
1923 {
1924 // implemented in msw/dir.cpp
1925 extern bool wxGetDirectoryTimes(const wxString& dirname,
1926 FILETIME *, FILETIME *, FILETIME *);
1927
1928 // we should pass the path without the trailing separator to
1929 // wxGetDirectoryTimes()
1930 ok = wxGetDirectoryTimes(GetPath(wxPATH_GET_VOLUME),
1931 &ftAccess, &ftCreate, &ftWrite);
1932 }
1933 else // file
1934 {
1935 wxFileHandle fh(GetFullPath(), wxFileHandle::Read);
1936 if ( fh.IsOk() )
1937 {
1938 ok = ::GetFileTime(fh,
1939 dtCreate ? &ftCreate : NULL,
1940 dtAccess ? &ftAccess : NULL,
1941 dtMod ? &ftWrite : NULL) != 0;
1942 }
1943 else
1944 {
1945 ok = false;
1946 }
1947 }
1948
1949 if ( ok )
1950 {
1951 if ( dtCreate )
1952 ConvertFileTimeToWx(dtCreate, ftCreate);
1953 if ( dtAccess )
1954 ConvertFileTimeToWx(dtAccess, ftAccess);
1955 if ( dtMod )
1956 ConvertFileTimeToWx(dtMod, ftWrite);
1957
1958 return true;
1959 }
1960 #elif defined(__UNIX_LIKE__) || defined(__WXMAC__) || (defined(__DOS__) && defined(__WATCOMC__))
1961 wxStructStat stBuf;
1962 if ( wxStat( GetFullPath().c_str(), &stBuf) == 0 )
1963 {
1964 if ( dtAccess )
1965 dtAccess->Set(stBuf.st_atime);
1966 if ( dtMod )
1967 dtMod->Set(stBuf.st_mtime);
1968 if ( dtCreate )
1969 dtCreate->Set(stBuf.st_ctime);
1970
1971 return true;
1972 }
1973 #else // other platform
1974 #endif // platforms
1975
1976 wxLogSysError(_("Failed to retrieve file times for '%s'"),
1977 GetFullPath().c_str());
1978
1979 return false;
1980 }
1981
1982 #endif // wxUSE_DATETIME
1983
1984 #ifdef __WXMAC__
1985
1986 const short kMacExtensionMaxLength = 16 ;
1987 class MacDefaultExtensionRecord
1988 {
1989 public :
1990 MacDefaultExtensionRecord()
1991 {
1992 m_ext[0] = 0 ;
1993 m_type = m_creator = NULL ;
1994 }
1995 MacDefaultExtensionRecord( const MacDefaultExtensionRecord& from )
1996 {
1997 wxStrcpy( m_ext , from.m_ext ) ;
1998 m_type = from.m_type ;
1999 m_creator = from.m_creator ;
2000 }
2001 MacDefaultExtensionRecord( const wxChar * extension , OSType type , OSType creator )
2002 {
2003 wxStrncpy( m_ext , extension , kMacExtensionMaxLength ) ;
2004 m_ext[kMacExtensionMaxLength] = 0 ;
2005 m_type = type ;
2006 m_creator = creator ;
2007 }
2008 wxChar m_ext[kMacExtensionMaxLength] ;
2009 OSType m_type ;
2010 OSType m_creator ;
2011 } ;
2012
2013 #include "wx/dynarray.h"
2014 WX_DECLARE_OBJARRAY(MacDefaultExtensionRecord, MacDefaultExtensionArray) ;
2015
2016 bool gMacDefaultExtensionsInited = false ;
2017
2018 #include "wx/arrimpl.cpp"
2019
2020 WX_DEFINE_EXPORTED_OBJARRAY(MacDefaultExtensionArray) ;
2021
2022 MacDefaultExtensionArray gMacDefaultExtensions ;
2023
2024 // load the default extensions
2025 MacDefaultExtensionRecord gDefaults[] =
2026 {
2027 MacDefaultExtensionRecord( wxT("txt") , 'TEXT' , 'ttxt' ) ,
2028 MacDefaultExtensionRecord( wxT("tif") , 'TIFF' , '****' ) ,
2029 MacDefaultExtensionRecord( wxT("jpg") , 'JPEG' , '****' ) ,
2030 } ;
2031
2032 static void MacEnsureDefaultExtensionsLoaded()
2033 {
2034 if ( !gMacDefaultExtensionsInited )
2035 {
2036 // we could load the pc exchange prefs here too
2037 for ( size_t i = 0 ; i < WXSIZEOF( gDefaults ) ; ++i )
2038 {
2039 gMacDefaultExtensions.Add( gDefaults[i] ) ;
2040 }
2041 gMacDefaultExtensionsInited = true ;
2042 }
2043 }
2044
2045 bool wxFileName::MacSetTypeAndCreator( wxUint32 type , wxUint32 creator )
2046 {
2047 FSRef fsRef ;
2048 FSCatalogInfo catInfo;
2049 FileInfo *finfo ;
2050
2051 if ( wxMacPathToFSRef( GetFullPath() , &fsRef ) == noErr )
2052 {
2053 if ( FSGetCatalogInfo (&fsRef, kFSCatInfoFinderInfo, &catInfo, NULL, NULL, NULL) == noErr )
2054 {
2055 finfo = (FileInfo*)&catInfo.finderInfo;
2056 finfo->fileType = type ;
2057 finfo->fileCreator = creator ;
2058 FSSetCatalogInfo( &fsRef, kFSCatInfoFinderInfo, &catInfo ) ;
2059 return true ;
2060 }
2061 }
2062 return false ;
2063 }
2064
2065 bool wxFileName::MacGetTypeAndCreator( wxUint32 *type , wxUint32 *creator )
2066 {
2067 FSRef fsRef ;
2068 FSCatalogInfo catInfo;
2069 FileInfo *finfo ;
2070
2071 if ( wxMacPathToFSRef( GetFullPath() , &fsRef ) == noErr )
2072 {
2073 if ( FSGetCatalogInfo (&fsRef, kFSCatInfoFinderInfo, &catInfo, NULL, NULL, NULL) == noErr )
2074 {
2075 finfo = (FileInfo*)&catInfo.finderInfo;
2076 *type = finfo->fileType ;
2077 *creator = finfo->fileCreator ;
2078 return true ;
2079 }
2080 }
2081 return false ;
2082 }
2083
2084 bool wxFileName::MacSetDefaultTypeAndCreator()
2085 {
2086 wxUint32 type , creator ;
2087 if ( wxFileName::MacFindDefaultTypeAndCreator(GetExt() , &type ,
2088 &creator ) )
2089 {
2090 return MacSetTypeAndCreator( type , creator ) ;
2091 }
2092 return false;
2093 }
2094
2095 bool wxFileName::MacFindDefaultTypeAndCreator( const wxString& ext , wxUint32 *type , wxUint32 *creator )
2096 {
2097 MacEnsureDefaultExtensionsLoaded() ;
2098 wxString extl = ext.Lower() ;
2099 for( int i = gMacDefaultExtensions.Count() - 1 ; i >= 0 ; --i )
2100 {
2101 if ( gMacDefaultExtensions.Item(i).m_ext == extl )
2102 {
2103 *type = gMacDefaultExtensions.Item(i).m_type ;
2104 *creator = gMacDefaultExtensions.Item(i).m_creator ;
2105 return true ;
2106 }
2107 }
2108 return false ;
2109 }
2110
2111 void wxFileName::MacRegisterDefaultTypeAndCreator( const wxString& ext , wxUint32 type , wxUint32 creator )
2112 {
2113 MacEnsureDefaultExtensionsLoaded() ;
2114 MacDefaultExtensionRecord rec ;
2115 rec.m_type = type ;
2116 rec.m_creator = creator ;
2117 wxStrncpy( rec.m_ext , ext.Lower().c_str() , kMacExtensionMaxLength ) ;
2118 gMacDefaultExtensions.Add( rec ) ;
2119 }
2120 #endif