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