X-Git-Url: https://git.saurik.com/wxWidgets.git/blobdiff_plain/43b2d5e7c3b3e3d6b245e279dde73d96e0075911..538a2cfaf2be9f864e58c9a9fe232966af6bf2a0:/src/common/filename.cpp diff --git a/src/common/filename.cpp b/src/common/filename.cpp index 0d3e6229f2..d6d68aeeb6 100644 --- a/src/common/filename.cpp +++ b/src/common/filename.cpp @@ -22,9 +22,18 @@ 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 @@ -68,7 +77,7 @@ #endif #ifndef WX_PRECOMP - #ifdef __WXMSW__ + #ifdef __WINDOWS__ #include "wx/msw/wrapwin.h" // For GetShort/LongPathName #endif #include "wx/dynarray.h" @@ -89,8 +98,10 @@ #include "wx/msw/gccpriv.h" #endif -#ifdef __WXWINCE__ -#include "wx/msw/private.h" +#ifdef __WINDOWS__ + #include "wx/msw/private.h" + #include // for CLSID_ShellLink + #include "wx/msw/missing.h" #endif #if defined(__WXMAC__) @@ -109,19 +120,6 @@ #include #endif -#ifdef __MWERKS__ -#ifdef __MACH__ -#include -#include -#include -#include -#else -#include -#include -#include -#endif -#endif - #ifdef __WATCOMC__ #include #include @@ -139,11 +137,19 @@ #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 @@ -158,17 +164,21 @@ class wxFileHandle public: enum OpenMode { - Read, - Write + ReadAttr, + WriteAttr }; 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.fn_str(), // name - mode == Read ? GENERIC_READ // access mask - : GENERIC_WRITE, + 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 @@ -179,7 +189,7 @@ public: if ( m_hFile == INVALID_HANDLE_VALUE ) { - if ( mode == Read ) + if ( mode == ReadAttr ) { wxLogSysError(_("Failed to open '%s' for reading"), filename.c_str()); @@ -230,13 +240,13 @@ static void ConvertFileTimeToWx(wxDateTime *dt, const FILETIME &ft) 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, @@ -257,12 +267,12 @@ static void ConvertWxToFileTime(FILETIME *ft, const wxDateTime& dt) FILETIME ftLocal; if ( !::SystemTimeToFileTime(&st, &ftLocal) ) { - wxLogLastError(_T("SystemTimeToFileTime")); + wxLogLastError(wxT("SystemTimeToFileTime")); } if ( !::LocalFileTimeToFileTime(&ftLocal, ft) ) { - wxLogLastError(_T("LocalFileTimeToFileTime")); + wxLogLastError(wxT("LocalFileTimeToFileTime")); } } @@ -283,7 +293,18 @@ static wxString wxGetVolumeString(const wxString& volume, wxPathFormat format) // 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 ) { @@ -295,17 +316,83 @@ static wxString wxGetVolumeString(const wxString& volume, wxPathFormat format) 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 - path[0u] == wxFILE_SEP_PATH_DOS && - path[1u] == wxFILE_SEP_PATH_DOS && - path[2u] != wxFILE_SEP_PATH_DOS; + 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 // ============================================================================ @@ -322,6 +409,7 @@ void wxFileName::Assign( const wxFileName &filepath ) 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, @@ -385,6 +473,13 @@ void wxFileName::SetPath( const wxString& pathOrig, wxPathFormat format ) } // 1) Determine if the path is relative or absolute. + + if ( path.empty() ) + { + // we had only the volume + return; + } + wxChar leadingChar = path[0u]; switch (format) @@ -412,7 +507,7 @@ void wxFileName::SetPath( const wxString& pathOrig, wxPathFormat format ) break; default: - wxFAIL_MSG( _T("Unknown path format") ); + wxFAIL_MSG( wxT("Unknown path format") ); // !! Fall through !! case wxPATH_UNIX: @@ -482,13 +577,15 @@ void wxFileName::Assign(const wxString& fullpathOrig, SplitPath(fullname, &volDummy, &pathDummy, &name, &ext, &hasExt, format); wxASSERT_MSG( volDummy.empty() && pathDummy.empty(), - _T("the file name shouldn't contain the path") ); + 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); } @@ -511,17 +608,19 @@ void wxFileName::AssignDir(const wxString& dir, wxPathFormat format) void wxFileName::Clear() { - m_dirs.Clear(); - - m_volume = - m_name = - m_ext = wxEmptyString; + m_dirs.clear(); + m_volume.clear(); + m_name.clear(); + m_ext.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 */ @@ -542,24 +641,168 @@ wxFileName wxFileName::DirName(const wxString& dir, wxPathFormat format) // 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( GetPath() ); + int flags = wxFILE_EXISTS_DIR; + if ( !ShouldFollowLink() ) + flags |= wxFILE_EXISTS_NO_FOLLOW; + + return Exists(GetPath(), flags); } -bool wxFileName::DirExists( const wxString &dir ) +/* static */ +bool wxFileName::DirExists( const wxString &dirPath ) +{ + return wxFileSystemObjectExists(dirPath, wxFILE_EXISTS_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); } // ---------------------------------------------------------------------------- @@ -649,7 +892,7 @@ static int wxOpenWithDeleteOnClose(const wxString& filename) DWORD attributes = FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE; - HANDLE h = ::CreateFile(filename.fn_str(), access, 0, NULL, + HANDLE h = ::CreateFile(filename.t_str(), access, 0, NULL, disposition, attributes, NULL); return wxOpenOSFHandle(h, wxO_BINARY); @@ -679,12 +922,12 @@ static bool wxTempOpen(wxFFile *file, const wxString& path, bool *deleteOnClose) { #ifndef wx_fdopen *deleteOnClose = false; - return file->Open(path, _T("w+b")); + 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")); + file->Attach(wx_fdopen(fd, "w+b"), path); return file->IsOpened(); #endif // wx_fdopen } @@ -744,10 +987,10 @@ static wxString wxCreateTempImpl( } #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__) - if ( !::GetTempFileName(dir.fn_str(), name.fn_str(), 0, - wxStringBuffer(path, MAX_PATH + 1)) ) + if (!::GetTempFileName(dir.t_str(), name.t_str(), 0, + wxStringBuffer(path, MAX_PATH + 1))) { - wxLogLastError(_T("GetTempFileName")); + wxLogLastError(wxT("GetTempFileName")); path.clear(); } @@ -765,7 +1008,7 @@ static wxString wxCreateTempImpl( #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(path.fn_str()); @@ -795,9 +1038,9 @@ static wxString wxCreateTempImpl( if ( ffileTemp ) { #ifdef wx_fdopen - ffileTemp->Attach(wx_fdopen(fdTemp, "r+b")); + ffileTemp->Attach(wx_fdopen(fdTemp, "r+b"), path); #else - ffileTemp->Open(path, _T("r+b")); + ffileTemp->Open(path, wxT("r+b")); close(fdTemp); #endif } @@ -812,7 +1055,7 @@ static wxString wxCreateTempImpl( #ifdef HAVE_MKTEMP // same as above - path += _T("XXXXXX"); + path += wxT("XXXXXX"); wxCharBuffer buf = wxConvFile.cWX2MB( path ); if ( !mktemp( (char*)(const char*) buf ) ) @@ -825,7 +1068,7 @@ static wxString wxCreateTempImpl( } #else // !HAVE_MKTEMP (includes __DOS__) // generate the unique file name ourselves - #if !defined(__DOS__) && !defined(__PALMOS__) && (!defined(__MWERKS__) || defined(__DARWIN__) ) + #if !defined(__DOS__) path << (unsigned int)getpid(); #endif @@ -835,7 +1078,7 @@ static wxString wxCreateTempImpl( 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); + pathTry = path + wxString::Format(wxT("%.03x"), (unsigned int) n); if ( !wxFileName::FileExists(pathTry) ) { break; @@ -1056,12 +1299,27 @@ wxString wxFileName::GetTempDir() #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__) if ( !::GetTempPath(MAX_PATH, wxStringBuffer(dir, MAX_PATH + 1)) ) { - wxLogLastError(_T("GetTempPath")); + wxLogLastError(wxT("GetTempPath")); } #elif defined(__WXMAC__) && wxOSX_USE_CARBON - dir = wxMacFindFolder(short(kOnSystemDisk), kTemporaryFolderType, kCreateFolder); + 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() ) @@ -1127,7 +1385,7 @@ bool wxFileName::Rmdir(int flags) const bool wxFileName::Rmdir(const wxString& dir, int flags) { -#ifdef __WXMSW__ +#ifdef __WINDOWS__ if ( flags & wxPATH_RMDIR_RECURSIVE ) { // SHFileOperation needs double null termination string @@ -1135,12 +1393,12 @@ bool wxFileName::Rmdir(const wxString& dir, int flags) wxString path(dir); if ( path.Last() == wxFILE_SEP_PATH ) path.RemoveLast(); - path += _T('\0'); + path += wxT('\0'); SHFILEOPSTRUCT fileop; wxZeroMemory(fileop); fileop.wFunc = FO_DELETE; - fileop.pFrom = path.fn_str(); + fileop.pFrom = path.t_str(); fileop.fFlags = FOF_SILENT | FOF_NOCONFIRMATION; #ifndef __WXWINCE__ // FOF_NOERRORUI is not defined in WinCE @@ -1152,17 +1410,31 @@ bool wxFileName::Rmdir(const wxString& dir, int flags) { // SHFileOperation may return non-Win32 error codes, so the error // message can be incorrect - wxLogApiError(_T("SHFileOperation"), ret); + wxLogApiError(wxT("SHFileOperation"), ret); return false; } return true; } else if ( flags & wxPATH_RMDIR_FULL ) -#else // !__WXMSW__ +#else // !__WINDOWS__ if ( flags != 0 ) // wxPATH_RMDIR_FULL or wxPATH_RMDIR_RECURSIVE -#endif // !__WXMSW__ +#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; @@ -1174,26 +1446,32 @@ bool wxFileName::Rmdir(const wxString& dir, int flags) wxString filename; - // first delete all subdirectories - bool cont = d.GetFirst(&filename, "", wxDIR_DIRS | wxDIR_HIDDEN); + // 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 __WXMSW__ +#ifndef __WINDOWS__ if ( flags & wxPATH_RMDIR_RECURSIVE ) { - // delete all files too - cont = d.GetFirst(&filename, "", wxDIR_FILES | wxDIR_HIDDEN); + // 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 // !__WXMSW__ +#endif // !__WINDOWS__ } return ::wxRmdir(dir); @@ -1245,7 +1523,7 @@ bool wxFileName::Normalize(int flags, 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)); @@ -1304,15 +1582,24 @@ bool wxFileName::Normalize(int flags, 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; + } } } @@ -1416,13 +1703,6 @@ bool wxFileName::ReplaceHomeDir(wxPathFormat format) // quotation marks." #if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE -// The following lines are necessary under WinCE -// #include "wx/msw/private.h" -// #include -#include -#if defined(__WXWINCE__) -#include -#endif bool wxFileName::GetShortcutTarget(const wxString& shortcutPath, wxString& targetFilename, @@ -1499,7 +1779,7 @@ bool wxFileName::IsAbsolute(wxPathFormat format) const { wxString dir = m_dirs[0u]; - if (!dir.empty() && dir[0u] == _T('~')) + if (!dir.empty() && dir[0u] == wxT('~')) return true; } } @@ -1563,7 +1843,7 @@ bool wxFileName::MakeRelativeTo(const wxString& pathBase, wxPathFormat format) // files) if ( m_dirs.IsEmpty() && IsDir() ) { - m_dirs.Add(_T('.')); + m_dirs.Add(wxT('.')); } } @@ -1590,8 +1870,15 @@ bool wxFileName::SameAs(const wxFileName& filepath, wxPathFormat format) const 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; } @@ -1599,7 +1886,7 @@ bool wxFileName::SameAs(const wxFileName& filepath, wxPathFormat format) const /* 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; } @@ -1624,7 +1911,7 @@ wxString wxFileName::GetForbiddenChars(wxPathFormat format) case wxPATH_MAC: // On a Mac even names with * and ? are allowed (Tested with OS // 9.2.1 and OS X 10.2.5) - strForbiddenChars = wxEmptyString; + strForbiddenChars.clear(); break; case wxPATH_DOS: @@ -1670,7 +1957,7 @@ wxString wxFileName::GetPathSeparators(wxPathFormat format) break; default: - wxFAIL_MSG( _T("Unknown wxPATH_XXX style") ); + wxFAIL_MSG( wxT("Unknown wxPATH_XXX style") ); // fall through case wxPATH_UNIX: @@ -1696,7 +1983,7 @@ wxString wxFileName::GetPathTerminators(wxPathFormat format) // under VMS the end of the path is ']', not the path separator used to // separate the components - return format == wxPATH_VMS ? wxString(_T(']')) : GetPathSeparators(format); + return format == wxPATH_VMS ? wxString(wxT(']')) : GetPathSeparators(format); } /* static */ @@ -1704,7 +1991,19 @@ bool wxFileName::IsPathSeparator(wxChar ch, wxPathFormat format) { // wxString::Find() doesn't work as expected with NUL - it will always find // it, so test for it separately - return ch != _T('\0') && GetPathSeparators(format).Find(ch) != wxNOT_FOUND; + return ch != wxT('\0') && 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; } // ---------------------------------------------------------------------------- @@ -1715,7 +2014,7 @@ bool wxFileName::IsPathSeparator(wxChar ch, wxPathFormat format) { if ( dir.empty() ) { - wxFAIL_MSG( _T("empty directory passed to wxFileName::InsertDir()") ); + wxFAIL_MSG( wxT("empty directory passed to wxFileName::InsertDir()") ); return false; } @@ -1725,7 +2024,7 @@ bool wxFileName::IsPathSeparator(wxChar ch, wxPathFormat format) { 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; } @@ -1734,10 +2033,12 @@ bool wxFileName::IsPathSeparator(wxChar ch, wxPathFormat format) return true; } -void wxFileName::AppendDir( const wxString& dir ) +bool wxFileName::AppendDir( const wxString& dir ) { - if ( IsValidDirComponent(dir) ) - m_dirs.Add( dir ); + if (!IsValidDirComponent(dir)) + return false; + m_dirs.Add(dir); + return true; } void wxFileName::PrependDir( const wxString& dir ) @@ -1745,10 +2046,12 @@ void wxFileName::PrependDir( const wxString& dir ) InsertDir(0, dir); } -void wxFileName::InsertDir(size_t before, const wxString& dir) +bool wxFileName::InsertDir(size_t before, const wxString& dir) { - if ( IsValidDirComponent(dir) ) - m_dirs.Insert(dir, before); + if (!IsValidDirComponent(dir)) + return false; + m_dirs.Insert(dir, before); + return true; } void wxFileName::RemoveDir(size_t pos) @@ -1898,14 +2201,14 @@ wxString wxFileName::GetShortPath() const { wxString path(GetFullPath()); -#if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__) - DWORD sz = ::GetShortPathName(path.fn_str(), NULL, 0); +#if defined(__WINDOWS__) && defined(__WIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__) + DWORD sz = ::GetShortPathName(path.t_str(), NULL, 0); if ( sz != 0 ) { wxString pathOut; if ( ::GetShortPathName ( - path.fn_str(), + path.t_str(), wxStringBuffer(pathOut, sz), sz ) != 0 ) @@ -1940,13 +2243,13 @@ wxString wxFileName::GetLongPath() const { s_triedToLoad = true; - wxDynamicLibrary dllKernel(_T("kernel32")); + wxDynamicLibrary dllKernel(wxT("kernel32")); - const wxChar* GetLongPathName = _T("GetLongPathName") + const wxChar* GetLongPathName = wxT("GetLongPathName") #if wxUSE_UNICODE - _T("W"); + wxT("W"); #else // ANSI - _T("A"); + wxT("A"); #endif // Unicode/ANSI if ( dllKernel.HasSymbol(GetLongPathName) ) @@ -1963,12 +2266,12 @@ wxString wxFileName::GetLongPath() const if ( s_pfnGetLongPathName ) { - DWORD dwSize = (*s_pfnGetLongPathName)(path.fn_str(), NULL, 0); + DWORD dwSize = (*s_pfnGetLongPathName)(path.t_str(), NULL, 0); if ( dwSize > 0 ) { if ( (*s_pfnGetLongPathName) ( - path.fn_str(), + path.t_str(), wxStringBuffer(pathOut, dwSize), dwSize ) != 0 ) @@ -1990,7 +2293,7 @@ wxString wxFileName::GetLongPath() const GetVolumeSeparator(wxPATH_DOS) + GetPathSeparator(wxPATH_DOS); else - pathOut = wxEmptyString; + pathOut.clear(); wxArrayString dirs = GetDirs(); dirs.Add(GetFullName()); @@ -2020,7 +2323,7 @@ wxString wxFileName::GetLongPath() const continue; } - hFind = ::FindFirstFile(tmpPath.fn_str(), &findFileData); + hFind = ::FindFirstFile(tmpPath.t_str(), &findFileData); if (hFind == INVALID_HANDLE_VALUE) { // Error: most likely reason is that path doesn't exist, so @@ -2048,7 +2351,7 @@ wxPathFormat wxFileName::GetFormat( wxPathFormat format ) { if (format == wxPATH_NATIVE) { -#if defined(__WXMSW__) || defined(__OS2__) || defined(__DOS__) +#if defined(__WINDOWS__) || defined(__OS2__) || defined(__DOS__) format = wxPATH_DOS; #elif defined(__VMS) format = wxPATH_VMS; @@ -2091,9 +2394,26 @@ wxFileName::SplitVolume(const wxString& fullpathWithVolume, wxString fullpath = fullpathWithVolume; - // special Windows UNC paths hack: transform \\share\path into share:path - if ( IsUNCPath(fullpath, 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 + + // 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) ) + { + // special Windows UNC paths hack: transform \\share\path into share:path + fullpath.erase(0, 2); size_t posFirstSlash = @@ -2112,8 +2432,11 @@ wxFileName::SplitVolume(const wxString& fullpathWithVolume, { 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 ) { @@ -2151,7 +2474,7 @@ void wxFileName::SplitPath(const wxString& fullpathWithVolume, if ( (posLastDot != wxString::npos) && (posLastDot == 0 || IsPathSeparator(fullpath[posLastDot - 1]) || - (format == wxPATH_VMS && fullpath[posLastDot - 1] == _T(']'))) ) + (format == wxPATH_VMS && fullpath[posLastDot - 1] == wxT(']'))) ) { // dot may be (and commonly -- at least under Unix -- is) the first // character of the filename, don't treat the entire filename as @@ -2193,7 +2516,7 @@ void wxFileName::SplitPath(const wxString& fullpathWithVolume, // special VMS hack: remove the initial bracket if ( format == wxPATH_VMS ) { - if ( (*pstrPath)[0u] == _T('[') ) + if ( (*pstrPath)[0u] == wxT('[') ) pstrPath->erase(0, 1); } } @@ -2308,7 +2631,7 @@ bool wxFileName::SetTimes(const wxDateTime *dtAccess, flags = 0; } - wxFileHandle fh(path, wxFileHandle::Write, flags); + wxFileHandle fh(path, wxFileHandle::WriteAttr, flags); if ( fh.IsOk() ) { if ( ::SetFileTime(fh, @@ -2392,7 +2715,7 @@ bool wxFileName::GetTimes(wxDateTime *dtAccess, } else // file { - wxFileHandle fh(GetFullPath(), wxFileHandle::Read); + wxFileHandle fh(GetFullPath(), wxFileHandle::ReadAttr); if ( fh.IsOk() ) { ok = ::GetFileTime(fh, @@ -2420,14 +2743,16 @@ bool wxFileName::GetTimes(wxDateTime *dtAccess, #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(stBuf.st_atime)); if ( dtMod ) - dtMod->Set(stBuf.st_mtime); + dtMod->Set(static_cast(stBuf.st_mtime)); if ( dtCreate ) - dtCreate->Set(stBuf.st_ctime); + dtCreate->Set(static_cast(stBuf.st_ctime)); return true; } @@ -2458,11 +2783,8 @@ wxULongLong wxFileName::GetSize(const wxString &filename) if (!wxFileExists(filename)) return wxInvalidSize; -#if defined(__WXPALMOS__) - // TODO - return wxInvalidSize; -#elif defined(__WIN32__) - wxFileHandle f(filename, wxFileHandle::Read); +#if defined(__WIN32__) + wxFileHandle f(filename, wxFileHandle::ReadAttr); if (!f.IsOk()) return wxInvalidSize; @@ -2474,11 +2796,7 @@ wxULongLong wxFileName::GetSize(const wxString &filename) return wxULongLong(lpFileSizeHigh, ret); #else // ! __WIN32__ wxStructStat st; -#ifndef wxNEED_WX_UNISTD_H - if (wxStat( filename.fn_str() , &st) != 0) -#else if (wxStat( filename, &st) != 0) -#endif return wxInvalidSize; return wxULongLong(st.st_size); #endif @@ -2487,27 +2805,54 @@ wxULongLong wxFileName::GetSize(const wxString &filename) /* static */ wxString wxFileName::GetHumanReadableSize(const wxULongLong &bs, const wxString &nullsize, - int precision) + int precision, + wxSizeConvention conv) { - static const double KILOBYTESIZE = 1024.0; - static const double MEGABYTESIZE = 1024.0*KILOBYTESIZE; - static const double GIGABYTESIZE = 1024.0*MEGABYTESIZE; - static const double TERABYTESIZE = 1024.0*GIGABYTESIZE; - - if (bs == 0 || bs == wxInvalidSize) + // deal with trivial case first + if ( bs == 0 || bs == wxInvalidSize ) return nullsize; - double bytesize = bs.ToDouble(); - if (bytesize < KILOBYTESIZE) - return wxString::Format(_("%s B"), bs.ToString().c_str()); - if (bytesize < MEGABYTESIZE) - return wxString::Format(_("%.*f kB"), precision, bytesize/KILOBYTESIZE); - if (bytesize < GIGABYTESIZE) - return wxString::Format(_("%.*f MB"), precision, bytesize/MEGABYTESIZE); - if (bytesize < TERABYTESIZE) - return wxString::Format(_("%.*f GB"), precision, bytesize/GIGABYTESIZE); + // 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; + + 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); - return wxString::Format(_("%.*f TB"), precision, bytesize/TERABYTESIZE); + return result; } wxULongLong wxFileName::GetSize() const @@ -2515,9 +2860,11 @@ wxULongLong wxFileName::GetSize() const return GetSize(GetFullPath()); } -wxString wxFileName::GetHumanReadableSize(const wxString &failmsg, int precision) const +wxString wxFileName::GetHumanReadableSize(const wxString& failmsg, + int precision, + wxSizeConvention conv) const { - return GetHumanReadableSize(GetSize(), failmsg, precision); + return GetHumanReadableSize(GetSize(), failmsg, precision, conv); } #endif // wxUSE_LONGLONG