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