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