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