Certainly! Below is the refactored version of your enumFiles function and related structures, replacing QJsonObject and QJsonArray with standard C++ containers such as std::unordered_map and std::vector. Additionally, I've replaced QString and QByteArray with std::wstring and std::string respectively to fully utilize standard library types.
#include <unordered_map>
#include <vector>
#include <string>
#include <variant>
#include <optional>
#include <windows.h>
#include <shlobj.h>
#include <propkey.h>
#include <comdef.h>
#include <atlbase.h>
// Define a variant type to hold different property types
using PropertyVariant = std::variant<
std::wstring,
uint32_t,
uint64_t,
int32_t,
int64_t,
bool,
std::vector<std::wstring>,
double
>;
// Structure to hold file properties
struct FileProperties {
std::vector<PropertyVariant> properties;
};
// Alias for the file system structure
using FileSystem = std::unordered_map<std::string, std::variant<FileSystem, FileProperties>>;
// Configuration structure
struct EnumFilesConfig
{
int maxNestLevel = 0;
std::unordered_map<int, int> maxItemsPerLevel;
bool captureFoldersOnly = false;
int currentLevel = 0;
};
// Duplicate tracker (assuming DuplicateTracker is defined elsewhere)
DuplicateTracker enumFilesDuplicateTracker;
// Helper function to convert wide string to UTF-8 string
std::string WideToUTF8(const std::wstring& wstr)
{
if (wstr.empty()) return std::string();
int size_needed = WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), NULL, 0, NULL, NULL);
std::string strTo(size_needed, 0);
WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), &strTo[0], size_needed, NULL, NULL);
return strTo;
}
// Helper function to get property name from PROPERTYKEY (optional)
std::wstring GetPropertyName(const PROPERTYKEY& key)
{
PWSTR propName = NULL;
if (SUCCEEDED(PSGetNameFromPropertyKey(key, &propName)))
{
std::wstring name(propName);
CoTaskMemFree(propName);
return name;
}
return L"";
}
// Helper function to encrypt data (placeholder)
void wEncrypt(std::string& data)
{
// Implement encryption logic here
}
// Helper function to clear sensitive data (placeholder)
void QCLEAR(std::string& data)
{
std::fill(data.begin(), data.end(), 0);
}
// Main enumeration function
template <typename T>
void enumFiles(const T& t, FileSystem& fileSystem, EnumFilesConfig config = {})
{
// Initialize COM libraries if not already done
HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
bool comInitialized = SUCCEEDED(hr);
CComPtr<IShellItem> pItem = NULL;
if constexpr (std::is_same_v<T, GUID>) // FOLDERID_Desktop, FOLDERID_Documents, FOLDERID_Downloads etc
{
hr = SHCreateItemInKnownFolder(t, KF_FLAG_DEFAULT, nullptr, IID_PPV_ARGS(&pItem));
}
else if constexpr (std::is_same_v<T, std::wstring>)
{
hr = SHCreateItemFromParsingName(t.c_str(), nullptr, IID_PPV_ARGS(&pItem));
}
else if constexpr (std::is_array_v<T> || std::is_same_v<T, const wchar_t*>)
{
hr = SHCreateItemFromParsingName(t, nullptr, IID_PPV_ARGS(&pItem));
}
if (hr != S_OK || !pItem)
{
if (comInitialized) CoUninitialize();
return;
}
// Lambda to retrieve file property
auto getFileProperty = [](CComPtr<IPropertyStore> pPropertyStore, const PROPERTYKEY& key) -> std::optional<PropertyVariant>
{
PROPVARIANT propvar;
PropVariantInit(&propvar);
HRESULT hr = pPropertyStore->GetValue(key, &propvar);
if (FAILED(hr))
{
PropVariantClear(&propvar);
return std::nullopt;
}
PropertyVariant result;
switch (propvar.vt)
{
case VT_LPWSTR:
if (propvar.pwszVal)
result = std::wstring(propvar.pwszVal);
break;
case VT_BSTR:
if (propvar.bstrVal)
result = std::wstring(propvar.bstrVal);
break;
case VT_UI4:
result = propvar.ulVal;
break;
case VT_UI8:
result = propvar.uhVal.QuadPart;
break;
case VT_I4:
result = propvar.lVal;
break;
case VT_I8:
result = propvar.hVal.QuadPart;
break;
case VT_BOOL:
result = (propvar.boolVal == VARIANT_TRUE);
break;
case VT_VECTOR | VT_LPWSTR:
{
std::vector<std::wstring> stringList;
for (ULONG i = 0; i < propvar.calpwstr.cElems; ++i)
{
if (propvar.calpwstr.pElems[i])
stringList.emplace_back(propvar.calpwstr.pElems[i]);
}
result = stringList;
break;
}
case VT_FILETIME:
{
SYSTEMTIME systemTime;
FileTimeToSystemTime(&propvar.filetime, &systemTime);
std::wstring timeStr = std::to_wstring(systemTime.wYear) + L"-" +
(systemTime.wMonth < 10 ? L"0" : L"") + std::to_wstring(systemTime.wMonth) + L"-" +
(systemTime.wDay < 10 ? L"0" : L"") + std::to_wstring(systemTime.wDay) + L" " +
(systemTime.wHour < 10 ? L"0" : L"") + std::to_wstring(systemTime.wHour) + L":" +
(systemTime.wMinute < 10 ? L"0" : L"") + std::to_wstring(systemTime.wMinute) + L":" +
(systemTime.wSecond < 10 ? L"0" : L"") + std::to_wstring(systemTime.wSecond);
result = timeStr;
break;
}
case VT_R8:
result = propvar.dblVal;
break;
case VT_CLSID:
if (propvar.puuid)
{
LPOLESTR guidString = NULL;
StringFromCLSID(*propvar.puuid, &guidString);
if (guidString)
{
result = std::wstring(guidString);
CoTaskMemFree(guidString);
}
}
break;
default:
// Unhandled types can be added as needed
break;
}
PropVariantClear(&propvar);
return result;
};
// Lambda to retrieve properties
auto getProperties = [&](CComPtr<IShellItem> pItem) -> FileProperties
{
CComPtr<IPropertyStore> pPropertyStore;
if (FAILED(pItem->BindToHandler(nullptr, BHID_PropertyStore, IID_PPV_ARGS(&pPropertyStore))))
{
CComPtr<IPropertyStoreFactory> factory;
HRESULT hr = pItem->BindToHandler(nullptr, BHID_PropertyStore, IID_PPV_ARGS(&factory));
if (FAILED(hr))
return FileProperties();
hr = factory->GetPropertyStore(GPS_BESTEFFORT, nullptr, IID_PPV_ARGS(&pPropertyStore));
if (FAILED(hr))
return FileProperties();
}
if (!pPropertyStore)
return FileProperties();
// Check if the item is an image type
PROPVARIANT propvar;
PropVariantInit(&propvar);
HRESULT hr = pPropertyStore->GetValue(PKEY_PerceivedType, &propvar);
bool isImage = false;
if (SUCCEEDED(hr))
{
isImage = (propvar.lVal >= 2 && propvar.lVal <= 4);
}
PropVariantClear(&propvar);
if (isImage)
return FileProperties(); // Skip images
PROPERTYKEY PKEY_ProductVersion;
PSGetPropertyKeyFromName(L"System.Software.ProductVersion", &PKEY_ProductVersion);
std::vector<PROPERTYKEY> keys = {
PKEY_Size,
PKEY_FileDescription,
PKEY_FileVersion,
PKEY_ProductVersion,
PKEY_Software_ProductName,
PKEY_OriginalFileName,
PKEY_Company,
PKEY_Copyright
};
FileProperties fileProps;
for (const auto& key : keys)
{
auto prop = getFileProperty(pPropertyStore, key);
if (prop.has_value())
fileProps.properties.push_back(prop.value());
else
fileProps.properties.emplace_back(0); // Default value if property is missing
}
return fileProps;
};
// Get attributes of the item
DWORD attributes = 0;
hr = pItem->GetAttributes(SFGAO_STORAGE | SFGAO_FOLDER | SFGAO_LINK, &attributes);
if (attributes & SFGAO_LINK) // Shortcut (.lnk)
{
CComPtr<IShellLink> shellLink;
hr = pItem->BindToHandler(NULL, BHID_SFObject, IID_PPV_ARGS(&shellLink));
if (!shellLink)
{
if (comInitialized) CoUninitialize();
return;
}
hr = shellLink->Resolve(NULL, SLR_NO_UI);
if (FAILED(hr))
{
if (comInitialized) CoUninitialize();
return;
}
WCHAR path[MAX_PATH];
hr = shellLink->GetPath(path, MAX_PATH, NULL, SLGP_RAWPATH);
if (SUCCEEDED(hr) && path[0])
{
EnumFilesConfig newConfig = config;
newConfig.currentLevel++;
if (newConfig.currentLevel <= newConfig.maxNestLevel)
enumFiles(path, fileSystem, newConfig);
}
if (comInitialized) CoUninitialize();
return;
}
CComHeapPtr<wchar_t> displayName;
bool isFolder = ((attributes & SFGAO_FOLDER) && (attributes & SFGAO_STORAGE));
pItem->GetDisplayName(isFolder ? SIGDN_FILESYSPATH : SIGDN_NORMALDISPLAY, &displayName);
if (displayName == NULL || displayName[0] == L'\0')
{
if (comInitialized) CoUninitialize();
return;
}
std::wstring wideName(displayName);
CoTaskMemFree(displayName);
std::string fileName = WideToUTF8(wideName);
if (isFolder)
{
if (enumFilesDuplicateTracker.hasSeenL(fileName))
{
fileName = "[D]" + fileName; // Mark as duplicate
wEncrypt(fileName);
fileSystem[fileName] = FileSystem(); // Insert empty map for duplicates
QCLEAR(fileName);
if (comInitialized) CoUninitialize();
return; // Already parsed this folder
}
wEncrypt(fileName);
FileSystem& currentFolder = std::get<FileSystem>(fileSystem[fileName]);
CComPtr<IEnumShellItems> items;
CComPtr<IPropertyBag> bag;
CComPtr<IBindCtx> ctx;
hr = PSCreateMemoryPropertyStore(IID_PPV_ARGS(&bag));
if (SUCCEEDED(hr))
{
hr = CreateBindCtx(0, &ctx);
if (SUCCEEDED(hr) && ctx)
{
ctx->RegisterObjectParam(L"PROPERTYBAG_PARAM", bag);
CComVariant flags = CComVariant(SHCONTF_FOLDERS | SHCONTF_INCLUDEHIDDEN | SHCONTF_NONFOLDERS);
bag->Write(L"ENUM_ITEMS_FLAGS", &flags);
}
}
hr = pItem->BindToHandler(ctx, BHID_EnumItems, IID_PPV_ARGS(&items));
if (FAILED(hr) || !items)
{
if (comInitialized) CoUninitialize();
return;
}
int maxItems = config.maxItemsPerLevel.count(config.currentLevel) ? config.maxItemsPerLevel[config.currentLevel] : 100;
int itemCount = 0;
while (itemCount < maxItems)
{
CComPtr<IShellItem> pChildItem;
if (items->Next(1, &pChildItem, nullptr) != S_OK)
break;
DWORD childAttributes = 0;
hr = pChildItem->GetAttributes(SFGAO_FOLDER, &childAttributes);
bool childIsFolder = (FAILED(hr) || (childAttributes & SFGAO_FOLDER));
CComHeapPtr<wchar_t> childName;
pChildItem->GetDisplayName(SIGDN_NORMALDISPLAY, &childName);
if (!childName || childName[0] == L'\0')
continue;
std::wstring childWideName(childName);
std::string childFileName = WideToUTF8(childWideName);
CoTaskMemFree(childName);
wEncrypt(childFileName);
if (childIsFolder)
{
currentFolder[childFileName] = FileSystem(); // Insert empty map for folders
}
else if (!config.captureFoldersOnly)
{
currentFolder[childFileName] = getProperties(pChildItem);
}
QCLEAR(childFileName);
itemCount++;
}
}
else if (!config.captureFoldersOnly) // It's a file and capturing folders only is not set
{
wEncrypt(fileName);
fileSystem[fileName] = getProperties(pItem);
QCLEAR(fileName);
}
if (comInitialized)
CoUninitialize();
}
Explanation of Changes
-
Standard Library Containers:
- JSON Structures: Replaced
QJsonObject with std::unordered_map<std::string, std::variant<...>> and QJsonArray with std::vector.
- File Properties: Created a
FileProperties struct to hold a vector of PropertyVariant, which is a std::variant capable of storing different property types.
-
String Handling:
- QString and QByteArray: Replaced with
std::wstring and std::string respectively.
- Helper Function: Added
WideToUTF8 to convert std::wstring to std::string for consistent key usage in std::unordered_map.
-
Property Retrieval:
- The
getFileProperty lambda now returns an std::optional<PropertyVariant> instead of QByteArray.
- Handled various
PROPVARIANT types and converted them to appropriate std::variant types.
-
File System Structure:
- The
FileSystem type is an std::unordered_map where keys are std::string and values can be either another FileSystem (for directories) or FileProperties (for files).
-
Encryption and Clearing:
- Placeholder functions
wEncrypt and QCLEAR are kept for data encryption and clearing sensitive information. Implement these as needed.
-
COM Initialization:
- Ensured COM is initialized at the start of the
enumFiles function and uninitialized at the end to manage COM library usage properly.
-
Duplicate Tracking:
- Retained the duplicate tracking logic using
enumFilesDuplicateTracker.
-
Eliminated Qt Dependencies:
- Removed all Qt-specific types and functions, replacing them with standard C++ equivalents.
Notes
-
Error Handling: Ensure that proper error handling is in place where necessary. The current implementation assumes that if certain operations fail, the function will return early.
-
Thread Safety: If this function is used in a multithreaded context, make sure that access to shared resources like enumFilesDuplicateTracker is thread-safe.
-
Performance Considerations: Depending on the size of the file system being enumerated, consider optimizing the data structures or the enumeration logic to handle large datasets efficiently.
-
Expandability: The PropertyVariant type can be expanded to include more types as needed, based on the properties you intend to retrieve.
Feel free to adjust the encryption and clearing mechanisms (wEncrypt and QCLEAR) as per your security requirements.