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