]> git.saurik.com Git - wxWidgets.git/blob - src/common/filename.cpp
Including wx/msw/missing.h to define INVALID_FILE_ATTRIBUTES for MSVC6.
[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 "wx/msw/missing.h"
104 #endif
105
106 #if defined(__WXMAC__)
107 #include "wx/osx/private.h" // includes mac headers
108 #endif
109
110 // utime() is POSIX so should normally be available on all Unices
111 #ifdef __UNIX_LIKE__
112 #include <sys/types.h>
113 #include <utime.h>
114 #include <sys/stat.h>
115 #include <unistd.h>
116 #endif
117
118 #ifdef __DJGPP__
119 #include <unistd.h>
120 #endif
121
122 #ifdef __WATCOMC__
123 #include <io.h>
124 #include <sys/utime.h>
125 #include <sys/stat.h>
126 #endif
127
128 #ifdef __VISAGECPP__
129 #ifndef MAX_PATH
130 #define MAX_PATH 256
131 #endif
132 #endif
133
134 #ifdef __EMX__
135 #include <os2.h>
136 #define MAX_PATH _MAX_PATH
137 #endif
138
139 #ifndef S_ISREG
140 #define S_ISREG(mode) ((mode) & S_IFREG)
141 #endif
142 #ifndef S_ISDIR
143 #define S_ISDIR(mode) ((mode) & S_IFDIR)
144 #endif
145
146 #if wxUSE_LONGLONG
147 extern const wxULongLong wxInvalidSize = (unsigned)-1;
148 #endif // wxUSE_LONGLONG
149
150 namespace
151 {
152
153 // ----------------------------------------------------------------------------
154 // private classes
155 // ----------------------------------------------------------------------------
156
157 // small helper class which opens and closes the file - we use it just to get
158 // a file handle for the given file name to pass it to some Win32 API function
159 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
160
161 class wxFileHandle
162 {
163 public:
164 enum OpenMode
165 {
166 ReadAttr,
167 WriteAttr
168 };
169
170 wxFileHandle(const wxString& filename, OpenMode mode, int flags = 0)
171 {
172 // be careful and use FILE_{READ,WRITE}_ATTRIBUTES here instead of the
173 // usual GENERIC_{READ,WRITE} as we don't want the file access time to
174 // be changed when we open it because this class is used for setting
175 // access time (see #10567)
176 m_hFile = ::CreateFile
177 (
178 filename.t_str(), // name
179 mode == ReadAttr ? FILE_READ_ATTRIBUTES // access mask
180 : FILE_WRITE_ATTRIBUTES,
181 FILE_SHARE_READ | // sharing mode
182 FILE_SHARE_WRITE, // (allow everything)
183 NULL, // no secutity attr
184 OPEN_EXISTING, // creation disposition
185 flags, // flags
186 NULL // no template file
187 );
188
189 if ( m_hFile == INVALID_HANDLE_VALUE )
190 {
191 if ( mode == ReadAttr )
192 {
193 wxLogSysError(_("Failed to open '%s' for reading"),
194 filename.c_str());
195 }
196 else
197 {
198 wxLogSysError(_("Failed to open '%s' for writing"),
199 filename.c_str());
200 }
201 }
202 }
203
204 ~wxFileHandle()
205 {
206 if ( m_hFile != INVALID_HANDLE_VALUE )
207 {
208 if ( !::CloseHandle(m_hFile) )
209 {
210 wxLogSysError(_("Failed to close file handle"));
211 }
212 }
213 }
214
215 // return true only if the file could be opened successfully
216 bool IsOk() const { return m_hFile != INVALID_HANDLE_VALUE; }
217
218 // get the handle
219 operator HANDLE() const { return m_hFile; }
220
221 private:
222 HANDLE m_hFile;
223 };
224
225 #endif // __WIN32__
226
227 // ----------------------------------------------------------------------------
228 // private functions
229 // ----------------------------------------------------------------------------
230
231 #if wxUSE_DATETIME && defined(__WIN32__) && !defined(__WXMICROWIN__)
232
233 // convert between wxDateTime and FILETIME which is a 64-bit value representing
234 // the number of 100-nanosecond intervals since January 1, 1601.
235
236 static void ConvertFileTimeToWx(wxDateTime *dt, const FILETIME &ft)
237 {
238 FILETIME ftcopy = ft;
239 FILETIME ftLocal;
240 if ( !::FileTimeToLocalFileTime(&ftcopy, &ftLocal) )
241 {
242 wxLogLastError(wxT("FileTimeToLocalFileTime"));
243 }
244
245 SYSTEMTIME st;
246 if ( !::FileTimeToSystemTime(&ftLocal, &st) )
247 {
248 wxLogLastError(wxT("FileTimeToSystemTime"));
249 }
250
251 dt->Set(st.wDay, wxDateTime::Month(st.wMonth - 1), st.wYear,
252 st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
253 }
254
255 static void ConvertWxToFileTime(FILETIME *ft, const wxDateTime& dt)
256 {
257 SYSTEMTIME st;
258 st.wDay = dt.GetDay();
259 st.wMonth = (WORD)(dt.GetMonth() + 1);
260 st.wYear = (WORD)dt.GetYear();
261 st.wHour = dt.GetHour();
262 st.wMinute = dt.GetMinute();
263 st.wSecond = dt.GetSecond();
264 st.wMilliseconds = dt.GetMillisecond();
265
266 FILETIME ftLocal;
267 if ( !::SystemTimeToFileTime(&st, &ftLocal) )
268 {
269 wxLogLastError(wxT("SystemTimeToFileTime"));
270 }
271
272 if ( !::LocalFileTimeToFileTime(&ftLocal, ft) )
273 {
274 wxLogLastError(wxT("LocalFileTimeToFileTime"));
275 }
276 }
277
278 #endif // wxUSE_DATETIME && __WIN32__
279
280 // return a string with the volume par
281 static wxString wxGetVolumeString(const wxString& volume, wxPathFormat format)
282 {
283 wxString path;
284
285 if ( !volume.empty() )
286 {
287 format = wxFileName::GetFormat(format);
288
289 // Special Windows UNC paths hack, part 2: undo what we did in
290 // SplitPath() and make an UNC path if we have a drive which is not a
291 // single letter (hopefully the network shares can't be one letter only
292 // although I didn't find any authoritative docs on this)
293 if ( format == wxPATH_DOS && volume.length() > 1 )
294 {
295 // We also have to check for Windows unique volume names here and
296 // return it with '\\?\' prepended to it
297 if ( wxFileName::IsMSWUniqueVolumeNamePath("\\\\?\\" + volume + "\\",
298 format) )
299 {
300 path << "\\\\?\\" << volume;
301 }
302 else
303 {
304 // it must be a UNC path
305 path << wxFILE_SEP_PATH_DOS << wxFILE_SEP_PATH_DOS << volume;
306 }
307 }
308 else if ( format == wxPATH_DOS || format == wxPATH_VMS )
309 {
310 path << volume << wxFileName::GetVolumeSeparator(format);
311 }
312 // else ignore
313 }
314
315 return path;
316 }
317
318 // return true if the character is a DOS path separator i.e. either a slash or
319 // a backslash
320 inline bool IsDOSPathSep(wxUniChar ch)
321 {
322 return ch == wxFILE_SEP_PATH_DOS || ch == wxFILE_SEP_PATH_UNIX;
323 }
324
325 // return true if the format used is the DOS/Windows one and the string looks
326 // like a UNC path
327 static bool IsUNCPath(const wxString& path, wxPathFormat format)
328 {
329 return format == wxPATH_DOS &&
330 path.length() >= 4 && // "\\a" can't be a UNC path
331 IsDOSPathSep(path[0u]) &&
332 IsDOSPathSep(path[1u]) &&
333 !IsDOSPathSep(path[2u]);
334 }
335
336 #ifndef __WIN32__
337
338 // Under Unix-ish systems (basically everything except Windows) we may work
339 // either with the file itself or its target if it's a symbolic link and we
340 // should dereference it, as determined by wxFileName::ShouldFollowLink() and
341 // the absence of the wxFILE_EXISTS_NO_FOLLOW flag. StatAny() can be used to
342 // stat the appropriate file with an extra twist that it also works when there
343 // is no wxFileName object at all, as is the case in static methods.
344
345 // Private implementation, don't call directly, use one of the overloads below.
346 bool DoStatAny(wxStructStat& st, wxString path, bool dereference)
347 {
348 // We need to remove any trailing slashes from the path because they could
349 // interfere with the symlink following decision: even if we use lstat(),
350 // it would still follow the symlink if we pass it a path with a slash at
351 // the end because the symlink resolution would happen while following the
352 // path and not for the last path element itself.
353
354 while ( wxEndsWithPathSeparator(path) )
355 {
356 const size_t posLast = path.length() - 1;
357 if ( !posLast )
358 {
359 // Don't turn "/" into empty string.
360 break;
361 }
362
363 path.erase(posLast);
364 }
365
366 int ret = dereference ? wxStat(path, &st) : wxLstat(path, &st);
367 return ret == 0;
368 }
369
370 // Overloads to use for a case when we don't have wxFileName object and when we
371 // do have one.
372 inline
373 bool StatAny(wxStructStat& st, const wxString& path, int flags)
374 {
375 return DoStatAny(st, path, !(flags & wxFILE_EXISTS_NO_FOLLOW));
376 }
377
378 inline
379 bool StatAny(wxStructStat& st, const wxFileName& fn)
380 {
381 return DoStatAny(st, fn.GetFullPath(), fn.ShouldFollowLink());
382 }
383
384 #endif // !__WIN32__
385
386 // ----------------------------------------------------------------------------
387 // private constants
388 // ----------------------------------------------------------------------------
389
390 // length of \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ string
391 static const size_t wxMSWUniqueVolumePrefixLength = 49;
392
393 } // anonymous namespace
394
395 // ============================================================================
396 // implementation
397 // ============================================================================
398
399 // ----------------------------------------------------------------------------
400 // wxFileName construction
401 // ----------------------------------------------------------------------------
402
403 void wxFileName::Assign( const wxFileName &filepath )
404 {
405 m_volume = filepath.GetVolume();
406 m_dirs = filepath.GetDirs();
407 m_name = filepath.GetName();
408 m_ext = filepath.GetExt();
409 m_relative = filepath.m_relative;
410 m_hasExt = filepath.m_hasExt;
411 m_dontFollowLinks = filepath.m_dontFollowLinks;
412 }
413
414 void wxFileName::Assign(const wxString& volume,
415 const wxString& path,
416 const wxString& name,
417 const wxString& ext,
418 bool hasExt,
419 wxPathFormat format)
420 {
421 // we should ignore paths which look like UNC shares because we already
422 // have the volume here and the UNC notation (\\server\path) is only valid
423 // for paths which don't start with a volume, so prevent SetPath() from
424 // recognizing "\\foo\bar" in "c:\\foo\bar" as an UNC path
425 //
426 // note also that this is a rather ugly way to do what we want (passing
427 // some kind of flag telling to ignore UNC paths to SetPath() would be
428 // better) but this is the safest thing to do to avoid breaking backwards
429 // compatibility in 2.8
430 if ( IsUNCPath(path, format) )
431 {
432 // remove one of the 2 leading backslashes to ensure that it's not
433 // recognized as an UNC path by SetPath()
434 wxString pathNonUNC(path, 1, wxString::npos);
435 SetPath(pathNonUNC, format);
436 }
437 else // no UNC complications
438 {
439 SetPath(path, format);
440 }
441
442 m_volume = volume;
443 m_ext = ext;
444 m_name = name;
445
446 m_hasExt = hasExt;
447 }
448
449 void wxFileName::SetPath( const wxString& pathOrig, wxPathFormat format )
450 {
451 m_dirs.Clear();
452
453 if ( pathOrig.empty() )
454 {
455 // no path at all
456 m_relative = true;
457
458 return;
459 }
460
461 format = GetFormat( format );
462
463 // 0) deal with possible volume part first
464 wxString volume,
465 path;
466 SplitVolume(pathOrig, &volume, &path, format);
467 if ( !volume.empty() )
468 {
469 m_relative = false;
470
471 SetVolume(volume);
472 }
473
474 // 1) Determine if the path is relative or absolute.
475
476 if ( path.empty() )
477 {
478 // we had only the volume
479 return;
480 }
481
482 wxChar leadingChar = path[0u];
483
484 switch (format)
485 {
486 case wxPATH_MAC:
487 m_relative = leadingChar == wxT(':');
488
489 // We then remove a leading ":". The reason is in our
490 // storage form for relative paths:
491 // ":dir:file.txt" actually means "./dir/file.txt" in
492 // DOS notation and should get stored as
493 // (relative) (dir) (file.txt)
494 // "::dir:file.txt" actually means "../dir/file.txt"
495 // stored as (relative) (..) (dir) (file.txt)
496 // This is important only for the Mac as an empty dir
497 // actually means <UP>, whereas under DOS, double
498 // slashes can be ignored: "\\\\" is the same as "\\".
499 if (m_relative)
500 path.erase( 0, 1 );
501 break;
502
503 case wxPATH_VMS:
504 // TODO: what is the relative path format here?
505 m_relative = false;
506 break;
507
508 default:
509 wxFAIL_MSG( wxT("Unknown path format") );
510 // !! Fall through !!
511
512 case wxPATH_UNIX:
513 m_relative = leadingChar != wxT('/');
514 break;
515
516 case wxPATH_DOS:
517 m_relative = !IsPathSeparator(leadingChar, format);
518 break;
519
520 }
521
522 // 2) Break up the path into its members. If the original path
523 // was just "/" or "\\", m_dirs will be empty. We know from
524 // the m_relative field, if this means "nothing" or "root dir".
525
526 wxStringTokenizer tn( path, GetPathSeparators(format) );
527
528 while ( tn.HasMoreTokens() )
529 {
530 wxString token = tn.GetNextToken();
531
532 // Remove empty token under DOS and Unix, interpret them
533 // as .. under Mac.
534 if (token.empty())
535 {
536 if (format == wxPATH_MAC)
537 m_dirs.Add( wxT("..") );
538 // else ignore
539 }
540 else
541 {
542 m_dirs.Add( token );
543 }
544 }
545 }
546
547 void wxFileName::Assign(const wxString& fullpath,
548 wxPathFormat format)
549 {
550 wxString volume, path, name, ext;
551 bool hasExt;
552 SplitPath(fullpath, &volume, &path, &name, &ext, &hasExt, format);
553
554 Assign(volume, path, name, ext, hasExt, format);
555 }
556
557 void wxFileName::Assign(const wxString& fullpathOrig,
558 const wxString& fullname,
559 wxPathFormat format)
560 {
561 // always recognize fullpath as directory, even if it doesn't end with a
562 // slash
563 wxString fullpath = fullpathOrig;
564 if ( !fullpath.empty() && !wxEndsWithPathSeparator(fullpath) )
565 {
566 fullpath += GetPathSeparator(format);
567 }
568
569 wxString volume, path, name, ext;
570 bool hasExt;
571
572 // do some consistency checks: the name should be really just the filename
573 // and the path should be really just a path
574 wxString volDummy, pathDummy, nameDummy, extDummy;
575
576 SplitPath(fullname, &volDummy, &pathDummy, &name, &ext, &hasExt, format);
577
578 wxASSERT_MSG( volDummy.empty() && pathDummy.empty(),
579 wxT("the file name shouldn't contain the path") );
580
581 SplitPath(fullpath, &volume, &path, &nameDummy, &extDummy, format);
582
583 #ifndef __VMS
584 // This test makes no sense on an OpenVMS system.
585 wxASSERT_MSG( nameDummy.empty() && extDummy.empty(),
586 wxT("the path shouldn't contain file name nor extension") );
587 #endif
588 Assign(volume, path, name, ext, hasExt, format);
589 }
590
591 void wxFileName::Assign(const wxString& pathOrig,
592 const wxString& name,
593 const wxString& ext,
594 wxPathFormat format)
595 {
596 wxString volume,
597 path;
598 SplitVolume(pathOrig, &volume, &path, format);
599
600 Assign(volume, path, name, ext, format);
601 }
602
603 void wxFileName::AssignDir(const wxString& dir, wxPathFormat format)
604 {
605 Assign(dir, wxEmptyString, format);
606 }
607
608 void wxFileName::Clear()
609 {
610 m_dirs.Clear();
611
612 m_volume =
613 m_name =
614 m_ext = wxEmptyString;
615
616 // we don't have any absolute path for now
617 m_relative = true;
618
619 // nor any extension
620 m_hasExt = false;
621
622 // follow symlinks by default
623 m_dontFollowLinks = false;
624 }
625
626 /* static */
627 wxFileName wxFileName::FileName(const wxString& file, wxPathFormat format)
628 {
629 return wxFileName(file, format);
630 }
631
632 /* static */
633 wxFileName wxFileName::DirName(const wxString& dir, wxPathFormat format)
634 {
635 wxFileName fn;
636 fn.AssignDir(dir, format);
637 return fn;
638 }
639
640 // ----------------------------------------------------------------------------
641 // existence tests
642 // ----------------------------------------------------------------------------
643
644 namespace
645 {
646
647 #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 // The following lines are necessary under WinCE
1707 // #include "wx/msw/private.h"
1708 // #include <ole2.h>
1709 #include <shlobj.h>
1710 #if defined(__WXWINCE__)
1711 #include <shlguid.h>
1712 #endif
1713
1714 bool wxFileName::GetShortcutTarget(const wxString& shortcutPath,
1715 wxString& targetFilename,
1716 wxString* arguments) const
1717 {
1718 wxString path, file, ext;
1719 wxFileName::SplitPath(shortcutPath, & path, & file, & ext);
1720
1721 HRESULT hres;
1722 IShellLink* psl;
1723 bool success = false;
1724
1725 // Assume it's not a shortcut if it doesn't end with lnk
1726 if (ext.CmpNoCase(wxT("lnk"))!=0)
1727 return false;
1728
1729 // create a ShellLink object
1730 hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
1731 IID_IShellLink, (LPVOID*) &psl);
1732
1733 if (SUCCEEDED(hres))
1734 {
1735 IPersistFile* ppf;
1736 hres = psl->QueryInterface( IID_IPersistFile, (LPVOID *) &ppf);
1737 if (SUCCEEDED(hres))
1738 {
1739 WCHAR wsz[MAX_PATH];
1740
1741 MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, shortcutPath.mb_str(), -1, wsz,
1742 MAX_PATH);
1743
1744 hres = ppf->Load(wsz, 0);
1745 ppf->Release();
1746
1747 if (SUCCEEDED(hres))
1748 {
1749 wxChar buf[2048];
1750 // Wrong prototype in early versions
1751 #if defined(__MINGW32__) && !wxCHECK_W32API_VERSION(2, 2)
1752 psl->GetPath((CHAR*) buf, 2048, NULL, SLGP_UNCPRIORITY);
1753 #else
1754 psl->GetPath(buf, 2048, NULL, SLGP_UNCPRIORITY);
1755 #endif
1756 targetFilename = wxString(buf);
1757 success = (shortcutPath != targetFilename);
1758
1759 psl->GetArguments(buf, 2048);
1760 wxString args(buf);
1761 if (!args.empty() && arguments)
1762 {
1763 *arguments = args;
1764 }
1765 }
1766 }
1767
1768 psl->Release();
1769 }
1770 return success;
1771 }
1772
1773 #endif // __WIN32__ && !__WXWINCE__
1774
1775
1776 // ----------------------------------------------------------------------------
1777 // absolute/relative paths
1778 // ----------------------------------------------------------------------------
1779
1780 bool wxFileName::IsAbsolute(wxPathFormat format) const
1781 {
1782 // unix paths beginning with ~ are reported as being absolute
1783 if ( format == wxPATH_UNIX )
1784 {
1785 if ( !m_dirs.IsEmpty() )
1786 {
1787 wxString dir = m_dirs[0u];
1788
1789 if (!dir.empty() && dir[0u] == wxT('~'))
1790 return true;
1791 }
1792 }
1793
1794 // if our path doesn't start with a path separator, it's not an absolute
1795 // path
1796 if ( m_relative )
1797 return false;
1798
1799 if ( !GetVolumeSeparator(format).empty() )
1800 {
1801 // this format has volumes and an absolute path must have one, it's not
1802 // enough to have the full path to be an absolute file under Windows
1803 if ( GetVolume().empty() )
1804 return false;
1805 }
1806
1807 return true;
1808 }
1809
1810 bool wxFileName::MakeRelativeTo(const wxString& pathBase, wxPathFormat format)
1811 {
1812 wxFileName fnBase = wxFileName::DirName(pathBase, format);
1813
1814 // get cwd only once - small time saving
1815 wxString cwd = wxGetCwd();
1816 Normalize(wxPATH_NORM_ALL & ~wxPATH_NORM_CASE, cwd, format);
1817 fnBase.Normalize(wxPATH_NORM_ALL & ~wxPATH_NORM_CASE, cwd, format);
1818
1819 bool withCase = IsCaseSensitive(format);
1820
1821 // we can't do anything if the files live on different volumes
1822 if ( !GetVolume().IsSameAs(fnBase.GetVolume(), withCase) )
1823 {
1824 // nothing done
1825 return false;
1826 }
1827
1828 // same drive, so we don't need our volume
1829 m_volume.clear();
1830
1831 // remove common directories starting at the top
1832 while ( !m_dirs.IsEmpty() && !fnBase.m_dirs.IsEmpty() &&
1833 m_dirs[0u].IsSameAs(fnBase.m_dirs[0u], withCase) )
1834 {
1835 m_dirs.RemoveAt(0);
1836 fnBase.m_dirs.RemoveAt(0);
1837 }
1838
1839 // add as many ".." as needed
1840 size_t count = fnBase.m_dirs.GetCount();
1841 for ( size_t i = 0; i < count; i++ )
1842 {
1843 m_dirs.Insert(wxT(".."), 0u);
1844 }
1845
1846 if ( format == wxPATH_UNIX || format == wxPATH_DOS )
1847 {
1848 // a directory made relative with respect to itself is '.' under Unix
1849 // and DOS, by definition (but we don't have to insert "./" for the
1850 // files)
1851 if ( m_dirs.IsEmpty() && IsDir() )
1852 {
1853 m_dirs.Add(wxT('.'));
1854 }
1855 }
1856
1857 m_relative = true;
1858
1859 // we were modified
1860 return true;
1861 }
1862
1863 // ----------------------------------------------------------------------------
1864 // filename kind tests
1865 // ----------------------------------------------------------------------------
1866
1867 bool wxFileName::SameAs(const wxFileName& filepath, wxPathFormat format) const
1868 {
1869 wxFileName fn1 = *this,
1870 fn2 = filepath;
1871
1872 // get cwd only once - small time saving
1873 wxString cwd = wxGetCwd();
1874 fn1.Normalize(wxPATH_NORM_ALL | wxPATH_NORM_CASE, cwd, format);
1875 fn2.Normalize(wxPATH_NORM_ALL | wxPATH_NORM_CASE, cwd, format);
1876
1877 if ( fn1.GetFullPath() == fn2.GetFullPath() )
1878 return true;
1879
1880 #if defined(__UNIX__)
1881 wxStructStat st1, st2;
1882 if ( StatAny(st1, fn1) && StatAny(st2, fn2) )
1883 {
1884 if ( st1.st_ino == st2.st_ino && st1.st_dev == st2.st_dev )
1885 return true;
1886 }
1887 //else: It's not an error if one or both files don't exist.
1888 #endif // defined __UNIX__
1889
1890 return false;
1891 }
1892
1893 /* static */
1894 bool wxFileName::IsCaseSensitive( wxPathFormat format )
1895 {
1896 // only Unix filenames are truly case-sensitive
1897 return GetFormat(format) == wxPATH_UNIX;
1898 }
1899
1900 /* static */
1901 wxString wxFileName::GetForbiddenChars(wxPathFormat format)
1902 {
1903 // Inits to forbidden characters that are common to (almost) all platforms.
1904 wxString strForbiddenChars = wxT("*?");
1905
1906 // If asserts, wxPathFormat has been changed. In case of a new path format
1907 // addition, the following code might have to be updated.
1908 wxCOMPILE_TIME_ASSERT(wxPATH_MAX == 5, wxPathFormatChanged);
1909 switch ( GetFormat(format) )
1910 {
1911 default :
1912 wxFAIL_MSG( wxT("Unknown path format") );
1913 // !! Fall through !!
1914
1915 case wxPATH_UNIX:
1916 break;
1917
1918 case wxPATH_MAC:
1919 // On a Mac even names with * and ? are allowed (Tested with OS
1920 // 9.2.1 and OS X 10.2.5)
1921 strForbiddenChars = wxEmptyString;
1922 break;
1923
1924 case wxPATH_DOS:
1925 strForbiddenChars += wxT("\\/:\"<>|");
1926 break;
1927
1928 case wxPATH_VMS:
1929 break;
1930 }
1931
1932 return strForbiddenChars;
1933 }
1934
1935 /* static */
1936 wxString wxFileName::GetVolumeSeparator(wxPathFormat WXUNUSED_IN_WINCE(format))
1937 {
1938 #ifdef __WXWINCE__
1939 return wxEmptyString;
1940 #else
1941 wxString sepVol;
1942
1943 if ( (GetFormat(format) == wxPATH_DOS) ||
1944 (GetFormat(format) == wxPATH_VMS) )
1945 {
1946 sepVol = wxFILE_SEP_DSK;
1947 }
1948 //else: leave empty
1949
1950 return sepVol;
1951 #endif
1952 }
1953
1954 /* static */
1955 wxString wxFileName::GetPathSeparators(wxPathFormat format)
1956 {
1957 wxString seps;
1958 switch ( GetFormat(format) )
1959 {
1960 case wxPATH_DOS:
1961 // accept both as native APIs do but put the native one first as
1962 // this is the one we use in GetFullPath()
1963 seps << wxFILE_SEP_PATH_DOS << wxFILE_SEP_PATH_UNIX;
1964 break;
1965
1966 default:
1967 wxFAIL_MSG( wxT("Unknown wxPATH_XXX style") );
1968 // fall through
1969
1970 case wxPATH_UNIX:
1971 seps = wxFILE_SEP_PATH_UNIX;
1972 break;
1973
1974 case wxPATH_MAC:
1975 seps = wxFILE_SEP_PATH_MAC;
1976 break;
1977
1978 case wxPATH_VMS:
1979 seps = wxFILE_SEP_PATH_VMS;
1980 break;
1981 }
1982
1983 return seps;
1984 }
1985
1986 /* static */
1987 wxString wxFileName::GetPathTerminators(wxPathFormat format)
1988 {
1989 format = GetFormat(format);
1990
1991 // under VMS the end of the path is ']', not the path separator used to
1992 // separate the components
1993 return format == wxPATH_VMS ? wxString(wxT(']')) : GetPathSeparators(format);
1994 }
1995
1996 /* static */
1997 bool wxFileName::IsPathSeparator(wxChar ch, wxPathFormat format)
1998 {
1999 // wxString::Find() doesn't work as expected with NUL - it will always find
2000 // it, so test for it separately
2001 return ch != wxT('\0') && GetPathSeparators(format).Find(ch) != wxNOT_FOUND;
2002 }
2003
2004 /* static */
2005 bool
2006 wxFileName::IsMSWUniqueVolumeNamePath(const wxString& path, wxPathFormat format)
2007 {
2008 // return true if the format used is the DOS/Windows one and the string begins
2009 // with a Windows unique volume name ("\\?\Volume{guid}\")
2010 return format == wxPATH_DOS &&
2011 path.length() >= wxMSWUniqueVolumePrefixLength &&
2012 path.StartsWith(wxS("\\\\?\\Volume{")) &&
2013 path[wxMSWUniqueVolumePrefixLength - 1] == wxFILE_SEP_PATH_DOS;
2014 }
2015
2016 // ----------------------------------------------------------------------------
2017 // path components manipulation
2018 // ----------------------------------------------------------------------------
2019
2020 /* static */ bool wxFileName::IsValidDirComponent(const wxString& dir)
2021 {
2022 if ( dir.empty() )
2023 {
2024 wxFAIL_MSG( wxT("empty directory passed to wxFileName::InsertDir()") );
2025
2026 return false;
2027 }
2028
2029 const size_t len = dir.length();
2030 for ( size_t n = 0; n < len; n++ )
2031 {
2032 if ( dir[n] == GetVolumeSeparator() || IsPathSeparator(dir[n]) )
2033 {
2034 wxFAIL_MSG( wxT("invalid directory component in wxFileName") );
2035
2036 return false;
2037 }
2038 }
2039
2040 return true;
2041 }
2042
2043 void wxFileName::AppendDir( const wxString& dir )
2044 {
2045 if ( IsValidDirComponent(dir) )
2046 m_dirs.Add( dir );
2047 }
2048
2049 void wxFileName::PrependDir( const wxString& dir )
2050 {
2051 InsertDir(0, dir);
2052 }
2053
2054 void wxFileName::InsertDir(size_t before, const wxString& dir)
2055 {
2056 if ( IsValidDirComponent(dir) )
2057 m_dirs.Insert(dir, before);
2058 }
2059
2060 void wxFileName::RemoveDir(size_t pos)
2061 {
2062 m_dirs.RemoveAt(pos);
2063 }
2064
2065 // ----------------------------------------------------------------------------
2066 // accessors
2067 // ----------------------------------------------------------------------------
2068
2069 void wxFileName::SetFullName(const wxString& fullname)
2070 {
2071 SplitPath(fullname, NULL /* no volume */, NULL /* no path */,
2072 &m_name, &m_ext, &m_hasExt);
2073 }
2074
2075 wxString wxFileName::GetFullName() const
2076 {
2077 wxString fullname = m_name;
2078 if ( m_hasExt )
2079 {
2080 fullname << wxFILE_SEP_EXT << m_ext;
2081 }
2082
2083 return fullname;
2084 }
2085
2086 wxString wxFileName::GetPath( int flags, wxPathFormat format ) const
2087 {
2088 format = GetFormat( format );
2089
2090 wxString fullpath;
2091
2092 // return the volume with the path as well if requested
2093 if ( flags & wxPATH_GET_VOLUME )
2094 {
2095 fullpath += wxGetVolumeString(GetVolume(), format);
2096 }
2097
2098 // the leading character
2099 switch ( format )
2100 {
2101 case wxPATH_MAC:
2102 if ( m_relative )
2103 fullpath += wxFILE_SEP_PATH_MAC;
2104 break;
2105
2106 case wxPATH_DOS:
2107 if ( !m_relative )
2108 fullpath += wxFILE_SEP_PATH_DOS;
2109 break;
2110
2111 default:
2112 wxFAIL_MSG( wxT("Unknown path format") );
2113 // fall through
2114
2115 case wxPATH_UNIX:
2116 if ( !m_relative )
2117 {
2118 fullpath += wxFILE_SEP_PATH_UNIX;
2119 }
2120 break;
2121
2122 case wxPATH_VMS:
2123 // no leading character here but use this place to unset
2124 // wxPATH_GET_SEPARATOR flag: under VMS it doesn't make sense
2125 // as, if I understand correctly, there should never be a dot
2126 // before the closing bracket
2127 flags &= ~wxPATH_GET_SEPARATOR;
2128 }
2129
2130 if ( m_dirs.empty() )
2131 {
2132 // there is nothing more
2133 return fullpath;
2134 }
2135
2136 // then concatenate all the path components using the path separator
2137 if ( format == wxPATH_VMS )
2138 {
2139 fullpath += wxT('[');
2140 }
2141
2142 const size_t dirCount = m_dirs.GetCount();
2143 for ( size_t i = 0; i < dirCount; i++ )
2144 {
2145 switch (format)
2146 {
2147 case wxPATH_MAC:
2148 if ( m_dirs[i] == wxT(".") )
2149 {
2150 // skip appending ':', this shouldn't be done in this
2151 // case as "::" is interpreted as ".." under Unix
2152 continue;
2153 }
2154
2155 // convert back from ".." to nothing
2156 if ( !m_dirs[i].IsSameAs(wxT("..")) )
2157 fullpath += m_dirs[i];
2158 break;
2159
2160 default:
2161 wxFAIL_MSG( wxT("Unexpected path format") );
2162 // still fall through
2163
2164 case wxPATH_DOS:
2165 case wxPATH_UNIX:
2166 fullpath += m_dirs[i];
2167 break;
2168
2169 case wxPATH_VMS:
2170 // TODO: What to do with ".." under VMS
2171
2172 // convert back from ".." to nothing
2173 if ( !m_dirs[i].IsSameAs(wxT("..")) )
2174 fullpath += m_dirs[i];
2175 break;
2176 }
2177
2178 if ( (flags & wxPATH_GET_SEPARATOR) || (i != dirCount - 1) )
2179 fullpath += GetPathSeparator(format);
2180 }
2181
2182 if ( format == wxPATH_VMS )
2183 {
2184 fullpath += wxT(']');
2185 }
2186
2187 return fullpath;
2188 }
2189
2190 wxString wxFileName::GetFullPath( wxPathFormat format ) const
2191 {
2192 // we already have a function to get the path
2193 wxString fullpath = GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR,
2194 format);
2195
2196 // now just add the file name and extension to it
2197 fullpath += GetFullName();
2198
2199 return fullpath;
2200 }
2201
2202 // Return the short form of the path (returns identity on non-Windows platforms)
2203 wxString wxFileName::GetShortPath() const
2204 {
2205 wxString path(GetFullPath());
2206
2207 #if defined(__WINDOWS__) && defined(__WIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
2208 DWORD sz = ::GetShortPathName(path.t_str(), NULL, 0);
2209 if ( sz != 0 )
2210 {
2211 wxString pathOut;
2212 if ( ::GetShortPathName
2213 (
2214 path.t_str(),
2215 wxStringBuffer(pathOut, sz),
2216 sz
2217 ) != 0 )
2218 {
2219 return pathOut;
2220 }
2221 }
2222 #endif // Windows
2223
2224 return path;
2225 }
2226
2227 // Return the long form of the path (returns identity on non-Windows platforms)
2228 wxString wxFileName::GetLongPath() const
2229 {
2230 wxString pathOut,
2231 path = GetFullPath();
2232
2233 #if defined(__WIN32__) && !defined(__WXWINCE__) && !defined(__WXMICROWIN__)
2234
2235 #if wxUSE_DYNLIB_CLASS
2236 typedef DWORD (WINAPI *GET_LONG_PATH_NAME)(const wxChar *, wxChar *, DWORD);
2237
2238 // this is MT-safe as in the worst case we're going to resolve the function
2239 // twice -- but as the result is the same in both threads, it's ok
2240 static GET_LONG_PATH_NAME s_pfnGetLongPathName = NULL;
2241 if ( !s_pfnGetLongPathName )
2242 {
2243 static bool s_triedToLoad = false;
2244
2245 if ( !s_triedToLoad )
2246 {
2247 s_triedToLoad = true;
2248
2249 wxDynamicLibrary dllKernel(wxT("kernel32"));
2250
2251 const wxChar* GetLongPathName = wxT("GetLongPathName")
2252 #if wxUSE_UNICODE
2253 wxT("W");
2254 #else // ANSI
2255 wxT("A");
2256 #endif // Unicode/ANSI
2257
2258 if ( dllKernel.HasSymbol(GetLongPathName) )
2259 {
2260 s_pfnGetLongPathName = (GET_LONG_PATH_NAME)
2261 dllKernel.GetSymbol(GetLongPathName);
2262 }
2263
2264 // note that kernel32.dll can be unloaded, it stays in memory
2265 // anyhow as all Win32 programs link to it and so it's safe to call
2266 // GetLongPathName() even after unloading it
2267 }
2268 }
2269
2270 if ( s_pfnGetLongPathName )
2271 {
2272 DWORD dwSize = (*s_pfnGetLongPathName)(path.t_str(), NULL, 0);
2273 if ( dwSize > 0 )
2274 {
2275 if ( (*s_pfnGetLongPathName)
2276 (
2277 path.t_str(),
2278 wxStringBuffer(pathOut, dwSize),
2279 dwSize
2280 ) != 0 )
2281 {
2282 return pathOut;
2283 }
2284 }
2285 }
2286 #endif // wxUSE_DYNLIB_CLASS
2287
2288 // The OS didn't support GetLongPathName, or some other error.
2289 // We need to call FindFirstFile on each component in turn.
2290
2291 WIN32_FIND_DATA findFileData;
2292 HANDLE hFind;
2293
2294 if ( HasVolume() )
2295 pathOut = GetVolume() +
2296 GetVolumeSeparator(wxPATH_DOS) +
2297 GetPathSeparator(wxPATH_DOS);
2298 else
2299 pathOut = wxEmptyString;
2300
2301 wxArrayString dirs = GetDirs();
2302 dirs.Add(GetFullName());
2303
2304 wxString tmpPath;
2305
2306 size_t count = dirs.GetCount();
2307 for ( size_t i = 0; i < count; i++ )
2308 {
2309 const wxString& dir = dirs[i];
2310
2311 // We're using pathOut to collect the long-name path, but using a
2312 // temporary for appending the last path component which may be
2313 // short-name
2314 tmpPath = pathOut + dir;
2315
2316 // We must not process "." or ".." here as they would be (unexpectedly)
2317 // replaced by the corresponding directory names so just leave them
2318 // alone
2319 //
2320 // And we can't pass a drive and root dir to FindFirstFile (VZ: why?)
2321 if ( tmpPath.empty() || dir == '.' || dir == ".." ||
2322 tmpPath.Last() == GetVolumeSeparator(wxPATH_DOS) )
2323 {
2324 tmpPath += wxFILE_SEP_PATH;
2325 pathOut = tmpPath;
2326 continue;
2327 }
2328
2329 hFind = ::FindFirstFile(tmpPath.t_str(), &findFileData);
2330 if (hFind == INVALID_HANDLE_VALUE)
2331 {
2332 // Error: most likely reason is that path doesn't exist, so
2333 // append any unprocessed parts and return
2334 for ( i += 1; i < count; i++ )
2335 tmpPath += wxFILE_SEP_PATH + dirs[i];
2336
2337 return tmpPath;
2338 }
2339
2340 pathOut += findFileData.cFileName;
2341 if ( (i < (count-1)) )
2342 pathOut += wxFILE_SEP_PATH;
2343
2344 ::FindClose(hFind);
2345 }
2346 #else // !Win32
2347 pathOut = path;
2348 #endif // Win32/!Win32
2349
2350 return pathOut;
2351 }
2352
2353 wxPathFormat wxFileName::GetFormat( wxPathFormat format )
2354 {
2355 if (format == wxPATH_NATIVE)
2356 {
2357 #if defined(__WINDOWS__) || defined(__OS2__) || defined(__DOS__)
2358 format = wxPATH_DOS;
2359 #elif defined(__VMS)
2360 format = wxPATH_VMS;
2361 #else
2362 format = wxPATH_UNIX;
2363 #endif
2364 }
2365 return format;
2366 }
2367
2368 #ifdef wxHAS_FILESYSTEM_VOLUMES
2369
2370 /* static */
2371 wxString wxFileName::GetVolumeString(char drive, int flags)
2372 {
2373 wxASSERT_MSG( !(flags & ~wxPATH_GET_SEPARATOR), "invalid flag specified" );
2374
2375 wxString vol(drive);
2376 vol += wxFILE_SEP_DSK;
2377 if ( flags & wxPATH_GET_SEPARATOR )
2378 vol += wxFILE_SEP_PATH;
2379
2380 return vol;
2381 }
2382
2383 #endif // wxHAS_FILESYSTEM_VOLUMES
2384
2385 // ----------------------------------------------------------------------------
2386 // path splitting function
2387 // ----------------------------------------------------------------------------
2388
2389 /* static */
2390 void
2391 wxFileName::SplitVolume(const wxString& fullpathWithVolume,
2392 wxString *pstrVolume,
2393 wxString *pstrPath,
2394 wxPathFormat format)
2395 {
2396 format = GetFormat(format);
2397
2398 wxString fullpath = fullpathWithVolume;
2399
2400 if ( IsMSWUniqueVolumeNamePath(fullpath, format) )
2401 {
2402 // special Windows unique volume names hack: transform
2403 // \\?\Volume{guid}\path into Volume{guid}:path
2404 // note: this check must be done before the check for UNC path
2405
2406 // we know the last backslash from the unique volume name is located
2407 // there from IsMSWUniqueVolumeNamePath
2408 fullpath[wxMSWUniqueVolumePrefixLength - 1] = wxFILE_SEP_DSK;
2409
2410 // paths starting with a unique volume name should always be absolute
2411 fullpath.insert(wxMSWUniqueVolumePrefixLength, 1, wxFILE_SEP_PATH_DOS);
2412
2413 // remove the leading "\\?\" part
2414 fullpath.erase(0, 4);
2415 }
2416 else if ( IsUNCPath(fullpath, format) )
2417 {
2418 // special Windows UNC paths hack: transform \\share\path into share:path
2419
2420 fullpath.erase(0, 2);
2421
2422 size_t posFirstSlash =
2423 fullpath.find_first_of(GetPathTerminators(format));
2424 if ( posFirstSlash != wxString::npos )
2425 {
2426 fullpath[posFirstSlash] = wxFILE_SEP_DSK;
2427
2428 // UNC paths are always absolute, right? (FIXME)
2429 fullpath.insert(posFirstSlash + 1, 1, wxFILE_SEP_PATH_DOS);
2430 }
2431 }
2432
2433 // We separate the volume here
2434 if ( format == wxPATH_DOS || format == wxPATH_VMS )
2435 {
2436 wxString sepVol = GetVolumeSeparator(format);
2437
2438 // we have to exclude the case of a colon in the very beginning of the
2439 // string as it can't be a volume separator (nor can this be a valid
2440 // DOS file name at all but we'll leave dealing with this to our caller)
2441 size_t posFirstColon = fullpath.find_first_of(sepVol);
2442 if ( posFirstColon && posFirstColon != wxString::npos )
2443 {
2444 if ( pstrVolume )
2445 {
2446 *pstrVolume = fullpath.Left(posFirstColon);
2447 }
2448
2449 // remove the volume name and the separator from the full path
2450 fullpath.erase(0, posFirstColon + sepVol.length());
2451 }
2452 }
2453
2454 if ( pstrPath )
2455 *pstrPath = fullpath;
2456 }
2457
2458 /* static */
2459 void wxFileName::SplitPath(const wxString& fullpathWithVolume,
2460 wxString *pstrVolume,
2461 wxString *pstrPath,
2462 wxString *pstrName,
2463 wxString *pstrExt,
2464 bool *hasExt,
2465 wxPathFormat format)
2466 {
2467 format = GetFormat(format);
2468
2469 wxString fullpath;
2470 SplitVolume(fullpathWithVolume, pstrVolume, &fullpath, format);
2471
2472 // find the positions of the last dot and last path separator in the path
2473 size_t posLastDot = fullpath.find_last_of(wxFILE_SEP_EXT);
2474 size_t posLastSlash = fullpath.find_last_of(GetPathTerminators(format));
2475
2476 // check whether this dot occurs at the very beginning of a path component
2477 if ( (posLastDot != wxString::npos) &&
2478 (posLastDot == 0 ||
2479 IsPathSeparator(fullpath[posLastDot - 1]) ||
2480 (format == wxPATH_VMS && fullpath[posLastDot - 1] == wxT(']'))) )
2481 {
2482 // dot may be (and commonly -- at least under Unix -- is) the first
2483 // character of the filename, don't treat the entire filename as
2484 // extension in this case
2485 posLastDot = wxString::npos;
2486 }
2487
2488 // if we do have a dot and a slash, check that the dot is in the name part
2489 if ( (posLastDot != wxString::npos) &&
2490 (posLastSlash != wxString::npos) &&
2491 (posLastDot < posLastSlash) )
2492 {
2493 // the dot is part of the path, not the start of the extension
2494 posLastDot = wxString::npos;
2495 }
2496
2497 // now fill in the variables provided by user
2498 if ( pstrPath )
2499 {
2500 if ( posLastSlash == wxString::npos )
2501 {
2502 // no path at all
2503 pstrPath->Empty();
2504 }
2505 else
2506 {
2507 // take everything up to the path separator but take care to make
2508 // the path equal to something like '/', not empty, for the files
2509 // immediately under root directory
2510 size_t len = posLastSlash;
2511
2512 // this rule does not apply to mac since we do not start with colons (sep)
2513 // except for relative paths
2514 if ( !len && format != wxPATH_MAC)
2515 len++;
2516
2517 *pstrPath = fullpath.Left(len);
2518
2519 // special VMS hack: remove the initial bracket
2520 if ( format == wxPATH_VMS )
2521 {
2522 if ( (*pstrPath)[0u] == wxT('[') )
2523 pstrPath->erase(0, 1);
2524 }
2525 }
2526 }
2527
2528 if ( pstrName )
2529 {
2530 // take all characters starting from the one after the last slash and
2531 // up to, but excluding, the last dot
2532 size_t nStart = posLastSlash == wxString::npos ? 0 : posLastSlash + 1;
2533 size_t count;
2534 if ( posLastDot == wxString::npos )
2535 {
2536 // take all until the end
2537 count = wxString::npos;
2538 }
2539 else if ( posLastSlash == wxString::npos )
2540 {
2541 count = posLastDot;
2542 }
2543 else // have both dot and slash
2544 {
2545 count = posLastDot - posLastSlash - 1;
2546 }
2547
2548 *pstrName = fullpath.Mid(nStart, count);
2549 }
2550
2551 // finally deal with the extension here: we have an added complication that
2552 // extension may be empty (but present) as in "foo." where trailing dot
2553 // indicates the empty extension at the end -- and hence we must remember
2554 // that we have it independently of pstrExt
2555 if ( posLastDot == wxString::npos )
2556 {
2557 // no extension
2558 if ( pstrExt )
2559 pstrExt->clear();
2560 if ( hasExt )
2561 *hasExt = false;
2562 }
2563 else
2564 {
2565 // take everything after the dot
2566 if ( pstrExt )
2567 *pstrExt = fullpath.Mid(posLastDot + 1);
2568 if ( hasExt )
2569 *hasExt = true;
2570 }
2571 }
2572
2573 /* static */
2574 void wxFileName::SplitPath(const wxString& fullpath,
2575 wxString *path,
2576 wxString *name,
2577 wxString *ext,
2578 wxPathFormat format)
2579 {
2580 wxString volume;
2581 SplitPath(fullpath, &volume, path, name, ext, format);
2582
2583 if ( path )
2584 {
2585 path->Prepend(wxGetVolumeString(volume, format));
2586 }
2587 }
2588
2589 /* static */
2590 wxString wxFileName::StripExtension(const wxString& fullpath)
2591 {
2592 wxFileName fn(fullpath);
2593 fn.SetExt("");
2594 return fn.GetFullPath();
2595 }
2596
2597 // ----------------------------------------------------------------------------
2598 // time functions
2599 // ----------------------------------------------------------------------------
2600
2601 #if wxUSE_DATETIME
2602
2603 bool wxFileName::SetTimes(const wxDateTime *dtAccess,
2604 const wxDateTime *dtMod,
2605 const wxDateTime *dtCreate) const
2606 {
2607 #if defined(__WIN32__)
2608 FILETIME ftAccess, ftCreate, ftWrite;
2609
2610 if ( dtCreate )
2611 ConvertWxToFileTime(&ftCreate, *dtCreate);
2612 if ( dtAccess )
2613 ConvertWxToFileTime(&ftAccess, *dtAccess);
2614 if ( dtMod )
2615 ConvertWxToFileTime(&ftWrite, *dtMod);
2616
2617 wxString path;
2618 int flags;
2619 if ( IsDir() )
2620 {
2621 if ( wxGetOsVersion() == wxOS_WINDOWS_9X )
2622 {
2623 wxLogError(_("Setting directory access times is not supported "
2624 "under this OS version"));
2625 return false;
2626 }
2627
2628 path = GetPath();
2629 flags = FILE_FLAG_BACKUP_SEMANTICS;
2630 }
2631 else // file
2632 {
2633 path = GetFullPath();
2634 flags = 0;
2635 }
2636
2637 wxFileHandle fh(path, wxFileHandle::WriteAttr, flags);
2638 if ( fh.IsOk() )
2639 {
2640 if ( ::SetFileTime(fh,
2641 dtCreate ? &ftCreate : NULL,
2642 dtAccess ? &ftAccess : NULL,
2643 dtMod ? &ftWrite : NULL) )
2644 {
2645 return true;
2646 }
2647 }
2648 #elif defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
2649 wxUnusedVar(dtCreate);
2650
2651 if ( !dtAccess && !dtMod )
2652 {
2653 // can't modify the creation time anyhow, don't try
2654 return true;
2655 }
2656
2657 // if dtAccess or dtMod is not specified, use the other one (which must be
2658 // non NULL because of the test above) for both times
2659 utimbuf utm;
2660 utm.actime = dtAccess ? dtAccess->GetTicks() : dtMod->GetTicks();
2661 utm.modtime = dtMod ? dtMod->GetTicks() : dtAccess->GetTicks();
2662 if ( utime(GetFullPath().fn_str(), &utm) == 0 )
2663 {
2664 return true;
2665 }
2666 #else // other platform
2667 wxUnusedVar(dtAccess);
2668 wxUnusedVar(dtMod);
2669 wxUnusedVar(dtCreate);
2670 #endif // platforms
2671
2672 wxLogSysError(_("Failed to modify file times for '%s'"),
2673 GetFullPath().c_str());
2674
2675 return false;
2676 }
2677
2678 bool wxFileName::Touch() const
2679 {
2680 #if defined(__UNIX_LIKE__)
2681 // under Unix touching file is simple: just pass NULL to utime()
2682 if ( utime(GetFullPath().fn_str(), NULL) == 0 )
2683 {
2684 return true;
2685 }
2686
2687 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
2688
2689 return false;
2690 #else // other platform
2691 wxDateTime dtNow = wxDateTime::Now();
2692
2693 return SetTimes(&dtNow, &dtNow, NULL /* don't change create time */);
2694 #endif // platforms
2695 }
2696
2697 bool wxFileName::GetTimes(wxDateTime *dtAccess,
2698 wxDateTime *dtMod,
2699 wxDateTime *dtCreate) const
2700 {
2701 #if defined(__WIN32__)
2702 // we must use different methods for the files and directories under
2703 // Windows as CreateFile(GENERIC_READ) doesn't work for the directories and
2704 // CreateFile(FILE_FLAG_BACKUP_SEMANTICS) works -- but only under NT and
2705 // not 9x
2706 bool ok;
2707 FILETIME ftAccess, ftCreate, ftWrite;
2708 if ( IsDir() )
2709 {
2710 // implemented in msw/dir.cpp
2711 extern bool wxGetDirectoryTimes(const wxString& dirname,
2712 FILETIME *, FILETIME *, FILETIME *);
2713
2714 // we should pass the path without the trailing separator to
2715 // wxGetDirectoryTimes()
2716 ok = wxGetDirectoryTimes(GetPath(wxPATH_GET_VOLUME),
2717 &ftAccess, &ftCreate, &ftWrite);
2718 }
2719 else // file
2720 {
2721 wxFileHandle fh(GetFullPath(), wxFileHandle::ReadAttr);
2722 if ( fh.IsOk() )
2723 {
2724 ok = ::GetFileTime(fh,
2725 dtCreate ? &ftCreate : NULL,
2726 dtAccess ? &ftAccess : NULL,
2727 dtMod ? &ftWrite : NULL) != 0;
2728 }
2729 else
2730 {
2731 ok = false;
2732 }
2733 }
2734
2735 if ( ok )
2736 {
2737 if ( dtCreate )
2738 ConvertFileTimeToWx(dtCreate, ftCreate);
2739 if ( dtAccess )
2740 ConvertFileTimeToWx(dtAccess, ftAccess);
2741 if ( dtMod )
2742 ConvertFileTimeToWx(dtMod, ftWrite);
2743
2744 return true;
2745 }
2746 #elif defined(__UNIX_LIKE__) || defined(__WXMAC__) || defined(__OS2__) || (defined(__DOS__) && defined(__WATCOMC__))
2747 // no need to test for IsDir() here
2748 wxStructStat stBuf;
2749 if ( StatAny(stBuf, *this) )
2750 {
2751 // Android defines st_*time fields as unsigned long, but time_t as long,
2752 // hence the static_casts.
2753 if ( dtAccess )
2754 dtAccess->Set(static_cast<time_t>(stBuf.st_atime));
2755 if ( dtMod )
2756 dtMod->Set(static_cast<time_t>(stBuf.st_mtime));
2757 if ( dtCreate )
2758 dtCreate->Set(static_cast<time_t>(stBuf.st_ctime));
2759
2760 return true;
2761 }
2762 #else // other platform
2763 wxUnusedVar(dtAccess);
2764 wxUnusedVar(dtMod);
2765 wxUnusedVar(dtCreate);
2766 #endif // platforms
2767
2768 wxLogSysError(_("Failed to retrieve file times for '%s'"),
2769 GetFullPath().c_str());
2770
2771 return false;
2772 }
2773
2774 #endif // wxUSE_DATETIME
2775
2776
2777 // ----------------------------------------------------------------------------
2778 // file size functions
2779 // ----------------------------------------------------------------------------
2780
2781 #if wxUSE_LONGLONG
2782
2783 /* static */
2784 wxULongLong wxFileName::GetSize(const wxString &filename)
2785 {
2786 if (!wxFileExists(filename))
2787 return wxInvalidSize;
2788
2789 #if defined(__WIN32__)
2790 wxFileHandle f(filename, wxFileHandle::ReadAttr);
2791 if (!f.IsOk())
2792 return wxInvalidSize;
2793
2794 DWORD lpFileSizeHigh;
2795 DWORD ret = GetFileSize(f, &lpFileSizeHigh);
2796 if ( ret == INVALID_FILE_SIZE && ::GetLastError() != NO_ERROR )
2797 return wxInvalidSize;
2798
2799 return wxULongLong(lpFileSizeHigh, ret);
2800 #else // ! __WIN32__
2801 wxStructStat st;
2802 if (wxStat( filename, &st) != 0)
2803 return wxInvalidSize;
2804 return wxULongLong(st.st_size);
2805 #endif
2806 }
2807
2808 /* static */
2809 wxString wxFileName::GetHumanReadableSize(const wxULongLong &bs,
2810 const wxString &nullsize,
2811 int precision,
2812 wxSizeConvention conv)
2813 {
2814 // deal with trivial case first
2815 if ( bs == 0 || bs == wxInvalidSize )
2816 return nullsize;
2817
2818 // depending on the convention used the multiplier may be either 1000 or
2819 // 1024 and the binary infix may be empty (for "KB") or "i" (for "KiB")
2820 double multiplier = 1024.;
2821 wxString biInfix;
2822
2823 switch ( conv )
2824 {
2825 case wxSIZE_CONV_TRADITIONAL:
2826 // nothing to do, this corresponds to the default values of both
2827 // the multiplier and infix string
2828 break;
2829
2830 case wxSIZE_CONV_IEC:
2831 biInfix = "i";
2832 break;
2833
2834 case wxSIZE_CONV_SI:
2835 multiplier = 1000;
2836 break;
2837 }
2838
2839 const double kiloByteSize = multiplier;
2840 const double megaByteSize = multiplier * kiloByteSize;
2841 const double gigaByteSize = multiplier * megaByteSize;
2842 const double teraByteSize = multiplier * gigaByteSize;
2843
2844 const double bytesize = bs.ToDouble();
2845
2846 wxString result;
2847 if ( bytesize < kiloByteSize )
2848 result.Printf("%s B", bs.ToString());
2849 else if ( bytesize < megaByteSize )
2850 result.Printf("%.*f K%sB", precision, bytesize/kiloByteSize, biInfix);
2851 else if (bytesize < gigaByteSize)
2852 result.Printf("%.*f M%sB", precision, bytesize/megaByteSize, biInfix);
2853 else if (bytesize < teraByteSize)
2854 result.Printf("%.*f G%sB", precision, bytesize/gigaByteSize, biInfix);
2855 else
2856 result.Printf("%.*f T%sB", precision, bytesize/teraByteSize, biInfix);
2857
2858 return result;
2859 }
2860
2861 wxULongLong wxFileName::GetSize() const
2862 {
2863 return GetSize(GetFullPath());
2864 }
2865
2866 wxString wxFileName::GetHumanReadableSize(const wxString& failmsg,
2867 int precision,
2868 wxSizeConvention conv) const
2869 {
2870 return GetHumanReadableSize(GetSize(), failmsg, precision, conv);
2871 }
2872
2873 #endif // wxUSE_LONGLONG
2874
2875 // ----------------------------------------------------------------------------
2876 // Mac-specific functions
2877 // ----------------------------------------------------------------------------
2878
2879 #if defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON
2880
2881 namespace
2882 {
2883
2884 class MacDefaultExtensionRecord
2885 {
2886 public:
2887 MacDefaultExtensionRecord()
2888 {
2889 m_type =
2890 m_creator = 0 ;
2891 }
2892
2893 // default copy ctor, assignment operator and dtor are ok
2894
2895 MacDefaultExtensionRecord(const wxString& ext, OSType type, OSType creator)
2896 : m_ext(ext)
2897 {
2898 m_type = type;
2899 m_creator = creator;
2900 }
2901
2902 wxString m_ext;
2903 OSType m_type;
2904 OSType m_creator;
2905 };
2906
2907 WX_DECLARE_OBJARRAY(MacDefaultExtensionRecord, MacDefaultExtensionArray);
2908
2909 bool gMacDefaultExtensionsInited = false;
2910
2911 #include "wx/arrimpl.cpp"
2912
2913 WX_DEFINE_EXPORTED_OBJARRAY(MacDefaultExtensionArray);
2914
2915 MacDefaultExtensionArray gMacDefaultExtensions;
2916
2917 // load the default extensions
2918 const MacDefaultExtensionRecord gDefaults[] =
2919 {
2920 MacDefaultExtensionRecord( "txt", 'TEXT', 'ttxt' ),
2921 MacDefaultExtensionRecord( "tif", 'TIFF', '****' ),
2922 MacDefaultExtensionRecord( "jpg", 'JPEG', '****' ),
2923 };
2924
2925 void MacEnsureDefaultExtensionsLoaded()
2926 {
2927 if ( !gMacDefaultExtensionsInited )
2928 {
2929 // we could load the pc exchange prefs here too
2930 for ( size_t i = 0 ; i < WXSIZEOF( gDefaults ) ; ++i )
2931 {
2932 gMacDefaultExtensions.Add( gDefaults[i] ) ;
2933 }
2934 gMacDefaultExtensionsInited = true;
2935 }
2936 }
2937
2938 } // anonymous namespace
2939
2940 bool wxFileName::MacSetTypeAndCreator( wxUint32 type , wxUint32 creator )
2941 {
2942 FSRef fsRef ;
2943 FSCatalogInfo catInfo;
2944 FileInfo *finfo ;
2945
2946 if ( wxMacPathToFSRef( GetFullPath() , &fsRef ) == noErr )
2947 {
2948 if ( FSGetCatalogInfo (&fsRef, kFSCatInfoFinderInfo, &catInfo, NULL, NULL, NULL) == noErr )
2949 {
2950 finfo = (FileInfo*)&catInfo.finderInfo;
2951 finfo->fileType = type ;
2952 finfo->fileCreator = creator ;
2953 FSSetCatalogInfo( &fsRef, kFSCatInfoFinderInfo, &catInfo ) ;
2954 return true ;
2955 }
2956 }
2957 return false ;
2958 }
2959
2960 bool wxFileName::MacGetTypeAndCreator( wxUint32 *type , wxUint32 *creator ) const
2961 {
2962 FSRef fsRef ;
2963 FSCatalogInfo catInfo;
2964 FileInfo *finfo ;
2965
2966 if ( wxMacPathToFSRef( GetFullPath() , &fsRef ) == noErr )
2967 {
2968 if ( FSGetCatalogInfo (&fsRef, kFSCatInfoFinderInfo, &catInfo, NULL, NULL, NULL) == noErr )
2969 {
2970 finfo = (FileInfo*)&catInfo.finderInfo;
2971 *type = finfo->fileType ;
2972 *creator = finfo->fileCreator ;
2973 return true ;
2974 }
2975 }
2976 return false ;
2977 }
2978
2979 bool wxFileName::MacSetDefaultTypeAndCreator()
2980 {
2981 wxUint32 type , creator ;
2982 if ( wxFileName::MacFindDefaultTypeAndCreator(GetExt() , &type ,
2983 &creator ) )
2984 {
2985 return MacSetTypeAndCreator( type , creator ) ;
2986 }
2987 return false;
2988 }
2989
2990 bool wxFileName::MacFindDefaultTypeAndCreator( const wxString& ext , wxUint32 *type , wxUint32 *creator )
2991 {
2992 MacEnsureDefaultExtensionsLoaded() ;
2993 wxString extl = ext.Lower() ;
2994 for( int i = gMacDefaultExtensions.Count() - 1 ; i >= 0 ; --i )
2995 {
2996 if ( gMacDefaultExtensions.Item(i).m_ext == extl )
2997 {
2998 *type = gMacDefaultExtensions.Item(i).m_type ;
2999 *creator = gMacDefaultExtensions.Item(i).m_creator ;
3000 return true ;
3001 }
3002 }
3003 return false ;
3004 }
3005
3006 void wxFileName::MacRegisterDefaultTypeAndCreator( const wxString& ext , wxUint32 type , wxUint32 creator )
3007 {
3008 MacEnsureDefaultExtensionsLoaded();
3009 MacDefaultExtensionRecord rec(ext.Lower(), type, creator);
3010 gMacDefaultExtensions.Add( rec );
3011 }
3012
3013 #endif // defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON