UI: FileUtil: Simplify realPath()

This commit is contained in:
Nodir Temirkhodjaev 2024-05-10 11:09:06 +03:00
parent ed758b7612
commit 6cbc10900f

View File

@ -264,25 +264,28 @@ inline bool isDevicePath(LPCWSTR path)
return path[0] == L'\\' && path[1] == L'\\' && path[2] == L'?' && path[3] == L'\\';
}
inline void realPathByHandle(HANDLE fileHandle, QString &path)
inline QString realPathByHandle(HANDLE fileHandle)
{
DWORD pathLen = GetFinalPathNameByHandleW(fileHandle, nullptr, 0, FILE_NAME_NORMALIZED);
if (pathLen == 0)
return;
return {};
// pathLen includes the null terminator
QVarLengthArray<BYTE, 4096> pathBuf(pathLen * sizeof(wchar_t));
LPWSTR pathData = (LPWSTR) pathBuf.data();
if (!GetFinalPathNameByHandleW(fileHandle, pathData, pathLen, FILE_NAME_NORMALIZED))
return;
pathLen = GetFinalPathNameByHandleW(fileHandle, pathData, pathLen, FILE_NAME_NORMALIZED);
if (pathLen == 0)
return {};
if (isDevicePath(pathData)) {
// pathLen does not include the null terminator
constexpr int prefixLen = 4;
if (pathLen > prefixLen && isDevicePath(pathData)) {
pathData += prefixLen;
pathLen -= prefixLen;
}
path = QString::fromWCharArray(pathData, pathLen - 1);
return QString::fromWCharArray(pathData, pathLen);
}
QString realPath(const QString &path)
@ -290,22 +293,17 @@ QString realPath(const QString &path)
if (path.isEmpty())
return path;
const QFileInfo fi(path);
if (!fi.exists() || fi.isSymbolicLink() || fi.isJunction())
return path;
QString resPath = path;
const HANDLE fileHandle = CreateFileW((LPCWSTR) resPath.utf16(), GENERIC_READ, FILE_SHARE_READ,
const HANDLE fileHandle = CreateFileW((LPCWSTR) path.utf16(), GENERIC_READ, FILE_SHARE_READ,
nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS /* open dir */, nullptr);
QString resPath;
if (fileHandle != INVALID_HANDLE_VALUE) {
realPathByHandle(fileHandle, resPath);
resPath = realPathByHandle(fileHandle);
CloseHandle(fileHandle);
}
return resPath;
return resPath.compare(path, Qt::CaseInsensitive) == 0 ? resPath : path;
}
bool removePath(const QString &path)