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