drive:\dir1\dir2\...\dirN\filename.ext where drive is a single
letter. "." and ".." as for Unix but no "~".
- There are also UNC names of the form \\share\fullpath
+ There are also UNC names of the form \\share\fullpath and
+ MSW unique volume names of the form \\?\Volume{GUID}\fullpath.
- wxPATH_MAC: Mac OS 8/9 and Mac OS X under CodeWarrior 7 format, absolute file
+ The latter provide a uniform way to access a volume regardless of
+ its current mount point, i.e. you can change a volume's mount
+ point from D: to E:, or even remove it, and still be able to
+ access it through its unique volume name. More on the subject can
+ be found in MSDN's article "Naming a Volume" that is currently at
+ http://msdn.microsoft.com/en-us/library/aa365248(VS.85).aspx.
+
+
+ wxPATH_MAC: Mac OS 8/9 only, not used any longer, absolute file
names have the form
volume:dir1:...:dirN:filename
and the relative file names are either
Note that VMS uses different separators unlike Unix:
: always after the device. If the path does not contain : than
the default (the device of the current directory) is assumed.
- [ start of directory specyfication
+ [ start of directory specification
. separator between directory and subdirectory
] between directory and file
*/
// headers
// ----------------------------------------------------------------------------
-#if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
-#pragma implementation "filename.h"
-#endif
-
// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"
#endif
#ifndef WX_PRECOMP
-#include "wx/intl.h"
-#include "wx/log.h"
-#include "wx/file.h"
+ #ifdef __WINDOWS__
+ #include "wx/msw/wrapwin.h" // For GetShort/LongPathName
+ #endif
+ #include "wx/dynarray.h"
+ #include "wx/intl.h"
+ #include "wx/log.h"
+ #include "wx/utils.h"
+ #include "wx/crt.h"
#endif
#include "wx/filename.h"
+#include "wx/private/filename.h"
#include "wx/tokenzr.h"
#include "wx/config.h" // for wxExpandEnvVars
-#include "wx/utils.h"
-#include "wx/file.h"
#include "wx/dynlib.h"
+#include "wx/dir.h"
-// For GetShort/LongPathName
-#ifdef __WIN32__
-#include "wx/msw/wrapwin.h"
+#if defined(__WIN32__) && defined(__MINGW32__)
+ #include "wx/msw/gccpriv.h"
#endif
-#ifdef __WXWINCE__
+#ifdef __WINDOWS__
#include "wx/msw/private.h"
#endif
#if defined(__WXMAC__)
- #include "wx/mac/private.h" // includes mac headers
+ #include "wx/osx/private.h" // includes mac headers
#endif
// utime() is POSIX so should normally be available on all Unices
#include <unistd.h>
#endif
-#ifdef __MWERKS__
-#ifdef __MACH__
-#include <sys/types.h>
-#include <utime.h>
-#include <sys/stat.h>
-#include <unistd.h>
-#else
-#include <stat.h>
-#include <unistd.h>
-#include <unix.h>
-#endif
-#endif
-
#ifdef __WATCOMC__
#include <io.h>
#include <sys/utime.h>
#define MAX_PATH _MAX_PATH
#endif
+#ifndef S_ISREG
+ #define S_ISREG(mode) ((mode) & S_IFREG)
+#endif
+#ifndef S_ISDIR
+ #define S_ISDIR(mode) ((mode) & S_IFDIR)
+#endif
+
+#if wxUSE_LONGLONG
+extern const wxULongLong wxInvalidSize = (unsigned)-1;
+#endif // wxUSE_LONGLONG
+
+namespace
+{
+
// ----------------------------------------------------------------------------
// private classes
// ----------------------------------------------------------------------------
public:
enum OpenMode
{
- Read,
- Write
+ ReadAttr,
+ WriteAttr
};
- wxFileHandle(const wxString& filename, OpenMode mode)
+ wxFileHandle(const wxString& filename, OpenMode mode, int flags = 0)
{
+ // be careful and use FILE_{READ,WRITE}_ATTRIBUTES here instead of the
+ // usual GENERIC_{READ,WRITE} as we don't want the file access time to
+ // be changed when we open it because this class is used for setting
+ // access time (see #10567)
m_hFile = ::CreateFile
(
- filename, // name
- mode == Read ? GENERIC_READ // access mask
- : GENERIC_WRITE,
- 0, // no sharing
+ filename.t_str(), // name
+ mode == ReadAttr ? FILE_READ_ATTRIBUTES // access mask
+ : FILE_WRITE_ATTRIBUTES,
+ FILE_SHARE_READ | // sharing mode
+ FILE_SHARE_WRITE, // (allow everything)
NULL, // no secutity attr
OPEN_EXISTING, // creation disposition
- 0, // no flags
+ flags, // flags
NULL // no template file
);
if ( m_hFile == INVALID_HANDLE_VALUE )
{
- wxLogSysError(_("Failed to open '%s' for %s"),
- filename.c_str(),
- mode == Read ? _("reading") : _("writing"));
+ if ( mode == ReadAttr )
+ {
+ wxLogSysError(_("Failed to open '%s' for reading"),
+ filename.c_str());
+ }
+ else
+ {
+ wxLogSysError(_("Failed to open '%s' for writing"),
+ filename.c_str());
+ }
}
}
FILETIME ftLocal;
if ( !::FileTimeToLocalFileTime(&ftcopy, &ftLocal) )
{
- wxLogLastError(_T("FileTimeToLocalFileTime"));
+ wxLogLastError(wxT("FileTimeToLocalFileTime"));
}
SYSTEMTIME st;
if ( !::FileTimeToSystemTime(&ftLocal, &st) )
{
- wxLogLastError(_T("FileTimeToSystemTime"));
+ wxLogLastError(wxT("FileTimeToSystemTime"));
}
dt->Set(st.wDay, wxDateTime::Month(st.wMonth - 1), st.wYear,
{
SYSTEMTIME st;
st.wDay = dt.GetDay();
- st.wMonth = dt.GetMonth() + 1;
- st.wYear = dt.GetYear();
+ st.wMonth = (WORD)(dt.GetMonth() + 1);
+ st.wYear = (WORD)dt.GetYear();
st.wHour = dt.GetHour();
st.wMinute = dt.GetMinute();
st.wSecond = dt.GetSecond();
FILETIME ftLocal;
if ( !::SystemTimeToFileTime(&st, &ftLocal) )
{
- wxLogLastError(_T("SystemTimeToFileTime"));
+ wxLogLastError(wxT("SystemTimeToFileTime"));
}
if ( !::LocalFileTimeToFileTime(&ftLocal, ft) )
{
- wxLogLastError(_T("LocalFileTimeToFileTime"));
+ wxLogLastError(wxT("LocalFileTimeToFileTime"));
}
}
// although I didn't find any authoritative docs on this)
if ( format == wxPATH_DOS && volume.length() > 1 )
{
- path << wxFILE_SEP_PATH_DOS << wxFILE_SEP_PATH_DOS << volume;
+ // We also have to check for Windows unique volume names here and
+ // return it with '\\?\' prepended to it
+ if ( wxFileName::IsMSWUniqueVolumeNamePath("\\\\?\\" + volume + "\\",
+ format) )
+ {
+ path << "\\\\?\\" << volume;
+ }
+ else
+ {
+ // it must be a UNC path
+ path << wxFILE_SEP_PATH_DOS << wxFILE_SEP_PATH_DOS << volume;
+ }
}
else if ( format == wxPATH_DOS || format == wxPATH_VMS )
{
return path;
}
+// return true if the character is a DOS path separator i.e. either a slash or
+// a backslash
+inline bool IsDOSPathSep(wxUniChar ch)
+{
+ return ch == wxFILE_SEP_PATH_DOS || ch == wxFILE_SEP_PATH_UNIX;
+}
+
+// return true if the format used is the DOS/Windows one and the string looks
+// like a UNC path
+static bool IsUNCPath(const wxString& path, wxPathFormat format)
+{
+ return format == wxPATH_DOS &&
+ path.length() >= 4 && // "\\a" can't be a UNC path
+ IsDOSPathSep(path[0u]) &&
+ IsDOSPathSep(path[1u]) &&
+ !IsDOSPathSep(path[2u]);
+}
+
+#ifndef __WIN32__
+
+// Under Unix-ish systems (basically everything except Windows) we may work
+// either with the file itself or its target if it's a symbolic link and we
+// should dereference it, as determined by wxFileName::ShouldFollowLink() and
+// the absence of the wxFILE_EXISTS_NO_FOLLOW flag. StatAny() can be used to
+// stat the appropriate file with an extra twist that it also works when there
+// is no wxFileName object at all, as is the case in static methods.
+
+// Private implementation, don't call directly, use one of the overloads below.
+bool DoStatAny(wxStructStat& st, wxString path, bool dereference)
+{
+ // We need to remove any trailing slashes from the path because they could
+ // interfere with the symlink following decision: even if we use lstat(),
+ // it would still follow the symlink if we pass it a path with a slash at
+ // the end because the symlink resolution would happen while following the
+ // path and not for the last path element itself.
+
+ while ( wxEndsWithPathSeparator(path) )
+ {
+ const size_t posLast = path.length() - 1;
+ if ( !posLast )
+ {
+ // Don't turn "/" into empty string.
+ break;
+ }
+
+ path.erase(posLast);
+ }
+
+ int ret = dereference ? wxStat(path, &st) : wxLstat(path, &st);
+ return ret == 0;
+}
+
+// Overloads to use for a case when we don't have wxFileName object and when we
+// do have one.
+inline
+bool StatAny(wxStructStat& st, const wxString& path, int flags)
+{
+ return DoStatAny(st, path, !(flags & wxFILE_EXISTS_NO_FOLLOW));
+}
+
+inline
+bool StatAny(wxStructStat& st, const wxFileName& fn)
+{
+ return DoStatAny(st, fn.GetFullPath(), fn.ShouldFollowLink());
+}
+
+#endif // !__WIN32__
+
+// ----------------------------------------------------------------------------
+// private constants
+// ----------------------------------------------------------------------------
+
+// length of \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ string
+static const size_t wxMSWUniqueVolumePrefixLength = 49;
+
+} // anonymous namespace
+
// ============================================================================
// implementation
// ============================================================================
m_name = filepath.GetName();
m_ext = filepath.GetExt();
m_relative = filepath.m_relative;
+ m_hasExt = filepath.m_hasExt;
+ m_dontFollowLinks = filepath.m_dontFollowLinks;
}
void wxFileName::Assign(const wxString& volume,
const wxString& path,
const wxString& name,
const wxString& ext,
- wxPathFormat format )
+ bool hasExt,
+ wxPathFormat format)
{
- SetPath( path, format );
+ // we should ignore paths which look like UNC shares because we already
+ // have the volume here and the UNC notation (\\server\path) is only valid
+ // for paths which don't start with a volume, so prevent SetPath() from
+ // recognizing "\\foo\bar" in "c:\\foo\bar" as an UNC path
+ //
+ // note also that this is a rather ugly way to do what we want (passing
+ // some kind of flag telling to ignore UNC paths to SetPath() would be
+ // better) but this is the safest thing to do to avoid breaking backwards
+ // compatibility in 2.8
+ if ( IsUNCPath(path, format) )
+ {
+ // remove one of the 2 leading backslashes to ensure that it's not
+ // recognized as an UNC path by SetPath()
+ wxString pathNonUNC(path, 1, wxString::npos);
+ SetPath(pathNonUNC, format);
+ }
+ else // no UNC complications
+ {
+ SetPath(path, format);
+ }
m_volume = volume;
m_ext = ext;
m_name = name;
+
+ m_hasExt = hasExt;
}
-void wxFileName::SetPath( const wxString &path, wxPathFormat format )
+void wxFileName::SetPath( const wxString& pathOrig, wxPathFormat format )
{
m_dirs.Clear();
- if ( !path.empty() )
+ if ( pathOrig.empty() )
{
- wxPathFormat my_format = GetFormat( format );
- wxString my_path = path;
+ // no path at all
+ m_relative = true;
- // 1) Determine if the path is relative or absolute.
- wxChar leadingChar = my_path[0u];
+ return;
+ }
- switch (my_format)
- {
- case wxPATH_MAC:
- m_relative = leadingChar == wxT(':');
-
- // We then remove a leading ":". The reason is in our
- // storage form for relative paths:
- // ":dir:file.txt" actually means "./dir/file.txt" in
- // DOS notation and should get stored as
- // (relative) (dir) (file.txt)
- // "::dir:file.txt" actually means "../dir/file.txt"
- // stored as (relative) (..) (dir) (file.txt)
- // This is important only for the Mac as an empty dir
- // actually means <UP>, whereas under DOS, double
- // slashes can be ignored: "\\\\" is the same as "\\".
- if (m_relative)
- my_path.erase( 0, 1 );
- break;
+ format = GetFormat( format );
- case wxPATH_VMS:
- // TODO: what is the relative path format here?
- m_relative = false;
- break;
+ // 0) deal with possible volume part first
+ wxString volume,
+ path;
+ SplitVolume(pathOrig, &volume, &path, format);
+ if ( !volume.empty() )
+ {
+ m_relative = false;
- default:
- wxFAIL_MSG( _T("Unknown path format") );
- // !! Fall through !!
+ SetVolume(volume);
+ }
- case wxPATH_UNIX:
- // the paths of the form "~" or "~username" are absolute
- m_relative = leadingChar != wxT('/') && leadingChar != _T('~');
- break;
+ // 1) Determine if the path is relative or absolute.
- case wxPATH_DOS:
- m_relative = !IsPathSeparator(leadingChar, my_format);
- break;
+ if ( path.empty() )
+ {
+ // we had only the volume
+ return;
+ }
- }
+ wxChar leadingChar = path[0u];
+
+ switch (format)
+ {
+ case wxPATH_MAC:
+ m_relative = leadingChar == wxT(':');
+
+ // We then remove a leading ":". The reason is in our
+ // storage form for relative paths:
+ // ":dir:file.txt" actually means "./dir/file.txt" in
+ // DOS notation and should get stored as
+ // (relative) (dir) (file.txt)
+ // "::dir:file.txt" actually means "../dir/file.txt"
+ // stored as (relative) (..) (dir) (file.txt)
+ // This is important only for the Mac as an empty dir
+ // actually means <UP>, whereas under DOS, double
+ // slashes can be ignored: "\\\\" is the same as "\\".
+ if (m_relative)
+ path.erase( 0, 1 );
+ break;
- // 2) Break up the path into its members. If the original path
- // was just "/" or "\\", m_dirs will be empty. We know from
- // the m_relative field, if this means "nothing" or "root dir".
+ case wxPATH_VMS:
+ // TODO: what is the relative path format here?
+ m_relative = false;
+ break;
- wxStringTokenizer tn( my_path, GetPathSeparators(my_format) );
+ default:
+ wxFAIL_MSG( wxT("Unknown path format") );
+ // !! Fall through !!
- while ( tn.HasMoreTokens() )
- {
- wxString token = tn.GetNextToken();
+ case wxPATH_UNIX:
+ m_relative = leadingChar != wxT('/');
+ break;
+
+ case wxPATH_DOS:
+ m_relative = !IsPathSeparator(leadingChar, format);
+ break;
- // Remove empty token under DOS and Unix, interpret them
- // as .. under Mac.
- if (token.empty())
- {
- if (my_format == wxPATH_MAC)
- m_dirs.Add( wxT("..") );
- // else ignore
- }
- else
- {
- m_dirs.Add( token );
- }
- }
}
- else // no path at all
+
+ // 2) Break up the path into its members. If the original path
+ // was just "/" or "\\", m_dirs will be empty. We know from
+ // the m_relative field, if this means "nothing" or "root dir".
+
+ wxStringTokenizer tn( path, GetPathSeparators(format) );
+
+ while ( tn.HasMoreTokens() )
{
- m_relative = true;
+ wxString token = tn.GetNextToken();
+
+ // Remove empty token under DOS and Unix, interpret them
+ // as .. under Mac.
+ if (token.empty())
+ {
+ if (format == wxPATH_MAC)
+ m_dirs.Add( wxT("..") );
+ // else ignore
+ }
+ else
+ {
+ m_dirs.Add( token );
+ }
}
}
wxPathFormat format)
{
wxString volume, path, name, ext;
- SplitPath(fullpath, &volume, &path, &name, &ext, format);
+ bool hasExt;
+ SplitPath(fullpath, &volume, &path, &name, &ext, &hasExt, format);
- Assign(volume, path, name, ext, format);
+ Assign(volume, path, name, ext, hasExt, format);
}
void wxFileName::Assign(const wxString& fullpathOrig,
// always recognize fullpath as directory, even if it doesn't end with a
// slash
wxString fullpath = fullpathOrig;
- if ( !wxEndsWithPathSeparator(fullpath) )
+ if ( !fullpath.empty() && !wxEndsWithPathSeparator(fullpath) )
{
fullpath += GetPathSeparator(format);
}
wxString volume, path, name, ext;
+ bool hasExt;
- // do some consistency checks in debug mode: the name should be really just
- // the filename and the path should be really just a path
-#ifdef __WXDEBUG__
- wxString pathDummy, nameDummy, extDummy;
+ // do some consistency checks: the name should be really just the filename
+ // and the path should be really just a path
+ wxString volDummy, pathDummy, nameDummy, extDummy;
- SplitPath(fullname, &pathDummy, &name, &ext, format);
+ SplitPath(fullname, &volDummy, &pathDummy, &name, &ext, &hasExt, format);
- wxASSERT_MSG( pathDummy.empty(),
- _T("the file name shouldn't contain the path") );
+ wxASSERT_MSG( volDummy.empty() && pathDummy.empty(),
+ wxT("the file name shouldn't contain the path") );
SplitPath(fullpath, &volume, &path, &nameDummy, &extDummy, format);
- wxASSERT_MSG( nameDummy.empty() && extDummy.empty(),
- _T("the path shouldn't contain file name nor extension") );
+#ifndef __VMS
+ // This test makes no sense on an OpenVMS system.
+ wxASSERT_MSG( nameDummy.empty() && extDummy.empty(),
+ wxT("the path shouldn't contain file name nor extension") );
+#endif
+ Assign(volume, path, name, ext, hasExt, format);
+}
-#else // !__WXDEBUG__
- SplitPath(fullname, NULL /* no path */, &name, &ext, format);
- SplitPath(fullpath, &volume, &path, NULL, NULL, format);
-#endif // __WXDEBUG__/!__WXDEBUG__
+void wxFileName::Assign(const wxString& pathOrig,
+ const wxString& name,
+ const wxString& ext,
+ wxPathFormat format)
+{
+ wxString volume,
+ path;
+ SplitVolume(pathOrig, &volume, &path, format);
Assign(volume, path, name, ext, format);
}
void wxFileName::AssignDir(const wxString& dir, wxPathFormat format)
{
- Assign(dir, _T(""), format);
+ Assign(dir, wxEmptyString, format);
}
void wxFileName::Clear()
// we don't have any absolute path for now
m_relative = true;
+
+ // nor any extension
+ m_hasExt = false;
+
+ // follow symlinks by default
+ m_dontFollowLinks = false;
}
/* static */
// existence tests
// ----------------------------------------------------------------------------
+namespace
+{
+
+#if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
+
+void RemoveTrailingSeparatorsFromPath(wxString& strPath)
+{
+ // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
+ // so remove all trailing backslashes from the path - but don't do this for
+ // the paths "d:\" (which are different from "d:"), for just "\" or for
+ // windows unique volume names ("\\?\Volume{GUID}\")
+ while ( wxEndsWithPathSeparator( strPath ) )
+ {
+ size_t len = strPath.length();
+ if ( len == 1 || (len == 3 && strPath[len - 2] == wxT(':')) ||
+ (len == wxMSWUniqueVolumePrefixLength &&
+ wxFileName::IsMSWUniqueVolumeNamePath(strPath)))
+ {
+ break;
+ }
+
+ strPath.Truncate(len - 1);
+ }
+}
+
+#endif // __WINDOWS__ || __OS2__
+
+bool
+wxFileSystemObjectExists(const wxString& path, int flags)
+{
+
+ // Should the existence of file/directory with this name be accepted, i.e.
+ // result in the true return value from this function?
+ const bool acceptFile = (flags & wxFILE_EXISTS_REGULAR) != 0;
+ const bool acceptDir = (flags & wxFILE_EXISTS_DIR) != 0;
+
+ wxString strPath(path);
+
+#if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
+ if ( acceptDir )
+ {
+ // Ensure that the path doesn't have any trailing separators when
+ // checking for directories.
+ RemoveTrailingSeparatorsFromPath(strPath);
+ }
+
+ // we must use GetFileAttributes() instead of the ANSI C functions because
+ // it can cope with network (UNC) paths unlike them
+ DWORD ret = ::GetFileAttributes(strPath.t_str());
+
+ if ( ret == INVALID_FILE_ATTRIBUTES )
+ return false;
+
+ if ( ret & FILE_ATTRIBUTE_DIRECTORY )
+ return acceptDir;
+
+ // Anything else must be a file (perhaps we should check for
+ // FILE_ATTRIBUTE_REPARSE_POINT?)
+ return acceptFile;
+#elif defined(__OS2__)
+ if ( acceptDir )
+ {
+ // OS/2 can't handle "d:", it wants either "d:\" or "d:."
+ if (strPath.length() == 2 && strPath[1u] == wxT(':'))
+ strPath << wxT('.');
+ }
+
+ FILESTATUS3 Info = {{0}};
+ APIRET rc = ::DosQueryPathInfo((PSZ)(WXSTRINGCAST strPath), FIL_STANDARD,
+ (void*) &Info, sizeof(FILESTATUS3));
+
+ if ( rc == NO_ERROR )
+ {
+ if ( Info.attrFile & FILE_DIRECTORY )
+ return acceptDir;
+ else
+ return acceptFile;
+ }
+
+ // We consider that the path must exist if we get a sharing violation for
+ // it but we don't know what is it in this case.
+ if ( rc == ERROR_SHARING_VIOLATION )
+ return flags & wxFILE_EXISTS_ANY;
+
+ // Any other error (usually ERROR_PATH_NOT_FOUND), means there is nothing
+ // there.
+ return false;
+#else // Non-MSW, non-OS/2
+ wxStructStat st;
+ if ( !StatAny(st, strPath, flags) )
+ return false;
+
+ if ( S_ISREG(st.st_mode) )
+ return acceptFile;
+ if ( S_ISDIR(st.st_mode) )
+ return acceptDir;
+ if ( S_ISLNK(st.st_mode) )
+ {
+ // Take care to not test for "!= 0" here as this would erroneously
+ // return true if only wxFILE_EXISTS_NO_FOLLOW, which is part of
+ // wxFILE_EXISTS_SYMLINK, is set too.
+ return (flags & wxFILE_EXISTS_SYMLINK) == wxFILE_EXISTS_SYMLINK;
+ }
+ if ( S_ISBLK(st.st_mode) || S_ISCHR(st.st_mode) )
+ return (flags & wxFILE_EXISTS_DEVICE) != 0;
+ if ( S_ISFIFO(st.st_mode) )
+ return (flags & wxFILE_EXISTS_FIFO) != 0;
+ if ( S_ISSOCK(st.st_mode) )
+ return (flags & wxFILE_EXISTS_SOCKET) != 0;
+
+ return flags & wxFILE_EXISTS_ANY;
+#endif // Platforms
+}
+
+} // anonymous namespace
+
bool wxFileName::FileExists() const
{
- return wxFileName::FileExists( GetFullPath() );
+ int flags = wxFILE_EXISTS_REGULAR;
+ if ( !ShouldFollowLink() )
+ flags |= wxFILE_EXISTS_NO_FOLLOW;
+
+ return wxFileSystemObjectExists(GetFullPath(), flags);
}
-bool wxFileName::FileExists( const wxString &file )
+/* static */
+bool wxFileName::FileExists( const wxString &filePath )
{
- return ::wxFileExists( file );
+ return wxFileSystemObjectExists(filePath, wxFILE_EXISTS_REGULAR);
}
bool wxFileName::DirExists() const
{
- return wxFileName::DirExists( GetFullPath() );
+ int flags = wxFILE_EXISTS_DIR;
+ if ( !ShouldFollowLink() )
+ flags |= wxFILE_EXISTS_NO_FOLLOW;
+
+ return Exists(GetPath(), flags);
+}
+
+/* static */
+bool wxFileName::DirExists( const wxString &dirPath )
+{
+ return wxFileSystemObjectExists(dirPath, wxFILE_EXISTS_DIR);
}
-bool wxFileName::DirExists( const wxString &dir )
+bool wxFileName::Exists(int flags) const
{
- return ::wxDirExists( dir );
+ // Notice that wxFILE_EXISTS_NO_FOLLOW may be specified in the flags even
+ // if our DontFollowLink() hadn't been called and we do honour it then. But
+ // if the user took the care of calling DontFollowLink(), it is always
+ // taken into account.
+ if ( !ShouldFollowLink() )
+ flags |= wxFILE_EXISTS_NO_FOLLOW;
+
+ return wxFileSystemObjectExists(GetFullPath(), flags);
+}
+
+/* static */
+bool wxFileName::Exists(const wxString& path, int flags)
+{
+ return wxFileSystemObjectExists(path, flags);
}
// ----------------------------------------------------------------------------
return cwd;
}
-bool wxFileName::SetCwd()
+bool wxFileName::SetCwd() const
{
- return wxFileName::SetCwd( GetFullPath() );
+ return wxFileName::SetCwd( GetPath() );
}
bool wxFileName::SetCwd( const wxString &cwd )
return ::wxGetHomeDir();
}
-void wxFileName::AssignTempFileName(const wxString& prefix, wxFile *fileTemp)
+
+// ----------------------------------------------------------------------------
+// CreateTempFileName
+// ----------------------------------------------------------------------------
+
+#if wxUSE_FILE || wxUSE_FFILE
+
+
+#if !defined wx_fdopen && defined HAVE_FDOPEN
+ #define wx_fdopen fdopen
+#endif
+
+// NB: GetTempFileName() under Windows creates the file, so using
+// O_EXCL there would fail
+#ifdef __WINDOWS__
+ #define wxOPEN_EXCL 0
+#else
+ #define wxOPEN_EXCL O_EXCL
+#endif
+
+
+#ifdef wxOpenOSFHandle
+#define WX_HAVE_DELETE_ON_CLOSE
+// On Windows create a file with the FILE_FLAGS_DELETE_ON_CLOSE flags.
+//
+static int wxOpenWithDeleteOnClose(const wxString& filename)
{
- wxString tempname = CreateTempFileName(prefix, fileTemp);
- if ( tempname.empty() )
- {
- // error, failed to get temp file name
- Clear();
- }
- else // ok
- {
- Assign(tempname);
- }
+ DWORD access = GENERIC_READ | GENERIC_WRITE;
+
+ DWORD disposition = OPEN_ALWAYS;
+
+ DWORD attributes = FILE_ATTRIBUTE_TEMPORARY |
+ FILE_FLAG_DELETE_ON_CLOSE;
+
+ HANDLE h = ::CreateFile(filename.t_str(), access, 0, NULL,
+ disposition, attributes, NULL);
+
+ return wxOpenOSFHandle(h, wxO_BINARY);
}
+#endif // wxOpenOSFHandle
-/* static */
-wxString
-wxFileName::CreateTempFileName(const wxString& prefix, wxFile *fileTemp)
+
+// Helper to open the file
+//
+static int wxTempOpen(const wxString& path, bool *deleteOnClose)
{
+#ifdef WX_HAVE_DELETE_ON_CLOSE
+ if (*deleteOnClose)
+ return wxOpenWithDeleteOnClose(path);
+#endif
+
+ *deleteOnClose = false;
+
+ return wxOpen(path, wxO_BINARY | O_RDWR | O_CREAT | wxOPEN_EXCL, 0600);
+}
+
+
+#if wxUSE_FFILE
+// Helper to open the file and attach it to the wxFFile
+//
+static bool wxTempOpen(wxFFile *file, const wxString& path, bool *deleteOnClose)
+{
+#ifndef wx_fdopen
+ *deleteOnClose = false;
+ return file->Open(path, wxT("w+b"));
+#else // wx_fdopen
+ int fd = wxTempOpen(path, deleteOnClose);
+ if (fd == -1)
+ return false;
+ file->Attach(wx_fdopen(fd, "w+b"), path);
+ return file->IsOpened();
+#endif // wx_fdopen
+}
+#endif // wxUSE_FFILE
+
+
+#if !wxUSE_FILE
+ #define WXFILEARGS(x, y) y
+#elif !wxUSE_FFILE
+ #define WXFILEARGS(x, y) x
+#else
+ #define WXFILEARGS(x, y) x, y
+#endif
+
+
+// Implementation of wxFileName::CreateTempFileName().
+//
+static wxString wxCreateTempImpl(
+ const wxString& prefix,
+ WXFILEARGS(wxFile *fileTemp, wxFFile *ffileTemp),
+ bool *deleteOnClose = NULL)
+{
+#if wxUSE_FILE && wxUSE_FFILE
+ wxASSERT(fileTemp == NULL || ffileTemp == NULL);
+#endif
wxString path, dir, name;
+ bool wantDeleteOnClose = false;
+
+ if (deleteOnClose)
+ {
+ // set the result to false initially
+ wantDeleteOnClose = *deleteOnClose;
+ *deleteOnClose = false;
+ }
+ else
+ {
+ // easier if it alwasys points to something
+ deleteOnClose = &wantDeleteOnClose;
+ }
// use the directory specified by the prefix
- SplitPath(prefix, &dir, &name, NULL /* extension */);
+ wxFileName::SplitPath(prefix, &dir, &name, NULL /* extension */);
-#if defined(__WXWINCE__)
if (dir.empty())
{
- // FIXME. Create \temp dir?
- dir = wxT("\\");
+ dir = wxFileName::GetTempDir();
}
- path = dir + wxT("\\") + prefix;
+
+#if defined(__WXWINCE__)
+ path = dir + wxT("\\") + name;
int i = 1;
- while (wxFileExists(path))
+ while (wxFileName::FileExists(path))
{
- path = dir + wxT("\\") + prefix ;
+ path = dir + wxT("\\") + name ;
path << i;
i ++;
}
#elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
-#ifdef __WIN32__
- if ( dir.empty() )
+ if (!::GetTempFileName(dir.t_str(), name.t_str(), 0,
+ wxStringBuffer(path, MAX_PATH + 1)))
{
- if ( !::GetTempPath(MAX_PATH, wxStringBuffer(dir, MAX_PATH + 1)) )
- {
- wxLogLastError(_T("GetTempPath"));
- }
+ wxLogLastError(wxT("GetTempFileName"));
- if ( dir.empty() )
- {
- // GetTempFileName() fails if we pass it an empty string
- dir = _T('.');
- }
- }
- else // we have a dir to create the file in
- {
- // ensure we use only the back slashes as GetTempFileName(), unlike all
- // the other APIs, is picky and doesn't accept the forward ones
- dir.Replace(_T("/"), _T("\\"));
- }
-
- if ( !::GetTempFileName(dir, name, 0, wxStringBuffer(path, MAX_PATH + 1)) )
- {
- wxLogLastError(_T("GetTempFileName"));
-
- path.clear();
- }
-#else // Win16
- if ( !::GetTempFileName(NULL, prefix, 0, wxStringBuffer(path, 1025)) )
- {
path.clear();
}
-#endif // Win32/16
#else // !Windows
- if ( dir.empty() )
- {
-#if defined(__WXMAC__) && !defined(__DARWIN__)
- dir = wxMacFindFolder( (short) kOnSystemDisk, kTemporaryFolderType, kCreateFolder ) ;
-#else // !Mac
- dir = wxGetenv(_T("TMP"));
- if ( dir.empty() )
- {
- dir = wxGetenv(_T("TEMP"));
- }
-
- if ( dir.empty() )
- {
- // default
- #if defined(__DOS__) || defined(__OS2__)
- dir = _T(".");
- #else
- dir = _T("/tmp");
- #endif
- }
-#endif // Mac/!Mac
- }
-
path = dir;
if ( !wxEndsWithPathSeparator(dir) &&
#if defined(HAVE_MKSTEMP)
// scratch space for mkstemp()
- path += _T("XXXXXX");
+ path += wxT("XXXXXX");
// we need to copy the path to the buffer in which mkstemp() can modify it
- wxCharBuffer buf( wxConvFile.cWX2MB( path ) );
+ wxCharBuffer buf(path.fn_str());
// cast is safe because the string length doesn't change
int fdTemp = mkstemp( (char*)(const char*) buf );
else // mkstemp() succeeded
{
path = wxConvFile.cMB2WX( (const char*) buf );
-
+
+ #if wxUSE_FILE
// avoid leaking the fd
if ( fileTemp )
{
fileTemp->Attach(fdTemp);
}
else
+ #endif
+
+ #if wxUSE_FFILE
+ if ( ffileTemp )
+ {
+ #ifdef wx_fdopen
+ ffileTemp->Attach(wx_fdopen(fdTemp, "r+b"), path);
+ #else
+ ffileTemp->Open(path, wxT("r+b"));
+ close(fdTemp);
+ #endif
+ }
+ else
+ #endif
+
{
close(fdTemp);
}
#ifdef HAVE_MKTEMP
// same as above
- path += _T("XXXXXX");
+ path += wxT("XXXXXX");
wxCharBuffer buf = wxConvFile.cWX2MB( path );
- if ( !mktemp( (const char*) buf ) )
+ if ( !mktemp( (char*)(const char*) buf ) )
{
path.clear();
}
}
#else // !HAVE_MKTEMP (includes __DOS__)
// generate the unique file name ourselves
- #if !defined(__DOS__) && (!defined(__MWERKS__) || defined(__DARWIN__) )
+ #if !defined(__DOS__)
path << (unsigned int)getpid();
#endif
for ( size_t n = 0; n < numTries; n++ )
{
// 3 hex digits is enough for numTries == 1000 < 4096
- pathTry = path + wxString::Format(_T("%.03x"), (unsigned int) n);
- if ( !wxFile::Exists(pathTry) )
+ pathTry = path + wxString::Format(wxT("%.03x"), (unsigned int) n);
+ if ( !wxFileName::FileExists(pathTry) )
{
break;
}
path = pathTry;
#endif // HAVE_MKTEMP/!HAVE_MKTEMP
- if ( !path.empty() )
- {
- }
#endif // HAVE_MKSTEMP/!HAVE_MKSTEMP
#endif // Windows/!Windows
{
wxLogSysError(_("Failed to create a temporary file name"));
}
- else if ( fileTemp && !fileTemp->IsOpened() )
+ else
{
+ bool ok = true;
+
// open the file - of course, there is a race condition here, this is
// why we always prefer using mkstemp()...
- //
- // NB: GetTempFileName() under Windows creates the file, so using
- // write_excl there would fail
- if ( !fileTemp->Open(path,
-#if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
- wxFile::write,
-#else
- wxFile::write_excl,
-#endif
- wxS_IRUSR | wxS_IWUSR) )
+ #if wxUSE_FILE
+ if ( fileTemp && !fileTemp->IsOpened() )
+ {
+ *deleteOnClose = wantDeleteOnClose;
+ int fd = wxTempOpen(path, deleteOnClose);
+ if (fd != -1)
+ fileTemp->Attach(fd);
+ else
+ ok = false;
+ }
+ #endif
+
+ #if wxUSE_FFILE
+ if ( ffileTemp && !ffileTemp->IsOpened() )
+ {
+ *deleteOnClose = wantDeleteOnClose;
+ ok = wxTempOpen(ffileTemp, path, deleteOnClose);
+ }
+ #endif
+
+ if ( !ok )
{
// FIXME: If !ok here should we loop and try again with another
// file name? That is the standard recourse if open(O_EXCL)
return path;
}
+
+static bool wxCreateTempImpl(
+ const wxString& prefix,
+ WXFILEARGS(wxFile *fileTemp, wxFFile *ffileTemp),
+ wxString *name)
+{
+ bool deleteOnClose = true;
+
+ *name = wxCreateTempImpl(prefix,
+ WXFILEARGS(fileTemp, ffileTemp),
+ &deleteOnClose);
+
+ bool ok = !name->empty();
+
+ if (deleteOnClose)
+ name->clear();
+#ifdef __UNIX__
+ else if (ok && wxRemoveFile(*name))
+ name->clear();
+#endif
+
+ return ok;
+}
+
+
+static void wxAssignTempImpl(
+ wxFileName *fn,
+ const wxString& prefix,
+ WXFILEARGS(wxFile *fileTemp, wxFFile *ffileTemp))
+{
+ wxString tempname;
+ tempname = wxCreateTempImpl(prefix, WXFILEARGS(fileTemp, ffileTemp));
+
+ if ( tempname.empty() )
+ {
+ // error, failed to get temp file name
+ fn->Clear();
+ }
+ else // ok
+ {
+ fn->Assign(tempname);
+ }
+}
+
+
+void wxFileName::AssignTempFileName(const wxString& prefix)
+{
+ wxAssignTempImpl(this, prefix, WXFILEARGS(NULL, NULL));
+}
+
+/* static */
+wxString wxFileName::CreateTempFileName(const wxString& prefix)
+{
+ return wxCreateTempImpl(prefix, WXFILEARGS(NULL, NULL));
+}
+
+#endif // wxUSE_FILE || wxUSE_FFILE
+
+
+#if wxUSE_FILE
+
+wxString wxCreateTempFileName(const wxString& prefix,
+ wxFile *fileTemp,
+ bool *deleteOnClose)
+{
+ return wxCreateTempImpl(prefix, WXFILEARGS(fileTemp, NULL), deleteOnClose);
+}
+
+bool wxCreateTempFile(const wxString& prefix,
+ wxFile *fileTemp,
+ wxString *name)
+{
+ return wxCreateTempImpl(prefix, WXFILEARGS(fileTemp, NULL), name);
+}
+
+void wxFileName::AssignTempFileName(const wxString& prefix, wxFile *fileTemp)
+{
+ wxAssignTempImpl(this, prefix, WXFILEARGS(fileTemp, NULL));
+}
+
+/* static */
+wxString
+wxFileName::CreateTempFileName(const wxString& prefix, wxFile *fileTemp)
+{
+ return wxCreateTempFileName(prefix, fileTemp);
+}
+
+#endif // wxUSE_FILE
+
+
+#if wxUSE_FFILE
+
+wxString wxCreateTempFileName(const wxString& prefix,
+ wxFFile *fileTemp,
+ bool *deleteOnClose)
+{
+ return wxCreateTempImpl(prefix, WXFILEARGS(NULL, fileTemp), deleteOnClose);
+}
+
+bool wxCreateTempFile(const wxString& prefix,
+ wxFFile *fileTemp,
+ wxString *name)
+{
+ return wxCreateTempImpl(prefix, WXFILEARGS(NULL, fileTemp), name);
+
+}
+
+void wxFileName::AssignTempFileName(const wxString& prefix, wxFFile *fileTemp)
+{
+ wxAssignTempImpl(this, prefix, WXFILEARGS(NULL, fileTemp));
+}
+
+/* static */
+wxString
+wxFileName::CreateTempFileName(const wxString& prefix, wxFFile *fileTemp)
+{
+ return wxCreateTempFileName(prefix, fileTemp);
+}
+
+#endif // wxUSE_FFILE
+
+
// ----------------------------------------------------------------------------
// directory operations
// ----------------------------------------------------------------------------
-bool wxFileName::Mkdir( int perm, int flags )
+// helper of GetTempDir(): check if the given directory exists and return it if
+// it does or an empty string otherwise
+namespace
+{
+
+wxString CheckIfDirExists(const wxString& dir)
+{
+ return wxFileName::DirExists(dir) ? dir : wxString();
+}
+
+} // anonymous namespace
+
+wxString wxFileName::GetTempDir()
+{
+ // first try getting it from environment: this allows overriding the values
+ // used by default if the user wants to create temporary files in another
+ // directory
+ wxString dir = CheckIfDirExists(wxGetenv("TMPDIR"));
+ if ( dir.empty() )
+ {
+ dir = CheckIfDirExists(wxGetenv("TMP"));
+ if ( dir.empty() )
+ dir = CheckIfDirExists(wxGetenv("TEMP"));
+ }
+
+ // if no environment variables are set, use the system default
+ if ( dir.empty() )
+ {
+#if defined(__WXWINCE__)
+ dir = CheckIfDirExists(wxT("\\temp"));
+#elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
+ if ( !::GetTempPath(MAX_PATH, wxStringBuffer(dir, MAX_PATH + 1)) )
+ {
+ wxLogLastError(wxT("GetTempPath"));
+ }
+#elif defined(__WXMAC__) && wxOSX_USE_CARBON
+ dir = wxMacFindFolderNoSeparator(short(kOnSystemDisk), kTemporaryFolderType, kCreateFolder);
+#endif // systems with native way
+ }
+ else // we got directory from an environment variable
+ {
+ // remove any trailing path separators, we don't want to ever return
+ // them from this function for consistency
+ const size_t lastNonSep = dir.find_last_not_of(GetPathSeparators());
+ if ( lastNonSep == wxString::npos )
+ {
+ // the string consists entirely of separators, leave only one
+ dir = GetPathSeparator();
+ }
+ else
+ {
+ dir.erase(lastNonSep + 1);
+ }
+ }
+
+ // fall back to hard coded value
+ if ( dir.empty() )
+ {
+#ifdef __UNIX_LIKE__
+ dir = CheckIfDirExists("/tmp");
+ if ( dir.empty() )
+#endif // __UNIX_LIKE__
+ dir = ".";
+ }
+
+ return dir;
+}
+
+bool wxFileName::Mkdir( int perm, int flags ) const
{
- return wxFileName::Mkdir( GetFullPath(), perm, flags );
+ return wxFileName::Mkdir(GetPath(), perm, flags);
}
bool wxFileName::Mkdir( const wxString& dir, int perm, int flags )
size_t count = dirs.GetCount();
for ( size_t i = 0; i < count; i++ )
{
- if ( i > 0 ||
-#if defined(__WXMAC__) && !defined(__DARWIN__)
- // relative pathnames are exactely the other way round under mac...
- !filename.IsAbsolute()
-#else
- filename.IsAbsolute()
-#endif
- )
+ if ( i > 0 || filename.IsAbsolute() )
currPath += wxFILE_SEP_PATH;
currPath += dirs[i];
return ::wxMkdir( dir, perm );
}
-bool wxFileName::Rmdir()
+bool wxFileName::Rmdir(int flags) const
{
- return wxFileName::Rmdir( GetFullPath() );
+ return wxFileName::Rmdir( GetPath(), flags );
}
-bool wxFileName::Rmdir( const wxString &dir )
+bool wxFileName::Rmdir(const wxString& dir, int flags)
{
- return ::wxRmdir( dir );
+#ifdef __WINDOWS__
+ if ( flags & wxPATH_RMDIR_RECURSIVE )
+ {
+ // SHFileOperation needs double null termination string
+ // but without separator at the end of the path
+ wxString path(dir);
+ if ( path.Last() == wxFILE_SEP_PATH )
+ path.RemoveLast();
+ path += wxT('\0');
+
+ SHFILEOPSTRUCT fileop;
+ wxZeroMemory(fileop);
+ fileop.wFunc = FO_DELETE;
+ fileop.pFrom = path.t_str();
+ fileop.fFlags = FOF_SILENT | FOF_NOCONFIRMATION;
+ #ifndef __WXWINCE__
+ // FOF_NOERRORUI is not defined in WinCE
+ fileop.fFlags |= FOF_NOERRORUI;
+ #endif
+
+ int ret = SHFileOperation(&fileop);
+ if ( ret != 0 )
+ {
+ // SHFileOperation may return non-Win32 error codes, so the error
+ // message can be incorrect
+ wxLogApiError(wxT("SHFileOperation"), ret);
+ return false;
+ }
+
+ return true;
+ }
+ else if ( flags & wxPATH_RMDIR_FULL )
+#else // !__WINDOWS__
+ if ( flags != 0 ) // wxPATH_RMDIR_FULL or wxPATH_RMDIR_RECURSIVE
+#endif // !__WINDOWS__
+ {
+#ifndef __WINDOWS__
+ if ( flags & wxPATH_RMDIR_RECURSIVE )
+ {
+ // When deleting the tree recursively, we are supposed to delete
+ // this directory itself even when it is a symlink -- but without
+ // following it. Do it here as wxRmdir() would simply follow if
+ // called for a symlink.
+ if ( wxFileName::Exists(dir, wxFILE_EXISTS_SYMLINK) )
+ {
+ return wxRemoveFile(dir);
+ }
+ }
+#endif // !__WINDOWS__
+
+ wxString path(dir);
+ if ( path.Last() != wxFILE_SEP_PATH )
+ path += wxFILE_SEP_PATH;
+
+ wxDir d(path);
+
+ if ( !d.IsOpened() )
+ return false;
+
+ wxString filename;
+
+ // First delete all subdirectories: notice that we don't follow
+ // symbolic links, potentially leading outside this directory, to avoid
+ // unpleasant surprises.
+ bool cont = d.GetFirst(&filename, wxString(),
+ wxDIR_DIRS | wxDIR_HIDDEN | wxDIR_NO_FOLLOW);
+ while ( cont )
+ {
+ wxFileName::Rmdir(path + filename, flags);
+ cont = d.GetNext(&filename);
+ }
+
+#ifndef __WINDOWS__
+ if ( flags & wxPATH_RMDIR_RECURSIVE )
+ {
+ // Delete all files too and, for the same reasons as above, don't
+ // follow symlinks which could refer to the files outside of this
+ // directory and just delete the symlinks themselves.
+ cont = d.GetFirst(&filename, wxString(),
+ wxDIR_FILES | wxDIR_HIDDEN | wxDIR_NO_FOLLOW);
+ while ( cont )
+ {
+ ::wxRemoveFile(path + filename);
+ cont = d.GetNext(&filename);
+ }
+ }
+#endif // !__WINDOWS__
+ }
+
+ return ::wxRmdir(dir);
}
// ----------------------------------------------------------------------------
}
}
-
// the existing path components
wxArrayString dirs = GetDirs();
format = GetFormat(format);
- // make the path absolute
+ // set up the directory to use for making the path absolute later
if ( (flags & wxPATH_NORM_ABSOLUTE) && !IsAbsolute(format) )
{
if ( cwd.empty() )
{
curDir.AssignDir(cwd);
}
-
- // the path may be not absolute because it doesn't have the volume name
- // but in this case we shouldn't modify the directory components of it
- // but just set the current volume
- if ( !HasVolume() && curDir.HasVolume() )
- {
- SetVolume(curDir.GetVolume());
-
- if ( !m_relative )
- {
- // yes, it was the case - we don't need curDir then
- curDir.Clear();
- }
- }
}
// handle ~ stuff under Unix only
- if ( (format == wxPATH_UNIX) && (flags & wxPATH_NORM_TILDE) )
+ if ( (format == wxPATH_UNIX) && (flags & wxPATH_NORM_TILDE) && m_relative )
{
if ( !dirs.IsEmpty() )
{
wxString dir = dirs[0u];
- if ( !dir.empty() && dir[0u] == _T('~') )
+ if ( !dir.empty() && dir[0u] == wxT('~') )
{
+ // to make the path absolute use the home directory
curDir.AssignDir(wxGetUserHome(dir.c_str() + 1));
-
dirs.RemoveAt(0u);
}
}
// transform relative path into abs one
if ( curDir.IsOk() )
{
- wxArrayString dirsNew = curDir.GetDirs();
- size_t count = dirs.GetCount();
- for ( size_t n = 0; n < count; n++ )
+ // this path may be relative because it doesn't have the volume name
+ // and still have m_relative=true; in this case we shouldn't modify
+ // our directory components but just set the current volume
+ if ( !HasVolume() && curDir.HasVolume() )
+ {
+ SetVolume(curDir.GetVolume());
+
+ if ( !m_relative )
{
- dirsNew.Add(dirs[n]);
+ // yes, it was the case - we don't need curDir then
+ curDir.Clear();
+ }
}
- dirs = dirsNew;
+ // finally, prepend curDir to the dirs array
+ wxArrayString dirsNew = curDir.GetDirs();
+ WX_PREPEND_ARRAY(dirs, dirsNew);
+
+ // if we used e.g. tilde expansion previously and wxGetUserHome didn't
+ // return for some reason an absolute path, then curDir maybe not be absolute!
+ if ( !curDir.m_relative )
+ {
+ // we have prepended an absolute path and thus we are now an absolute
+ // file name too
+ m_relative = false;
+ }
+ // else if (flags & wxPATH_NORM_ABSOLUTE):
+ // should we warn the user that we didn't manage to make the path absolute?
}
// now deal with ".", ".." and the rest
if ( dir == wxT("..") )
{
- if ( m_dirs.IsEmpty() )
+ if ( m_dirs.empty() )
{
- wxLogError(_("The path '%s' contains too many \"..\"!"),
- GetFullPath().c_str());
- return false;
- }
+ // We have more ".." than directory components so far.
+ // Don't treat this as an error as the path could have been
+ // entered by user so try to handle it reasonably: if the
+ // path is absolute, just ignore the extra ".." because
+ // "/.." is the same as "/". Otherwise, i.e. for relative
+ // paths, keep ".." unchanged because removing it would
+ // modify the file a relative path refers to.
+ if ( !m_relative )
+ continue;
- m_dirs.RemoveAt(m_dirs.GetCount() - 1);
- continue;
+ }
+ else // Normal case, go one step up.
+ {
+ m_dirs.pop_back();
+ continue;
+ }
}
}
- if ( (flags & wxPATH_NORM_CASE) && !IsCaseSensitive(format) )
- {
- dir.MakeLower();
- }
-
m_dirs.Add(dir);
}
-
-#ifdef __WIN32__
+
+#if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
if ( (flags & wxPATH_NORM_SHORTCUT) )
{
wxString filename;
if (GetShortcutTarget(GetFullPath(format), filename))
{
- // Repeat this since we may now have a new path
- if ( (flags & wxPATH_NORM_CASE) && !IsCaseSensitive(format) )
- {
- filename.MakeLower();
- }
m_relative = false;
Assign(filename);
}
}
#endif
- if ( (flags & wxPATH_NORM_CASE) && !IsCaseSensitive(format) )
+#if defined(__WIN32__)
+ if ( (flags & wxPATH_NORM_LONG) && (format == wxPATH_DOS) )
{
- // VZ: expand env vars here too?
+ Assign(GetLongPath());
+ }
+#endif // Win32
+ // Change case (this should be kept at the end of the function, to ensure
+ // that the path doesn't change any more after we normalize its case)
+ if ( (flags & wxPATH_NORM_CASE) && !IsCaseSensitive(format) )
+ {
+ m_volume.MakeLower();
m_name.MakeLower();
m_ext.MakeLower();
+
+ // directory entries must be made lower case as well
+ count = m_dirs.GetCount();
+ for ( size_t i = 0; i < count; i++ )
+ {
+ m_dirs[i].MakeLower();
+ }
}
- // we do have the path now
- //
- // NB: need to do this before (maybe) calling Assign() below
- m_relative = false;
+ return true;
+}
+
+#ifndef __WXWINCE__
+bool wxFileName::ReplaceEnvVariable(const wxString& envname,
+ const wxString& replacementFmtString,
+ wxPathFormat format)
+{
+ // look into stringForm for the contents of the given environment variable
+ wxString val;
+ if (envname.empty() ||
+ !wxGetEnv(envname, &val))
+ return false;
+ if (val.empty())
+ return false;
+
+ wxString stringForm = GetPath(wxPATH_GET_VOLUME, format);
+ // do not touch the file name and the extension
+
+ wxString replacement = wxString::Format(replacementFmtString, envname);
+ stringForm.Replace(val, replacement);
+
+ // Now assign ourselves the modified path:
+ Assign(stringForm, GetFullName(), format);
+
+ return true;
+}
+#endif
+
+bool wxFileName::ReplaceHomeDir(wxPathFormat format)
+{
+ wxString homedir = wxGetHomeDir();
+ if (homedir.empty())
+ return false;
+
+ wxString stringForm = GetPath(wxPATH_GET_VOLUME, format);
+ // do not touch the file name and the extension
-#if defined(__WIN32__)
- if ( (flags & wxPATH_NORM_LONG) && (format == wxPATH_DOS) )
- {
- Assign(GetLongPath());
- }
-#endif // Win32
+ stringForm.Replace(homedir, "~");
+
+ // Now assign ourselves the modified path:
+ Assign(stringForm, GetFullName(), format);
return true;
}
// get the shortcut target
// ----------------------------------------------------------------------------
-#if defined(__WIN32__) && !defined(__WXWINCE__)
+// WinCE (3) doesn't have CLSID_ShellLink, IID_IShellLink definitions.
+// The .lnk file is a plain text file so it should be easy to
+// make it work. Hint from Google Groups:
+// "If you open up a lnk file, you'll see a
+// number, followed by a pound sign (#), followed by more text. The
+// number is the number of characters that follows the pound sign. The
+// characters after the pound sign are the command line (which _can_
+// include arguments) to be executed. Any path (e.g. \windows\program
+// files\myapp.exe) that includes spaces needs to be enclosed in
+// quotation marks."
+
+#if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
+// The following lines are necessary under WinCE
+// #include "wx/msw/private.h"
+// #include <ole2.h>
#include <shlobj.h>
+#if defined(__WXWINCE__)
+#include <shlguid.h>
#endif
-#ifdef __WIN32__
-bool wxFileName::GetShortcutTarget(const wxString& shortcutPath, wxString& targetFilename, wxString* arguments)
+bool wxFileName::GetShortcutTarget(const wxString& shortcutPath,
+ wxString& targetFilename,
+ wxString* arguments) const
{
-#ifdef __WXWINCE__
- // Not tested on WinCE, so don't compile yet
- return shortcutPath;
-#else
wxString path, file, ext;
- wxSplitPath(shortcutPath, & path, & file, & ext);
-
- HRESULT hres;
- IShellLink* psl;
- bool success = FALSE;
+ wxFileName::SplitPath(shortcutPath, & path, & file, & ext);
+
+ HRESULT hres;
+ IShellLink* psl;
+ bool success = false;
// Assume it's not a shortcut if it doesn't end with lnk
- if (ext.Lower() != wxT("lnk"))
- return FALSE;
-
- // create a ShellLink object
- hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
- IID_IShellLink, (LPVOID*) &psl);
-
- if (SUCCEEDED(hres))
- {
- IPersistFile* ppf;
- hres = psl->QueryInterface( IID_IPersistFile, (LPVOID *) &ppf);
- if (SUCCEEDED(hres))
- {
- WCHAR wsz[MAX_PATH];
-
- MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, shortcutPath.mb_str(), -1, wsz,
- MAX_PATH);
-
- hres = ppf->Load(wsz, 0);
- if (SUCCEEDED(hres))
- {
+ if (ext.CmpNoCase(wxT("lnk"))!=0)
+ return false;
+
+ // create a ShellLink object
+ hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
+ IID_IShellLink, (LPVOID*) &psl);
+
+ if (SUCCEEDED(hres))
+ {
+ IPersistFile* ppf;
+ hres = psl->QueryInterface( IID_IPersistFile, (LPVOID *) &ppf);
+ if (SUCCEEDED(hres))
+ {
+ WCHAR wsz[MAX_PATH];
+
+ MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, shortcutPath.mb_str(), -1, wsz,
+ MAX_PATH);
+
+ hres = ppf->Load(wsz, 0);
+ ppf->Release();
+
+ if (SUCCEEDED(hres))
+ {
wxChar buf[2048];
- psl->GetPath(buf, 2048, NULL, SLGP_UNCPRIORITY);
- targetFilename = wxString(buf);
+ // Wrong prototype in early versions
+#if defined(__MINGW32__) && !wxCHECK_W32API_VERSION(2, 2)
+ psl->GetPath((CHAR*) buf, 2048, NULL, SLGP_UNCPRIORITY);
+#else
+ psl->GetPath(buf, 2048, NULL, SLGP_UNCPRIORITY);
+#endif
+ targetFilename = wxString(buf);
success = (shortcutPath != targetFilename);
- psl->GetArguments(buf, 2048);
+ psl->GetArguments(buf, 2048);
wxString args(buf);
- if (!args.IsEmpty() && arguments)
+ if (!args.empty() && arguments)
{
*arguments = args;
- }
- }
- }
- }
- psl->Release();
- return success;
-#endif
+ }
+ }
+ }
+
+ psl->Release();
+ }
+ return success;
}
-#endif
+
+#endif // __WIN32__ && !__WXWINCE__
// ----------------------------------------------------------------------------
bool wxFileName::IsAbsolute(wxPathFormat format) const
{
+ // unix paths beginning with ~ are reported as being absolute
+ if ( format == wxPATH_UNIX )
+ {
+ if ( !m_dirs.IsEmpty() )
+ {
+ wxString dir = m_dirs[0u];
+
+ if (!dir.empty() && dir[0u] == wxT('~'))
+ return true;
+ }
+ }
+
// if our path doesn't start with a path separator, it's not an absolute
// path
if ( m_relative )
if ( !GetVolumeSeparator(format).empty() )
{
// this format has volumes and an absolute path must have one, it's not
- // enough to have the full path to bean absolute file under Windows
+ // enough to have the full path to be an absolute file under Windows
if ( GetVolume().empty() )
return false;
}
// files)
if ( m_dirs.IsEmpty() && IsDir() )
{
- m_dirs.Add(_T('.'));
+ m_dirs.Add(wxT('.'));
}
}
// get cwd only once - small time saving
wxString cwd = wxGetCwd();
- fn1.Normalize(wxPATH_NORM_ALL & ~wxPATH_NORM_CASE, cwd, format);
- fn2.Normalize(wxPATH_NORM_ALL & ~wxPATH_NORM_CASE, cwd, format);
+ fn1.Normalize(wxPATH_NORM_ALL | wxPATH_NORM_CASE, cwd, format);
+ fn2.Normalize(wxPATH_NORM_ALL | wxPATH_NORM_CASE, cwd, format);
if ( fn1.GetFullPath() == fn2.GetFullPath() )
return true;
- // TODO: compare inodes for Unix, this works even when filenames are
- // different but files are the same (symlinks) (VZ)
+#if defined(__UNIX__)
+ wxStructStat st1, st2;
+ if ( StatAny(st1, fn1) && StatAny(st2, fn2) )
+ {
+ if ( st1.st_ino == st2.st_ino && st1.st_dev == st2.st_dev )
+ return true;
+ }
+ //else: It's not an error if one or both files don't exist.
+#endif // defined __UNIX__
return false;
}
/* static */
bool wxFileName::IsCaseSensitive( wxPathFormat format )
{
- // only Unix filenames are truely case-sensitive
+ // only Unix filenames are truly case-sensitive
return GetFormat(format) == wxPATH_UNIX;
}
}
/* static */
-wxString wxFileName::GetVolumeSeparator(wxPathFormat format)
+wxString wxFileName::GetVolumeSeparator(wxPathFormat WXUNUSED_IN_WINCE(format))
{
+#ifdef __WXWINCE__
+ return wxEmptyString;
+#else
wxString sepVol;
if ( (GetFormat(format) == wxPATH_DOS) ||
//else: leave empty
return sepVol;
+#endif
}
/* static */
break;
default:
- wxFAIL_MSG( _T("Unknown wxPATH_XXX style") );
+ wxFAIL_MSG( wxT("Unknown wxPATH_XXX style") );
// fall through
case wxPATH_UNIX:
return seps;
}
+/* static */
+wxString wxFileName::GetPathTerminators(wxPathFormat format)
+{
+ format = GetFormat(format);
+
+ // under VMS the end of the path is ']', not the path separator used to
+ // separate the components
+ return format == wxPATH_VMS ? wxString(wxT(']')) : GetPathSeparators(format);
+}
+
/* static */
bool wxFileName::IsPathSeparator(wxChar ch, wxPathFormat format)
{
// wxString::Find() doesn't work as expected with NUL - it will always find
- // it, so it is almost surely a bug if this function is called with NUL arg
- wxASSERT_MSG( ch != _T('\0'), _T("shouldn't be called with NUL") );
+ // it, so test for it separately
+ return ch != wxT('\0') && GetPathSeparators(format).Find(ch) != wxNOT_FOUND;
+}
- return GetPathSeparators(format).Find(ch) != wxNOT_FOUND;
+/* static */
+bool
+wxFileName::IsMSWUniqueVolumeNamePath(const wxString& path, wxPathFormat format)
+{
+ // return true if the format used is the DOS/Windows one and the string begins
+ // with a Windows unique volume name ("\\?\Volume{guid}\")
+ return format == wxPATH_DOS &&
+ path.length() >= wxMSWUniqueVolumePrefixLength &&
+ path.StartsWith(wxS("\\\\?\\Volume{")) &&
+ path[wxMSWUniqueVolumePrefixLength - 1] == wxFILE_SEP_PATH_DOS;
}
// ----------------------------------------------------------------------------
{
if ( dir.empty() )
{
- wxFAIL_MSG( _T("empty directory passed to wxFileName::InsertDir()") );
+ wxFAIL_MSG( wxT("empty directory passed to wxFileName::InsertDir()") );
return false;
}
{
if ( dir[n] == GetVolumeSeparator() || IsPathSeparator(dir[n]) )
{
- wxFAIL_MSG( _T("invalid directory component in wxFileName") );
+ wxFAIL_MSG( wxT("invalid directory component in wxFileName") );
return false;
}
return true;
}
-void wxFileName::AppendDir( const wxString &dir )
+void wxFileName::AppendDir( const wxString& dir )
{
if ( IsValidDirComponent(dir) )
m_dirs.Add( dir );
}
-void wxFileName::PrependDir( const wxString &dir )
+void wxFileName::PrependDir( const wxString& dir )
{
InsertDir(0, dir);
}
-void wxFileName::InsertDir( int before, const wxString &dir )
+void wxFileName::InsertDir(size_t before, const wxString& dir)
{
if ( IsValidDirComponent(dir) )
- m_dirs.Insert( dir, before );
+ m_dirs.Insert(dir, before);
}
-void wxFileName::RemoveDir( int pos )
+void wxFileName::RemoveDir(size_t pos)
{
- m_dirs.RemoveAt( (size_t)pos );
+ m_dirs.RemoveAt(pos);
}
// ----------------------------------------------------------------------------
void wxFileName::SetFullName(const wxString& fullname)
{
- SplitPath(fullname, NULL /* no path */, &m_name, &m_ext);
+ SplitPath(fullname, NULL /* no volume */, NULL /* no path */,
+ &m_name, &m_ext, &m_hasExt);
}
wxString wxFileName::GetFullName() const
{
wxString fullname = m_name;
- if ( !m_ext.empty() )
+ if ( m_hasExt )
{
fullname << wxFILE_SEP_EXT << m_ext;
}
case wxPATH_UNIX:
if ( !m_relative )
{
- // normally the absolute file names start with a slash
- // with one exception: the ones like "~/foo.bar" don't
- // have it
- if ( m_dirs.IsEmpty() || m_dirs[0u] != _T('~') )
- {
- fullpath += wxFILE_SEP_PATH_UNIX;
- }
+ fullpath += wxFILE_SEP_PATH_UNIX;
}
break;
}
// convert back from ".." to nothing
- if ( m_dirs[i] != wxT("..") )
+ if ( !m_dirs[i].IsSameAs(wxT("..")) )
fullpath += m_dirs[i];
break;
// TODO: What to do with ".." under VMS
// convert back from ".." to nothing
- if ( m_dirs[i] != wxT("..") )
+ if ( !m_dirs[i].IsSameAs(wxT("..")) )
fullpath += m_dirs[i];
break;
}
// Return the short form of the path (returns identity on non-Windows platforms)
wxString wxFileName::GetShortPath() const
{
-#if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
wxString path(GetFullPath());
- wxString pathOut;
- DWORD sz = ::GetShortPathName(path, NULL, 0);
- bool ok = sz != 0;
- if ( ok )
+
+#if defined(__WINDOWS__) && defined(__WIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
+ DWORD sz = ::GetShortPathName(path.t_str(), NULL, 0);
+ if ( sz != 0 )
{
- ok = ::GetShortPathName
+ wxString pathOut;
+ if ( ::GetShortPathName
(
- path,
+ path.t_str(),
wxStringBuffer(pathOut, sz),
sz
- ) != 0;
+ ) != 0 )
+ {
+ return pathOut;
+ }
}
- if (ok)
- return pathOut;
+#endif // Windows
return path;
-#else
- return GetFullPath();
-#endif
}
// Return the long form of the path (returns identity on non-Windows platforms)
wxString pathOut,
path = GetFullPath();
-#if defined(__WIN32__) && !defined(__WXMICROWIN__)
- bool success = false;
+#if defined(__WIN32__) && !defined(__WXWINCE__) && !defined(__WXMICROWIN__)
-#if wxUSE_DYNAMIC_LOADER
+#if wxUSE_DYNLIB_CLASS
typedef DWORD (WINAPI *GET_LONG_PATH_NAME)(const wxChar *, wxChar *, DWORD);
- static bool s_triedToLoad = false;
-
- if ( !s_triedToLoad )
+ // this is MT-safe as in the worst case we're going to resolve the function
+ // twice -- but as the result is the same in both threads, it's ok
+ static GET_LONG_PATH_NAME s_pfnGetLongPathName = NULL;
+ if ( !s_pfnGetLongPathName )
{
- // suppress the errors about missing GetLongPathName[AW]
- wxLogNull noLog;
+ static bool s_triedToLoad = false;
- s_triedToLoad = true;
- wxDynamicLibrary dllKernel(_T("kernel32"));
- if ( dllKernel.IsLoaded() )
+ if ( !s_triedToLoad )
{
- // may succeed or fail depending on the Windows version
- static GET_LONG_PATH_NAME s_pfnGetLongPathName = NULL;
-#ifdef _UNICODE
- s_pfnGetLongPathName = (GET_LONG_PATH_NAME) dllKernel.GetSymbol(_T("GetLongPathNameW"));
-#else
- s_pfnGetLongPathName = (GET_LONG_PATH_NAME) dllKernel.GetSymbol(_T("GetLongPathNameA"));
-#endif
+ s_triedToLoad = true;
- if ( s_pfnGetLongPathName )
- {
- DWORD dwSize = (*s_pfnGetLongPathName)(path, NULL, 0);
- bool ok = dwSize > 0;
+ wxDynamicLibrary dllKernel(wxT("kernel32"));
- if ( ok )
- {
- DWORD sz = (*s_pfnGetLongPathName)(path, NULL, 0);
- ok = sz != 0;
- if ( ok )
- {
- ok = (*s_pfnGetLongPathName)
- (
- path,
- wxStringBuffer(pathOut, sz),
- sz
- ) != 0;
- success = true;
- }
- }
+ const wxChar* GetLongPathName = wxT("GetLongPathName")
+#if wxUSE_UNICODE
+ wxT("W");
+#else // ANSI
+ wxT("A");
+#endif // Unicode/ANSI
+
+ if ( dllKernel.HasSymbol(GetLongPathName) )
+ {
+ s_pfnGetLongPathName = (GET_LONG_PATH_NAME)
+ dllKernel.GetSymbol(GetLongPathName);
}
+
+ // note that kernel32.dll can be unloaded, it stays in memory
+ // anyhow as all Win32 programs link to it and so it's safe to call
+ // GetLongPathName() even after unloading it
}
}
- if (success)
- return pathOut;
-#endif // wxUSE_DYNAMIC_LOADER
-
- if (!success)
+ if ( s_pfnGetLongPathName )
{
- // The OS didn't support GetLongPathName, or some other error.
- // We need to call FindFirstFile on each component in turn.
-
- WIN32_FIND_DATA findFileData;
- HANDLE hFind;
+ DWORD dwSize = (*s_pfnGetLongPathName)(path.t_str(), NULL, 0);
+ if ( dwSize > 0 )
+ {
+ if ( (*s_pfnGetLongPathName)
+ (
+ path.t_str(),
+ wxStringBuffer(pathOut, dwSize),
+ dwSize
+ ) != 0 )
+ {
+ return pathOut;
+ }
+ }
+ }
+#endif // wxUSE_DYNLIB_CLASS
- if ( HasVolume() )
- pathOut = GetVolume() +
- GetVolumeSeparator(wxPATH_DOS) +
- GetPathSeparator(wxPATH_DOS);
- else
- pathOut = wxEmptyString;
+ // The OS didn't support GetLongPathName, or some other error.
+ // We need to call FindFirstFile on each component in turn.
- wxArrayString dirs = GetDirs();
- dirs.Add(GetFullName());
+ WIN32_FIND_DATA findFileData;
+ HANDLE hFind;
- wxString tmpPath;
+ if ( HasVolume() )
+ pathOut = GetVolume() +
+ GetVolumeSeparator(wxPATH_DOS) +
+ GetPathSeparator(wxPATH_DOS);
+ else
+ pathOut = wxEmptyString;
- size_t count = dirs.GetCount();
- for ( size_t i = 0; i < count; i++ )
- {
- // We're using pathOut to collect the long-name path, but using a
- // temporary for appending the last path component which may be
- // short-name
- tmpPath = pathOut + dirs[i];
+ wxArrayString dirs = GetDirs();
+ dirs.Add(GetFullName());
- if ( tmpPath.empty() )
- continue;
+ wxString tmpPath;
- // can't see this being necessary? MF
- if ( tmpPath.Last() == GetVolumeSeparator(wxPATH_DOS) )
- {
- // Can't pass a drive and root dir to FindFirstFile,
- // so continue to next dir
- tmpPath += wxFILE_SEP_PATH;
- pathOut = tmpPath;
- continue;
- }
+ size_t count = dirs.GetCount();
+ for ( size_t i = 0; i < count; i++ )
+ {
+ const wxString& dir = dirs[i];
- hFind = ::FindFirstFile(tmpPath, &findFileData);
- if (hFind == INVALID_HANDLE_VALUE)
- {
- // Error: most likely reason is that path doesn't exist, so
- // append any unprocessed parts and return
- for ( i += 1; i < count; i++ )
- tmpPath += wxFILE_SEP_PATH + dirs[i];
+ // We're using pathOut to collect the long-name path, but using a
+ // temporary for appending the last path component which may be
+ // short-name
+ tmpPath = pathOut + dir;
- return tmpPath;
- }
+ // We must not process "." or ".." here as they would be (unexpectedly)
+ // replaced by the corresponding directory names so just leave them
+ // alone
+ //
+ // And we can't pass a drive and root dir to FindFirstFile (VZ: why?)
+ if ( tmpPath.empty() || dir == '.' || dir == ".." ||
+ tmpPath.Last() == GetVolumeSeparator(wxPATH_DOS) )
+ {
+ tmpPath += wxFILE_SEP_PATH;
+ pathOut = tmpPath;
+ continue;
+ }
- pathOut += findFileData.cFileName;
- if ( (i < (count-1)) )
- pathOut += wxFILE_SEP_PATH;
+ hFind = ::FindFirstFile(tmpPath.t_str(), &findFileData);
+ if (hFind == INVALID_HANDLE_VALUE)
+ {
+ // Error: most likely reason is that path doesn't exist, so
+ // append any unprocessed parts and return
+ for ( i += 1; i < count; i++ )
+ tmpPath += wxFILE_SEP_PATH + dirs[i];
- ::FindClose(hFind);
+ return tmpPath;
}
+
+ pathOut += findFileData.cFileName;
+ if ( (i < (count-1)) )
+ pathOut += wxFILE_SEP_PATH;
+
+ ::FindClose(hFind);
}
#else // !Win32
pathOut = path;
{
if (format == wxPATH_NATIVE)
{
-#if defined(__WXMSW__) || defined(__OS2__) || defined(__DOS__)
+#if defined(__WINDOWS__) || defined(__OS2__) || defined(__DOS__)
format = wxPATH_DOS;
-#elif defined(__WXMAC__) && !defined(__DARWIN__)
- format = wxPATH_MAC;
#elif defined(__VMS)
format = wxPATH_VMS;
#else
return format;
}
+#ifdef wxHAS_FILESYSTEM_VOLUMES
+
+/* static */
+wxString wxFileName::GetVolumeString(char drive, int flags)
+{
+ wxASSERT_MSG( !(flags & ~wxPATH_GET_SEPARATOR), "invalid flag specified" );
+
+ wxString vol(drive);
+ vol += wxFILE_SEP_DSK;
+ if ( flags & wxPATH_GET_SEPARATOR )
+ vol += wxFILE_SEP_PATH;
+
+ return vol;
+}
+
+#endif // wxHAS_FILESYSTEM_VOLUMES
+
// ----------------------------------------------------------------------------
// path splitting function
// ----------------------------------------------------------------------------
/* static */
-void wxFileName::SplitPath(const wxString& fullpathWithVolume,
- wxString *pstrVolume,
- wxString *pstrPath,
- wxString *pstrName,
- wxString *pstrExt,
- wxPathFormat format)
+void
+wxFileName::SplitVolume(const wxString& fullpathWithVolume,
+ wxString *pstrVolume,
+ wxString *pstrPath,
+ wxPathFormat format)
{
format = GetFormat(format);
wxString fullpath = fullpathWithVolume;
- // under VMS the end of the path is ']', not the path separator used to
- // separate the components
- wxString sepPath = format == wxPATH_VMS ? wxString(_T(']'))
- : GetPathSeparators(format);
+ if ( IsMSWUniqueVolumeNamePath(fullpath, format) )
+ {
+ // special Windows unique volume names hack: transform
+ // \\?\Volume{guid}\path into Volume{guid}:path
+ // note: this check must be done before the check for UNC path
- // special Windows UNC paths hack: transform \\share\path into share:path
- if ( format == wxPATH_DOS )
+ // we know the last backslash from the unique volume name is located
+ // there from IsMSWUniqueVolumeNamePath
+ fullpath[wxMSWUniqueVolumePrefixLength - 1] = wxFILE_SEP_DSK;
+
+ // paths starting with a unique volume name should always be absolute
+ fullpath.insert(wxMSWUniqueVolumePrefixLength, 1, wxFILE_SEP_PATH_DOS);
+
+ // remove the leading "\\?\" part
+ fullpath.erase(0, 4);
+ }
+ else if ( IsUNCPath(fullpath, format) )
{
- if ( fullpath.length() >= 4 &&
- fullpath[0u] == wxFILE_SEP_PATH_DOS &&
- fullpath[1u] == wxFILE_SEP_PATH_DOS )
- {
- fullpath.erase(0, 2);
+ // special Windows UNC paths hack: transform \\share\path into share:path
- size_t posFirstSlash = fullpath.find_first_of(sepPath);
- if ( posFirstSlash != wxString::npos )
- {
- fullpath[posFirstSlash] = wxFILE_SEP_DSK;
+ fullpath.erase(0, 2);
- // UNC paths are always absolute, right? (FIXME)
- fullpath.insert(posFirstSlash + 1, 1, wxFILE_SEP_PATH_DOS);
- }
+ size_t posFirstSlash =
+ fullpath.find_first_of(GetPathTerminators(format));
+ if ( posFirstSlash != wxString::npos )
+ {
+ fullpath[posFirstSlash] = wxFILE_SEP_DSK;
+
+ // UNC paths are always absolute, right? (FIXME)
+ fullpath.insert(posFirstSlash + 1, 1, wxFILE_SEP_PATH_DOS);
}
}
{
wxString sepVol = GetVolumeSeparator(format);
+ // we have to exclude the case of a colon in the very beginning of the
+ // string as it can't be a volume separator (nor can this be a valid
+ // DOS file name at all but we'll leave dealing with this to our caller)
size_t posFirstColon = fullpath.find_first_of(sepVol);
- if ( posFirstColon != wxString::npos )
+ if ( posFirstColon && posFirstColon != wxString::npos )
{
if ( pstrVolume )
{
}
}
+ if ( pstrPath )
+ *pstrPath = fullpath;
+}
+
+/* static */
+void wxFileName::SplitPath(const wxString& fullpathWithVolume,
+ wxString *pstrVolume,
+ wxString *pstrPath,
+ wxString *pstrName,
+ wxString *pstrExt,
+ bool *hasExt,
+ wxPathFormat format)
+{
+ format = GetFormat(format);
+
+ wxString fullpath;
+ SplitVolume(fullpathWithVolume, pstrVolume, &fullpath, format);
+
// find the positions of the last dot and last path separator in the path
size_t posLastDot = fullpath.find_last_of(wxFILE_SEP_EXT);
- size_t posLastSlash = fullpath.find_last_of(sepPath);
+ size_t posLastSlash = fullpath.find_last_of(GetPathTerminators(format));
+ // check whether this dot occurs at the very beginning of a path component
if ( (posLastDot != wxString::npos) &&
- ((format == wxPATH_UNIX) || (format == wxPATH_VMS)) )
+ (posLastDot == 0 ||
+ IsPathSeparator(fullpath[posLastDot - 1]) ||
+ (format == wxPATH_VMS && fullpath[posLastDot - 1] == wxT(']'))) )
{
- if ( (posLastDot == 0) ||
- (fullpath[posLastDot - 1] == sepPath[0u] ) )
- {
- // under Unix and VMS, dot may be (and commonly is) the first
- // character of the filename, don't treat the entire filename as
- // extension in this case
- posLastDot = wxString::npos;
- }
+ // dot may be (and commonly -- at least under Unix -- is) the first
+ // character of the filename, don't treat the entire filename as
+ // extension in this case
+ posLastDot = wxString::npos;
}
// if we do have a dot and a slash, check that the dot is in the name part
// special VMS hack: remove the initial bracket
if ( format == wxPATH_VMS )
{
- if ( (*pstrPath)[0u] == _T('[') )
+ if ( (*pstrPath)[0u] == wxT('[') )
pstrPath->erase(0, 1);
}
}
*pstrName = fullpath.Mid(nStart, count);
}
- if ( pstrExt )
+ // finally deal with the extension here: we have an added complication that
+ // extension may be empty (but present) as in "foo." where trailing dot
+ // indicates the empty extension at the end -- and hence we must remember
+ // that we have it independently of pstrExt
+ if ( posLastDot == wxString::npos )
{
- if ( posLastDot == wxString::npos )
- {
- // no extension
- pstrExt->Empty();
- }
- else
- {
- // take everything after the dot
+ // no extension
+ if ( pstrExt )
+ pstrExt->clear();
+ if ( hasExt )
+ *hasExt = false;
+ }
+ else
+ {
+ // take everything after the dot
+ if ( pstrExt )
*pstrExt = fullpath.Mid(posLastDot + 1);
- }
+ if ( hasExt )
+ *hasExt = true;
}
}
}
}
+/* static */
+wxString wxFileName::StripExtension(const wxString& fullpath)
+{
+ wxFileName fn(fullpath);
+ fn.SetExt("");
+ return fn.GetFullPath();
+}
+
// ----------------------------------------------------------------------------
// time functions
// ----------------------------------------------------------------------------
bool wxFileName::SetTimes(const wxDateTime *dtAccess,
const wxDateTime *dtMod,
- const wxDateTime *dtCreate)
+ const wxDateTime *dtCreate) const
{
#if defined(__WIN32__)
+ FILETIME ftAccess, ftCreate, ftWrite;
+
+ if ( dtCreate )
+ ConvertWxToFileTime(&ftCreate, *dtCreate);
+ if ( dtAccess )
+ ConvertWxToFileTime(&ftAccess, *dtAccess);
+ if ( dtMod )
+ ConvertWxToFileTime(&ftWrite, *dtMod);
+
+ wxString path;
+ int flags;
if ( IsDir() )
{
- // VZ: please let me know how to do this if you can
- wxFAIL_MSG( _T("SetTimes() not implemented for the directories") );
+ if ( wxGetOsVersion() == wxOS_WINDOWS_9X )
+ {
+ wxLogError(_("Setting directory access times is not supported "
+ "under this OS version"));
+ return false;
+ }
+
+ path = GetPath();
+ flags = FILE_FLAG_BACKUP_SEMANTICS;
}
else // file
{
- wxFileHandle fh(GetFullPath(), wxFileHandle::Write);
- if ( fh.IsOk() )
- {
- FILETIME ftAccess, ftCreate, ftWrite;
-
- if ( dtCreate )
- ConvertWxToFileTime(&ftCreate, *dtCreate);
- if ( dtAccess )
- ConvertWxToFileTime(&ftAccess, *dtAccess);
- if ( dtMod )
- ConvertWxToFileTime(&ftWrite, *dtMod);
+ path = GetFullPath();
+ flags = 0;
+ }
- if ( ::SetFileTime(fh,
- dtCreate ? &ftCreate : NULL,
- dtAccess ? &ftAccess : NULL,
- dtMod ? &ftWrite : NULL) )
- {
- return true;
- }
+ wxFileHandle fh(path, wxFileHandle::WriteAttr, flags);
+ if ( fh.IsOk() )
+ {
+ if ( ::SetFileTime(fh,
+ dtCreate ? &ftCreate : NULL,
+ dtAccess ? &ftAccess : NULL,
+ dtMod ? &ftWrite : NULL) )
+ {
+ return true;
}
}
#elif defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
+ wxUnusedVar(dtCreate);
+
if ( !dtAccess && !dtMod )
{
// can't modify the creation time anyhow, don't try
return true;
}
#else // other platform
+ wxUnusedVar(dtAccess);
+ wxUnusedVar(dtMod);
+ wxUnusedVar(dtCreate);
#endif // platforms
wxLogSysError(_("Failed to modify file times for '%s'"),
return false;
}
-bool wxFileName::Touch()
+bool wxFileName::Touch() const
{
#if defined(__UNIX_LIKE__)
// under Unix touching file is simple: just pass NULL to utime()
}
else // file
{
- wxFileHandle fh(GetFullPath(), wxFileHandle::Read);
+ wxFileHandle fh(GetFullPath(), wxFileHandle::ReadAttr);
if ( fh.IsOk() )
{
ok = ::GetFileTime(fh,
return true;
}
-#elif defined(__UNIX_LIKE__) || defined(__WXMAC__) || (defined(__DOS__) && defined(__WATCOMC__))
+#elif defined(__UNIX_LIKE__) || defined(__WXMAC__) || defined(__OS2__) || (defined(__DOS__) && defined(__WATCOMC__))
+ // no need to test for IsDir() here
wxStructStat stBuf;
- if ( wxStat( GetFullPath().c_str(), &stBuf) == 0 )
+ if ( StatAny(stBuf, *this) )
{
+ // Android defines st_*time fields as unsigned long, but time_t as long,
+ // hence the static_casts.
if ( dtAccess )
- dtAccess->Set(stBuf.st_atime);
+ dtAccess->Set(static_cast<time_t>(stBuf.st_atime));
if ( dtMod )
- dtMod->Set(stBuf.st_mtime);
+ dtMod->Set(static_cast<time_t>(stBuf.st_mtime));
if ( dtCreate )
- dtCreate->Set(stBuf.st_ctime);
+ dtCreate->Set(static_cast<time_t>(stBuf.st_ctime));
return true;
}
#else // other platform
+ wxUnusedVar(dtAccess);
+ wxUnusedVar(dtMod);
+ wxUnusedVar(dtCreate);
#endif // platforms
wxLogSysError(_("Failed to retrieve file times for '%s'"),
#endif // wxUSE_DATETIME
-#ifdef __WXMAC__
-const short kMacExtensionMaxLength = 16 ;
-class MacDefaultExtensionRecord
+// ----------------------------------------------------------------------------
+// file size functions
+// ----------------------------------------------------------------------------
+
+#if wxUSE_LONGLONG
+
+/* static */
+wxULongLong wxFileName::GetSize(const wxString &filename)
{
-public :
- MacDefaultExtensionRecord()
- {
- m_ext[0] = 0 ;
- m_type = m_creator = NULL ;
- }
- MacDefaultExtensionRecord( const MacDefaultExtensionRecord& from )
- {
- wxStrcpy( m_ext , from.m_ext ) ;
- m_type = from.m_type ;
- m_creator = from.m_creator ;
- }
- MacDefaultExtensionRecord( const wxChar * extension , OSType type , OSType creator )
- {
- wxStrncpy( m_ext , extension , kMacExtensionMaxLength ) ;
- m_ext[kMacExtensionMaxLength] = 0 ;
- m_type = type ;
- m_creator = creator ;
- }
- wxChar m_ext[kMacExtensionMaxLength] ;
- OSType m_type ;
- OSType m_creator ;
-} ;
+ if (!wxFileExists(filename))
+ return wxInvalidSize;
+
+#if defined(__WIN32__)
+ wxFileHandle f(filename, wxFileHandle::ReadAttr);
+ if (!f.IsOk())
+ return wxInvalidSize;
+
+ DWORD lpFileSizeHigh;
+ DWORD ret = GetFileSize(f, &lpFileSizeHigh);
+ if ( ret == INVALID_FILE_SIZE && ::GetLastError() != NO_ERROR )
+ return wxInvalidSize;
+
+ return wxULongLong(lpFileSizeHigh, ret);
+#else // ! __WIN32__
+ wxStructStat st;
+ if (wxStat( filename, &st) != 0)
+ return wxInvalidSize;
+ return wxULongLong(st.st_size);
+#endif
+}
-#include "wx/dynarray.h"
-WX_DECLARE_OBJARRAY(MacDefaultExtensionRecord, MacDefaultExtensionArray) ;
+/* static */
+wxString wxFileName::GetHumanReadableSize(const wxULongLong &bs,
+ const wxString &nullsize,
+ int precision,
+ wxSizeConvention conv)
+{
+ // deal with trivial case first
+ if ( bs == 0 || bs == wxInvalidSize )
+ return nullsize;
-bool gMacDefaultExtensionsInited = false ;
+ // depending on the convention used the multiplier may be either 1000 or
+ // 1024 and the binary infix may be empty (for "KB") or "i" (for "KiB")
+ double multiplier = 1024.;
+ wxString biInfix;
-#include "wx/arrimpl.cpp"
+ switch ( conv )
+ {
+ case wxSIZE_CONV_TRADITIONAL:
+ // nothing to do, this corresponds to the default values of both
+ // the multiplier and infix string
+ break;
+
+ case wxSIZE_CONV_IEC:
+ biInfix = "i";
+ break;
+
+ case wxSIZE_CONV_SI:
+ multiplier = 1000;
+ break;
+ }
+
+ const double kiloByteSize = multiplier;
+ const double megaByteSize = multiplier * kiloByteSize;
+ const double gigaByteSize = multiplier * megaByteSize;
+ const double teraByteSize = multiplier * gigaByteSize;
+
+ const double bytesize = bs.ToDouble();
+
+ wxString result;
+ if ( bytesize < kiloByteSize )
+ result.Printf("%s B", bs.ToString());
+ else if ( bytesize < megaByteSize )
+ result.Printf("%.*f K%sB", precision, bytesize/kiloByteSize, biInfix);
+ else if (bytesize < gigaByteSize)
+ result.Printf("%.*f M%sB", precision, bytesize/megaByteSize, biInfix);
+ else if (bytesize < teraByteSize)
+ result.Printf("%.*f G%sB", precision, bytesize/gigaByteSize, biInfix);
+ else
+ result.Printf("%.*f T%sB", precision, bytesize/teraByteSize, biInfix);
-WX_DEFINE_EXPORTED_OBJARRAY(MacDefaultExtensionArray) ;
+ return result;
+}
-MacDefaultExtensionArray gMacDefaultExtensions ;
+wxULongLong wxFileName::GetSize() const
+{
+ return GetSize(GetFullPath());
+}
-static void MacEnsureDefaultExtensionsLoaded()
+wxString wxFileName::GetHumanReadableSize(const wxString& failmsg,
+ int precision,
+ wxSizeConvention conv) const
{
- if ( !gMacDefaultExtensionsInited )
- {
+ return GetHumanReadableSize(GetSize(), failmsg, precision, conv);
+}
+
+#endif // wxUSE_LONGLONG
+
+// ----------------------------------------------------------------------------
+// Mac-specific functions
+// ----------------------------------------------------------------------------
+
+#if defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON
+
+namespace
+{
+
+class MacDefaultExtensionRecord
+{
+public:
+ MacDefaultExtensionRecord()
+ {
+ m_type =
+ m_creator = 0 ;
+ }
+
+ // default copy ctor, assignment operator and dtor are ok
- // load the default extensions
- MacDefaultExtensionRecord defaults[1] =
+ MacDefaultExtensionRecord(const wxString& ext, OSType type, OSType creator)
+ : m_ext(ext)
{
- MacDefaultExtensionRecord( wxT("txt") , 'TEXT' , 'ttxt' ) ,
+ m_type = type;
+ m_creator = creator;
+ }
+
+ wxString m_ext;
+ OSType m_type;
+ OSType m_creator;
+};
+
+WX_DECLARE_OBJARRAY(MacDefaultExtensionRecord, MacDefaultExtensionArray);
- } ;
- // we could load the pc exchange prefs here too
+bool gMacDefaultExtensionsInited = false;
- for ( size_t i = 0 ; i < WXSIZEOF( defaults ) ; ++i )
+#include "wx/arrimpl.cpp"
+
+WX_DEFINE_EXPORTED_OBJARRAY(MacDefaultExtensionArray);
+
+MacDefaultExtensionArray gMacDefaultExtensions;
+
+// load the default extensions
+const MacDefaultExtensionRecord gDefaults[] =
+{
+ MacDefaultExtensionRecord( "txt", 'TEXT', 'ttxt' ),
+ MacDefaultExtensionRecord( "tif", 'TIFF', '****' ),
+ MacDefaultExtensionRecord( "jpg", 'JPEG', '****' ),
+};
+
+void MacEnsureDefaultExtensionsLoaded()
+{
+ if ( !gMacDefaultExtensionsInited )
{
- gMacDefaultExtensions.Add( defaults[i] ) ;
+ // we could load the pc exchange prefs here too
+ for ( size_t i = 0 ; i < WXSIZEOF( gDefaults ) ; ++i )
+ {
+ gMacDefaultExtensions.Add( gDefaults[i] ) ;
+ }
+ gMacDefaultExtensionsInited = true;
}
- gMacDefaultExtensionsInited = true ;
- }
}
+
+} // anonymous namespace
+
bool wxFileName::MacSetTypeAndCreator( wxUint32 type , wxUint32 creator )
{
- FInfo fndrInfo ;
- FSSpec spec ;
- wxMacFilename2FSSpec(GetFullPath(),&spec) ;
- OSErr err = FSpGetFInfo( &spec , &fndrInfo ) ;
- wxCHECK( err == noErr , false ) ;
+ FSRef fsRef ;
+ FSCatalogInfo catInfo;
+ FileInfo *finfo ;
- fndrInfo.fdType = type ;
- fndrInfo.fdCreator = creator ;
- FSpSetFInfo( &spec , &fndrInfo ) ;
- return true ;
+ if ( wxMacPathToFSRef( GetFullPath() , &fsRef ) == noErr )
+ {
+ if ( FSGetCatalogInfo (&fsRef, kFSCatInfoFinderInfo, &catInfo, NULL, NULL, NULL) == noErr )
+ {
+ finfo = (FileInfo*)&catInfo.finderInfo;
+ finfo->fileType = type ;
+ finfo->fileCreator = creator ;
+ FSSetCatalogInfo( &fsRef, kFSCatInfoFinderInfo, &catInfo ) ;
+ return true ;
+ }
+ }
+ return false ;
}
-bool wxFileName::MacGetTypeAndCreator( wxUint32 *type , wxUint32 *creator )
+bool wxFileName::MacGetTypeAndCreator( wxUint32 *type , wxUint32 *creator ) const
{
- FInfo fndrInfo ;
- FSSpec spec ;
- wxMacFilename2FSSpec(GetFullPath(),&spec) ;
- OSErr err = FSpGetFInfo( &spec , &fndrInfo ) ;
- wxCHECK( err == noErr , false ) ;
+ FSRef fsRef ;
+ FSCatalogInfo catInfo;
+ FileInfo *finfo ;
- *type = fndrInfo.fdType ;
- *creator = fndrInfo.fdCreator ;
- return true ;
+ if ( wxMacPathToFSRef( GetFullPath() , &fsRef ) == noErr )
+ {
+ if ( FSGetCatalogInfo (&fsRef, kFSCatInfoFinderInfo, &catInfo, NULL, NULL, NULL) == noErr )
+ {
+ finfo = (FileInfo*)&catInfo.finderInfo;
+ *type = finfo->fileType ;
+ *creator = finfo->fileCreator ;
+ return true ;
+ }
+ }
+ return false ;
}
bool wxFileName::MacSetDefaultTypeAndCreator()
void wxFileName::MacRegisterDefaultTypeAndCreator( const wxString& ext , wxUint32 type , wxUint32 creator )
{
- MacEnsureDefaultExtensionsLoaded() ;
- MacDefaultExtensionRecord rec ;
- rec.m_type = type ;
- rec.m_creator = creator ;
- wxStrncpy( rec.m_ext , ext.Lower().c_str() , kMacExtensionMaxLength ) ;
- gMacDefaultExtensions.Add( rec ) ;
+ MacEnsureDefaultExtensionsLoaded();
+ MacDefaultExtensionRecord rec(ext.Lower(), type, creator);
+ gMacDefaultExtensions.Add( rec );
}
-#endif
+
+#endif // defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON