chore: apply light lints (#2570)

This commit is contained in:
iTrooz
2025-12-19 23:49:37 +01:00
committed by GitHub
parent 92cfdf1145
commit 261610dcf1
72 changed files with 477 additions and 447 deletions

View File

@@ -1,3 +1,8 @@
# Disabled rules should have a comment associated
# Or at least an empty comment # to show they were put here explicitely,
# and not as part of the historical CLion-generated rules
# Note: `- -X` means disable X
Checks: Checks:
- -* - -*
- mpi-* - mpi-*
@@ -22,11 +27,11 @@ Checks:
- cert-dcl58-cpp - cert-dcl58-cpp
- cert-flp30-c - cert-flp30-c
- cppcoreguidelines-avoid-const-or-ref-data-members - cppcoreguidelines-avoid-const-or-ref-data-members
- cppcoreguidelines-pro-type-member-init - cppcoreguidelines-pro-type-member-init # We want to use default member initializers
- cppcoreguidelines-slicing - cppcoreguidelines-slicing
- cppcoreguidelines-interfaces-global-init - cppcoreguidelines-interfaces-global-init
- cppcoreguidelines-pro-type-static-cast-downcast - cppcoreguidelines-pro-type-static-cast-downcast
- cppcoreguidelines-narrowing-conversions - -cppcoreguidelines-narrowing-conversions #
- google-default-arguments - google-default-arguments
- google-runtime-operator - google-runtime-operator
- google-explicit-constructor - google-explicit-constructor
@@ -43,8 +48,11 @@ Checks:
- -misc-static-assert - -misc-static-assert
- -misc-no-recursion - -misc-no-recursion
- -misc-const-correctness - -misc-const-correctness
- -misc-use-internal-linkage # False positives if header where function is defined is not included
- -misc-include-cleaner # Allow indirect includes
- modernize-* - modernize-*
- -modernize-use-trailing-return-type - -modernize-use-trailing-return-type
- -modernize-use-std-print # We want to use fmt::print instead
- openmp-use-default-none - openmp-use-default-none
- performance-* - performance-*
- -performance-no-int-to-ptr - -performance-no-int-to-ptr
@@ -64,5 +72,31 @@ Checks:
- -readability-redundant-access-specifiers - -readability-redundant-access-specifiers
- -readability-function-cognitive-complexity - -readability-function-cognitive-complexity
- -readability-identifier-naming - -readability-identifier-naming
- '*-include-cleaner'
- -readability-qualified-auto - -readability-qualified-auto
- -readability-use-std-min-max # Less readable imo
- -readability-math-missing-parentheses # Basic math
- -readability-implicit-bool-conversion # Not much of a problem ?
- -readability-convert-member-functions-to-static #
- -readability-use-concise-preprocessor-directives # We do not use #ifdef
- -readability-uppercase-literal-suffix # Not important enough
- -readability-static-accessed-through-instance
- '*-include-cleaner'
# idk
# Will check later if useful or not
- -readability-make-member-function-const # to make functions const. Seems to not catch everything ?
- -misc-unconventional-assign-operator
- -bugprone-unchecked-optional-access
- -modernize-avoid-c-arrays
- -misc-non-private-member-variables-in-classes
- -performance-move-const-arg
- -bugprone-suspicious-stringview-data-usage
- -cert-err34-c
- -hicpp-exception-baseclass
- -modernize-use-integer-sign-comparison
- -performance-for-range-copy
- -performance-unnecessary-value-param
- -bugprone-empty-catch
- -bugprone-multi-level-implicit-pointer-conversion
- -modernize-pass-by-value

View File

@@ -16,7 +16,7 @@ EXPORT_MODULE namespace hex {
void stopServices(); void stopServices();
} }
void registerService(const UnlocalizedString &unlocalizedString, const impl::Callback &callback); void registerService(const UnlocalizedString &unlocalizedName, const impl::Callback &callback);
} }
} }

View File

@@ -10,6 +10,7 @@
#include <span> #include <span>
#include <string> #include <string>
#include <numbers> #include <numbers>
#include <array>
#include <opengl_support.h> #include <opengl_support.h>
#include "imgui.h" #include "imgui.h"
@@ -935,7 +936,7 @@ namespace hex::gl {
void attachTexture(const Texture &texture) const; void attachTexture(const Texture &texture) const;
private: private:
GLuint m_frameBuffer, m_renderBuffer; GLuint m_frameBuffer = 0, m_renderBuffer = 0;
}; };
class AxesVectors { class AxesVectors {

View File

@@ -264,8 +264,7 @@ namespace hex {
} }
} }
if (json.empty()) if (json.empty()) return;
return;
#if defined(OS_WEB) #if defined(OS_WEB)
auto data = json.dump(); auto data = json.dump();

View File

@@ -1,3 +1,4 @@
#include <algorithm>
#include <hex/api/event_manager.hpp> #include <hex/api/event_manager.hpp>
namespace hex { namespace hex {
@@ -35,7 +36,7 @@ namespace hex {
void EventManager::unsubscribe(void *token, impl::EventId id) { void EventManager::unsubscribe(void *token, impl::EventId id) {
auto &tokenStore = getTokenStore(); auto &tokenStore = getTokenStore();
auto iter = std::find_if(tokenStore.begin(), tokenStore.end(), [&](auto &item) { auto iter = std::ranges::find_if(tokenStore, [&](auto &item) {
return item.first == token && item.second->first == id; return item.first == token && item.second->first == id;
}); });

View File

@@ -50,7 +50,7 @@ namespace hex {
definition.fallbackLanguageId = item["fallback"].get<std::string>(); definition.fallbackLanguageId = item["fallback"].get<std::string>();
} }
if (item.contains("hidden") && item["hidden"].get<bool>() == true) { if (item.contains("hidden") && item["hidden"].get<bool>()) {
definition.hidden = true; definition.hidden = true;
} }
@@ -155,7 +155,7 @@ namespace hex {
static AutoReset<std::unordered_map<std::size_t, std::string>> loadedLocalization; static AutoReset<std::unordered_map<std::size_t, std::string>> loadedLocalization;
static std::mutex mutex; static std::mutex mutex;
std::lock_guard lock(mutex); std::scoped_lock lock(mutex);
if (*currentLanguageId != languageId) { if (*currentLanguageId != languageId) {
currentLanguageId = languageId; currentLanguageId = languageId;
loadedLocalization->clear(); loadedLocalization->clear();

View File

@@ -85,7 +85,7 @@ namespace hex {
} }
Plugin::Plugin(const std::string &name, const hex::PluginFunctions &functions) : Plugin::Plugin(const std::string &name, const hex::PluginFunctions &functions) :
m_handle(0), m_path(name), m_addedManually(true), m_functions(functions) { } m_path(name), m_addedManually(true), m_functions(functions) { }
Plugin::Plugin(Plugin &&other) noexcept { Plugin::Plugin(Plugin &&other) noexcept {

View File

@@ -7,7 +7,7 @@ namespace hex {
namespace { namespace {
void skipWhitespace(std::string_view &string) { void skipWhitespace(std::string_view &string) {
while (string.length() > 0) { while (!string.empty()) {
if (!std::isspace(string.front())) if (!std::isspace(string.front()))
break; break;
string = string.substr(1); string = string.substr(1);
@@ -89,7 +89,7 @@ namespace hex {
return { }; return { };
bool inString = false; bool inString = false;
while (string.length() > 0) { while (!string.empty()) {
BinaryPattern::Pattern pattern = { 0, 0 }; BinaryPattern::Pattern pattern = { 0, 0 };
if (string.starts_with("\"")) { if (string.starts_with("\"")) {

View File

@@ -1,3 +1,4 @@
#include <algorithm>
#include <hex/helpers/default_paths.hpp> #include <hex/helpers/default_paths.hpp>
#include <hex/api/imhex_api/system.hpp> #include <hex/api/imhex_api/system.hpp>
@@ -39,7 +40,7 @@ namespace hex::paths {
paths.push_back(xdg::DataHomeDir()); paths.push_back(xdg::DataHomeDir());
auto dataDirs = xdg::DataDirs(); auto dataDirs = xdg::DataDirs();
std::copy(dataDirs.begin(), dataDirs.end(), std::back_inserter(paths)); std::ranges::copy(dataDirs, std::back_inserter(paths));
#endif #endif
@@ -108,7 +109,7 @@ namespace hex::paths {
// Add the system plugin directory to the path if one was provided at compile time // Add the system plugin directory to the path if one was provided at compile time
#if defined(OS_LINUX) && defined(SYSTEM_PLUGINS_LOCATION) #if defined(OS_LINUX) && defined(SYSTEM_PLUGINS_LOCATION)
paths.push_back(SYSTEM_PLUGINS_LOCATION); paths.emplace_back(SYSTEM_PLUGINS_LOCATION);
#endif #endif
return paths; return paths;

View File

@@ -2,6 +2,7 @@
#include <hex/helpers/utils.hpp> #include <hex/helpers/utils.hpp>
#include <ranges>
#include <wolv/io/file.hpp> #include <wolv/io/file.hpp>
#include <wolv/utils/string.hpp> #include <wolv/utils/string.hpp>
@@ -89,9 +90,7 @@ namespace hex {
std::pair<std::string_view, size_t> EncodingFile::getEncodingFor(std::span<const u8> buffer) const { std::pair<std::string_view, size_t> EncodingFile::getEncodingFor(std::span<const u8> buffer) const {
for (auto riter = m_mapping->crbegin(); riter != m_mapping->crend(); ++riter) { for (auto [size, mapping] : std::ranges::reverse_view(*m_mapping)) {
const auto &[size, mapping] = *riter;
if (size > buffer.size()) continue; if (size > buffer.size()) continue;
std::vector key(buffer.begin(), buffer.begin() + size); std::vector key(buffer.begin(), buffer.begin() + size);
@@ -103,9 +102,7 @@ namespace hex {
} }
u64 EncodingFile::getEncodingLengthFor(std::span<u8> buffer) const { u64 EncodingFile::getEncodingLengthFor(std::span<u8> buffer) const {
for (auto riter = m_mapping->crbegin(); riter != m_mapping->crend(); ++riter) { for (auto [size, mapping] : std::ranges::reverse_view(*m_mapping)) {
const auto &[size, mapping] = *riter;
if (size > buffer.size()) continue; if (size > buffer.size()) continue;
std::vector key(buffer.begin(), buffer.begin() + size); std::vector key(buffer.begin(), buffer.begin() + size);

View File

@@ -13,8 +13,6 @@
#include <xdg.hpp> #include <xdg.hpp>
# if defined(OS_FREEBSD) # if defined(OS_FREEBSD)
#include <sys/syslimits.h> #include <sys/syslimits.h>
# else
#include <limits.h>
# endif # endif
#endif #endif

View File

@@ -1,9 +1,14 @@
#include <cstddef>
#include "wolv/types.hpp"
#include <cmath>
#include <hex/helpers/opengl.hpp> #include <hex/helpers/opengl.hpp>
#include <opengl_support.h> #include <opengl_support.h>
#include <hex/helpers/utils.hpp>
#include <hex/helpers/logger.hpp> #include <hex/helpers/logger.hpp>
#include <string_view>
#include <vector>
#include <span>
#include <wolv/utils/guards.hpp> #include <wolv/utils/guards.hpp>
#include <numbers> #include <numbers>

View File

@@ -1,3 +1,4 @@
#include <algorithm>
#include <hex/helpers/patches.hpp> #include <hex/helpers/patches.hpp>
#include <hex/helpers/utils.hpp> #include <hex/helpers/utils.hpp>
@@ -5,7 +6,6 @@
#include <hex/providers/provider.hpp> #include <hex/providers/provider.hpp>
#include <cstring> #include <cstring>
#include <string_view>
namespace hex { namespace hex {
@@ -83,7 +83,7 @@ namespace hex {
[[nodiscard]] UnlocalizedString getTypeName() const override { return ""; } [[nodiscard]] UnlocalizedString getTypeName() const override { return ""; }
const std::map<u64, u8>& getPatches() const { [[nodiscard]] const std::map<u64, u8>& getPatches() const {
return m_patches; return m_patches;
} }
private: private:
@@ -92,7 +92,7 @@ namespace hex {
void pushStringBack(std::vector<u8> &buffer, const std::string &string) { void pushStringBack(std::vector<u8> &buffer, const std::string &string) {
std::copy(string.begin(), string.end(), std::back_inserter(buffer)); std::ranges::copy(string, std::back_inserter(buffer));
} }
template<typename T> template<typename T>

View File

@@ -14,7 +14,7 @@
namespace hex { namespace hex {
UDPServer::UDPServer(u16 port, Callback callback) UDPServer::UDPServer(u16 port, Callback callback)
: m_port(port), m_callback(std::move(callback)), m_running(false), m_socketFd(-1) { : m_port(port), m_callback(std::move(callback)), m_running(false) {
} }
UDPServer::~UDPServer() { UDPServer::~UDPServer() {

View File

@@ -1,3 +1,4 @@
#include <algorithm>
#include <cwchar> #include <cwchar>
#include <hex/helpers/utils.hpp> #include <hex/helpers/utils.hpp>
@@ -98,7 +99,7 @@ namespace hex {
string = wolv::util::replaceStrings(string, ",", ""); string = wolv::util::replaceStrings(string, ",", "");
// Check for non-hex characters // Check for non-hex characters
bool isValidHexString = std::find_if(string.begin(), string.end(), [](char c) { bool isValidHexString = std::ranges::find_if(string, [](char c) {
return !std::isxdigit(c) && !std::isspace(c); return !std::isxdigit(c) && !std::isspace(c);
}) == string.end(); }) == string.end();
@@ -824,10 +825,10 @@ namespace hex {
if (lang.has_value() && !lang->empty() && *lang != "C" && *lang != "C.UTF-8") { if (lang.has_value() && !lang->empty() && *lang != "C" && *lang != "C.UTF-8") {
auto parts = wolv::util::splitString(*lang, "."); auto parts = wolv::util::splitString(*lang, ".");
if (parts.size() > 0) if (!parts.empty())
return parts[0]; return parts[0];
else else
return *lang; return lang;
} }
return std::nullopt; return std::nullopt;

View File

@@ -10,13 +10,14 @@ namespace hex {
void executeCmd(const std::vector<std::string> &argsVector) { void executeCmd(const std::vector<std::string> &argsVector) {
std::vector<char*> cArgsVector; std::vector<char*> cArgsVector;
for (const auto &str : argsVector) { cArgsVector.reserve(argsVector.size());
for (const auto &str : argsVector) {
cArgsVector.push_back(const_cast<char*>(str.c_str())); cArgsVector.push_back(const_cast<char*>(str.c_str()));
} }
cArgsVector.push_back(nullptr); cArgsVector.push_back(nullptr);
if (fork() == 0) { if (fork() == 0) {
execvp(cArgsVector[0], &cArgsVector[0]); execvp(cArgsVector[0], cArgsVector.data());
log::error("execvp() failed: {}", strerror(errno)); log::error("execvp() failed: {}", strerror(errno));
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }

View File

@@ -1516,9 +1516,9 @@ namespace ImGuiExt {
bool IsDarkBackground(const ImColor& bgColor) { bool IsDarkBackground(const ImColor& bgColor) {
// Extract RGB components in 0255 range // Extract RGB components in 0255 range
int r = static_cast<int>(bgColor.Value.x * 255.0f); int r = static_cast<int>(bgColor.Value.x * 255.0F);
int g = static_cast<int>(bgColor.Value.y * 255.0f); int g = static_cast<int>(bgColor.Value.y * 255.0F);
int b = static_cast<int>(bgColor.Value.z * 255.0f); int b = static_cast<int>(bgColor.Value.z * 255.0F);
// Compute brightness using perceived luminance // Compute brightness using perceived luminance
int brightness = (r * 299 + g * 587 + b * 114) / 1000; int brightness = (r * 299 + g * 587 + b * 114) / 1000;

View File

@@ -22,6 +22,5 @@ namespace hex::trace {
}; };
StackTraceResult getStackTrace(); StackTraceResult getStackTrace();
[[nodiscard]] std::string demangle(const std::string &mangledName); [[nodiscard]] std::string demangle(const std::string &symbolName);
}
}

View File

@@ -218,7 +218,7 @@ static std::mutex s_traceMutex;
} }
StackTraceResult getStackTrace() { StackTraceResult getStackTrace() {
std::lock_guard lock(s_traceMutex); std::scoped_lock lock(s_traceMutex);
static std::vector<StackFrame> result; static std::vector<StackFrame> result;

View File

@@ -35,7 +35,7 @@
while (true) { while (true) {
const auto result = splashWindow->loop(); const auto result = splashWindow->loop();
if (result.has_value()) { if (result.has_value()) {
if (result.value() == false) { if (!result.value()) {
ImHexApi::System::impl::addInitArgument("tasks-failed"); ImHexApi::System::impl::addInitArgument("tasks-failed");
} }

View File

@@ -40,7 +40,7 @@ namespace hex::init {
WindowSplash::WindowSplash() : m_window(nullptr) { WindowSplash::WindowSplash() : m_window(nullptr) {
RequestAddInitTask::subscribe([this](const std::string& name, bool async, const TaskFunction &function){ RequestAddInitTask::subscribe([this](const std::string& name, bool async, const TaskFunction &function){
std::lock_guard guard(m_progressMutex); std::scoped_lock guard(m_progressMutex);
m_tasks.push_back(Task{ name, function, async, false }); m_tasks.push_back(Task{ name, function, async, false });
m_totalTaskCount += 1; m_totalTaskCount += 1;
@@ -210,14 +210,14 @@ namespace hex::init {
// Save an iterator to the current task name // Save an iterator to the current task name
decltype(m_currTaskNames)::iterator taskNameIter; decltype(m_currTaskNames)::iterator taskNameIter;
{ {
std::lock_guard guard(m_progressMutex); std::scoped_lock guard(m_progressMutex);
m_currTaskNames.push_back(task.name + "..."); m_currTaskNames.push_back(task.name + "...");
taskNameIter = std::prev(m_currTaskNames.end()); taskNameIter = std::prev(m_currTaskNames.end());
} }
// When the task finished, increment the progress bar // When the task finished, increment the progress bar
ON_SCOPE_EXIT { ON_SCOPE_EXIT {
std::lock_guard guard(m_progressMutex); std::scoped_lock guard(m_progressMutex);
m_completedTaskCount += 1; m_completedTaskCount += 1;
m_progress = float(m_completedTaskCount) / float(m_totalTaskCount); m_progress = float(m_completedTaskCount) / float(m_totalTaskCount);
}; };
@@ -239,7 +239,7 @@ namespace hex::init {
// Erase the task name from the list of running tasks // Erase the task name from the list of running tasks
{ {
std::lock_guard guard(m_progressMutex); std::scoped_lock guard(m_progressMutex);
m_currTaskNames.erase(taskNameIter); m_currTaskNames.erase(taskNameIter);
} }
} catch (const std::exception &e) { } catch (const std::exception &e) {
@@ -272,11 +272,11 @@ namespace hex::init {
// Check every 10ms if all tasks have run // Check every 10ms if all tasks have run
while (true) { while (true) {
// Loop over all registered init tasks // Loop over all registered init tasks
for (auto it = m_tasks.begin(); it != m_tasks.end(); ++it) { for (auto & m_task : m_tasks) {
// Construct a new task callback // Construct a new task callback
if (!it->running) { if (!m_task.running) {
this->createTask(*it); this->createTask(m_task);
it->running = true; m_task.running = true;
} }
} }
@@ -396,7 +396,7 @@ namespace hex::init {
// Draw the task progress bar // Draw the task progress bar
{ {
std::lock_guard guard(m_progressMutex); std::scoped_lock guard(m_progressMutex);
const auto progressBackgroundStart = ImVec2(99, 357); const auto progressBackgroundStart = ImVec2(99, 357);
const auto progressBackgroundSize = ImVec2(442, 30); const auto progressBackgroundSize = ImVec2(442, 30);

View File

@@ -64,7 +64,7 @@ int main(int argc, char **argv) {
#if defined(OS_LINUX) #if defined(OS_LINUX)
if (auto distro = ImHexApi::System::getLinuxDistro(); distro.has_value()) { if (auto distro = ImHexApi::System::getLinuxDistro(); distro.has_value()) {
log::info("Linux distribution: {}. Version: {}", distro->name, distro->version == "" ? "None" : distro->version); log::info("Linux distribution: {}. Version: {}", distro->name, distro->version.empty() ? "None" : distro->version);
} }
#endif #endif

View File

@@ -1,6 +1,5 @@
#if defined(OS_LINUX) #if defined(OS_LINUX)
#include <stdexcept>
#include <fcntl.h> #include <fcntl.h>
#include <sys/file.h> #include <sys/file.h>
#include <unistd.h> #include <unistd.h>
@@ -25,7 +24,7 @@ namespace hex::messaging {
fullEventData.insert(fullEventData.end(), args.begin(), args.end()); fullEventData.insert(fullEventData.end(), args.begin(), args.end());
u8 *data = &fullEventData[0]; u8 *data = fullEventData.data();
auto dataSize = fullEventData.size(); auto dataSize = fullEventData.size();
int fifo = open(CommunicationPipePath, O_WRONLY); int fifo = open(CommunicationPipePath, O_WRONLY);

View File

@@ -20,7 +20,6 @@
#include <GLFW/glfw3.h> #include <GLFW/glfw3.h>
#include <imgui_impl_glfw.h> #include <imgui_impl_glfw.h>
#include <string.h>
#include <ranges> #include <ranges>
#if defined(IMHEX_HAS_FONTCONFIG) #if defined(IMHEX_HAS_FONTCONFIG)

View File

@@ -25,8 +25,6 @@
#include <hex/ui/banner.hpp> #include <hex/ui/banner.hpp>
#include <cmath> #include <cmath>
#include <chrono>
#include <csignal>
#include <numbers> #include <numbers>
#include <romfs/romfs.hpp> #include <romfs/romfs.hpp>
@@ -663,7 +661,7 @@ namespace hex {
const auto windowPos = ImHexApi::System::getMainWindowPosition(); const auto windowPos = ImHexApi::System::getMainWindowPosition();
float startY = windowPos.y + ImGui::GetTextLineHeight() + ((ImGui::GetTextLineHeight() + (ImGui::GetStyle().FramePadding.y * 2.0F)) * (onWelcomeScreen ? 1 : 2)); float startY = windowPos.y + ImGui::GetTextLineHeight() + ((ImGui::GetTextLineHeight() + (ImGui::GetStyle().FramePadding.y * 2.0F)) * (onWelcomeScreen ? 1 : 2));
const auto height = ImGui::GetTextLineHeightWithSpacing() * 1.5f; const auto height = ImGui::GetTextLineHeightWithSpacing() * 1.5F;
// Offset banner based on the size of the title bar. On macOS, it's slightly taller // Offset banner based on the size of the title bar. On macOS, it's slightly taller
#if defined(OS_MACOS) #if defined(OS_MACOS)
@@ -956,13 +954,13 @@ namespace hex {
GLuint quadVAO, quadVBO; GLuint quadVAO, quadVBO;
float quadVertices[] = { float quadVertices[] = {
// positions // texCoords // positions // texCoords
-1.0f, 1.0f, 0.0f, 1.0f, -1.0F, 1.0F, 0.0F, 1.0F,
-1.0f, -1.0f, 0.0f, 0.0f, -1.0F, -1.0F, 0.0F, 0.0F,
1.0f, -1.0f, 1.0f, 0.0f, 1.0F, -1.0F, 1.0F, 0.0F,
-1.0f, 1.0f, 0.0f, 1.0f, -1.0F, 1.0F, 0.0F, 1.0F,
1.0f, -1.0f, 1.0f, 0.0f, 1.0F, -1.0F, 1.0F, 0.0F,
1.0f, 1.0f, 1.0f, 1.0f 1.0F, 1.0F, 1.0F, 1.0F
}; };
glGenVertexArrays(1, &quadVAO); glGenVertexArrays(1, &quadVAO);
@@ -971,7 +969,7 @@ namespace hex {
glBindBuffer(GL_ARRAY_BUFFER, quadVBO); glBindBuffer(GL_ARRAY_BUFFER, quadVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(quadVertices), quadVertices, GL_STATIC_DRAW); glBufferData(GL_ARRAY_BUFFER, sizeof(quadVertices), quadVertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0); glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void*)0); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), nullptr);
glEnableVertexAttribArray(1); glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void*)(2 * sizeof(float))); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void*)(2 * sizeof(float)));
glBindVertexArray(0); glBindVertexArray(0);

View File

@@ -158,7 +158,7 @@ bool installUpdate(const std::fs::path &updatePath) {
UpdateHandler { ".deb", "zenity --password | sudo -S apt install -y --fix-broken \"{}\"" }, UpdateHandler { ".deb", "zenity --password | sudo -S apt install -y --fix-broken \"{}\"" },
UpdateHandler { ".rpm", "zenity --password | sudo -S rpm -i \"{}\"" }, UpdateHandler { ".rpm", "zenity --password | sudo -S rpm -i \"{}\"" },
UpdateHandler { ".pkg.tar.zst", "zenity --password | sudo -S pacman -Syy && sudo pacman -U --noconfirm \"{}\"" }, UpdateHandler { ".pkg.tar.zst", "zenity --password | sudo -S pacman -Syy && sudo pacman -U --noconfirm \"{}\"" },
UpdateHandler { ".AppImage", fmt::format("zenity --password | sudo -S cp \"{{}}\" \"{}\"", hex::getEnvironmentVariable("APPIMAGE").value_or("")) }, UpdateHandler { ".AppImage", fmt::format(R"(zenity --password | sudo -S cp "{{}}" "{}")", hex::getEnvironmentVariable("APPIMAGE").value_or("")) },
UpdateHandler { ".flatpak", "zenity --password | sudo -S flatpak install -y --reinstall \"{}\"" }, UpdateHandler { ".flatpak", "zenity --password | sudo -S flatpak install -y --reinstall \"{}\"" },
UpdateHandler { ".snap", "zenity --password | sudo -S snap install --dangerous \"{}\"" }, UpdateHandler { ".snap", "zenity --password | sudo -S snap install --dangerous \"{}\"" },
}; };

View File

@@ -12,7 +12,7 @@ namespace hex::plugin::builtin {
[[nodiscard]] UnlocalizedString getTitle() const override; [[nodiscard]] UnlocalizedString getTitle() const override;
private: private:
static void resize(size_t newSize); void resize(size_t newSize);
u64 m_size; u64 m_size;
}; };
} }

View File

@@ -66,7 +66,7 @@ namespace hex::plugin::builtin {
private: private:
void handleFileChange(); void handleFileChange();
OpenResult open(bool memoryMapped); OpenResult open(bool directAccess);
protected: protected:
std::fs::path m_path; std::fs::path m_path;

View File

@@ -191,7 +191,7 @@ namespace hex::plugin::builtin {
void renderErrors(); void renderErrors();
/// A token range is the set of token indices of a definition. The namespace token /// A token range is the set of token indices of a definition. The namespace token
/// ranges are obtained first because they are needed to obtain unique identifiers. /// ranges are obtained first because they are needed to obtain unique identifiers.
void getAllTokenRanges(IdentifierType idtype); void getAllTokenRanges(IdentifierType identifierTypeToSearch);
/// The global scope is the complement of the union of all the function and UDT token ranges /// The global scope is the complement of the union of all the function and UDT token ranges
void getGlobalTokenRanges(); void getGlobalTokenRanges();
/// If the current token is a function or UDT, creates a map entry from the name to the token range. These are ordered alphabetically by name. /// If the current token is a function or UDT, creates a map entry from the name to the token range. These are ordered alphabetically by name.
@@ -251,10 +251,10 @@ namespace hex::plugin::builtin {
void skipDelimiters(i32 maxSkipCount, Token delimiter[2], i8 increment); void skipDelimiters(i32 maxSkipCount, Token delimiter[2], i8 increment);
void skipToken(Token token, i8 step=1); void skipToken(Token token, i8 step=1);
/// from given or current names find the corresponding definition /// from given or current names find the corresponding definition
bool findIdentifierDefinition(Definition &result, const std::string &optionalIdentifierName = "", std::string optionalName = "", bool optional = false); bool findIdentifierDefinition(Definition &result, const std::string &optionalIdentifierName = "", std::string optionalName = "", bool setInstances = false);
/// To deal with the Parent keyword /// To deal with the Parent keyword
std::optional<Definition> setChildrenTypes(); std::optional<Definition> setChildrenTypes();
bool findParentTypes(std::vector<std::string> &parentTypes, const std::string &optionalName=""); bool findParentTypes(std::vector<std::string> &parentTypes, const std::string &optionalUDTName="");
bool findAllParentTypes(std::vector<std::string> &parentTypes, std::vector<Identifier *> &identifiers, std::string &optionalFullName); bool findAllParentTypes(std::vector<std::string> &parentTypes, std::vector<Identifier *> &identifiers, std::string &optionalFullName);
bool tryParentType(const std::string &parentType, std::string &variableName, std::optional<Definition> &result, std::vector<Identifier *> &identifiers); bool tryParentType(const std::string &parentType, std::string &variableName, std::optional<Definition> &result, std::vector<Identifier *> &identifiers);
/// Convenience function /// Convenience function

View File

@@ -0,0 +1,46 @@
namespace hex::plugin::builtin {
void registerEventHandlers();
void registerDataVisualizers();
void registerMiniMapVisualizers();
void registerDataInspectorEntries();
void registerToolEntries();
void registerPatternLanguageFunctions();
void registerPatternLanguageTypes();
void registerPatternLanguagePragmas();
void registerPatternLanguageVisualizers();
void registerCommandPaletteCommands();
void registerSettings();
void loadSettings();
void registerDataProcessorNodes();
void registerProviders();
void registerDataFormatters();
void registerMainMenuEntries();
void createWelcomeScreen();
void registerViews();
void registerThemeHandlers();
void registerStyleHandlers();
void registerThemes();
void registerBackgroundServices();
void registerNetworkEndpoints();
void registerMCPTools();
void registerFileHandlers();
void registerProjectHandlers();
void registerAchievements();
void registerReportGenerators();
void registerTutorials();
void registerDataInformationSections();
void loadWorkspaces();
void addWindowDecoration();
void addFooterItems();
void addTitleBarButtons();
void addToolbarItems();
void addGlobalUIItems();
void addInitTasks();
void handleBorderlessWindowMode();
void setupOutOfBoxExperience();
void extractBundledFiles();
}

View File

@@ -352,7 +352,7 @@ namespace hex::plugin::builtin {
} }
void handleHexdumpCommand(const std::vector<std::string> &args) { void handleHexdumpCommand(const std::vector<std::string> &args) {
if (args.size() < 1 || args.size() > 3) { if (args.empty() || args.size() > 3) {
log::println("usage: imhex --hexdump <file> <offset> <size>"); log::println("usage: imhex --hexdump <file> <offset> <size>");
std::exit(EXIT_FAILURE); std::exit(EXIT_FAILURE);
} }
@@ -399,7 +399,7 @@ namespace hex::plugin::builtin {
if (std::fgets(input.data(), input.size() - 1, stdin) == nullptr) if (std::fgets(input.data(), input.size() - 1, stdin) == nullptr)
std::exit(EXIT_FAILURE); std::exit(EXIT_FAILURE);
input = input.c_str(); input = input.c_str(); // Stop at first null byte
input = wolv::util::trim(input); input = wolv::util::trim(input);
if (input == ConfirmationString) { if (input == ConfirmationString) {
@@ -536,7 +536,7 @@ namespace hex::plugin::builtin {
mcp::Client client; mcp::Client client;
auto result = client.run(std::cin, std::cout); auto result = client.run(std::cin, std::cout);
std::fprintf(stderr, "MCP Client disconnected!\n"); fmt::print(stderr, "MCP Client disconnected!\n");
std::exit(result); std::exit(result);
} }

View File

@@ -1,3 +1,4 @@
#include <algorithm>
#include <hex/api/imhex_api/provider.hpp> #include <hex/api/imhex_api/provider.hpp>
#include <hex/api/imhex_api/hex_editor.hpp> #include <hex/api/imhex_api/hex_editor.hpp>
#include <hex/api/content_registry/data_inspector.hpp> #include <hex/api/content_registry/data_inspector.hpp>
@@ -42,7 +43,7 @@ namespace hex::plugin::builtin {
std::memcpy(bytes.data(), &result, bytes.size()); std::memcpy(bytes.data(), &result, bytes.size());
if (endian != std::endian::native) if (endian != std::endian::native)
std::reverse(bytes.begin(), bytes.end()); std::ranges::reverse(bytes);
return bytes; return bytes;
}); });
@@ -58,7 +59,7 @@ namespace hex::plugin::builtin {
std::memcpy(bytes.data(), &result, bytes.size()); std::memcpy(bytes.data(), &result, bytes.size());
if (endian != std::endian::native) if (endian != std::endian::native)
std::reverse(bytes.begin(), bytes.end()); std::ranges::reverse(bytes);
return bytes; return bytes;
}); });
@@ -73,7 +74,7 @@ namespace hex::plugin::builtin {
std::memcpy(bytes.data(), &result, bytes.size()); std::memcpy(bytes.data(), &result, bytes.size());
if (endian != std::endian::native) if (endian != std::endian::native)
std::reverse(bytes.begin(), bytes.end()); std::ranges::reverse(bytes);
return bytes; return bytes;
}); });
@@ -449,7 +450,7 @@ namespace hex::plugin::builtin {
std::memcpy(bytes.data(), wideString->data(), bytes.size()); std::memcpy(bytes.data(), wideString->data(), bytes.size());
if (endian != std::endian::native) if (endian != std::endian::native)
std::reverse(bytes.begin(), bytes.end()); std::ranges::reverse(bytes);
return bytes; return bytes;
}) })
@@ -477,7 +478,7 @@ namespace hex::plugin::builtin {
std::memcpy(bytes.data(), wideString->data(), bytes.size()); std::memcpy(bytes.data(), wideString->data(), bytes.size());
if (endian != std::endian::native) if (endian != std::endian::native)
std::reverse(bytes.begin(), bytes.end()); std::ranges::reverse(bytes);
return bytes; return bytes;
}) })
@@ -505,7 +506,7 @@ namespace hex::plugin::builtin {
std::memcpy(bytes.data(), wideString->data(), bytes.size()); std::memcpy(bytes.data(), wideString->data(), bytes.size());
if (endian != std::endian::native) if (endian != std::endian::native)
std::reverse(bytes.begin(), bytes.end()); std::ranges::reverse(bytes);
return bytes; return bytes;
}) })

View File

@@ -1,3 +1,4 @@
#include <algorithm>
#include <hex/api/content_registry/data_processor.hpp> #include <hex/api/content_registry/data_processor.hpp>
#include <hex/data_processor/node.hpp> #include <hex/data_processor/node.hpp>
@@ -159,7 +160,7 @@ namespace hex::plugin::builtin {
for (u8 &b : data) for (u8 &b : data)
b = BitFlipLookup[b & 0xf] << 4 | BitFlipLookup[b >> 4]; b = BitFlipLookup[b & 0xf] << 4 | BitFlipLookup[b >> 4];
std::reverse(data.begin(), data.end()); std::ranges::reverse(data);
this->setBufferOnOutput(1, data); this->setBufferOnOutput(1, data);
} }

View File

@@ -1,3 +1,4 @@
#include <algorithm>
#include <hex/api/imhex_api/provider.hpp> #include <hex/api/imhex_api/provider.hpp>
#include <hex/api/content_registry/pattern_language.hpp> #include <hex/api/content_registry/pattern_language.hpp>
#include <hex/api/content_registry/data_processor.hpp> #include <hex/api/content_registry/data_processor.hpp>
@@ -8,6 +9,7 @@
#include <hex/data_processor/node.hpp> #include <hex/data_processor/node.hpp>
#include <hex/helpers/utils.hpp> #include <hex/helpers/utils.hpp>
#include <numeric>
#include <wolv/utils/core.hpp> #include <wolv/utils/core.hpp>
#include <content/helpers/diagrams.hpp> #include <content/helpers/diagrams.hpp>
@@ -174,7 +176,7 @@ namespace hex::plugin::builtin {
const auto &inputB = this->getBufferOnInput(1); const auto &inputB = this->getBufferOnInput(1);
auto output = inputA; auto output = inputA;
std::copy(inputB.begin(), inputB.end(), std::back_inserter(output)); std::ranges::copy(inputB, std::back_inserter(output));
this->setBufferOnOutput(2, output); this->setBufferOnOutput(2, output);
} }
@@ -212,7 +214,7 @@ namespace hex::plugin::builtin {
output.resize(buffer.size() * count); output.resize(buffer.size() * count);
for (u32 i = 0; i < count; i++) for (u32 i = 0; i < count; i++)
std::copy(buffer.begin(), buffer.end(), output.begin() + buffer.size() * i); std::ranges::copy(buffer, output.begin() + buffer.size() * i);
this->setBufferOnOutput(2, output); this->setBufferOnOutput(2, output);
} }
@@ -233,7 +235,7 @@ namespace hex::plugin::builtin {
if (address + patch.size() > buffer.size()) if (address + patch.size() > buffer.size())
buffer.resize(address + patch.size()); buffer.resize(address + patch.size());
std::copy(patch.begin(), patch.end(), buffer.begin() + address); std::ranges::copy(patch, buffer.begin() + address);
this->setBufferOnOutput(3, buffer); this->setBufferOnOutput(3, buffer);
} }
@@ -382,7 +384,7 @@ namespace hex::plugin::builtin {
if (ImPlot::BeginPlot("##distribution", viewSize, ImPlotFlags_NoLegend | ImPlotFlags_NoMenus | ImPlotFlags_NoBoxSelect)) { if (ImPlot::BeginPlot("##distribution", viewSize, ImPlotFlags_NoLegend | ImPlotFlags_NoMenus | ImPlotFlags_NoBoxSelect)) {
ImPlot::SetupAxes("Address", "Count", ImPlotAxisFlags_Lock, ImPlotAxisFlags_Lock); ImPlot::SetupAxes("Address", "Count", ImPlotAxisFlags_Lock, ImPlotAxisFlags_Lock);
ImPlot::SetupAxisScale(ImAxis_Y1, ImPlotScale_Log10); ImPlot::SetupAxisScale(ImAxis_Y1, ImPlotScale_Log10);
ImPlot::SetupAxesLimits(0, 256, 1, double(*std::max_element(m_counts.begin(), m_counts.end())) * 1.1F, ImGuiCond_Always); ImPlot::SetupAxesLimits(0, 256, 1, double(*std::ranges::max_element(m_counts)) * 1.1F, ImGuiCond_Always);
static auto x = [] { static auto x = [] {
std::array<ImU64, 256> result { 0 }; std::array<ImU64, 256> result { 0 };
@@ -463,7 +465,7 @@ namespace hex::plugin::builtin {
void process() override { void process() override {
auto data = this->getBufferOnInput(0); auto data = this->getBufferOnInput(0);
std::reverse(data.begin(), data.end()); std::ranges::reverse(data);
this->setBufferOnOutput(1, data); this->setBufferOnOutput(1, data);
} }

View File

@@ -90,8 +90,8 @@ namespace hex::plugin::builtin {
} }
private: private:
constexpr static inline auto ByteCount = 1; constexpr static auto ByteCount = 1;
constexpr static inline auto CharCount = ByteCount * 2; constexpr static auto CharCount = ByteCount * 2;
const static inline auto FormattingUpperCase = fmt::format("%0{}{}X", CharCount, ImGuiExt::getFormatLengthSpecifier<u8>()); const static inline auto FormattingUpperCase = fmt::format("%0{}{}X", CharCount, ImGuiExt::getFormatLengthSpecifier<u8>());
const static inline auto FormattingLowerCase = fmt::format("%0{}{}x", CharCount, ImGuiExt::getFormatLengthSpecifier<u8>()); const static inline auto FormattingLowerCase = fmt::format("%0{}{}x", CharCount, ImGuiExt::getFormatLengthSpecifier<u8>());
@@ -175,13 +175,13 @@ namespace hex::plugin::builtin {
} }
private: private:
constexpr static inline auto ByteCount = sizeof(T); constexpr static auto ByteCount = sizeof(T);
constexpr static inline auto CharCount = 14; constexpr static auto CharCount = 14;
const static inline auto FormatStringUpperCase = fmt::format("%{}G", CharCount); const static inline auto FormatStringUpperCase = fmt::format("%{}G", CharCount);
const static inline auto FormatStringLowerCase = fmt::format("%{}g", CharCount); const static inline auto FormatStringLowerCase = fmt::format("%{}g", CharCount);
const char *getFormatString(bool upperCase) const { [[nodiscard]] const char *getFormatString(bool upperCase) const {
if (upperCase) if (upperCase)
return FormatStringUpperCase.c_str(); return FormatStringUpperCase.c_str();
else else

View File

@@ -258,11 +258,11 @@ namespace hex::plugin::builtin {
}); });
EventImHexStartupFinished::subscribe([] { EventImHexStartupFinished::subscribe([] {
const auto currVersion = ImHexApi::System::getImHexVersion(); const auto& currVersion = ImHexApi::System::getImHexVersion();
const auto prevLaunchVersion = ContentRegistry::Settings::read<std::string>("hex.builtin.setting.general", "hex.builtin.setting.general.prev_launch_version", ""); const auto prevLaunchVersion = ContentRegistry::Settings::read<std::string>("hex.builtin.setting.general", "hex.builtin.setting.general.prev_launch_version", "");
const auto forceOobe = getEnvironmentVariable("IMHEX_FORCE_OOBE"); const auto forceOobe = getEnvironmentVariable("IMHEX_FORCE_OOBE");
if (prevLaunchVersion == "" || (forceOobe.has_value() && *forceOobe != "0")) { if (prevLaunchVersion.empty() || (forceOobe.has_value() && *forceOobe != "0")) {
EventFirstLaunch::post(); EventFirstLaunch::post();
return; return;
} }

View File

@@ -123,7 +123,7 @@ namespace hex::plugin::builtin {
if (restoreWindowPos) { if (restoreWindowPos) {
ImHexApi::System::InitialWindowProperties properties = {}; ImHexApi::System::InitialWindowProperties properties = {};
properties.maximized = ContentRegistry::Settings::read<bool>("hex.builtin.setting.interface", "hex.builtin.setting.interface.window.maximized", 0); properties.maximized = ContentRegistry::Settings::read<bool>("hex.builtin.setting.interface", "hex.builtin.setting.interface.window.maximized", false);
properties.x = ContentRegistry::Settings::read<int>("hex.builtin.setting.interface", "hex.builtin.setting.interface.window.x", 0); properties.x = ContentRegistry::Settings::read<int>("hex.builtin.setting.interface", "hex.builtin.setting.interface.window.x", 0);
properties.y = ContentRegistry::Settings::read<int>("hex.builtin.setting.interface", "hex.builtin.setting.interface.window.y", 0); properties.y = ContentRegistry::Settings::read<int>("hex.builtin.setting.interface", "hex.builtin.setting.interface.window.y", 0);
properties.width = ContentRegistry::Settings::read<int>("hex.builtin.setting.interface", "hex.builtin.setting.interface.window.width", 0); properties.width = ContentRegistry::Settings::read<int>("hex.builtin.setting.interface", "hex.builtin.setting.interface.window.width", 0);

View File

@@ -51,9 +51,9 @@ namespace hex::plugin::builtin {
void zerosMiniMapVisualizer(u64, std::span<const u8> data, std::vector<ImColor> &output) { void zerosMiniMapVisualizer(u64, std::span<const u8> data, std::vector<ImColor> &output) {
for (u8 byte : data) { for (u8 byte : data) {
if (byte == 0x00) if (byte == 0x00)
output.push_back(ImColor(1.0F, 1.0F, 1.0F, 1.0F)); output.emplace_back(1.0F, 1.0F, 1.0F, 1.0F);
else else
output.push_back(ImColor(0.0F, 0.0F, 0.0F, 1.0F)); output.emplace_back(0.0F, 0.0F, 0.0F, 1.0F);
} }
} }
@@ -99,7 +99,7 @@ namespace hex::plugin::builtin {
void rgba8MiniMapVisualizer(u64 address, std::span<const u8> data, std::vector<ImColor> &output) { void rgba8MiniMapVisualizer(u64 address, std::span<const u8> data, std::vector<ImColor> &output) {
colorMinimapVisualizer(address, data, output, 4, [](std::span<const u8> subData) -> ImColor { colorMinimapVisualizer(address, data, output, 4, [](std::span<const u8> subData) -> ImColor {
return ImColor(subData[0], subData[1], subData[2], 0xFF); return {subData[0], subData[1], subData[2], 0xFF};
}); });
} }
@@ -108,7 +108,7 @@ namespace hex::plugin::builtin {
u8 r = (subData[0] & 0xF8); u8 r = (subData[0] & 0xF8);
u8 g = ((subData[0] & 0x07) << 5) | ((subData[1] & 0xE0) >> 3); u8 g = ((subData[0] & 0x07) << 5) | ((subData[1] & 0xE0) >> 3);
u8 b = (subData[1] & 0x1F) << 3; u8 b = (subData[1] & 0x1F) << 3;
return ImColor(r, g, b, 0xFF); return {r, g, b, 0xFF};
}); });
} }

View File

@@ -37,7 +37,7 @@ namespace hex::plugin::builtin {
class Blend { class Blend {
public: public:
Blend(float start, float end) : m_time(0), m_start(start), m_end(end) {} Blend(float start, float end) : m_start(start), m_end(end) {}
[[nodiscard]] operator float() { [[nodiscard]] operator float() {
m_time += ImGui::GetIO().DeltaTime; m_time += ImGui::GetIO().DeltaTime;
@@ -56,7 +56,7 @@ namespace hex::plugin::builtin {
} }
private: private:
float m_time; float m_time = 0;
float m_start, m_end; float m_start, m_end;
}; };
@@ -472,7 +472,7 @@ namespace hex::plugin::builtin {
EventFirstLaunch::subscribe([] { EventFirstLaunch::subscribe([] {
ImHexApi::System::setWindowResizable(false); ImHexApi::System::setWindowResizable(false);
const auto imageTheme = ThemeManager::getImageTheme(); auto &imageTheme = ThemeManager::getImageTheme();
s_imhexBanner = ImGuiExt::Texture::fromSVG(romfs::get(fmt::format("assets/{}/banner.svg", imageTheme)).span<std::byte>(), 0, 0, ImGuiExt::Texture::Filter::Linear); s_imhexBanner = ImGuiExt::Texture::fromSVG(romfs::get(fmt::format("assets/{}/banner.svg", imageTheme)).span<std::byte>(), 0, 0, ImGuiExt::Texture::Filter::Linear);
s_compassTexture = ImGuiExt::Texture::fromImage(romfs::get("assets/common/compass.png").span<std::byte>(), ImGuiExt::Texture::Filter::Linear); s_compassTexture = ImGuiExt::Texture::fromImage(romfs::get("assets/common/compass.png").span<std::byte>(), ImGuiExt::Texture::Filter::Linear);
s_globeTexture = ImGuiExt::Texture::fromImage(romfs::get("assets/common/globe.png").span<std::byte>(), ImGuiExt::Texture::Filter::Linear); s_globeTexture = ImGuiExt::Texture::fromImage(romfs::get("assets/common/globe.png").span<std::byte>(), ImGuiExt::Texture::Filter::Linear);

View File

@@ -1,3 +1,4 @@
#include <algorithm>
#include <hex/api/content_registry/pattern_language.hpp> #include <hex/api/content_registry/pattern_language.hpp>
#include <hex/helpers/encoding_file.hpp> #include <hex/helpers/encoding_file.hpp>
@@ -43,7 +44,7 @@ namespace hex::plugin::builtin {
this->getEvaluator()->readData(this->getOffset(), result.data(), result.size(), this->getSection()); this->getEvaluator()->readData(this->getOffset(), result.data(), result.size(), this->getSection());
if (this->getEndian() != std::endian::native) if (this->getEndian() != std::endian::native)
std::reverse(result.begin(), result.end()); std::ranges::reverse(result);
return result; return result;
} }

View File

@@ -27,7 +27,7 @@ namespace hex::plugin::builtin {
using namespace std::chrono_literals; using namespace std::chrono_literals;
CommandProvider::CommandProvider() { } CommandProvider::CommandProvider() = default;
bool CommandProvider::isAvailable() const { bool CommandProvider::isAvailable() const {
return m_open; return m_open;

View File

@@ -217,7 +217,7 @@ namespace hex::plugin::builtin {
auto data = gdb::readMemory(m_socket, offset, size); auto data = gdb::readMemory(m_socket, offset, size);
if (!data.empty()) if (!data.empty())
std::memcpy(buffer, &data[0], data.size()); std::memcpy(buffer, data.data(), data.size());
} }
void GDBProvider::writeToSource(u64 offset, const void *buffer, size_t size) { void GDBProvider::writeToSource(u64 offset, const void *buffer, size_t size) {

View File

@@ -1,5 +1,6 @@
#if defined(OS_WINDOWS) || defined(OS_MACOS) || (defined(OS_LINUX) && !defined(OS_FREEBSD)) #if defined(OS_WINDOWS) || defined(OS_MACOS) || (defined(OS_LINUX) && !defined(OS_FREEBSD))
#include <algorithm>
#include <content/providers/process_memory_provider.hpp> #include <content/providers/process_memory_provider.hpp>
#include <hex/api/imhex_api/hex_editor.hpp> #include <hex/api/imhex_api/hex_editor.hpp>
@@ -568,7 +569,7 @@ namespace hex::plugin::builtin {
std::variant<std::string, i128> ProcessMemoryProvider::queryInformation(const std::string &category, const std::string &argument) { std::variant<std::string, i128> ProcessMemoryProvider::queryInformation(const std::string &category, const std::string &argument) {
auto findRegionByName = [this](const std::string &name) { auto findRegionByName = [this](const std::string &name) {
return std::find_if(m_memoryRegions.begin(), m_memoryRegions.end(), return std::ranges::find_if(m_memoryRegions,
[name](const auto &region) { [name](const auto &region) {
return region.name == name; return region.name == name;
}); });

View File

@@ -116,7 +116,7 @@ namespace hex::plugin::builtin::recent {
return ImGuiWindowFlags_AlwaysAutoResize; return ImGuiWindowFlags_AlwaysAutoResize;
} }
void saveCurrentProjectAsRecent() { static void saveCurrentProjectAsRecent() {
if (!ContentRegistry::Settings::read<bool>("hex.builtin.setting.general", "hex.builtin.setting.general.save_recent_providers", true)) { if (!ContentRegistry::Settings::read<bool>("hex.builtin.setting.general", "hex.builtin.setting.general.save_recent_providers", true)) {
return; return;
} }

View File

@@ -1,3 +1,4 @@
#include <algorithm>
#include <hex/api/imhex_api/system.hpp> #include <hex/api/imhex_api/system.hpp>
#include <hex/api/content_registry/settings.hpp> #include <hex/api/content_registry/settings.hpp>
#include <hex/api/content_registry/user_interface.hpp> #include <hex/api/content_registry/user_interface.hpp>
@@ -81,11 +82,7 @@ namespace hex::plugin::builtin {
return "%d FPS"; return "%d FPS";
}(); }();
if (ImGui::SliderInt(name.data(), &m_value, 14, 201, format.c_str(), ImGuiSliderFlags_AlwaysClamp)) { return ImGui::SliderInt(name.data(), &m_value, 14, 201, format.c_str(), ImGuiSliderFlags_AlwaysClamp);
return true;
}
return false;
} }
void load(const nlohmann::json &data) override { void load(const nlohmann::json &data) override {
@@ -129,7 +126,7 @@ namespace hex::plugin::builtin {
if (ImGuiExt::DimmedIconButton(ICON_VS_NEW_FOLDER, ImGui::GetStyleColorVec4(ImGuiCol_Text))) { if (ImGuiExt::DimmedIconButton(ICON_VS_NEW_FOLDER, ImGui::GetStyleColorVec4(ImGuiCol_Text))) {
fs::openFileBrowser(fs::DialogMode::Folder, {}, [&](const std::fs::path &path) { fs::openFileBrowser(fs::DialogMode::Folder, {}, [&](const std::fs::path &path) {
if (std::find(m_paths.begin(), m_paths.end(), path) == m_paths.end()) { if (std::ranges::find(m_paths, path) == m_paths.end()) {
m_paths.emplace_back(path); m_paths.emplace_back(path);
ImHexApi::System::setAdditionalFolderPaths(m_paths); ImHexApi::System::setAdditionalFolderPaths(m_paths);
@@ -170,7 +167,8 @@ namespace hex::plugin::builtin {
nlohmann::json store() override { nlohmann::json store() override {
std::vector<std::string> pathStrings; std::vector<std::string> pathStrings;
for (const auto &path : m_paths) { pathStrings.reserve(m_paths.size());
for (const auto &path : m_paths) {
pathStrings.push_back(wolv::io::fs::toNormalizedPathString(path)); pathStrings.push_back(wolv::io::fs::toNormalizedPathString(path));
} }
@@ -211,7 +209,7 @@ namespace hex::plugin::builtin {
return m_value; return m_value;
} }
float getValue() const { [[nodiscard]] float getValue() const {
return m_value; return m_value;
} }
@@ -232,11 +230,7 @@ namespace hex::plugin::builtin {
return fmt::format("hex.builtin.setting.general.backups.auto_backup_time.format.extended"_lang, value / 60, value % 60); return fmt::format("hex.builtin.setting.general.backups.auto_backup_time.format.extended"_lang, value / 60, value % 60);
}(); }();
if (ImGui::SliderInt(name.data(), &m_value, 0, (30 * 60) / 30, format.c_str(), ImGuiSliderFlags_AlwaysClamp | ImGuiSliderFlags_NoInput)) { return ImGui::SliderInt(name.data(), &m_value, 0, (30 * 60) / 30, format.c_str(), ImGuiSliderFlags_AlwaysClamp | ImGuiSliderFlags_NoInput);
return true;
}
return false;
} }
void load(const nlohmann::json &data) override { void load(const nlohmann::json &data) override {
@@ -794,6 +788,7 @@ namespace hex::plugin::builtin {
{ {
auto themeNames = ThemeManager::getThemeNames(); auto themeNames = ThemeManager::getThemeNames();
std::vector<nlohmann::json> themeJsons = { }; std::vector<nlohmann::json> themeJsons = { };
themeJsons.reserve(themeNames.size());
for (const auto &themeName : themeNames) for (const auto &themeName : themeNames)
themeJsons.emplace_back(themeName); themeJsons.emplace_back(themeName);
@@ -1059,7 +1054,8 @@ namespace hex::plugin::builtin {
auto folderPathStrings = ContentRegistry::Settings::read<std::vector<std::string>>("hex.builtin.setting.folders", "hex.builtin.setting.folders", { }); auto folderPathStrings = ContentRegistry::Settings::read<std::vector<std::string>>("hex.builtin.setting.folders", "hex.builtin.setting.folders", { });
std::vector<std::fs::path> paths; std::vector<std::fs::path> paths;
for (const auto &pathString : folderPathStrings) { paths.reserve(folderPathStrings.size());
for (const auto &pathString : folderPathStrings) {
paths.emplace_back(pathString); paths.emplace_back(pathString);
} }

View File

@@ -1,3 +1,4 @@
#include <algorithm>
#include <content/text_highlighting/pattern_language.hpp> #include <content/text_highlighting/pattern_language.hpp>
#include <pl/core/ast/ast_node_type_decl.hpp> #include <pl/core/ast/ast_node_type_decl.hpp>
#include <pl/core/ast/ast_node_enum.hpp> #include <pl/core/ast/ast_node_enum.hpp>
@@ -59,7 +60,7 @@ namespace hex::plugin::builtin {
bool TextHighlighter::forwardIdentifierName(std::string &identifierName, std::vector<Identifier *> &identifiers, bool preserveCurr ) { bool TextHighlighter::forwardIdentifierName(std::string &identifierName, std::vector<Identifier *> &identifiers, bool preserveCurr ) {
auto curr = m_curr; auto curr = m_curr;
Identifier *identifier = getValue<Identifier>(0); auto *identifier = getValue<Identifier>(0);
std::string current; std::string current;
if (identifier != nullptr) { if (identifier != nullptr) {
@@ -287,7 +288,7 @@ namespace hex::plugin::builtin {
if (peek(tkn::Literal::Identifier)) { if (peek(tkn::Literal::Identifier)) {
if (identifier = getValue<Identifier>(0); identifier != nullptr) { if (identifier = getValue<Identifier>(0); identifier != nullptr) {
identifierType = identifier->getType(); identifierType = identifier->getType();
std::string name = identifier->get(); auto& name = identifier->get();
if (identifierType == identifierTypeToSearch) { if (identifierType == identifierTypeToSearch) {
switch (identifierType) { switch (identifierType) {
@@ -367,8 +368,7 @@ namespace hex::plugin::builtin {
} }
} }
m_curr = curr; m_curr = curr;
return; }
}
void TextHighlighter::skipTemplate(i32 maxSkipCount, bool forward) { void TextHighlighter::skipTemplate(i32 maxSkipCount, bool forward) {
Token delimiters[2]; Token delimiters[2];
@@ -523,7 +523,7 @@ namespace hex::plugin::builtin {
result.idType = IdentifierType::Unknown; result.idType = IdentifierType::Unknown;
std::string identifierName = optionalIdentifierName; std::string identifierName = optionalIdentifierName;
if (optionalIdentifierName == "") { if (optionalIdentifierName.empty()) {
std::vector<Identifier *> identifiers; std::vector<Identifier *> identifiers;
getFullName(identifierName, identifiers); getFullName(identifierName, identifiers);
} }
@@ -579,7 +579,7 @@ namespace hex::plugin::builtin {
} }
} }
} }
auto it = std::find_if(definitions.begin(), definitions.end(), [&](const Definition &definition) { auto it = std::ranges::find_if(definitions, [&](const Definition &definition) {
return definition.tokenIndex > tokenRange.start && definition.tokenIndex < tokenRange.end; return definition.tokenIndex > tokenRange.start && definition.tokenIndex < tokenRange.end;
}); });
@@ -681,7 +681,7 @@ namespace hex::plugin::builtin {
next(); next();
} else if (auto udtVars = m_UDTVariables[result.typeStr];udtVars.contains(vectorString[index-1])) { } else if (auto udtVars = m_UDTVariables[result.typeStr];udtVars.contains(vectorString[index-1])) {
auto saveCurr = m_curr; auto saveCurr = m_curr;
std::string templateName = ""; std::string templateName;
auto instances = m_instances[variableParentType]; auto instances = m_instances[variableParentType];
for (auto instance : instances) { for (auto instance : instances) {
if (auto *identifier = std::get_if<Identifier>(&m_tokens[instance].value); identifier != nullptr && identifier->getType() == IdentifierType::TemplateArgument) { if (auto *identifier = std::get_if<Identifier>(&m_tokens[instance].value); identifier != nullptr && identifier->getType() == IdentifierType::TemplateArgument) {
@@ -704,7 +704,7 @@ namespace hex::plugin::builtin {
next(); next();
} else{ } else{
if (m_typeDefMap.contains(variableParentType)) { if (m_typeDefMap.contains(variableParentType)) {
std::string typeName = ""; std::string typeName;
instances = m_instances[variableParentType]; instances = m_instances[variableParentType];
for (auto instance: instances) { for (auto instance: instances) {
if (auto *identifier = std::get_if<Identifier>(&m_tokens[instance].value); if (auto *identifier = std::get_if<Identifier>(&m_tokens[instance].value);
@@ -771,7 +771,7 @@ namespace hex::plugin::builtin {
if (!sequence(tkn::Operator::ScopeResolution) || vectorStringCount != i+2 || if (!sequence(tkn::Operator::ScopeResolution) || vectorStringCount != i+2 ||
!m_UDTVariables.contains(name)) !m_UDTVariables.contains(name))
return false; return false;
auto variableName = vectorString[i+1]; const auto& variableName = vectorString[i+1];
if (!m_UDTVariables[name].contains(variableName)) if (!m_UDTVariables[name].contains(variableName))
return false; return false;
auto variableDefinition = m_UDTVariables[name][variableName][0]; auto variableDefinition = m_UDTVariables[name][variableName][0];
@@ -858,16 +858,14 @@ namespace hex::plugin::builtin {
if (tokenId > interval.start && tokenId < interval.end) { if (tokenId > interval.start && tokenId < interval.end) {
if (nameSpace == "") if (nameSpace.empty())
nameSpace = name; nameSpace = name;
else else
nameSpace = name + "::" + nameSpace; nameSpace = name + "::" + nameSpace;
} }
} }
if (nameSpace != "") return nameSpace != "";
return true;
return false;
} }
//The context is the name of the function or UDT that the variable is in. //The context is the name of the function or UDT that the variable is in.
@@ -1300,7 +1298,7 @@ namespace hex::plugin::builtin {
if (identifierType == IdentifierType::Typedef) { if (identifierType == IdentifierType::Typedef) {
auto curr = m_curr; auto curr = m_curr;
next(); next();
std::string typeName = ""; std::string typeName;
if (sequence(tkn::Operator::Assign, tkn::Literal::Identifier)) { if (sequence(tkn::Operator::Assign, tkn::Literal::Identifier)) {
auto identifier2 = getValue<Identifier>(-1); auto identifier2 = getValue<Identifier>(-1);
if (identifier2 != nullptr) { if (identifier2 != nullptr) {
@@ -1452,7 +1450,8 @@ namespace hex::plugin::builtin {
void TextHighlighter::colorRemainingIdentifierTokens() { void TextHighlighter::colorRemainingIdentifierTokens() {
std::vector<i32> taggedIdentifiers; std::vector<i32> taggedIdentifiers;
for (auto index: m_taggedIdentifiers) { taggedIdentifiers.reserve(m_taggedIdentifiers.size());
for (auto index: m_taggedIdentifiers) {
taggedIdentifiers.push_back(index); taggedIdentifiers.push_back(index);
} }
m_taggedIdentifiers.clear(); m_taggedIdentifiers.clear();
@@ -1470,7 +1469,7 @@ namespace hex::plugin::builtin {
taggedIdentifiers.pop_back(); taggedIdentifiers.pop_back();
} }
Token *token = const_cast<Token *>(&m_curr[0]); auto *token = const_cast<Token *>(&m_curr[0]);
if (sequence(tkn::Keyword::Import, tkn::Literal::Identifier)) { if (sequence(tkn::Keyword::Import, tkn::Literal::Identifier)) {
next(-1); next(-1);
@@ -1581,7 +1580,7 @@ namespace hex::plugin::builtin {
continue; continue;
std::string lineOfColors = std::string(m_lines[line].size(), 0); std::string lineOfColors = std::string(m_lines[line].size(), 0);
for (auto tokenIndex = m_firstTokenIdOfLine[line]; tokenIndex < m_firstTokenIdOfLine[nextLine(line)]; tokenIndex++) { for (auto tokenIndex = m_firstTokenIdOfLine[line]; tokenIndex < m_firstTokenIdOfLine[nextLine(line)]; tokenIndex++) {
Token *token = const_cast<Token *>(&m_tokens[tokenIndex]); auto *token = const_cast<Token *>(&m_tokens[tokenIndex]);
if (m_tokenColors.contains(token) && token->type == Token::Type::Identifier) { if (m_tokenColors.contains(token) && token->type == Token::Type::Identifier) {
u8 color = (u8) m_tokenColors.at(token); u8 color = (u8) m_tokenColors.at(token);
u32 tokenLength = token->location.length; u32 tokenLength = token->location.length;
@@ -1935,7 +1934,7 @@ namespace hex::plugin::builtin {
} }
m_lines = wolv::util::splitString(m_text, "\n"); m_lines = wolv::util::splitString(m_text, "\n");
m_lines.push_back(""); m_lines.emplace_back("");
m_firstTokenIdOfLine.clear(); m_firstTokenIdOfLine.clear();
m_firstTokenIdOfLine.resize(m_lines.size(), -1); m_firstTokenIdOfLine.resize(m_lines.size(), -1);
@@ -2143,7 +2142,7 @@ namespace hex::plugin::builtin {
while (next != ranges.end()) { while (next != ranges.end()) {
if (next->start - it->end < 2) { if (next->start - it->end < 2) {
Interval &range = const_cast<Interval &>(*it); auto &range = const_cast<Interval &>(*it);
range.end = next->end; range.end = next->end;
ranges.erase(next); ranges.erase(next);
next = std::next(it); next = std::next(it);
@@ -2345,6 +2344,5 @@ namespace hex::plugin::builtin {
m_wasInterrupted = true; m_wasInterrupted = true;
return; return;
} }
return;
} }
} }

View File

@@ -4,6 +4,7 @@
#include <imgui.h> #include <imgui.h>
#include <hex/ui/imgui_imhex_extensions.h> #include <hex/ui/imgui_imhex_extensions.h>
#include <content/tools_entries.hpp>
#include <fonts/vscode_icons.hpp> #include <fonts/vscode_icons.hpp>

View File

@@ -124,7 +124,7 @@ namespace hex::plugin::builtin {
if (response.valid() && response.wait_for(0s) != std::future_status::timeout) { if (response.valid() && response.wait_for(0s) != std::future_status::timeout) {
const auto result = response.get(); const auto result = response.get();
const auto data = result.getData(); const auto& data = result.getData();
if (const auto status = result.getStatusCode(); status != 0) if (const auto status = result.getStatusCode(); status != 0)
responseText = "Status: " + std::to_string(result.getStatusCode()) + "\n\n" + data; responseText = "Status: " + std::to_string(result.getStatusCode()) + "\n\n" + data;

View File

@@ -25,12 +25,12 @@ namespace hex::plugin::builtin {
class IEEE754STATICS { class IEEE754STATICS {
public: public:
IEEE754STATICS() : value(0), exponentBitCount(8), mantissaBitCount(23), resultFloat(0) {} IEEE754STATICS() {}
u128 value; u128 value = 0;
i32 exponentBitCount; i32 exponentBitCount = 8;
i32 mantissaBitCount; i32 mantissaBitCount =23;
long double resultFloat; long double resultFloat = 0;
}; };
static IEEE754STATICS ieee754statics; static IEEE754STATICS ieee754statics;

View File

@@ -9,7 +9,7 @@
namespace hex::plugin::builtin { namespace hex::plugin::builtin {
void drawFileTools() { static void drawFileTools() {
if (ImGui::BeginTabBar("file_tools_tabs")) { if (ImGui::BeginTabBar("file_tools_tabs")) {
if (ImGui::BeginTabItem("hex.builtin.tools.file_tools.shredder"_lang)) { if (ImGui::BeginTabItem("hex.builtin.tools.file_tools.shredder"_lang)) {
drawFileToolShredder(); drawFileToolShredder();

View File

@@ -121,7 +121,7 @@ namespace hex::plugin::builtin {
try { try {
const auto attribute = pattern->getAttributeArguments(SimplifiedEditorAttribute); const auto attribute = pattern->getAttributeArguments(SimplifiedEditorAttribute);
const auto name = attribute.size() >= 1 ? attribute[0].toString() : pattern->getDisplayName(); const auto name = !attribute.empty() ? attribute[0].toString() : pattern->getDisplayName();
const auto description = attribute.size() >= 2 ? attribute[1].toString() : pattern->getComment(); const auto description = attribute.size() >= 2 ? attribute[1].toString() : pattern->getComment();
const auto widgetPos = 200_scaled; const auto widgetPos = 200_scaled;

View File

@@ -1,5 +1,6 @@
#include "content/views/view_achievements.hpp" #include "content/views/view_achievements.hpp"
#include <algorithm>
#include <hex/api/content_registry/user_interface.hpp> #include <hex/api/content_registry/user_interface.hpp>
#include <hex/api/content_registry/settings.hpp> #include <hex/api/content_registry/settings.hpp>
#include <hex/api/task_manager.hpp> #include <hex/api/task_manager.hpp>
@@ -321,11 +322,12 @@ namespace hex::plugin::builtin {
// Get all achievement category names // Get all achievement category names
std::vector<std::string> categories; std::vector<std::string> categories;
for (const auto &[categoryName, achievements] : startNodes) { categories.reserve(startNodes.size());
for (const auto &[categoryName, achievements] : startNodes) {
categories.push_back(categoryName); categories.push_back(categoryName);
} }
std::reverse(categories.begin(), categories.end()); std::ranges::reverse(categories);
// Draw each individual achievement category // Draw each individual achievement category
for (const auto &categoryName : categories) { for (const auto &categoryName : categories) {

View File

@@ -1,5 +1,6 @@
#include "content/views/view_data_inspector.hpp" #include "content/views/view_data_inspector.hpp"
#include <algorithm>
#include <hex/api/achievement_manager.hpp> #include <hex/api/achievement_manager.hpp>
#include <hex/api/content_registry/settings.hpp> #include <hex/api/content_registry/settings.hpp>
#include <hex/providers/provider.hpp> #include <hex/providers/provider.hpp>
@@ -263,7 +264,7 @@ namespace hex::plugin::builtin {
} }
const auto selection = ImHexApi::HexEditor::getSelection(); const auto selection = ImHexApi::HexEditor::getSelection();
const auto selectedEntryIt = std::find_if(m_cachedData.begin(), m_cachedData.end(), [this](const InspectorCacheEntry &entry) { const auto selectedEntryIt = std::ranges::find_if(m_cachedData, [this](const InspectorCacheEntry &entry) {
return entry.unlocalizedName == m_selectedEntryName; return entry.unlocalizedName == m_selectedEntryName;
}); });

View File

@@ -1,4 +1,5 @@
#include "content/views/view_data_processor.hpp" #include "content/views/view_data_processor.hpp"
#include <algorithm>
#include <toasts/toast_notification.hpp> #include <toasts/toast_notification.hpp>
#include <hex/api/content_registry/data_processor.hpp> #include <hex/api/content_registry/data_processor.hpp>
@@ -52,9 +53,9 @@ namespace hex::plugin::builtin {
void setValue(auto value) { m_value = std::move(value); } void setValue(auto value) { m_value = std::move(value); }
const std::string &getName() const { return m_name; } [[nodiscard]] const std::string &getName() const { return m_name; }
dp::Attribute::Type getType() const { [[nodiscard]] dp::Attribute::Type getType() const {
switch (m_type) { switch (m_type) {
default: default:
case 0: return dp::Attribute::Type::Integer; case 0: return dp::Attribute::Type::Integer;
@@ -121,8 +122,8 @@ namespace hex::plugin::builtin {
ImGui::PopItemWidth(); ImGui::PopItemWidth();
} }
const std::string &getName() const { return m_name; } [[nodiscard]] const std::string &getName() const { return m_name; }
dp::Attribute::Type getType() const { [[nodiscard]] dp::Attribute::Type getType() const {
switch (m_type) { switch (m_type) {
case 0: return dp::Attribute::Type::Integer; case 0: return dp::Attribute::Type::Integer;
case 1: return dp::Attribute::Type::Float; case 1: return dp::Attribute::Type::Float;
@@ -139,7 +140,7 @@ namespace hex::plugin::builtin {
} }
} }
const auto& getValue() const { return m_value; } [[nodiscard]] const auto& getValue() const { return m_value; }
void store(nlohmann::json &j) const override { void store(nlohmann::json &j) const override {
j = nlohmann::json::object(); j = nlohmann::json::object();
@@ -314,7 +315,7 @@ namespace hex::plugin::builtin {
} }
private: private:
std::vector<dp::Attribute> findAttributes() const { [[nodiscard]] std::vector<dp::Attribute> findAttributes() const {
std::vector<dp::Attribute> result; std::vector<dp::Attribute> result;
// Search through all nodes in the workspace and add all input and output nodes to the result // Search through all nodes in the workspace and add all input and output nodes to the result
@@ -328,7 +329,7 @@ namespace hex::plugin::builtin {
return result; return result;
} }
NodeCustomInput* findInput(const std::string &name) const { [[nodiscard]] NodeCustomInput* findInput(const std::string &name) const {
for (auto &node : m_workspace.nodes) { for (auto &node : m_workspace.nodes) {
if (auto *inputNode = dynamic_cast<NodeCustomInput*>(node.get()); inputNode != nullptr && inputNode->getName() == name) if (auto *inputNode = dynamic_cast<NodeCustomInput*>(node.get()); inputNode != nullptr && inputNode->getName() == name)
return inputNode; return inputNode;
@@ -337,7 +338,7 @@ namespace hex::plugin::builtin {
return nullptr; return nullptr;
} }
NodeCustomOutput* findOutput(const std::string &name) const { [[nodiscard]] NodeCustomOutput* findOutput(const std::string &name) const {
for (auto &node : m_workspace.nodes) { for (auto &node : m_workspace.nodes) {
if (auto *outputNode = dynamic_cast<NodeCustomOutput*>(node.get()); outputNode != nullptr && outputNode->getName() == name) if (auto *outputNode = dynamic_cast<NodeCustomOutput*>(node.get()); outputNode != nullptr && outputNode->getName() == name)
return outputNode; return outputNode;
@@ -445,7 +446,7 @@ namespace hex::plugin::builtin {
void ViewDataProcessor::eraseLink(Workspace &workspace, int id) { void ViewDataProcessor::eraseLink(Workspace &workspace, int id) {
// Find the link with the given ID // Find the link with the given ID
auto link = std::find_if(workspace.links.begin(), workspace.links.end(), auto link = std::ranges::find_if(workspace.links,
[&id](auto link) { [&id](auto link) {
return link.getId() == id; return link.getId() == id;
}); });
@@ -472,7 +473,7 @@ namespace hex::plugin::builtin {
// and remove all links that are connected to the attributes of the node // and remove all links that are connected to the attributes of the node
for (int id : ids) { for (int id : ids) {
// Find the node with the given ID // Find the node with the given ID
auto node = std::find_if(workspace.nodes.begin(), workspace.nodes.end(), auto node = std::ranges::find_if(workspace.nodes,
[&id](const auto &node) { [&id](const auto &node) {
return node->getId() == id; return node->getId() == id;
}); });
@@ -495,7 +496,7 @@ namespace hex::plugin::builtin {
// and remove the nodes from the workspace // and remove the nodes from the workspace
for (int id : ids) { for (int id : ids) {
// Find the node with the given ID // Find the node with the given ID
auto node = std::find_if(workspace.nodes.begin(), workspace.nodes.end(), auto node = std::ranges::find_if(workspace.nodes,
[&id](const auto &node) { [&id](const auto &node) {
return node->getId() == id; return node->getId() == id;
}); });
@@ -762,7 +763,7 @@ namespace hex::plugin::builtin {
if (ImGui::BeginPopup("Node Menu")) { if (ImGui::BeginPopup("Node Menu")) {
if (ImGui::MenuItem("hex.builtin.view.data_processor.menu.save_node"_lang)) { if (ImGui::MenuItem("hex.builtin.view.data_processor.menu.save_node"_lang)) {
// Find the node that was right-clicked // Find the node that was right-clicked
auto it = std::find_if(workspace.nodes.begin(), workspace.nodes.end(), auto it = std::ranges::find_if(workspace.nodes,
[this](const auto &node) { [this](const auto &node) {
return node->getId() == m_rightClickedId; return node->getId() == m_rightClickedId;
}); });
@@ -856,7 +857,7 @@ namespace hex::plugin::builtin {
auto value = i64(*reinterpret_cast<i128*>(defaultValue.data())); auto value = i64(*reinterpret_cast<i128*>(defaultValue.data()));
if (ImGui::InputScalar(Lang(attribute.getUnlocalizedName()), ImGuiDataType_S64, &value)) { if (ImGui::InputScalar(Lang(attribute.getUnlocalizedName()), ImGuiDataType_S64, &value)) {
std::fill(defaultValue.begin(), defaultValue.end(), 0x00); std::ranges::fill(defaultValue, 0x00);
i128 writeValue = value; i128 writeValue = value;
std::memcpy(defaultValue.data(), &writeValue, sizeof(writeValue)); std::memcpy(defaultValue.data(), &writeValue, sizeof(writeValue));
@@ -866,7 +867,7 @@ namespace hex::plugin::builtin {
auto value = double(*reinterpret_cast<long double*>(defaultValue.data())); auto value = double(*reinterpret_cast<long double*>(defaultValue.data()));
if (ImGui::InputScalar(Lang(attribute.getUnlocalizedName()), ImGuiDataType_Double, &value)) { if (ImGui::InputScalar(Lang(attribute.getUnlocalizedName()), ImGuiDataType_Double, &value)) {
std::fill(defaultValue.begin(), defaultValue.end(), 0x00); std::ranges::fill(defaultValue, 0x00);
long double writeValue = value; long double writeValue = value;
std::memcpy(defaultValue.data(), &writeValue, sizeof(writeValue)); std::memcpy(defaultValue.data(), &writeValue, sizeof(writeValue));

View File

@@ -1,5 +1,6 @@
#include "content/views/view_find.hpp" #include "content/views/view_find.hpp"
#include <algorithm>
#include <hex/api/achievement_manager.hpp> #include <hex/api/achievement_manager.hpp>
#include <hex/api/imhex_api/hex_editor.hpp> #include <hex/api/imhex_api/hex_editor.hpp>
#include <hex/api/events/events_interaction.hpp> #include <hex/api/events/events_interaction.hpp>
@@ -214,16 +215,16 @@ namespace hex::plugin::builtin {
newSettings.type = ASCII; newSettings.type = ASCII;
auto asciiResults = searchStrings(task, provider, searchRegion, newSettings); auto asciiResults = searchStrings(task, provider, searchRegion, newSettings);
std::copy(asciiResults.begin(), asciiResults.end(), std::back_inserter(results)); std::ranges::copy(asciiResults, std::back_inserter(results));
if (settings.type == ASCII_UTF16BE) { if (settings.type == ASCII_UTF16BE) {
newSettings.type = UTF16BE; newSettings.type = UTF16BE;
auto utf16Results = searchStrings(task, provider, searchRegion, newSettings); auto utf16Results = searchStrings(task, provider, searchRegion, newSettings);
std::copy(utf16Results.begin(), utf16Results.end(), std::back_inserter(results)); std::ranges::copy(utf16Results, std::back_inserter(results));
} else if (settings.type == ASCII_UTF16LE) { } else if (settings.type == ASCII_UTF16LE) {
newSettings.type = UTF16LE; newSettings.type = UTF16LE;
auto utf16Results = searchStrings(task, provider, searchRegion, newSettings); auto utf16Results = searchStrings(task, provider, searchRegion, newSettings);
std::copy(utf16Results.begin(), utf16Results.end(), std::back_inserter(results)); std::ranges::copy(utf16Results, std::back_inserter(results));
} }
return results; return results;
@@ -921,7 +922,7 @@ namespace hex::plugin::builtin {
ImGui::Checkbox(fmt::format("{} [0-9]", "hex.builtin.view.find.strings.numbers"_lang.get()).c_str(), &settings.numbers); ImGui::Checkbox(fmt::format("{} [0-9]", "hex.builtin.view.find.strings.numbers"_lang.get()).c_str(), &settings.numbers);
ImGui::Checkbox(fmt::format("{} [_]", "hex.builtin.view.find.strings.underscores"_lang.get()).c_str(), &settings.underscores); ImGui::Checkbox(fmt::format("{} [_]", "hex.builtin.view.find.strings.underscores"_lang.get()).c_str(), &settings.underscores);
ImGui::Checkbox(fmt::format("{} [!\"#$%...]", "hex.builtin.view.find.strings.symbols"_lang.get()).c_str(), &settings.symbols); ImGui::Checkbox(fmt::format("{} [!\"#$%...]", "hex.builtin.view.find.strings.symbols"_lang.get()).c_str(), &settings.symbols);
ImGui::Checkbox(fmt::format("{} [ \\f\\t\\v]", "hex.builtin.view.find.strings.spaces"_lang.get()).c_str(), &settings.spaces); ImGui::Checkbox(fmt::format(R"({} [ \f\t\v])", "hex.builtin.view.find.strings.spaces"_lang.get()).c_str(), &settings.spaces);
ImGui::Checkbox(fmt::format("{} [\\r\\n]", "hex.builtin.view.find.strings.line_feeds"_lang.get()).c_str(), &settings.lineFeeds); ImGui::Checkbox(fmt::format("{} [\\r\\n]", "hex.builtin.view.find.strings.line_feeds"_lang.get()).c_str(), &settings.lineFeeds);
ImGui::EndPopup(); ImGui::EndPopup();
@@ -1158,11 +1159,11 @@ namespace hex::plugin::builtin {
m_filterTask.interrupt(); m_filterTask.interrupt();
static std::mutex mutex; static std::mutex mutex;
std::lock_guard lock(mutex); std::scoped_lock lock(mutex);
if (!m_currFilter->empty()) { if (!m_currFilter->empty()) {
m_filterTask = TaskManager::createTask("hex.builtin.task.filtering_data", currOccurrences.size(), [this, provider, &currOccurrences, filter = m_currFilter.get(provider)](Task &task) { m_filterTask = TaskManager::createTask("hex.builtin.task.filtering_data", currOccurrences.size(), [this, provider, &currOccurrences, filter = m_currFilter.get(provider)](Task &task) {
std::lock_guard lock(mutex); std::scoped_lock lock(mutex);
u64 progress = 0; u64 progress = 0;
std::erase_if(currOccurrences, [this, provider, &task, &progress, &filter](const auto &region) { std::erase_if(currOccurrences, [this, provider, &task, &progress, &filter](const auto &region) {

View File

@@ -304,7 +304,7 @@ namespace hex::plugin::builtin {
try { try {
const auto attribute = pattern->getAttributeArguments(SimplifiedEditorAttribute); const auto attribute = pattern->getAttributeArguments(SimplifiedEditorAttribute);
const auto name = attribute.size() >= 1 ? attribute[0].toString() : pattern->getDisplayName(); const auto name = !attribute.empty() ? attribute[0].toString() : pattern->getDisplayName();
const auto description = attribute.size() >= 2 ? attribute[1].toString() : pattern->getComment(); const auto description = attribute.size() >= 2 ? attribute[1].toString() : pattern->getComment();
const auto widgetPos = 200_scaled; const auto widgetPos = 200_scaled;

View File

@@ -456,8 +456,8 @@ namespace hex::plugin::builtin {
) )
) )
); );
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f)); ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0F, 0.0F));
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0.0f, 0.0f)); ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0.0F, 0.0F));
if (ImGui::BeginChild("##pattern_editor_resizer", defaultEditorSize, ImGuiChildFlags_ResizeY)) { if (ImGui::BeginChild("##pattern_editor_resizer", defaultEditorSize, ImGuiChildFlags_ResizeY)) {
m_textEditor.get(provider).render("##pattern_editor", ImGui::GetContentRegionAvail(), false); m_textEditor.get(provider).render("##pattern_editor", ImGui::GetContentRegionAvail(), false);
m_textEditorHoverBox = ImGui::GetCurrentWindow()->Rect(); m_textEditorHoverBox = ImGui::GetCurrentWindow()->Rect();
@@ -1257,7 +1257,7 @@ namespace hex::plugin::builtin {
m_hasUnevaluatedChanges.get(provider) = true; m_hasUnevaluatedChanges.get(provider) = true;
variable.value = buffer[0]; variable.value = buffer[0];
} else if (variable.type == pl::core::Token::ValueType::String) { } else if (variable.type == pl::core::Token::ValueType::String) {
std::string buffer = hex::get_or<std::string>(variable.value, ""); auto buffer = hex::get_or<std::string>(variable.value, "");
if (ImGui::InputText(label.c_str(), buffer)) if (ImGui::InputText(label.c_str(), buffer))
m_hasUnevaluatedChanges.get(provider) = true; m_hasUnevaluatedChanges.get(provider) = true;
variable.value = buffer; variable.value = buffer;
@@ -1354,7 +1354,7 @@ namespace hex::plugin::builtin {
for (const auto &frame : **m_callStack | std::views::reverse) { for (const auto &frame : **m_callStack | std::views::reverse) {
auto location = frame.node->getLocation(); auto location = frame.node->getLocation();
if (location.source != nullptr && location.source->mainSource) { if (location.source != nullptr && location.source->mainSource) {
std::string message = ""; std::string message;
if (m_lastEvaluationError->has_value()) if (m_lastEvaluationError->has_value())
message = processMessage((*m_lastEvaluationError)->message); message = processMessage((*m_lastEvaluationError)->message);
auto key = ui::TextEditor::Coordinates(location.line, location.column); auto key = ui::TextEditor::Coordinates(location.line, location.column);
@@ -1646,7 +1646,7 @@ namespace hex::plugin::builtin {
ContentRegistry::PatternLanguage::configureRuntime(*m_editorRuntime, nullptr); ContentRegistry::PatternLanguage::configureRuntime(*m_editorRuntime, nullptr);
const auto &ast = m_editorRuntime->parseString(code, pl::api::Source::DefaultSource); const auto &ast = m_editorRuntime->parseString(code, pl::api::Source::DefaultSource);
m_textEditor.get(provider).setLongestLineLength(m_editorRuntime->getInternals().preprocessor.get()->getLongestLineLength()); m_textEditor.get(provider).setLongestLineLength(m_editorRuntime->getInternals().preprocessor->getLongestLineLength());
auto &patternVariables = m_patternVariables.get(provider); auto &patternVariables = m_patternVariables.get(provider);
auto oldPatternVariables = std::move(patternVariables); auto oldPatternVariables = std::move(patternVariables);
@@ -2132,7 +2132,7 @@ namespace hex::plugin::builtin {
if (m_breakpoints->contains(line)) if (m_breakpoints->contains(line))
evaluator->removeBreakpoint(line); evaluator->removeBreakpoint(line);
else else
evaluator->addBreakpoint(line); evaluator->addBreakpoint(line);
m_breakpoints = evaluator->getBreakpoints(); m_breakpoints = evaluator->getBreakpoints();

View File

@@ -1,3 +1,4 @@
#include <algorithm>
#include <hex.hpp> #include <hex.hpp>
#include <hex/api/workspace_manager.hpp> #include <hex/api/workspace_manager.hpp>
@@ -162,7 +163,7 @@ namespace hex::plugin::builtin {
bool isAnyViewOpen() { bool isAnyViewOpen() {
const auto &views = ContentRegistry::Views::impl::getEntries(); const auto &views = ContentRegistry::Views::impl::getEntries();
return std::any_of(views.begin(), views.end(), return std::ranges::any_of(views,
[](const auto &entry) { [](const auto &entry) {
return entry.second->getWindowOpenState(); return entry.second->getWindowOpenState();
}); });
@@ -819,7 +820,7 @@ namespace hex::plugin::builtin {
std::mt19937 random(daysSinceEpoch.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()]; const auto& chosenTip = chosenCategory[random()%chosenCategory.size()];
s_tipOfTheDay = chosenTip.get<std::string>(); s_tipOfTheDay = chosenTip.get<std::string>();
bool showTipOfTheDay = ContentRegistry::Settings::read<bool>("hex.builtin.setting.general", "hex.builtin.setting.general.show_tips", false); bool showTipOfTheDay = ContentRegistry::Settings::read<bool>("hex.builtin.setting.general", "hex.builtin.setting.general.show_tips", false);

View File

@@ -1,3 +1,4 @@
#include <algorithm>
#include <hex/api/content_registry/user_interface.hpp> #include <hex/api/content_registry/user_interface.hpp>
#include <hex/api/content_registry/views.hpp> #include <hex/api/content_registry/views.hpp>
#include <hex/api/content_registry/settings.hpp> #include <hex/api/content_registry/settings.hpp>
@@ -601,7 +602,7 @@ namespace hex::plugin::builtin {
if (const auto &items = ContentRegistry::UserInterface::impl::getSidebarItems(); items.empty()) { if (const auto &items = ContentRegistry::UserInterface::impl::getSidebarItems(); items.empty()) {
return false; return false;
} else { } else {
return std::any_of(items.begin(), items.end(), [](const auto &item) { return std::ranges::any_of(items, [](const auto &item) {
return item.enabledCallback(); return item.enabledCallback();
}); });
} }
@@ -609,7 +610,7 @@ namespace hex::plugin::builtin {
bool isAnyViewOpen() { bool isAnyViewOpen() {
const auto &views = ContentRegistry::Views::impl::getEntries(); const auto &views = ContentRegistry::Views::impl::getEntries();
return std::any_of(views.begin(), views.end(), return std::ranges::any_of(views,
[](const auto &entry) { [](const auto &entry) {
return entry.second->getWindowOpenState(); return entry.second->getWindowOpenState();
}); });

View File

@@ -1,5 +1,6 @@
#include <hex/plugin.hpp> #include <plugin_builtin.hpp>
#include <hex/plugin.hpp>
#include <hex/api/content_registry/settings.hpp> #include <hex/api/content_registry/settings.hpp>
#include <hex/api/task_manager.hpp> #include <hex/api/task_manager.hpp>
#include <hex/helpers/logger.hpp> #include <hex/helpers/logger.hpp>
@@ -15,54 +16,6 @@
using namespace hex; using namespace hex;
namespace hex::plugin::builtin {
void registerEventHandlers();
void registerDataVisualizers();
void registerMiniMapVisualizers();
void registerDataInspectorEntries();
void registerToolEntries();
void registerPatternLanguageFunctions();
void registerPatternLanguageTypes();
void registerPatternLanguagePragmas();
void registerPatternLanguageVisualizers();
void registerCommandPaletteCommands();
void registerSettings();
void loadSettings();
void registerDataProcessorNodes();
void registerProviders();
void registerDataFormatters();
void registerMainMenuEntries();
void createWelcomeScreen();
void registerViews();
void registerThemeHandlers();
void registerStyleHandlers();
void registerThemes();
void registerBackgroundServices();
void registerNetworkEndpoints();
void registerMCPTools();
void registerFileHandlers();
void registerProjectHandlers();
void registerAchievements();
void registerReportGenerators();
void registerTutorials();
void registerDataInformationSections();
void loadWorkspaces();
void addWindowDecoration();
void addFooterItems();
void addTitleBarButtons();
void addToolbarItems();
void addGlobalUIItems();
void addInitTasks();
void handleBorderlessWindowMode();
void setupOutOfBoxExperience();
void extractBundledFiles();
}
IMHEX_PLUGIN_SUBCOMMANDS() { IMHEX_PLUGIN_SUBCOMMANDS() {
{ "help", "h", "Print help about this command", hex::plugin::builtin::handleHelpCommand }, { "help", "h", "Print help about this command", hex::plugin::builtin::handleHelpCommand },
{ "version", "", "Print ImHex version", hex::plugin::builtin::handleVersionCommand }, { "version", "", "Print ImHex version", hex::plugin::builtin::handleVersionCommand },

View File

@@ -3,14 +3,10 @@
#include <string> #include <string>
#include <vector> #include <vector>
#include <array> #include <array>
#include <memory>
#include <functional>
#include <unordered_set> #include <unordered_set>
#include <unordered_map> #include <unordered_map>
#include <map> #include <map>
#include <regex> #include <regex>
#include <chrono>
#include <iostream>
#include "imgui.h" #include "imgui.h"
#include "imgui_internal.h" #include "imgui_internal.h"
#include <hex/helpers/utils.hpp> #include <hex/helpers/utils.hpp>
@@ -107,7 +103,7 @@ namespace hex::ui {
public: public:
friend class TextEditor; friend class TextEditor;
bool operator==(const EditorState &o) const; bool operator==(const EditorState &o) const;
EditorState() : m_selection(), m_cursorPosition() {} EditorState() = default;
EditorState(const Range &selection, const Coordinates &cursorPosition) : m_selection(selection), m_cursorPosition(cursorPosition) {} EditorState(const Range &selection, const Coordinates &cursorPosition) : m_selection(selection), m_cursorPosition(cursorPosition) {}
private: private:
Range m_selection; Range m_selection;
@@ -277,37 +273,37 @@ namespace hex::ui {
enum class LinePart { Chars, Utf8, Colors, Flags }; enum class LinePart { Chars, Utf8, Colors, Flags };
Line() : m_chars(""), m_colors(""), m_flags(""), m_colorized(false), m_lineMaxColumn(-1) {} Line() : m_lineMaxColumn(-1) {}
explicit Line(const char *line) : Line(std::string(line)) {} explicit Line(const char *line) : Line(std::string(line)) {}
explicit Line(const std::string &line) : m_chars(line), m_colors(std::string(line.size(), 0x00)), m_flags(std::string(line.size(), 0x00)), m_colorized(false), m_lineMaxColumn(maxColumn()) {} explicit Line(const std::string &line) : m_chars(line), m_colors(std::string(line.size(), 0x00)), m_flags(std::string(line.size(), 0x00)), m_lineMaxColumn(maxColumn()) {}
Line(const Line &line) : m_chars(std::string(line.m_chars)), m_colors(std::string(line.m_colors)), m_flags(std::string(line.m_flags)), m_colorized(line.m_colorized), m_lineMaxColumn(line.m_lineMaxColumn) {} Line(const Line &line) : m_chars(std::string(line.m_chars)), m_colors(std::string(line.m_colors)), m_flags(std::string(line.m_flags)), m_colorized(line.m_colorized), m_lineMaxColumn(line.m_lineMaxColumn) {}
Line(Line &&line) noexcept : m_chars(std::move(line.m_chars)), m_colors(std::move(line.m_colors)), m_flags(std::move(line.m_flags)), m_colorized(line.m_colorized), m_lineMaxColumn(line.m_lineMaxColumn) {} Line(Line &&line) noexcept : m_chars(std::move(line.m_chars)), m_colors(std::move(line.m_colors)), m_flags(std::move(line.m_flags)), m_colorized(line.m_colorized), m_lineMaxColumn(line.m_lineMaxColumn) {}
Line(std::string chars, std::string colors, std::string flags) : m_chars(std::move(chars)), m_colors(std::move(colors)), m_flags(std::move(flags)), m_colorized(false), m_lineMaxColumn(maxColumn()) {} Line(std::string chars, std::string colors, std::string flags) : m_chars(std::move(chars)), m_colors(std::move(colors)), m_flags(std::move(flags)), m_lineMaxColumn(maxColumn()) {}
bool operator==(const Line &o) const; bool operator==(const Line &line) const;
bool operator!=(const Line &o) const; bool operator!=(const Line &line) const;
i32 indexColumn(i32 stringIndex) const; [[nodiscard]] i32 indexColumn(i32 stringIndex) const;
i32 maxColumn(); [[nodiscard]] i32 maxColumn();
i32 maxColumn() const; [[nodiscard]] i32 maxColumn() const;
i32 columnIndex(i32 column) const; [[nodiscard]] i32 columnIndex(i32 column) const;
i32 textSize() const; [[nodiscard]] i32 textSize() const;
i32 textSize(u32 index) const; [[nodiscard]] i32 textSize(u32 index) const;
i32 lineTextSize(TrimMode trimMode = TrimMode::TrimNone); i32 lineTextSize(TrimMode trimMode = TrimMode::TrimNone);
i32 stringTextSize(const std::string &str) const; [[nodiscard]] i32 stringTextSize(const std::string &str) const;
i32 textSizeIndex(float textSize, i32 position); i32 textSizeIndex(float textSize, i32 position);
LineIterator begin() const; [[nodiscard]] LineIterator begin() const;
LineIterator end() const; [[nodiscard]] LineIterator end() const;
LineIterator begin(); LineIterator begin();
LineIterator end(); LineIterator end();
Line &operator=(const Line &line); Line &operator=(const Line &line);
Line &operator=(Line &&line) noexcept; Line &operator=(Line &&line) noexcept;
u64 size() const; [[nodiscard]] u64 size() const;
TextEditor::Line trim(TrimMode trimMode); TextEditor::Line trim(TrimMode trimMode);
char front(LinePart part = LinePart::Chars) const; [[nodiscard]] char front(LinePart part = LinePart::Chars) const;
std::string frontUtf8(LinePart part = LinePart::Chars) const; [[nodiscard]] std::string frontUtf8(LinePart part = LinePart::Chars) const;
void push_back(char c); void push_back(char c);
bool empty() const; [[nodiscard]] bool empty() const;
std::string substr(u64 start, u64 length = (u64) -1, LinePart part = LinePart::Chars) const; [[nodiscard]] std::string substr(u64 start, u64 length = (u64) -1, LinePart part = LinePart::Chars) const;
Line subLine(u64 start, u64 length = (u64) -1); Line subLine(u64 start, u64 length = (u64) -1);
char operator[](u64 index) const; char operator[](u64 index) const;
// C++ can't overload functions based on return type, so use any type other // C++ can't overload functions based on return type, so use any type other
@@ -315,12 +311,12 @@ namespace hex::ui {
std::string operator[](i64 column) const; std::string operator[](i64 column) const;
void setNeedsUpdate(bool needsUpdate); void setNeedsUpdate(bool needsUpdate);
void append(const char *text); void append(const char *text);
void append(const char text); void append(char text);
void append(const std::string &text); void append(const std::string &text);
void append(const Line &line); void append(const Line &line);
void append(LineIterator begin, LineIterator end); void append(LineIterator begin, LineIterator end);
void insert(LineIterator iter, const std::string &text); void insert(LineIterator iter, const std::string &text);
void insert(LineIterator iter, const char text); void insert(LineIterator iter, char text);
void insert(LineIterator iter, strConstIter beginString, strConstIter endString); void insert(LineIterator iter, strConstIter beginString, strConstIter endString);
void insert(LineIterator iter, const Line &line); void insert(LineIterator iter, const Line &line);
void insert(LineIterator iter, LineIterator beginLine, LineIterator endLine); void insert(LineIterator iter, LineIterator beginLine, LineIterator endLine);
@@ -330,7 +326,7 @@ namespace hex::ui {
void clear(); void clear();
void setLine(const std::string &text); void setLine(const std::string &text);
void setLine(const Line &text); void setLine(const Line &text);
bool needsUpdate() const; [[nodiscard]] bool needsUpdate() const;
bool isEndOfLine(i32 column); bool isEndOfLine(i32 column);
private: private:
std::string m_chars; std::string m_chars;
@@ -352,14 +348,14 @@ namespace hex::ui {
Identifiers m_identifiers; Identifiers m_identifiers;
Identifiers m_preprocIdentifiers; Identifiers m_preprocIdentifiers;
std::string m_singleLineComment, m_commentEnd, m_commentStart, m_globalDocComment, m_docComment, m_blockDocComment; std::string m_singleLineComment, m_commentEnd, m_commentStart, m_globalDocComment, m_docComment, m_blockDocComment;
char m_preprocChar; char m_preprocChar = '#';
bool m_autoIndentation; bool m_autoIndentation = true;
TokenizeCallback m_tokenize; TokenizeCallback m_tokenize;
TokenRegexStrings m_tokenRegexStrings; TokenRegexStrings m_tokenRegexStrings;
bool m_caseSensitive; bool m_caseSensitive = true;
LanguageDefinition() : m_name(""), m_keywords({}), m_identifiers({}), m_preprocIdentifiers({}), m_singleLineComment(""), m_commentEnd(""), m_commentStart(""), m_globalDocComment(""), LanguageDefinition() : m_keywords({}), m_identifiers({}), m_preprocIdentifiers({}),
m_docComment(""), m_blockDocComment(""), m_preprocChar('#'), m_autoIndentation(true), m_tokenize(nullptr), m_tokenRegexStrings({}), m_caseSensitive(true) {} m_tokenize(nullptr), m_tokenRegexStrings({}) {}
static const LanguageDefinition &CPlusPlus(); static const LanguageDefinition &CPlusPlus();
static const LanguageDefinition &HLSL(); static const LanguageDefinition &HLSL();
@@ -376,12 +372,12 @@ namespace hex::ui {
class UndoRecord { class UndoRecord {
public: public:
friend class TextEditor; friend class TextEditor;
UndoRecord() {} UndoRecord() = default;
~UndoRecord() {} ~UndoRecord() {}
UndoRecord( const std::string &added, UndoRecord( const std::string &added,
const Range addedRange, Range addedRange,
const std::string &removed, const std::string &removed,
const Range removedRange, Range removedRange,
EditorState &before, EditorState &before,
EditorState &after); EditorState &after);
@@ -398,7 +394,7 @@ namespace hex::ui {
class UndoAction { class UndoAction {
public: public:
UndoAction() {} UndoAction() = default;
~UndoAction() {} ~UndoAction() {}
explicit UndoAction(const UndoRecords &records) : m_records(records) {} explicit UndoAction(const UndoRecords &records) : m_records(records) {}
void undo(TextEditor *editor); void undo(TextEditor *editor);
@@ -412,8 +408,8 @@ namespace hex::ui {
struct MatchedBracket { struct MatchedBracket {
bool m_active = false; bool m_active = false;
bool m_changed = false; bool m_changed = false;
Coordinates m_nearCursor = {}; Coordinates m_nearCursor;
Coordinates m_matched = {}; Coordinates m_matched;
static const std::string s_separators; static const std::string s_separators;
static const std::string s_operators; static const std::string s_operators;
@@ -421,7 +417,7 @@ namespace hex::ui {
m_nearCursor(other.m_nearCursor), m_nearCursor(other.m_nearCursor),
m_matched(other.m_matched) {} m_matched(other.m_matched) {}
MatchedBracket() : m_active(false), m_changed(false), m_nearCursor(0, 0), m_matched(0, 0) {} MatchedBracket() : m_nearCursor(0, 0), m_matched(0, 0) {}
MatchedBracket(bool active, bool changed, const Coordinates &nearCursor, const Coordinates &matched) MatchedBracket(bool active, bool changed, const Coordinates &nearCursor, const Coordinates &matched)
: m_active(active), m_changed(changed), m_nearCursor(nearCursor), m_matched(matched) {} : m_active(active), m_changed(changed), m_nearCursor(nearCursor), m_matched(matched) {}
@@ -429,8 +425,8 @@ namespace hex::ui {
bool isNearABracket(TextEditor *editor, const Coordinates &from); bool isNearABracket(TextEditor *editor, const Coordinates &from);
i32 detectDirection(TextEditor *editor, const Coordinates &from); i32 detectDirection(TextEditor *editor, const Coordinates &from);
void findMatchingBracket(TextEditor *editor); void findMatchingBracket(TextEditor *editor);
bool isActive() const { return m_active; } [[nodiscard]] bool isActive() const { return m_active; }
bool hasChanged() const { return m_changed; } [[nodiscard]] bool hasChanged() const { return m_changed; }
}; };
@@ -446,11 +442,11 @@ namespace hex::ui {
void setTopLine(); void setTopLine();
void render(const char *title, const ImVec2 &size = ImVec2(), bool border = false); void render(const char *title, const ImVec2 &size = ImVec2(), bool border = false);
inline void setShowCursor(bool value) { m_showCursor = value; } void setShowCursor(bool value) { m_showCursor = value; }
inline void setShowLineNumbers(bool value) { m_showLineNumbers = value; } void setShowLineNumbers(bool value) { m_showLineNumbers = value; }
inline void setShowWhitespaces(bool value) { m_showWhitespaces = value; } void setShowWhitespaces(bool value) { m_showWhitespaces = value; }
inline bool isShowingWhitespaces() const { return m_showWhitespaces; } bool isShowingWhitespaces() const { return m_showWhitespaces; }
inline i32 getTabSize() const { return m_tabSize; } i32 getTabSize() const { return m_tabSize; }
ImVec2 &getCharAdvance() { return m_charAdvance; } ImVec2 &getCharAdvance() { return m_charAdvance; }
void clearGotoBoxes() { m_errorGotoBoxes.clear(); } void clearGotoBoxes() { m_errorGotoBoxes.clear(); }
void clearCursorBoxes() { m_cursorBoxes.clear(); } void clearCursorBoxes() { m_cursorBoxes.clear(); }
@@ -461,7 +457,7 @@ namespace hex::ui {
void setLongestLineLength(u64 line) { m_longestLineLength = line; } void setLongestLineLength(u64 line) { m_longestLineLength = line; }
u64 getLongestLineLength() const { return m_longestLineLength; } u64 getLongestLineLength() const { return m_longestLineLength; }
void setTopMarginChanged(i32 newMargin); void setTopMarginChanged(i32 newMargin);
void setFocusAtCoords(const Coordinates &coords, bool ensureVisible = false); void setFocusAtCoords(const Coordinates &coords, bool scrollToCursor = false);
void clearErrorMarkers(); void clearErrorMarkers();
void clearActionables(); void clearActionables();
private: private:
@@ -518,16 +514,16 @@ namespace hex::ui {
std::vector<std::string> getTextLines() const; std::vector<std::string> getTextLines() const;
std::string getSelectedText(); std::string getSelectedText();
std::string getLineText(i32 line); std::string getLineText(i32 line);
inline void setTextChanged(bool value) { m_textChanged = value; } void setTextChanged(bool value) { m_textChanged = value; }
inline bool isTextChanged() { return m_textChanged; } bool isTextChanged() { return m_textChanged; }
inline void setReadOnly(bool value) { m_readOnly = value; } void setReadOnly(bool value) { m_readOnly = value; }
inline void setHandleMouseInputs(bool value) { m_handleMouseInputs = value; } void setHandleMouseInputs(bool value) { m_handleMouseInputs = value; }
inline bool isHandleMouseInputsEnabled() const { return m_handleKeyboardInputs; } bool isHandleMouseInputsEnabled() const { return m_handleMouseInputs; }
inline void setHandleKeyboardInputs(bool value) { m_handleKeyboardInputs = value; } void setHandleKeyboardInputs(bool value) { m_handleKeyboardInputs = value; }
inline bool isHandleKeyboardInputsEnabled() const { return m_handleKeyboardInputs; } bool isHandleKeyboardInputsEnabled() const { return m_handleKeyboardInputs; }
private: private:
std::string getText(const Range &selection); std::string getText(const Range &from);
void deleteRange(const Range &selection); void deleteRange(const Range &rangeToDelete);
i32 insertTextAt(Coordinates &where, const std::string &value); i32 insertTextAt(Coordinates &where, const std::string &value);
void removeLine(i32 start, i32 end); void removeLine(i32 start, i32 end);
void removeLine(i32 index); void removeLine(i32 index);
@@ -575,10 +571,10 @@ namespace hex::ui {
i32 getTotalLines() const { return (i32) m_lines.size(); } i32 getTotalLines() const { return (i32) m_lines.size(); }
FindReplaceHandler *getFindReplaceHandler() { return &m_findReplaceHandler; } FindReplaceHandler *getFindReplaceHandler() { return &m_findReplaceHandler; }
void setSourceCodeEditor(TextEditor *editor) { m_sourceCodeEditor = editor; } void setSourceCodeEditor(TextEditor *editor) { m_sourceCodeEditor = editor; }
inline void clearBreakpointsChanged() { m_breakPointsChanged = false; } void clearBreakpointsChanged() { m_breakPointsChanged = false; }
inline bool isBreakpointsChanged() { return m_breakPointsChanged; } bool isBreakpointsChanged() { return m_breakPointsChanged; }
inline void setImGuiChildIgnored(bool value) { m_ignoreImGuiChild = value; } void setImGuiChildIgnored(bool value) { m_ignoreImGuiChild = value; }
inline bool isImGuiChildIgnored() const { return m_ignoreImGuiChild; } bool isImGuiChildIgnored() const { return m_ignoreImGuiChild; }
bool raiseContextMenu() { return m_raiseContextMenu; } bool raiseContextMenu() { return m_raiseContextMenu; }
void clearRaiseContextMenu() { m_raiseContextMenu = false; } void clearRaiseContextMenu() { m_raiseContextMenu = false; }
TextEditor *getSourceCodeEditor(); TextEditor *getSourceCodeEditor();
@@ -610,7 +606,7 @@ namespace hex::ui {
private: private:
float m_lineSpacing = 1.0F; float m_lineSpacing = 1.0F;
Lines m_lines; Lines m_lines;
EditorState m_state = {}; EditorState m_state;
UndoBuffer m_undoBuffer; UndoBuffer m_undoBuffer;
i32 m_undoIndex = 0; i32 m_undoIndex = 0;
bool m_scrollToBottom = false; bool m_scrollToBottom = false;
@@ -638,18 +634,18 @@ namespace hex::ui {
bool m_ignoreImGuiChild = false; bool m_ignoreImGuiChild = false;
bool m_showWhitespaces = true; bool m_showWhitespaces = true;
MatchedBracket m_matchedBracket = {}; MatchedBracket m_matchedBracket;
Palette m_palette = {}; Palette m_palette = {};
LanguageDefinition m_languageDefinition = {}; LanguageDefinition m_languageDefinition;
RegexList m_regexList; RegexList m_regexList;
bool m_updateFlags = true; bool m_updateFlags = true;
Breakpoints m_breakpoints = {}; Breakpoints m_breakpoints;
ErrorMarkers m_errorMarkers = {}; ErrorMarkers m_errorMarkers;
ErrorHoverBoxes m_errorHoverBoxes = {}; ErrorHoverBoxes m_errorHoverBoxes;
ErrorGotoBoxes m_errorGotoBoxes = {}; ErrorGotoBoxes m_errorGotoBoxes;
CursorBoxes m_cursorBoxes = {}; CursorBoxes m_cursorBoxes;
ImVec2 m_charAdvance = {}; ImVec2 m_charAdvance;
Range m_interactiveSelection = {}; Range m_interactiveSelection;
u64 m_startTime = 0; u64 m_startTime = 0;
std::vector<std::string> m_defines; std::vector<std::string> m_defines;
TextEditor *m_sourceCodeEditor = nullptr; TextEditor *m_sourceCodeEditor = nullptr;
@@ -663,7 +659,7 @@ namespace hex::ui {
bool m_showCursor = true; bool m_showCursor = true;
bool m_showLineNumbers = true; bool m_showLineNumbers = true;
bool m_raiseContextMenu = false; bool m_raiseContextMenu = false;
Coordinates m_focusAtCoords = {}; Coordinates m_focusAtCoords;
bool m_updateFocus = false; bool m_updateFocus = false;
std::vector<std::string> m_clickableText; std::vector<std::string> m_clickableText;

View File

@@ -250,7 +250,7 @@ namespace hex::ui {
return wolv::container::Lazy<ImGuiExt::Texture>([data = std::move(data)]() -> ImGuiExt::Texture { return wolv::container::Lazy<ImGuiExt::Texture>([data = std::move(data)]() -> ImGuiExt::Texture {
if (data.empty()) if (data.empty())
return ImGuiExt::Texture(); return {};
auto texture = ImGuiExt::Texture::fromImage(data.data(), data.size(), ImGuiExt::Texture::Filter::Linear); auto texture = ImGuiExt::Texture::fromImage(data.data(), data.size(), ImGuiExt::Texture::Filter::Linear);
if (!texture.isValid()) { if (!texture.isValid()) {

View File

@@ -1,3 +1,4 @@
#include <algorithm>
#include <ui/pattern_drawer.hpp> #include <ui/pattern_drawer.hpp>
#include <pl/core/lexer.hpp> #include <pl/core/lexer.hpp>
@@ -320,10 +321,9 @@ namespace hex::ui {
m_filteredPatterns.push_back(pattern); m_filteredPatterns.push_back(pattern);
} else { } else {
auto patternValue = pattern->getValue(); auto patternValue = pattern->getValue();
if (!m_filter->inverted && (patternValue <=> *m_filter->value) == m_filter->operation) { auto operation = patternValue <=> *m_filter->value;
if (!m_filter->typeMatch || (m_filter->value->index() == patternValue.index())) bool isOperationOk = operation == m_filter->operation;
m_filteredPatterns.push_back(pattern); if ((!m_filter->inverted && isOperationOk) || (m_filter->inverted && !isOperationOk)) {
} else if (m_filter->inverted && (patternValue <=> *m_filter->value) != m_filter->operation) {
if (!m_filter->typeMatch || (m_filter->value->index() == patternValue.index())) if (!m_filter->typeMatch || (m_filter->value->index() == patternValue.index()))
m_filteredPatterns.push_back(pattern); m_filteredPatterns.push_back(pattern);
} }
@@ -480,7 +480,7 @@ namespace hex::ui {
pattern = pattern->getParent(); pattern = pattern->getParent();
} }
std::reverse(result.begin(), result.end()); std::ranges::reverse(result);
return result; return result;
} }
@@ -1221,7 +1221,7 @@ namespace hex::ui {
if (!m_favoritesUpdateTask.isRunning()) { if (!m_favoritesUpdateTask.isRunning()) {
sortedPatterns = patterns; sortedPatterns = patterns;
std::stable_sort(sortedPatterns.begin(), sortedPatterns.end(), [this, &sortSpecs](const std::shared_ptr<pl::ptrn::Pattern> &left, const std::shared_ptr<pl::ptrn::Pattern> &right) -> bool { std::ranges::stable_sort(sortedPatterns, [this, &sortSpecs](const std::shared_ptr<pl::ptrn::Pattern> &left, const std::shared_ptr<pl::ptrn::Pattern> &right) -> bool {
return this->sortPatterns(sortSpecs, left.get(), right.get()); return this->sortPatterns(sortSpecs, left.get(), right.get());
}); });
@@ -1365,7 +1365,7 @@ namespace hex::ui {
for (const auto &formatter : m_formatters) { for (const auto &formatter : m_formatters) {
const auto name = [&]{ const auto name = [&]{
auto formatterName = formatter->getName(); auto formatterName = formatter->getName();
std::transform(formatterName.begin(), formatterName.end(), formatterName.begin(), [](char c){ return char(std::toupper(c)); }); std::ranges::transform(formatterName, formatterName.begin(), [](char c){ return char(std::toupper(c)); });
return formatterName; return formatterName;
}(); }();

View File

@@ -1,3 +1,4 @@
#include <algorithm>
#include <ui/text_editor.hpp> #include <ui/text_editor.hpp>
#include <algorithm> #include <algorithm>
#include <string> #include <string>
@@ -21,11 +22,10 @@ namespace hex::ui {
TextEditor::TextEditor() { TextEditor::TextEditor() {
m_startTime = ImGui::GetTime() * 1000; m_startTime = ImGui::GetTime() * 1000;
setLanguageDefinition(LanguageDefinition::HLSL()); setLanguageDefinition(LanguageDefinition::HLSL());
m_lines.push_back(Line()); m_lines.emplace_back();
} }
TextEditor::~TextEditor() { TextEditor::~TextEditor() = default;
}
std::string TextEditor::getText(const Range &from) { std::string TextEditor::getText(const Range &from) {
std::string result; std::string result;
@@ -83,7 +83,7 @@ namespace hex::ui {
m_lines[0].m_lineMaxColumn = -1; m_lines[0].m_lineMaxColumn = -1;
m_lines[0].m_lineMaxColumn = m_lines[0].maxColumn(); m_lines[0].m_lineMaxColumn = m_lines[0].maxColumn();
} else { } else {
m_lines.push_back(Line(text)); m_lines.emplace_back(text);
auto &line = m_lines.back(); auto &line = m_lines.back();
line.m_lineMaxColumn = -1; line.m_lineMaxColumn = -1;
line.m_lineMaxColumn = line.maxColumn(); line.m_lineMaxColumn = line.maxColumn();
@@ -366,7 +366,7 @@ namespace hex::ui {
u.m_addedRange.m_start = coord; u.m_addedRange.m_start = coord;
if (m_lines.empty()) if (m_lines.empty())
m_lines.push_back(Line()); m_lines.emplace_back();
if (character == '\n') { if (character == '\n') {
insertLine(coord.m_line + 1); insertLine(coord.m_line + 1);
@@ -426,9 +426,9 @@ namespace hex::ui {
} }
u.m_addedRange.m_end = setCoordinates(m_state.m_cursorPosition); u.m_addedRange.m_end = setCoordinates(m_state.m_cursorPosition);
} else { } else {
std::string buf = ""; std::string buf;
imTextCharToUtf8(buf, character); imTextCharToUtf8(buf, character);
if (buf.size() > 0) { if (!buf.empty()) {
auto &line = m_lines[coord.m_line]; auto &line = m_lines[coord.m_line];
auto charIndex = lineCoordinatesToIndex(coord); auto charIndex = lineCoordinatesToIndex(coord);
@@ -679,7 +679,7 @@ namespace hex::ui {
if (!isEmpty()) { if (!isEmpty()) {
std::string str; std::string str;
const auto &line = m_lines[setCoordinates(m_state.m_cursorPosition).m_line]; const auto &line = m_lines[setCoordinates(m_state.m_cursorPosition).m_line];
std::copy(line.m_chars.begin(), line.m_chars.end(), std::back_inserter(str)); std::ranges::copy(line.m_chars, std::back_inserter(str));
ImGui::SetClipboardText(str.c_str()); ImGui::SetClipboardText(str.c_str());
} }
} }
@@ -744,7 +744,7 @@ namespace hex::ui {
const char *clipText = ImGui::GetClipboardText(); const char *clipText = ImGui::GetClipboardText();
if (clipText != nullptr) { if (clipText != nullptr) {
auto stringVector = wolv::util::splitString(clipText, "\n", false); auto stringVector = wolv::util::splitString(clipText, "\n", false);
if (std::any_of(stringVector.begin(), stringVector.end(), [](const std::string &s) { return s.size() > 1024; })) { if (std::ranges::any_of(stringVector, [](const std::string &s) { return s.size() > 1024; })) {
ui::PopupQuestion::open("hex.builtin.view.pattern_editor.warning_paste_large"_lang, [this, clipText]() { ui::PopupQuestion::open("hex.builtin.view.pattern_editor.warning_paste_large"_lang, [this, clipText]() {
this->doPaste(clipText); this->doPaste(clipText);
}, [] {}); }, [] {});
@@ -858,8 +858,8 @@ namespace hex::ui {
} }
void TextEditor::UndoAction::redo(TextEditor *editor) { void TextEditor::UndoAction::redo(TextEditor *editor) {
for (i32 i = 0; i < (i32) m_records.size(); i++) for (auto & m_record : m_records)
m_records.at(i).redo(editor); m_record.redo(editor);
} }
} }

View File

@@ -1,7 +1,7 @@
#include <algorithm>
#include <ui/text_editor.hpp> #include <ui/text_editor.hpp>
#include <hex/helpers/utils.hpp> #include <hex/helpers/utils.hpp>
#include <hex/helpers/logger.hpp> #include <hex/helpers/logger.hpp>
#include <algorithm>
namespace hex::ui { namespace hex::ui {
extern TextEditor::Palette s_paletteBase; extern TextEditor::Palette s_paletteBase;
@@ -25,7 +25,7 @@ namespace hex::ui {
auto &lineTokens = m_lines[line].m_colors; auto &lineTokens = m_lines[line].m_colors;
if (lineTokens.size() != tokens.size()) { if (lineTokens.size() != tokens.size()) {
lineTokens.resize(tokens.size()); lineTokens.resize(tokens.size());
std::fill(lineTokens.begin(), lineTokens.end(), 0x00); std::ranges::fill(lineTokens, 0x00);
} }
bool needsUpdate = false; bool needsUpdate = false;
for (u64 i = 0; i < tokens.size(); ++i) { for (u64 i = 0; i < tokens.size(); ++i) {
@@ -94,10 +94,10 @@ namespace hex::ui {
// todo : almost all language definitions use lower case to specify keywords, so shouldn't this use ::tolower ? // todo : almost all language definitions use lower case to specify keywords, so shouldn't this use ::tolower ?
if (!m_languageDefinition.m_caseSensitive) if (!m_languageDefinition.m_caseSensitive)
std::transform(id.begin(), id.end(), id.begin(), ::toupper); std::ranges::transform(id, id.begin(), ::toupper);
else if (m_languageDefinition.m_keywords.count(id) != 0) else if (m_languageDefinition.m_keywords.contains(id))
token_color = PaletteIndex::Keyword; token_color = PaletteIndex::Keyword;
else if (m_languageDefinition.m_identifiers.count(id) != 0) else if (m_languageDefinition.m_identifiers.contains(id))
token_color = PaletteIndex::BuiltInType; token_color = PaletteIndex::BuiltInType;
else if (id == "$") else if (id == "$")
token_color = PaletteIndex::GlobalVariable; token_color = PaletteIndex::GlobalVariable;
@@ -105,7 +105,7 @@ namespace hex::ui {
} else { } else {
if ((token_color == PaletteIndex::Identifier || flags.m_bits.preprocessor) && !flags.m_bits.deactivated && !(flags.m_value & inComment)) { if ((token_color == PaletteIndex::Identifier || flags.m_bits.preprocessor) && !flags.m_bits.deactivated && !(flags.m_value & inComment)) {
id.assign(token_begin, token_end); id.assign(token_begin, token_end);
if (m_languageDefinition.m_preprocIdentifiers.count(id) != 0) { if (m_languageDefinition.m_preprocIdentifiers.contains(id)) {
token_color = PaletteIndex::Directive; token_color = PaletteIndex::Directive;
token_begin -= 1; token_begin -= 1;
token_length = token_end - token_begin; token_length = token_end - token_begin;
@@ -125,7 +125,7 @@ namespace hex::ui {
token_color = PaletteIndex::PreprocessorDeactivated; token_color = PaletteIndex::PreprocessorDeactivated;
token_begin -= 1; token_begin -= 1;
token_offset -= 1; token_offset -= 1;
} else if (id.assign(token_begin, token_end);flags.m_value & inComment && m_languageDefinition.m_preprocIdentifiers.count(id) != 0) { } else if (id.assign(token_begin, token_end);flags.m_value & inComment && m_languageDefinition.m_preprocIdentifiers.contains(id)) {
token_color = getColorIndexFromFlags(flags); token_color = getColorIndexFromFlags(flags);
token_begin -= 1; token_begin -= 1;
token_offset -= 1; token_offset -= 1;
@@ -148,12 +148,12 @@ namespace hex::ui {
if (token_offset + token_length >= line.m_colors.size()) { if (token_offset + token_length >= line.m_colors.size()) {
auto colors = line.m_colors; auto colors = line.m_colors;
line.m_colors.resize(token_offset + token_length, static_cast<char>(PaletteIndex::Default)); line.m_colors.resize(token_offset + token_length, static_cast<char>(PaletteIndex::Default));
std::copy(colors.begin(), colors.end(), line.m_colors.begin()); std::ranges::copy(colors, line.m_colors.begin());
} }
try { try {
line.m_colors.replace(token_offset, token_length, token_length, static_cast<char>(token_color)); line.m_colors.replace(token_offset, token_length, token_length, static_cast<char>(token_color));
} catch (const std::exception &e) { } catch (const std::exception &e) {
std::cerr << "Error replacing color: " << e.what() << std::endl; fmt::print(stderr, "Error replacing color: {}\n", e.what());
return; return;
} }
} }
@@ -184,7 +184,7 @@ namespace hex::ui {
std::vector<bool> ifDefs; std::vector<bool> ifDefs;
ifDefs.push_back(true); ifDefs.push_back(true);
m_defines.push_back("__IMHEX__"); m_defines.emplace_back("__IMHEX__");
for (currentLine = 0; currentLine < endLine; currentLine++) { for (currentLine = 0; currentLine < endLine; currentLine++) {
auto &line = m_lines[currentLine]; auto &line = m_lines[currentLine];
auto lineLength = line.size(); auto lineLength = line.size();
@@ -298,10 +298,10 @@ namespace hex::ui {
auto definesBegin = m_defines.begin(); auto definesBegin = m_defines.begin();
auto definesEnd = m_defines.end(); auto definesEnd = m_defines.end();
if (directive == "define") { if (directive == "define") {
if (identifier.size() > 0 && !withinNotDef && std::find(definesBegin, definesEnd, identifier) == definesEnd) if (!identifier.empty() && !withinNotDef && std::find(definesBegin, definesEnd, identifier) == definesEnd)
m_defines.push_back(identifier); m_defines.push_back(identifier);
} else if (directive == "undef") { } else if (directive == "undef") {
if (identifier.size() > 0 && !withinNotDef) if (!identifier.empty() && !withinNotDef)
m_defines.erase(std::remove(definesBegin, definesEnd, identifier), definesEnd); m_defines.erase(std::remove(definesBegin, definesEnd, identifier), definesEnd);
} else if (directive == "ifdef") { } else if (directive == "ifdef") {
if (!withinNotDef) { if (!withinNotDef) {
@@ -407,7 +407,7 @@ namespace hex::ui {
m_regexList.clear(); m_regexList.clear();
for (auto &r: m_languageDefinition.m_tokenRegexStrings) for (auto &r: m_languageDefinition.m_tokenRegexStrings)
m_regexList.push_back(std::make_pair(std::regex(r.first, std::regex_constants::optimize), r.second)); m_regexList.emplace_back(std::regex(r.first, std::regex_constants::optimize), r.second);
colorize(); colorize();
} }
@@ -649,16 +649,16 @@ namespace hex::ui {
langDef.m_identifiers.insert(std::make_pair(std::string(k), id)); langDef.m_identifiers.insert(std::make_pair(std::string(k), id));
} }
langDef.m_tokenRegexStrings.push_back(std::make_pair("[ \\t]*#[ \\t]*[a-zA-Z_]+", PaletteIndex::Directive)); langDef.m_tokenRegexStrings.emplace_back("[ \\t]*#[ \\t]*[a-zA-Z_]+", PaletteIndex::Directive);
langDef.m_tokenRegexStrings.push_back(std::make_pair("L?\\\"(\\\\.|[^\\\"])*\\\"", PaletteIndex::StringLiteral)); langDef.m_tokenRegexStrings.emplace_back(R"(L?\"(\\.|[^\"])*\")", PaletteIndex::StringLiteral);
langDef.m_tokenRegexStrings.push_back(std::make_pair("\\'\\\\?[^\\']\\'", PaletteIndex::CharLiteral)); langDef.m_tokenRegexStrings.emplace_back(R"(\'\\?[^\']\')", PaletteIndex::CharLiteral);
langDef.m_tokenRegexStrings.push_back(std::make_pair("[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)([eE][+-]?[0-9]+)?[fF]?", PaletteIndex::NumericLiteral)); langDef.m_tokenRegexStrings.emplace_back("[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)([eE][+-]?[0-9]+)?[fF]?", PaletteIndex::NumericLiteral);
langDef.m_tokenRegexStrings.push_back(std::make_pair("[+-]?[0-9]+[Uu]?[lL]?[lL]?", PaletteIndex::NumericLiteral)); langDef.m_tokenRegexStrings.emplace_back("[+-]?[0-9]+[Uu]?[lL]?[lL]?", PaletteIndex::NumericLiteral);
langDef.m_tokenRegexStrings.push_back(std::make_pair("0[0-7]+[Uu]?[lL]?[lL]?", PaletteIndex::NumericLiteral)); langDef.m_tokenRegexStrings.emplace_back("0[0-7]+[Uu]?[lL]?[lL]?", PaletteIndex::NumericLiteral);
langDef.m_tokenRegexStrings.push_back(std::make_pair("0[xX][0-9a-fA-F]+[uU]?[lL]?[lL]?", PaletteIndex::NumericLiteral)); langDef.m_tokenRegexStrings.emplace_back("0[xX][0-9a-fA-F]+[uU]?[lL]?[lL]?", PaletteIndex::NumericLiteral);
langDef.m_tokenRegexStrings.push_back(std::make_pair("[a-zA-Z_][a-zA-Z0-9_]*", PaletteIndex::Identifier)); langDef.m_tokenRegexStrings.emplace_back("[a-zA-Z_][a-zA-Z0-9_]*", PaletteIndex::Identifier);
langDef.m_tokenRegexStrings.push_back(std::make_pair("[\\!\\%\\^\\&\\*\\-\\+\\=\\~\\|\\<\\>\\?\\/]", PaletteIndex::Operator)); langDef.m_tokenRegexStrings.emplace_back(R"([\!\%\^\&\*\-\+\=\~\|\<\>\?\/])", PaletteIndex::Operator);
langDef.m_tokenRegexStrings.push_back(std::make_pair("[\\[\\]\\{\\}\\(\\)\\;\\,\\.]", PaletteIndex::Separator)); langDef.m_tokenRegexStrings.emplace_back(R"([\[\]\{\}\(\)\;\,\.])", PaletteIndex::Separator);
langDef.m_commentStart = "/*"; langDef.m_commentStart = "/*";
langDef.m_commentEnd = "*/"; langDef.m_commentEnd = "*/";
langDef.m_singleLineComment = "//"; langDef.m_singleLineComment = "//";
@@ -700,16 +700,16 @@ namespace hex::ui {
langDef.m_identifiers.insert(std::make_pair(std::string(k), id)); langDef.m_identifiers.insert(std::make_pair(std::string(k), id));
} }
langDef.m_tokenRegexStrings.push_back(std::make_pair("[ \\t]*#[ \\t]*[a-zA-Z_]+", PaletteIndex::Directive)); langDef.m_tokenRegexStrings.emplace_back("[ \\t]*#[ \\t]*[a-zA-Z_]+", PaletteIndex::Directive);
langDef.m_tokenRegexStrings.push_back(std::make_pair("L?\\\"(\\\\.|[^\\\"])*\\\"", PaletteIndex::StringLiteral)); langDef.m_tokenRegexStrings.emplace_back(R"(L?\"(\\.|[^\"])*\")", PaletteIndex::StringLiteral);
langDef.m_tokenRegexStrings.push_back(std::make_pair("\\'\\\\?[^\\']\\'", PaletteIndex::CharLiteral)); langDef.m_tokenRegexStrings.emplace_back(R"(\'\\?[^\']\')", PaletteIndex::CharLiteral);
langDef.m_tokenRegexStrings.push_back(std::make_pair("[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)([eE][+-]?[0-9]+)?[fF]?",PaletteIndex::NumericLiteral)); langDef.m_tokenRegexStrings.emplace_back("[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)([eE][+-]?[0-9]+)?[fF]?",PaletteIndex::NumericLiteral);
langDef.m_tokenRegexStrings.push_back(std::make_pair("[+-]?[0-9]+[Uu]?[lL]?[lL]?", PaletteIndex::NumericLiteral)); langDef.m_tokenRegexStrings.emplace_back("[+-]?[0-9]+[Uu]?[lL]?[lL]?", PaletteIndex::NumericLiteral);
langDef.m_tokenRegexStrings.push_back(std::make_pair("0[0-7]+[Uu]?[lL]?[lL]?", PaletteIndex::NumericLiteral)); langDef.m_tokenRegexStrings.emplace_back("0[0-7]+[Uu]?[lL]?[lL]?", PaletteIndex::NumericLiteral);
langDef.m_tokenRegexStrings.push_back(std::make_pair("0[xX][0-9a-fA-F]+[uU]?[lL]?[lL]?", PaletteIndex::NumericLiteral)); langDef.m_tokenRegexStrings.emplace_back("0[xX][0-9a-fA-F]+[uU]?[lL]?[lL]?", PaletteIndex::NumericLiteral);
langDef.m_tokenRegexStrings.push_back(std::make_pair("[a-zA-Z_][a-zA-Z0-9_]*", PaletteIndex::Identifier)); langDef.m_tokenRegexStrings.emplace_back("[a-zA-Z_][a-zA-Z0-9_]*", PaletteIndex::Identifier);
langDef.m_tokenRegexStrings.push_back(std::make_pair("[\\!\\%\\^\\&\\*\\-\\+\\=\\~\\|\\<\\>\\?\\/]", PaletteIndex::Operator)); langDef.m_tokenRegexStrings.emplace_back(R"([\!\%\^\&\*\-\+\=\~\|\<\>\?\/])", PaletteIndex::Operator);
langDef.m_tokenRegexStrings.push_back(std::make_pair("[\\[\\]\\{\\}\\(\\)\\;\\,\\.]", PaletteIndex::Separator)); langDef.m_tokenRegexStrings.emplace_back(R"([\[\]\{\}\(\)\;\,\.])", PaletteIndex::Separator);
langDef.m_commentStart = "/*"; langDef.m_commentStart = "/*";
langDef.m_commentEnd = "*/"; langDef.m_commentEnd = "*/";
langDef.m_singleLineComment = "//"; langDef.m_singleLineComment = "//";
@@ -844,16 +844,16 @@ namespace hex::ui {
langDef.m_identifiers.insert(std::make_pair(std::string(k), id)); langDef.m_identifiers.insert(std::make_pair(std::string(k), id));
} }
langDef.m_tokenRegexStrings.push_back(std::make_pair("[ \\t]*#[ \\t]*[a-zA-Z_]+", PaletteIndex::Directive)); langDef.m_tokenRegexStrings.emplace_back("[ \\t]*#[ \\t]*[a-zA-Z_]+", PaletteIndex::Directive);
langDef.m_tokenRegexStrings.push_back(std::make_pair("L?\\\"(\\\\.|[^\\\"])*\\\"", PaletteIndex::StringLiteral)); langDef.m_tokenRegexStrings.emplace_back(R"(L?\"(\\.|[^\"])*\")", PaletteIndex::StringLiteral);
langDef.m_tokenRegexStrings.push_back(std::make_pair("\\'\\\\?[^\\']\\'", PaletteIndex::CharLiteral)); langDef.m_tokenRegexStrings.emplace_back(R"(\'\\?[^\']\')", PaletteIndex::CharLiteral);
langDef.m_tokenRegexStrings.push_back(std::make_pair("[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)([eE][+-]?[0-9]+)?[fF]?",PaletteIndex::NumericLiteral)); langDef.m_tokenRegexStrings.emplace_back("[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)([eE][+-]?[0-9]+)?[fF]?",PaletteIndex::NumericLiteral);
langDef.m_tokenRegexStrings.push_back(std::make_pair("[+-]?[0-9]+[Uu]?[lL]?[lL]?", PaletteIndex::NumericLiteral)); langDef.m_tokenRegexStrings.emplace_back("[+-]?[0-9]+[Uu]?[lL]?[lL]?", PaletteIndex::NumericLiteral);
langDef.m_tokenRegexStrings.push_back(std::make_pair("0[0-7]+[Uu]?[lL]?[lL]?", PaletteIndex::NumericLiteral)); langDef.m_tokenRegexStrings.emplace_back("0[0-7]+[Uu]?[lL]?[lL]?", PaletteIndex::NumericLiteral);
langDef.m_tokenRegexStrings.push_back(std::make_pair("0[xX][0-9a-fA-F]+[uU]?[lL]?[lL]?", PaletteIndex::NumericLiteral)); langDef.m_tokenRegexStrings.emplace_back("0[xX][0-9a-fA-F]+[uU]?[lL]?[lL]?", PaletteIndex::NumericLiteral);
langDef.m_tokenRegexStrings.push_back(std::make_pair("[a-zA-Z_][a-zA-Z0-9_]*", PaletteIndex::Identifier)); langDef.m_tokenRegexStrings.emplace_back("[a-zA-Z_][a-zA-Z0-9_]*", PaletteIndex::Identifier);
langDef.m_tokenRegexStrings.push_back(std::make_pair("[\\!\\%\\^\\&\\*\\-\\+\\=\\~\\|\\<\\>\\?\\/]", PaletteIndex::Operator)); langDef.m_tokenRegexStrings.emplace_back(R"([\!\%\^\&\*\-\+\=\~\|\<\>\?\/])", PaletteIndex::Operator);
langDef.m_tokenRegexStrings.push_back(std::make_pair("[\\[\\]\\{\\}\\(\\)\\;\\,\\.]", PaletteIndex::Separator)); langDef.m_tokenRegexStrings.emplace_back(R"([\[\]\{\}\(\)\;\,\.])", PaletteIndex::Separator);
langDef.m_commentStart = "/*"; langDef.m_commentStart = "/*";
langDef.m_commentEnd = "*/"; langDef.m_commentEnd = "*/";
@@ -897,16 +897,16 @@ namespace hex::ui {
langDef.m_identifiers.insert(std::make_pair(std::string(k), id)); langDef.m_identifiers.insert(std::make_pair(std::string(k), id));
} }
langDef.m_tokenRegexStrings.push_back(std::make_pair("[ \\t]*#[ \\t]*[a-zA-Z_]+", PaletteIndex::Directive)); langDef.m_tokenRegexStrings.emplace_back("[ \\t]*#[ \\t]*[a-zA-Z_]+", PaletteIndex::Directive);
langDef.m_tokenRegexStrings.push_back(std::make_pair("L?\\\"(\\\\.|[^\\\"])*\\\"", PaletteIndex::StringLiteral)); langDef.m_tokenRegexStrings.emplace_back(R"(L?\"(\\.|[^\"])*\")", PaletteIndex::StringLiteral);
langDef.m_tokenRegexStrings.push_back(std::make_pair("\\'\\\\?[^\\']\\'", PaletteIndex::CharLiteral)); langDef.m_tokenRegexStrings.emplace_back(R"(\'\\?[^\']\')", PaletteIndex::CharLiteral);
langDef.m_tokenRegexStrings.push_back(std::make_pair("[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)([eE][+-]?[0-9]+)?[fF]?",PaletteIndex::NumericLiteral)); langDef.m_tokenRegexStrings.emplace_back("[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)([eE][+-]?[0-9]+)?[fF]?",PaletteIndex::NumericLiteral);
langDef.m_tokenRegexStrings.push_back(std::make_pair("[+-]?[0-9]+[Uu]?[lL]?[lL]?", PaletteIndex::NumericLiteral)); langDef.m_tokenRegexStrings.emplace_back("[+-]?[0-9]+[Uu]?[lL]?[lL]?", PaletteIndex::NumericLiteral);
langDef.m_tokenRegexStrings.push_back(std::make_pair("0[0-7]+[Uu]?[lL]?[lL]?", PaletteIndex::NumericLiteral)); langDef.m_tokenRegexStrings.emplace_back("0[0-7]+[Uu]?[lL]?[lL]?", PaletteIndex::NumericLiteral);
langDef.m_tokenRegexStrings.push_back(std::make_pair("0[xX][0-9a-fA-F]+[uU]?[lL]?[lL]?", PaletteIndex::NumericLiteral)); langDef.m_tokenRegexStrings.emplace_back("0[xX][0-9a-fA-F]+[uU]?[lL]?[lL]?", PaletteIndex::NumericLiteral);
langDef.m_tokenRegexStrings.push_back(std::make_pair("[a-zA-Z_][a-zA-Z0-9_]*", PaletteIndex::Identifier)); langDef.m_tokenRegexStrings.emplace_back("[a-zA-Z_][a-zA-Z0-9_]*", PaletteIndex::Identifier);
langDef.m_tokenRegexStrings.push_back(std::make_pair("[\\!\\%\\^\\&\\*\\-\\+\\=\\~\\|\\<\\>\\?\\/]", PaletteIndex::Operator)); langDef.m_tokenRegexStrings.emplace_back(R"([\!\%\^\&\*\-\+\=\~\|\<\>\?\/])", PaletteIndex::Operator);
langDef.m_tokenRegexStrings.push_back(std::make_pair("[\\[\\]\\{\\}\\(\\)\\;\\,\\.]", PaletteIndex::Separator)); langDef.m_tokenRegexStrings.emplace_back(R"([\[\]\{\}\(\)\;\,\.])", PaletteIndex::Separator);
langDef.m_commentStart = "/*"; langDef.m_commentStart = "/*";
langDef.m_commentEnd = "*/"; langDef.m_commentEnd = "*/";
@@ -961,16 +961,16 @@ namespace hex::ui {
langDef.m_identifiers.insert(std::make_pair(std::string(k), id)); langDef.m_identifiers.insert(std::make_pair(std::string(k), id));
} }
langDef.m_tokenRegexStrings.push_back(std::make_pair("[ \\t]*#[ \\t]*[a-zA-Z_]+", PaletteIndex::Directive)); langDef.m_tokenRegexStrings.emplace_back(R"([ \t]*#[ \t]*[a-zA-Z_]+)", PaletteIndex::Directive);
langDef.m_tokenRegexStrings.push_back(std::make_pair("L?\\\"(\\\\.|[^\\\"])*\\\"", PaletteIndex::StringLiteral)); langDef.m_tokenRegexStrings.emplace_back(R"(L?\"(\\.|[^\"])*\")", PaletteIndex::StringLiteral);
langDef.m_tokenRegexStrings.push_back(std::make_pair("\\'\\\\?[^\\']\\'", PaletteIndex::CharLiteral)); langDef.m_tokenRegexStrings.emplace_back(R"(\'\\?[^\']\')", PaletteIndex::CharLiteral);
langDef.m_tokenRegexStrings.push_back(std::make_pair("[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)([eE][+-]?[0-9]+)?[fF]?", PaletteIndex::NumericLiteral)); langDef.m_tokenRegexStrings.emplace_back("[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)([eE][+-]?[0-9]+)?[fF]?", PaletteIndex::NumericLiteral);
langDef.m_tokenRegexStrings.push_back(std::make_pair("[+-]?[0-9]+[Uu]?[lL]?[lL]?", PaletteIndex::NumericLiteral)); langDef.m_tokenRegexStrings.emplace_back("[+-]?[0-9]+[Uu]?[lL]?[lL]?", PaletteIndex::NumericLiteral);
langDef.m_tokenRegexStrings.push_back(std::make_pair("0[0-7]+[Uu]?[lL]?[lL]?", PaletteIndex::NumericLiteral)); langDef.m_tokenRegexStrings.emplace_back("0[0-7]+[Uu]?[lL]?[lL]?", PaletteIndex::NumericLiteral);
langDef.m_tokenRegexStrings.push_back(std::make_pair("0[xX][0-9a-fA-F]+[uU]?[lL]?[lL]?", PaletteIndex::NumericLiteral)); langDef.m_tokenRegexStrings.emplace_back("0[xX][0-9a-fA-F]+[uU]?[lL]?[lL]?", PaletteIndex::NumericLiteral);
langDef.m_tokenRegexStrings.push_back(std::make_pair("[a-zA-Z_][a-zA-Z0-9_]*", PaletteIndex::Identifier)); langDef.m_tokenRegexStrings.emplace_back("[a-zA-Z_][a-zA-Z0-9_]*", PaletteIndex::Identifier);
langDef.m_tokenRegexStrings.push_back(std::make_pair("[\\!\\%\\^\\&\\*\\-\\+\\=\\~\\|\\<\\>\\?\\/]", PaletteIndex::Operator)); langDef.m_tokenRegexStrings.emplace_back(R"([\!\%\^\&\*\-\+\=\~\|\<\>\?\/])", PaletteIndex::Operator);
langDef.m_tokenRegexStrings.push_back(std::make_pair("[\\[\\]\\{\\}\\(\\)\\;\\,\\.]", PaletteIndex::Separator)); langDef.m_tokenRegexStrings.emplace_back(R"([\[\]\{\}\(\)\;\,\.])", PaletteIndex::Separator);
langDef.m_commentStart = "--[["; langDef.m_commentStart = "--[[";
langDef.m_commentEnd = "]]"; langDef.m_commentEnd = "]]";
@@ -1001,10 +1001,11 @@ namespace hex::ui {
} }
// handle escape character for " // handle escape character for "
if (*p == '\\' && p + 1 < in_end && p[1] == '\\') if (*p == '\\' && p + 1 < in_end) {
p++; if (p[1] == '\\' || p[1] == '"') {
else if (*p == '\\' && p + 1 < in_end && p[1] == '"') p++;
p++; }
}
p++; p++;
} }
@@ -1169,9 +1170,9 @@ namespace hex::ui {
out_begin = in_begin; out_begin = in_begin;
out_end = in_begin + 1; out_end = in_begin + 1;
return true; return true;
default:
return false;
} }
return false;
} }
bool tokenizeCStyleSeparator(strConstIter in_begin, strConstIter in_end, strConstIter &out_begin, strConstIter &out_end) { bool tokenizeCStyleSeparator(strConstIter in_begin, strConstIter in_end, strConstIter &out_begin, strConstIter &out_end) {

View File

@@ -4,7 +4,7 @@
namespace hex::ui { namespace hex::ui {
bool isWordChar(char c) { static bool isWordChar(char c) {
auto asUChar = static_cast<u8>(c); auto asUChar = static_cast<u8>(c);
return std::isalnum(asUChar) || c == '_' || asUChar > 0x7F; return std::isalnum(asUChar) || c == '_' || asUChar > 0x7F;
} }
@@ -237,13 +237,13 @@ namespace hex::ui {
return; return;
i32 home; i32 home;
if (!prefix.empty()) { if (!prefix.empty()) {
auto idx = prefix.find_first_not_of(" "); auto idx = prefix.find_first_not_of(' ');
if (idx == std::string::npos) { if (idx == std::string::npos) {
auto postIdx = postfix.find_first_of(" "); auto postIdx = postfix.find_first_of(' ');
if (postIdx == std::string::npos || postIdx == 0) if (postIdx == std::string::npos || postIdx == 0)
home = 0; home = 0;
else { else {
postIdx = postfix.find_first_not_of(" "); postIdx = postfix.find_first_not_of(' ');
if (postIdx == std::string::npos) if (postIdx == std::string::npos)
home = this->lineMaxColumn(oldPos.m_line); home = this->lineMaxColumn(oldPos.m_line);
else if (postIdx == 0) else if (postIdx == 0)
@@ -254,11 +254,11 @@ namespace hex::ui {
} else } else
home = idx; home = idx;
} else { } else {
auto postIdx = postfix.find_first_of(" "); auto postIdx = postfix.find_first_of(' ');
if (postIdx == std::string::npos) if (postIdx == std::string::npos)
home = 0; home = 0;
else { else {
postIdx = postfix.find_first_not_of(" "); postIdx = postfix.find_first_not_of(' ');
if (postIdx == std::string::npos) if (postIdx == std::string::npos)
home = lineMaxColumn(oldPos.m_line); home = lineMaxColumn(oldPos.m_line);
else else
@@ -360,9 +360,7 @@ namespace hex::ui {
if (std::abs(m_line) > (i32) maxLine) if (std::abs(m_line) > (i32) maxLine)
return false; return false;
auto maxColumn = editor->lineMaxColumn(m_line); auto maxColumn = editor->lineMaxColumn(m_line);
if (std::abs(m_column) > maxColumn) return std::abs(m_column) <= maxColumn;
return false;
return true;
} }
TextEditor::Coordinates TextEditor::Coordinates::sanitize(TextEditor *editor) { TextEditor::Coordinates TextEditor::Coordinates::sanitize(TextEditor *editor) {
@@ -387,8 +385,8 @@ namespace hex::ui {
TextEditor::Coordinates TextEditor::setCoordinates(i32 line, i32 column) { TextEditor::Coordinates TextEditor::setCoordinates(i32 line, i32 column) {
if (isEmpty()) if (isEmpty())
return Coordinates(0, 0); return {0, 0};
return Coordinates(this, line, column); return {this, line, column};
} }
TextEditor::Coordinates TextEditor::setCoordinates(const Coordinates &value) { TextEditor::Coordinates TextEditor::setCoordinates(const Coordinates &value) {
@@ -400,11 +398,11 @@ namespace hex::ui {
auto start = setCoordinates(value.m_start); auto start = setCoordinates(value.m_start);
auto end = setCoordinates(value.m_end); auto end = setCoordinates(value.m_end);
if (start == Invalid || end == Invalid) if (start == Invalid || end == Invalid)
return Range(Invalid, Invalid); return {Invalid, Invalid};
if (start > end) { if (start > end) {
std::swap(start, end); std::swap(start, end);
} }
return Range(start, end); return {start, end};
} }
void TextEditor::advance(Coordinates &coordinates) const { void TextEditor::advance(Coordinates &coordinates) const {

View File

@@ -453,7 +453,7 @@ namespace hex::ui {
} }
} }
// Draw breakpoints // Draw breakpoints
if (m_breakpoints.count(lineNo + 1) != 0) { if (m_breakpoints.contains(lineNo + 1)) {
auto end = ImVec2(lineNoStartScreenPos.x + contentSize.x + m_lineNumberFieldWidth, lineStartScreenPos.y + m_charAdvance.y); auto end = ImVec2(lineNoStartScreenPos.x + contentSize.x + m_lineNumberFieldWidth, lineStartScreenPos.y + m_charAdvance.y);
drawList->AddRectFilled(ImVec2(position.x, lineStartScreenPos.y), end, m_palette[(i32) PaletteIndex::Breakpoint]); drawList->AddRectFilled(ImVec2(position.x, lineStartScreenPos.y), end, m_palette[(i32) PaletteIndex::Breakpoint]);
@@ -501,7 +501,7 @@ namespace hex::ui {
std::string errorLineColumn; std::string errorLineColumn;
bool found = false; bool found = false;
for (auto text: m_clickableText) { for (auto text: m_clickableText) {
if (lineText.find(text) == 0) { if (lineText.starts_with(text)) {
errorLineColumn = lineText.substr(text.size()); errorLineColumn = lineText.substr(text.size());
if (!errorLineColumn.empty()) { if (!errorLineColumn.empty()) {
found = true; found = true;
@@ -511,7 +511,7 @@ namespace hex::ui {
} }
if (found) { if (found) {
i32 currLine = 0, currColumn = 0; i32 currLine = 0, currColumn = 0;
if (auto idx = errorLineColumn.find(":"); idx != std::string::npos) { if (auto idx = errorLineColumn.find(':'); idx != std::string::npos) {
auto errorLine = errorLineColumn.substr(0, idx); auto errorLine = errorLineColumn.substr(0, idx);
if (!errorLine.empty()) if (!errorLine.empty())
currLine = std::stoi(errorLine) - 1; currLine = std::stoi(errorLine) - 1;
@@ -532,12 +532,12 @@ namespace hex::ui {
} }
} }
} }
if (m_cursorBoxes.find(gotoKey) != m_cursorBoxes.end()) { if (m_cursorBoxes.contains(gotoKey)) {
auto box = m_cursorBoxes[gotoKey]; auto box = m_cursorBoxes[gotoKey];
if (box.trigger()) box.callback(); if (box.trigger()) box.callback();
} }
if (m_errorGotoBoxes.find(gotoKey) != m_errorGotoBoxes.end()) { if (m_errorGotoBoxes.contains(gotoKey)) {
auto box = m_errorGotoBoxes[gotoKey]; auto box = m_errorGotoBoxes[gotoKey];
if (box.trigger()) box.callback(); if (box.trigger()) box.callback();
} }
@@ -568,7 +568,7 @@ namespace hex::ui {
ErrorHoverBox box = ErrorHoverBox(ImRect({begin, end}), key, errorMessage.c_str()); ErrorHoverBox box = ErrorHoverBox(ImRect({begin, end}), key, errorMessage.c_str());
m_errorHoverBoxes[key] = box; m_errorHoverBoxes[key] = box;
} }
if (m_errorHoverBoxes.find(key) != m_errorHoverBoxes.end()) { if (m_errorHoverBoxes.contains(key)) {
auto box = m_errorHoverBoxes[key]; auto box = m_errorHoverBoxes[key];
if (box.trigger()) box.callback(); if (box.trigger()) box.callback();
} }
@@ -626,7 +626,7 @@ namespace hex::ui {
ImVec2 TextEditor::calculateCharAdvance() const { ImVec2 TextEditor::calculateCharAdvance() const {
/* Compute mCharAdvance regarding scaled font size (Ctrl + mouse wheel)*/ /* Compute mCharAdvance regarding scaled font size (Ctrl + mouse wheel)*/
const float fontSize = ImGui::GetFont()->CalcTextSizeA(ImGui::GetFontSize(), FLT_MAX, -1.0f, "#", nullptr, nullptr).x; const float fontSize = ImGui::GetFont()->CalcTextSizeA(ImGui::GetFontSize(), FLT_MAX, -1.0f, "#", nullptr, nullptr).x;
return ImVec2(fontSize, GImGui->FontSize * m_lineSpacing); return {fontSize, GImGui->FontSize * m_lineSpacing};
} }
float TextEditor::textDistanceToLineStart(const Coordinates &aFrom) { float TextEditor::textDistanceToLineStart(const Coordinates &aFrom) {

View File

@@ -1,3 +1,4 @@
#include <algorithm>
#include <ui/text_editor.hpp> #include <ui/text_editor.hpp>
#include <hex/helpers/logger.hpp> #include <hex/helpers/logger.hpp>
#include <algorithm> #include <algorithm>
@@ -37,11 +38,11 @@ namespace hex::ui {
} }
Coordinates Coordinates::operator+(const Coordinates &o) const { Coordinates Coordinates::operator+(const Coordinates &o) const {
return Coordinates(m_line + o.m_line, m_column + o.m_column); return {m_line + o.m_line, m_column + o.m_column};
} }
Coordinates Coordinates::operator-(const Coordinates &o) const { Coordinates Coordinates::operator-(const Coordinates &o) const {
return Coordinates(m_line - o.m_line, m_column - o.m_column); return {m_line - o.m_line, m_column - o.m_column};
} }
bool Range::operator==(const Range &o) const { bool Range::operator==(const Range &o) const {
@@ -52,13 +53,13 @@ namespace hex::ui {
} }
Coordinates Range::getSelectedLines() { Coordinates Range::getSelectedLines() {
return Coordinates(m_start.m_line, m_end.m_line); return {m_start.m_line, m_end.m_line};
} }
Coordinates Range::getSelectedColumns() { Coordinates Range::getSelectedColumns() {
if (isSingleLine()) if (isSingleLine())
return Coordinates(m_start.m_column, m_end.m_column - m_start.m_column); return {m_start.m_column, m_end.m_column - m_start.m_column};
return Coordinates(m_start.m_column, m_end.m_column); return {m_start.m_column, m_end.m_column};
} }
bool Range::isSingleLine() { bool Range::isSingleLine() {
@@ -209,14 +210,7 @@ namespace hex::ui {
return iter; return iter;
} }
Line &Line::operator=(const Line &line) { Line &Line::operator=(const Line &line) = default;
m_chars = line.m_chars;
m_colors = line.m_colors;
m_flags = line.m_flags;
m_colorized = line.m_colorized;
m_lineMaxColumn = line.m_lineMaxColumn;
return *this;
}
Line &Line::operator=(Line &&line) noexcept { Line &Line::operator=(Line &&line) noexcept {
m_chars = std::move(line.m_chars); m_chars = std::move(line.m_chars);
@@ -899,11 +893,11 @@ namespace hex::ui {
std::string wordLower = m_findWord; std::string wordLower = m_findWord;
if (!getMatchCase()) if (!getMatchCase())
std::transform(wordLower.begin(), wordLower.end(), wordLower.begin(), ::tolower); std::ranges::transform(wordLower, wordLower.begin(), ::tolower);
std::string textSrc = editor->getText(); std::string textSrc = editor->getText();
if (!getMatchCase()) if (!getMatchCase())
std::transform(textSrc.begin(), textSrc.end(), textSrc.begin(), ::tolower); std::ranges::transform(textSrc, textSrc.begin(), ::tolower);
u64 textLoc; u64 textLoc;
// TODO: use regexp find iterator in all cases // TODO: use regexp find iterator in all cases
@@ -1010,7 +1004,6 @@ namespace hex::ui {
editor->m_state = saveState; editor->m_state = saveState;
editor->ensureCursorVisible(); editor->ensureCursorVisible();
return;
} }

View File

@@ -196,7 +196,7 @@ namespace hex::ui {
auto result = getCharacterCoordinates(lineNo, count - increase); auto result = getCharacterCoordinates(lineNo, count - increase);
result = setCoordinates(result); result = setCoordinates(result);
if (result == Invalid) if (result == Invalid)
return Coordinates(0, 0); return {0, 0};
return result; return result;
} }
@@ -205,7 +205,7 @@ namespace hex::ui {
return Invalid; return Invalid;
const auto &line = m_lines[coordinates.m_line]; const auto &line = m_lines[coordinates.m_line];
return Coordinates(coordinates.m_line,line.columnIndex(coordinates.m_column)); return {coordinates.m_line,line.columnIndex(coordinates.m_column)};
} }
i32 TextEditor::lineCoordinatesToIndex(const Coordinates &coordinates) const { i32 TextEditor::lineCoordinatesToIndex(const Coordinates &coordinates) const {
@@ -218,7 +218,7 @@ namespace hex::ui {
TextEditor::Coordinates TextEditor::getCharacterCoordinates(i32 lineIndex, i32 strIndex) { TextEditor::Coordinates TextEditor::getCharacterCoordinates(i32 lineIndex, i32 strIndex) {
if (lineIndex < 0 || lineIndex >= (i32) m_lines.size()) if (lineIndex < 0 || lineIndex >= (i32) m_lines.size())
return Coordinates(0, 0); return {0, 0};
auto &line = m_lines[lineIndex]; auto &line = m_lines[lineIndex];
return setCoordinates(lineIndex, line.indexColumn(strIndex)); return setCoordinates(lineIndex, line.indexColumn(strIndex));
} }
@@ -233,7 +233,7 @@ namespace hex::ui {
TextEditor::Coordinates TextEditor::stringIndexToCoordinates(i32 strIndex, const std::string &input) { TextEditor::Coordinates TextEditor::stringIndexToCoordinates(i32 strIndex, const std::string &input) {
if (strIndex < 0 || strIndex > (i32) input.size()) if (strIndex < 0 || strIndex > (i32) input.size())
return TextEditor::Coordinates(0, 0); return {0, 0};
std::string str = input.substr(0, strIndex); std::string str = input.substr(0, strIndex);
auto line = std::count(str.begin(), str.end(), '\n'); auto line = std::count(str.begin(), str.end(), '\n');
auto index = str.find_last_of('\n'); auto index = str.find_last_of('\n');

View File

@@ -1,3 +1,4 @@
#include <algorithm>
#include <hex/helpers/crypto.hpp> #include <hex/helpers/crypto.hpp>
#include <hex/helpers/logger.hpp> #include <hex/helpers/logger.hpp>
#include <hex/test/test_provider.hpp> #include <hex/test/test_provider.hpp>
@@ -6,12 +7,13 @@
#include <random> #include <random>
#include <vector> #include <vector>
#include <array> #include <array>
#include <algorithm>
#include <fmt/ranges.h> #include <fmt/ranges.h>
using std::string;
struct EncodeChek { struct EncodeChek {
std::vector<u8> vec; std::vector<u8> vec;
std::string string; std::string string;
}; };
TEST_SEQUENCE("EncodeDecode16") { TEST_SEQUENCE("EncodeDecode16") {
@@ -40,7 +42,7 @@ TEST_SEQUENCE("EncodeDecode16") {
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::ranges::generate(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);
@@ -56,11 +58,11 @@ TEST_SEQUENCE("EncodeDecode16") {
}; };
std::string vectorToString(std::vector<u8> in) { std::string vectorToString(std::vector<u8> in) {
return std::string(reinterpret_cast<char *>(in.data()), in.size()); return { reinterpret_cast<char *>(in.data()), in.size() };
} }
std::vector<u8> stringToVector(std::string in) { std::vector<u8> stringToVector(std::string in) {
return std::vector<u8>(in.begin(), in.end()); return { in.begin(), in.end() };
} }
TEST_SEQUENCE("EncodeDecode64") { TEST_SEQUENCE("EncodeDecode64") {
@@ -90,7 +92,7 @@ TEST_SEQUENCE("EncodeDecode64") {
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::ranges::generate(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 +149,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::ranges::generate(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);
@@ -193,7 +195,7 @@ 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++) {

View File

@@ -1,9 +1,9 @@
#include <algorithm>
#include <hex/test/tests.hpp> #include <hex/test/tests.hpp>
#include <hex/test/test_provider.hpp> #include <hex/test/test_provider.hpp>
#include <hex/helpers/crypto.hpp> #include <hex/helpers/crypto.hpp>
#include <algorithm>
#include <vector> #include <vector>
TEST_SEQUENCE("TestSucceeding") { TEST_SEQUENCE("TestSucceeding") {
@@ -21,7 +21,7 @@ TEST_SEQUENCE("TestProvider_read") {
u8 buff[1024]; u8 buff[1024];
std::fill(std::begin(buff), std::end(buff), 22); std::ranges::fill(buff, 22);
provider2->read(0, buff + 1, 4); provider2->read(0, buff + 1, 4);
TEST_ASSERT(buff[0] == 22); // should be unchanged TEST_ASSERT(buff[0] == 22); // should be unchanged
TEST_ASSERT(buff[1] == 0xde); TEST_ASSERT(buff[1] == 0xde);
@@ -30,13 +30,13 @@ TEST_SEQUENCE("TestProvider_read") {
TEST_ASSERT(buff[4] == 0xef); TEST_ASSERT(buff[4] == 0xef);
TEST_ASSERT(buff[5] == 22); // should be unchanged TEST_ASSERT(buff[5] == 22); // should be unchanged
std::fill(std::begin(buff), std::end(buff), 22); std::ranges::fill(buff, 22);
provider2->read(6, buff, 2); provider2->read(6, buff, 2);
TEST_ASSERT(buff[0] == 0x00); TEST_ASSERT(buff[0] == 0x00);
TEST_ASSERT(buff[1] == 0xff); TEST_ASSERT(buff[1] == 0xff);
TEST_ASSERT(buff[2] == 22); // should be unchanged TEST_ASSERT(buff[2] == 22); // should be unchanged
std::fill(std::begin(buff), std::end(buff), 22); std::ranges::fill(buff, 22);
provider2->read(7, buff, 2); provider2->read(7, buff, 2);
TEST_ASSERT(std::count(std::begin(buff), std::end(buff), 22) == std::size(buff)); // buff should be unchanged TEST_ASSERT(std::count(std::begin(buff), std::end(buff), 22) == std::size(buff)); // buff should be unchanged
@@ -50,7 +50,7 @@ TEST_SEQUENCE("TestProvider_write") {
u8 data[1024] = { 0xde, 0xad, 0xbe, 0xef, 0x42, 0x2a, 0x00, 0xff }; u8 data[1024] = { 0xde, 0xad, 0xbe, 0xef, 0x42, 0x2a, 0x00, 0xff };
std::fill(std::begin(buff), std::end(buff), 22); std::ranges::fill(buff, 22);
provider2->writeRaw(1, data, 4); provider2->writeRaw(1, data, 4);
TEST_ASSERT(buff[0] == 22); // should be unchanged TEST_ASSERT(buff[0] == 22); // should be unchanged
TEST_ASSERT(buff[1] == 0xde); TEST_ASSERT(buff[1] == 0xde);
@@ -59,19 +59,19 @@ TEST_SEQUENCE("TestProvider_write") {
TEST_ASSERT(buff[4] == 0xef); TEST_ASSERT(buff[4] == 0xef);
TEST_ASSERT(buff[5] == 22); // should be unchanged TEST_ASSERT(buff[5] == 22); // should be unchanged
std::fill(std::begin(buff), std::end(buff), 22); std::ranges::fill(buff, 22);
provider2->writeRaw(0, data + 6, 2); provider2->writeRaw(0, data + 6, 2);
TEST_ASSERT(buff[0] == 0x00); TEST_ASSERT(buff[0] == 0x00);
TEST_ASSERT(buff[1] == 0xff); TEST_ASSERT(buff[1] == 0xff);
TEST_ASSERT(buff[2] == 22); // should be unchanged TEST_ASSERT(buff[2] == 22); // should be unchanged
std::fill(std::begin(buff), std::end(buff), 22); std::ranges::fill(buff, 22);
provider2->writeRaw(6, data, 2); provider2->writeRaw(6, data, 2);
TEST_ASSERT(buff[5] == 22); // should be unchanged TEST_ASSERT(buff[5] == 22); // should be unchanged
TEST_ASSERT(buff[6] == 0xde); TEST_ASSERT(buff[6] == 0xde);
TEST_ASSERT(buff[7] == 0xad); TEST_ASSERT(buff[7] == 0xad);
std::fill(std::begin(buff), std::end(buff), 22); std::ranges::fill(buff, 22);
provider2->writeRaw(7, data, 2); provider2->writeRaw(7, data, 2);
TEST_ASSERT(std::count(std::begin(buff), std::end(buff), 22) == std::size(buff)); // buff should be unchanged TEST_ASSERT(std::count(std::begin(buff), std::end(buff), 22) == std::size(buff)); // buff should be unchanged