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