impr: Code style improvements

This commit is contained in:
WerWolv
2023-12-27 16:33:49 +01:00
parent ec45d1f564
commit 74b5c93caf
64 changed files with 267 additions and 277 deletions

View File

@@ -1,6 +1,6 @@
html, body { html, body {
height: 100%; height: 100%;
margin: 0px; margin: 0;
user-select: none; user-select: none;
} }
@@ -16,16 +16,7 @@ body {
margin-left: auto; margin-left: auto;
margin-right: auto; margin-right: auto;
display: none; display: none;
border: 0px none; border: 0 none;
}
.canvas_full_screen {
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
image-rendering: pixelated;
} }
h1, h2, h5 { h1, h2, h5 {
@@ -44,7 +35,7 @@ h2 {
} }
h5 { h5 {
margin-top: 0px; margin-top: 0;
font-size: 17px; font-size: 17px;
} }
@@ -63,7 +54,7 @@ a {
} }
a:hover { a:hover {
text-shadow: #3a4677 0px 0px 10px; text-shadow: #3a4677 0 0 10px;
} }
.footer { .footer {
@@ -135,8 +126,8 @@ a:hover {
opacity: 1; opacity: 1;
} }
100% { 100% {
top: 0px; top: 0;
left: 0px; left: 0;
width: 72px; width: 72px;
height: 72px; height: 72px;
opacity: 0; opacity: 0;

View File

@@ -42,7 +42,7 @@ namespace hex {
class Plugin { class Plugin {
public: public:
explicit Plugin(const std::fs::path &path); explicit Plugin(const std::fs::path &path);
explicit Plugin(PluginFunctions functions); explicit Plugin(const PluginFunctions &functions);
Plugin(const Plugin &) = delete; Plugin(const Plugin &) = delete;
Plugin(Plugin &&other) noexcept; Plugin(Plugin &&other) noexcept;

View File

@@ -448,7 +448,7 @@ namespace hex {
[[nodiscard]] static std::optional<Shortcut> getPreviousShortcut(); [[nodiscard]] static std::optional<Shortcut> getPreviousShortcut();
[[nodiscard]] static std::vector<ShortcutEntry> getGlobalShortcuts(); [[nodiscard]] static std::vector<ShortcutEntry> getGlobalShortcuts();
[[nodiscard]] static std::vector<ShortcutEntry> getViewShortcuts(View *view); [[nodiscard]] static std::vector<ShortcutEntry> getViewShortcuts(const View *view);
[[nodiscard]] static bool updateShortcut(const Shortcut &oldShortcut, const Shortcut &newShortcut, View *view = nullptr); [[nodiscard]] static bool updateShortcut(const Shortcut &oldShortcut, const Shortcut &newShortcut, View *view = nullptr);
}; };

View File

@@ -606,9 +606,9 @@ namespace hex {
std::string getImHexVersion(bool withBuildType) { std::string getImHexVersion(bool withBuildType) {
#if defined IMHEX_VERSION #if defined IMHEX_VERSION
if (withBuildType) if (withBuildType) {
return IMHEX_VERSION; return IMHEX_VERSION;
else { } else {
auto version = std::string(IMHEX_VERSION); auto version = std::string(IMHEX_VERSION);
return version.substr(0, version.find('-')); return version.substr(0, version.find('-'));
} }

View File

@@ -46,7 +46,7 @@ namespace hex {
m_functions.getSubCommandsFunction = getPluginFunction<PluginFunctions::GetSubCommandsFunc>("getSubCommands"); m_functions.getSubCommandsFunction = getPluginFunction<PluginFunctions::GetSubCommandsFunc>("getSubCommands");
} }
Plugin::Plugin(hex::PluginFunctions functions) { Plugin::Plugin(const hex::PluginFunctions &functions) {
m_handle = 0; m_handle = 0;
m_functions = functions; m_functions = functions;
} }
@@ -125,9 +125,9 @@ namespace hex {
} }
std::string Plugin::getPluginName() const { std::string Plugin::getPluginName() const {
if (m_functions.getPluginNameFunction != nullptr) if (m_functions.getPluginNameFunction != nullptr) {
return m_functions.getPluginNameFunction(); return m_functions.getPluginNameFunction();
else { } else {
if (this->isLibraryPlugin()) if (this->isLibraryPlugin())
return "Library Plugin"; return "Library Plugin";
else else
@@ -185,8 +185,9 @@ namespace hex {
if (m_functions.getSubCommandsFunction != nullptr) { if (m_functions.getSubCommandsFunction != nullptr) {
auto result = m_functions.getSubCommandsFunction(); auto result = m_functions.getSubCommandsFunction();
return *static_cast<std::vector<SubCommand>*>(result); return *static_cast<std::vector<SubCommand>*>(result);
} else } else {
return { }; return { };
}
} }
bool Plugin::isLibraryPlugin() const { bool Plugin::isLibraryPlugin() const {

View File

@@ -98,7 +98,7 @@ namespace hex {
return result; return result;
} }
std::vector<ShortcutManager::ShortcutEntry> ShortcutManager::getViewShortcuts(View *view) { std::vector<ShortcutManager::ShortcutEntry> ShortcutManager::getViewShortcuts(const View *view) {
std::vector<ShortcutManager::ShortcutEntry> result; std::vector<ShortcutManager::ShortcutEntry> result;
for (auto &[shortcut, entry] : view->m_shortcuts) for (auto &[shortcut, entry] : view->m_shortcuts)

View File

@@ -90,9 +90,9 @@ namespace hex {
theme["styles"][type] = {}; theme["styles"][type] = {};
for (const auto &[key, style] : handler.styleMap) { for (const auto &[key, style] : handler.styleMap) {
if (std::holds_alternative<float*>(style.value)) if (std::holds_alternative<float*>(style.value)) {
theme["styles"][type][key] = *std::get<float*>(style.value); theme["styles"][type][key] = *std::get<float*>(style.value);
else if (std::holds_alternative<ImVec2*>(style.value)) { } else if (std::holds_alternative<ImVec2*>(style.value)) {
theme["styles"][type][key] = { theme["styles"][type][key] = {
std::get<ImVec2*>(style.value)->x, std::get<ImVec2*>(style.value)->x,
std::get<ImVec2*>(style.value)->y std::get<ImVec2*>(style.value)->y

View File

@@ -85,8 +85,8 @@ namespace hex {
s_proxyUrl = std::move(proxy); s_proxyUrl = std::move(proxy);
} }
void HttpRequest::setProxyState(bool state) { void HttpRequest::setProxyState(bool enabled) {
s_proxyState = state; s_proxyState = enabled;
} }
void HttpRequest::checkProxyErrors() { void HttpRequest::checkProxyErrors() {

View File

@@ -635,13 +635,13 @@ namespace hex::gl {
} }
} }
void LightSourceVectors::moveTo(const Vector<float, 3> &positionVector) { void LightSourceVectors::moveTo(const Vector<float, 3> &position) {
auto vertexCount = m_vertices.size(); auto vertexCount = m_vertices.size();
for (unsigned k = 0; k < vertexCount; k += 3) { for (unsigned k = 0; k < vertexCount; k += 3) {
m_vertices[k ] = m_radius * m_normals[k ] + positionVector[0]; m_vertices[k ] = m_radius * m_normals[k ] + position[0];
m_vertices[k + 1] = m_radius * m_normals[k + 1] + positionVector[1]; m_vertices[k + 1] = m_radius * m_normals[k + 1] + position[1];
m_vertices[k + 2] = m_radius * m_normals[k + 2] + positionVector[2]; m_vertices[k + 2] = m_radius * m_normals[k + 2] + position[2];
} }
} }

View File

@@ -67,8 +67,9 @@ namespace hex {
if (value < 0) { if (value < 0) {
data[index] = '-'; data[index] = '-';
return { data + index }; return { data + index };
} else } else {
return { data + index + 1 }; return { data + index + 1 };
}
} }
std::string toLower(std::string string) { std::string toLower(std::string string) {
@@ -376,9 +377,9 @@ namespace hex {
std::string result; std::string result;
for (u8 byte : bytes) { for (u8 byte : bytes) {
if (std::isprint(byte) && byte != '\\') if (std::isprint(byte) && byte != '\\') {
result += char(byte); result += char(byte);
else { } else {
switch (byte) { switch (byte) {
case '\\': case '\\':
result += "\\"; result += "\\";
@@ -538,9 +539,9 @@ namespace hex {
std::wstring utf16; std::wstring utf16;
for (auto unicode : unicodes) { for (auto unicode : unicodes) {
if (unicode <= 0xFFFF) if (unicode <= 0xFFFF) {
utf16 += static_cast<wchar_t>(unicode); utf16 += static_cast<wchar_t>(unicode);
else { } else {
unicode -= 0x10000; unicode -= 0x10000;
utf16 += static_cast<wchar_t>(((unicode >> 10) + 0xD800)); utf16 += static_cast<wchar_t>(((unicode >> 10) + 0xD800));
utf16 += static_cast<wchar_t>(((unicode & 0x3FF) + 0xDC00)); utf16 += static_cast<wchar_t>(((unicode & 0x3FF) + 0xDC00));

View File

@@ -2,7 +2,6 @@
#include <imgui.h> #include <imgui.h>
#include <functional>
#include <string> #include <string>
namespace hex { namespace hex {

View File

@@ -8,7 +8,6 @@
#include <hex/helpers/fs.hpp> #include <hex/helpers/fs.hpp>
#include <hex/helpers/stacktrace.hpp> #include <hex/helpers/stacktrace.hpp>
#include <wolv/io/fs.hpp>
#include <wolv/utils/string.hpp> #include <wolv/utils/string.hpp>
#include <window.hpp> #include <window.hpp>

View File

@@ -95,9 +95,9 @@ namespace hex::init {
}(); }();
for (const auto &colorConfig : highlightConfig) { for (const auto &colorConfig : highlightConfig) {
if (!colorConfig.contains("time")) if (!colorConfig.contains("time")) {
selectedConfigs.push_back(colorConfig); selectedConfigs.push_back(colorConfig);
else { } else {
const auto &time = colorConfig["time"]; const auto &time = colorConfig["time"];
const auto &start = time["start"]; const auto &start = time["start"];
const auto &end = time["end"]; const auto &end = time["end"];

View File

@@ -29,9 +29,9 @@ namespace hex {
template<typename T> template<typename T>
using WinUniquePtr = std::unique_ptr<std::remove_pointer_t<T>, BOOL(*)(T)>; using WinUniquePtr = std::unique_ptr<std::remove_pointer_t<T>, BOOL(*)(T)>;
static LONG_PTR g_oldWndProc; static LONG_PTR s_oldWndProc;
static float g_titleBarHeight; static float s_titleBarHeight;
static Microsoft::WRL::ComPtr<ITaskbarList4> g_taskbarList; static Microsoft::WRL::ComPtr<ITaskbarList4> s_taskbarList;
void nativeErrorMessage(const std::string &message) { void nativeErrorMessage(const std::string &message) {
log::fatal(message); log::fatal(message);
@@ -83,7 +83,7 @@ namespace hex {
} }
case WM_SETCURSOR: { case WM_SETCURSOR: {
if (LOWORD(lParam) != HTCLIENT) { if (LOWORD(lParam) != HTCLIENT) {
return CallWindowProc((WNDPROC)g_oldWndProc, hwnd, uMsg, wParam, lParam); return CallWindowProc((WNDPROC)s_oldWndProc, hwnd, uMsg, wParam, lParam);
} else { } else {
switch (ImGui::GetMouseCursor()) { switch (ImGui::GetMouseCursor()) {
case ImGuiMouseCursor_Arrow: case ImGuiMouseCursor_Arrow:
@@ -122,7 +122,7 @@ namespace hex {
break; break;
} }
return CallWindowProc((WNDPROC)g_oldWndProc, hwnd, uMsg, wParam, lParam); return CallWindowProc((WNDPROC)s_oldWndProc, hwnd, uMsg, wParam, lParam);
} }
// Custom window procedure for borderless window // Custom window procedure for borderless window
@@ -140,7 +140,7 @@ namespace hex {
RECT &rect = *reinterpret_cast<RECT *>(lParam); RECT &rect = *reinterpret_cast<RECT *>(lParam);
RECT client = rect; RECT client = rect;
CallWindowProc((WNDPROC)g_oldWndProc, hwnd, uMsg, wParam, lParam); CallWindowProc((WNDPROC)s_oldWndProc, hwnd, uMsg, wParam, lParam);
if (IsMaximized(hwnd)) { if (IsMaximized(hwnd)) {
WINDOWINFO windowInfo = { }; WINDOWINFO windowInfo = { };
@@ -211,7 +211,7 @@ namespace hex {
return HTBOTTOMRIGHT; return HTBOTTOMRIGHT;
case RegionClient: case RegionClient:
default: default:
if (cursor.y < (window.top + g_titleBarHeight * 2)) { if (cursor.y < (window.top + s_titleBarHeight * 2)) {
if (hoveredWindowName == "##MainMenuBar" || hoveredWindowName == "ImHexDockSpace") { if (hoveredWindowName == "##MainMenuBar" || hoveredWindowName == "ImHexDockSpace") {
if (!ImGui::IsAnyItemHovered()) { if (!ImGui::IsAnyItemHovered()) {
return HTCAPTION; return HTCAPTION;
@@ -302,7 +302,7 @@ namespace hex {
// Set up the correct window procedure based on the borderless window mode state // Set up the correct window procedure based on the borderless window mode state
if (borderlessWindowMode) { if (borderlessWindowMode) {
g_oldWndProc = ::SetWindowLongPtr(hwnd, GWLP_WNDPROC, (LONG_PTR)borderlessWindowProc); s_oldWndProc = ::SetWindowLongPtr(hwnd, GWLP_WNDPROC, (LONG_PTR)borderlessWindowProc);
MARGINS borderless = { 1, 1, 1, 1 }; MARGINS borderless = { 1, 1, 1, 1 };
::DwmExtendFrameIntoClientArea(hwnd, &borderless); ::DwmExtendFrameIntoClientArea(hwnd, &borderless);
@@ -313,41 +313,41 @@ namespace hex {
::SetWindowPos(hwnd, nullptr, 0, 0, 0, 0, SWP_NOZORDER | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSIZE | SWP_NOMOVE); ::SetWindowPos(hwnd, nullptr, 0, 0, 0, 0, SWP_NOZORDER | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSIZE | SWP_NOMOVE);
::SetWindowLong(hwnd, GWL_STYLE, GetWindowLong(hwnd, GWL_STYLE) | WS_OVERLAPPEDWINDOW); ::SetWindowLong(hwnd, GWL_STYLE, GetWindowLong(hwnd, GWL_STYLE) | WS_OVERLAPPEDWINDOW);
} else { } else {
g_oldWndProc = ::SetWindowLongPtr(hwnd, GWLP_WNDPROC, (LONG_PTR)commonWindowProc); s_oldWndProc = ::SetWindowLongPtr(hwnd, GWLP_WNDPROC, (LONG_PTR)commonWindowProc);
} }
// Set up a taskbar progress handler // Set up a taskbar progress handler
{ {
if (SUCCEEDED(CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED))) { if (SUCCEEDED(CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED))) {
CoCreateInstance(CLSID_TaskbarList, nullptr, CLSCTX_INPROC_SERVER, IID_ITaskbarList4, &g_taskbarList); CoCreateInstance(CLSID_TaskbarList, nullptr, CLSCTX_INPROC_SERVER, IID_ITaskbarList4, &s_taskbarList);
} }
EventSetTaskBarIconState::subscribe([hwnd](u32 state, u32 type, u32 progress){ EventSetTaskBarIconState::subscribe([hwnd](u32 state, u32 type, u32 progress){
using enum ImHexApi::System::TaskProgressState; using enum ImHexApi::System::TaskProgressState;
switch (ImHexApi::System::TaskProgressState(state)) { switch (ImHexApi::System::TaskProgressState(state)) {
case Reset: case Reset:
g_taskbarList->SetProgressState(hwnd, TBPF_NOPROGRESS); s_taskbarList->SetProgressState(hwnd, TBPF_NOPROGRESS);
g_taskbarList->SetProgressValue(hwnd, 0, 0); s_taskbarList->SetProgressValue(hwnd, 0, 0);
break; break;
case Flash: case Flash:
FlashWindow(hwnd, true); FlashWindow(hwnd, true);
break; break;
case Progress: case Progress:
g_taskbarList->SetProgressState(hwnd, TBPF_INDETERMINATE); s_taskbarList->SetProgressState(hwnd, TBPF_INDETERMINATE);
g_taskbarList->SetProgressValue(hwnd, progress, 100); s_taskbarList->SetProgressValue(hwnd, progress, 100);
break; break;
} }
using enum ImHexApi::System::TaskProgressType; using enum ImHexApi::System::TaskProgressType;
switch (ImHexApi::System::TaskProgressType(type)) { switch (ImHexApi::System::TaskProgressType(type)) {
case Normal: case Normal:
g_taskbarList->SetProgressState(hwnd, TBPF_NORMAL); s_taskbarList->SetProgressState(hwnd, TBPF_NORMAL);
break; break;
case Warning: case Warning:
g_taskbarList->SetProgressState(hwnd, TBPF_PAUSED); s_taskbarList->SetProgressState(hwnd, TBPF_PAUSED);
break; break;
case Error: case Error:
g_taskbarList->SetProgressState(hwnd, TBPF_ERROR); s_taskbarList->SetProgressState(hwnd, TBPF_ERROR);
break; break;
} }
}); });
@@ -388,7 +388,7 @@ namespace hex {
} }
void Window::beginNativeWindowFrame() { void Window::beginNativeWindowFrame() {
g_titleBarHeight = ImGui::GetCurrentWindowRead()->MenuBarHeight(); s_titleBarHeight = ImGui::GetCurrentWindowRead()->MenuBarHeight();
} }
void Window::endNativeWindowFrame() { void Window::endNativeWindowFrame() {

View File

@@ -372,9 +372,9 @@ namespace hex {
ImGui::PopStyleVar(); ImGui::PopStyleVar();
bool shouldDrawSidebar = [] { bool shouldDrawSidebar = [] {
if (const auto &items = ContentRegistry::Interface::impl::getSidebarItems(); items.empty()) if (const auto &items = ContentRegistry::Interface::impl::getSidebarItems(); items.empty()) {
return false; return false;
else { } else {
return std::any_of(items.begin(), items.end(), [](const auto &item) { return std::any_of(items.begin(), items.end(), [](const auto &item) {
return item.enabledCallback(); return item.enabledCallback();
}); });
@@ -894,12 +894,12 @@ namespace hex {
for (const auto viewPort : ImGui::GetPlatformIO().Viewports) { for (const auto viewPort : ImGui::GetPlatformIO().Viewports) {
auto drawData = viewPort->DrawData; auto drawData = viewPort->DrawData;
for (int n = 0; n < drawData->CmdListsCount; n++) { for (int n = 0; n < drawData->CmdListsCount; n++) {
const ImDrawList *cmd_list = drawData->CmdLists[n]; const ImDrawList *cmdList = drawData->CmdLists[n];
drawDataHash = ImHashData(cmd_list->VtxBuffer.Data, cmd_list->VtxBuffer.Size * sizeof(ImDrawVert), drawDataHash); drawDataHash = ImHashData(cmdList->VtxBuffer.Data, cmdList->VtxBuffer.Size * sizeof(ImDrawVert), drawDataHash);
} }
for (int n = 0; n < drawData->CmdListsCount; n++) { for (int n = 0; n < drawData->CmdListsCount; n++) {
const ImDrawList *cmd_list = drawData->CmdLists[n]; const ImDrawList *cmdList = drawData->CmdLists[n];
drawDataHash = ImHashData(cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx), drawDataHash); drawDataHash = ImHashData(cmdList->IdxBuffer.Data, cmdList->IdxBuffer.Size * sizeof(ImDrawIdx), drawDataHash);
} }
} }
@@ -1202,7 +1202,7 @@ namespace hex {
handler.ReadOpenFn = [](ImGuiContext *ctx, ImGuiSettingsHandler *, const char *) -> void* { return ctx; }; handler.ReadOpenFn = [](ImGuiContext *ctx, ImGuiSettingsHandler *, const char *) -> void* { return ctx; };
handler.ReadLineFn = [](ImGuiContext *, ImGuiSettingsHandler *handler, void *, const char *line) { handler.ReadLineFn = [](ImGuiContext *, ImGuiSettingsHandler *handler, void *, const char *line) {
Window* window = static_cast<Window*>(handler->UserData); auto window = static_cast<Window*>(handler->UserData);
for (auto &[name, view] : ContentRegistry::Views::impl::getEntries()) { for (auto &[name, view] : ContentRegistry::Views::impl::getEntries()) {
std::string format = view->getUnlocalizedName().get() + "=%d"; std::string format = view->getUnlocalizedName().get() + "=%d";

View File

@@ -59,16 +59,6 @@ namespace hex::plugin::builtin {
[[nodiscard]] ImVec2 getMaxSize() const override { return scaled({ 900, 700 }); } [[nodiscard]] ImVec2 getMaxSize() const override { return scaled({ 900, 700 }); }
private: private:
HttpRequest m_httpRequest = HttpRequest("GET", "");
std::future<HttpRequest::Result<std::string>> m_apiRequest;
std::future<HttpRequest::Result<std::string>> m_download;
std::fs::path m_downloadPath;
RequestStatus m_requestStatus = RequestStatus::NotAttempted;
std::vector<StoreCategory> m_categories;
TaskHolder m_updateAllTask;
std::atomic<u32> m_updateCount = 0;
void drawStore(); void drawStore();
void drawTab(StoreCategory &category); void drawTab(StoreCategory &category);
void handleDownloadFinished(const StoreCategory &category, StoreEntry &entry); void handleDownloadFinished(const StoreCategory &category, StoreEntry &entry);
@@ -80,6 +70,17 @@ namespace hex::plugin::builtin {
bool download(fs::ImHexPath pathType, const std::string &fileName, const std::string &url, bool update); bool download(fs::ImHexPath pathType, const std::string &fileName, const std::string &url, bool update);
bool remove(fs::ImHexPath pathType, const std::string &fileName); bool remove(fs::ImHexPath pathType, const std::string &fileName);
private:
HttpRequest m_httpRequest = HttpRequest("GET", "");
std::future<HttpRequest::Result<std::string>> m_apiRequest;
std::future<HttpRequest::Result<std::string>> m_download;
std::fs::path m_downloadPath;
RequestStatus m_requestStatus = RequestStatus::NotAttempted;
std::vector<StoreCategory> m_categories;
TaskHolder m_updateAllTask;
std::atomic<u32> m_updateCount = 0;
}; };
} }

View File

@@ -220,7 +220,7 @@ namespace hex::plugin::builtin {
ProjectFile::registerHandler({ ProjectFile::registerHandler({
.basePath = "challenge", .basePath = "challenge",
.required = false, .required = false,
.load = [](const std::fs::path &basePath, Tar &tar) { .load = [](const std::fs::path &basePath, const Tar &tar) {
if (!tar.contains(basePath / "achievements.json") || !tar.contains(basePath / "description.txt")) if (!tar.contains(basePath / "achievements.json") || !tar.contains(basePath / "description.txt"))
return true; return true;
@@ -302,7 +302,7 @@ namespace hex::plugin::builtin {
return true; return true;
}, },
.store = [](const std::fs::path &basePath, Tar &tar) { .store = [](const std::fs::path &basePath, const Tar &tar) {
if (!challengeAchievement.empty()) if (!challengeAchievement.empty())
tar.writeString(basePath / "achievements.json", challengeAchievement); tar.writeString(basePath / "achievements.json", challengeAchievement);
if (!challengeDescription.empty()) if (!challengeDescription.empty())

View File

@@ -266,9 +266,9 @@ namespace hex::plugin::builtin {
void handlePatternLanguageCommand(const std::vector<std::string> &args) { void handlePatternLanguageCommand(const std::vector<std::string> &args) {
std::vector<std::string> processedArgs = args; std::vector<std::string> processedArgs = args;
if (processedArgs.empty()) if (processedArgs.empty()) {
processedArgs.emplace_back("--help"); processedArgs.emplace_back("--help");
else { } else {
for (const auto &path : fs::getDefaultPaths(fs::ImHexPath::PatternsInclude)) for (const auto &path : fs::getDefaultPaths(fs::ImHexPath::PatternsInclude))
processedArgs.emplace_back(hex::format("--includes={}", wolv::util::toUTF8String(path))); processedArgs.emplace_back(hex::format("--includes={}", wolv::util::toUTF8String(path)));
} }

View File

@@ -46,7 +46,7 @@ namespace hex::plugin::builtin {
} else { } else {
m_value = std::stod(value) * m_multiplier; m_value = std::stod(value) * m_multiplier;
} }
} catch (const std::exception &e) { } catch (const std::exception &) {
m_value = 0; m_value = 0;
m_unit = Unit::Invalid; m_unit = Unit::Invalid;
m_unitString.clear(); m_unitString.clear();
@@ -176,34 +176,34 @@ namespace hex::plugin::builtin {
else if (unitString.starts_with("a")) { multiplier = 1E-18; unitString = unitString.substr(1); } else if (unitString.starts_with("a")) { multiplier = 1E-18; unitString = unitString.substr(1); }
else if (unitString.starts_with("z")) { multiplier = 1E-21; unitString = unitString.substr(1); } else if (unitString.starts_with("z")) { multiplier = 1E-21; unitString = unitString.substr(1); }
else if (unitString.starts_with("y")) { multiplier = 1E-24; unitString = unitString.substr(1); } else if (unitString.starts_with("y")) { multiplier = 1E-24; unitString = unitString.substr(1); }
else return parseUnit(unitString, false); else { return parseUnit(unitString, false); }
} }
unitString = wolv::util::trim(unitString); unitString = wolv::util::trim(unitString);
m_unitString = unitString; m_unitString = unitString;
if (unitString.empty()) { if (unitString.empty()) {
if (multiplier == 1) if (multiplier == 1) {
return { Unit::Unitless, 1 }; return { Unit::Unitless, 1 };
else { } else {
m_unitString = unitStringCopy; m_unitString = unitStringCopy;
return { Unit::Unitless, 1 }; return { Unit::Unitless, 1 };
} }
} } else if (unitString == "bit" || unitString == "bits" || unitString == "b") {
else if (unitString == "bit" || unitString == "bits" || unitString == "b")
return { Unit::Bits, multiplier }; return { Unit::Bits, multiplier };
else if (unitString == "byte" || unitString == "bytes" || unitString == "B") } else if (unitString == "byte" || unitString == "bytes" || unitString == "B") {
return { Unit::Bytes, multiplier }; return { Unit::Bytes, multiplier };
else if (unitString == "hex" || unitString == "hex.builtin.command.convert.hexadecimal"_lang.get()) } else if (unitString == "hex" || unitString == "hex.builtin.command.convert.hexadecimal"_lang.get()) {
return { Unit::Hexadecimal, multiplier }; return { Unit::Hexadecimal, multiplier };
else if (unitString == "bin" || unitString == "hex.builtin.command.convert.binary"_lang.get()) } else if (unitString == "bin" || unitString == "hex.builtin.command.convert.binary"_lang.get()) {
return { Unit::Binary, multiplier }; return { Unit::Binary, multiplier };
else if (unitString == "oct" || unitString == "hex.builtin.command.convert.octal"_lang.get()) } else if (unitString == "oct" || unitString == "hex.builtin.command.convert.octal"_lang.get()) {
return { Unit::Octal, multiplier }; return { Unit::Octal, multiplier };
else if (unitString == "dec" || unitString == "hex.builtin.command.convert.decimal"_lang.get()) } else if (unitString == "dec" || unitString == "hex.builtin.command.convert.decimal"_lang.get()) {
return { Unit::Decimal, multiplier }; return { Unit::Decimal, multiplier };
else } else {
return { Unit::Invalid, multiplier }; return { Unit::Invalid, multiplier };
}
} }
private: private:

View File

@@ -3,7 +3,6 @@
#include <imgui.h> #include <imgui.h>
#include <hex/ui/imgui_imhex_extensions.h> #include <hex/ui/imgui_imhex_extensions.h>
#include <hex/helpers/logger.hpp>
#include <hex/helpers/utils.hpp> #include <hex/helpers/utils.hpp>
#include <wolv/utils/string.hpp> #include <wolv/utils/string.hpp>
@@ -30,9 +29,9 @@ namespace hex::plugin::builtin {
if (size == ByteCount) { if (size == ByteCount) {
return drawDefaultScalarEditingTextBox(address, getFormatString(upperCase), ImGuiExt::getImGuiDataType<T>(), data, ImGuiInputTextFlags_CharsHexadecimal); return drawDefaultScalarEditingTextBox(address, getFormatString(upperCase), ImGuiExt::getImGuiDataType<T>(), data, ImGuiInputTextFlags_CharsHexadecimal);
} } else {
else
return false; return false;
}
} }
private: private:
@@ -73,9 +72,9 @@ namespace hex::plugin::builtin {
ImGui::Text(getFormatString(upperCase), c); ImGui::Text(getFormatString(upperCase), c);
break; break;
} }
} } else {
else
ImGuiExt::TextFormatted("{: {}s}", CharCount); ImGuiExt::TextFormatted("{: {}s}", CharCount);
}
} }
bool drawEditing(u64 address, u8 *data, size_t size, bool upperCase, bool startedEditing) override { bool drawEditing(u64 address, u8 *data, size_t size, bool upperCase, bool startedEditing) override {
@@ -83,9 +82,9 @@ namespace hex::plugin::builtin {
if (size == ByteCount) { if (size == ByteCount) {
return drawDefaultScalarEditingTextBox(address, getFormatString(upperCase), ImGuiExt::getImGuiDataType<u8>(), data, ImGuiInputTextFlags_None); return drawDefaultScalarEditingTextBox(address, getFormatString(upperCase), ImGuiExt::getImGuiDataType<u8>(), data, ImGuiInputTextFlags_None);
} } else {
else
return false; return false;
}
} }
private: private:
@@ -116,9 +115,9 @@ namespace hex::plugin::builtin {
ImGui::Text(getFormatString(), static_cast<i64>(*reinterpret_cast<const T*>(data))); ImGui::Text(getFormatString(), static_cast<i64>(*reinterpret_cast<const T*>(data)));
else else
ImGui::Text(getFormatString(), static_cast<u64>(*reinterpret_cast<const T*>(data))); ImGui::Text(getFormatString(), static_cast<u64>(*reinterpret_cast<const T*>(data)));
} } else {
else
ImGuiExt::TextFormatted("{: {}s}", CharCount); ImGuiExt::TextFormatted("{: {}s}", CharCount);
}
} }
bool drawEditing(u64 address, u8 *data, size_t size, bool upperCase, bool startedEditing) override { bool drawEditing(u64 address, u8 *data, size_t size, bool upperCase, bool startedEditing) override {
@@ -126,9 +125,9 @@ namespace hex::plugin::builtin {
if (size == ByteCount) { if (size == ByteCount) {
return drawDefaultScalarEditingTextBox(address, FormatString.c_str(), ImGuiExt::getImGuiDataType<T>(), data, ImGuiInputTextFlags_None); return drawDefaultScalarEditingTextBox(address, FormatString.c_str(), ImGuiExt::getImGuiDataType<T>(), data, ImGuiInputTextFlags_None);
} } else {
else
return false; return false;
}
} }
private: private:
@@ -163,9 +162,9 @@ namespace hex::plugin::builtin {
if (size == ByteCount) { if (size == ByteCount) {
return drawDefaultScalarEditingTextBox(address, getFormatString(upperCase), ImGuiExt::getImGuiDataType<T>(), data, ImGuiInputTextFlags_CharsScientific); return drawDefaultScalarEditingTextBox(address, getFormatString(upperCase), ImGuiExt::getImGuiDataType<T>(), data, ImGuiInputTextFlags_CharsScientific);
} } else {
else
return false; return false;
}
} }
private: private:

View File

@@ -108,7 +108,7 @@ namespace hex::plugin::builtin {
ui::ToastError::open(hex::format("hex.builtin.popup.error.project.load"_lang, wolv::util::toUTF8String(path))); ui::ToastError::open(hex::format("hex.builtin.popup.error.project.load"_lang, wolv::util::toUTF8String(path)));
} }
} else { } else {
FileProvider* newProvider = static_cast<FileProvider*>( auto newProvider = static_cast<FileProvider*>(
ImHexApi::Provider::createProvider("hex.builtin.provider.file", true) ImHexApi::Provider::createProvider("hex.builtin.provider.file", true)
); );
@@ -116,9 +116,9 @@ namespace hex::plugin::builtin {
return; return;
newProvider->setPath(path); newProvider->setPath(path);
if (!newProvider->open()) if (!newProvider->open()) {
hex::ImHexApi::Provider::remove(newProvider); hex::ImHexApi::Provider::remove(newProvider);
else { } else {
EventProviderOpened::post(newProvider); EventProviderOpened::post(newProvider);
AchievementManager::unlockAchievement("hex.builtin.achievement.starting_out", "hex.builtin.achievement.starting_out.open_file.name"); AchievementManager::unlockAchievement("hex.builtin.achievement.starting_out", "hex.builtin.achievement.starting_out.open_file.name");
} }

View File

@@ -1,4 +1,3 @@
#include <imgui_internal.h>
#include <hex/api/imhex_api.hpp> #include <hex/api/imhex_api.hpp>
#include <romfs/romfs.hpp> #include <romfs/romfs.hpp>
@@ -8,8 +7,6 @@
#include <fonts/codicons_font.h> #include <fonts/codicons_font.h>
#include <fonts/blendericons_font.h> #include <fonts/blendericons_font.h>
#include <imgui_freetype.h>
namespace hex::plugin::builtin { namespace hex::plugin::builtin {
void loadFonts() { void loadFonts() {

View File

@@ -4,7 +4,6 @@
#include <hex/api/task_manager.hpp> #include <hex/api/task_manager.hpp>
#include <hex/helpers/http_requests.hpp> #include <hex/helpers/http_requests.hpp>
#include <hex/helpers/fmt.hpp>
#include <hex/helpers/fs.hpp> #include <hex/helpers/fs.hpp>
#include <hex/helpers/utils.hpp> #include <hex/helpers/utils.hpp>
#include <hex/helpers/logger.hpp> #include <hex/helpers/logger.hpp>
@@ -59,7 +58,7 @@ namespace hex::plugin::builtin {
ImHexApi::System::impl::addInitArgument("update-available", latestVersion.data()); ImHexApi::System::impl::addInitArgument("update-available", latestVersion.data());
// Check if there is a telemetry uuid // Check if there is a telemetry uuid
std::string uuid = ContentRegistry::Settings::read("hex.builtin.setting.general", "hex.builtin.setting.general.uuid", "").get<std::string>(); auto uuid = ContentRegistry::Settings::read("hex.builtin.setting.general", "hex.builtin.setting.general.uuid", "").get<std::string>();
if (uuid.empty()) { if (uuid.empty()) {
// Generate a new uuid // Generate a new uuid
uuid = wolv::hash::generateUUID(); uuid = wolv::hash::generateUUID();

View File

@@ -26,7 +26,7 @@ using namespace std::literals::string_literals;
namespace hex::plugin::builtin { namespace hex::plugin::builtin {
static bool g_demoWindowOpen = false; static bool s_demoWindowOpen = false;
namespace { namespace {
@@ -275,9 +275,9 @@ namespace hex::plugin::builtin {
return; return;
} }
if (data.has_value()) if (data.has_value()) {
file.writeVector(data.value()); file.writeVector(data.value());
else { } else {
handleIPSError(data.error()); handleIPSError(data.error());
} }
@@ -314,9 +314,9 @@ namespace hex::plugin::builtin {
return; return;
} }
if (data.has_value()) if (data.has_value()) {
file.writeVector(data.value()); file.writeVector(data.value());
else { } else {
handleIPSError(data.error()); handleIPSError(data.error());
} }
@@ -490,7 +490,7 @@ namespace hex::plugin::builtin {
#if defined(DEBUG) #if defined(DEBUG)
ImGui::Separator(); ImGui::Separator();
ImGui::MenuItem("hex.builtin.menu.view.demo"_lang, "", &g_demoWindowOpen); ImGui::MenuItem("hex.builtin.menu.view.demo"_lang, "", &s_demoWindowOpen);
ImGui::MenuItem("hex.builtin.menu.view.debug"_lang, "", &hex::dbg::impl::getDebugWindowState()); ImGui::MenuItem("hex.builtin.menu.view.debug"_lang, "", &hex::dbg::impl::getDebugWindowState());
#endif #endif
}); });
@@ -531,9 +531,9 @@ namespace hex::plugin::builtin {
if (shift) { if (shift) {
wolv::io::fs::remove(path); wolv::io::fs::remove(path);
LayoutManager::reload(); LayoutManager::reload();
} } else {
else
LayoutManager::load(path); LayoutManager::load(path);
}
} }
} }
}); });
@@ -580,9 +580,9 @@ namespace hex::plugin::builtin {
createHelpMenu(); createHelpMenu();
(void)EventFrameEnd::subscribe([] { (void)EventFrameEnd::subscribe([] {
if (g_demoWindowOpen) { if (s_demoWindowOpen) {
ImGui::ShowDemoWindow(&g_demoWindowOpen); ImGui::ShowDemoWindow(&s_demoWindowOpen);
ImPlot::ShowDemoWindow(&g_demoWindowOpen); ImPlot::ShowDemoWindow(&s_demoWindowOpen);
} }
}); });
} }

View File

@@ -6,7 +6,6 @@
#include <pl/core/token.hpp> #include <pl/core/token.hpp>
#include <pl/core/evaluator.hpp> #include <pl/core/evaluator.hpp>
#include <pl/patterns/pattern.hpp>
#include <llvm/Demangle/Demangle.h> #include <llvm/Demangle/Demangle.h>

View File

@@ -44,7 +44,7 @@ namespace hex::plugin::builtin {
ProjectFile::registerHandler({ ProjectFile::registerHandler({
.basePath = "providers", .basePath = "providers",
.required = true, .required = true,
.load = [](const std::fs::path &basePath, Tar &tar) { .load = [](const std::fs::path &basePath, const Tar &tar) {
auto json = nlohmann::json::parse(tar.readString(basePath / "providers.json")); auto json = nlohmann::json::parse(tar.readString(basePath / "providers.json"));
auto providerIds = json.at("providers").get<std::vector<int>>(); auto providerIds = json.at("providers").get<std::vector<int>>();
@@ -88,8 +88,9 @@ namespace hex::plugin::builtin {
if (loaded) { if (loaded) {
if (!newProvider->open() || !newProvider->isAvailable() || !newProvider->isReadable()) { if (!newProvider->open() || !newProvider->isAvailable() || !newProvider->isReadable()) {
providerWarnings[newProvider] = newProvider->getErrorMessage(); providerWarnings[newProvider] = newProvider->getErrorMessage();
} else } else {
EventProviderOpened::post(newProvider); EventProviderOpened::post(newProvider);
}
} }
} }
@@ -110,15 +111,16 @@ namespace hex::plugin::builtin {
} else { } else {
// Else, if are warnings, still display them // Else, if are warnings, still display them
if (warningMsg.empty()) return true; if (warningMsg.empty()) {
else { return true;
} else {
showWarning( showWarning(
hex::format("hex.builtin.popup.error.project.load.some_providers_failed"_lang, warningMsg)); hex::format("hex.builtin.popup.error.project.load.some_providers_failed"_lang, warningMsg));
} }
return success; return success;
} }
}, },
.store = [](const std::fs::path &basePath, Tar &tar) { .store = [](const std::fs::path &basePath, const Tar &tar) {
std::vector<int> providerIds; std::vector<int> providerIds;
for (const auto &provider : ImHexApi::Provider::getProviders()) { for (const auto &provider : ImHexApi::Provider::getProviders()) {
auto id = provider->getID(); auto id = provider->getID();

View File

@@ -302,7 +302,7 @@ namespace hex::plugin::builtin {
size_t currSize = std::min<u64>(size, m_sectorSize); size_t currSize = std::min<u64>(size, m_sectorSize);
this->readRaw(sectorBase, modifiedSectorBuffer.data(), modifiedSectorBuffer.size()); this->readRaw(sectorBase, modifiedSectorBuffer.data(), modifiedSectorBuffer.size());
std::memcpy(modifiedSectorBuffer.data() + ((offset - sectorBase) % m_sectorSize), reinterpret_cast<const u8 *>(buffer) + (startOffset - offset), currSize); std::memcpy(modifiedSectorBuffer.data() + ((offset - sectorBase) % m_sectorSize), static_cast<const u8 *>(buffer) + (startOffset - offset), currSize);
LARGE_INTEGER seekPosition; LARGE_INTEGER seekPosition;
seekPosition.LowPart = (offset & 0xFFFF'FFFF) - (offset % m_sectorSize); seekPosition.LowPart = (offset & 0xFFFF'FFFF) - (offset % m_sectorSize);

View File

@@ -260,9 +260,9 @@ namespace hex::plugin::builtin {
this->setErrorMessage(hex::format("hex.builtin.provider.file.error.open"_lang, m_path.string(), e.what())); this->setErrorMessage(hex::format("hex.builtin.provider.file.error.open"_lang, m_path.string(), e.what()));
} }
} }
} } else {
else
this->setPath(path); this->setPath(path);
}
} }
nlohmann::json FileProvider::storeSettings(nlohmann::json settings) const { nlohmann::json FileProvider::storeSettings(nlohmann::json settings) const {
@@ -290,9 +290,9 @@ namespace hex::plugin::builtin {
auto newProvider = hex::ImHexApi::Provider::createProvider("hex.builtin.provider.mem_file", true); auto newProvider = hex::ImHexApi::Provider::createProvider("hex.builtin.provider.mem_file", true);
if (auto memoryProvider = dynamic_cast<MemoryFileProvider*>(newProvider); memoryProvider != nullptr) { if (auto memoryProvider = dynamic_cast<MemoryFileProvider*>(newProvider); memoryProvider != nullptr) {
if (!memoryProvider->open()) if (!memoryProvider->open()) {
ImHexApi::Provider::remove(newProvider); ImHexApi::Provider::remove(newProvider);
else { } else {
const auto size = this->getActualSize(); const auto size = this->getActualSize();
TaskManager::createTask("Loading into memory", size, [this, size, memoryProvider](Task &task) { TaskManager::createTask("Loading into memory", size, [this, size, memoryProvider](Task &task) {
task.setInterruptCallback([memoryProvider]{ task.setInterruptCallback([memoryProvider]{

View File

@@ -57,9 +57,9 @@ namespace hex::plugin::builtin {
return string[offset++]; return string[offset++];
}; };
auto parseValue = [&](u8 byteCount) { auto parseValue = [&](u8 count) {
u64 value = 0x00; u64 value = 0x00;
for (u8 i = 0; i < byteCount; i++) { for (u8 i = 0; i < count; i++) {
u8 byte = (parseHexDigit(c()) << 4) | parseHexDigit(c()); u8 byte = (parseHexDigit(c()) << 4) | parseHexDigit(c());
value <<= 8; value <<= 8;
value |= byte; value |= byte;

View File

@@ -53,9 +53,9 @@ namespace hex::plugin::builtin {
if (auto fileProvider = dynamic_cast<FileProvider*>(newProvider); fileProvider != nullptr) { if (auto fileProvider = dynamic_cast<FileProvider*>(newProvider); fileProvider != nullptr) {
fileProvider->setPath(path); fileProvider->setPath(path);
if (!fileProvider->open()) if (!fileProvider->open()) {
ImHexApi::Provider::remove(newProvider); ImHexApi::Provider::remove(newProvider);
else { } else {
MovePerProviderData::post(this, fileProvider); MovePerProviderData::post(this, fileProvider);
fileProvider->markDirty(false); fileProvider->markDirty(false);

View File

@@ -43,9 +43,9 @@ namespace hex::plugin::builtin {
return string[offset++]; return string[offset++];
}; };
auto parseValue = [&](u8 byteCount) { auto parseValue = [&](u8 count) {
u64 value = 0x00; u64 value = 0x00;
for (u8 i = 0; i < byteCount; i++) { for (u8 i = 0; i < count; i++) {
u8 byte = (parseHexDigit(c()) << 4) | parseHexDigit(c()); u8 byte = (parseHexDigit(c()) << 4) | parseHexDigit(c());
value <<= 8; value <<= 8;
value |= byte; value |= byte;

View File

@@ -400,8 +400,9 @@ namespace hex::plugin::builtin {
return m_selectedProcess->id; return m_selectedProcess->id;
} else if (category == "process_name") { } else if (category == "process_name") {
return m_selectedProcess->name; return m_selectedProcess->name;
} else } else {
return Provider::queryInformation(category, argument); return Provider::queryInformation(category, argument);
}
} }
} }

View File

@@ -344,9 +344,10 @@ namespace hex::plugin::builtin::recent {
s_recentEntries.clear(); s_recentEntries.clear();
// Remove all recent files // Remove all recent files
for (const auto &recentPath : fs::getDefaultPaths(fs::ImHexPath::Recent)) for (const auto &recentPath : fs::getDefaultPaths(fs::ImHexPath::Recent)) {
for (const auto &entry : std::fs::directory_iterator(recentPath)) for (const auto &entry : std::fs::directory_iterator(recentPath))
std::fs::remove(entry.path()); std::fs::remove(entry.path());
}
} }
ImGui::EndMenu(); ImGui::EndMenu();

View File

@@ -543,9 +543,9 @@ namespace hex::plugin::builtin {
static void loadThemeSettings() { static void loadThemeSettings() {
auto theme = ContentRegistry::Settings::read("hex.builtin.setting.interface", "hex.builtin.setting.interface.color", ThemeManager::NativeTheme).get<std::string>(); auto theme = ContentRegistry::Settings::read("hex.builtin.setting.interface", "hex.builtin.setting.interface.color", ThemeManager::NativeTheme).get<std::string>();
if (theme == ThemeManager::NativeTheme) if (theme == ThemeManager::NativeTheme) {
ImHexApi::System::enableSystemThemeDetection(true); ImHexApi::System::enableSystemThemeDetection(true);
else { } else {
ImHexApi::System::enableSystemThemeDetection(false); ImHexApi::System::enableSystemThemeDetection(false);
ThemeManager::changeTheme(theme); ThemeManager::changeTheme(theme);
} }

View File

@@ -3,8 +3,6 @@
#include <hex/api/localization_manager.hpp> #include <hex/api/localization_manager.hpp>
#include <wolv/math_eval/math_evaluator.hpp>
#include <imgui.h> #include <imgui.h>
#include <hex/ui/imgui_imhex_extensions.h> #include <hex/ui/imgui_imhex_extensions.h>

View File

@@ -106,9 +106,9 @@ namespace hex::plugin::builtin {
ImGui::BeginDisabled(files.empty() || outputPath.empty()); ImGui::BeginDisabled(files.empty() || outputPath.empty());
{ {
if (combinerTask.isRunning()) if (combinerTask.isRunning()) {
ImGuiExt::TextSpinner("hex.builtin.tools.file_tools.combiner.combining"_lang); ImGuiExt::TextSpinner("hex.builtin.tools.file_tools.combiner.combining"_lang);
else { } else {
if (ImGui::Button("hex.builtin.tools.file_tools.combiner.combine"_lang)) { if (ImGui::Button("hex.builtin.tools.file_tools.combiner.combine"_lang)) {
combinerTask = TaskManager::createTask("hex.builtin.tools.file_tools.combiner.combining", 0, [](auto &task) { combinerTask = TaskManager::createTask("hex.builtin.tools.file_tools.combiner.combining", 0, [](auto &task) {
wolv::io::File output(outputPath, wolv::io::File::Mode::Create); wolv::io::File output(outputPath, wolv::io::File::Mode::Create);

View File

@@ -42,9 +42,9 @@ namespace hex::plugin::builtin {
} }
ImGui::EndChild(); ImGui::EndChild();
if (shredderTask.isRunning()) if (shredderTask.isRunning()) {
ImGuiExt::TextSpinner("hex.builtin.tools.file_tools.shredder.shredding"_lang); ImGuiExt::TextSpinner("hex.builtin.tools.file_tools.shredder.shredding"_lang);
else { } else {
ImGui::BeginDisabled(selectedFile.empty()); ImGui::BeginDisabled(selectedFile.empty());
{ {
if (ImGui::Button("hex.builtin.tools.file_tools.shredder.shred"_lang)) { if (ImGui::Button("hex.builtin.tools.file_tools.shredder.shred"_lang)) {

View File

@@ -89,9 +89,9 @@ namespace hex::plugin::builtin {
ImGui::BeginDisabled(selectedFile.empty() || baseOutputPath.empty() || splitSize == 0); ImGui::BeginDisabled(selectedFile.empty() || baseOutputPath.empty() || splitSize == 0);
{ {
if (splitterTask.isRunning()) if (splitterTask.isRunning()) {
ImGuiExt::TextSpinner("hex.builtin.tools.file_tools.splitter.picker.splitting"_lang); ImGuiExt::TextSpinner("hex.builtin.tools.file_tools.splitter.picker.splitting"_lang);
else { } else {
if (ImGui::Button("hex.builtin.tools.file_tools.splitter.picker.split"_lang)) { if (ImGui::Button("hex.builtin.tools.file_tools.splitter.picker.split"_lang)) {
splitterTask = TaskManager::createTask("hex.builtin.tools.file_tools.splitter.picker.splitting", 0, [](auto &task) { splitterTask = TaskManager::createTask("hex.builtin.tools.file_tools.splitter.picker.splitting", 0, [](auto &task) {
ON_SCOPE_EXIT { ON_SCOPE_EXIT {

View File

@@ -262,9 +262,9 @@ namespace hex::plugin::builtin {
// Zero or denormal. // Zero or denormal.
if (ieee754.exponentBits == 0) { if (ieee754.exponentBits == 0) {
// Result doesn't fit in 128 bits. // Result doesn't fit in 128 bits.
if ((ieee754.exponentBias - 1) > 128) if ((ieee754.exponentBias - 1) > 128) {
ieee754.exponentValue = std::pow(2.0L, static_cast<long double>(-ieee754.exponentBias + 1)); ieee754.exponentValue = std::pow(2.0L, static_cast<long double>(-ieee754.exponentBias + 1));
else { } else {
if (ieee754.exponentBias == 0) { if (ieee754.exponentBias == 0) {
// Exponent is zero. // Exponent is zero.
if (ieee754.mantissaBits == 0) if (ieee754.mantissaBits == 0)
@@ -272,17 +272,18 @@ namespace hex::plugin::builtin {
else else
// Exponent is one. // Exponent is one.
ieee754.exponentValue = 2.0; ieee754.exponentValue = 2.0;
} } else {
else
ieee754.exponentValue = 1.0 / static_cast<long double>(u128(1) << (ieee754.exponentBias - 1)); ieee754.exponentValue = 1.0 / static_cast<long double>(u128(1) << (ieee754.exponentBias - 1));
}
} }
} }
// Normal. // Normal.
else { else {
// Result doesn't fit in 128 bits. // Result doesn't fit in 128 bits.
if (std::abs(ieee754.exponentBits - ieee754.exponentBias) > 128) if (std::abs(ieee754.exponentBits - ieee754.exponentBias) > 128) {
ieee754.exponentValue = std::pow(2.0L, static_cast<long double>(ieee754.exponentBits - ieee754.exponentBias)); ieee754.exponentValue = std::pow(2.0L, static_cast<long double>(ieee754.exponentBits - ieee754.exponentBias));
//Result fits in 128 bits. }
//Result fits in 128 bits.
else { else {
// Exponent is positive. // Exponent is positive.
if (ieee754.exponentBits > ieee754.exponentBias) if (ieee754.exponentBits > ieee754.exponentBias)
@@ -356,9 +357,10 @@ namespace hex::plugin::builtin {
// And remove it from the string. // And remove it from the string.
ieee754.signBits = 1; ieee754.signBits = 1;
decimalFloatingPointNumberString.erase(0, 1); decimalFloatingPointNumberString.erase(0, 1);
} else } else {
// Important to switch from - to +. // Important to switch from - to +.
ieee754.signBits = 0; ieee754.signBits = 0;
}
InputType inputType = InputType::Regular; InputType inputType = InputType::Regular;
bool matchFound = false; bool matchFound = false;
@@ -385,14 +387,13 @@ namespace hex::plugin::builtin {
ieee754statics.resultFloat = std::numeric_limits<long double>::infinity(); ieee754statics.resultFloat = std::numeric_limits<long double>::infinity();
ieee754statics.resultFloat *= (ieee754.signBits == 1 ? -1 : 1); ieee754statics.resultFloat *= (ieee754.signBits == 1 ? -1 : 1);
} else if (inputType == InputType::NotANumber) } else if (inputType == InputType::NotANumber) {
ieee754statics.resultFloat = std::numeric_limits<long double>::quiet_NaN(); ieee754statics.resultFloat = std::numeric_limits<long double>::quiet_NaN();
} else if (inputType == InputType::QuietNotANumber) {
else if (inputType == InputType::QuietNotANumber)
ieee754statics.resultFloat = std::numeric_limits<long double>::quiet_NaN(); ieee754statics.resultFloat = std::numeric_limits<long double>::quiet_NaN();
} else if (inputType == InputType::SignalingNotANumber) {
else if (inputType == InputType::SignalingNotANumber)
ieee754statics.resultFloat = std::numeric_limits<long double>::signaling_NaN(); ieee754statics.resultFloat = std::numeric_limits<long double>::signaling_NaN();
}
if (inputType != InputType::Invalid) { if (inputType != InputType::Invalid) {
@@ -514,15 +515,15 @@ namespace hex::plugin::builtin {
ImGui::Text("qNaN"); ImGui::Text("qNaN");
else else
ImGui::Text("sNaN"); ImGui::Text("sNaN");
} else if (ieee754.numberType == NumberType::Infinity) {
} else if (ieee754.numberType == NumberType::Infinity)
ImGui::Text("Inf"); ImGui::Text("Inf");
else if (ieee754.numberType == NumberType::Zero) } else if (ieee754.numberType == NumberType::Zero) {
ImGui::Text("0"); ImGui::Text("0");
else if (ieee754.numberType == NumberType::Denormal) } else if (ieee754.numberType == NumberType::Denormal) {
ImGuiExt::TextFormatted("2^{0}", 1 - ieee754.exponentBias); ImGuiExt::TextFormatted("2^{0}", 1 - ieee754.exponentBias);
else } else {
ImGuiExt::TextFormatted("2^{0}", ieee754.exponentBits - ieee754.exponentBias); ImGuiExt::TextFormatted("2^{0}", ieee754.exponentBits - ieee754.exponentBias);
}
ImGui::Unindent(20_scaled); ImGui::Unindent(20_scaled);
@@ -681,8 +682,9 @@ namespace hex::plugin::builtin {
decimalFloatingPointNumberString = "qnan"; decimalFloatingPointNumberString = "qnan";
else else
decimalFloatingPointNumberString = "snan"; decimalFloatingPointNumberString = "snan";
} else } else {
decimalFloatingPointNumberString = fmt::format("{:.{}}", ieee754statics.resultFloat, ieee754.precision); decimalFloatingPointNumberString = fmt::format("{:.{}}", ieee754statics.resultFloat, ieee754.precision);
}
auto style1 = ImGui::GetStyle(); auto style1 = ImGui::GetStyle();
inputFieldWidth = std::fmax(inputFieldWidth, ImGui::CalcTextSize(decimalFloatingPointNumberString.c_str()).x + 2 * style1.FramePadding.x); inputFieldWidth = std::fmax(inputFieldWidth, ImGui::CalcTextSize(decimalFloatingPointNumberString.c_str()).x + 2 * style1.FramePadding.x);

View File

@@ -16,7 +16,7 @@ namespace hex::plugin::builtin {
using namespace std::literals::chrono_literals; using namespace std::literals::chrono_literals;
std::string getWikipediaApiUrl() { std::string getWikipediaApiUrl() {
std::string setting = ContentRegistry::Settings::read("hex.builtin.setting.interface", "hex.builtin.setting.interface.wiki_explain_language", "en").get<std::string>(); auto setting = ContentRegistry::Settings::read("hex.builtin.setting.interface", "hex.builtin.setting.interface.wiki_explain_language", "en").get<std::string>();
return "https://" + setting + ".wikipedia.org/w/api.php?format=json&action=query&prop=extracts&explaintext&redirects=10&formatversion=2"; return "https://" + setting + ".wikipedia.org/w/api.php?format=json&action=query&prop=extracts&explaintext&redirects=10&formatversion=2";
} }

View File

@@ -92,7 +92,7 @@ namespace hex::plugin::builtin {
Lang("hex.builtin.view.tutorials.name") Lang("hex.builtin.view.tutorials.name")
}) })
.onAppear([&step] { .onAppear([&step] {
EventViewOpened::subscribe([&step](View *view){ EventViewOpened::subscribe([&step](const View *view){
if (view->getUnlocalizedName() == UnlocalizedString("hex.builtin.view.tutorials.name")) if (view->getUnlocalizedName() == UnlocalizedString("hex.builtin.view.tutorials.name"))
step.complete(); step.complete();
}); });

View File

@@ -53,14 +53,14 @@ namespace hex::plugin::builtin {
// Determine achievement fill color based on unlock state // Determine achievement fill color based on unlock state
const auto fillColor = [&] { const auto fillColor = [&] {
if (achievement.isUnlocked()) if (achievement.isUnlocked()) {
return ImGui::GetColorU32(ImGuiCol_FrameBg, 1.0F) | 0xFF000000; return ImGui::GetColorU32(ImGuiCol_FrameBg, 1.0F) | 0xFF000000;
else if (node->isUnlockable()) { } else if (node->isUnlockable()) {
auto cycleProgress = sinf(float(ImGui::GetTime()) * 6.0F) * 0.5F + 0.5F; auto cycleProgress = sinf(float(ImGui::GetTime()) * 6.0F) * 0.5F + 0.5F;
return (u32(ImColor(ImLerp(ImGui::GetStyleColorVec4(ImGuiCol_TextDisabled), ImGui::GetStyleColorVec4(ImGuiCol_Text), cycleProgress))) & 0x00FFFFFF) | 0x80000000; return (u32(ImColor(ImLerp(ImGui::GetStyleColorVec4(ImGuiCol_TextDisabled), ImGui::GetStyleColorVec4(ImGuiCol_Text), cycleProgress))) & 0x00FFFFFF) | 0x80000000;
} } else {
else
return ImGui::GetColorU32(ImGuiCol_TextDisabled, 0.5F); return ImGui::GetColorU32(ImGuiCol_TextDisabled, 0.5F);
}
}(); }();
// Draw achievement background // Draw achievement background

View File

@@ -141,7 +141,7 @@ namespace hex::plugin::builtin {
ProjectFile::registerPerProviderHandler({ ProjectFile::registerPerProviderHandler({
.basePath = "bookmarks.json", .basePath = "bookmarks.json",
.required = false, .required = false,
.load = [this](prv::Provider *provider, const std::fs::path &basePath, Tar &tar) -> bool { .load = [this](prv::Provider *provider, const std::fs::path &basePath, const Tar &tar) -> bool {
auto fileContent = tar.readString(basePath); auto fileContent = tar.readString(basePath);
if (fileContent.empty()) if (fileContent.empty())
return true; return true;
@@ -150,7 +150,7 @@ namespace hex::plugin::builtin {
m_bookmarks.get(provider).clear(); m_bookmarks.get(provider).clear();
return this->importBookmarks(provider, data); return this->importBookmarks(provider, data);
}, },
.store = [this](prv::Provider *provider, const std::fs::path &basePath, Tar &tar) -> bool { .store = [this](prv::Provider *provider, const std::fs::path &basePath, const Tar &tar) -> bool {
nlohmann::json data; nlohmann::json data;
bool result = this->exportBookmarks(provider, data); bool result = this->exportBookmarks(provider, data);
@@ -194,7 +194,7 @@ namespace hex::plugin::builtin {
static void drawColorPopup(ImColor &color) { static void drawColorPopup(ImColor &color) {
// Generate color picker palette // Generate color picker palette
static auto Palette = [] { const static auto Palette = [] {
constexpr static auto ColorCount = 36; constexpr static auto ColorCount = 36;
std::array<ImColor, ColorCount> result = { 0 }; std::array<ImColor, ColorCount> result = { 0 };
@@ -212,7 +212,7 @@ namespace hex::plugin::builtin {
bool colorChanged = false; bool colorChanged = false;
// Draw default color picker // Draw default color picker
if (ImGui::ColorPicker4("##picker", (float*)&color, ImGuiColorEditFlags_NoSidePreview | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoOptions | ImGuiColorEditFlags_NoSmallPreview)) if (ImGui::ColorPicker4("##picker", &color.Value.x, ImGuiColorEditFlags_NoSidePreview | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoOptions | ImGuiColorEditFlags_NoSmallPreview))
colorChanged = true; colorChanged = true;
ImGui::Separator(); ImGui::Separator();
@@ -343,9 +343,9 @@ namespace hex::plugin::builtin {
ImGui::SameLine(); ImGui::SameLine();
// Draw bookmark name if the bookmark is locked or an input text box if it's unlocked // Draw bookmark name if the bookmark is locked or an input text box if it's unlocked
if (locked) if (locked) {
ImGui::TextUnformatted(name.data()); ImGui::TextUnformatted(name.data());
else { } else {
ImGui::PushItemWidth(ImGui::GetContentRegionAvail().x); ImGui::PushItemWidth(ImGui::GetContentRegionAvail().x);
ImGui::InputText("##nameInput", name); ImGui::InputText("##nameInput", name);
ImGui::PopItemWidth(); ImGui::PopItemWidth();

View File

@@ -164,9 +164,9 @@ namespace hex::plugin::builtin {
// These commands are used by entering a single symbol and then any input // These commands are used by entering a single symbol and then any input
if (auto [match, value] = MatchCommand(input, command); match != MatchType::NoMatch) { if (auto [match, value] = MatchCommand(input, command); match != MatchType::NoMatch) {
if (match != MatchType::PerfectMatch) if (match != MatchType::PerfectMatch) {
results.push_back({ command + " (" + Lang(unlocalizedDescription) + ")", "", AutoComplete }); results.push_back({ command + " (" + Lang(unlocalizedDescription) + ")", "", AutoComplete });
else { } else {
auto matchedCommand = wolv::util::trim(input.substr(command.length())); auto matchedCommand = wolv::util::trim(input.substr(command.length()));
results.push_back({ displayCallback(matchedCommand), matchedCommand, executeCallback }); results.push_back({ displayCallback(matchedCommand), matchedCommand, executeCallback });
} }
@@ -176,9 +176,9 @@ namespace hex::plugin::builtin {
// These commands are used by entering a keyword followed by a space and then any input // These commands are used by entering a keyword followed by a space and then any input
if (auto [match, value] = MatchCommand(input, command + " "); match != MatchType::NoMatch) { if (auto [match, value] = MatchCommand(input, command + " "); match != MatchType::NoMatch) {
if (match != MatchType::PerfectMatch) if (match != MatchType::PerfectMatch) {
results.push_back({ command + " (" + Lang(unlocalizedDescription) + ")", "", AutoComplete }); results.push_back({ command + " (" + Lang(unlocalizedDescription) + ")", "", AutoComplete });
else { } else {
auto matchedCommand = wolv::util::trim(input.substr(command.length() + 1)); auto matchedCommand = wolv::util::trim(input.substr(command.length() + 1));
results.push_back({ displayCallback(matchedCommand), matchedCommand, executeCallback }); results.push_back({ displayCallback(matchedCommand), matchedCommand, executeCallback });
} }

View File

@@ -213,9 +213,10 @@ namespace hex::plugin::builtin {
// Find the index of an attribute by its id // Find the index of an attribute by its id
auto indexFromId = [this](u32 id) -> std::optional<u32> { auto indexFromId = [this](u32 id) -> std::optional<u32> {
const auto &attributes = this->getAttributes(); const auto &attributes = this->getAttributes();
for (u32 i = 0; i < attributes.size(); i++) for (u32 i = 0; i < attributes.size(); i++) {
if (u32(attributes[i].getId()) == id) if (u32(attributes[i].getId()) == id)
return i; return i;
}
return std::nullopt; return std::nullopt;
}; };
@@ -355,7 +356,7 @@ namespace hex::plugin::builtin {
ProjectFile::registerPerProviderHandler({ ProjectFile::registerPerProviderHandler({
.basePath = "data_processor.json", .basePath = "data_processor.json",
.required = false, .required = false,
.load = [this](prv::Provider *provider, const std::fs::path &basePath, Tar &tar) { .load = [this](prv::Provider *provider, const std::fs::path &basePath, const Tar &tar) {
std::string save = tar.readString(basePath); std::string save = tar.readString(basePath);
ViewDataProcessor::loadNodes(m_mainWorkspace.get(provider), nlohmann::json::parse(save)); ViewDataProcessor::loadNodes(m_mainWorkspace.get(provider), nlohmann::json::parse(save));
@@ -363,7 +364,7 @@ namespace hex::plugin::builtin {
return true; return true;
}, },
.store = [this](prv::Provider *provider, const std::fs::path &basePath, Tar &tar) { .store = [this](prv::Provider *provider, const std::fs::path &basePath, const Tar &tar) {
tar.writeString(basePath, ViewDataProcessor::saveNodes(m_mainWorkspace.get(provider)).dump(4)); tar.writeString(basePath, ViewDataProcessor::saveNodes(m_mainWorkspace.get(provider)).dump(4));
return true; return true;
@@ -599,11 +600,11 @@ namespace hex::plugin::builtin {
// Show a different context menu depending on if a node, a link // Show a different context menu depending on if a node, a link
// or the background was right-clicked // or the background was right-clicked
if (ImNodes::IsNodeHovered(&m_rightClickedId)) if (ImNodes::IsNodeHovered(&m_rightClickedId)) {
ImGui::OpenPopup("Node Menu"); ImGui::OpenPopup("Node Menu");
else if (ImNodes::IsLinkHovered(&m_rightClickedId)) } else if (ImNodes::IsLinkHovered(&m_rightClickedId)) {
ImGui::OpenPopup("Link Menu"); ImGui::OpenPopup("Link Menu");
else { } else {
ImGui::OpenPopup("Context Menu"); ImGui::OpenPopup("Context Menu");
this->reloadCustomNodes(); this->reloadCustomNodes();
} }

View File

@@ -264,7 +264,7 @@ namespace hex::plugin::builtin {
return { }; return { };
std::vector<u8> bytes; std::vector<u8> bytes;
Occurrence::DecodeType decodeType = Occurrence::DecodeType::Binary; auto decodeType = Occurrence::DecodeType::Binary;
std::endian endian; std::endian endian;
switch (settings.type) { switch (settings.type) {
default: default:
@@ -494,11 +494,11 @@ namespace hex::plugin::builtin {
void ViewFind::runSearch() { void ViewFind::runSearch() {
Region searchRegion = m_searchSettings.region; Region searchRegion = m_searchSettings.region;
if (m_searchSettings.mode == SearchSettings::Mode::Strings) if (m_searchSettings.mode == SearchSettings::Mode::Strings) {
AchievementManager::unlockAchievement("hex.builtin.achievement.find", "hex.builtin.achievement.find.find_strings.name"); AchievementManager::unlockAchievement("hex.builtin.achievement.find", "hex.builtin.achievement.find.find_strings.name");
else if (m_searchSettings.mode == SearchSettings::Mode::Sequence) } else if (m_searchSettings.mode == SearchSettings::Mode::Sequence) {
AchievementManager::unlockAchievement("hex.builtin.achievement.find", "hex.builtin.achievement.find.find_specific_string.name"); AchievementManager::unlockAchievement("hex.builtin.achievement.find", "hex.builtin.achievement.find.find_specific_string.name");
else if (m_searchSettings.mode == SearchSettings::Mode::Value) { } else if (m_searchSettings.mode == SearchSettings::Mode::Value) {
if (m_searchSettings.value.inputMin == "250" && m_searchSettings.value.inputMax == "1000") if (m_searchSettings.value.inputMin == "250" && m_searchSettings.value.inputMax == "1000")
AchievementManager::unlockAchievement("hex.builtin.achievement.find", "hex.builtin.achievement.find.find_numeric.name"); AchievementManager::unlockAchievement("hex.builtin.achievement.find", "hex.builtin.achievement.find.find_numeric.name");
} }

View File

@@ -1013,7 +1013,7 @@ namespace hex::plugin::builtin {
ProjectFile::registerPerProviderHandler({ ProjectFile::registerPerProviderHandler({
.basePath = "custom_encoding.tbl", .basePath = "custom_encoding.tbl",
.required = false, .required = false,
.load = [this](prv::Provider *, const std::fs::path &basePath, Tar &tar) { .load = [this](prv::Provider *, const std::fs::path &basePath, const Tar &tar) {
if (!tar.contains(basePath)) if (!tar.contains(basePath))
return true; return true;
@@ -1023,7 +1023,7 @@ namespace hex::plugin::builtin {
return true; return true;
}, },
.store = [this](prv::Provider *, const std::fs::path &basePath, Tar &tar) { .store = [this](prv::Provider *, const std::fs::path &basePath, const Tar &tar) {
if (const auto &encoding = m_hexEditor.getCustomEncoding(); encoding.has_value()) { if (const auto &encoding = m_hexEditor.getCustomEncoding(); encoding.has_value()) {
auto content = encoding->getTableContent(); auto content = encoding->getTableContent();

View File

@@ -115,7 +115,7 @@ namespace hex::plugin::builtin {
ProjectFile::registerPerProviderHandler({ ProjectFile::registerPerProviderHandler({
.basePath = "highlight_rules.json", .basePath = "highlight_rules.json",
.required = false, .required = false,
.load = [this](prv::Provider *provider, const std::fs::path &basePath, Tar &tar) -> bool { .load = [this](prv::Provider *provider, const std::fs::path &basePath, const Tar &tar) -> bool {
const auto json = nlohmann::json::parse(tar.readString(basePath)); const auto json = nlohmann::json::parse(tar.readString(basePath));
auto &rules = m_rules.get(provider); auto &rules = m_rules.get(provider);
@@ -138,7 +138,7 @@ namespace hex::plugin::builtin {
return true; return true;
}, },
.store = [this](prv::Provider *provider, const std::fs::path &basePath, Tar &tar) -> bool { .store = [this](prv::Provider *provider, const std::fs::path &basePath, const Tar &tar) -> bool {
nlohmann::json result = nlohmann::json::array(); nlohmann::json result = nlohmann::json::array();
for (const auto &rule : m_rules.get(provider)) { for (const auto &rule : m_rules.get(provider)) {
nlohmann::json content; nlohmann::json content;

View File

@@ -292,9 +292,9 @@ namespace hex::plugin::builtin {
ImGui::TableNextColumn(); ImGui::TableNextColumn();
ImGuiExt::TextFormatted("{}", "hex.builtin.view.information.file_entropy"_lang); ImGuiExt::TextFormatted("{}", "hex.builtin.view.information.file_entropy"_lang);
ImGui::TableNextColumn(); ImGui::TableNextColumn();
if (m_averageEntropy < 0) if (m_averageEntropy < 0) {
ImGui::TextUnformatted("???"); ImGui::TextUnformatted("???");
else { } else {
auto entropy = std::abs(m_averageEntropy); auto entropy = std::abs(m_averageEntropy);
ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 0.1F); ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 0.1F);
ImGui::PushStyleColor(ImGuiCol_FrameBg, ImGui::GetColorU32(ImGuiCol_TableRowBgAlt)); ImGui::PushStyleColor(ImGuiCol_FrameBg, ImGui::GetColorU32(ImGuiCol_TableRowBgAlt));
@@ -333,9 +333,9 @@ namespace hex::plugin::builtin {
ImGui::TableNextColumn(); ImGui::TableNextColumn();
ImGuiExt::TextFormatted("{}", "hex.builtin.view.information.plain_text_percentage"_lang); ImGuiExt::TextFormatted("{}", "hex.builtin.view.information.plain_text_percentage"_lang);
ImGui::TableNextColumn(); ImGui::TableNextColumn();
if (m_plainTextCharacterPercentage < 0) if (m_plainTextCharacterPercentage < 0) {
ImGui::TextUnformatted("???"); ImGui::TextUnformatted("???");
else { } else {
ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 0.1F); ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 0.1F);
ImGui::PushStyleColor(ImGuiCol_FrameBg, ImGui::GetColorU32(ImGuiCol_TableRowBgAlt)); ImGui::PushStyleColor(ImGuiCol_FrameBg, ImGui::GetColorU32(ImGuiCol_TableRowBgAlt));
ImGui::PushStyleColor(ImGuiCol_PlotHistogram, ImColor::HSV(0.3F * (m_plainTextCharacterPercentage / 100.0F), 0.8F, 0.6F, 1.0F).Value); ImGui::PushStyleColor(ImGuiCol_PlotHistogram, ImColor::HSV(0.3F * (m_plainTextCharacterPercentage / 100.0F), 0.8F, 0.6F, 1.0F).Value);

View File

@@ -21,7 +21,7 @@ namespace hex::plugin::builtin {
ProjectFile::registerPerProviderHandler({ ProjectFile::registerPerProviderHandler({
.basePath = "patches.json", .basePath = "patches.json",
.required = false, .required = false,
.load = [](prv::Provider *provider, const std::fs::path &basePath, Tar &tar) { .load = [](prv::Provider *provider, const std::fs::path &basePath, const Tar &tar) {
auto json = nlohmann::json::parse(tar.readString(basePath)); auto json = nlohmann::json::parse(tar.readString(basePath));
auto patches = json.at("patches").get<std::map<u64, u8>>(); auto patches = json.at("patches").get<std::map<u64, u8>>();

View File

@@ -1,7 +1,6 @@
#include <content/views/view_pattern_data.hpp> #include <content/views/view_pattern_data.hpp>
#include <hex/api/content_registry.hpp> #include <hex/api/content_registry.hpp>
#include <hex/providers/provider.hpp>
#include <pl/patterns/pattern.hpp> #include <pl/patterns/pattern.hpp>
#include <wolv/utils/lock.hpp> #include <wolv/utils/lock.hpp>

View File

@@ -68,12 +68,13 @@ namespace hex::plugin::builtin {
paletteIndex = TextEditor::PaletteIndex::Default; paletteIndex = TextEditor::PaletteIndex::Default;
} else if (TokenizeCStyleIdentifier(inBegin, inEnd, outBegin, outEnd)) { } else if (TokenizeCStyleIdentifier(inBegin, inEnd, outBegin, outEnd)) {
paletteIndex = TextEditor::PaletteIndex::Identifier; paletteIndex = TextEditor::PaletteIndex::Identifier;
} else if (TokenizeCStyleNumber(inBegin, inEnd, outBegin, outEnd)) } else if (TokenizeCStyleNumber(inBegin, inEnd, outBegin, outEnd)) {
paletteIndex = TextEditor::PaletteIndex::Number; paletteIndex = TextEditor::PaletteIndex::Number;
else if (TokenizeCStyleCharacterLiteral(inBegin, inEnd, outBegin, outEnd)) } else if (TokenizeCStyleCharacterLiteral(inBegin, inEnd, outBegin, outEnd)) {
paletteIndex = TextEditor::PaletteIndex::CharLiteral; paletteIndex = TextEditor::PaletteIndex::CharLiteral;
else if (TokenizeCStyleString(inBegin, inEnd, outBegin, outEnd)) } else if (TokenizeCStyleString(inBegin, inEnd, outBegin, outEnd)) {
paletteIndex = TextEditor::PaletteIndex::String; paletteIndex = TextEditor::PaletteIndex::String;
}
return paletteIndex != TextEditor::PaletteIndex::Max; return paletteIndex != TextEditor::PaletteIndex::Max;
}; };
@@ -625,9 +626,9 @@ namespace hex::plugin::builtin {
}); });
const auto &patterns = [&, this] -> const auto& { const auto &patterns = [&, this] -> const auto& {
if (patternProvider->isReadable() && *m_executionDone) if (patternProvider->isReadable() && *m_executionDone) {
return runtime.getPatterns(id); return runtime.getPatterns(id);
else { } else {
static const std::vector<std::shared_ptr<pl::ptrn::Pattern>> empty; static const std::vector<std::shared_ptr<pl::ptrn::Pattern>> empty;
return empty; return empty;
} }
@@ -1150,9 +1151,9 @@ namespace hex::plugin::builtin {
if (newProvider != nullptr) { if (newProvider != nullptr) {
m_consoleEditor.SetTextLines(m_console.get(newProvider)); m_consoleEditor.SetTextLines(m_console.get(newProvider));
m_textEditor.SetText(wolv::util::trim(m_sourceCode.get(newProvider))); m_textEditor.SetText(wolv::util::trim(m_sourceCode.get(newProvider)));
} } else {
else
m_textEditor.SetText(""); m_textEditor.SetText("");
}
} else { } else {
m_hasUnevaluatedChanges = true; m_hasUnevaluatedChanges = true;
} }
@@ -1252,16 +1253,18 @@ namespace hex::plugin::builtin {
[&, this] { [&, this] {
if (ImGui::BeginMenu("hex.builtin.view.pattern_editor.menu.edit.place_pattern.builtin"_lang)) { if (ImGui::BeginMenu("hex.builtin.view.pattern_editor.menu.edit.place_pattern.builtin"_lang)) {
if (ImGui::BeginMenu("hex.builtin.view.pattern_editor.menu.edit.place_pattern.builtin.single"_lang)) { if (ImGui::BeginMenu("hex.builtin.view.pattern_editor.menu.edit.place_pattern.builtin.single"_lang)) {
for (const auto &[type, size] : Types) for (const auto &[type, size] : Types) {
if (ImGui::MenuItem(type)) if (ImGui::MenuItem(type))
appendVariable(type); appendVariable(type);
}
ImGui::EndMenu(); ImGui::EndMenu();
} }
if (ImGui::BeginMenu("hex.builtin.view.pattern_editor.menu.edit.place_pattern.builtin.array"_lang)) { if (ImGui::BeginMenu("hex.builtin.view.pattern_editor.menu.edit.place_pattern.builtin.array"_lang)) {
for (const auto &[type, size] : Types) for (const auto &[type, size] : Types) {
if (ImGui::MenuItem(type)) if (ImGui::MenuItem(type))
appendArray(type, size); appendArray(type, size);
}
ImGui::EndMenu(); ImGui::EndMenu();
} }
@@ -1366,7 +1369,7 @@ namespace hex::plugin::builtin {
ProjectFile::registerPerProviderHandler({ ProjectFile::registerPerProviderHandler({
.basePath = "pattern_source_code.hexpat", .basePath = "pattern_source_code.hexpat",
.required = false, .required = false,
.load = [this](prv::Provider *provider, const std::fs::path &basePath, Tar &tar) { .load = [this](prv::Provider *provider, const std::fs::path &basePath, const Tar &tar) {
std::string sourceCode = tar.readString(basePath); std::string sourceCode = tar.readString(basePath);
if (!m_syncPatternSourceCode) if (!m_syncPatternSourceCode)
@@ -1377,7 +1380,7 @@ namespace hex::plugin::builtin {
return true; return true;
}, },
.store = [this](prv::Provider *provider, const std::fs::path &basePath, Tar &tar) { .store = [this](prv::Provider *provider, const std::fs::path &basePath, const Tar &tar) {
std::string sourceCode; std::string sourceCode;
if (provider == ImHexApi::Provider::get()) if (provider == ImHexApi::Provider::get())

View File

@@ -359,8 +359,9 @@ namespace hex::plugin::builtin {
} }
category.downloadCallback(); category.downloadCallback();
} else } else {
log::error("Download failed! HTTP Code {}", response.getStatusCode()); log::error("Download failed! HTTP Code {}", response.getStatusCode());
}
m_download = {}; m_download = {};

View File

@@ -564,7 +564,7 @@ namespace hex::plugin::builtin {
crashFileData.value("logFile", ""), crashFileData.value("logFile", ""),
// Restore callback // Restore callback
[=] { [crashFileData, backupFilePath, hasProject, hasBackupFile] {
if (hasBackupFile) { if (hasBackupFile) {
ProjectFile::load(backupFilePath); ProjectFile::load(backupFilePath);
if (hasProject) { if (hasProject) {
@@ -595,8 +595,8 @@ namespace hex::plugin::builtin {
auto tipsCategories = nlohmann::json::parse(tipsData.string()); auto tipsCategories = nlohmann::json::parse(tipsData.string());
auto now = std::chrono::system_clock::now(); auto now = std::chrono::system_clock::now();
auto days_since_epoch = std::chrono::duration_cast<std::chrono::days>(now.time_since_epoch()); auto daysSinceEpoch = std::chrono::duration_cast<std::chrono::days>(now.time_since_epoch());
std::mt19937 random(days_since_epoch.count()); std::mt19937 random(daysSinceEpoch.count());
auto chosenCategory = tipsCategories[random()%tipsCategories.size()].at("tips"); auto chosenCategory = tipsCategories[random()%tipsCategories.size()].at("tips");
auto chosenTip = chosenCategory[random()%chosenCategory.size()]; auto chosenTip = chosenCategory[random()%chosenCategory.size()];

View File

@@ -108,7 +108,7 @@ namespace hex::plugin::hashes {
ProjectFile::registerPerProviderHandler({ ProjectFile::registerPerProviderHandler({
.basePath = "hashes.json", .basePath = "hashes.json",
.required = false, .required = false,
.load = [this](prv::Provider *provider, const std::fs::path &basePath, Tar &tar) -> bool { .load = [this](prv::Provider *provider, const std::fs::path &basePath, const Tar &tar) -> bool {
auto fileContent = tar.readString(basePath); auto fileContent = tar.readString(basePath);
if (fileContent.empty()) if (fileContent.empty())
return true; return true;
@@ -118,7 +118,7 @@ namespace hex::plugin::hashes {
return this->importHashes(provider, data); return this->importHashes(provider, data);
}, },
.store = [this](prv::Provider *provider, const std::fs::path &basePath, Tar &tar) -> bool { .store = [this](prv::Provider *provider, const std::fs::path &basePath, const Tar &tar) -> bool {
nlohmann::json data; nlohmann::json data;
bool result = this->exportHashes(provider, data); bool result = this->exportHashes(provider, data);

View File

@@ -22,7 +22,7 @@ namespace hex::ui {
virtual ~PatternDrawer() = default; virtual ~PatternDrawer() = default;
void draw(const std::vector<std::shared_ptr<pl::ptrn::Pattern>> &patterns, pl::PatternLanguage *runtime = nullptr, float height = 0.0F); void draw(const std::vector<std::shared_ptr<pl::ptrn::Pattern>> &patterns, const pl::PatternLanguage *runtime = nullptr, float height = 0.0F);
enum class TreeStyle { enum class TreeStyle {
Default = 0, Default = 0,

View File

@@ -24,9 +24,9 @@ namespace hex::ui {
ImGui::Text("%c", c); ImGui::Text("%c", c);
else else
ImGui::TextDisabled("."); ImGui::TextDisabled(".");
} } else {
else
ImGui::TextDisabled("."); ImGui::TextDisabled(".");
}
} }
bool drawEditing(u64 address, u8 *data, size_t size, bool upperCase, bool startedEditing) override { bool drawEditing(u64 address, u8 *data, size_t size, bool upperCase, bool startedEditing) override {
@@ -62,9 +62,9 @@ namespace hex::ui {
ImGui::PopID(); ImGui::PopID();
return userData.editingDone || ImGui::IsKeyPressed(ImGuiKey_Enter) || ImGui::IsKeyPressed(ImGuiKey_Escape); return userData.editingDone || ImGui::IsKeyPressed(ImGuiKey_Enter) || ImGui::IsKeyPressed(ImGuiKey_Escape);
} } else {
else
return false; return false;
}
} }
}; };
@@ -317,8 +317,8 @@ namespace hex::ui {
const auto innerRect = window->InnerRect; const auto innerRect = window->InnerRect;
const auto borderSize = window->WindowBorderSize; const auto borderSize = window->WindowBorderSize;
const auto scrollbarWidth = ImGui::GetStyle().ScrollbarSize; const auto scrollbarWidth = ImGui::GetStyle().ScrollbarSize;
const ImRect bb = ImRect(ImMax(outerRect.Min.x, outerRect.Max.x - borderSize - scrollbarWidth), innerRect.Min.y, outerRect.Max.x, innerRect.Max.y); const auto bb = ImRect(ImMax(outerRect.Min.x, outerRect.Max.x - borderSize - scrollbarWidth), innerRect.Min.y, outerRect.Max.x, innerRect.Max.y);
const ImDrawFlags roundingCorners = ImDrawFlags_RoundCornersTopRight | ImDrawFlags_RoundCornersBottomRight; const auto roundingCorners = ImDrawFlags_RoundCornersTopRight | ImDrawFlags_RoundCornersBottomRight;
if (numRows > 0) { if (numRows > 0) {
ImGui::ScrollbarEx( ImGui::ScrollbarEx(
@@ -363,9 +363,9 @@ namespace hex::ui {
if (m_showAscii) { if (m_showAscii) {
ImGui::TableSetupColumn("hex.ui.common.encoding.ascii"_lang, ImGuiTableColumnFlags_WidthFixed, (CharacterSize.x + m_characterCellPadding * 1_scaled) * m_bytesPerRow); ImGui::TableSetupColumn("hex.ui.common.encoding.ascii"_lang, ImGuiTableColumnFlags_WidthFixed, (CharacterSize.x + m_characterCellPadding * 1_scaled) * m_bytesPerRow);
} } else {
else
ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthFixed, 0); ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthFixed, 0);
}
ImGui::TableSetupColumn(""); ImGui::TableSetupColumn("");
// Custom encoding column // Custom encoding column
@@ -773,9 +773,9 @@ namespace hex::ui {
? hex::toByteString(selection.getSize()) ? hex::toByteString(selection.getSize())
: hex::format("{}", selection.getSize()) : hex::format("{}", selection.getSize())
); );
} } else {
else
value = std::string("hex.ui.hex_editor.selection.none"_lang); value = std::string("hex.ui.hex_editor.selection.none"_lang);
}
ImGuiExt::TextFormatted("{}:", "hex.ui.hex_editor.selection"_lang); ImGuiExt::TextFormatted("{}:", "hex.ui.hex_editor.selection"_lang);
ImGui::SameLine(); ImGui::SameLine();

View File

@@ -54,7 +54,7 @@ namespace hex::ui {
template<typename T> template<typename T>
auto highlightWhenSelected(u64 address, u64 size, const T &callback) { auto highlightWhenSelected(u64 address, u64 size, const T &callback) {
constexpr bool HasReturn = !requires(T t) { { t() } -> std::same_as<void>; }; constexpr static bool HasReturn = !requires(T t) { { t() } -> std::same_as<void>; };
auto selected = isPatternSelected(address, size); auto selected = isPatternSelected(address, size);
@@ -103,7 +103,7 @@ namespace hex::ui {
} }
void drawOffsetColumn(const pl::ptrn::Pattern& pattern) { void drawOffsetColumn(const pl::ptrn::Pattern& pattern) {
auto *bitfieldMember = dynamic_cast<pl::ptrn::PatternBitfieldMember const*>(&pattern); auto *bitfieldMember = dynamic_cast<const pl::ptrn::PatternBitfieldMember*>(&pattern);
if (bitfieldMember != nullptr && bitfieldMember->getParentBitfield() != nullptr) { if (bitfieldMember != nullptr && bitfieldMember->getParentBitfield() != nullptr) {
drawOffsetColumnForBitfieldMember(*bitfieldMember); drawOffsetColumnForBitfieldMember(*bitfieldMember);
return; return;
@@ -134,7 +134,7 @@ namespace hex::ui {
} }
void drawSizeColumn(const pl::ptrn::Pattern& pattern) { void drawSizeColumn(const pl::ptrn::Pattern& pattern) {
if (auto *bitfieldMember = dynamic_cast<pl::ptrn::PatternBitfieldMember const*>(&pattern); bitfieldMember != nullptr && bitfieldMember->getParentBitfield() != nullptr) if (auto *bitfieldMember = dynamic_cast<const pl::ptrn::PatternBitfieldMember*>(&pattern); bitfieldMember != nullptr && bitfieldMember->getParentBitfield() != nullptr)
drawSizeColumnForBitfieldMember(*bitfieldMember); drawSizeColumnForBitfieldMember(*bitfieldMember);
else else
ImGuiExt::TextFormatted("0x{0:04X}", pattern.getSize()); ImGuiExt::TextFormatted("0x{0:04X}", pattern.getSize());
@@ -179,9 +179,9 @@ namespace hex::ui {
return std::nullopt; return std::nullopt;
} }
break; break;
} else if (c == '.') } else if (c == '.') {
result.path.emplace_back(); result.path.emplace_back();
else if (c == '[') { } else if (c == '[') {
result.path.emplace_back(); result.path.emplace_back();
result.path.back() += c; result.path.back() += c;
} else if (c == ' ') { } else if (c == ' ') {
@@ -849,11 +849,11 @@ namespace hex::ui {
if (matchesFilter(m_filter.path, m_currPatternPath, false)) { if (matchesFilter(m_filter.path, m_currPatternPath, false)) {
if (m_filter.value.has_value()) { if (m_filter.value.has_value()) {
auto patternValue = pattern.getValue(); auto patternValue = pattern.getValue();
if (patternValue == m_filter.value) if (patternValue == m_filter.value) {
pattern.accept(*this); pattern.accept(*this);
else if (!matchesFilter(m_filter.path, m_currPatternPath, true)) } else if (!matchesFilter(m_filter.path, m_currPatternPath, true)) {
pattern.accept(*this); pattern.accept(*this);
else if (patternValue.isPattern() && m_filter.value->isString()) { } else if (patternValue.isPattern() && m_filter.value->isString()) {
if (patternValue.toString(true) == m_filter.value->toString(false)) if (patternValue.toString(true) == m_filter.value->toString(false))
pattern.accept(*this); pattern.accept(*this);
} }
@@ -1060,10 +1060,11 @@ namespace hex::ui {
return this->sortPatterns(sortSpecs, left, right); return this->sortPatterns(sortSpecs, left, right);
}); });
for (auto &pattern : sortedPatterns) for (auto &pattern : sortedPatterns) {
pattern->sort([this, &sortSpecs](const pl::ptrn::Pattern *left, const pl::ptrn::Pattern *right){ pattern->sort([this, &sortSpecs](const pl::ptrn::Pattern *left, const pl::ptrn::Pattern *right){
return this->sortPatterns(sortSpecs, left, right); return this->sortPatterns(sortSpecs, left, right);
}); });
}
sortSpecs->SpecsDirty = false; sortSpecs->SpecsDirty = false;
@@ -1082,7 +1083,7 @@ namespace hex::ui {
} }
} }
void PatternDrawer::draw(const std::vector<std::shared_ptr<pl::ptrn::Pattern>> &patterns, pl::PatternLanguage *runtime, float height) { void PatternDrawer::draw(const std::vector<std::shared_ptr<pl::ptrn::Pattern>> &patterns, const pl::PatternLanguage *runtime, float height) {
std::scoped_lock lock(s_resetDrawMutex); std::scoped_lock lock(s_resetDrawMutex);
const auto treeStyleButton = [this](auto icon, TreeStyle style, const char *tooltip) { const auto treeStyleButton = [this](auto icon, TreeStyle style, const char *tooltip) {
@@ -1141,10 +1142,10 @@ namespace hex::ui {
if (ImGui::BeginPopup("ExportPatterns")) { if (ImGui::BeginPopup("ExportPatterns")) {
for (const auto &formatter : m_formatters) { for (const auto &formatter : m_formatters) {
const auto name = [&]{ const auto name = [&]{
auto name = formatter->getName(); auto formatterName = formatter->getName();
std::transform(name.begin(), name.end(), name.begin(), [](char c){ return char(std::toupper(c)); }); std::transform(formatterName.begin(), formatterName.end(), formatterName.begin(), [](char c){ return char(std::toupper(c)); });
return name; return formatterName;
}(); }();
const auto &extension = formatter->getFileExtension(); const auto &extension = formatter->getFileExtension();
@@ -1170,17 +1171,17 @@ namespace hex::ui {
for (auto &pattern : patterns) { for (auto &pattern : patterns) {
std::vector<std::string> patternPath; std::vector<std::string> patternPath;
traversePatternTree(*pattern, patternPath, [&, this](const pl::ptrn::Pattern &pattern) { traversePatternTree(*pattern, patternPath, [&, this](const pl::ptrn::Pattern &currPattern) {
if (pattern.hasAttribute("hex::favorite")) if (currPattern.hasAttribute("hex::favorite"))
m_favorites.insert({ patternPath, pattern.clone() }); m_favorites.insert({ patternPath, currPattern.clone() });
if (const auto &args = pattern.getAttributeArguments("hex::group"); !args.empty()) { if (const auto &args = currPattern.getAttributeArguments("hex::group"); !args.empty()) {
auto groupName = args.front().toString(); auto groupName = args.front().toString();
if (!m_groups.contains(groupName)) if (!m_groups.contains(groupName))
m_groups.insert({groupName, std::vector<std::unique_ptr<pl::ptrn::Pattern>>()}); m_groups.insert({groupName, std::vector<std::unique_ptr<pl::ptrn::Pattern>>()});
m_groups[groupName].push_back(pattern.clone()); m_groups[groupName].push_back(currPattern.clone());
} }
}); });
@@ -1189,14 +1190,14 @@ namespace hex::ui {
task.update(); task.update();
patternPath.clear(); patternPath.clear();
traversePatternTree(*pattern, patternPath, [&, this](const pl::ptrn::Pattern &pattern) { traversePatternTree(*pattern, patternPath, [&, this](const pl::ptrn::Pattern &currPattern) {
for (auto &[path, favoritePattern] : m_favorites) { for (auto &[path, favoritePattern] : m_favorites) {
if (updatedFavorites == m_favorites.size()) if (updatedFavorites == m_favorites.size())
task.interrupt(); task.interrupt();
task.update(); task.update();
if (this->matchesFilter(patternPath, path, true)) { if (this->matchesFilter(patternPath, path, true)) {
favoritePattern = pattern.clone(); favoritePattern = currPattern.clone();
updatedFavorites += 1; updatedFavorites += 1;
break; break;
@@ -1309,9 +1310,10 @@ namespace hex::ui {
for (auto &[path, pattern] : m_favorites) for (auto &[path, pattern] : m_favorites)
pattern = nullptr; pattern = nullptr;
for (auto &[groupName, patterns]: m_groups) for (auto &[groupName, patterns]: m_groups) {
for (auto &pattern: patterns) for (auto &pattern: patterns)
pattern = nullptr; pattern = nullptr;
}
m_groups.clear(); m_groups.clear();

View File

@@ -579,18 +579,18 @@ namespace hex::plugin::visualizers {
void draw3DVisualizer(pl::ptrn::Pattern &, pl::ptrn::IIterable &, bool shouldReset, std::span<const pl::core::Token::Literal> arguments) { void draw3DVisualizer(pl::ptrn::Pattern &, pl::ptrn::IIterable &, bool shouldReset, std::span<const pl::core::Token::Literal> arguments) {
static gl::LightSourceVectors sourceVectors(20); static gl::LightSourceVectors sourceVectors(20);
static gl::VertexArray sourceVertexArray = gl::VertexArray(); static gl::VertexArray sourceVertexArray = {};
static gl::LightSourceBuffers sourceBuffers(sourceVertexArray, sourceVectors); static gl::LightSourceBuffers sourceBuffers(sourceVertexArray, sourceVectors);
static gl::VertexArray gridVertexArray = gl::VertexArray(); static gl::VertexArray gridVertexArray = {};
static gl::GridVectors gridVectors(9); static gl::GridVectors gridVectors(9);
static gl::GridBuffers gridBuffers(gridVertexArray, gridVectors); static gl::GridBuffers gridBuffers(gridVertexArray, gridVectors);
static gl::VertexArray axesVertexArray = gl::VertexArray(); static gl::VertexArray axesVertexArray = {};
static gl::AxesVectors axesVectors; static gl::AxesVectors axesVectors;
static gl::AxesBuffers axesBuffers(axesVertexArray, axesVectors); static gl::AxesBuffers axesBuffers(axesVertexArray, axesVectors);
static gl::VertexArray vertexArray = gl::VertexArray(); static gl::VertexArray vertexArray = {};
static Buffers buffers; static Buffers buffers;
static LineBuffers lineBuffers; static LineBuffers lineBuffers;

View File

@@ -2,13 +2,10 @@
#include <content/visualizer_helpers.hpp> #include <content/visualizer_helpers.hpp>
#include <implot.h>
#include <imgui.h> #include <imgui.h>
#include <hex/ui/imgui_imhex_extensions.h> #include <hex/ui/imgui_imhex_extensions.h>
#include <content/visualizer_helpers.hpp>
namespace hex::plugin::visualizers { namespace hex::plugin::visualizers {
void drawImageVisualizer(pl::ptrn::Pattern &, pl::ptrn::IIterable &, bool shouldReset, std::span<const pl::core::Token::Literal> arguments) { void drawImageVisualizer(pl::ptrn::Pattern &, pl::ptrn::IIterable &, bool shouldReset, std::span<const pl::core::Token::Literal> arguments) {

View File

@@ -3,7 +3,6 @@
#include <hex/api/content_registry.hpp> #include <hex/api/content_registry.hpp>
#include <hex/api/project_file_manager.hpp> #include <hex/api/project_file_manager.hpp>
#include <hex/helpers/utils.hpp>
#include <hex/helpers/fs.hpp> #include <hex/helpers/fs.hpp>
#include <toasts/toast_notification.hpp> #include <toasts/toast_notification.hpp>
@@ -16,7 +15,6 @@
#pragma GCC diagnostic pop #pragma GCC diagnostic pop
#include <filesystem> #include <filesystem>
#include <thread>
#include <wolv/io/file.hpp> #include <wolv/io/file.hpp>
#include <wolv/io/fs.hpp> #include <wolv/io/fs.hpp>
@@ -44,7 +42,7 @@ namespace hex::plugin::yara {
ProjectFile::registerPerProviderHandler({ ProjectFile::registerPerProviderHandler({
.basePath = "yara.json", .basePath = "yara.json",
.required = false, .required = false,
.load = [this](prv::Provider *provider, const std::fs::path &basePath, Tar &tar) -> bool { .load = [this](prv::Provider *provider, const std::fs::path &basePath, const Tar &tar) -> bool {
auto fileContent = tar.readString(basePath); auto fileContent = tar.readString(basePath);
if (fileContent.empty()) if (fileContent.empty())
return true; return true;
@@ -75,7 +73,7 @@ namespace hex::plugin::yara {
return true; return true;
}, },
.store = [this](prv::Provider *provider, const std::fs::path &basePath, Tar &tar) -> bool { .store = [this](prv::Provider *provider, const std::fs::path &basePath, const Tar &tar) -> bool {
nlohmann::json data; nlohmann::json data;
data["rules"] = nlohmann::json::array(); data["rules"] = nlohmann::json::array();
@@ -233,13 +231,14 @@ namespace hex::plugin::yara {
ImGuiListClipper clipper; ImGuiListClipper clipper;
clipper.Begin(m_consoleMessages.size()); clipper.Begin(m_consoleMessages.size());
while (clipper.Step()) while (clipper.Step()) {
for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) { for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) {
const auto &message = m_consoleMessages[i]; const auto &message = m_consoleMessages[i];
if (ImGui::Selectable(message.c_str())) if (ImGui::Selectable(message.c_str()))
ImGui::SetClipboardText(message.c_str()); ImGui::SetClipboardText(message.c_str());
} }
}
} }
ImGui::EndChild(); ImGui::EndChild();
} }

View File

@@ -35,12 +35,12 @@ TEST_SEQUENCE("EncodeDecode16") {
std::random_device rd; std::random_device rd;
std::mt19937 gen(rd()); std::mt19937 gen(rd());
std::uniform_int_distribution<> dataLen(0, 1024); std::uniform_int_distribution dataLen(0, 1024);
std::uniform_int_distribution<u8> data; std::uniform_int_distribution<u8> data;
for (int i = 0; i < 1000; i++) { for (int i = 0; i < 1000; i++) {
std::vector<u8> original(dataLen(gen)); std::vector<u8> original(dataLen(gen));
std::generate(std::begin(original), std::end(original), [&]() { return data(gen); }); std::generate(std::begin(original), std::end(original), [&] { return data(gen); });
auto encoded = hex::crypt::encode16(original); auto encoded = hex::crypt::encode16(original);
auto decoded = hex::crypt::decode16(encoded); auto decoded = hex::crypt::decode16(encoded);
@@ -85,12 +85,12 @@ TEST_SEQUENCE("EncodeDecode64") {
std::random_device rd; std::random_device rd;
std::mt19937 gen(rd()); std::mt19937 gen(rd());
std::uniform_int_distribution<> dataLen(0, 1024); std::uniform_int_distribution dataLen(0, 1024);
std::uniform_int_distribution<u8> data; std::uniform_int_distribution<u8> data;
for (int i = 0; i < 1000; i++) { for (int i = 0; i < 1000; i++) {
std::vector<u8> original(dataLen(gen)); std::vector<u8> original(dataLen(gen));
std::generate(std::begin(original), std::end(original), [&]() { return data(gen); }); std::generate(std::begin(original), std::end(original), [&] { return data(gen); });
auto encoded = vectorToString(hex::crypt::encode64(original)); auto encoded = vectorToString(hex::crypt::encode64(original));
auto decoded = hex::crypt::decode64(stringToVector(encoded)); auto decoded = hex::crypt::decode64(stringToVector(encoded));
@@ -147,7 +147,7 @@ TEST_SEQUENCE("EncodeDecodeLEB128") {
for (int i = 0; i < 1000; i++) { for (int i = 0; i < 1000; i++) {
std::vector<u8> original(sizeof(u128)); std::vector<u8> original(sizeof(u128));
std::generate(std::begin(original), std::end(original), [&]() { return data(gen); }); std::generate(std::begin(original), std::end(original), [&] { return data(gen); });
u128 u = *reinterpret_cast<u128*>(original.data()); u128 u = *reinterpret_cast<u128*>(original.data());
i128 s = *reinterpret_cast<i128*>(original.data()); i128 s = *reinterpret_cast<i128*>(original.data());
auto encodedS = hex::crypt::encodeSleb128(s); auto encodedS = hex::crypt::encodeSleb128(s);
@@ -192,14 +192,14 @@ int checkCrcAgainstRandomData(Func func, int width) {
std::random_device rd; std::random_device rd;
std::mt19937 gen(rd()); std::mt19937 gen(rd());
std::uniform_int_distribution<> distribLen(0, 1024); std::uniform_int_distribution distribLen(0, 1024);
std::uniform_int_distribution<uint64_t> distribPoly(0, (0b10ull << (width - 1)) - 1); std::uniform_int_distribution<uint64_t> distribPoly(0, (0b10ull << (width - 1)) - 1);
std::uniform_int_distribution<u8> distribData; std::uniform_int_distribution<u8> distribData;
for (int i = 0; i < 500; i++) { for (int i = 0; i < 500; i++) {
CrcCheck c { "", width, distribPoly(gen), distribPoly(gen), 0, false, false, 0, {} }; CrcCheck c { "", width, distribPoly(gen), distribPoly(gen), 0, false, false, 0, {} };
c.data.resize(distribLen(gen)); c.data.resize(distribLen(gen));
std::generate(std::begin(c.data), std::end(c.data), [&]() { return distribData(gen); }); std::generate(std::begin(c.data), std::end(c.data), [&] { return distribData(gen); });
hex::test::TestProvider testprovider(&c.data); hex::test::TestProvider testprovider(&c.data);
hex::prv::Provider *provider = &testprovider; hex::prv::Provider *provider = &testprovider;

View File

@@ -1,7 +1,6 @@
#include <hex/test/tests.hpp> #include <hex/test/tests.hpp>
#include <wolv/io/file.hpp> #include <wolv/io/file.hpp>
#include <hex/helpers/fs.hpp>
using namespace std::literals::string_literals; using namespace std::literals::string_literals;

View File

@@ -3,7 +3,6 @@
#include <hex/api_urls.hpp> #include <hex/api_urls.hpp>
#include <hex/helpers/http_requests.hpp> #include <hex/helpers/http_requests.hpp>
#include <wolv/io/file.hpp> #include <wolv/io/file.hpp>
#include <hex/helpers/fs.hpp>
using namespace std::literals::string_literals; using namespace std::literals::string_literals;