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