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