]> git.saurik.com Git - wxWidgets.git/blob - src/common/filename.cpp
29cf9acb3a516c1a49e3a3c5bab09ff2aeb5ff0c
[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 // ----------------------------------------------------------------------------
736 // CWD and HOME stuff
737 // ----------------------------------------------------------------------------
738
739 void wxFileName::AssignCwd(const wxString& volume)
740 {
741 AssignDir(wxFileName::GetCwd(volume));
742 }
743
744 /* static */
745 wxString wxFileName::GetCwd(const wxString& volume)
746 {
747 // if we have the volume, we must get the current directory on this drive
748 // and to do this we have to chdir to this volume - at least under Windows,
749 // I don't know how to get the current drive on another volume elsewhere
750 // (TODO)
751 wxString cwdOld;
752 if ( !volume.empty() )
753 {
754 cwdOld = wxGetCwd();
755 SetCwd(volume + GetVolumeSeparator());
756 }
757
758 wxString cwd = ::wxGetCwd();
759
760 if ( !volume.empty() )
761 {
762 SetCwd(cwdOld);
763 }
764
765 return cwd;
766 }
767
768 bool wxFileName::SetCwd() const
769 {
770 return wxFileName::SetCwd( GetPath() );
771 }
772
773 bool wxFileName::SetCwd( const wxString &cwd )
774 {
775 return ::wxSetWorkingDirectory( cwd );
776 }
777
778 void wxFileName::AssignHomeDir()
779 {
780 AssignDir(wxFileName::GetHomeDir());
781 }
782
783 wxString wxFileName::GetHomeDir()
784 {
785 return ::wxGetHomeDir();
786 }
787
788
789 // ----------------------------------------------------------------------------
790 // CreateTempFileName
791 // ----------------------------------------------------------------------------
792
793 #if wxUSE_FILE || wxUSE_FFILE
794
795
796 #if !defined wx_fdopen && defined HAVE_FDOPEN
797 #define wx_fdopen fdopen
798 #endif
799
800 // NB: GetTempFileName() under Windows creates the file, so using
801 // O_EXCL there would fail
802 #ifdef __WINDOWS__
803 #define wxOPEN_EXCL 0
804 #else
805 #define wxOPEN_EXCL O_EXCL
806 #endif
807
808
809 #ifdef wxOpenOSFHandle
810 #define WX_HAVE_DELETE_ON_CLOSE
811 // On Windows create a file with the FILE_FLAGS_DELETE_ON_CLOSE flags.
812 //
813 static int wxOpenWithDeleteOnClose(const wxString& filename)
814 {
815 DWORD access = GENERIC_READ | GENERIC_WRITE;
816
817 DWORD disposition = OPEN_ALWAYS;
818
819 DWORD attributes = FILE_ATTRIBUTE_TEMPORARY |
820 FILE_FLAG_DELETE_ON_CLOSE;
821
822 HANDLE h = ::CreateFile(filename.fn_str(), access, 0, NULL,
823 disposition, attributes, NULL);
824
825 return wxOpenOSFHandle(h, wxO_BINARY);
826 }
827 #endif // wxOpenOSFHandle
828
829
830 // Helper to open the file
831 //
832 static int wxTempOpen(const wxString& path, bool *deleteOnClose)
833 {
834 #ifdef WX_HAVE_DELETE_ON_CLOSE
835 if (*deleteOnClose)
836 return wxOpenWithDeleteOnClose(path);
837 #endif
838
839 *deleteOnClose = false;
840
841 return wxOpen(path, wxO_BINARY | O_RDWR | O_CREAT | wxOPEN_EXCL, 0600);
842 }
843
844
845 #if wxUSE_FFILE
846 // Helper to open the file and attach it to the wxFFile
847 //
848 static bool wxTempOpen(wxFFile *file, const wxString& path, bool *deleteOnClose)
849 {
850 #ifndef wx_fdopen
851 *deleteOnClose = false;
852 return file->Open(path, wxT("w+b"));
853 #else // wx_fdopen
854 int fd = wxTempOpen(path, deleteOnClose);
855 if (fd == -1)
856 return false;
857 file->Attach(wx_fdopen(fd, "w+b"), path);
858 return file->IsOpened();
859 #endif // wx_fdopen
860 }
861 #endif // wxUSE_FFILE
862
863
864 #if !wxUSE_FILE
865 #define WXFILEARGS(x, y) y
866 #elif !wxUSE_FFILE
867 #define WXFILEARGS(x, y) x
868 #else
869 #define WXFILEARGS(x, y) x, y
870 #endif
871
872
873 // Implementation of wxFileName::CreateTempFileName().
874 //
875 static wxString wxCreateTempImpl(
876 const wxString& prefix,
877 WXFILEARGS(wxFile *fileTemp, wxFFile *ffileTemp),
878 bool *deleteOnClose = NULL)
879 {
880 #if wxUSE_FILE && wxUSE_FFILE
881 wxASSERT(fileTemp == NULL || ffileTemp == NULL);
882 #endif
883 wxString path, dir, name;
884 bool wantDeleteOnClose = false;
885
886 if (deleteOnClose)
887 {
888 // set the result to false initially
889 wantDeleteOnClose = *deleteOnClose;
890 *deleteOnClose = false;
891 }
892 else
893 {
894 // easier if it alwasys points to something
895 deleteOnClose = &wantDeleteOnClose;
896 }
897
898 // use the directory specified by the prefix
899 wxFileName::SplitPath(prefix, &dir, &name, NULL /* extension */);
900
901 if (dir.empty())
902 {
903 dir = wxFileName::GetTempDir();
904 }
905
906 #if defined(__WXWINCE__)
907 path = dir + wxT("\\") + name;
908 int i = 1;
909 while (wxFileName::FileExists(path))
910 {
911 path = dir + wxT("\\") + name ;
912 path << i;
913 i ++;
914 }
915
916 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
917 if (!::GetTempFileName(dir.t_str(), name.t_str(), 0,
918 wxStringBuffer(path, MAX_PATH + 1)))
919 {
920 wxLogLastError(wxT("GetTempFileName"));
921
922 path.clear();
923 }
924
925 #else // !Windows
926 path = dir;
927
928 if ( !wxEndsWithPathSeparator(dir) &&
929 (name.empty() || !wxIsPathSeparator(name[0u])) )
930 {
931 path += wxFILE_SEP_PATH;
932 }
933
934 path += name;
935
936 #if defined(HAVE_MKSTEMP)
937 // scratch space for mkstemp()
938 path += wxT("XXXXXX");
939
940 // we need to copy the path to the buffer in which mkstemp() can modify it
941 wxCharBuffer buf(path.fn_str());
942
943 // cast is safe because the string length doesn't change
944 int fdTemp = mkstemp( (char*)(const char*) buf );
945 if ( fdTemp == -1 )
946 {
947 // this might be not necessary as mkstemp() on most systems should have
948 // already done it but it doesn't hurt neither...
949 path.clear();
950 }
951 else // mkstemp() succeeded
952 {
953 path = wxConvFile.cMB2WX( (const char*) buf );
954
955 #if wxUSE_FILE
956 // avoid leaking the fd
957 if ( fileTemp )
958 {
959 fileTemp->Attach(fdTemp);
960 }
961 else
962 #endif
963
964 #if wxUSE_FFILE
965 if ( ffileTemp )
966 {
967 #ifdef wx_fdopen
968 ffileTemp->Attach(wx_fdopen(fdTemp, "r+b"), path);
969 #else
970 ffileTemp->Open(path, wxT("r+b"));
971 close(fdTemp);
972 #endif
973 }
974 else
975 #endif
976
977 {
978 close(fdTemp);
979 }
980 }
981 #else // !HAVE_MKSTEMP
982
983 #ifdef HAVE_MKTEMP
984 // same as above
985 path += wxT("XXXXXX");
986
987 wxCharBuffer buf = wxConvFile.cWX2MB( path );
988 if ( !mktemp( (char*)(const char*) buf ) )
989 {
990 path.clear();
991 }
992 else
993 {
994 path = wxConvFile.cMB2WX( (const char*) buf );
995 }
996 #else // !HAVE_MKTEMP (includes __DOS__)
997 // generate the unique file name ourselves
998 #if !defined(__DOS__) && (!defined(__MWERKS__) || defined(__DARWIN__) )
999 path << (unsigned int)getpid();
1000 #endif
1001
1002 wxString pathTry;
1003
1004 static const size_t numTries = 1000;
1005 for ( size_t n = 0; n < numTries; n++ )
1006 {
1007 // 3 hex digits is enough for numTries == 1000 < 4096
1008 pathTry = path + wxString::Format(wxT("%.03x"), (unsigned int) n);
1009 if ( !wxFileName::FileExists(pathTry) )
1010 {
1011 break;
1012 }
1013
1014 pathTry.clear();
1015 }
1016
1017 path = pathTry;
1018 #endif // HAVE_MKTEMP/!HAVE_MKTEMP
1019
1020 #endif // HAVE_MKSTEMP/!HAVE_MKSTEMP
1021
1022 #endif // Windows/!Windows
1023
1024 if ( path.empty() )
1025 {
1026 wxLogSysError(_("Failed to create a temporary file name"));
1027 }
1028 else
1029 {
1030 bool ok = true;
1031
1032 // open the file - of course, there is a race condition here, this is
1033 // why we always prefer using mkstemp()...
1034 #if wxUSE_FILE
1035 if ( fileTemp && !fileTemp->IsOpened() )
1036 {
1037 *deleteOnClose = wantDeleteOnClose;
1038 int fd = wxTempOpen(path, deleteOnClose);
1039 if (fd != -1)
1040 fileTemp->Attach(fd);
1041 else
1042 ok = false;
1043 }
1044 #endif
1045
1046 #if wxUSE_FFILE
1047 if ( ffileTemp && !ffileTemp->IsOpened() )
1048 {
1049 *deleteOnClose = wantDeleteOnClose;
1050 ok = wxTempOpen(ffileTemp, path, deleteOnClose);
1051 }
1052 #endif
1053
1054 if ( !ok )
1055 {
1056 // FIXME: If !ok here should we loop and try again with another
1057 // file name? That is the standard recourse if open(O_EXCL)
1058 // fails, though of course it should be protected against
1059 // possible infinite looping too.
1060
1061 wxLogError(_("Failed to open temporary file."));
1062
1063 path.clear();
1064 }
1065 }
1066
1067 return path;
1068 }
1069
1070
1071 static bool wxCreateTempImpl(
1072 const wxString& prefix,
1073 WXFILEARGS(wxFile *fileTemp, wxFFile *ffileTemp),
1074 wxString *name)
1075 {
1076 bool deleteOnClose = true;
1077
1078 *name = wxCreateTempImpl(prefix,
1079 WXFILEARGS(fileTemp, ffileTemp),
1080 &deleteOnClose);
1081
1082 bool ok = !name->empty();
1083
1084 if (deleteOnClose)
1085 name->clear();
1086 #ifdef __UNIX__
1087 else if (ok && wxRemoveFile(*name))
1088 name->clear();
1089 #endif
1090
1091 return ok;
1092 }
1093
1094
1095 static void wxAssignTempImpl(
1096 wxFileName *fn,
1097 const wxString& prefix,
1098 WXFILEARGS(wxFile *fileTemp, wxFFile *ffileTemp))
1099 {
1100 wxString tempname;
1101 tempname = wxCreateTempImpl(prefix, WXFILEARGS(fileTemp, ffileTemp));
1102
1103 if ( tempname.empty() )
1104 {
1105 // error, failed to get temp file name
1106 fn->Clear();
1107 }
1108 else // ok
1109 {
1110 fn->Assign(tempname);
1111 }
1112 }
1113
1114
1115 void wxFileName::AssignTempFileName(const wxString& prefix)
1116 {
1117 wxAssignTempImpl(this, prefix, WXFILEARGS(NULL, NULL));
1118 }
1119
1120 /* static */
1121 wxString wxFileName::CreateTempFileName(const wxString& prefix)
1122 {
1123 return wxCreateTempImpl(prefix, WXFILEARGS(NULL, NULL));
1124 }
1125
1126 #endif // wxUSE_FILE || wxUSE_FFILE
1127
1128
1129 #if wxUSE_FILE
1130
1131 wxString wxCreateTempFileName(const wxString& prefix,
1132 wxFile *fileTemp,
1133 bool *deleteOnClose)
1134 {
1135 return wxCreateTempImpl(prefix, WXFILEARGS(fileTemp, NULL), deleteOnClose);
1136 }
1137
1138 bool wxCreateTempFile(const wxString& prefix,
1139 wxFile *fileTemp,
1140 wxString *name)
1141 {
1142 return wxCreateTempImpl(prefix, WXFILEARGS(fileTemp, NULL), name);
1143 }
1144
1145 void wxFileName::AssignTempFileName(const wxString& prefix, wxFile *fileTemp)
1146 {
1147 wxAssignTempImpl(this, prefix, WXFILEARGS(fileTemp, NULL));
1148 }
1149
1150 /* static */
1151 wxString
1152 wxFileName::CreateTempFileName(const wxString& prefix, wxFile *fileTemp)
1153 {
1154 return wxCreateTempFileName(prefix, fileTemp);
1155 }
1156
1157 #endif // wxUSE_FILE
1158
1159
1160 #if wxUSE_FFILE
1161
1162 wxString wxCreateTempFileName(const wxString& prefix,
1163 wxFFile *fileTemp,
1164 bool *deleteOnClose)
1165 {
1166 return wxCreateTempImpl(prefix, WXFILEARGS(NULL, fileTemp), deleteOnClose);
1167 }
1168
1169 bool wxCreateTempFile(const wxString& prefix,
1170 wxFFile *fileTemp,
1171 wxString *name)
1172 {
1173 return wxCreateTempImpl(prefix, WXFILEARGS(NULL, fileTemp), name);
1174
1175 }
1176
1177 void wxFileName::AssignTempFileName(const wxString& prefix, wxFFile *fileTemp)
1178 {
1179 wxAssignTempImpl(this, prefix, WXFILEARGS(NULL, fileTemp));
1180 }
1181
1182 /* static */
1183 wxString
1184 wxFileName::CreateTempFileName(const wxString& prefix, wxFFile *fileTemp)
1185 {
1186 return wxCreateTempFileName(prefix, fileTemp);
1187 }
1188
1189 #endif // wxUSE_FFILE
1190
1191
1192 // ----------------------------------------------------------------------------
1193 // directory operations
1194 // ----------------------------------------------------------------------------
1195
1196 // helper of GetTempDir(): check if the given directory exists and return it if
1197 // it does or an empty string otherwise
1198 namespace
1199 {
1200
1201 wxString CheckIfDirExists(const wxString& dir)
1202 {
1203 return wxFileName::DirExists(dir) ? dir : wxString();
1204 }
1205
1206 } // anonymous namespace
1207
1208 wxString wxFileName::GetTempDir()
1209 {
1210 // first try getting it from environment: this allows overriding the values
1211 // used by default if the user wants to create temporary files in another
1212 // directory
1213 wxString dir = CheckIfDirExists(wxGetenv("TMPDIR"));
1214 if ( dir.empty() )
1215 {
1216 dir = CheckIfDirExists(wxGetenv("TMP"));
1217 if ( dir.empty() )
1218 dir = CheckIfDirExists(wxGetenv("TEMP"));
1219 }
1220
1221 // if no environment variables are set, use the system default
1222 if ( dir.empty() )
1223 {
1224 #if defined(__WXWINCE__)
1225 dir = CheckIfDirExists(wxT("\\temp"));
1226 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1227 if ( !::GetTempPath(MAX_PATH, wxStringBuffer(dir, MAX_PATH + 1)) )
1228 {
1229 wxLogLastError(wxT("GetTempPath"));
1230 }
1231 #elif defined(__WXMAC__) && wxOSX_USE_CARBON
1232 dir = wxMacFindFolderNoSeparator(short(kOnSystemDisk), kTemporaryFolderType, kCreateFolder);
1233 #endif // systems with native way
1234 }
1235 else // we got directory from an environment variable
1236 {
1237 // remove any trailing path separators, we don't want to ever return
1238 // them from this function for consistency
1239 const size_t lastNonSep = dir.find_last_not_of(GetPathSeparators());
1240 if ( lastNonSep == wxString::npos )
1241 {
1242 // the string consists entirely of separators, leave only one
1243 dir = GetPathSeparator();
1244 }
1245 else
1246 {
1247 dir.erase(lastNonSep + 1);
1248 }
1249 }
1250
1251 // fall back to hard coded value
1252 if ( dir.empty() )
1253 {
1254 #ifdef __UNIX_LIKE__
1255 dir = CheckIfDirExists("/tmp");
1256 if ( dir.empty() )
1257 #endif // __UNIX_LIKE__
1258 dir = ".";
1259 }
1260
1261 return dir;
1262 }
1263
1264 bool wxFileName::Mkdir( int perm, int flags ) const
1265 {
1266 return wxFileName::Mkdir(GetPath(), perm, flags);
1267 }
1268
1269 bool wxFileName::Mkdir( const wxString& dir, int perm, int flags )
1270 {
1271 if ( flags & wxPATH_MKDIR_FULL )
1272 {
1273 // split the path in components
1274 wxFileName filename;
1275 filename.AssignDir(dir);
1276
1277 wxString currPath;
1278 if ( filename.HasVolume())
1279 {
1280 currPath << wxGetVolumeString(filename.GetVolume(), wxPATH_NATIVE);
1281 }
1282
1283 wxArrayString dirs = filename.GetDirs();
1284 size_t count = dirs.GetCount();
1285 for ( size_t i = 0; i < count; i++ )
1286 {
1287 if ( i > 0 || filename.IsAbsolute() )
1288 currPath += wxFILE_SEP_PATH;
1289 currPath += dirs[i];
1290
1291 if (!DirExists(currPath))
1292 {
1293 if (!wxMkdir(currPath, perm))
1294 {
1295 // no need to try creating further directories
1296 return false;
1297 }
1298 }
1299 }
1300
1301 return true;
1302
1303 }
1304
1305 return ::wxMkdir( dir, perm );
1306 }
1307
1308 bool wxFileName::Rmdir(int flags) const
1309 {
1310 return wxFileName::Rmdir( GetPath(), flags );
1311 }
1312
1313 bool wxFileName::Rmdir(const wxString& dir, int flags)
1314 {
1315 #ifdef __WXMSW__
1316 if ( flags & wxPATH_RMDIR_RECURSIVE )
1317 {
1318 // SHFileOperation needs double null termination string
1319 // but without separator at the end of the path
1320 wxString path(dir);
1321 if ( path.Last() == wxFILE_SEP_PATH )
1322 path.RemoveLast();
1323 path += wxT('\0');
1324
1325 SHFILEOPSTRUCT fileop;
1326 wxZeroMemory(fileop);
1327 fileop.wFunc = FO_DELETE;
1328 #if defined(__CYGWIN__) && defined(wxUSE_UNICODE)
1329 fileop.pFrom = path.wc_str();
1330 #else
1331 fileop.pFrom = path.fn_str();
1332 #endif
1333 fileop.fFlags = FOF_SILENT | FOF_NOCONFIRMATION;
1334 #ifndef __WXWINCE__
1335 // FOF_NOERRORUI is not defined in WinCE
1336 fileop.fFlags |= FOF_NOERRORUI;
1337 #endif
1338
1339 int ret = SHFileOperation(&fileop);
1340 if ( ret != 0 )
1341 {
1342 // SHFileOperation may return non-Win32 error codes, so the error
1343 // message can be incorrect
1344 wxLogApiError(wxT("SHFileOperation"), ret);
1345 return false;
1346 }
1347
1348 return true;
1349 }
1350 else if ( flags & wxPATH_RMDIR_FULL )
1351 #else // !__WXMSW__
1352 if ( flags != 0 ) // wxPATH_RMDIR_FULL or wxPATH_RMDIR_RECURSIVE
1353 #endif // !__WXMSW__
1354 {
1355 wxString path(dir);
1356 if ( path.Last() != wxFILE_SEP_PATH )
1357 path += wxFILE_SEP_PATH;
1358
1359 wxDir d(path);
1360
1361 if ( !d.IsOpened() )
1362 return false;
1363
1364 wxString filename;
1365
1366 // first delete all subdirectories
1367 bool cont = d.GetFirst(&filename, "", wxDIR_DIRS | wxDIR_HIDDEN);
1368 while ( cont )
1369 {
1370 wxFileName::Rmdir(path + filename, flags);
1371 cont = d.GetNext(&filename);
1372 }
1373
1374 #ifndef __WXMSW__
1375 if ( flags & wxPATH_RMDIR_RECURSIVE )
1376 {
1377 // delete all files too
1378 cont = d.GetFirst(&filename, "", wxDIR_FILES | wxDIR_HIDDEN);
1379 while ( cont )
1380 {
1381 ::wxRemoveFile(path + filename);
1382 cont = d.GetNext(&filename);
1383 }
1384 }
1385 #endif // !__WXMSW__
1386 }
1387
1388 return ::wxRmdir(dir);
1389 }
1390
1391 // ----------------------------------------------------------------------------
1392 // path normalization
1393 // ----------------------------------------------------------------------------
1394
1395 bool wxFileName::Normalize(int flags,
1396 const wxString& cwd,
1397 wxPathFormat format)
1398 {
1399 // deal with env vars renaming first as this may seriously change the path
1400 if ( flags & wxPATH_NORM_ENV_VARS )
1401 {
1402 wxString pathOrig = GetFullPath(format);
1403 wxString path = wxExpandEnvVars(pathOrig);
1404 if ( path != pathOrig )
1405 {
1406 Assign(path);
1407 }
1408 }
1409
1410 // the existing path components
1411 wxArrayString dirs = GetDirs();
1412
1413 // the path to prepend in front to make the path absolute
1414 wxFileName curDir;
1415
1416 format = GetFormat(format);
1417
1418 // set up the directory to use for making the path absolute later
1419 if ( (flags & wxPATH_NORM_ABSOLUTE) && !IsAbsolute(format) )
1420 {
1421 if ( cwd.empty() )
1422 {
1423 curDir.AssignCwd(GetVolume());
1424 }
1425 else // cwd provided
1426 {
1427 curDir.AssignDir(cwd);
1428 }
1429 }
1430
1431 // handle ~ stuff under Unix only
1432 if ( (format == wxPATH_UNIX) && (flags & wxPATH_NORM_TILDE) && m_relative )
1433 {
1434 if ( !dirs.IsEmpty() )
1435 {
1436 wxString dir = dirs[0u];
1437 if ( !dir.empty() && dir[0u] == wxT('~') )
1438 {
1439 // to make the path absolute use the home directory
1440 curDir.AssignDir(wxGetUserHome(dir.c_str() + 1));
1441 dirs.RemoveAt(0u);
1442 }
1443 }
1444 }
1445
1446 // transform relative path into abs one
1447 if ( curDir.IsOk() )
1448 {
1449 // this path may be relative because it doesn't have the volume name
1450 // and still have m_relative=true; in this case we shouldn't modify
1451 // our directory components but just set the current volume
1452 if ( !HasVolume() && curDir.HasVolume() )
1453 {
1454 SetVolume(curDir.GetVolume());
1455
1456 if ( !m_relative )
1457 {
1458 // yes, it was the case - we don't need curDir then
1459 curDir.Clear();
1460 }
1461 }
1462
1463 // finally, prepend curDir to the dirs array
1464 wxArrayString dirsNew = curDir.GetDirs();
1465 WX_PREPEND_ARRAY(dirs, dirsNew);
1466
1467 // if we used e.g. tilde expansion previously and wxGetUserHome didn't
1468 // return for some reason an absolute path, then curDir maybe not be absolute!
1469 if ( !curDir.m_relative )
1470 {
1471 // we have prepended an absolute path and thus we are now an absolute
1472 // file name too
1473 m_relative = false;
1474 }
1475 // else if (flags & wxPATH_NORM_ABSOLUTE):
1476 // should we warn the user that we didn't manage to make the path absolute?
1477 }
1478
1479 // now deal with ".", ".." and the rest
1480 m_dirs.Empty();
1481 size_t count = dirs.GetCount();
1482 for ( size_t n = 0; n < count; n++ )
1483 {
1484 wxString dir = dirs[n];
1485
1486 if ( flags & wxPATH_NORM_DOTS )
1487 {
1488 if ( dir == wxT(".") )
1489 {
1490 // just ignore
1491 continue;
1492 }
1493
1494 if ( dir == wxT("..") )
1495 {
1496 if ( m_dirs.empty() )
1497 {
1498 // We have more ".." than directory components so far.
1499 // Don't treat this as an error as the path could have been
1500 // entered by user so try to handle it reasonably: if the
1501 // path is absolute, just ignore the extra ".." because
1502 // "/.." is the same as "/". Otherwise, i.e. for relative
1503 // paths, keep ".." unchanged because removing it would
1504 // modify the file a relative path refers to.
1505 if ( !m_relative )
1506 continue;
1507
1508 }
1509 else // Normal case, go one step up.
1510 {
1511 m_dirs.pop_back();
1512 continue;
1513 }
1514 }
1515 }
1516
1517 m_dirs.Add(dir);
1518 }
1519
1520 #if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
1521 if ( (flags & wxPATH_NORM_SHORTCUT) )
1522 {
1523 wxString filename;
1524 if (GetShortcutTarget(GetFullPath(format), filename))
1525 {
1526 m_relative = false;
1527 Assign(filename);
1528 }
1529 }
1530 #endif
1531
1532 #if defined(__WIN32__)
1533 if ( (flags & wxPATH_NORM_LONG) && (format == wxPATH_DOS) )
1534 {
1535 Assign(GetLongPath());
1536 }
1537 #endif // Win32
1538
1539 // Change case (this should be kept at the end of the function, to ensure
1540 // that the path doesn't change any more after we normalize its case)
1541 if ( (flags & wxPATH_NORM_CASE) && !IsCaseSensitive(format) )
1542 {
1543 m_volume.MakeLower();
1544 m_name.MakeLower();
1545 m_ext.MakeLower();
1546
1547 // directory entries must be made lower case as well
1548 count = m_dirs.GetCount();
1549 for ( size_t i = 0; i < count; i++ )
1550 {
1551 m_dirs[i].MakeLower();
1552 }
1553 }
1554
1555 return true;
1556 }
1557
1558 #ifndef __WXWINCE__
1559 bool wxFileName::ReplaceEnvVariable(const wxString& envname,
1560 const wxString& replacementFmtString,
1561 wxPathFormat format)
1562 {
1563 // look into stringForm for the contents of the given environment variable
1564 wxString val;
1565 if (envname.empty() ||
1566 !wxGetEnv(envname, &val))
1567 return false;
1568 if (val.empty())
1569 return false;
1570
1571 wxString stringForm = GetPath(wxPATH_GET_VOLUME, format);
1572 // do not touch the file name and the extension
1573
1574 wxString replacement = wxString::Format(replacementFmtString, envname);
1575 stringForm.Replace(val, replacement);
1576
1577 // Now assign ourselves the modified path:
1578 Assign(stringForm, GetFullName(), format);
1579
1580 return true;
1581 }
1582 #endif
1583
1584 bool wxFileName::ReplaceHomeDir(wxPathFormat format)
1585 {
1586 wxString homedir = wxGetHomeDir();
1587 if (homedir.empty())
1588 return false;
1589
1590 wxString stringForm = GetPath(wxPATH_GET_VOLUME, format);
1591 // do not touch the file name and the extension
1592
1593 stringForm.Replace(homedir, "~");
1594
1595 // Now assign ourselves the modified path:
1596 Assign(stringForm, GetFullName(), format);
1597
1598 return true;
1599 }
1600
1601 // ----------------------------------------------------------------------------
1602 // get the shortcut target
1603 // ----------------------------------------------------------------------------
1604
1605 // WinCE (3) doesn't have CLSID_ShellLink, IID_IShellLink definitions.
1606 // The .lnk file is a plain text file so it should be easy to
1607 // make it work. Hint from Google Groups:
1608 // "If you open up a lnk file, you'll see a
1609 // number, followed by a pound sign (#), followed by more text. The
1610 // number is the number of characters that follows the pound sign. The
1611 // characters after the pound sign are the command line (which _can_
1612 // include arguments) to be executed. Any path (e.g. \windows\program
1613 // files\myapp.exe) that includes spaces needs to be enclosed in
1614 // quotation marks."
1615
1616 #if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
1617 // The following lines are necessary under WinCE
1618 // #include "wx/msw/private.h"
1619 // #include <ole2.h>
1620 #include <shlobj.h>
1621 #if defined(__WXWINCE__)
1622 #include <shlguid.h>
1623 #endif
1624
1625 bool wxFileName::GetShortcutTarget(const wxString& shortcutPath,
1626 wxString& targetFilename,
1627 wxString* arguments) const
1628 {
1629 wxString path, file, ext;
1630 wxFileName::SplitPath(shortcutPath, & path, & file, & ext);
1631
1632 HRESULT hres;
1633 IShellLink* psl;
1634 bool success = false;
1635
1636 // Assume it's not a shortcut if it doesn't end with lnk
1637 if (ext.CmpNoCase(wxT("lnk"))!=0)
1638 return false;
1639
1640 // create a ShellLink object
1641 hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
1642 IID_IShellLink, (LPVOID*) &psl);
1643
1644 if (SUCCEEDED(hres))
1645 {
1646 IPersistFile* ppf;
1647 hres = psl->QueryInterface( IID_IPersistFile, (LPVOID *) &ppf);
1648 if (SUCCEEDED(hres))
1649 {
1650 WCHAR wsz[MAX_PATH];
1651
1652 MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, shortcutPath.mb_str(), -1, wsz,
1653 MAX_PATH);
1654
1655 hres = ppf->Load(wsz, 0);
1656 ppf->Release();
1657
1658 if (SUCCEEDED(hres))
1659 {
1660 wxChar buf[2048];
1661 // Wrong prototype in early versions
1662 #if defined(__MINGW32__) && !wxCHECK_W32API_VERSION(2, 2)
1663 psl->GetPath((CHAR*) buf, 2048, NULL, SLGP_UNCPRIORITY);
1664 #else
1665 psl->GetPath(buf, 2048, NULL, SLGP_UNCPRIORITY);
1666 #endif
1667 targetFilename = wxString(buf);
1668 success = (shortcutPath != targetFilename);
1669
1670 psl->GetArguments(buf, 2048);
1671 wxString args(buf);
1672 if (!args.empty() && arguments)
1673 {
1674 *arguments = args;
1675 }
1676 }
1677 }
1678
1679 psl->Release();
1680 }
1681 return success;
1682 }
1683
1684 #endif // __WIN32__ && !__WXWINCE__
1685
1686
1687 // ----------------------------------------------------------------------------
1688 // absolute/relative paths
1689 // ----------------------------------------------------------------------------
1690
1691 bool wxFileName::IsAbsolute(wxPathFormat format) const
1692 {
1693 // unix paths beginning with ~ are reported as being absolute
1694 if ( format == wxPATH_UNIX )
1695 {
1696 if ( !m_dirs.IsEmpty() )
1697 {
1698 wxString dir = m_dirs[0u];
1699
1700 if (!dir.empty() && dir[0u] == wxT('~'))
1701 return true;
1702 }
1703 }
1704
1705 // if our path doesn't start with a path separator, it's not an absolute
1706 // path
1707 if ( m_relative )
1708 return false;
1709
1710 if ( !GetVolumeSeparator(format).empty() )
1711 {
1712 // this format has volumes and an absolute path must have one, it's not
1713 // enough to have the full path to be an absolute file under Windows
1714 if ( GetVolume().empty() )
1715 return false;
1716 }
1717
1718 return true;
1719 }
1720
1721 bool wxFileName::MakeRelativeTo(const wxString& pathBase, wxPathFormat format)
1722 {
1723 wxFileName fnBase = wxFileName::DirName(pathBase, format);
1724
1725 // get cwd only once - small time saving
1726 wxString cwd = wxGetCwd();
1727 Normalize(wxPATH_NORM_ALL & ~wxPATH_NORM_CASE, cwd, format);
1728 fnBase.Normalize(wxPATH_NORM_ALL & ~wxPATH_NORM_CASE, cwd, format);
1729
1730 bool withCase = IsCaseSensitive(format);
1731
1732 // we can't do anything if the files live on different volumes
1733 if ( !GetVolume().IsSameAs(fnBase.GetVolume(), withCase) )
1734 {
1735 // nothing done
1736 return false;
1737 }
1738
1739 // same drive, so we don't need our volume
1740 m_volume.clear();
1741
1742 // remove common directories starting at the top
1743 while ( !m_dirs.IsEmpty() && !fnBase.m_dirs.IsEmpty() &&
1744 m_dirs[0u].IsSameAs(fnBase.m_dirs[0u], withCase) )
1745 {
1746 m_dirs.RemoveAt(0);
1747 fnBase.m_dirs.RemoveAt(0);
1748 }
1749
1750 // add as many ".." as needed
1751 size_t count = fnBase.m_dirs.GetCount();
1752 for ( size_t i = 0; i < count; i++ )
1753 {
1754 m_dirs.Insert(wxT(".."), 0u);
1755 }
1756
1757 if ( format == wxPATH_UNIX || format == wxPATH_DOS )
1758 {
1759 // a directory made relative with respect to itself is '.' under Unix
1760 // and DOS, by definition (but we don't have to insert "./" for the
1761 // files)
1762 if ( m_dirs.IsEmpty() && IsDir() )
1763 {
1764 m_dirs.Add(wxT('.'));
1765 }
1766 }
1767
1768 m_relative = true;
1769
1770 // we were modified
1771 return true;
1772 }
1773
1774 // ----------------------------------------------------------------------------
1775 // filename kind tests
1776 // ----------------------------------------------------------------------------
1777
1778 bool wxFileName::SameAs(const wxFileName& filepath, wxPathFormat format) const
1779 {
1780 wxFileName fn1 = *this,
1781 fn2 = filepath;
1782
1783 // get cwd only once - small time saving
1784 wxString cwd = wxGetCwd();
1785 fn1.Normalize(wxPATH_NORM_ALL | wxPATH_NORM_CASE, cwd, format);
1786 fn2.Normalize(wxPATH_NORM_ALL | wxPATH_NORM_CASE, cwd, format);
1787
1788 if ( fn1.GetFullPath() == fn2.GetFullPath() )
1789 return true;
1790
1791 // TODO: compare inodes for Unix, this works even when filenames are
1792 // different but files are the same (symlinks) (VZ)
1793
1794 return false;
1795 }
1796
1797 /* static */
1798 bool wxFileName::IsCaseSensitive( wxPathFormat format )
1799 {
1800 // only Unix filenames are truely case-sensitive
1801 return GetFormat(format) == wxPATH_UNIX;
1802 }
1803
1804 /* static */
1805 wxString wxFileName::GetForbiddenChars(wxPathFormat format)
1806 {
1807 // Inits to forbidden characters that are common to (almost) all platforms.
1808 wxString strForbiddenChars = wxT("*?");
1809
1810 // If asserts, wxPathFormat has been changed. In case of a new path format
1811 // addition, the following code might have to be updated.
1812 wxCOMPILE_TIME_ASSERT(wxPATH_MAX == 5, wxPathFormatChanged);
1813 switch ( GetFormat(format) )
1814 {
1815 default :
1816 wxFAIL_MSG( wxT("Unknown path format") );
1817 // !! Fall through !!
1818
1819 case wxPATH_UNIX:
1820 break;
1821
1822 case wxPATH_MAC:
1823 // On a Mac even names with * and ? are allowed (Tested with OS
1824 // 9.2.1 and OS X 10.2.5)
1825 strForbiddenChars = wxEmptyString;
1826 break;
1827
1828 case wxPATH_DOS:
1829 strForbiddenChars += wxT("\\/:\"<>|");
1830 break;
1831
1832 case wxPATH_VMS:
1833 break;
1834 }
1835
1836 return strForbiddenChars;
1837 }
1838
1839 /* static */
1840 wxString wxFileName::GetVolumeSeparator(wxPathFormat WXUNUSED_IN_WINCE(format))
1841 {
1842 #ifdef __WXWINCE__
1843 return wxEmptyString;
1844 #else
1845 wxString sepVol;
1846
1847 if ( (GetFormat(format) == wxPATH_DOS) ||
1848 (GetFormat(format) == wxPATH_VMS) )
1849 {
1850 sepVol = wxFILE_SEP_DSK;
1851 }
1852 //else: leave empty
1853
1854 return sepVol;
1855 #endif
1856 }
1857
1858 /* static */
1859 wxString wxFileName::GetPathSeparators(wxPathFormat format)
1860 {
1861 wxString seps;
1862 switch ( GetFormat(format) )
1863 {
1864 case wxPATH_DOS:
1865 // accept both as native APIs do but put the native one first as
1866 // this is the one we use in GetFullPath()
1867 seps << wxFILE_SEP_PATH_DOS << wxFILE_SEP_PATH_UNIX;
1868 break;
1869
1870 default:
1871 wxFAIL_MSG( wxT("Unknown wxPATH_XXX style") );
1872 // fall through
1873
1874 case wxPATH_UNIX:
1875 seps = wxFILE_SEP_PATH_UNIX;
1876 break;
1877
1878 case wxPATH_MAC:
1879 seps = wxFILE_SEP_PATH_MAC;
1880 break;
1881
1882 case wxPATH_VMS:
1883 seps = wxFILE_SEP_PATH_VMS;
1884 break;
1885 }
1886
1887 return seps;
1888 }
1889
1890 /* static */
1891 wxString wxFileName::GetPathTerminators(wxPathFormat format)
1892 {
1893 format = GetFormat(format);
1894
1895 // under VMS the end of the path is ']', not the path separator used to
1896 // separate the components
1897 return format == wxPATH_VMS ? wxString(wxT(']')) : GetPathSeparators(format);
1898 }
1899
1900 /* static */
1901 bool wxFileName::IsPathSeparator(wxChar ch, wxPathFormat format)
1902 {
1903 // wxString::Find() doesn't work as expected with NUL - it will always find
1904 // it, so test for it separately
1905 return ch != wxT('\0') && GetPathSeparators(format).Find(ch) != wxNOT_FOUND;
1906 }
1907
1908 /* static */
1909 bool
1910 wxFileName::IsMSWUniqueVolumeNamePath(const wxString& path, wxPathFormat format)
1911 {
1912 // return true if the format used is the DOS/Windows one and the string begins
1913 // with a Windows unique volume name ("\\?\Volume{guid}\")
1914 return format == wxPATH_DOS &&
1915 path.length() >= wxMSWUniqueVolumePrefixLength &&
1916 path.StartsWith(wxS("\\\\?\\Volume{")) &&
1917 path[wxMSWUniqueVolumePrefixLength - 1] == wxFILE_SEP_PATH_DOS;
1918 }
1919
1920 // ----------------------------------------------------------------------------
1921 // path components manipulation
1922 // ----------------------------------------------------------------------------
1923
1924 /* static */ bool wxFileName::IsValidDirComponent(const wxString& dir)
1925 {
1926 if ( dir.empty() )
1927 {
1928 wxFAIL_MSG( wxT("empty directory passed to wxFileName::InsertDir()") );
1929
1930 return false;
1931 }
1932
1933 const size_t len = dir.length();
1934 for ( size_t n = 0; n < len; n++ )
1935 {
1936 if ( dir[n] == GetVolumeSeparator() || IsPathSeparator(dir[n]) )
1937 {
1938 wxFAIL_MSG( wxT("invalid directory component in wxFileName") );
1939
1940 return false;
1941 }
1942 }
1943
1944 return true;
1945 }
1946
1947 void wxFileName::AppendDir( const wxString& dir )
1948 {
1949 if ( IsValidDirComponent(dir) )
1950 m_dirs.Add( dir );
1951 }
1952
1953 void wxFileName::PrependDir( const wxString& dir )
1954 {
1955 InsertDir(0, dir);
1956 }
1957
1958 void wxFileName::InsertDir(size_t before, const wxString& dir)
1959 {
1960 if ( IsValidDirComponent(dir) )
1961 m_dirs.Insert(dir, before);
1962 }
1963
1964 void wxFileName::RemoveDir(size_t pos)
1965 {
1966 m_dirs.RemoveAt(pos);
1967 }
1968
1969 // ----------------------------------------------------------------------------
1970 // accessors
1971 // ----------------------------------------------------------------------------
1972
1973 void wxFileName::SetFullName(const wxString& fullname)
1974 {
1975 SplitPath(fullname, NULL /* no volume */, NULL /* no path */,
1976 &m_name, &m_ext, &m_hasExt);
1977 }
1978
1979 wxString wxFileName::GetFullName() const
1980 {
1981 wxString fullname = m_name;
1982 if ( m_hasExt )
1983 {
1984 fullname << wxFILE_SEP_EXT << m_ext;
1985 }
1986
1987 return fullname;
1988 }
1989
1990 wxString wxFileName::GetPath( int flags, wxPathFormat format ) const
1991 {
1992 format = GetFormat( format );
1993
1994 wxString fullpath;
1995
1996 // return the volume with the path as well if requested
1997 if ( flags & wxPATH_GET_VOLUME )
1998 {
1999 fullpath += wxGetVolumeString(GetVolume(), format);
2000 }
2001
2002 // the leading character
2003 switch ( format )
2004 {
2005 case wxPATH_MAC:
2006 if ( m_relative )
2007 fullpath += wxFILE_SEP_PATH_MAC;
2008 break;
2009
2010 case wxPATH_DOS:
2011 if ( !m_relative )
2012 fullpath += wxFILE_SEP_PATH_DOS;
2013 break;
2014
2015 default:
2016 wxFAIL_MSG( wxT("Unknown path format") );
2017 // fall through
2018
2019 case wxPATH_UNIX:
2020 if ( !m_relative )
2021 {
2022 fullpath += wxFILE_SEP_PATH_UNIX;
2023 }
2024 break;
2025
2026 case wxPATH_VMS:
2027 // no leading character here but use this place to unset
2028 // wxPATH_GET_SEPARATOR flag: under VMS it doesn't make sense
2029 // as, if I understand correctly, there should never be a dot
2030 // before the closing bracket
2031 flags &= ~wxPATH_GET_SEPARATOR;
2032 }
2033
2034 if ( m_dirs.empty() )
2035 {
2036 // there is nothing more
2037 return fullpath;
2038 }
2039
2040 // then concatenate all the path components using the path separator
2041 if ( format == wxPATH_VMS )
2042 {
2043 fullpath += wxT('[');
2044 }
2045
2046 const size_t dirCount = m_dirs.GetCount();
2047 for ( size_t i = 0; i < dirCount; i++ )
2048 {
2049 switch (format)
2050 {
2051 case wxPATH_MAC:
2052 if ( m_dirs[i] == wxT(".") )
2053 {
2054 // skip appending ':', this shouldn't be done in this
2055 // case as "::" is interpreted as ".." under Unix
2056 continue;
2057 }
2058
2059 // convert back from ".." to nothing
2060 if ( !m_dirs[i].IsSameAs(wxT("..")) )
2061 fullpath += m_dirs[i];
2062 break;
2063
2064 default:
2065 wxFAIL_MSG( wxT("Unexpected path format") );
2066 // still fall through
2067
2068 case wxPATH_DOS:
2069 case wxPATH_UNIX:
2070 fullpath += m_dirs[i];
2071 break;
2072
2073 case wxPATH_VMS:
2074 // TODO: What to do with ".." under VMS
2075
2076 // convert back from ".." to nothing
2077 if ( !m_dirs[i].IsSameAs(wxT("..")) )
2078 fullpath += m_dirs[i];
2079 break;
2080 }
2081
2082 if ( (flags & wxPATH_GET_SEPARATOR) || (i != dirCount - 1) )
2083 fullpath += GetPathSeparator(format);
2084 }
2085
2086 if ( format == wxPATH_VMS )
2087 {
2088 fullpath += wxT(']');
2089 }
2090
2091 return fullpath;
2092 }
2093
2094 wxString wxFileName::GetFullPath( wxPathFormat format ) const
2095 {
2096 // we already have a function to get the path
2097 wxString fullpath = GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR,
2098 format);
2099
2100 // now just add the file name and extension to it
2101 fullpath += GetFullName();
2102
2103 return fullpath;
2104 }
2105
2106 // Return the short form of the path (returns identity on non-Windows platforms)
2107 wxString wxFileName::GetShortPath() const
2108 {
2109 wxString path(GetFullPath());
2110
2111 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
2112 DWORD sz = ::GetShortPathName(path.t_str(), NULL, 0);
2113 if ( sz != 0 )
2114 {
2115 wxString pathOut;
2116 if ( ::GetShortPathName
2117 (
2118 path.t_str(),
2119 wxStringBuffer(pathOut, sz),
2120 sz
2121 ) != 0 )
2122 {
2123 return pathOut;
2124 }
2125 }
2126 #endif // Windows
2127
2128 return path;
2129 }
2130
2131 // Return the long form of the path (returns identity on non-Windows platforms)
2132 wxString wxFileName::GetLongPath() const
2133 {
2134 wxString pathOut,
2135 path = GetFullPath();
2136
2137 #if defined(__WIN32__) && !defined(__WXWINCE__) && !defined(__WXMICROWIN__)
2138
2139 #if wxUSE_DYNLIB_CLASS
2140 typedef DWORD (WINAPI *GET_LONG_PATH_NAME)(const wxChar *, wxChar *, DWORD);
2141
2142 // this is MT-safe as in the worst case we're going to resolve the function
2143 // twice -- but as the result is the same in both threads, it's ok
2144 static GET_LONG_PATH_NAME s_pfnGetLongPathName = NULL;
2145 if ( !s_pfnGetLongPathName )
2146 {
2147 static bool s_triedToLoad = false;
2148
2149 if ( !s_triedToLoad )
2150 {
2151 s_triedToLoad = true;
2152
2153 wxDynamicLibrary dllKernel(wxT("kernel32"));
2154
2155 const wxChar* GetLongPathName = wxT("GetLongPathName")
2156 #if wxUSE_UNICODE
2157 wxT("W");
2158 #else // ANSI
2159 wxT("A");
2160 #endif // Unicode/ANSI
2161
2162 if ( dllKernel.HasSymbol(GetLongPathName) )
2163 {
2164 s_pfnGetLongPathName = (GET_LONG_PATH_NAME)
2165 dllKernel.GetSymbol(GetLongPathName);
2166 }
2167
2168 // note that kernel32.dll can be unloaded, it stays in memory
2169 // anyhow as all Win32 programs link to it and so it's safe to call
2170 // GetLongPathName() even after unloading it
2171 }
2172 }
2173
2174 if ( s_pfnGetLongPathName )
2175 {
2176 DWORD dwSize = (*s_pfnGetLongPathName)(path.t_str(), NULL, 0);
2177 if ( dwSize > 0 )
2178 {
2179 if ( (*s_pfnGetLongPathName)
2180 (
2181 path.t_str(),
2182 wxStringBuffer(pathOut, dwSize),
2183 dwSize
2184 ) != 0 )
2185 {
2186 return pathOut;
2187 }
2188 }
2189 }
2190 #endif // wxUSE_DYNLIB_CLASS
2191
2192 // The OS didn't support GetLongPathName, or some other error.
2193 // We need to call FindFirstFile on each component in turn.
2194
2195 WIN32_FIND_DATA findFileData;
2196 HANDLE hFind;
2197
2198 if ( HasVolume() )
2199 pathOut = GetVolume() +
2200 GetVolumeSeparator(wxPATH_DOS) +
2201 GetPathSeparator(wxPATH_DOS);
2202 else
2203 pathOut = wxEmptyString;
2204
2205 wxArrayString dirs = GetDirs();
2206 dirs.Add(GetFullName());
2207
2208 wxString tmpPath;
2209
2210 size_t count = dirs.GetCount();
2211 for ( size_t i = 0; i < count; i++ )
2212 {
2213 const wxString& dir = dirs[i];
2214
2215 // We're using pathOut to collect the long-name path, but using a
2216 // temporary for appending the last path component which may be
2217 // short-name
2218 tmpPath = pathOut + dir;
2219
2220 // We must not process "." or ".." here as they would be (unexpectedly)
2221 // replaced by the corresponding directory names so just leave them
2222 // alone
2223 //
2224 // And we can't pass a drive and root dir to FindFirstFile (VZ: why?)
2225 if ( tmpPath.empty() || dir == '.' || dir == ".." ||
2226 tmpPath.Last() == GetVolumeSeparator(wxPATH_DOS) )
2227 {
2228 tmpPath += wxFILE_SEP_PATH;
2229 pathOut = tmpPath;
2230 continue;
2231 }
2232
2233 hFind = ::FindFirstFile(tmpPath.t_str(), &findFileData);
2234 if (hFind == INVALID_HANDLE_VALUE)
2235 {
2236 // Error: most likely reason is that path doesn't exist, so
2237 // append any unprocessed parts and return
2238 for ( i += 1; i < count; i++ )
2239 tmpPath += wxFILE_SEP_PATH + dirs[i];
2240
2241 return tmpPath;
2242 }
2243
2244 pathOut += findFileData.cFileName;
2245 if ( (i < (count-1)) )
2246 pathOut += wxFILE_SEP_PATH;
2247
2248 ::FindClose(hFind);
2249 }
2250 #else // !Win32
2251 pathOut = path;
2252 #endif // Win32/!Win32
2253
2254 return pathOut;
2255 }
2256
2257 wxPathFormat wxFileName::GetFormat( wxPathFormat format )
2258 {
2259 if (format == wxPATH_NATIVE)
2260 {
2261 #if defined(__WXMSW__) || defined(__OS2__) || defined(__DOS__)
2262 format = wxPATH_DOS;
2263 #elif defined(__VMS)
2264 format = wxPATH_VMS;
2265 #else
2266 format = wxPATH_UNIX;
2267 #endif
2268 }
2269 return format;
2270 }
2271
2272 #ifdef wxHAS_FILESYSTEM_VOLUMES
2273
2274 /* static */
2275 wxString wxFileName::GetVolumeString(char drive, int flags)
2276 {
2277 wxASSERT_MSG( !(flags & ~wxPATH_GET_SEPARATOR), "invalid flag specified" );
2278
2279 wxString vol(drive);
2280 vol += wxFILE_SEP_DSK;
2281 if ( flags & wxPATH_GET_SEPARATOR )
2282 vol += wxFILE_SEP_PATH;
2283
2284 return vol;
2285 }
2286
2287 #endif // wxHAS_FILESYSTEM_VOLUMES
2288
2289 // ----------------------------------------------------------------------------
2290 // path splitting function
2291 // ----------------------------------------------------------------------------
2292
2293 /* static */
2294 void
2295 wxFileName::SplitVolume(const wxString& fullpathWithVolume,
2296 wxString *pstrVolume,
2297 wxString *pstrPath,
2298 wxPathFormat format)
2299 {
2300 format = GetFormat(format);
2301
2302 wxString fullpath = fullpathWithVolume;
2303
2304 if ( IsMSWUniqueVolumeNamePath(fullpath, format) )
2305 {
2306 // special Windows unique volume names hack: transform
2307 // \\?\Volume{guid}\path into Volume{guid}:path
2308 // note: this check must be done before the check for UNC path
2309
2310 // we know the last backslash from the unique volume name is located
2311 // there from IsMSWUniqueVolumeNamePath
2312 fullpath[wxMSWUniqueVolumePrefixLength - 1] = wxFILE_SEP_DSK;
2313
2314 // paths starting with a unique volume name should always be absolute
2315 fullpath.insert(wxMSWUniqueVolumePrefixLength, 1, wxFILE_SEP_PATH_DOS);
2316
2317 // remove the leading "\\?\" part
2318 fullpath.erase(0, 4);
2319 }
2320 else if ( IsUNCPath(fullpath, format) )
2321 {
2322 // special Windows UNC paths hack: transform \\share\path into share:path
2323
2324 fullpath.erase(0, 2);
2325
2326 size_t posFirstSlash =
2327 fullpath.find_first_of(GetPathTerminators(format));
2328 if ( posFirstSlash != wxString::npos )
2329 {
2330 fullpath[posFirstSlash] = wxFILE_SEP_DSK;
2331
2332 // UNC paths are always absolute, right? (FIXME)
2333 fullpath.insert(posFirstSlash + 1, 1, wxFILE_SEP_PATH_DOS);
2334 }
2335 }
2336
2337 // We separate the volume here
2338 if ( format == wxPATH_DOS || format == wxPATH_VMS )
2339 {
2340 wxString sepVol = GetVolumeSeparator(format);
2341
2342 // we have to exclude the case of a colon in the very beginning of the
2343 // string as it can't be a volume separator (nor can this be a valid
2344 // DOS file name at all but we'll leave dealing with this to our caller)
2345 size_t posFirstColon = fullpath.find_first_of(sepVol);
2346 if ( posFirstColon && posFirstColon != wxString::npos )
2347 {
2348 if ( pstrVolume )
2349 {
2350 *pstrVolume = fullpath.Left(posFirstColon);
2351 }
2352
2353 // remove the volume name and the separator from the full path
2354 fullpath.erase(0, posFirstColon + sepVol.length());
2355 }
2356 }
2357
2358 if ( pstrPath )
2359 *pstrPath = fullpath;
2360 }
2361
2362 /* static */
2363 void wxFileName::SplitPath(const wxString& fullpathWithVolume,
2364 wxString *pstrVolume,
2365 wxString *pstrPath,
2366 wxString *pstrName,
2367 wxString *pstrExt,
2368 bool *hasExt,
2369 wxPathFormat format)
2370 {
2371 format = GetFormat(format);
2372
2373 wxString fullpath;
2374 SplitVolume(fullpathWithVolume, pstrVolume, &fullpath, format);
2375
2376 // find the positions of the last dot and last path separator in the path
2377 size_t posLastDot = fullpath.find_last_of(wxFILE_SEP_EXT);
2378 size_t posLastSlash = fullpath.find_last_of(GetPathTerminators(format));
2379
2380 // check whether this dot occurs at the very beginning of a path component
2381 if ( (posLastDot != wxString::npos) &&
2382 (posLastDot == 0 ||
2383 IsPathSeparator(fullpath[posLastDot - 1]) ||
2384 (format == wxPATH_VMS && fullpath[posLastDot - 1] == wxT(']'))) )
2385 {
2386 // dot may be (and commonly -- at least under Unix -- is) the first
2387 // character of the filename, don't treat the entire filename as
2388 // extension in this case
2389 posLastDot = wxString::npos;
2390 }
2391
2392 // if we do have a dot and a slash, check that the dot is in the name part
2393 if ( (posLastDot != wxString::npos) &&
2394 (posLastSlash != wxString::npos) &&
2395 (posLastDot < posLastSlash) )
2396 {
2397 // the dot is part of the path, not the start of the extension
2398 posLastDot = wxString::npos;
2399 }
2400
2401 // now fill in the variables provided by user
2402 if ( pstrPath )
2403 {
2404 if ( posLastSlash == wxString::npos )
2405 {
2406 // no path at all
2407 pstrPath->Empty();
2408 }
2409 else
2410 {
2411 // take everything up to the path separator but take care to make
2412 // the path equal to something like '/', not empty, for the files
2413 // immediately under root directory
2414 size_t len = posLastSlash;
2415
2416 // this rule does not apply to mac since we do not start with colons (sep)
2417 // except for relative paths
2418 if ( !len && format != wxPATH_MAC)
2419 len++;
2420
2421 *pstrPath = fullpath.Left(len);
2422
2423 // special VMS hack: remove the initial bracket
2424 if ( format == wxPATH_VMS )
2425 {
2426 if ( (*pstrPath)[0u] == wxT('[') )
2427 pstrPath->erase(0, 1);
2428 }
2429 }
2430 }
2431
2432 if ( pstrName )
2433 {
2434 // take all characters starting from the one after the last slash and
2435 // up to, but excluding, the last dot
2436 size_t nStart = posLastSlash == wxString::npos ? 0 : posLastSlash + 1;
2437 size_t count;
2438 if ( posLastDot == wxString::npos )
2439 {
2440 // take all until the end
2441 count = wxString::npos;
2442 }
2443 else if ( posLastSlash == wxString::npos )
2444 {
2445 count = posLastDot;
2446 }
2447 else // have both dot and slash
2448 {
2449 count = posLastDot - posLastSlash - 1;
2450 }
2451
2452 *pstrName = fullpath.Mid(nStart, count);
2453 }
2454
2455 // finally deal with the extension here: we have an added complication that
2456 // extension may be empty (but present) as in "foo." where trailing dot
2457 // indicates the empty extension at the end -- and hence we must remember
2458 // that we have it independently of pstrExt
2459 if ( posLastDot == wxString::npos )
2460 {
2461 // no extension
2462 if ( pstrExt )
2463 pstrExt->clear();
2464 if ( hasExt )
2465 *hasExt = false;
2466 }
2467 else
2468 {
2469 // take everything after the dot
2470 if ( pstrExt )
2471 *pstrExt = fullpath.Mid(posLastDot + 1);
2472 if ( hasExt )
2473 *hasExt = true;
2474 }
2475 }
2476
2477 /* static */
2478 void wxFileName::SplitPath(const wxString& fullpath,
2479 wxString *path,
2480 wxString *name,
2481 wxString *ext,
2482 wxPathFormat format)
2483 {
2484 wxString volume;
2485 SplitPath(fullpath, &volume, path, name, ext, format);
2486
2487 if ( path )
2488 {
2489 path->Prepend(wxGetVolumeString(volume, format));
2490 }
2491 }
2492
2493 /* static */
2494 wxString wxFileName::StripExtension(const wxString& fullpath)
2495 {
2496 wxFileName fn(fullpath);
2497 fn.SetExt("");
2498 return fn.GetFullPath();
2499 }
2500
2501 // ----------------------------------------------------------------------------
2502 // time functions
2503 // ----------------------------------------------------------------------------
2504
2505 #if wxUSE_DATETIME
2506
2507 bool wxFileName::SetTimes(const wxDateTime *dtAccess,
2508 const wxDateTime *dtMod,
2509 const wxDateTime *dtCreate) const
2510 {
2511 #if defined(__WIN32__)
2512 FILETIME ftAccess, ftCreate, ftWrite;
2513
2514 if ( dtCreate )
2515 ConvertWxToFileTime(&ftCreate, *dtCreate);
2516 if ( dtAccess )
2517 ConvertWxToFileTime(&ftAccess, *dtAccess);
2518 if ( dtMod )
2519 ConvertWxToFileTime(&ftWrite, *dtMod);
2520
2521 wxString path;
2522 int flags;
2523 if ( IsDir() )
2524 {
2525 if ( wxGetOsVersion() == wxOS_WINDOWS_9X )
2526 {
2527 wxLogError(_("Setting directory access times is not supported "
2528 "under this OS version"));
2529 return false;
2530 }
2531
2532 path = GetPath();
2533 flags = FILE_FLAG_BACKUP_SEMANTICS;
2534 }
2535 else // file
2536 {
2537 path = GetFullPath();
2538 flags = 0;
2539 }
2540
2541 wxFileHandle fh(path, wxFileHandle::WriteAttr, flags);
2542 if ( fh.IsOk() )
2543 {
2544 if ( ::SetFileTime(fh,
2545 dtCreate ? &ftCreate : NULL,
2546 dtAccess ? &ftAccess : NULL,
2547 dtMod ? &ftWrite : NULL) )
2548 {
2549 return true;
2550 }
2551 }
2552 #elif defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
2553 wxUnusedVar(dtCreate);
2554
2555 if ( !dtAccess && !dtMod )
2556 {
2557 // can't modify the creation time anyhow, don't try
2558 return true;
2559 }
2560
2561 // if dtAccess or dtMod is not specified, use the other one (which must be
2562 // non NULL because of the test above) for both times
2563 utimbuf utm;
2564 utm.actime = dtAccess ? dtAccess->GetTicks() : dtMod->GetTicks();
2565 utm.modtime = dtMod ? dtMod->GetTicks() : dtAccess->GetTicks();
2566 if ( utime(GetFullPath().fn_str(), &utm) == 0 )
2567 {
2568 return true;
2569 }
2570 #else // other platform
2571 wxUnusedVar(dtAccess);
2572 wxUnusedVar(dtMod);
2573 wxUnusedVar(dtCreate);
2574 #endif // platforms
2575
2576 wxLogSysError(_("Failed to modify file times for '%s'"),
2577 GetFullPath().c_str());
2578
2579 return false;
2580 }
2581
2582 bool wxFileName::Touch() const
2583 {
2584 #if defined(__UNIX_LIKE__)
2585 // under Unix touching file is simple: just pass NULL to utime()
2586 if ( utime(GetFullPath().fn_str(), NULL) == 0 )
2587 {
2588 return true;
2589 }
2590
2591 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
2592
2593 return false;
2594 #else // other platform
2595 wxDateTime dtNow = wxDateTime::Now();
2596
2597 return SetTimes(&dtNow, &dtNow, NULL /* don't change create time */);
2598 #endif // platforms
2599 }
2600
2601 bool wxFileName::GetTimes(wxDateTime *dtAccess,
2602 wxDateTime *dtMod,
2603 wxDateTime *dtCreate) const
2604 {
2605 #if defined(__WIN32__)
2606 // we must use different methods for the files and directories under
2607 // Windows as CreateFile(GENERIC_READ) doesn't work for the directories and
2608 // CreateFile(FILE_FLAG_BACKUP_SEMANTICS) works -- but only under NT and
2609 // not 9x
2610 bool ok;
2611 FILETIME ftAccess, ftCreate, ftWrite;
2612 if ( IsDir() )
2613 {
2614 // implemented in msw/dir.cpp
2615 extern bool wxGetDirectoryTimes(const wxString& dirname,
2616 FILETIME *, FILETIME *, FILETIME *);
2617
2618 // we should pass the path without the trailing separator to
2619 // wxGetDirectoryTimes()
2620 ok = wxGetDirectoryTimes(GetPath(wxPATH_GET_VOLUME),
2621 &ftAccess, &ftCreate, &ftWrite);
2622 }
2623 else // file
2624 {
2625 wxFileHandle fh(GetFullPath(), wxFileHandle::ReadAttr);
2626 if ( fh.IsOk() )
2627 {
2628 ok = ::GetFileTime(fh,
2629 dtCreate ? &ftCreate : NULL,
2630 dtAccess ? &ftAccess : NULL,
2631 dtMod ? &ftWrite : NULL) != 0;
2632 }
2633 else
2634 {
2635 ok = false;
2636 }
2637 }
2638
2639 if ( ok )
2640 {
2641 if ( dtCreate )
2642 ConvertFileTimeToWx(dtCreate, ftCreate);
2643 if ( dtAccess )
2644 ConvertFileTimeToWx(dtAccess, ftAccess);
2645 if ( dtMod )
2646 ConvertFileTimeToWx(dtMod, ftWrite);
2647
2648 return true;
2649 }
2650 #elif defined(__UNIX_LIKE__) || defined(__WXMAC__) || defined(__OS2__) || (defined(__DOS__) && defined(__WATCOMC__))
2651 // no need to test for IsDir() here
2652 wxStructStat stBuf;
2653 if ( wxStat( GetFullPath(), &stBuf) == 0 )
2654 {
2655 if ( dtAccess )
2656 dtAccess->Set(stBuf.st_atime);
2657 if ( dtMod )
2658 dtMod->Set(stBuf.st_mtime);
2659 if ( dtCreate )
2660 dtCreate->Set(stBuf.st_ctime);
2661
2662 return true;
2663 }
2664 #else // other platform
2665 wxUnusedVar(dtAccess);
2666 wxUnusedVar(dtMod);
2667 wxUnusedVar(dtCreate);
2668 #endif // platforms
2669
2670 wxLogSysError(_("Failed to retrieve file times for '%s'"),
2671 GetFullPath().c_str());
2672
2673 return false;
2674 }
2675
2676 #endif // wxUSE_DATETIME
2677
2678
2679 // ----------------------------------------------------------------------------
2680 // file size functions
2681 // ----------------------------------------------------------------------------
2682
2683 #if wxUSE_LONGLONG
2684
2685 /* static */
2686 wxULongLong wxFileName::GetSize(const wxString &filename)
2687 {
2688 if (!wxFileExists(filename))
2689 return wxInvalidSize;
2690
2691 #if defined(__WIN32__)
2692 wxFileHandle f(filename, wxFileHandle::ReadAttr);
2693 if (!f.IsOk())
2694 return wxInvalidSize;
2695
2696 DWORD lpFileSizeHigh;
2697 DWORD ret = GetFileSize(f, &lpFileSizeHigh);
2698 if ( ret == INVALID_FILE_SIZE && ::GetLastError() != NO_ERROR )
2699 return wxInvalidSize;
2700
2701 return wxULongLong(lpFileSizeHigh, ret);
2702 #else // ! __WIN32__
2703 wxStructStat st;
2704 if (wxStat( filename, &st) != 0)
2705 return wxInvalidSize;
2706 return wxULongLong(st.st_size);
2707 #endif
2708 }
2709
2710 /* static */
2711 wxString wxFileName::GetHumanReadableSize(const wxULongLong &bs,
2712 const wxString &nullsize,
2713 int precision,
2714 wxSizeConvention conv)
2715 {
2716 // deal with trivial case first
2717 if ( bs == 0 || bs == wxInvalidSize )
2718 return nullsize;
2719
2720 // depending on the convention used the multiplier may be either 1000 or
2721 // 1024 and the binary infix may be empty (for "KB") or "i" (for "KiB")
2722 double multiplier = 1024.;
2723 wxString biInfix;
2724
2725 switch ( conv )
2726 {
2727 case wxSIZE_CONV_TRADITIONAL:
2728 // nothing to do, this corresponds to the default values of both
2729 // the multiplier and infix string
2730 break;
2731
2732 case wxSIZE_CONV_IEC:
2733 biInfix = "i";
2734 break;
2735
2736 case wxSIZE_CONV_SI:
2737 multiplier = 1000;
2738 break;
2739 }
2740
2741 const double kiloByteSize = multiplier;
2742 const double megaByteSize = multiplier * kiloByteSize;
2743 const double gigaByteSize = multiplier * megaByteSize;
2744 const double teraByteSize = multiplier * gigaByteSize;
2745
2746 const double bytesize = bs.ToDouble();
2747
2748 wxString result;
2749 if ( bytesize < kiloByteSize )
2750 result.Printf("%s B", bs.ToString());
2751 else if ( bytesize < megaByteSize )
2752 result.Printf("%.*f K%sB", precision, bytesize/kiloByteSize, biInfix);
2753 else if (bytesize < gigaByteSize)
2754 result.Printf("%.*f M%sB", precision, bytesize/megaByteSize, biInfix);
2755 else if (bytesize < teraByteSize)
2756 result.Printf("%.*f G%sB", precision, bytesize/gigaByteSize, biInfix);
2757 else
2758 result.Printf("%.*f T%sB", precision, bytesize/teraByteSize, biInfix);
2759
2760 return result;
2761 }
2762
2763 wxULongLong wxFileName::GetSize() const
2764 {
2765 return GetSize(GetFullPath());
2766 }
2767
2768 wxString wxFileName::GetHumanReadableSize(const wxString& failmsg,
2769 int precision,
2770 wxSizeConvention conv) const
2771 {
2772 return GetHumanReadableSize(GetSize(), failmsg, precision, conv);
2773 }
2774
2775 #endif // wxUSE_LONGLONG
2776
2777 // ----------------------------------------------------------------------------
2778 // Mac-specific functions
2779 // ----------------------------------------------------------------------------
2780
2781 #if defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON
2782
2783 namespace
2784 {
2785
2786 class MacDefaultExtensionRecord
2787 {
2788 public:
2789 MacDefaultExtensionRecord()
2790 {
2791 m_type =
2792 m_creator = 0 ;
2793 }
2794
2795 // default copy ctor, assignment operator and dtor are ok
2796
2797 MacDefaultExtensionRecord(const wxString& ext, OSType type, OSType creator)
2798 : m_ext(ext)
2799 {
2800 m_type = type;
2801 m_creator = creator;
2802 }
2803
2804 wxString m_ext;
2805 OSType m_type;
2806 OSType m_creator;
2807 };
2808
2809 WX_DECLARE_OBJARRAY(MacDefaultExtensionRecord, MacDefaultExtensionArray);
2810
2811 bool gMacDefaultExtensionsInited = false;
2812
2813 #include "wx/arrimpl.cpp"
2814
2815 WX_DEFINE_EXPORTED_OBJARRAY(MacDefaultExtensionArray);
2816
2817 MacDefaultExtensionArray gMacDefaultExtensions;
2818
2819 // load the default extensions
2820 const MacDefaultExtensionRecord gDefaults[] =
2821 {
2822 MacDefaultExtensionRecord( "txt", 'TEXT', 'ttxt' ),
2823 MacDefaultExtensionRecord( "tif", 'TIFF', '****' ),
2824 MacDefaultExtensionRecord( "jpg", 'JPEG', '****' ),
2825 };
2826
2827 void MacEnsureDefaultExtensionsLoaded()
2828 {
2829 if ( !gMacDefaultExtensionsInited )
2830 {
2831 // we could load the pc exchange prefs here too
2832 for ( size_t i = 0 ; i < WXSIZEOF( gDefaults ) ; ++i )
2833 {
2834 gMacDefaultExtensions.Add( gDefaults[i] ) ;
2835 }
2836 gMacDefaultExtensionsInited = true;
2837 }
2838 }
2839
2840 } // anonymous namespace
2841
2842 bool wxFileName::MacSetTypeAndCreator( wxUint32 type , wxUint32 creator )
2843 {
2844 FSRef fsRef ;
2845 FSCatalogInfo catInfo;
2846 FileInfo *finfo ;
2847
2848 if ( wxMacPathToFSRef( GetFullPath() , &fsRef ) == noErr )
2849 {
2850 if ( FSGetCatalogInfo (&fsRef, kFSCatInfoFinderInfo, &catInfo, NULL, NULL, NULL) == noErr )
2851 {
2852 finfo = (FileInfo*)&catInfo.finderInfo;
2853 finfo->fileType = type ;
2854 finfo->fileCreator = creator ;
2855 FSSetCatalogInfo( &fsRef, kFSCatInfoFinderInfo, &catInfo ) ;
2856 return true ;
2857 }
2858 }
2859 return false ;
2860 }
2861
2862 bool wxFileName::MacGetTypeAndCreator( wxUint32 *type , wxUint32 *creator ) const
2863 {
2864 FSRef fsRef ;
2865 FSCatalogInfo catInfo;
2866 FileInfo *finfo ;
2867
2868 if ( wxMacPathToFSRef( GetFullPath() , &fsRef ) == noErr )
2869 {
2870 if ( FSGetCatalogInfo (&fsRef, kFSCatInfoFinderInfo, &catInfo, NULL, NULL, NULL) == noErr )
2871 {
2872 finfo = (FileInfo*)&catInfo.finderInfo;
2873 *type = finfo->fileType ;
2874 *creator = finfo->fileCreator ;
2875 return true ;
2876 }
2877 }
2878 return false ;
2879 }
2880
2881 bool wxFileName::MacSetDefaultTypeAndCreator()
2882 {
2883 wxUint32 type , creator ;
2884 if ( wxFileName::MacFindDefaultTypeAndCreator(GetExt() , &type ,
2885 &creator ) )
2886 {
2887 return MacSetTypeAndCreator( type , creator ) ;
2888 }
2889 return false;
2890 }
2891
2892 bool wxFileName::MacFindDefaultTypeAndCreator( const wxString& ext , wxUint32 *type , wxUint32 *creator )
2893 {
2894 MacEnsureDefaultExtensionsLoaded() ;
2895 wxString extl = ext.Lower() ;
2896 for( int i = gMacDefaultExtensions.Count() - 1 ; i >= 0 ; --i )
2897 {
2898 if ( gMacDefaultExtensions.Item(i).m_ext == extl )
2899 {
2900 *type = gMacDefaultExtensions.Item(i).m_type ;
2901 *creator = gMacDefaultExtensions.Item(i).m_creator ;
2902 return true ;
2903 }
2904 }
2905 return false ;
2906 }
2907
2908 void wxFileName::MacRegisterDefaultTypeAndCreator( const wxString& ext , wxUint32 type , wxUint32 creator )
2909 {
2910 MacEnsureDefaultExtensionsLoaded();
2911 MacDefaultExtensionRecord rec(ext.Lower(), type, creator);
2912 gMacDefaultExtensions.Add( rec );
2913 }
2914
2915 #endif // defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON