X-Git-Url: https://git.saurik.com/wxWidgets.git/blobdiff_plain/35c2aa4f19cce4f5a6bd0199333017453e569a2d..0f1c3d30d4a699817340ce56e752b61b78cccb1c:/src/common/filename.cpp diff --git a/src/common/filename.cpp b/src/common/filename.cpp index 9285be0e5d..917c89de0f 100644 --- a/src/common/filename.cpp +++ b/src/common/filename.cpp @@ -22,7 +22,16 @@ 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. + + 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 and Mac OS X under CodeWarrior 7 format, absolute file names have the form @@ -83,6 +92,7 @@ #include "wx/tokenzr.h" #include "wx/config.h" // for wxExpandEnvVars #include "wx/dynlib.h" +#include "wx/dir.h" #if defined(__WIN32__) && defined(__MINGW32__) #include "wx/msw/gccpriv.h" @@ -143,6 +153,15 @@ extern const wxULongLong wxInvalidSize = (unsigned)-1; #endif // wxUSE_LONGLONG +#ifdef __WIN32__ + // this define is missing from VC6 headers + #ifndef INVALID_FILE_ATTRIBUTES + #define INVALID_FILE_ATTRIBUTES ((DWORD)-1) + #endif +#endif // __WIN32__ + +namespace +{ // ---------------------------------------------------------------------------- // private classes @@ -157,33 +176,41 @@ class wxFileHandle 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.fn_str(), // name - mode == Read ? GENERIC_READ // access mask - : GENERIC_WRITE, + 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 ) { - if ( mode == Read ) + if ( mode == ReadAttr ) + { wxLogSysError(_("Failed to open '%s' for reading"), filename.c_str()); + } else + { wxLogSysError(_("Failed to open '%s' for writing"), filename.c_str()); + } } } @@ -225,13 +252,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, @@ -252,12 +279,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")); } } @@ -278,7 +305,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 ) { @@ -290,17 +328,33 @@ 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]); } +// ---------------------------------------------------------------------------- +// private constants +// ---------------------------------------------------------------------------- + +// length of \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ string +static const size_t wxMSWUniqueVolumePrefixLength = 49; + +} // anonymous namespace + // ============================================================================ // implementation // ============================================================================ @@ -380,6 +434,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) @@ -407,12 +468,11 @@ 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: - // the paths of the form "~" or "~username" are absolute - m_relative = leadingChar != wxT('/') && leadingChar != _T('~'); + m_relative = leadingChar != wxT('/'); break; case wxPATH_DOS: @@ -471,27 +531,22 @@ void wxFileName::Assign(const wxString& fullpathOrig, 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__ + // 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, &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") ); - -#else // !__WXDEBUG__ - SplitPath(fullname, NULL /* no volume */, NULL /* no path */, - &name, &ext, &hasExt, format); - SplitPath(fullpath, &volume, &path, NULL, NULL, format); -#endif // __WXDEBUG__/!__WXDEBUG__ - +#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); } @@ -550,9 +605,30 @@ bool wxFileName::FileExists() const return wxFileName::FileExists( GetFullPath() ); } -bool wxFileName::FileExists( const wxString &file ) +/* static */ +bool wxFileName::FileExists( const wxString &filePath ) { - return ::wxFileExists( file ); +#if defined(__WXPALMOS__) + return false; +#elif defined(__WIN32__) && !defined(__WXMICROWIN__) + // we must use GetFileAttributes() instead of the ANSI C functions because + // it can cope with network (UNC) paths unlike them + DWORD ret = ::GetFileAttributes(filePath.fn_str()); + + return (ret != INVALID_FILE_ATTRIBUTES) && !(ret & FILE_ATTRIBUTE_DIRECTORY); +#else // !__WIN32__ + #ifndef S_ISREG + #define S_ISREG(mode) ((mode) & S_IFREG) + #endif + wxStructStat st; + + return (wxStat( filePath, &st) == 0 && S_ISREG(st.st_mode)) +#ifdef __OS2__ + || (errno == EACCES) // if access is denied something with that name + // exists and is opened in exclusive mode. +#endif + ; +#endif // __WIN32__/!__WIN32__ } bool wxFileName::DirExists() const @@ -560,9 +636,62 @@ bool wxFileName::DirExists() const return wxFileName::DirExists( GetPath() ); } -bool wxFileName::DirExists( const wxString &dir ) +/* static */ +bool wxFileName::DirExists( const wxString &dirPath ) { - return ::wxDirExists( dir ); + wxString strPath(dirPath); + +#if defined(__WINDOWS__) || defined(__OS2__) + // 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__ + +#ifdef __OS2__ + // OS/2 can't handle "d:", it wants either "d:\" or "d:." + if (strPath.length() == 2 && strPath[1u] == wxT(':')) + strPath << wxT('.'); +#endif + +#if defined(__WXPALMOS__) + return false; +#elif defined(__WIN32__) && !defined(__WXMICROWIN__) + // stat() can't cope with network paths + DWORD ret = ::GetFileAttributes(strPath.fn_str()); + + return (ret != INVALID_FILE_ATTRIBUTES) && (ret & FILE_ATTRIBUTE_DIRECTORY); +#elif defined(__OS2__) + FILESTATUS3 Info = {{0}}; + APIRET rc = ::DosQueryPathInfo((PSZ)(WXSTRINGCAST strPath), FIL_STANDARD, + (void*) &Info, sizeof(FILESTATUS3)); + + return ((rc == NO_ERROR) && (Info.attrFile & FILE_DIRECTORY)) || + (rc == ERROR_SHARING_VIOLATION); + // If we got a sharing violation, there must be something with this name. +#else // !__WIN32__ + + wxStructStat st; +#ifndef __VISAGECPP__ + return wxStat(strPath, &st) == 0 && ((st.st_mode & S_IFMT) == S_IFDIR); +#else + // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only + return wxStat(strPath, &st) == 0 && (st.st_mode == S_IFDIR); +#endif + +#endif // __WIN32__/!__WIN32__ } // ---------------------------------------------------------------------------- @@ -598,7 +727,7 @@ wxString wxFileName::GetCwd(const wxString& volume) return cwd; } -bool wxFileName::SetCwd() +bool wxFileName::SetCwd() const { return wxFileName::SetCwd( GetPath() ); } @@ -682,7 +811,7 @@ 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) @@ -750,7 +879,7 @@ static wxString wxCreateTempImpl( if ( !::GetTempFileName(dir.fn_str(), name.fn_str(), 0, wxStringBuffer(path, MAX_PATH + 1)) ) { - wxLogLastError(_T("GetTempFileName")); + wxLogLastError(wxT("GetTempFileName")); path.clear(); } @@ -768,7 +897,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()); @@ -800,7 +929,7 @@ static wxString wxCreateTempImpl( #ifdef wx_fdopen ffileTemp->Attach(wx_fdopen(fdTemp, "r+b")); #else - ffileTemp->Open(path, _T("r+b")); + ffileTemp->Open(path, wxT("r+b")); close(fdTemp); #endif } @@ -815,7 +944,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 ) ) @@ -838,7 +967,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; @@ -1059,7 +1188,7 @@ 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); @@ -1079,7 +1208,7 @@ wxString wxFileName::GetTempDir() return dir; } -bool wxFileName::Mkdir( int perm, int flags ) +bool wxFileName::Mkdir( int perm, int flags ) const { return wxFileName::Mkdir(GetPath(), perm, flags); } @@ -1123,14 +1252,83 @@ bool wxFileName::Mkdir( const wxString& dir, int perm, int flags ) return ::wxMkdir( dir, perm ); } -bool wxFileName::Rmdir() +bool wxFileName::Rmdir(int flags) const { - return wxFileName::Rmdir( GetPath() ); + return wxFileName::Rmdir( GetPath(), flags ); } -bool wxFileName::Rmdir( const wxString &dir ) +bool wxFileName::Rmdir(const wxString& dir, int flags) { - return ::wxRmdir( dir ); +#ifdef __WXMSW__ + 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.fn_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 // !__WXMSW__ + if ( flags != 0 ) // wxPATH_RMDIR_FULL or wxPATH_RMDIR_RECURSIVE +#endif // !__WXMSW__ + { + 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 + bool cont = d.GetFirst(&filename, "", wxDIR_DIRS | wxDIR_HIDDEN); + while ( cont ) + { + wxFileName::Rmdir(path + filename, flags); + cont = d.GetNext(&filename); + } + +#ifndef __WXMSW__ + if ( flags & wxPATH_RMDIR_RECURSIVE ) + { + // delete all files too + cont = d.GetFirst(&filename, "", wxDIR_FILES | wxDIR_HIDDEN); + while ( cont ) + { + ::wxRemoveFile(path + filename); + cont = d.GetNext(&filename); + } + } +#endif // !__WXMSW__ + } + + return ::wxRmdir(dir); } // ---------------------------------------------------------------------------- @@ -1152,7 +1350,6 @@ bool wxFileName::Normalize(int flags, } } - // the existing path components wxArrayString dirs = GetDirs(); @@ -1175,25 +1372,15 @@ bool wxFileName::Normalize(int flags, } // 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)); - - // if we are expanding the tilde, then this path - // *should* be already relative (since we checked for - // the tilde only in the first char of the first dir); - // if m_relative==false, it's because it was initialized - // from a string which started with /~; in that case - // we reach this point but then need m_relative=true - // for relative->absolute expansion later - m_relative = true; - dirs.RemoveAt(0u); } } @@ -1222,7 +1409,7 @@ bool wxFileName::Normalize(int flags, // 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.IsAbsolute(format) ) + if ( !curDir.m_relative ) { // we have prepended an absolute path and thus we are now an absolute // file name too @@ -1302,6 +1489,49 @@ bool wxFileName::Normalize(int flags, 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 + + stringForm.Replace(homedir, "~"); + + // Now assign ourselves the modified path: + Assign(stringForm, GetFullName(), format); + + return true; +} + // ---------------------------------------------------------------------------- // get the shortcut target // ---------------------------------------------------------------------------- @@ -1328,10 +1558,10 @@ bool wxFileName::Normalize(int flags, bool wxFileName::GetShortcutTarget(const wxString& shortcutPath, wxString& targetFilename, - wxString* arguments) + wxString* arguments) const { wxString path, file, ext; - wxSplitPath(shortcutPath, & path, & file, & ext); + wxFileName::SplitPath(shortcutPath, & path, & file, & ext); HRESULT hres; IShellLink* psl; @@ -1394,6 +1624,18 @@ bool wxFileName::GetShortcutTarget(const wxString& shortcutPath, 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 ) @@ -1402,7 +1644,7 @@ bool wxFileName::IsAbsolute(wxPathFormat format) const 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; } @@ -1453,7 +1695,7 @@ bool wxFileName::MakeRelativeTo(const wxString& pathBase, wxPathFormat format) // files) if ( m_dirs.IsEmpty() && IsDir() ) { - m_dirs.Add(_T('.')); + m_dirs.Add(wxT('.')); } } @@ -1560,7 +1802,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: @@ -1586,7 +1828,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 */ @@ -1594,7 +1836,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; } // ---------------------------------------------------------------------------- @@ -1605,7 +1859,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; } @@ -1615,7 +1869,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; } @@ -1699,13 +1953,7 @@ wxString wxFileName::GetPath( int flags, wxPathFormat format ) const 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; @@ -1836,13 +2084,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) ) @@ -1896,19 +2144,21 @@ wxString wxFileName::GetLongPath() const size_t count = dirs.GetCount(); for ( size_t i = 0; i < count; i++ ) { + const wxString& dir = 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 + dirs[i]; - - if ( tmpPath.empty() ) - continue; - - // can't see this being necessary? MF - if ( tmpPath.Last() == GetVolumeSeparator(wxPATH_DOS) ) + tmpPath = pathOut + dir; + + // 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) ) { - // Can't pass a drive and root dir to FindFirstFile, - // so continue to next dir tmpPath += wxFILE_SEP_PATH; pathOut = tmpPath; continue; @@ -1985,9 +2235,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 = @@ -2006,8 +2273,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 ) { @@ -2045,7 +2315,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 @@ -2087,7 +2357,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); } } @@ -2154,6 +2424,14 @@ void wxFileName::SplitPath(const wxString& fullpath, } } +/* static */ +wxString wxFileName::StripExtension(const wxString& fullpath) +{ + wxFileName fn(fullpath); + fn.SetExt(""); + return fn.GetFullPath(); +} + // ---------------------------------------------------------------------------- // time functions // ---------------------------------------------------------------------------- @@ -2162,35 +2440,47 @@ void wxFileName::SplitPath(const wxString& fullpath, 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__)) @@ -2223,7 +2513,7 @@ bool wxFileName::SetTimes(const wxDateTime *dtAccess, return false; } -bool wxFileName::Touch() +bool wxFileName::Touch() const { #if defined(__UNIX_LIKE__) // under Unix touching file is simple: just pass NULL to utime() @@ -2266,7 +2556,7 @@ bool wxFileName::GetTimes(wxDateTime *dtAccess, } else // file { - wxFileHandle fh(GetFullPath(), wxFileHandle::Read); + wxFileHandle fh(GetFullPath(), wxFileHandle::ReadAttr); if ( fh.IsOk() ) { ok = ::GetFileTime(fh, @@ -2294,7 +2584,7 @@ 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 ( wxStat( GetFullPath(), &stBuf) == 0 ) { if ( dtAccess ) dtAccess->Set(stBuf.st_atime); @@ -2336,7 +2626,7 @@ wxULongLong wxFileName::GetSize(const wxString &filename) // TODO return wxInvalidSize; #elif defined(__WIN32__) - wxFileHandle f(filename, wxFileHandle::Read); + wxFileHandle f(filename, wxFileHandle::ReadAttr); if (!f.IsOk()) return wxInvalidSize; @@ -2348,11 +2638,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 @@ -2402,52 +2688,51 @@ wxString wxFileName::GetHumanReadableSize(const wxString &failmsg, int precision #if defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON -const short kMacExtensionMaxLength = 16 ; +namespace +{ + class MacDefaultExtensionRecord { -public : - MacDefaultExtensionRecord() - { - m_ext[0] = 0 ; - m_type = m_creator = 0 ; - } - 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 ; -} ; +public: + MacDefaultExtensionRecord() + { + m_type = + m_creator = 0 ; + } -WX_DECLARE_OBJARRAY(MacDefaultExtensionRecord, MacDefaultExtensionArray) ; + // default copy ctor, assignment operator and dtor are ok -bool gMacDefaultExtensionsInited = false ; + MacDefaultExtensionRecord(const wxString& ext, OSType type, OSType creator) + : m_ext(ext) + { + m_type = type; + m_creator = creator; + } + + wxString m_ext; + OSType m_type; + OSType m_creator; +}; + +WX_DECLARE_OBJARRAY(MacDefaultExtensionRecord, MacDefaultExtensionArray); + +bool gMacDefaultExtensionsInited = false; #include "wx/arrimpl.cpp" -WX_DEFINE_EXPORTED_OBJARRAY(MacDefaultExtensionArray) ; +WX_DEFINE_EXPORTED_OBJARRAY(MacDefaultExtensionArray); -MacDefaultExtensionArray gMacDefaultExtensions ; +MacDefaultExtensionArray gMacDefaultExtensions; // load the default extensions -MacDefaultExtensionRecord gDefaults[] = +const MacDefaultExtensionRecord gDefaults[] = { - MacDefaultExtensionRecord( wxT("txt") , 'TEXT' , 'ttxt' ) , - MacDefaultExtensionRecord( wxT("tif") , 'TIFF' , '****' ) , - MacDefaultExtensionRecord( wxT("jpg") , 'JPEG' , '****' ) , -} ; + MacDefaultExtensionRecord( "txt", 'TEXT', 'ttxt' ), + MacDefaultExtensionRecord( "tif", 'TIFF', '****' ), + MacDefaultExtensionRecord( "jpg", 'JPEG', '****' ), +}; -static void MacEnsureDefaultExtensionsLoaded() +void MacEnsureDefaultExtensionsLoaded() { if ( !gMacDefaultExtensionsInited ) { @@ -2456,10 +2741,12 @@ static void MacEnsureDefaultExtensionsLoaded() { gMacDefaultExtensions.Add( gDefaults[i] ) ; } - gMacDefaultExtensionsInited = true ; + gMacDefaultExtensionsInited = true; } } +} // anonymous namespace + bool wxFileName::MacSetTypeAndCreator( wxUint32 type , wxUint32 creator ) { FSRef fsRef ; @@ -2480,7 +2767,7 @@ bool wxFileName::MacSetTypeAndCreator( wxUint32 type , wxUint32 creator ) return false ; } -bool wxFileName::MacGetTypeAndCreator( wxUint32 *type , wxUint32 *creator ) +bool wxFileName::MacGetTypeAndCreator( wxUint32 *type , wxUint32 *creator ) const { FSRef fsRef ; FSCatalogInfo catInfo; @@ -2528,11 +2815,9 @@ bool wxFileName::MacFindDefaultTypeAndCreator( const wxString& ext , wxUint32 *t 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