]> git.saurik.com Git - wxWidgets.git/blob - src/common/filename.cpp
Factor out text measurement from wxDC and wxWindow into wxTextMeasure.
[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 and
26 MSW unique volume names of the form \\?\Volume{GUID}\fullpath.
27
28 The latter provide a uniform way to access a volume regardless of
29 its current mount point, i.e. you can change a volume's mount
30 point from D: to E:, or even remove it, and still be able to
31 access it through its unique volume name. More on the subject can
32 be found in MSDN's article "Naming a Volume" that is currently at
33 http://msdn.microsoft.com/en-us/library/aa365248(VS.85).aspx.
34
35
36 wxPATH_MAC: Mac OS 8/9 only, not used any longer, absolute file
37 names have the form
38 volume:dir1:...:dirN:filename
39 and the relative file names are either
40 :dir1:...:dirN:filename
41 or just
42 filename
43 (although :filename works as well).
44 Since the volume is just part of the file path, it is not
45 treated like a separate entity as it is done under DOS and
46 VMS, it is just treated as another dir.
47
48 wxPATH_VMS: VMS native format, absolute file names have the form
49 <device>:[dir1.dir2.dir3]file.txt
50 or
51 <device>:[000000.dir1.dir2.dir3]file.txt
52
53 the <device> is the physical device (i.e. disk). 000000 is the
54 root directory on the device which can be omitted.
55
56 Note that VMS uses different separators unlike Unix:
57 : always after the device. If the path does not contain : than
58 the default (the device of the current directory) is assumed.
59 [ start of directory specification
60 . separator between directory and subdirectory
61 ] between directory and file
62 */
63
64 // ============================================================================
65 // declarations
66 // ============================================================================
67
68 // ----------------------------------------------------------------------------
69 // headers
70 // ----------------------------------------------------------------------------
71
72 // For compilers that support precompilation, includes "wx.h".
73 #include "wx/wxprec.h"
74
75 #ifdef __BORLANDC__
76 #pragma hdrstop
77 #endif
78
79 #ifndef WX_PRECOMP
80 #ifdef __WINDOWS__
81 #include "wx/msw/wrapwin.h" // For GetShort/LongPathName
82 #endif
83 #include "wx/dynarray.h"
84 #include "wx/intl.h"
85 #include "wx/log.h"
86 #include "wx/utils.h"
87 #include "wx/crt.h"
88 #endif
89
90 #include "wx/filename.h"
91 #include "wx/private/filename.h"
92 #include "wx/tokenzr.h"
93 #include "wx/config.h" // for wxExpandEnvVars
94 #include "wx/dynlib.h"
95 #include "wx/dir.h"
96
97 #if defined(__WIN32__) && defined(__MINGW32__)
98 #include "wx/msw/gccpriv.h"
99 #endif
100
101 #ifdef __WINDOWS__
102 #include "wx/msw/private.h"
103 #endif
104
105 #if defined(__WXMAC__)
106 #include "wx/osx/private.h" // includes mac headers
107 #endif
108
109 // utime() is POSIX so should normally be available on all Unices
110 #ifdef __UNIX_LIKE__
111 #include <sys/types.h>
112 #include <utime.h>
113 #include <sys/stat.h>
114 #include <unistd.h>
115 #endif
116
117 #ifdef __DJGPP__
118 #include <unistd.h>
119 #endif
120
121 #ifdef __WATCOMC__
122 #include <io.h>
123 #include <sys/utime.h>
124 #include <sys/stat.h>
125 #endif
126
127 #ifdef __VISAGECPP__
128 #ifndef MAX_PATH
129 #define MAX_PATH 256
130 #endif
131 #endif
132
133 #ifdef __EMX__
134 #include <os2.h>
135 #define MAX_PATH _MAX_PATH
136 #endif
137
138 #ifndef S_ISREG
139 #define S_ISREG(mode) ((mode) & S_IFREG)
140 #endif
141 #ifndef S_ISDIR
142 #define S_ISDIR(mode) ((mode) & S_IFDIR)
143 #endif
144
145 #if wxUSE_LONGLONG
146 extern const wxULongLong wxInvalidSize = (unsigned)-1;
147 #endif // wxUSE_LONGLONG
148
149 namespace
150 {
151
152 // ----------------------------------------------------------------------------
153 // private classes
154 // ----------------------------------------------------------------------------
155
156 // small helper class which opens and closes the file - we use it just to get
157 // a file handle for the given file name to pass it to some Win32 API function
158 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
159
160 class wxFileHandle
161 {
162 public:
163 enum OpenMode
164 {
165 ReadAttr,
166 WriteAttr
167 };
168
169 wxFileHandle(const wxString& filename, OpenMode mode, int flags = 0)
170 {
171 // be careful and use FILE_{READ,WRITE}_ATTRIBUTES here instead of the
172 // usual GENERIC_{READ,WRITE} as we don't want the file access time to
173 // be changed when we open it because this class is used for setting
174 // access time (see #10567)
175 m_hFile = ::CreateFile
176 (
177 filename.t_str(), // name
178 mode == ReadAttr ? FILE_READ_ATTRIBUTES // access mask
179 : FILE_WRITE_ATTRIBUTES,
180 FILE_SHARE_READ | // sharing mode
181 FILE_SHARE_WRITE, // (allow everything)
182 NULL, // no secutity attr
183 OPEN_EXISTING, // creation disposition
184 flags, // flags
185 NULL // no template file
186 );
187
188 if ( m_hFile == INVALID_HANDLE_VALUE )
189 {
190 if ( mode == ReadAttr )
191 {
192 wxLogSysError(_("Failed to open '%s' for reading"),
193 filename.c_str());
194 }
195 else
196 {
197 wxLogSysError(_("Failed to open '%s' for writing"),
198 filename.c_str());
199 }
200 }
201 }
202
203 ~wxFileHandle()
204 {
205 if ( m_hFile != INVALID_HANDLE_VALUE )
206 {
207 if ( !::CloseHandle(m_hFile) )
208 {
209 wxLogSysError(_("Failed to close file handle"));
210 }
211 }
212 }
213
214 // return true only if the file could be opened successfully
215 bool IsOk() const { return m_hFile != INVALID_HANDLE_VALUE; }
216
217 // get the handle
218 operator HANDLE() const { return m_hFile; }
219
220 private:
221 HANDLE m_hFile;
222 };
223
224 #endif // __WIN32__
225
226 // ----------------------------------------------------------------------------
227 // private functions
228 // ----------------------------------------------------------------------------
229
230 #if wxUSE_DATETIME && defined(__WIN32__) && !defined(__WXMICROWIN__)
231
232 // convert between wxDateTime and FILETIME which is a 64-bit value representing
233 // the number of 100-nanosecond intervals since January 1, 1601.
234
235 static void ConvertFileTimeToWx(wxDateTime *dt, const FILETIME &ft)
236 {
237 FILETIME ftcopy = ft;
238 FILETIME ftLocal;
239 if ( !::FileTimeToLocalFileTime(&ftcopy, &ftLocal) )
240 {
241 wxLogLastError(wxT("FileTimeToLocalFileTime"));
242 }
243
244 SYSTEMTIME st;
245 if ( !::FileTimeToSystemTime(&ftLocal, &st) )
246 {
247 wxLogLastError(wxT("FileTimeToSystemTime"));
248 }
249
250 dt->Set(st.wDay, wxDateTime::Month(st.wMonth - 1), st.wYear,
251 st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
252 }
253
254 static void ConvertWxToFileTime(FILETIME *ft, const wxDateTime& dt)
255 {
256 SYSTEMTIME st;
257 st.wDay = dt.GetDay();
258 st.wMonth = (WORD)(dt.GetMonth() + 1);
259 st.wYear = (WORD)dt.GetYear();
260 st.wHour = dt.GetHour();
261 st.wMinute = dt.GetMinute();
262 st.wSecond = dt.GetSecond();
263 st.wMilliseconds = dt.GetMillisecond();
264
265 FILETIME ftLocal;
266 if ( !::SystemTimeToFileTime(&st, &ftLocal) )
267 {
268 wxLogLastError(wxT("SystemTimeToFileTime"));
269 }
270
271 if ( !::LocalFileTimeToFileTime(&ftLocal, ft) )
272 {
273 wxLogLastError(wxT("LocalFileTimeToFileTime"));
274 }
275 }
276
277 #endif // wxUSE_DATETIME && __WIN32__
278
279 // return a string with the volume par
280 static wxString wxGetVolumeString(const wxString& volume, wxPathFormat format)
281 {
282 wxString path;
283
284 if ( !volume.empty() )
285 {
286 format = wxFileName::GetFormat(format);
287
288 // Special Windows UNC paths hack, part 2: undo what we did in
289 // SplitPath() and make an UNC path if we have a drive which is not a
290 // single letter (hopefully the network shares can't be one letter only
291 // although I didn't find any authoritative docs on this)
292 if ( format == wxPATH_DOS && volume.length() > 1 )
293 {
294 // We also have to check for Windows unique volume names here and
295 // return it with '\\?\' prepended to it
296 if ( wxFileName::IsMSWUniqueVolumeNamePath("\\\\?\\" + volume + "\\",
297 format) )
298 {
299 path << "\\\\?\\" << volume;
300 }
301 else
302 {
303 // it must be a UNC path
304 path << wxFILE_SEP_PATH_DOS << wxFILE_SEP_PATH_DOS << volume;
305 }
306 }
307 else if ( format == wxPATH_DOS || format == wxPATH_VMS )
308 {
309 path << volume << wxFileName::GetVolumeSeparator(format);
310 }
311 // else ignore
312 }
313
314 return path;
315 }
316
317 // return true if the character is a DOS path separator i.e. either a slash or
318 // a backslash
319 inline bool IsDOSPathSep(wxUniChar ch)
320 {
321 return ch == wxFILE_SEP_PATH_DOS || ch == wxFILE_SEP_PATH_UNIX;
322 }
323
324 // return true if the format used is the DOS/Windows one and the string looks
325 // like a UNC path
326 static bool IsUNCPath(const wxString& path, wxPathFormat format)
327 {
328 return format == wxPATH_DOS &&
329 path.length() >= 4 && // "\\a" can't be a UNC path
330 IsDOSPathSep(path[0u]) &&
331 IsDOSPathSep(path[1u]) &&
332 !IsDOSPathSep(path[2u]);
333 }
334
335 #ifndef __WIN32__
336
337 // Under Unix-ish systems (basically everything except Windows) we may work
338 // either with the file itself or its target in case it's a symbolic link, as
339 // determined by wxFileName::ShouldFollowLink(). StatAny() can be used to stat
340 // the appropriate file with an extra twist that it also works (by following
341 // the symlink by default) when there is no wxFileName object at all, as is the
342 // case in static methods.
343
344 // Private implementation, don't call directly, use one of the overloads below.
345 bool DoStatAny(wxStructStat& st, wxString path, const wxFileName* fn)
346 {
347 // We need to remove any trailing slashes from the path because they could
348 // interfere with the symlink following decision: even if we use lstat(),
349 // it would still follow the symlink if we pass it a path with a slash at
350 // the end because the symlink resolution would happen while following the
351 // path and not for the last path element itself.
352
353 while ( wxEndsWithPathSeparator(path) )
354 path.RemoveLast();
355
356 int ret = !fn || fn->ShouldFollowLink() ? wxStat(path, &st)
357 : wxLstat(path, &st);
358 return ret == 0;
359 }
360
361 // Overloads to use for a case when we don't have wxFileName object and when we
362 // do have one.
363 inline
364 bool StatAny(wxStructStat& st, const wxString& path)
365 {
366 return DoStatAny(st, path, NULL);
367 }
368
369 inline
370 bool StatAny(wxStructStat& st, const wxFileName& fn)
371 {
372 return DoStatAny(st, fn.GetFullPath(), &fn);
373 }
374
375 #endif // !__WIN32__
376
377 // ----------------------------------------------------------------------------
378 // private constants
379 // ----------------------------------------------------------------------------
380
381 // length of \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ string
382 static const size_t wxMSWUniqueVolumePrefixLength = 49;
383
384 } // anonymous namespace
385
386 // ============================================================================
387 // implementation
388 // ============================================================================
389
390 // ----------------------------------------------------------------------------
391 // wxFileName construction
392 // ----------------------------------------------------------------------------
393
394 void wxFileName::Assign( const wxFileName &filepath )
395 {
396 m_volume = filepath.GetVolume();
397 m_dirs = filepath.GetDirs();
398 m_name = filepath.GetName();
399 m_ext = filepath.GetExt();
400 m_relative = filepath.m_relative;
401 m_hasExt = filepath.m_hasExt;
402 m_dontFollowLinks = filepath.m_dontFollowLinks;
403 }
404
405 void wxFileName::Assign(const wxString& volume,
406 const wxString& path,
407 const wxString& name,
408 const wxString& ext,
409 bool hasExt,
410 wxPathFormat format)
411 {
412 // we should ignore paths which look like UNC shares because we already
413 // have the volume here and the UNC notation (\\server\path) is only valid
414 // for paths which don't start with a volume, so prevent SetPath() from
415 // recognizing "\\foo\bar" in "c:\\foo\bar" as an UNC path
416 //
417 // note also that this is a rather ugly way to do what we want (passing
418 // some kind of flag telling to ignore UNC paths to SetPath() would be
419 // better) but this is the safest thing to do to avoid breaking backwards
420 // compatibility in 2.8
421 if ( IsUNCPath(path, format) )
422 {
423 // remove one of the 2 leading backslashes to ensure that it's not
424 // recognized as an UNC path by SetPath()
425 wxString pathNonUNC(path, 1, wxString::npos);
426 SetPath(pathNonUNC, format);
427 }
428 else // no UNC complications
429 {
430 SetPath(path, format);
431 }
432
433 m_volume = volume;
434 m_ext = ext;
435 m_name = name;
436
437 m_hasExt = hasExt;
438 }
439
440 void wxFileName::SetPath( const wxString& pathOrig, wxPathFormat format )
441 {
442 m_dirs.Clear();
443
444 if ( pathOrig.empty() )
445 {
446 // no path at all
447 m_relative = true;
448
449 return;
450 }
451
452 format = GetFormat( format );
453
454 // 0) deal with possible volume part first
455 wxString volume,
456 path;
457 SplitVolume(pathOrig, &volume, &path, format);
458 if ( !volume.empty() )
459 {
460 m_relative = false;
461
462 SetVolume(volume);
463 }
464
465 // 1) Determine if the path is relative or absolute.
466
467 if ( path.empty() )
468 {
469 // we had only the volume
470 return;
471 }
472
473 wxChar leadingChar = path[0u];
474
475 switch (format)
476 {
477 case wxPATH_MAC:
478 m_relative = leadingChar == wxT(':');
479
480 // We then remove a leading ":". The reason is in our
481 // storage form for relative paths:
482 // ":dir:file.txt" actually means "./dir/file.txt" in
483 // DOS notation and should get stored as
484 // (relative) (dir) (file.txt)
485 // "::dir:file.txt" actually means "../dir/file.txt"
486 // stored as (relative) (..) (dir) (file.txt)
487 // This is important only for the Mac as an empty dir
488 // actually means <UP>, whereas under DOS, double
489 // slashes can be ignored: "\\\\" is the same as "\\".
490 if (m_relative)
491 path.erase( 0, 1 );
492 break;
493
494 case wxPATH_VMS:
495 // TODO: what is the relative path format here?
496 m_relative = false;
497 break;
498
499 default:
500 wxFAIL_MSG( wxT("Unknown path format") );
501 // !! Fall through !!
502
503 case wxPATH_UNIX:
504 m_relative = leadingChar != wxT('/');
505 break;
506
507 case wxPATH_DOS:
508 m_relative = !IsPathSeparator(leadingChar, format);
509 break;
510
511 }
512
513 // 2) Break up the path into its members. If the original path
514 // was just "/" or "\\", m_dirs will be empty. We know from
515 // the m_relative field, if this means "nothing" or "root dir".
516
517 wxStringTokenizer tn( path, GetPathSeparators(format) );
518
519 while ( tn.HasMoreTokens() )
520 {
521 wxString token = tn.GetNextToken();
522
523 // Remove empty token under DOS and Unix, interpret them
524 // as .. under Mac.
525 if (token.empty())
526 {
527 if (format == wxPATH_MAC)
528 m_dirs.Add( wxT("..") );
529 // else ignore
530 }
531 else
532 {
533 m_dirs.Add( token );
534 }
535 }
536 }
537
538 void wxFileName::Assign(const wxString& fullpath,
539 wxPathFormat format)
540 {
541 wxString volume, path, name, ext;
542 bool hasExt;
543 SplitPath(fullpath, &volume, &path, &name, &ext, &hasExt, format);
544
545 Assign(volume, path, name, ext, hasExt, format);
546 }
547
548 void wxFileName::Assign(const wxString& fullpathOrig,
549 const wxString& fullname,
550 wxPathFormat format)
551 {
552 // always recognize fullpath as directory, even if it doesn't end with a
553 // slash
554 wxString fullpath = fullpathOrig;
555 if ( !fullpath.empty() && !wxEndsWithPathSeparator(fullpath) )
556 {
557 fullpath += GetPathSeparator(format);
558 }
559
560 wxString volume, path, name, ext;
561 bool hasExt;
562
563 // do some consistency checks: the name should be really just the filename
564 // and the path should be really just a path
565 wxString volDummy, pathDummy, nameDummy, extDummy;
566
567 SplitPath(fullname, &volDummy, &pathDummy, &name, &ext, &hasExt, format);
568
569 wxASSERT_MSG( volDummy.empty() && pathDummy.empty(),
570 wxT("the file name shouldn't contain the path") );
571
572 SplitPath(fullpath, &volume, &path, &nameDummy, &extDummy, format);
573
574 #ifndef __VMS
575 // This test makes no sense on an OpenVMS system.
576 wxASSERT_MSG( nameDummy.empty() && extDummy.empty(),
577 wxT("the path shouldn't contain file name nor extension") );
578 #endif
579 Assign(volume, path, name, ext, hasExt, format);
580 }
581
582 void wxFileName::Assign(const wxString& pathOrig,
583 const wxString& name,
584 const wxString& ext,
585 wxPathFormat format)
586 {
587 wxString volume,
588 path;
589 SplitVolume(pathOrig, &volume, &path, format);
590
591 Assign(volume, path, name, ext, format);
592 }
593
594 void wxFileName::AssignDir(const wxString& dir, wxPathFormat format)
595 {
596 Assign(dir, wxEmptyString, format);
597 }
598
599 void wxFileName::Clear()
600 {
601 m_dirs.Clear();
602
603 m_volume =
604 m_name =
605 m_ext = wxEmptyString;
606
607 // we don't have any absolute path for now
608 m_relative = true;
609
610 // nor any extension
611 m_hasExt = false;
612
613 // follow symlinks by default
614 m_dontFollowLinks = false;
615 }
616
617 /* static */
618 wxFileName wxFileName::FileName(const wxString& file, wxPathFormat format)
619 {
620 return wxFileName(file, format);
621 }
622
623 /* static */
624 wxFileName wxFileName::DirName(const wxString& dir, wxPathFormat format)
625 {
626 wxFileName fn;
627 fn.AssignDir(dir, format);
628 return fn;
629 }
630
631 // ----------------------------------------------------------------------------
632 // existence tests
633 // ----------------------------------------------------------------------------
634
635 namespace
636 {
637
638 // Flags for wxFileSystemObjectExists() asking it to check for:
639 enum
640 {
641 wxFileSystemObject_File = 1, // file existence
642 wxFileSystemObject_Dir = 2, // directory existence
643 wxFileSystemObject_Other = 4, // existence of something else, e.g.
644 // device, socket, FIFO under Unix
645 wxFileSystemObject_Any = 7 // existence of anything at all
646 };
647
648 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
649
650 void RemoveTrailingSeparatorsFromPath(wxString& strPath)
651 {
652 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
653 // so remove all trailing backslashes from the path - but don't do this for
654 // the paths "d:\" (which are different from "d:"), for just "\" or for
655 // windows unique volume names ("\\?\Volume{GUID}\")
656 while ( wxEndsWithPathSeparator( strPath ) )
657 {
658 size_t len = strPath.length();
659 if ( len == 1 || (len == 3 && strPath[len - 2] == wxT(':')) ||
660 (len == wxMSWUniqueVolumePrefixLength &&
661 wxFileName::IsMSWUniqueVolumeNamePath(strPath)))
662 {
663 break;
664 }
665
666 strPath.Truncate(len - 1);
667 }
668 }
669
670 #endif // __WINDOWS__ || __OS2__
671
672 bool
673 wxFileSystemObjectExists(const wxString& path, int flags,
674 const wxFileName* fn = NULL)
675 {
676 wxUnusedVar(fn); // It's only used under Unix
677
678 // Should the existence of file/directory with this name be accepted, i.e.
679 // result in the true return value from this function?
680 const bool acceptFile = (flags & wxFileSystemObject_File) != 0;
681 const bool acceptDir = (flags & wxFileSystemObject_Dir) != 0;
682
683 wxString strPath(path);
684
685 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
686 if ( acceptDir )
687 {
688 // Ensure that the path doesn't have any trailing separators when
689 // checking for directories.
690 RemoveTrailingSeparatorsFromPath(strPath);
691 }
692
693 // we must use GetFileAttributes() instead of the ANSI C functions because
694 // it can cope with network (UNC) paths unlike them
695 DWORD ret = ::GetFileAttributes(strPath.t_str());
696
697 if ( ret == INVALID_FILE_ATTRIBUTES )
698 return false;
699
700 if ( ret & FILE_ATTRIBUTE_DIRECTORY )
701 return acceptDir;
702
703 // Anything else must be a file (perhaps we should check for
704 // FILE_ATTRIBUTE_REPARSE_POINT?)
705 return acceptFile;
706 #elif defined(__OS2__)
707 if ( acceptDir )
708 {
709 // OS/2 can't handle "d:", it wants either "d:\" or "d:."
710 if (strPath.length() == 2 && strPath[1u] == wxT(':'))
711 strPath << wxT('.');
712 }
713
714 FILESTATUS3 Info = {{0}};
715 APIRET rc = ::DosQueryPathInfo((PSZ)(WXSTRINGCAST strPath), FIL_STANDARD,
716 (void*) &Info, sizeof(FILESTATUS3));
717
718 if ( rc == NO_ERROR )
719 {
720 if ( Info.attrFile & FILE_DIRECTORY )
721 return acceptDir;
722 else
723 return acceptFile;
724 }
725
726 // We consider that the path must exist if we get a sharing violation for
727 // it but we don't know what is it in this case.
728 if ( rc == ERROR_SHARING_VIOLATION )
729 return flags & wxFileSystemObject_Other;
730
731 // Any other error (usually ERROR_PATH_NOT_FOUND), means there is nothing
732 // there.
733 return false;
734 #else // Non-MSW, non-OS/2
735 wxStructStat st;
736 if ( !DoStatAny(st, strPath, fn) )
737 return false;
738
739 if ( S_ISREG(st.st_mode) )
740 return acceptFile;
741 if ( S_ISDIR(st.st_mode) )
742 return acceptDir;
743
744 return flags & wxFileSystemObject_Other;
745 #endif // Platforms
746 }
747
748 } // anonymous namespace
749
750 bool wxFileName::FileExists() const
751 {
752 return wxFileSystemObjectExists(GetFullPath(), wxFileSystemObject_File, this);
753 }
754
755 /* static */
756 bool wxFileName::FileExists( const wxString &filePath )
757 {
758 return wxFileSystemObjectExists(filePath, wxFileSystemObject_File);
759 }
760
761 bool wxFileName::DirExists() const
762 {
763 return wxFileSystemObjectExists(GetPath(), wxFileSystemObject_Dir, this);
764 }
765
766 /* static */
767 bool wxFileName::DirExists( const wxString &dirPath )
768 {
769 return wxFileSystemObjectExists(dirPath, wxFileSystemObject_Dir);
770 }
771
772 bool wxFileName::Exists() const
773 {
774 return wxFileSystemObjectExists(GetFullPath(), wxFileSystemObject_Any, this);
775 }
776
777 /* static */
778 bool wxFileName::Exists(const wxString& path)
779 {
780 return wxFileSystemObjectExists(path, wxFileSystemObject_Any);
781 }
782
783 // ----------------------------------------------------------------------------
784 // CWD and HOME stuff
785 // ----------------------------------------------------------------------------
786
787 void wxFileName::AssignCwd(const wxString& volume)
788 {
789 AssignDir(wxFileName::GetCwd(volume));
790 }
791
792 /* static */
793 wxString wxFileName::GetCwd(const wxString& volume)
794 {
795 // if we have the volume, we must get the current directory on this drive
796 // and to do this we have to chdir to this volume - at least under Windows,
797 // I don't know how to get the current drive on another volume elsewhere
798 // (TODO)
799 wxString cwdOld;
800 if ( !volume.empty() )
801 {
802 cwdOld = wxGetCwd();
803 SetCwd(volume + GetVolumeSeparator());
804 }
805
806 wxString cwd = ::wxGetCwd();
807
808 if ( !volume.empty() )
809 {
810 SetCwd(cwdOld);
811 }
812
813 return cwd;
814 }
815
816 bool wxFileName::SetCwd() const
817 {
818 return wxFileName::SetCwd( GetPath() );
819 }
820
821 bool wxFileName::SetCwd( const wxString &cwd )
822 {
823 return ::wxSetWorkingDirectory( cwd );
824 }
825
826 void wxFileName::AssignHomeDir()
827 {
828 AssignDir(wxFileName::GetHomeDir());
829 }
830
831 wxString wxFileName::GetHomeDir()
832 {
833 return ::wxGetHomeDir();
834 }
835
836
837 // ----------------------------------------------------------------------------
838 // CreateTempFileName
839 // ----------------------------------------------------------------------------
840
841 #if wxUSE_FILE || wxUSE_FFILE
842
843
844 #if !defined wx_fdopen && defined HAVE_FDOPEN
845 #define wx_fdopen fdopen
846 #endif
847
848 // NB: GetTempFileName() under Windows creates the file, so using
849 // O_EXCL there would fail
850 #ifdef __WINDOWS__
851 #define wxOPEN_EXCL 0
852 #else
853 #define wxOPEN_EXCL O_EXCL
854 #endif
855
856
857 #ifdef wxOpenOSFHandle
858 #define WX_HAVE_DELETE_ON_CLOSE
859 // On Windows create a file with the FILE_FLAGS_DELETE_ON_CLOSE flags.
860 //
861 static int wxOpenWithDeleteOnClose(const wxString& filename)
862 {
863 DWORD access = GENERIC_READ | GENERIC_WRITE;
864
865 DWORD disposition = OPEN_ALWAYS;
866
867 DWORD attributes = FILE_ATTRIBUTE_TEMPORARY |
868 FILE_FLAG_DELETE_ON_CLOSE;
869
870 HANDLE h = ::CreateFile(filename.t_str(), access, 0, NULL,
871 disposition, attributes, NULL);
872
873 return wxOpenOSFHandle(h, wxO_BINARY);
874 }
875 #endif // wxOpenOSFHandle
876
877
878 // Helper to open the file
879 //
880 static int wxTempOpen(const wxString& path, bool *deleteOnClose)
881 {
882 #ifdef WX_HAVE_DELETE_ON_CLOSE
883 if (*deleteOnClose)
884 return wxOpenWithDeleteOnClose(path);
885 #endif
886
887 *deleteOnClose = false;
888
889 return wxOpen(path, wxO_BINARY | O_RDWR | O_CREAT | wxOPEN_EXCL, 0600);
890 }
891
892
893 #if wxUSE_FFILE
894 // Helper to open the file and attach it to the wxFFile
895 //
896 static bool wxTempOpen(wxFFile *file, const wxString& path, bool *deleteOnClose)
897 {
898 #ifndef wx_fdopen
899 *deleteOnClose = false;
900 return file->Open(path, wxT("w+b"));
901 #else // wx_fdopen
902 int fd = wxTempOpen(path, deleteOnClose);
903 if (fd == -1)
904 return false;
905 file->Attach(wx_fdopen(fd, "w+b"), path);
906 return file->IsOpened();
907 #endif // wx_fdopen
908 }
909 #endif // wxUSE_FFILE
910
911
912 #if !wxUSE_FILE
913 #define WXFILEARGS(x, y) y
914 #elif !wxUSE_FFILE
915 #define WXFILEARGS(x, y) x
916 #else
917 #define WXFILEARGS(x, y) x, y
918 #endif
919
920
921 // Implementation of wxFileName::CreateTempFileName().
922 //
923 static wxString wxCreateTempImpl(
924 const wxString& prefix,
925 WXFILEARGS(wxFile *fileTemp, wxFFile *ffileTemp),
926 bool *deleteOnClose = NULL)
927 {
928 #if wxUSE_FILE && wxUSE_FFILE
929 wxASSERT(fileTemp == NULL || ffileTemp == NULL);
930 #endif
931 wxString path, dir, name;
932 bool wantDeleteOnClose = false;
933
934 if (deleteOnClose)
935 {
936 // set the result to false initially
937 wantDeleteOnClose = *deleteOnClose;
938 *deleteOnClose = false;
939 }
940 else
941 {
942 // easier if it alwasys points to something
943 deleteOnClose = &wantDeleteOnClose;
944 }
945
946 // use the directory specified by the prefix
947 wxFileName::SplitPath(prefix, &dir, &name, NULL /* extension */);
948
949 if (dir.empty())
950 {
951 dir = wxFileName::GetTempDir();
952 }
953
954 #if defined(__WXWINCE__)
955 path = dir + wxT("\\") + name;
956 int i = 1;
957 while (wxFileName::FileExists(path))
958 {
959 path = dir + wxT("\\") + name ;
960 path << i;
961 i ++;
962 }
963
964 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
965 if (!::GetTempFileName(dir.t_str(), name.t_str(), 0,
966 wxStringBuffer(path, MAX_PATH + 1)))
967 {
968 wxLogLastError(wxT("GetTempFileName"));
969
970 path.clear();
971 }
972
973 #else // !Windows
974 path = dir;
975
976 if ( !wxEndsWithPathSeparator(dir) &&
977 (name.empty() || !wxIsPathSeparator(name[0u])) )
978 {
979 path += wxFILE_SEP_PATH;
980 }
981
982 path += name;
983
984 #if defined(HAVE_MKSTEMP)
985 // scratch space for mkstemp()
986 path += wxT("XXXXXX");
987
988 // we need to copy the path to the buffer in which mkstemp() can modify it
989 wxCharBuffer buf(path.fn_str());
990
991 // cast is safe because the string length doesn't change
992 int fdTemp = mkstemp( (char*)(const char*) buf );
993 if ( fdTemp == -1 )
994 {
995 // this might be not necessary as mkstemp() on most systems should have
996 // already done it but it doesn't hurt neither...
997 path.clear();
998 }
999 else // mkstemp() succeeded
1000 {
1001 path = wxConvFile.cMB2WX( (const char*) buf );
1002
1003 #if wxUSE_FILE
1004 // avoid leaking the fd
1005 if ( fileTemp )
1006 {
1007 fileTemp->Attach(fdTemp);
1008 }
1009 else
1010 #endif
1011
1012 #if wxUSE_FFILE
1013 if ( ffileTemp )
1014 {
1015 #ifdef wx_fdopen
1016 ffileTemp->Attach(wx_fdopen(fdTemp, "r+b"), path);
1017 #else
1018 ffileTemp->Open(path, wxT("r+b"));
1019 close(fdTemp);
1020 #endif
1021 }
1022 else
1023 #endif
1024
1025 {
1026 close(fdTemp);
1027 }
1028 }
1029 #else // !HAVE_MKSTEMP
1030
1031 #ifdef HAVE_MKTEMP
1032 // same as above
1033 path += wxT("XXXXXX");
1034
1035 wxCharBuffer buf = wxConvFile.cWX2MB( path );
1036 if ( !mktemp( (char*)(const char*) buf ) )
1037 {
1038 path.clear();
1039 }
1040 else
1041 {
1042 path = wxConvFile.cMB2WX( (const char*) buf );
1043 }
1044 #else // !HAVE_MKTEMP (includes __DOS__)
1045 // generate the unique file name ourselves
1046 #if !defined(__DOS__)
1047 path << (unsigned int)getpid();
1048 #endif
1049
1050 wxString pathTry;
1051
1052 static const size_t numTries = 1000;
1053 for ( size_t n = 0; n < numTries; n++ )
1054 {
1055 // 3 hex digits is enough for numTries == 1000 < 4096
1056 pathTry = path + wxString::Format(wxT("%.03x"), (unsigned int) n);
1057 if ( !wxFileName::FileExists(pathTry) )
1058 {
1059 break;
1060 }
1061
1062 pathTry.clear();
1063 }
1064
1065 path = pathTry;
1066 #endif // HAVE_MKTEMP/!HAVE_MKTEMP
1067
1068 #endif // HAVE_MKSTEMP/!HAVE_MKSTEMP
1069
1070 #endif // Windows/!Windows
1071
1072 if ( path.empty() )
1073 {
1074 wxLogSysError(_("Failed to create a temporary file name"));
1075 }
1076 else
1077 {
1078 bool ok = true;
1079
1080 // open the file - of course, there is a race condition here, this is
1081 // why we always prefer using mkstemp()...
1082 #if wxUSE_FILE
1083 if ( fileTemp && !fileTemp->IsOpened() )
1084 {
1085 *deleteOnClose = wantDeleteOnClose;
1086 int fd = wxTempOpen(path, deleteOnClose);
1087 if (fd != -1)
1088 fileTemp->Attach(fd);
1089 else
1090 ok = false;
1091 }
1092 #endif
1093
1094 #if wxUSE_FFILE
1095 if ( ffileTemp && !ffileTemp->IsOpened() )
1096 {
1097 *deleteOnClose = wantDeleteOnClose;
1098 ok = wxTempOpen(ffileTemp, path, deleteOnClose);
1099 }
1100 #endif
1101
1102 if ( !ok )
1103 {
1104 // FIXME: If !ok here should we loop and try again with another
1105 // file name? That is the standard recourse if open(O_EXCL)
1106 // fails, though of course it should be protected against
1107 // possible infinite looping too.
1108
1109 wxLogError(_("Failed to open temporary file."));
1110
1111 path.clear();
1112 }
1113 }
1114
1115 return path;
1116 }
1117
1118
1119 static bool wxCreateTempImpl(
1120 const wxString& prefix,
1121 WXFILEARGS(wxFile *fileTemp, wxFFile *ffileTemp),
1122 wxString *name)
1123 {
1124 bool deleteOnClose = true;
1125
1126 *name = wxCreateTempImpl(prefix,
1127 WXFILEARGS(fileTemp, ffileTemp),
1128 &deleteOnClose);
1129
1130 bool ok = !name->empty();
1131
1132 if (deleteOnClose)
1133 name->clear();
1134 #ifdef __UNIX__
1135 else if (ok && wxRemoveFile(*name))
1136 name->clear();
1137 #endif
1138
1139 return ok;
1140 }
1141
1142
1143 static void wxAssignTempImpl(
1144 wxFileName *fn,
1145 const wxString& prefix,
1146 WXFILEARGS(wxFile *fileTemp, wxFFile *ffileTemp))
1147 {
1148 wxString tempname;
1149 tempname = wxCreateTempImpl(prefix, WXFILEARGS(fileTemp, ffileTemp));
1150
1151 if ( tempname.empty() )
1152 {
1153 // error, failed to get temp file name
1154 fn->Clear();
1155 }
1156 else // ok
1157 {
1158 fn->Assign(tempname);
1159 }
1160 }
1161
1162
1163 void wxFileName::AssignTempFileName(const wxString& prefix)
1164 {
1165 wxAssignTempImpl(this, prefix, WXFILEARGS(NULL, NULL));
1166 }
1167
1168 /* static */
1169 wxString wxFileName::CreateTempFileName(const wxString& prefix)
1170 {
1171 return wxCreateTempImpl(prefix, WXFILEARGS(NULL, NULL));
1172 }
1173
1174 #endif // wxUSE_FILE || wxUSE_FFILE
1175
1176
1177 #if wxUSE_FILE
1178
1179 wxString wxCreateTempFileName(const wxString& prefix,
1180 wxFile *fileTemp,
1181 bool *deleteOnClose)
1182 {
1183 return wxCreateTempImpl(prefix, WXFILEARGS(fileTemp, NULL), deleteOnClose);
1184 }
1185
1186 bool wxCreateTempFile(const wxString& prefix,
1187 wxFile *fileTemp,
1188 wxString *name)
1189 {
1190 return wxCreateTempImpl(prefix, WXFILEARGS(fileTemp, NULL), name);
1191 }
1192
1193 void wxFileName::AssignTempFileName(const wxString& prefix, wxFile *fileTemp)
1194 {
1195 wxAssignTempImpl(this, prefix, WXFILEARGS(fileTemp, NULL));
1196 }
1197
1198 /* static */
1199 wxString
1200 wxFileName::CreateTempFileName(const wxString& prefix, wxFile *fileTemp)
1201 {
1202 return wxCreateTempFileName(prefix, fileTemp);
1203 }
1204
1205 #endif // wxUSE_FILE
1206
1207
1208 #if wxUSE_FFILE
1209
1210 wxString wxCreateTempFileName(const wxString& prefix,
1211 wxFFile *fileTemp,
1212 bool *deleteOnClose)
1213 {
1214 return wxCreateTempImpl(prefix, WXFILEARGS(NULL, fileTemp), deleteOnClose);
1215 }
1216
1217 bool wxCreateTempFile(const wxString& prefix,
1218 wxFFile *fileTemp,
1219 wxString *name)
1220 {
1221 return wxCreateTempImpl(prefix, WXFILEARGS(NULL, fileTemp), name);
1222
1223 }
1224
1225 void wxFileName::AssignTempFileName(const wxString& prefix, wxFFile *fileTemp)
1226 {
1227 wxAssignTempImpl(this, prefix, WXFILEARGS(NULL, fileTemp));
1228 }
1229
1230 /* static */
1231 wxString
1232 wxFileName::CreateTempFileName(const wxString& prefix, wxFFile *fileTemp)
1233 {
1234 return wxCreateTempFileName(prefix, fileTemp);
1235 }
1236
1237 #endif // wxUSE_FFILE
1238
1239
1240 // ----------------------------------------------------------------------------
1241 // directory operations
1242 // ----------------------------------------------------------------------------
1243
1244 // helper of GetTempDir(): check if the given directory exists and return it if
1245 // it does or an empty string otherwise
1246 namespace
1247 {
1248
1249 wxString CheckIfDirExists(const wxString& dir)
1250 {
1251 return wxFileName::DirExists(dir) ? dir : wxString();
1252 }
1253
1254 } // anonymous namespace
1255
1256 wxString wxFileName::GetTempDir()
1257 {
1258 // first try getting it from environment: this allows overriding the values
1259 // used by default if the user wants to create temporary files in another
1260 // directory
1261 wxString dir = CheckIfDirExists(wxGetenv("TMPDIR"));
1262 if ( dir.empty() )
1263 {
1264 dir = CheckIfDirExists(wxGetenv("TMP"));
1265 if ( dir.empty() )
1266 dir = CheckIfDirExists(wxGetenv("TEMP"));
1267 }
1268
1269 // if no environment variables are set, use the system default
1270 if ( dir.empty() )
1271 {
1272 #if defined(__WXWINCE__)
1273 dir = CheckIfDirExists(wxT("\\temp"));
1274 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1275 if ( !::GetTempPath(MAX_PATH, wxStringBuffer(dir, MAX_PATH + 1)) )
1276 {
1277 wxLogLastError(wxT("GetTempPath"));
1278 }
1279 #elif defined(__WXMAC__) && wxOSX_USE_CARBON
1280 dir = wxMacFindFolderNoSeparator(short(kOnSystemDisk), kTemporaryFolderType, kCreateFolder);
1281 #endif // systems with native way
1282 }
1283 else // we got directory from an environment variable
1284 {
1285 // remove any trailing path separators, we don't want to ever return
1286 // them from this function for consistency
1287 const size_t lastNonSep = dir.find_last_not_of(GetPathSeparators());
1288 if ( lastNonSep == wxString::npos )
1289 {
1290 // the string consists entirely of separators, leave only one
1291 dir = GetPathSeparator();
1292 }
1293 else
1294 {
1295 dir.erase(lastNonSep + 1);
1296 }
1297 }
1298
1299 // fall back to hard coded value
1300 if ( dir.empty() )
1301 {
1302 #ifdef __UNIX_LIKE__
1303 dir = CheckIfDirExists("/tmp");
1304 if ( dir.empty() )
1305 #endif // __UNIX_LIKE__
1306 dir = ".";
1307 }
1308
1309 return dir;
1310 }
1311
1312 bool wxFileName::Mkdir( int perm, int flags ) const
1313 {
1314 return wxFileName::Mkdir(GetPath(), perm, flags);
1315 }
1316
1317 bool wxFileName::Mkdir( const wxString& dir, int perm, int flags )
1318 {
1319 if ( flags & wxPATH_MKDIR_FULL )
1320 {
1321 // split the path in components
1322 wxFileName filename;
1323 filename.AssignDir(dir);
1324
1325 wxString currPath;
1326 if ( filename.HasVolume())
1327 {
1328 currPath << wxGetVolumeString(filename.GetVolume(), wxPATH_NATIVE);
1329 }
1330
1331 wxArrayString dirs = filename.GetDirs();
1332 size_t count = dirs.GetCount();
1333 for ( size_t i = 0; i < count; i++ )
1334 {
1335 if ( i > 0 || filename.IsAbsolute() )
1336 currPath += wxFILE_SEP_PATH;
1337 currPath += dirs[i];
1338
1339 if (!DirExists(currPath))
1340 {
1341 if (!wxMkdir(currPath, perm))
1342 {
1343 // no need to try creating further directories
1344 return false;
1345 }
1346 }
1347 }
1348
1349 return true;
1350
1351 }
1352
1353 return ::wxMkdir( dir, perm );
1354 }
1355
1356 bool wxFileName::Rmdir(int flags) const
1357 {
1358 return wxFileName::Rmdir( GetPath(), flags );
1359 }
1360
1361 bool wxFileName::Rmdir(const wxString& dir, int flags)
1362 {
1363 #ifdef __WINDOWS__
1364 if ( flags & wxPATH_RMDIR_RECURSIVE )
1365 {
1366 // SHFileOperation needs double null termination string
1367 // but without separator at the end of the path
1368 wxString path(dir);
1369 if ( path.Last() == wxFILE_SEP_PATH )
1370 path.RemoveLast();
1371 path += wxT('\0');
1372
1373 SHFILEOPSTRUCT fileop;
1374 wxZeroMemory(fileop);
1375 fileop.wFunc = FO_DELETE;
1376 fileop.pFrom = path.t_str();
1377 fileop.fFlags = FOF_SILENT | FOF_NOCONFIRMATION;
1378 #ifndef __WXWINCE__
1379 // FOF_NOERRORUI is not defined in WinCE
1380 fileop.fFlags |= FOF_NOERRORUI;
1381 #endif
1382
1383 int ret = SHFileOperation(&fileop);
1384 if ( ret != 0 )
1385 {
1386 // SHFileOperation may return non-Win32 error codes, so the error
1387 // message can be incorrect
1388 wxLogApiError(wxT("SHFileOperation"), ret);
1389 return false;
1390 }
1391
1392 return true;
1393 }
1394 else if ( flags & wxPATH_RMDIR_FULL )
1395 #else // !__WINDOWS__
1396 if ( flags != 0 ) // wxPATH_RMDIR_FULL or wxPATH_RMDIR_RECURSIVE
1397 #endif // !__WINDOWS__
1398 {
1399 wxString path(dir);
1400 if ( path.Last() != wxFILE_SEP_PATH )
1401 path += wxFILE_SEP_PATH;
1402
1403 wxDir d(path);
1404
1405 if ( !d.IsOpened() )
1406 return false;
1407
1408 wxString filename;
1409
1410 // first delete all subdirectories
1411 bool cont = d.GetFirst(&filename, "", wxDIR_DIRS | wxDIR_HIDDEN);
1412 while ( cont )
1413 {
1414 wxFileName::Rmdir(path + filename, flags);
1415 cont = d.GetNext(&filename);
1416 }
1417
1418 #ifndef __WINDOWS__
1419 if ( flags & wxPATH_RMDIR_RECURSIVE )
1420 {
1421 // delete all files too
1422 cont = d.GetFirst(&filename, "", wxDIR_FILES | wxDIR_HIDDEN);
1423 while ( cont )
1424 {
1425 ::wxRemoveFile(path + filename);
1426 cont = d.GetNext(&filename);
1427 }
1428 }
1429 #endif // !__WINDOWS__
1430 }
1431
1432 return ::wxRmdir(dir);
1433 }
1434
1435 // ----------------------------------------------------------------------------
1436 // path normalization
1437 // ----------------------------------------------------------------------------
1438
1439 bool wxFileName::Normalize(int flags,
1440 const wxString& cwd,
1441 wxPathFormat format)
1442 {
1443 // deal with env vars renaming first as this may seriously change the path
1444 if ( flags & wxPATH_NORM_ENV_VARS )
1445 {
1446 wxString pathOrig = GetFullPath(format);
1447 wxString path = wxExpandEnvVars(pathOrig);
1448 if ( path != pathOrig )
1449 {
1450 Assign(path);
1451 }
1452 }
1453
1454 // the existing path components
1455 wxArrayString dirs = GetDirs();
1456
1457 // the path to prepend in front to make the path absolute
1458 wxFileName curDir;
1459
1460 format = GetFormat(format);
1461
1462 // set up the directory to use for making the path absolute later
1463 if ( (flags & wxPATH_NORM_ABSOLUTE) && !IsAbsolute(format) )
1464 {
1465 if ( cwd.empty() )
1466 {
1467 curDir.AssignCwd(GetVolume());
1468 }
1469 else // cwd provided
1470 {
1471 curDir.AssignDir(cwd);
1472 }
1473 }
1474
1475 // handle ~ stuff under Unix only
1476 if ( (format == wxPATH_UNIX) && (flags & wxPATH_NORM_TILDE) && m_relative )
1477 {
1478 if ( !dirs.IsEmpty() )
1479 {
1480 wxString dir = dirs[0u];
1481 if ( !dir.empty() && dir[0u] == wxT('~') )
1482 {
1483 // to make the path absolute use the home directory
1484 curDir.AssignDir(wxGetUserHome(dir.c_str() + 1));
1485 dirs.RemoveAt(0u);
1486 }
1487 }
1488 }
1489
1490 // transform relative path into abs one
1491 if ( curDir.IsOk() )
1492 {
1493 // this path may be relative because it doesn't have the volume name
1494 // and still have m_relative=true; in this case we shouldn't modify
1495 // our directory components but just set the current volume
1496 if ( !HasVolume() && curDir.HasVolume() )
1497 {
1498 SetVolume(curDir.GetVolume());
1499
1500 if ( !m_relative )
1501 {
1502 // yes, it was the case - we don't need curDir then
1503 curDir.Clear();
1504 }
1505 }
1506
1507 // finally, prepend curDir to the dirs array
1508 wxArrayString dirsNew = curDir.GetDirs();
1509 WX_PREPEND_ARRAY(dirs, dirsNew);
1510
1511 // if we used e.g. tilde expansion previously and wxGetUserHome didn't
1512 // return for some reason an absolute path, then curDir maybe not be absolute!
1513 if ( !curDir.m_relative )
1514 {
1515 // we have prepended an absolute path and thus we are now an absolute
1516 // file name too
1517 m_relative = false;
1518 }
1519 // else if (flags & wxPATH_NORM_ABSOLUTE):
1520 // should we warn the user that we didn't manage to make the path absolute?
1521 }
1522
1523 // now deal with ".", ".." and the rest
1524 m_dirs.Empty();
1525 size_t count = dirs.GetCount();
1526 for ( size_t n = 0; n < count; n++ )
1527 {
1528 wxString dir = dirs[n];
1529
1530 if ( flags & wxPATH_NORM_DOTS )
1531 {
1532 if ( dir == wxT(".") )
1533 {
1534 // just ignore
1535 continue;
1536 }
1537
1538 if ( dir == wxT("..") )
1539 {
1540 if ( m_dirs.empty() )
1541 {
1542 // We have more ".." than directory components so far.
1543 // Don't treat this as an error as the path could have been
1544 // entered by user so try to handle it reasonably: if the
1545 // path is absolute, just ignore the extra ".." because
1546 // "/.." is the same as "/". Otherwise, i.e. for relative
1547 // paths, keep ".." unchanged because removing it would
1548 // modify the file a relative path refers to.
1549 if ( !m_relative )
1550 continue;
1551
1552 }
1553 else // Normal case, go one step up.
1554 {
1555 m_dirs.pop_back();
1556 continue;
1557 }
1558 }
1559 }
1560
1561 m_dirs.Add(dir);
1562 }
1563
1564 #if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
1565 if ( (flags & wxPATH_NORM_SHORTCUT) )
1566 {
1567 wxString filename;
1568 if (GetShortcutTarget(GetFullPath(format), filename))
1569 {
1570 m_relative = false;
1571 Assign(filename);
1572 }
1573 }
1574 #endif
1575
1576 #if defined(__WIN32__)
1577 if ( (flags & wxPATH_NORM_LONG) && (format == wxPATH_DOS) )
1578 {
1579 Assign(GetLongPath());
1580 }
1581 #endif // Win32
1582
1583 // Change case (this should be kept at the end of the function, to ensure
1584 // that the path doesn't change any more after we normalize its case)
1585 if ( (flags & wxPATH_NORM_CASE) && !IsCaseSensitive(format) )
1586 {
1587 m_volume.MakeLower();
1588 m_name.MakeLower();
1589 m_ext.MakeLower();
1590
1591 // directory entries must be made lower case as well
1592 count = m_dirs.GetCount();
1593 for ( size_t i = 0; i < count; i++ )
1594 {
1595 m_dirs[i].MakeLower();
1596 }
1597 }
1598
1599 return true;
1600 }
1601
1602 #ifndef __WXWINCE__
1603 bool wxFileName::ReplaceEnvVariable(const wxString& envname,
1604 const wxString& replacementFmtString,
1605 wxPathFormat format)
1606 {
1607 // look into stringForm for the contents of the given environment variable
1608 wxString val;
1609 if (envname.empty() ||
1610 !wxGetEnv(envname, &val))
1611 return false;
1612 if (val.empty())
1613 return false;
1614
1615 wxString stringForm = GetPath(wxPATH_GET_VOLUME, format);
1616 // do not touch the file name and the extension
1617
1618 wxString replacement = wxString::Format(replacementFmtString, envname);
1619 stringForm.Replace(val, replacement);
1620
1621 // Now assign ourselves the modified path:
1622 Assign(stringForm, GetFullName(), format);
1623
1624 return true;
1625 }
1626 #endif
1627
1628 bool wxFileName::ReplaceHomeDir(wxPathFormat format)
1629 {
1630 wxString homedir = wxGetHomeDir();
1631 if (homedir.empty())
1632 return false;
1633
1634 wxString stringForm = GetPath(wxPATH_GET_VOLUME, format);
1635 // do not touch the file name and the extension
1636
1637 stringForm.Replace(homedir, "~");
1638
1639 // Now assign ourselves the modified path:
1640 Assign(stringForm, GetFullName(), format);
1641
1642 return true;
1643 }
1644
1645 // ----------------------------------------------------------------------------
1646 // get the shortcut target
1647 // ----------------------------------------------------------------------------
1648
1649 // WinCE (3) doesn't have CLSID_ShellLink, IID_IShellLink definitions.
1650 // The .lnk file is a plain text file so it should be easy to
1651 // make it work. Hint from Google Groups:
1652 // "If you open up a lnk file, you'll see a
1653 // number, followed by a pound sign (#), followed by more text. The
1654 // number is the number of characters that follows the pound sign. The
1655 // characters after the pound sign are the command line (which _can_
1656 // include arguments) to be executed. Any path (e.g. \windows\program
1657 // files\myapp.exe) that includes spaces needs to be enclosed in
1658 // quotation marks."
1659
1660 #if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
1661 // The following lines are necessary under WinCE
1662 // #include "wx/msw/private.h"
1663 // #include <ole2.h>
1664 #include <shlobj.h>
1665 #if defined(__WXWINCE__)
1666 #include <shlguid.h>
1667 #endif
1668
1669 bool wxFileName::GetShortcutTarget(const wxString& shortcutPath,
1670 wxString& targetFilename,
1671 wxString* arguments) const
1672 {
1673 wxString path, file, ext;
1674 wxFileName::SplitPath(shortcutPath, & path, & file, & ext);
1675
1676 HRESULT hres;
1677 IShellLink* psl;
1678 bool success = false;
1679
1680 // Assume it's not a shortcut if it doesn't end with lnk
1681 if (ext.CmpNoCase(wxT("lnk"))!=0)
1682 return false;
1683
1684 // create a ShellLink object
1685 hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
1686 IID_IShellLink, (LPVOID*) &psl);
1687
1688 if (SUCCEEDED(hres))
1689 {
1690 IPersistFile* ppf;
1691 hres = psl->QueryInterface( IID_IPersistFile, (LPVOID *) &ppf);
1692 if (SUCCEEDED(hres))
1693 {
1694 WCHAR wsz[MAX_PATH];
1695
1696 MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, shortcutPath.mb_str(), -1, wsz,
1697 MAX_PATH);
1698
1699 hres = ppf->Load(wsz, 0);
1700 ppf->Release();
1701
1702 if (SUCCEEDED(hres))
1703 {
1704 wxChar buf[2048];
1705 // Wrong prototype in early versions
1706 #if defined(__MINGW32__) && !wxCHECK_W32API_VERSION(2, 2)
1707 psl->GetPath((CHAR*) buf, 2048, NULL, SLGP_UNCPRIORITY);
1708 #else
1709 psl->GetPath(buf, 2048, NULL, SLGP_UNCPRIORITY);
1710 #endif
1711 targetFilename = wxString(buf);
1712 success = (shortcutPath != targetFilename);
1713
1714 psl->GetArguments(buf, 2048);
1715 wxString args(buf);
1716 if (!args.empty() && arguments)
1717 {
1718 *arguments = args;
1719 }
1720 }
1721 }
1722
1723 psl->Release();
1724 }
1725 return success;
1726 }
1727
1728 #endif // __WIN32__ && !__WXWINCE__
1729
1730
1731 // ----------------------------------------------------------------------------
1732 // absolute/relative paths
1733 // ----------------------------------------------------------------------------
1734
1735 bool wxFileName::IsAbsolute(wxPathFormat format) const
1736 {
1737 // unix paths beginning with ~ are reported as being absolute
1738 if ( format == wxPATH_UNIX )
1739 {
1740 if ( !m_dirs.IsEmpty() )
1741 {
1742 wxString dir = m_dirs[0u];
1743
1744 if (!dir.empty() && dir[0u] == wxT('~'))
1745 return true;
1746 }
1747 }
1748
1749 // if our path doesn't start with a path separator, it's not an absolute
1750 // path
1751 if ( m_relative )
1752 return false;
1753
1754 if ( !GetVolumeSeparator(format).empty() )
1755 {
1756 // this format has volumes and an absolute path must have one, it's not
1757 // enough to have the full path to be an absolute file under Windows
1758 if ( GetVolume().empty() )
1759 return false;
1760 }
1761
1762 return true;
1763 }
1764
1765 bool wxFileName::MakeRelativeTo(const wxString& pathBase, wxPathFormat format)
1766 {
1767 wxFileName fnBase = wxFileName::DirName(pathBase, format);
1768
1769 // get cwd only once - small time saving
1770 wxString cwd = wxGetCwd();
1771 Normalize(wxPATH_NORM_ALL & ~wxPATH_NORM_CASE, cwd, format);
1772 fnBase.Normalize(wxPATH_NORM_ALL & ~wxPATH_NORM_CASE, cwd, format);
1773
1774 bool withCase = IsCaseSensitive(format);
1775
1776 // we can't do anything if the files live on different volumes
1777 if ( !GetVolume().IsSameAs(fnBase.GetVolume(), withCase) )
1778 {
1779 // nothing done
1780 return false;
1781 }
1782
1783 // same drive, so we don't need our volume
1784 m_volume.clear();
1785
1786 // remove common directories starting at the top
1787 while ( !m_dirs.IsEmpty() && !fnBase.m_dirs.IsEmpty() &&
1788 m_dirs[0u].IsSameAs(fnBase.m_dirs[0u], withCase) )
1789 {
1790 m_dirs.RemoveAt(0);
1791 fnBase.m_dirs.RemoveAt(0);
1792 }
1793
1794 // add as many ".." as needed
1795 size_t count = fnBase.m_dirs.GetCount();
1796 for ( size_t i = 0; i < count; i++ )
1797 {
1798 m_dirs.Insert(wxT(".."), 0u);
1799 }
1800
1801 if ( format == wxPATH_UNIX || format == wxPATH_DOS )
1802 {
1803 // a directory made relative with respect to itself is '.' under Unix
1804 // and DOS, by definition (but we don't have to insert "./" for the
1805 // files)
1806 if ( m_dirs.IsEmpty() && IsDir() )
1807 {
1808 m_dirs.Add(wxT('.'));
1809 }
1810 }
1811
1812 m_relative = true;
1813
1814 // we were modified
1815 return true;
1816 }
1817
1818 // ----------------------------------------------------------------------------
1819 // filename kind tests
1820 // ----------------------------------------------------------------------------
1821
1822 bool wxFileName::SameAs(const wxFileName& filepath, wxPathFormat format) const
1823 {
1824 wxFileName fn1 = *this,
1825 fn2 = filepath;
1826
1827 // get cwd only once - small time saving
1828 wxString cwd = wxGetCwd();
1829 fn1.Normalize(wxPATH_NORM_ALL | wxPATH_NORM_CASE, cwd, format);
1830 fn2.Normalize(wxPATH_NORM_ALL | wxPATH_NORM_CASE, cwd, format);
1831
1832 if ( fn1.GetFullPath() == fn2.GetFullPath() )
1833 return true;
1834
1835 #if defined(__UNIX__)
1836 wxStructStat st1, st2;
1837 if ( StatAny(st1, fn1) && StatAny(st2, fn2) )
1838 {
1839 if ( st1.st_ino == st2.st_ino && st1.st_dev == st2.st_dev )
1840 return true;
1841 }
1842 //else: It's not an error if one or both files don't exist.
1843 #endif // defined __UNIX__
1844
1845 return false;
1846 }
1847
1848 /* static */
1849 bool wxFileName::IsCaseSensitive( wxPathFormat format )
1850 {
1851 // only Unix filenames are truly case-sensitive
1852 return GetFormat(format) == wxPATH_UNIX;
1853 }
1854
1855 /* static */
1856 wxString wxFileName::GetForbiddenChars(wxPathFormat format)
1857 {
1858 // Inits to forbidden characters that are common to (almost) all platforms.
1859 wxString strForbiddenChars = wxT("*?");
1860
1861 // If asserts, wxPathFormat has been changed. In case of a new path format
1862 // addition, the following code might have to be updated.
1863 wxCOMPILE_TIME_ASSERT(wxPATH_MAX == 5, wxPathFormatChanged);
1864 switch ( GetFormat(format) )
1865 {
1866 default :
1867 wxFAIL_MSG( wxT("Unknown path format") );
1868 // !! Fall through !!
1869
1870 case wxPATH_UNIX:
1871 break;
1872
1873 case wxPATH_MAC:
1874 // On a Mac even names with * and ? are allowed (Tested with OS
1875 // 9.2.1 and OS X 10.2.5)
1876 strForbiddenChars = wxEmptyString;
1877 break;
1878
1879 case wxPATH_DOS:
1880 strForbiddenChars += wxT("\\/:\"<>|");
1881 break;
1882
1883 case wxPATH_VMS:
1884 break;
1885 }
1886
1887 return strForbiddenChars;
1888 }
1889
1890 /* static */
1891 wxString wxFileName::GetVolumeSeparator(wxPathFormat WXUNUSED_IN_WINCE(format))
1892 {
1893 #ifdef __WXWINCE__
1894 return wxEmptyString;
1895 #else
1896 wxString sepVol;
1897
1898 if ( (GetFormat(format) == wxPATH_DOS) ||
1899 (GetFormat(format) == wxPATH_VMS) )
1900 {
1901 sepVol = wxFILE_SEP_DSK;
1902 }
1903 //else: leave empty
1904
1905 return sepVol;
1906 #endif
1907 }
1908
1909 /* static */
1910 wxString wxFileName::GetPathSeparators(wxPathFormat format)
1911 {
1912 wxString seps;
1913 switch ( GetFormat(format) )
1914 {
1915 case wxPATH_DOS:
1916 // accept both as native APIs do but put the native one first as
1917 // this is the one we use in GetFullPath()
1918 seps << wxFILE_SEP_PATH_DOS << wxFILE_SEP_PATH_UNIX;
1919 break;
1920
1921 default:
1922 wxFAIL_MSG( wxT("Unknown wxPATH_XXX style") );
1923 // fall through
1924
1925 case wxPATH_UNIX:
1926 seps = wxFILE_SEP_PATH_UNIX;
1927 break;
1928
1929 case wxPATH_MAC:
1930 seps = wxFILE_SEP_PATH_MAC;
1931 break;
1932
1933 case wxPATH_VMS:
1934 seps = wxFILE_SEP_PATH_VMS;
1935 break;
1936 }
1937
1938 return seps;
1939 }
1940
1941 /* static */
1942 wxString wxFileName::GetPathTerminators(wxPathFormat format)
1943 {
1944 format = GetFormat(format);
1945
1946 // under VMS the end of the path is ']', not the path separator used to
1947 // separate the components
1948 return format == wxPATH_VMS ? wxString(wxT(']')) : GetPathSeparators(format);
1949 }
1950
1951 /* static */
1952 bool wxFileName::IsPathSeparator(wxChar ch, wxPathFormat format)
1953 {
1954 // wxString::Find() doesn't work as expected with NUL - it will always find
1955 // it, so test for it separately
1956 return ch != wxT('\0') && GetPathSeparators(format).Find(ch) != wxNOT_FOUND;
1957 }
1958
1959 /* static */
1960 bool
1961 wxFileName::IsMSWUniqueVolumeNamePath(const wxString& path, wxPathFormat format)
1962 {
1963 // return true if the format used is the DOS/Windows one and the string begins
1964 // with a Windows unique volume name ("\\?\Volume{guid}\")
1965 return format == wxPATH_DOS &&
1966 path.length() >= wxMSWUniqueVolumePrefixLength &&
1967 path.StartsWith(wxS("\\\\?\\Volume{")) &&
1968 path[wxMSWUniqueVolumePrefixLength - 1] == wxFILE_SEP_PATH_DOS;
1969 }
1970
1971 // ----------------------------------------------------------------------------
1972 // path components manipulation
1973 // ----------------------------------------------------------------------------
1974
1975 /* static */ bool wxFileName::IsValidDirComponent(const wxString& dir)
1976 {
1977 if ( dir.empty() )
1978 {
1979 wxFAIL_MSG( wxT("empty directory passed to wxFileName::InsertDir()") );
1980
1981 return false;
1982 }
1983
1984 const size_t len = dir.length();
1985 for ( size_t n = 0; n < len; n++ )
1986 {
1987 if ( dir[n] == GetVolumeSeparator() || IsPathSeparator(dir[n]) )
1988 {
1989 wxFAIL_MSG( wxT("invalid directory component in wxFileName") );
1990
1991 return false;
1992 }
1993 }
1994
1995 return true;
1996 }
1997
1998 void wxFileName::AppendDir( const wxString& dir )
1999 {
2000 if ( IsValidDirComponent(dir) )
2001 m_dirs.Add( dir );
2002 }
2003
2004 void wxFileName::PrependDir( const wxString& dir )
2005 {
2006 InsertDir(0, dir);
2007 }
2008
2009 void wxFileName::InsertDir(size_t before, const wxString& dir)
2010 {
2011 if ( IsValidDirComponent(dir) )
2012 m_dirs.Insert(dir, before);
2013 }
2014
2015 void wxFileName::RemoveDir(size_t pos)
2016 {
2017 m_dirs.RemoveAt(pos);
2018 }
2019
2020 // ----------------------------------------------------------------------------
2021 // accessors
2022 // ----------------------------------------------------------------------------
2023
2024 void wxFileName::SetFullName(const wxString& fullname)
2025 {
2026 SplitPath(fullname, NULL /* no volume */, NULL /* no path */,
2027 &m_name, &m_ext, &m_hasExt);
2028 }
2029
2030 wxString wxFileName::GetFullName() const
2031 {
2032 wxString fullname = m_name;
2033 if ( m_hasExt )
2034 {
2035 fullname << wxFILE_SEP_EXT << m_ext;
2036 }
2037
2038 return fullname;
2039 }
2040
2041 wxString wxFileName::GetPath( int flags, wxPathFormat format ) const
2042 {
2043 format = GetFormat( format );
2044
2045 wxString fullpath;
2046
2047 // return the volume with the path as well if requested
2048 if ( flags & wxPATH_GET_VOLUME )
2049 {
2050 fullpath += wxGetVolumeString(GetVolume(), format);
2051 }
2052
2053 // the leading character
2054 switch ( format )
2055 {
2056 case wxPATH_MAC:
2057 if ( m_relative )
2058 fullpath += wxFILE_SEP_PATH_MAC;
2059 break;
2060
2061 case wxPATH_DOS:
2062 if ( !m_relative )
2063 fullpath += wxFILE_SEP_PATH_DOS;
2064 break;
2065
2066 default:
2067 wxFAIL_MSG( wxT("Unknown path format") );
2068 // fall through
2069
2070 case wxPATH_UNIX:
2071 if ( !m_relative )
2072 {
2073 fullpath += wxFILE_SEP_PATH_UNIX;
2074 }
2075 break;
2076
2077 case wxPATH_VMS:
2078 // no leading character here but use this place to unset
2079 // wxPATH_GET_SEPARATOR flag: under VMS it doesn't make sense
2080 // as, if I understand correctly, there should never be a dot
2081 // before the closing bracket
2082 flags &= ~wxPATH_GET_SEPARATOR;
2083 }
2084
2085 if ( m_dirs.empty() )
2086 {
2087 // there is nothing more
2088 return fullpath;
2089 }
2090
2091 // then concatenate all the path components using the path separator
2092 if ( format == wxPATH_VMS )
2093 {
2094 fullpath += wxT('[');
2095 }
2096
2097 const size_t dirCount = m_dirs.GetCount();
2098 for ( size_t i = 0; i < dirCount; i++ )
2099 {
2100 switch (format)
2101 {
2102 case wxPATH_MAC:
2103 if ( m_dirs[i] == wxT(".") )
2104 {
2105 // skip appending ':', this shouldn't be done in this
2106 // case as "::" is interpreted as ".." under Unix
2107 continue;
2108 }
2109
2110 // convert back from ".." to nothing
2111 if ( !m_dirs[i].IsSameAs(wxT("..")) )
2112 fullpath += m_dirs[i];
2113 break;
2114
2115 default:
2116 wxFAIL_MSG( wxT("Unexpected path format") );
2117 // still fall through
2118
2119 case wxPATH_DOS:
2120 case wxPATH_UNIX:
2121 fullpath += m_dirs[i];
2122 break;
2123
2124 case wxPATH_VMS:
2125 // TODO: What to do with ".." under VMS
2126
2127 // convert back from ".." to nothing
2128 if ( !m_dirs[i].IsSameAs(wxT("..")) )
2129 fullpath += m_dirs[i];
2130 break;
2131 }
2132
2133 if ( (flags & wxPATH_GET_SEPARATOR) || (i != dirCount - 1) )
2134 fullpath += GetPathSeparator(format);
2135 }
2136
2137 if ( format == wxPATH_VMS )
2138 {
2139 fullpath += wxT(']');
2140 }
2141
2142 return fullpath;
2143 }
2144
2145 wxString wxFileName::GetFullPath( wxPathFormat format ) const
2146 {
2147 // we already have a function to get the path
2148 wxString fullpath = GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR,
2149 format);
2150
2151 // now just add the file name and extension to it
2152 fullpath += GetFullName();
2153
2154 return fullpath;
2155 }
2156
2157 // Return the short form of the path (returns identity on non-Windows platforms)
2158 wxString wxFileName::GetShortPath() const
2159 {
2160 wxString path(GetFullPath());
2161
2162 #if defined(__WINDOWS__) && defined(__WIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
2163 DWORD sz = ::GetShortPathName(path.t_str(), NULL, 0);
2164 if ( sz != 0 )
2165 {
2166 wxString pathOut;
2167 if ( ::GetShortPathName
2168 (
2169 path.t_str(),
2170 wxStringBuffer(pathOut, sz),
2171 sz
2172 ) != 0 )
2173 {
2174 return pathOut;
2175 }
2176 }
2177 #endif // Windows
2178
2179 return path;
2180 }
2181
2182 // Return the long form of the path (returns identity on non-Windows platforms)
2183 wxString wxFileName::GetLongPath() const
2184 {
2185 wxString pathOut,
2186 path = GetFullPath();
2187
2188 #if defined(__WIN32__) && !defined(__WXWINCE__) && !defined(__WXMICROWIN__)
2189
2190 #if wxUSE_DYNLIB_CLASS
2191 typedef DWORD (WINAPI *GET_LONG_PATH_NAME)(const wxChar *, wxChar *, DWORD);
2192
2193 // this is MT-safe as in the worst case we're going to resolve the function
2194 // twice -- but as the result is the same in both threads, it's ok
2195 static GET_LONG_PATH_NAME s_pfnGetLongPathName = NULL;
2196 if ( !s_pfnGetLongPathName )
2197 {
2198 static bool s_triedToLoad = false;
2199
2200 if ( !s_triedToLoad )
2201 {
2202 s_triedToLoad = true;
2203
2204 wxDynamicLibrary dllKernel(wxT("kernel32"));
2205
2206 const wxChar* GetLongPathName = wxT("GetLongPathName")
2207 #if wxUSE_UNICODE
2208 wxT("W");
2209 #else // ANSI
2210 wxT("A");
2211 #endif // Unicode/ANSI
2212
2213 if ( dllKernel.HasSymbol(GetLongPathName) )
2214 {
2215 s_pfnGetLongPathName = (GET_LONG_PATH_NAME)
2216 dllKernel.GetSymbol(GetLongPathName);
2217 }
2218
2219 // note that kernel32.dll can be unloaded, it stays in memory
2220 // anyhow as all Win32 programs link to it and so it's safe to call
2221 // GetLongPathName() even after unloading it
2222 }
2223 }
2224
2225 if ( s_pfnGetLongPathName )
2226 {
2227 DWORD dwSize = (*s_pfnGetLongPathName)(path.t_str(), NULL, 0);
2228 if ( dwSize > 0 )
2229 {
2230 if ( (*s_pfnGetLongPathName)
2231 (
2232 path.t_str(),
2233 wxStringBuffer(pathOut, dwSize),
2234 dwSize
2235 ) != 0 )
2236 {
2237 return pathOut;
2238 }
2239 }
2240 }
2241 #endif // wxUSE_DYNLIB_CLASS
2242
2243 // The OS didn't support GetLongPathName, or some other error.
2244 // We need to call FindFirstFile on each component in turn.
2245
2246 WIN32_FIND_DATA findFileData;
2247 HANDLE hFind;
2248
2249 if ( HasVolume() )
2250 pathOut = GetVolume() +
2251 GetVolumeSeparator(wxPATH_DOS) +
2252 GetPathSeparator(wxPATH_DOS);
2253 else
2254 pathOut = wxEmptyString;
2255
2256 wxArrayString dirs = GetDirs();
2257 dirs.Add(GetFullName());
2258
2259 wxString tmpPath;
2260
2261 size_t count = dirs.GetCount();
2262 for ( size_t i = 0; i < count; i++ )
2263 {
2264 const wxString& dir = dirs[i];
2265
2266 // We're using pathOut to collect the long-name path, but using a
2267 // temporary for appending the last path component which may be
2268 // short-name
2269 tmpPath = pathOut + dir;
2270
2271 // We must not process "." or ".." here as they would be (unexpectedly)
2272 // replaced by the corresponding directory names so just leave them
2273 // alone
2274 //
2275 // And we can't pass a drive and root dir to FindFirstFile (VZ: why?)
2276 if ( tmpPath.empty() || dir == '.' || dir == ".." ||
2277 tmpPath.Last() == GetVolumeSeparator(wxPATH_DOS) )
2278 {
2279 tmpPath += wxFILE_SEP_PATH;
2280 pathOut = tmpPath;
2281 continue;
2282 }
2283
2284 hFind = ::FindFirstFile(tmpPath.t_str(), &findFileData);
2285 if (hFind == INVALID_HANDLE_VALUE)
2286 {
2287 // Error: most likely reason is that path doesn't exist, so
2288 // append any unprocessed parts and return
2289 for ( i += 1; i < count; i++ )
2290 tmpPath += wxFILE_SEP_PATH + dirs[i];
2291
2292 return tmpPath;
2293 }
2294
2295 pathOut += findFileData.cFileName;
2296 if ( (i < (count-1)) )
2297 pathOut += wxFILE_SEP_PATH;
2298
2299 ::FindClose(hFind);
2300 }
2301 #else // !Win32
2302 pathOut = path;
2303 #endif // Win32/!Win32
2304
2305 return pathOut;
2306 }
2307
2308 wxPathFormat wxFileName::GetFormat( wxPathFormat format )
2309 {
2310 if (format == wxPATH_NATIVE)
2311 {
2312 #if defined(__WINDOWS__) || defined(__OS2__) || defined(__DOS__)
2313 format = wxPATH_DOS;
2314 #elif defined(__VMS)
2315 format = wxPATH_VMS;
2316 #else
2317 format = wxPATH_UNIX;
2318 #endif
2319 }
2320 return format;
2321 }
2322
2323 #ifdef wxHAS_FILESYSTEM_VOLUMES
2324
2325 /* static */
2326 wxString wxFileName::GetVolumeString(char drive, int flags)
2327 {
2328 wxASSERT_MSG( !(flags & ~wxPATH_GET_SEPARATOR), "invalid flag specified" );
2329
2330 wxString vol(drive);
2331 vol += wxFILE_SEP_DSK;
2332 if ( flags & wxPATH_GET_SEPARATOR )
2333 vol += wxFILE_SEP_PATH;
2334
2335 return vol;
2336 }
2337
2338 #endif // wxHAS_FILESYSTEM_VOLUMES
2339
2340 // ----------------------------------------------------------------------------
2341 // path splitting function
2342 // ----------------------------------------------------------------------------
2343
2344 /* static */
2345 void
2346 wxFileName::SplitVolume(const wxString& fullpathWithVolume,
2347 wxString *pstrVolume,
2348 wxString *pstrPath,
2349 wxPathFormat format)
2350 {
2351 format = GetFormat(format);
2352
2353 wxString fullpath = fullpathWithVolume;
2354
2355 if ( IsMSWUniqueVolumeNamePath(fullpath, format) )
2356 {
2357 // special Windows unique volume names hack: transform
2358 // \\?\Volume{guid}\path into Volume{guid}:path
2359 // note: this check must be done before the check for UNC path
2360
2361 // we know the last backslash from the unique volume name is located
2362 // there from IsMSWUniqueVolumeNamePath
2363 fullpath[wxMSWUniqueVolumePrefixLength - 1] = wxFILE_SEP_DSK;
2364
2365 // paths starting with a unique volume name should always be absolute
2366 fullpath.insert(wxMSWUniqueVolumePrefixLength, 1, wxFILE_SEP_PATH_DOS);
2367
2368 // remove the leading "\\?\" part
2369 fullpath.erase(0, 4);
2370 }
2371 else if ( IsUNCPath(fullpath, format) )
2372 {
2373 // special Windows UNC paths hack: transform \\share\path into share:path
2374
2375 fullpath.erase(0, 2);
2376
2377 size_t posFirstSlash =
2378 fullpath.find_first_of(GetPathTerminators(format));
2379 if ( posFirstSlash != wxString::npos )
2380 {
2381 fullpath[posFirstSlash] = wxFILE_SEP_DSK;
2382
2383 // UNC paths are always absolute, right? (FIXME)
2384 fullpath.insert(posFirstSlash + 1, 1, wxFILE_SEP_PATH_DOS);
2385 }
2386 }
2387
2388 // We separate the volume here
2389 if ( format == wxPATH_DOS || format == wxPATH_VMS )
2390 {
2391 wxString sepVol = GetVolumeSeparator(format);
2392
2393 // we have to exclude the case of a colon in the very beginning of the
2394 // string as it can't be a volume separator (nor can this be a valid
2395 // DOS file name at all but we'll leave dealing with this to our caller)
2396 size_t posFirstColon = fullpath.find_first_of(sepVol);
2397 if ( posFirstColon && posFirstColon != wxString::npos )
2398 {
2399 if ( pstrVolume )
2400 {
2401 *pstrVolume = fullpath.Left(posFirstColon);
2402 }
2403
2404 // remove the volume name and the separator from the full path
2405 fullpath.erase(0, posFirstColon + sepVol.length());
2406 }
2407 }
2408
2409 if ( pstrPath )
2410 *pstrPath = fullpath;
2411 }
2412
2413 /* static */
2414 void wxFileName::SplitPath(const wxString& fullpathWithVolume,
2415 wxString *pstrVolume,
2416 wxString *pstrPath,
2417 wxString *pstrName,
2418 wxString *pstrExt,
2419 bool *hasExt,
2420 wxPathFormat format)
2421 {
2422 format = GetFormat(format);
2423
2424 wxString fullpath;
2425 SplitVolume(fullpathWithVolume, pstrVolume, &fullpath, format);
2426
2427 // find the positions of the last dot and last path separator in the path
2428 size_t posLastDot = fullpath.find_last_of(wxFILE_SEP_EXT);
2429 size_t posLastSlash = fullpath.find_last_of(GetPathTerminators(format));
2430
2431 // check whether this dot occurs at the very beginning of a path component
2432 if ( (posLastDot != wxString::npos) &&
2433 (posLastDot == 0 ||
2434 IsPathSeparator(fullpath[posLastDot - 1]) ||
2435 (format == wxPATH_VMS && fullpath[posLastDot - 1] == wxT(']'))) )
2436 {
2437 // dot may be (and commonly -- at least under Unix -- is) the first
2438 // character of the filename, don't treat the entire filename as
2439 // extension in this case
2440 posLastDot = wxString::npos;
2441 }
2442
2443 // if we do have a dot and a slash, check that the dot is in the name part
2444 if ( (posLastDot != wxString::npos) &&
2445 (posLastSlash != wxString::npos) &&
2446 (posLastDot < posLastSlash) )
2447 {
2448 // the dot is part of the path, not the start of the extension
2449 posLastDot = wxString::npos;
2450 }
2451
2452 // now fill in the variables provided by user
2453 if ( pstrPath )
2454 {
2455 if ( posLastSlash == wxString::npos )
2456 {
2457 // no path at all
2458 pstrPath->Empty();
2459 }
2460 else
2461 {
2462 // take everything up to the path separator but take care to make
2463 // the path equal to something like '/', not empty, for the files
2464 // immediately under root directory
2465 size_t len = posLastSlash;
2466
2467 // this rule does not apply to mac since we do not start with colons (sep)
2468 // except for relative paths
2469 if ( !len && format != wxPATH_MAC)
2470 len++;
2471
2472 *pstrPath = fullpath.Left(len);
2473
2474 // special VMS hack: remove the initial bracket
2475 if ( format == wxPATH_VMS )
2476 {
2477 if ( (*pstrPath)[0u] == wxT('[') )
2478 pstrPath->erase(0, 1);
2479 }
2480 }
2481 }
2482
2483 if ( pstrName )
2484 {
2485 // take all characters starting from the one after the last slash and
2486 // up to, but excluding, the last dot
2487 size_t nStart = posLastSlash == wxString::npos ? 0 : posLastSlash + 1;
2488 size_t count;
2489 if ( posLastDot == wxString::npos )
2490 {
2491 // take all until the end
2492 count = wxString::npos;
2493 }
2494 else if ( posLastSlash == wxString::npos )
2495 {
2496 count = posLastDot;
2497 }
2498 else // have both dot and slash
2499 {
2500 count = posLastDot - posLastSlash - 1;
2501 }
2502
2503 *pstrName = fullpath.Mid(nStart, count);
2504 }
2505
2506 // finally deal with the extension here: we have an added complication that
2507 // extension may be empty (but present) as in "foo." where trailing dot
2508 // indicates the empty extension at the end -- and hence we must remember
2509 // that we have it independently of pstrExt
2510 if ( posLastDot == wxString::npos )
2511 {
2512 // no extension
2513 if ( pstrExt )
2514 pstrExt->clear();
2515 if ( hasExt )
2516 *hasExt = false;
2517 }
2518 else
2519 {
2520 // take everything after the dot
2521 if ( pstrExt )
2522 *pstrExt = fullpath.Mid(posLastDot + 1);
2523 if ( hasExt )
2524 *hasExt = true;
2525 }
2526 }
2527
2528 /* static */
2529 void wxFileName::SplitPath(const wxString& fullpath,
2530 wxString *path,
2531 wxString *name,
2532 wxString *ext,
2533 wxPathFormat format)
2534 {
2535 wxString volume;
2536 SplitPath(fullpath, &volume, path, name, ext, format);
2537
2538 if ( path )
2539 {
2540 path->Prepend(wxGetVolumeString(volume, format));
2541 }
2542 }
2543
2544 /* static */
2545 wxString wxFileName::StripExtension(const wxString& fullpath)
2546 {
2547 wxFileName fn(fullpath);
2548 fn.SetExt("");
2549 return fn.GetFullPath();
2550 }
2551
2552 // ----------------------------------------------------------------------------
2553 // time functions
2554 // ----------------------------------------------------------------------------
2555
2556 #if wxUSE_DATETIME
2557
2558 bool wxFileName::SetTimes(const wxDateTime *dtAccess,
2559 const wxDateTime *dtMod,
2560 const wxDateTime *dtCreate) const
2561 {
2562 #if defined(__WIN32__)
2563 FILETIME ftAccess, ftCreate, ftWrite;
2564
2565 if ( dtCreate )
2566 ConvertWxToFileTime(&ftCreate, *dtCreate);
2567 if ( dtAccess )
2568 ConvertWxToFileTime(&ftAccess, *dtAccess);
2569 if ( dtMod )
2570 ConvertWxToFileTime(&ftWrite, *dtMod);
2571
2572 wxString path;
2573 int flags;
2574 if ( IsDir() )
2575 {
2576 if ( wxGetOsVersion() == wxOS_WINDOWS_9X )
2577 {
2578 wxLogError(_("Setting directory access times is not supported "
2579 "under this OS version"));
2580 return false;
2581 }
2582
2583 path = GetPath();
2584 flags = FILE_FLAG_BACKUP_SEMANTICS;
2585 }
2586 else // file
2587 {
2588 path = GetFullPath();
2589 flags = 0;
2590 }
2591
2592 wxFileHandle fh(path, wxFileHandle::WriteAttr, flags);
2593 if ( fh.IsOk() )
2594 {
2595 if ( ::SetFileTime(fh,
2596 dtCreate ? &ftCreate : NULL,
2597 dtAccess ? &ftAccess : NULL,
2598 dtMod ? &ftWrite : NULL) )
2599 {
2600 return true;
2601 }
2602 }
2603 #elif defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
2604 wxUnusedVar(dtCreate);
2605
2606 if ( !dtAccess && !dtMod )
2607 {
2608 // can't modify the creation time anyhow, don't try
2609 return true;
2610 }
2611
2612 // if dtAccess or dtMod is not specified, use the other one (which must be
2613 // non NULL because of the test above) for both times
2614 utimbuf utm;
2615 utm.actime = dtAccess ? dtAccess->GetTicks() : dtMod->GetTicks();
2616 utm.modtime = dtMod ? dtMod->GetTicks() : dtAccess->GetTicks();
2617 if ( utime(GetFullPath().fn_str(), &utm) == 0 )
2618 {
2619 return true;
2620 }
2621 #else // other platform
2622 wxUnusedVar(dtAccess);
2623 wxUnusedVar(dtMod);
2624 wxUnusedVar(dtCreate);
2625 #endif // platforms
2626
2627 wxLogSysError(_("Failed to modify file times for '%s'"),
2628 GetFullPath().c_str());
2629
2630 return false;
2631 }
2632
2633 bool wxFileName::Touch() const
2634 {
2635 #if defined(__UNIX_LIKE__)
2636 // under Unix touching file is simple: just pass NULL to utime()
2637 if ( utime(GetFullPath().fn_str(), NULL) == 0 )
2638 {
2639 return true;
2640 }
2641
2642 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
2643
2644 return false;
2645 #else // other platform
2646 wxDateTime dtNow = wxDateTime::Now();
2647
2648 return SetTimes(&dtNow, &dtNow, NULL /* don't change create time */);
2649 #endif // platforms
2650 }
2651
2652 bool wxFileName::GetTimes(wxDateTime *dtAccess,
2653 wxDateTime *dtMod,
2654 wxDateTime *dtCreate) const
2655 {
2656 #if defined(__WIN32__)
2657 // we must use different methods for the files and directories under
2658 // Windows as CreateFile(GENERIC_READ) doesn't work for the directories and
2659 // CreateFile(FILE_FLAG_BACKUP_SEMANTICS) works -- but only under NT and
2660 // not 9x
2661 bool ok;
2662 FILETIME ftAccess, ftCreate, ftWrite;
2663 if ( IsDir() )
2664 {
2665 // implemented in msw/dir.cpp
2666 extern bool wxGetDirectoryTimes(const wxString& dirname,
2667 FILETIME *, FILETIME *, FILETIME *);
2668
2669 // we should pass the path without the trailing separator to
2670 // wxGetDirectoryTimes()
2671 ok = wxGetDirectoryTimes(GetPath(wxPATH_GET_VOLUME),
2672 &ftAccess, &ftCreate, &ftWrite);
2673 }
2674 else // file
2675 {
2676 wxFileHandle fh(GetFullPath(), wxFileHandle::ReadAttr);
2677 if ( fh.IsOk() )
2678 {
2679 ok = ::GetFileTime(fh,
2680 dtCreate ? &ftCreate : NULL,
2681 dtAccess ? &ftAccess : NULL,
2682 dtMod ? &ftWrite : NULL) != 0;
2683 }
2684 else
2685 {
2686 ok = false;
2687 }
2688 }
2689
2690 if ( ok )
2691 {
2692 if ( dtCreate )
2693 ConvertFileTimeToWx(dtCreate, ftCreate);
2694 if ( dtAccess )
2695 ConvertFileTimeToWx(dtAccess, ftAccess);
2696 if ( dtMod )
2697 ConvertFileTimeToWx(dtMod, ftWrite);
2698
2699 return true;
2700 }
2701 #elif defined(__UNIX_LIKE__) || defined(__WXMAC__) || defined(__OS2__) || (defined(__DOS__) && defined(__WATCOMC__))
2702 // no need to test for IsDir() here
2703 wxStructStat stBuf;
2704 if ( StatAny(stBuf, *this) )
2705 {
2706 // Android defines st_*time fields as unsigned long, but time_t as long,
2707 // hence the static_casts.
2708 if ( dtAccess )
2709 dtAccess->Set(static_cast<time_t>(stBuf.st_atime));
2710 if ( dtMod )
2711 dtMod->Set(static_cast<time_t>(stBuf.st_mtime));
2712 if ( dtCreate )
2713 dtCreate->Set(static_cast<time_t>(stBuf.st_ctime));
2714
2715 return true;
2716 }
2717 #else // other platform
2718 wxUnusedVar(dtAccess);
2719 wxUnusedVar(dtMod);
2720 wxUnusedVar(dtCreate);
2721 #endif // platforms
2722
2723 wxLogSysError(_("Failed to retrieve file times for '%s'"),
2724 GetFullPath().c_str());
2725
2726 return false;
2727 }
2728
2729 #endif // wxUSE_DATETIME
2730
2731
2732 // ----------------------------------------------------------------------------
2733 // file size functions
2734 // ----------------------------------------------------------------------------
2735
2736 #if wxUSE_LONGLONG
2737
2738 /* static */
2739 wxULongLong wxFileName::GetSize(const wxString &filename)
2740 {
2741 if (!wxFileExists(filename))
2742 return wxInvalidSize;
2743
2744 #if defined(__WIN32__)
2745 wxFileHandle f(filename, wxFileHandle::ReadAttr);
2746 if (!f.IsOk())
2747 return wxInvalidSize;
2748
2749 DWORD lpFileSizeHigh;
2750 DWORD ret = GetFileSize(f, &lpFileSizeHigh);
2751 if ( ret == INVALID_FILE_SIZE && ::GetLastError() != NO_ERROR )
2752 return wxInvalidSize;
2753
2754 return wxULongLong(lpFileSizeHigh, ret);
2755 #else // ! __WIN32__
2756 wxStructStat st;
2757 if (wxStat( filename, &st) != 0)
2758 return wxInvalidSize;
2759 return wxULongLong(st.st_size);
2760 #endif
2761 }
2762
2763 /* static */
2764 wxString wxFileName::GetHumanReadableSize(const wxULongLong &bs,
2765 const wxString &nullsize,
2766 int precision,
2767 wxSizeConvention conv)
2768 {
2769 // deal with trivial case first
2770 if ( bs == 0 || bs == wxInvalidSize )
2771 return nullsize;
2772
2773 // depending on the convention used the multiplier may be either 1000 or
2774 // 1024 and the binary infix may be empty (for "KB") or "i" (for "KiB")
2775 double multiplier = 1024.;
2776 wxString biInfix;
2777
2778 switch ( conv )
2779 {
2780 case wxSIZE_CONV_TRADITIONAL:
2781 // nothing to do, this corresponds to the default values of both
2782 // the multiplier and infix string
2783 break;
2784
2785 case wxSIZE_CONV_IEC:
2786 biInfix = "i";
2787 break;
2788
2789 case wxSIZE_CONV_SI:
2790 multiplier = 1000;
2791 break;
2792 }
2793
2794 const double kiloByteSize = multiplier;
2795 const double megaByteSize = multiplier * kiloByteSize;
2796 const double gigaByteSize = multiplier * megaByteSize;
2797 const double teraByteSize = multiplier * gigaByteSize;
2798
2799 const double bytesize = bs.ToDouble();
2800
2801 wxString result;
2802 if ( bytesize < kiloByteSize )
2803 result.Printf("%s B", bs.ToString());
2804 else if ( bytesize < megaByteSize )
2805 result.Printf("%.*f K%sB", precision, bytesize/kiloByteSize, biInfix);
2806 else if (bytesize < gigaByteSize)
2807 result.Printf("%.*f M%sB", precision, bytesize/megaByteSize, biInfix);
2808 else if (bytesize < teraByteSize)
2809 result.Printf("%.*f G%sB", precision, bytesize/gigaByteSize, biInfix);
2810 else
2811 result.Printf("%.*f T%sB", precision, bytesize/teraByteSize, biInfix);
2812
2813 return result;
2814 }
2815
2816 wxULongLong wxFileName::GetSize() const
2817 {
2818 return GetSize(GetFullPath());
2819 }
2820
2821 wxString wxFileName::GetHumanReadableSize(const wxString& failmsg,
2822 int precision,
2823 wxSizeConvention conv) const
2824 {
2825 return GetHumanReadableSize(GetSize(), failmsg, precision, conv);
2826 }
2827
2828 #endif // wxUSE_LONGLONG
2829
2830 // ----------------------------------------------------------------------------
2831 // Mac-specific functions
2832 // ----------------------------------------------------------------------------
2833
2834 #if defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON
2835
2836 namespace
2837 {
2838
2839 class MacDefaultExtensionRecord
2840 {
2841 public:
2842 MacDefaultExtensionRecord()
2843 {
2844 m_type =
2845 m_creator = 0 ;
2846 }
2847
2848 // default copy ctor, assignment operator and dtor are ok
2849
2850 MacDefaultExtensionRecord(const wxString& ext, OSType type, OSType creator)
2851 : m_ext(ext)
2852 {
2853 m_type = type;
2854 m_creator = creator;
2855 }
2856
2857 wxString m_ext;
2858 OSType m_type;
2859 OSType m_creator;
2860 };
2861
2862 WX_DECLARE_OBJARRAY(MacDefaultExtensionRecord, MacDefaultExtensionArray);
2863
2864 bool gMacDefaultExtensionsInited = false;
2865
2866 #include "wx/arrimpl.cpp"
2867
2868 WX_DEFINE_EXPORTED_OBJARRAY(MacDefaultExtensionArray);
2869
2870 MacDefaultExtensionArray gMacDefaultExtensions;
2871
2872 // load the default extensions
2873 const MacDefaultExtensionRecord gDefaults[] =
2874 {
2875 MacDefaultExtensionRecord( "txt", 'TEXT', 'ttxt' ),
2876 MacDefaultExtensionRecord( "tif", 'TIFF', '****' ),
2877 MacDefaultExtensionRecord( "jpg", 'JPEG', '****' ),
2878 };
2879
2880 void MacEnsureDefaultExtensionsLoaded()
2881 {
2882 if ( !gMacDefaultExtensionsInited )
2883 {
2884 // we could load the pc exchange prefs here too
2885 for ( size_t i = 0 ; i < WXSIZEOF( gDefaults ) ; ++i )
2886 {
2887 gMacDefaultExtensions.Add( gDefaults[i] ) ;
2888 }
2889 gMacDefaultExtensionsInited = true;
2890 }
2891 }
2892
2893 } // anonymous namespace
2894
2895 bool wxFileName::MacSetTypeAndCreator( wxUint32 type , wxUint32 creator )
2896 {
2897 FSRef fsRef ;
2898 FSCatalogInfo catInfo;
2899 FileInfo *finfo ;
2900
2901 if ( wxMacPathToFSRef( GetFullPath() , &fsRef ) == noErr )
2902 {
2903 if ( FSGetCatalogInfo (&fsRef, kFSCatInfoFinderInfo, &catInfo, NULL, NULL, NULL) == noErr )
2904 {
2905 finfo = (FileInfo*)&catInfo.finderInfo;
2906 finfo->fileType = type ;
2907 finfo->fileCreator = creator ;
2908 FSSetCatalogInfo( &fsRef, kFSCatInfoFinderInfo, &catInfo ) ;
2909 return true ;
2910 }
2911 }
2912 return false ;
2913 }
2914
2915 bool wxFileName::MacGetTypeAndCreator( wxUint32 *type , wxUint32 *creator ) const
2916 {
2917 FSRef fsRef ;
2918 FSCatalogInfo catInfo;
2919 FileInfo *finfo ;
2920
2921 if ( wxMacPathToFSRef( GetFullPath() , &fsRef ) == noErr )
2922 {
2923 if ( FSGetCatalogInfo (&fsRef, kFSCatInfoFinderInfo, &catInfo, NULL, NULL, NULL) == noErr )
2924 {
2925 finfo = (FileInfo*)&catInfo.finderInfo;
2926 *type = finfo->fileType ;
2927 *creator = finfo->fileCreator ;
2928 return true ;
2929 }
2930 }
2931 return false ;
2932 }
2933
2934 bool wxFileName::MacSetDefaultTypeAndCreator()
2935 {
2936 wxUint32 type , creator ;
2937 if ( wxFileName::MacFindDefaultTypeAndCreator(GetExt() , &type ,
2938 &creator ) )
2939 {
2940 return MacSetTypeAndCreator( type , creator ) ;
2941 }
2942 return false;
2943 }
2944
2945 bool wxFileName::MacFindDefaultTypeAndCreator( const wxString& ext , wxUint32 *type , wxUint32 *creator )
2946 {
2947 MacEnsureDefaultExtensionsLoaded() ;
2948 wxString extl = ext.Lower() ;
2949 for( int i = gMacDefaultExtensions.Count() - 1 ; i >= 0 ; --i )
2950 {
2951 if ( gMacDefaultExtensions.Item(i).m_ext == extl )
2952 {
2953 *type = gMacDefaultExtensions.Item(i).m_type ;
2954 *creator = gMacDefaultExtensions.Item(i).m_creator ;
2955 return true ;
2956 }
2957 }
2958 return false ;
2959 }
2960
2961 void wxFileName::MacRegisterDefaultTypeAndCreator( const wxString& ext , wxUint32 type , wxUint32 creator )
2962 {
2963 MacEnsureDefaultExtensionsLoaded();
2964 MacDefaultExtensionRecord rec(ext.Lower(), type, creator);
2965 gMacDefaultExtensions.Add( rec );
2966 }
2967
2968 #endif // defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON