Load widget resources from lumps

Add banner
This commit is contained in:
Magnus Norddahl 2023-12-28 18:39:04 +01:00 committed by Christoph Oelckers
commit 71ff4d3685
10 changed files with 667 additions and 63 deletions

View file

@ -1,62 +1,41 @@
#include <zwidget/core/resourcedata.h>
#include "filesystem.h"
#include "printf.h"
// To do: this should load data from lumps
FResourceFile* WidgetResources;
#ifdef WIN32
#include <Windows.h>
#include <stdexcept>
static std::wstring to_utf16(const std::string& str)
void InitWidgetResources(const char* filename)
{
if (str.empty()) return {};
int needed = MultiByteToWideChar(CP_UTF8, 0, str.data(), (int)str.size(), nullptr, 0);
if (needed == 0)
throw std::runtime_error("MultiByteToWideChar failed");
std::wstring result;
result.resize(needed);
needed = MultiByteToWideChar(CP_UTF8, 0, str.data(), (int)str.size(), &result[0], (int)result.size());
if (needed == 0)
throw std::runtime_error("MultiByteToWideChar failed");
return result;
WidgetResources = FResourceFile::OpenResourceFile(filename);
if (!WidgetResources)
I_FatalError("Unable to open %s", filename);
}
static std::vector<uint8_t> ReadAllBytes(const std::string& filename)
std::vector<uint8_t> LoadWidgetFontData(const std::string& name)
{
HANDLE handle = CreateFile(to_utf16(filename).c_str(), 0x0001/*FILE_READ_ACCESS*/, FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
if (handle == INVALID_HANDLE_VALUE)
throw std::runtime_error("Could not open " + filename);
LARGE_INTEGER fileSize;
BOOL result = GetFileSizeEx(handle, &fileSize);
if (result == FALSE)
{
CloseHandle(handle);
throw std::runtime_error("GetFileSizeEx failed");
}
std::vector<uint8_t> buffer(fileSize.QuadPart);
DWORD bytesRead = 0;
result = ReadFile(handle, buffer.data(), (DWORD)buffer.size(), &bytesRead, nullptr);
if (result == FALSE || bytesRead != buffer.size())
{
CloseHandle(handle);
throw std::runtime_error("ReadFile failed");
}
CloseHandle(handle);
auto lump = WidgetResources->FindLump("newmenufont.ttf");
if (!lump)
I_FatalError("Unable to find %s", name.c_str());
auto data = lump->Lock();
std::vector<uint8_t> buffer;
buffer.resize(lump->Size());
memcpy(buffer.data(), data, buffer.size());
lump->Unlock();
return buffer;
}
std::vector<uint8_t> LoadWidgetFontData(const std::string& name)
std::vector<uint8_t> LoadWidgetImageData(const std::string& name)
{
return ReadAllBytes("C:\\Windows\\Fonts\\segoeui.ttf");
}
auto lump = WidgetResources->FindLump(name.c_str());
if (!lump)
I_FatalError("Unable to find %s", name.c_str());
#else
std::vector<uint8_t> LoadWidgetFontData(const std::string& name)
{
return {};
auto data = lump->Lock();
std::vector<uint8_t> buffer;
buffer.resize(lump->Size());
memcpy(buffer.data(), data, buffer.size());
lump->Unlock();
return buffer;
}
#endif