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