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