diff --git a/.clang-tidy b/.clang-tidy index dd910c584..df98b12ff 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -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: - -* - mpi-* @@ -22,11 +27,11 @@ Checks: - cert-dcl58-cpp - cert-flp30-c - 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-interfaces-global-init - cppcoreguidelines-pro-type-static-cast-downcast -- cppcoreguidelines-narrowing-conversions +- -cppcoreguidelines-narrowing-conversions # - google-default-arguments - google-runtime-operator - google-explicit-constructor @@ -43,8 +48,11 @@ Checks: - -misc-static-assert - -misc-no-recursion - -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-use-trailing-return-type +- -modernize-use-std-print # We want to use fmt::print instead - openmp-use-default-none - performance-* - -performance-no-int-to-ptr @@ -64,5 +72,31 @@ Checks: - -readability-redundant-access-specifiers - -readability-function-cognitive-complexity - -readability-identifier-naming -- '*-include-cleaner' - -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 \ No newline at end of file diff --git a/lib/external/pattern_language b/lib/external/pattern_language index f213e0a6f..a06da46a3 160000 --- a/lib/external/pattern_language +++ b/lib/external/pattern_language @@ -1 +1 @@ -Subproject commit f213e0a6f08638586999c790692f7c04935d155a +Subproject commit a06da46a3cf1694ccc785d21a37a2dca08deb56a diff --git a/lib/libimhex/include/hex/api/content_registry/background_services.hpp b/lib/libimhex/include/hex/api/content_registry/background_services.hpp index 425eccc0b..79373b6f4 100644 --- a/lib/libimhex/include/hex/api/content_registry/background_services.hpp +++ b/lib/libimhex/include/hex/api/content_registry/background_services.hpp @@ -16,7 +16,7 @@ EXPORT_MODULE namespace hex { void stopServices(); } - void registerService(const UnlocalizedString &unlocalizedString, const impl::Callback &callback); + void registerService(const UnlocalizedString &unlocalizedName, const impl::Callback &callback); } } \ No newline at end of file diff --git a/lib/libimhex/include/hex/helpers/opengl.hpp b/lib/libimhex/include/hex/helpers/opengl.hpp index 37911e638..5f2c8209a 100644 --- a/lib/libimhex/include/hex/helpers/opengl.hpp +++ b/lib/libimhex/include/hex/helpers/opengl.hpp @@ -10,6 +10,7 @@ #include #include #include +#include #include #include "imgui.h" @@ -935,7 +936,7 @@ namespace hex::gl { void attachTexture(const Texture &texture) const; private: - GLuint m_frameBuffer, m_renderBuffer; + GLuint m_frameBuffer = 0, m_renderBuffer = 0; }; class AxesVectors { diff --git a/lib/libimhex/source/api/achievement_manager.cpp b/lib/libimhex/source/api/achievement_manager.cpp index dfa9811c9..9ef549497 100644 --- a/lib/libimhex/source/api/achievement_manager.cpp +++ b/lib/libimhex/source/api/achievement_manager.cpp @@ -264,8 +264,7 @@ namespace hex { } } - if (json.empty()) - return; + if (json.empty()) return; #if defined(OS_WEB) auto data = json.dump(); diff --git a/lib/libimhex/source/api/event_manager.cpp b/lib/libimhex/source/api/event_manager.cpp index af37f36fc..9c5b6cfe6 100644 --- a/lib/libimhex/source/api/event_manager.cpp +++ b/lib/libimhex/source/api/event_manager.cpp @@ -1,3 +1,4 @@ +#include #include namespace hex { @@ -35,7 +36,7 @@ namespace hex { void EventManager::unsubscribe(void *token, impl::EventId id) { 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; }); diff --git a/lib/libimhex/source/api/localization_manager.cpp b/lib/libimhex/source/api/localization_manager.cpp index a1e391d09..16ac67a94 100644 --- a/lib/libimhex/source/api/localization_manager.cpp +++ b/lib/libimhex/source/api/localization_manager.cpp @@ -50,7 +50,7 @@ namespace hex { definition.fallbackLanguageId = item["fallback"].get(); } - if (item.contains("hidden") && item["hidden"].get() == true) { + if (item.contains("hidden") && item["hidden"].get()) { definition.hidden = true; } @@ -155,7 +155,7 @@ namespace hex { static AutoReset> loadedLocalization; static std::mutex mutex; - std::lock_guard lock(mutex); + std::scoped_lock lock(mutex); if (*currentLanguageId != languageId) { currentLanguageId = languageId; loadedLocalization->clear(); diff --git a/lib/libimhex/source/api/plugin_manager.cpp b/lib/libimhex/source/api/plugin_manager.cpp index 108ad0e97..81e156514 100644 --- a/lib/libimhex/source/api/plugin_manager.cpp +++ b/lib/libimhex/source/api/plugin_manager.cpp @@ -85,7 +85,7 @@ namespace hex { } 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 { diff --git a/lib/libimhex/source/helpers/binary_pattern.cpp b/lib/libimhex/source/helpers/binary_pattern.cpp index 80bba3619..d0e2da959 100644 --- a/lib/libimhex/source/helpers/binary_pattern.cpp +++ b/lib/libimhex/source/helpers/binary_pattern.cpp @@ -7,7 +7,7 @@ namespace hex { namespace { void skipWhitespace(std::string_view &string) { - while (string.length() > 0) { + while (!string.empty()) { if (!std::isspace(string.front())) break; string = string.substr(1); @@ -89,7 +89,7 @@ namespace hex { return { }; bool inString = false; - while (string.length() > 0) { + while (!string.empty()) { BinaryPattern::Pattern pattern = { 0, 0 }; if (string.starts_with("\"")) { diff --git a/lib/libimhex/source/helpers/default_paths.cpp b/lib/libimhex/source/helpers/default_paths.cpp index 3c1e556d7..8a06954da 100644 --- a/lib/libimhex/source/helpers/default_paths.cpp +++ b/lib/libimhex/source/helpers/default_paths.cpp @@ -1,3 +1,4 @@ +#include #include #include @@ -39,7 +40,7 @@ namespace hex::paths { paths.push_back(xdg::DataHomeDir()); auto dataDirs = xdg::DataDirs(); - std::copy(dataDirs.begin(), dataDirs.end(), std::back_inserter(paths)); + std::ranges::copy(dataDirs, std::back_inserter(paths)); #endif @@ -108,7 +109,7 @@ namespace hex::paths { // Add the system plugin directory to the path if one was provided at compile time #if defined(OS_LINUX) && defined(SYSTEM_PLUGINS_LOCATION) - paths.push_back(SYSTEM_PLUGINS_LOCATION); + paths.emplace_back(SYSTEM_PLUGINS_LOCATION); #endif return paths; diff --git a/lib/libimhex/source/helpers/encoding_file.cpp b/lib/libimhex/source/helpers/encoding_file.cpp index 8909d5e0e..df777801c 100644 --- a/lib/libimhex/source/helpers/encoding_file.cpp +++ b/lib/libimhex/source/helpers/encoding_file.cpp @@ -2,6 +2,7 @@ #include +#include #include #include @@ -89,9 +90,7 @@ namespace hex { std::pair EncodingFile::getEncodingFor(std::span buffer) const { - for (auto riter = m_mapping->crbegin(); riter != m_mapping->crend(); ++riter) { - const auto &[size, mapping] = *riter; - + for (auto [size, mapping] : std::ranges::reverse_view(*m_mapping)) { if (size > buffer.size()) continue; std::vector key(buffer.begin(), buffer.begin() + size); @@ -103,9 +102,7 @@ namespace hex { } u64 EncodingFile::getEncodingLengthFor(std::span buffer) const { - for (auto riter = m_mapping->crbegin(); riter != m_mapping->crend(); ++riter) { - const auto &[size, mapping] = *riter; - + for (auto [size, mapping] : std::ranges::reverse_view(*m_mapping)) { if (size > buffer.size()) continue; std::vector key(buffer.begin(), buffer.begin() + size); diff --git a/lib/libimhex/source/helpers/fs.cpp b/lib/libimhex/source/helpers/fs.cpp index 31a9c23f3..6443e3179 100644 --- a/lib/libimhex/source/helpers/fs.cpp +++ b/lib/libimhex/source/helpers/fs.cpp @@ -13,8 +13,6 @@ #include # if defined(OS_FREEBSD) #include -# else - #include # endif #endif diff --git a/lib/libimhex/source/helpers/opengl.cpp b/lib/libimhex/source/helpers/opengl.cpp index 909c7e265..4e03b59d9 100644 --- a/lib/libimhex/source/helpers/opengl.cpp +++ b/lib/libimhex/source/helpers/opengl.cpp @@ -1,9 +1,14 @@ +#include +#include "wolv/types.hpp" +#include #include #include -#include #include +#include +#include +#include #include #include diff --git a/lib/libimhex/source/helpers/patches.cpp b/lib/libimhex/source/helpers/patches.cpp index 6c14d1552..0e8a3a039 100644 --- a/lib/libimhex/source/helpers/patches.cpp +++ b/lib/libimhex/source/helpers/patches.cpp @@ -1,3 +1,4 @@ +#include #include #include @@ -5,7 +6,6 @@ #include #include -#include namespace hex { @@ -83,7 +83,7 @@ namespace hex { [[nodiscard]] UnlocalizedString getTypeName() const override { return ""; } - const std::map& getPatches() const { + [[nodiscard]] const std::map& getPatches() const { return m_patches; } private: @@ -92,7 +92,7 @@ namespace hex { void pushStringBack(std::vector &buffer, const std::string &string) { - std::copy(string.begin(), string.end(), std::back_inserter(buffer)); + std::ranges::copy(string, std::back_inserter(buffer)); } template diff --git a/lib/libimhex/source/helpers/udp_server.cpp b/lib/libimhex/source/helpers/udp_server.cpp index a15e3d466..9c269aaa7 100644 --- a/lib/libimhex/source/helpers/udp_server.cpp +++ b/lib/libimhex/source/helpers/udp_server.cpp @@ -14,7 +14,7 @@ namespace hex { 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() { diff --git a/lib/libimhex/source/helpers/utils.cpp b/lib/libimhex/source/helpers/utils.cpp index 8b0941e46..c70fc4748 100644 --- a/lib/libimhex/source/helpers/utils.cpp +++ b/lib/libimhex/source/helpers/utils.cpp @@ -1,3 +1,4 @@ +#include #include #include @@ -98,7 +99,7 @@ namespace hex { string = wolv::util::replaceStrings(string, ",", ""); // 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); }) == string.end(); @@ -824,10 +825,10 @@ namespace hex { if (lang.has_value() && !lang->empty() && *lang != "C" && *lang != "C.UTF-8") { auto parts = wolv::util::splitString(*lang, "."); - if (parts.size() > 0) + if (!parts.empty()) return parts[0]; else - return *lang; + return lang; } return std::nullopt; diff --git a/lib/libimhex/source/helpers/utils_linux.cpp b/lib/libimhex/source/helpers/utils_linux.cpp index cf8048247..f63a7105b 100644 --- a/lib/libimhex/source/helpers/utils_linux.cpp +++ b/lib/libimhex/source/helpers/utils_linux.cpp @@ -10,13 +10,14 @@ namespace hex { void executeCmd(const std::vector &argsVector) { std::vector cArgsVector; - for (const auto &str : argsVector) { + cArgsVector.reserve(argsVector.size()); +for (const auto &str : argsVector) { cArgsVector.push_back(const_cast(str.c_str())); } cArgsVector.push_back(nullptr); if (fork() == 0) { - execvp(cArgsVector[0], &cArgsVector[0]); + execvp(cArgsVector[0], cArgsVector.data()); log::error("execvp() failed: {}", strerror(errno)); exit(EXIT_FAILURE); } diff --git a/lib/libimhex/source/ui/imgui_imhex_extensions.cpp b/lib/libimhex/source/ui/imgui_imhex_extensions.cpp index eb2535a38..815c4c91d 100644 --- a/lib/libimhex/source/ui/imgui_imhex_extensions.cpp +++ b/lib/libimhex/source/ui/imgui_imhex_extensions.cpp @@ -1516,9 +1516,9 @@ namespace ImGuiExt { bool IsDarkBackground(const ImColor& bgColor) { // Extract RGB components in 0–255 range - int r = static_cast(bgColor.Value.x * 255.0f); - int g = static_cast(bgColor.Value.y * 255.0f); - int b = static_cast(bgColor.Value.z * 255.0f); + int r = static_cast(bgColor.Value.x * 255.0F); + int g = static_cast(bgColor.Value.y * 255.0F); + int b = static_cast(bgColor.Value.z * 255.0F); // Compute brightness using perceived luminance int brightness = (r * 299 + g * 587 + b * 114) / 1000; diff --git a/lib/trace/include/hex/trace/stacktrace.hpp b/lib/trace/include/hex/trace/stacktrace.hpp index b0671506d..74f4746c0 100644 --- a/lib/trace/include/hex/trace/stacktrace.hpp +++ b/lib/trace/include/hex/trace/stacktrace.hpp @@ -22,6 +22,5 @@ namespace hex::trace { }; StackTraceResult getStackTrace(); - [[nodiscard]] std::string demangle(const std::string &mangledName); - -} \ No newline at end of file + [[nodiscard]] std::string demangle(const std::string &symbolName); +} diff --git a/lib/trace/source/stacktrace.cpp b/lib/trace/source/stacktrace.cpp index 3ced627c2..1028a3f7d 100644 --- a/lib/trace/source/stacktrace.cpp +++ b/lib/trace/source/stacktrace.cpp @@ -218,7 +218,7 @@ static std::mutex s_traceMutex; } StackTraceResult getStackTrace() { - std::lock_guard lock(s_traceMutex); + std::scoped_lock lock(s_traceMutex); static std::vector result; diff --git a/main/gui/source/init/run/desktop.cpp b/main/gui/source/init/run/desktop.cpp index a9b0714a3..c7a3308f2 100644 --- a/main/gui/source/init/run/desktop.cpp +++ b/main/gui/source/init/run/desktop.cpp @@ -35,7 +35,7 @@ while (true) { const auto result = splashWindow->loop(); if (result.has_value()) { - if (result.value() == false) { + if (!result.value()) { ImHexApi::System::impl::addInitArgument("tasks-failed"); } diff --git a/main/gui/source/init/splash_window.cpp b/main/gui/source/init/splash_window.cpp index 65ec90113..281c373ee 100644 --- a/main/gui/source/init/splash_window.cpp +++ b/main/gui/source/init/splash_window.cpp @@ -40,7 +40,7 @@ namespace hex::init { WindowSplash::WindowSplash() : m_window(nullptr) { 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_totalTaskCount += 1; @@ -210,14 +210,14 @@ namespace hex::init { // Save an iterator to the current task name decltype(m_currTaskNames)::iterator taskNameIter; { - std::lock_guard guard(m_progressMutex); + std::scoped_lock guard(m_progressMutex); m_currTaskNames.push_back(task.name + "..."); taskNameIter = std::prev(m_currTaskNames.end()); } // When the task finished, increment the progress bar ON_SCOPE_EXIT { - std::lock_guard guard(m_progressMutex); + std::scoped_lock guard(m_progressMutex); m_completedTaskCount += 1; 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 { - std::lock_guard guard(m_progressMutex); + std::scoped_lock guard(m_progressMutex); m_currTaskNames.erase(taskNameIter); } } catch (const std::exception &e) { @@ -272,11 +272,11 @@ namespace hex::init { // Check every 10ms if all tasks have run while (true) { // 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 - if (!it->running) { - this->createTask(*it); - it->running = true; + if (!m_task.running) { + this->createTask(m_task); + m_task.running = true; } } @@ -396,7 +396,7 @@ namespace hex::init { // 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 progressBackgroundSize = ImVec2(442, 30); diff --git a/main/gui/source/main.cpp b/main/gui/source/main.cpp index a7137323a..579410aa2 100644 --- a/main/gui/source/main.cpp +++ b/main/gui/source/main.cpp @@ -64,7 +64,7 @@ int main(int argc, char **argv) { #if defined(OS_LINUX) 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 diff --git a/main/gui/source/messaging/linux.cpp b/main/gui/source/messaging/linux.cpp index feed83b12..8705efa54 100644 --- a/main/gui/source/messaging/linux.cpp +++ b/main/gui/source/messaging/linux.cpp @@ -1,6 +1,5 @@ #if defined(OS_LINUX) -#include #include #include #include @@ -25,7 +24,7 @@ namespace hex::messaging { fullEventData.insert(fullEventData.end(), args.begin(), args.end()); - u8 *data = &fullEventData[0]; + u8 *data = fullEventData.data(); auto dataSize = fullEventData.size(); int fifo = open(CommunicationPipePath, O_WRONLY); diff --git a/main/gui/source/window/platform/linux.cpp b/main/gui/source/window/platform/linux.cpp index 78c2707dc..d18ddf3e9 100644 --- a/main/gui/source/window/platform/linux.cpp +++ b/main/gui/source/window/platform/linux.cpp @@ -20,7 +20,6 @@ #include #include - #include #include #if defined(IMHEX_HAS_FONTCONFIG) diff --git a/main/gui/source/window/window.cpp b/main/gui/source/window/window.cpp index baef38047..a93c6afc5 100644 --- a/main/gui/source/window/window.cpp +++ b/main/gui/source/window/window.cpp @@ -25,8 +25,6 @@ #include #include -#include -#include #include #include @@ -663,7 +661,7 @@ namespace hex { const auto windowPos = ImHexApi::System::getMainWindowPosition(); 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 #if defined(OS_MACOS) @@ -956,13 +954,13 @@ namespace hex { GLuint quadVAO, quadVBO; float quadVertices[] = { // positions // texCoords - -1.0f, 1.0f, 0.0f, 1.0f, - -1.0f, -1.0f, 0.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, 0.0F, + 1.0F, -1.0F, 1.0F, 0.0F, - -1.0f, 1.0f, 0.0f, 1.0f, - 1.0f, -1.0f, 1.0f, 0.0f, - 1.0f, 1.0f, 1.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, 1.0F }; glGenVertexArrays(1, &quadVAO); @@ -971,7 +969,7 @@ namespace hex { glBindBuffer(GL_ARRAY_BUFFER, quadVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(quadVertices), quadVertices, GL_STATIC_DRAW); 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); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void*)(2 * sizeof(float))); glBindVertexArray(0); diff --git a/main/updater/source/main.cpp b/main/updater/source/main.cpp index 4bfe5492b..82dfd8c3e 100644 --- a/main/updater/source/main.cpp +++ b/main/updater/source/main.cpp @@ -158,7 +158,7 @@ bool installUpdate(const std::fs::path &updatePath) { UpdateHandler { ".deb", "zenity --password | sudo -S apt install -y --fix-broken \"{}\"" }, UpdateHandler { ".rpm", "zenity --password | sudo -S rpm -i \"{}\"" }, 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 { ".snap", "zenity --password | sudo -S snap install --dangerous \"{}\"" }, }; diff --git a/plugins/builtin/include/content/popups/hex_editor/popup_hex_editor_resize.hpp b/plugins/builtin/include/content/popups/hex_editor/popup_hex_editor_resize.hpp index 1d2ec321a..c4683d16c 100644 --- a/plugins/builtin/include/content/popups/hex_editor/popup_hex_editor_resize.hpp +++ b/plugins/builtin/include/content/popups/hex_editor/popup_hex_editor_resize.hpp @@ -12,7 +12,7 @@ namespace hex::plugin::builtin { [[nodiscard]] UnlocalizedString getTitle() const override; private: - static void resize(size_t newSize); + void resize(size_t newSize); u64 m_size; }; } \ No newline at end of file diff --git a/plugins/builtin/include/content/providers/file_provider.hpp b/plugins/builtin/include/content/providers/file_provider.hpp index fd6d0900f..f0a431f55 100644 --- a/plugins/builtin/include/content/providers/file_provider.hpp +++ b/plugins/builtin/include/content/providers/file_provider.hpp @@ -66,7 +66,7 @@ namespace hex::plugin::builtin { private: void handleFileChange(); - OpenResult open(bool memoryMapped); + OpenResult open(bool directAccess); protected: std::fs::path m_path; diff --git a/plugins/builtin/include/content/text_highlighting/pattern_language.hpp b/plugins/builtin/include/content/text_highlighting/pattern_language.hpp index 82b6c0c66..9f3917599 100644 --- a/plugins/builtin/include/content/text_highlighting/pattern_language.hpp +++ b/plugins/builtin/include/content/text_highlighting/pattern_language.hpp @@ -191,7 +191,7 @@ namespace hex::plugin::builtin { void renderErrors(); /// 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. - 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 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. @@ -251,10 +251,10 @@ namespace hex::plugin::builtin { void skipDelimiters(i32 maxSkipCount, Token delimiter[2], i8 increment); void skipToken(Token token, i8 step=1); /// 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 std::optional setChildrenTypes(); - bool findParentTypes(std::vector &parentTypes, const std::string &optionalName=""); + bool findParentTypes(std::vector &parentTypes, const std::string &optionalUDTName=""); bool findAllParentTypes(std::vector &parentTypes, std::vector &identifiers, std::string &optionalFullName); bool tryParentType(const std::string &parentType, std::string &variableName, std::optional &result, std::vector &identifiers); /// Convenience function diff --git a/plugins/builtin/include/plugin_builtin.hpp b/plugins/builtin/include/plugin_builtin.hpp new file mode 100644 index 000000000..e75704aac --- /dev/null +++ b/plugins/builtin/include/plugin_builtin.hpp @@ -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(); +} diff --git a/plugins/builtin/source/content/command_line_interface.cpp b/plugins/builtin/source/content/command_line_interface.cpp index 62a91a40d..d11f60a89 100644 --- a/plugins/builtin/source/content/command_line_interface.cpp +++ b/plugins/builtin/source/content/command_line_interface.cpp @@ -352,7 +352,7 @@ namespace hex::plugin::builtin { } void handleHexdumpCommand(const std::vector &args) { - if (args.size() < 1 || args.size() > 3) { + if (args.empty() || args.size() > 3) { log::println("usage: imhex --hexdump "); std::exit(EXIT_FAILURE); } @@ -399,7 +399,7 @@ namespace hex::plugin::builtin { if (std::fgets(input.data(), input.size() - 1, stdin) == nullptr) std::exit(EXIT_FAILURE); - input = input.c_str(); + input = input.c_str(); // Stop at first null byte input = wolv::util::trim(input); if (input == ConfirmationString) { @@ -536,7 +536,7 @@ namespace hex::plugin::builtin { mcp::Client client; 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); } diff --git a/plugins/builtin/source/content/data_inspector.cpp b/plugins/builtin/source/content/data_inspector.cpp index b94f8e4e8..123644e7a 100644 --- a/plugins/builtin/source/content/data_inspector.cpp +++ b/plugins/builtin/source/content/data_inspector.cpp @@ -1,3 +1,4 @@ +#include #include #include #include @@ -42,7 +43,7 @@ namespace hex::plugin::builtin { std::memcpy(bytes.data(), &result, bytes.size()); if (endian != std::endian::native) - std::reverse(bytes.begin(), bytes.end()); + std::ranges::reverse(bytes); return bytes; }); @@ -58,7 +59,7 @@ namespace hex::plugin::builtin { std::memcpy(bytes.data(), &result, bytes.size()); if (endian != std::endian::native) - std::reverse(bytes.begin(), bytes.end()); + std::ranges::reverse(bytes); return bytes; }); @@ -73,7 +74,7 @@ namespace hex::plugin::builtin { std::memcpy(bytes.data(), &result, bytes.size()); if (endian != std::endian::native) - std::reverse(bytes.begin(), bytes.end()); + std::ranges::reverse(bytes); return bytes; }); @@ -449,7 +450,7 @@ namespace hex::plugin::builtin { std::memcpy(bytes.data(), wideString->data(), bytes.size()); if (endian != std::endian::native) - std::reverse(bytes.begin(), bytes.end()); + std::ranges::reverse(bytes); return bytes; }) @@ -477,7 +478,7 @@ namespace hex::plugin::builtin { std::memcpy(bytes.data(), wideString->data(), bytes.size()); if (endian != std::endian::native) - std::reverse(bytes.begin(), bytes.end()); + std::ranges::reverse(bytes); return bytes; }) @@ -505,7 +506,7 @@ namespace hex::plugin::builtin { std::memcpy(bytes.data(), wideString->data(), bytes.size()); if (endian != std::endian::native) - std::reverse(bytes.begin(), bytes.end()); + std::ranges::reverse(bytes); return bytes; }) diff --git a/plugins/builtin/source/content/data_processor_nodes/logic_nodes.cpp b/plugins/builtin/source/content/data_processor_nodes/logic_nodes.cpp index bd9637e01..4d246b08b 100644 --- a/plugins/builtin/source/content/data_processor_nodes/logic_nodes.cpp +++ b/plugins/builtin/source/content/data_processor_nodes/logic_nodes.cpp @@ -1,3 +1,4 @@ +#include #include #include @@ -159,7 +160,7 @@ namespace hex::plugin::builtin { for (u8 &b : data) b = BitFlipLookup[b & 0xf] << 4 | BitFlipLookup[b >> 4]; - std::reverse(data.begin(), data.end()); + std::ranges::reverse(data); this->setBufferOnOutput(1, data); } diff --git a/plugins/builtin/source/content/data_processor_nodes/other_nodes.cpp b/plugins/builtin/source/content/data_processor_nodes/other_nodes.cpp index 4b2b4d5e4..626927a5b 100644 --- a/plugins/builtin/source/content/data_processor_nodes/other_nodes.cpp +++ b/plugins/builtin/source/content/data_processor_nodes/other_nodes.cpp @@ -1,3 +1,4 @@ +#include #include #include #include @@ -8,6 +9,7 @@ #include #include +#include #include #include @@ -174,7 +176,7 @@ namespace hex::plugin::builtin { const auto &inputB = this->getBufferOnInput(1); 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); } @@ -212,7 +214,7 @@ namespace hex::plugin::builtin { output.resize(buffer.size() * count); 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); } @@ -233,7 +235,7 @@ namespace hex::plugin::builtin { if (address + patch.size() > buffer.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); } @@ -382,7 +384,7 @@ namespace hex::plugin::builtin { if (ImPlot::BeginPlot("##distribution", viewSize, ImPlotFlags_NoLegend | ImPlotFlags_NoMenus | ImPlotFlags_NoBoxSelect)) { ImPlot::SetupAxes("Address", "Count", ImPlotAxisFlags_Lock, ImPlotAxisFlags_Lock); 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 = [] { std::array result { 0 }; @@ -463,7 +465,7 @@ namespace hex::plugin::builtin { void process() override { auto data = this->getBufferOnInput(0); - std::reverse(data.begin(), data.end()); + std::ranges::reverse(data); this->setBufferOnOutput(1, data); } diff --git a/plugins/builtin/source/content/data_visualizers.cpp b/plugins/builtin/source/content/data_visualizers.cpp index efc48a9fe..7fee3654e 100644 --- a/plugins/builtin/source/content/data_visualizers.cpp +++ b/plugins/builtin/source/content/data_visualizers.cpp @@ -90,8 +90,8 @@ namespace hex::plugin::builtin { } private: - constexpr static inline auto ByteCount = 1; - constexpr static inline auto CharCount = ByteCount * 2; + constexpr static auto ByteCount = 1; + constexpr static auto CharCount = ByteCount * 2; const static inline auto FormattingUpperCase = fmt::format("%0{}{}X", CharCount, ImGuiExt::getFormatLengthSpecifier()); const static inline auto FormattingLowerCase = fmt::format("%0{}{}x", CharCount, ImGuiExt::getFormatLengthSpecifier()); @@ -175,13 +175,13 @@ namespace hex::plugin::builtin { } private: - constexpr static inline auto ByteCount = sizeof(T); - constexpr static inline auto CharCount = 14; + constexpr static auto ByteCount = sizeof(T); + constexpr static auto CharCount = 14; const static inline auto FormatStringUpperCase = 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) return FormatStringUpperCase.c_str(); else diff --git a/plugins/builtin/source/content/events.cpp b/plugins/builtin/source/content/events.cpp index c912fbb23..7a88baad1 100644 --- a/plugins/builtin/source/content/events.cpp +++ b/plugins/builtin/source/content/events.cpp @@ -258,11 +258,11 @@ namespace hex::plugin::builtin { }); EventImHexStartupFinished::subscribe([] { - const auto currVersion = ImHexApi::System::getImHexVersion(); + const auto& currVersion = ImHexApi::System::getImHexVersion(); const auto prevLaunchVersion = ContentRegistry::Settings::read("hex.builtin.setting.general", "hex.builtin.setting.general.prev_launch_version", ""); const auto forceOobe = getEnvironmentVariable("IMHEX_FORCE_OOBE"); - if (prevLaunchVersion == "" || (forceOobe.has_value() && *forceOobe != "0")) { + if (prevLaunchVersion.empty() || (forceOobe.has_value() && *forceOobe != "0")) { EventFirstLaunch::post(); return; } diff --git a/plugins/builtin/source/content/init_tasks.cpp b/plugins/builtin/source/content/init_tasks.cpp index 7136f1577..f3f17cc8e 100644 --- a/plugins/builtin/source/content/init_tasks.cpp +++ b/plugins/builtin/source/content/init_tasks.cpp @@ -123,7 +123,7 @@ namespace hex::plugin::builtin { if (restoreWindowPos) { ImHexApi::System::InitialWindowProperties properties = {}; - properties.maximized = ContentRegistry::Settings::read("hex.builtin.setting.interface", "hex.builtin.setting.interface.window.maximized", 0); + properties.maximized = ContentRegistry::Settings::read("hex.builtin.setting.interface", "hex.builtin.setting.interface.window.maximized", false); properties.x = ContentRegistry::Settings::read("hex.builtin.setting.interface", "hex.builtin.setting.interface.window.x", 0); properties.y = ContentRegistry::Settings::read("hex.builtin.setting.interface", "hex.builtin.setting.interface.window.y", 0); properties.width = ContentRegistry::Settings::read("hex.builtin.setting.interface", "hex.builtin.setting.interface.window.width", 0); diff --git a/plugins/builtin/source/content/minimap_visualizers.cpp b/plugins/builtin/source/content/minimap_visualizers.cpp index 66bdfbfd1..f44a3630a 100644 --- a/plugins/builtin/source/content/minimap_visualizers.cpp +++ b/plugins/builtin/source/content/minimap_visualizers.cpp @@ -51,9 +51,9 @@ namespace hex::plugin::builtin { void zerosMiniMapVisualizer(u64, std::span data, std::vector &output) { for (u8 byte : data) { 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 - 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 data, std::vector &output) { colorMinimapVisualizer(address, data, output, 4, [](std::span 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 g = ((subData[0] & 0x07) << 5) | ((subData[1] & 0xE0) >> 3); u8 b = (subData[1] & 0x1F) << 3; - return ImColor(r, g, b, 0xFF); + return {r, g, b, 0xFF}; }); } diff --git a/plugins/builtin/source/content/out_of_box_experience.cpp b/plugins/builtin/source/content/out_of_box_experience.cpp index 2384bd7cb..b7841ed22 100644 --- a/plugins/builtin/source/content/out_of_box_experience.cpp +++ b/plugins/builtin/source/content/out_of_box_experience.cpp @@ -37,7 +37,7 @@ namespace hex::plugin::builtin { class Blend { 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() { m_time += ImGui::GetIO().DeltaTime; @@ -56,7 +56,7 @@ namespace hex::plugin::builtin { } private: - float m_time; + float m_time = 0; float m_start, m_end; }; @@ -472,7 +472,7 @@ namespace hex::plugin::builtin { EventFirstLaunch::subscribe([] { 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(), 0, 0, ImGuiExt::Texture::Filter::Linear); s_compassTexture = ImGuiExt::Texture::fromImage(romfs::get("assets/common/compass.png").span(), ImGuiExt::Texture::Filter::Linear); s_globeTexture = ImGuiExt::Texture::fromImage(romfs::get("assets/common/globe.png").span(), ImGuiExt::Texture::Filter::Linear); diff --git a/plugins/builtin/source/content/pl_builtin_types.cpp b/plugins/builtin/source/content/pl_builtin_types.cpp index 421bbc00e..10145a2d6 100644 --- a/plugins/builtin/source/content/pl_builtin_types.cpp +++ b/plugins/builtin/source/content/pl_builtin_types.cpp @@ -1,3 +1,4 @@ +#include #include #include @@ -43,7 +44,7 @@ namespace hex::plugin::builtin { this->getEvaluator()->readData(this->getOffset(), result.data(), result.size(), this->getSection()); if (this->getEndian() != std::endian::native) - std::reverse(result.begin(), result.end()); + std::ranges::reverse(result); return result; } diff --git a/plugins/builtin/source/content/providers/command_provider.cpp b/plugins/builtin/source/content/providers/command_provider.cpp index 1999e0ae4..1c6beda9c 100644 --- a/plugins/builtin/source/content/providers/command_provider.cpp +++ b/plugins/builtin/source/content/providers/command_provider.cpp @@ -27,7 +27,7 @@ namespace hex::plugin::builtin { using namespace std::chrono_literals; - CommandProvider::CommandProvider() { } + CommandProvider::CommandProvider() = default; bool CommandProvider::isAvailable() const { return m_open; diff --git a/plugins/builtin/source/content/providers/gdb_provider.cpp b/plugins/builtin/source/content/providers/gdb_provider.cpp index 07bf3b008..d9aed184f 100644 --- a/plugins/builtin/source/content/providers/gdb_provider.cpp +++ b/plugins/builtin/source/content/providers/gdb_provider.cpp @@ -217,7 +217,7 @@ namespace hex::plugin::builtin { auto data = gdb::readMemory(m_socket, offset, size); 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) { diff --git a/plugins/builtin/source/content/providers/process_memory_provider.cpp b/plugins/builtin/source/content/providers/process_memory_provider.cpp index db85fda42..01dffa810 100644 --- a/plugins/builtin/source/content/providers/process_memory_provider.cpp +++ b/plugins/builtin/source/content/providers/process_memory_provider.cpp @@ -1,5 +1,6 @@ #if defined(OS_WINDOWS) || defined(OS_MACOS) || (defined(OS_LINUX) && !defined(OS_FREEBSD)) +#include #include #include @@ -568,7 +569,7 @@ namespace hex::plugin::builtin { std::variant ProcessMemoryProvider::queryInformation(const std::string &category, const std::string &argument) { 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 ®ion) { return region.name == name; }); diff --git a/plugins/builtin/source/content/recent.cpp b/plugins/builtin/source/content/recent.cpp index 9c5cc6763..490feeb81 100644 --- a/plugins/builtin/source/content/recent.cpp +++ b/plugins/builtin/source/content/recent.cpp @@ -116,7 +116,7 @@ namespace hex::plugin::builtin::recent { return ImGuiWindowFlags_AlwaysAutoResize; } - void saveCurrentProjectAsRecent() { + static void saveCurrentProjectAsRecent() { if (!ContentRegistry::Settings::read("hex.builtin.setting.general", "hex.builtin.setting.general.save_recent_providers", true)) { return; } diff --git a/plugins/builtin/source/content/settings_entries.cpp b/plugins/builtin/source/content/settings_entries.cpp index 356b991d8..28c84cb05 100644 --- a/plugins/builtin/source/content/settings_entries.cpp +++ b/plugins/builtin/source/content/settings_entries.cpp @@ -1,3 +1,4 @@ +#include #include #include #include @@ -81,11 +82,7 @@ namespace hex::plugin::builtin { return "%d FPS"; }(); - if (ImGui::SliderInt(name.data(), &m_value, 14, 201, format.c_str(), ImGuiSliderFlags_AlwaysClamp)) { - return true; - } - - return false; + return ImGui::SliderInt(name.data(), &m_value, 14, 201, format.c_str(), ImGuiSliderFlags_AlwaysClamp); } 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))) { 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); ImHexApi::System::setAdditionalFolderPaths(m_paths); @@ -170,7 +167,8 @@ namespace hex::plugin::builtin { nlohmann::json store() override { std::vector 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)); } @@ -211,7 +209,7 @@ namespace hex::plugin::builtin { return m_value; } - float getValue() const { + [[nodiscard]] float getValue() const { 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); }(); - if (ImGui::SliderInt(name.data(), &m_value, 0, (30 * 60) / 30, format.c_str(), ImGuiSliderFlags_AlwaysClamp | ImGuiSliderFlags_NoInput)) { - return true; - } - - return false; + return ImGui::SliderInt(name.data(), &m_value, 0, (30 * 60) / 30, format.c_str(), ImGuiSliderFlags_AlwaysClamp | ImGuiSliderFlags_NoInput); } void load(const nlohmann::json &data) override { @@ -794,6 +788,7 @@ namespace hex::plugin::builtin { { auto themeNames = ThemeManager::getThemeNames(); std::vector themeJsons = { }; + themeJsons.reserve(themeNames.size()); for (const auto &themeName : themeNames) themeJsons.emplace_back(themeName); @@ -1059,7 +1054,8 @@ namespace hex::plugin::builtin { auto folderPathStrings = ContentRegistry::Settings::read>("hex.builtin.setting.folders", "hex.builtin.setting.folders", { }); std::vector paths; - for (const auto &pathString : folderPathStrings) { + paths.reserve(folderPathStrings.size()); +for (const auto &pathString : folderPathStrings) { paths.emplace_back(pathString); } diff --git a/plugins/builtin/source/content/text_highlighting/pattern_language.cpp b/plugins/builtin/source/content/text_highlighting/pattern_language.cpp index 7b0737f45..d7d8e8fee 100644 --- a/plugins/builtin/source/content/text_highlighting/pattern_language.cpp +++ b/plugins/builtin/source/content/text_highlighting/pattern_language.cpp @@ -1,3 +1,4 @@ +#include #include #include #include @@ -59,7 +60,7 @@ namespace hex::plugin::builtin { bool TextHighlighter::forwardIdentifierName(std::string &identifierName, std::vector &identifiers, bool preserveCurr ) { auto curr = m_curr; - Identifier *identifier = getValue(0); + auto *identifier = getValue(0); std::string current; if (identifier != nullptr) { @@ -287,7 +288,7 @@ namespace hex::plugin::builtin { if (peek(tkn::Literal::Identifier)) { if (identifier = getValue(0); identifier != nullptr) { identifierType = identifier->getType(); - std::string name = identifier->get(); + auto& name = identifier->get(); if (identifierType == identifierTypeToSearch) { switch (identifierType) { @@ -367,8 +368,7 @@ namespace hex::plugin::builtin { } } m_curr = curr; - return; - } + } void TextHighlighter::skipTemplate(i32 maxSkipCount, bool forward) { Token delimiters[2]; @@ -523,7 +523,7 @@ namespace hex::plugin::builtin { result.idType = IdentifierType::Unknown; std::string identifierName = optionalIdentifierName; - if (optionalIdentifierName == "") { + if (optionalIdentifierName.empty()) { std::vector 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; }); @@ -681,7 +681,7 @@ namespace hex::plugin::builtin { next(); } else if (auto udtVars = m_UDTVariables[result.typeStr];udtVars.contains(vectorString[index-1])) { auto saveCurr = m_curr; - std::string templateName = ""; + std::string templateName; auto instances = m_instances[variableParentType]; for (auto instance : instances) { if (auto *identifier = std::get_if(&m_tokens[instance].value); identifier != nullptr && identifier->getType() == IdentifierType::TemplateArgument) { @@ -704,7 +704,7 @@ namespace hex::plugin::builtin { next(); } else{ if (m_typeDefMap.contains(variableParentType)) { - std::string typeName = ""; + std::string typeName; instances = m_instances[variableParentType]; for (auto instance: instances) { if (auto *identifier = std::get_if(&m_tokens[instance].value); @@ -771,7 +771,7 @@ namespace hex::plugin::builtin { if (!sequence(tkn::Operator::ScopeResolution) || vectorStringCount != i+2 || !m_UDTVariables.contains(name)) return false; - auto variableName = vectorString[i+1]; + const auto& variableName = vectorString[i+1]; if (!m_UDTVariables[name].contains(variableName)) return false; auto variableDefinition = m_UDTVariables[name][variableName][0]; @@ -858,16 +858,14 @@ namespace hex::plugin::builtin { if (tokenId > interval.start && tokenId < interval.end) { - if (nameSpace == "") + if (nameSpace.empty()) nameSpace = name; else nameSpace = name + "::" + nameSpace; } } - if (nameSpace != "") - return true; - return false; + return nameSpace != ""; } //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) { auto curr = m_curr; next(); - std::string typeName = ""; + std::string typeName; if (sequence(tkn::Operator::Assign, tkn::Literal::Identifier)) { auto identifier2 = getValue(-1); if (identifier2 != nullptr) { @@ -1452,7 +1450,8 @@ namespace hex::plugin::builtin { void TextHighlighter::colorRemainingIdentifierTokens() { std::vector taggedIdentifiers; - for (auto index: m_taggedIdentifiers) { + taggedIdentifiers.reserve(m_taggedIdentifiers.size()); +for (auto index: m_taggedIdentifiers) { taggedIdentifiers.push_back(index); } m_taggedIdentifiers.clear(); @@ -1470,7 +1469,7 @@ namespace hex::plugin::builtin { taggedIdentifiers.pop_back(); } - Token *token = const_cast(&m_curr[0]); + auto *token = const_cast(&m_curr[0]); if (sequence(tkn::Keyword::Import, tkn::Literal::Identifier)) { next(-1); @@ -1581,7 +1580,7 @@ namespace hex::plugin::builtin { continue; std::string lineOfColors = std::string(m_lines[line].size(), 0); for (auto tokenIndex = m_firstTokenIdOfLine[line]; tokenIndex < m_firstTokenIdOfLine[nextLine(line)]; tokenIndex++) { - Token *token = const_cast(&m_tokens[tokenIndex]); + auto *token = const_cast(&m_tokens[tokenIndex]); if (m_tokenColors.contains(token) && token->type == Token::Type::Identifier) { u8 color = (u8) m_tokenColors.at(token); u32 tokenLength = token->location.length; @@ -1935,7 +1934,7 @@ namespace hex::plugin::builtin { } m_lines = wolv::util::splitString(m_text, "\n"); - m_lines.push_back(""); + m_lines.emplace_back(""); m_firstTokenIdOfLine.clear(); m_firstTokenIdOfLine.resize(m_lines.size(), -1); @@ -2143,7 +2142,7 @@ namespace hex::plugin::builtin { while (next != ranges.end()) { if (next->start - it->end < 2) { - Interval &range = const_cast(*it); + auto &range = const_cast(*it); range.end = next->end; ranges.erase(next); next = std::next(it); @@ -2345,6 +2344,5 @@ namespace hex::plugin::builtin { m_wasInterrupted = true; return; } - return; } } diff --git a/plugins/builtin/source/content/tools/byte_swapper.cpp b/plugins/builtin/source/content/tools/byte_swapper.cpp index f16045a10..87279349c 100644 --- a/plugins/builtin/source/content/tools/byte_swapper.cpp +++ b/plugins/builtin/source/content/tools/byte_swapper.cpp @@ -4,6 +4,7 @@ #include #include +#include #include diff --git a/plugins/builtin/source/content/tools/http_requests.cpp b/plugins/builtin/source/content/tools/http_requests.cpp index 8dde6b6a2..a76ae8bc4 100644 --- a/plugins/builtin/source/content/tools/http_requests.cpp +++ b/plugins/builtin/source/content/tools/http_requests.cpp @@ -124,7 +124,7 @@ namespace hex::plugin::builtin { if (response.valid() && response.wait_for(0s) != std::future_status::timeout) { const auto result = response.get(); - const auto data = result.getData(); + const auto& data = result.getData(); if (const auto status = result.getStatusCode(); status != 0) responseText = "Status: " + std::to_string(result.getStatusCode()) + "\n\n" + data; diff --git a/plugins/builtin/source/content/tools/ieee_decoder.cpp b/plugins/builtin/source/content/tools/ieee_decoder.cpp index 52c9b6620..f6d03b7d8 100644 --- a/plugins/builtin/source/content/tools/ieee_decoder.cpp +++ b/plugins/builtin/source/content/tools/ieee_decoder.cpp @@ -25,12 +25,12 @@ namespace hex::plugin::builtin { class IEEE754STATICS { public: - IEEE754STATICS() : value(0), exponentBitCount(8), mantissaBitCount(23), resultFloat(0) {} + IEEE754STATICS() {} - u128 value; - i32 exponentBitCount; - i32 mantissaBitCount; - long double resultFloat; + u128 value = 0; + i32 exponentBitCount = 8; + i32 mantissaBitCount =23; + long double resultFloat = 0; }; static IEEE754STATICS ieee754statics; diff --git a/plugins/builtin/source/content/tools_entries.cpp b/plugins/builtin/source/content/tools_entries.cpp index d6580937c..65c33207a 100644 --- a/plugins/builtin/source/content/tools_entries.cpp +++ b/plugins/builtin/source/content/tools_entries.cpp @@ -9,7 +9,7 @@ namespace hex::plugin::builtin { - void drawFileTools() { + static void drawFileTools() { if (ImGui::BeginTabBar("file_tools_tabs")) { if (ImGui::BeginTabItem("hex.builtin.tools.file_tools.shredder"_lang)) { drawFileToolShredder(); diff --git a/plugins/builtin/source/content/views/fullscreen/view_fullscreen_save_editor.cpp b/plugins/builtin/source/content/views/fullscreen/view_fullscreen_save_editor.cpp index 3048f15a0..04480d680 100644 --- a/plugins/builtin/source/content/views/fullscreen/view_fullscreen_save_editor.cpp +++ b/plugins/builtin/source/content/views/fullscreen/view_fullscreen_save_editor.cpp @@ -121,7 +121,7 @@ namespace hex::plugin::builtin { try { 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 widgetPos = 200_scaled; diff --git a/plugins/builtin/source/content/views/view_achievements.cpp b/plugins/builtin/source/content/views/view_achievements.cpp index 282222136..b4a83c388 100644 --- a/plugins/builtin/source/content/views/view_achievements.cpp +++ b/plugins/builtin/source/content/views/view_achievements.cpp @@ -1,5 +1,6 @@ #include "content/views/view_achievements.hpp" +#include #include #include #include @@ -321,11 +322,12 @@ namespace hex::plugin::builtin { // Get all achievement category names std::vector categories; - for (const auto &[categoryName, achievements] : startNodes) { + categories.reserve(startNodes.size()); +for (const auto &[categoryName, achievements] : startNodes) { categories.push_back(categoryName); } - std::reverse(categories.begin(), categories.end()); + std::ranges::reverse(categories); // Draw each individual achievement category for (const auto &categoryName : categories) { diff --git a/plugins/builtin/source/content/views/view_data_inspector.cpp b/plugins/builtin/source/content/views/view_data_inspector.cpp index 10380b637..4b41ee87f 100644 --- a/plugins/builtin/source/content/views/view_data_inspector.cpp +++ b/plugins/builtin/source/content/views/view_data_inspector.cpp @@ -1,5 +1,6 @@ #include "content/views/view_data_inspector.hpp" +#include #include #include #include @@ -263,7 +264,7 @@ namespace hex::plugin::builtin { } 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; }); diff --git a/plugins/builtin/source/content/views/view_data_processor.cpp b/plugins/builtin/source/content/views/view_data_processor.cpp index 7b8af928f..df1021d97 100644 --- a/plugins/builtin/source/content/views/view_data_processor.cpp +++ b/plugins/builtin/source/content/views/view_data_processor.cpp @@ -1,4 +1,5 @@ #include "content/views/view_data_processor.hpp" +#include #include #include @@ -52,9 +53,9 @@ namespace hex::plugin::builtin { 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) { default: case 0: return dp::Attribute::Type::Integer; @@ -121,8 +122,8 @@ namespace hex::plugin::builtin { ImGui::PopItemWidth(); } - const std::string &getName() const { return m_name; } - dp::Attribute::Type getType() const { + [[nodiscard]] const std::string &getName() const { return m_name; } + [[nodiscard]] dp::Attribute::Type getType() const { switch (m_type) { case 0: return dp::Attribute::Type::Integer; 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 { j = nlohmann::json::object(); @@ -314,7 +315,7 @@ namespace hex::plugin::builtin { } private: - std::vector findAttributes() const { + [[nodiscard]] std::vector findAttributes() const { std::vector 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; } - NodeCustomInput* findInput(const std::string &name) const { + [[nodiscard]] NodeCustomInput* findInput(const std::string &name) const { for (auto &node : m_workspace.nodes) { if (auto *inputNode = dynamic_cast(node.get()); inputNode != nullptr && inputNode->getName() == name) return inputNode; @@ -337,7 +338,7 @@ namespace hex::plugin::builtin { return nullptr; } - NodeCustomOutput* findOutput(const std::string &name) const { + [[nodiscard]] NodeCustomOutput* findOutput(const std::string &name) const { for (auto &node : m_workspace.nodes) { if (auto *outputNode = dynamic_cast(node.get()); outputNode != nullptr && outputNode->getName() == name) return outputNode; @@ -445,7 +446,7 @@ namespace hex::plugin::builtin { void ViewDataProcessor::eraseLink(Workspace &workspace, int 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) { 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 for (int id : ids) { // 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) { return node->getId() == id; }); @@ -495,7 +496,7 @@ namespace hex::plugin::builtin { // and remove the nodes from the workspace for (int id : ids) { // 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) { return node->getId() == id; }); @@ -762,7 +763,7 @@ namespace hex::plugin::builtin { if (ImGui::BeginPopup("Node Menu")) { if (ImGui::MenuItem("hex.builtin.view.data_processor.menu.save_node"_lang)) { // 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) { return node->getId() == m_rightClickedId; }); @@ -856,7 +857,7 @@ namespace hex::plugin::builtin { auto value = i64(*reinterpret_cast(defaultValue.data())); if (ImGui::InputScalar(Lang(attribute.getUnlocalizedName()), ImGuiDataType_S64, &value)) { - std::fill(defaultValue.begin(), defaultValue.end(), 0x00); + std::ranges::fill(defaultValue, 0x00); i128 writeValue = value; std::memcpy(defaultValue.data(), &writeValue, sizeof(writeValue)); @@ -866,7 +867,7 @@ namespace hex::plugin::builtin { auto value = double(*reinterpret_cast(defaultValue.data())); 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; std::memcpy(defaultValue.data(), &writeValue, sizeof(writeValue)); diff --git a/plugins/builtin/source/content/views/view_find.cpp b/plugins/builtin/source/content/views/view_find.cpp index 8ba514635..30ff59138 100644 --- a/plugins/builtin/source/content/views/view_find.cpp +++ b/plugins/builtin/source/content/views/view_find.cpp @@ -1,5 +1,6 @@ #include "content/views/view_find.hpp" +#include #include #include #include @@ -214,16 +215,16 @@ namespace hex::plugin::builtin { newSettings.type = ASCII; 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) { newSettings.type = UTF16BE; 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) { newSettings.type = UTF16LE; 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; @@ -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("{} [_]", "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("{} [ \\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::EndPopup(); @@ -1158,11 +1159,11 @@ namespace hex::plugin::builtin { m_filterTask.interrupt(); static std::mutex mutex; - std::lock_guard lock(mutex); + std::scoped_lock lock(mutex); 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) { - std::lock_guard lock(mutex); + std::scoped_lock lock(mutex); u64 progress = 0; std::erase_if(currOccurrences, [this, provider, &task, &progress, &filter](const auto ®ion) { diff --git a/plugins/builtin/source/content/views/view_pattern_data.cpp b/plugins/builtin/source/content/views/view_pattern_data.cpp index 44c1e2086..1e6b0bd8b 100644 --- a/plugins/builtin/source/content/views/view_pattern_data.cpp +++ b/plugins/builtin/source/content/views/view_pattern_data.cpp @@ -304,7 +304,7 @@ namespace hex::plugin::builtin { try { 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 widgetPos = 200_scaled; diff --git a/plugins/builtin/source/content/views/view_pattern_editor.cpp b/plugins/builtin/source/content/views/view_pattern_editor.cpp index 5b4380653..8aae63355 100644 --- a/plugins/builtin/source/content/views/view_pattern_editor.cpp +++ b/plugins/builtin/source/content/views/view_pattern_editor.cpp @@ -456,8 +456,8 @@ namespace hex::plugin::builtin { ) ) ); - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f)); - ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0.0f, 0.0f)); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0F, 0.0F)); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0.0F, 0.0F)); if (ImGui::BeginChild("##pattern_editor_resizer", defaultEditorSize, ImGuiChildFlags_ResizeY)) { m_textEditor.get(provider).render("##pattern_editor", ImGui::GetContentRegionAvail(), false); m_textEditorHoverBox = ImGui::GetCurrentWindow()->Rect(); @@ -1257,7 +1257,7 @@ namespace hex::plugin::builtin { m_hasUnevaluatedChanges.get(provider) = true; variable.value = buffer[0]; } else if (variable.type == pl::core::Token::ValueType::String) { - std::string buffer = hex::get_or(variable.value, ""); + auto buffer = hex::get_or(variable.value, ""); if (ImGui::InputText(label.c_str(), buffer)) m_hasUnevaluatedChanges.get(provider) = true; variable.value = buffer; @@ -1354,7 +1354,7 @@ namespace hex::plugin::builtin { for (const auto &frame : **m_callStack | std::views::reverse) { auto location = frame.node->getLocation(); if (location.source != nullptr && location.source->mainSource) { - std::string message = ""; + std::string message; if (m_lastEvaluationError->has_value()) message = processMessage((*m_lastEvaluationError)->message); auto key = ui::TextEditor::Coordinates(location.line, location.column); @@ -1646,7 +1646,7 @@ namespace hex::plugin::builtin { ContentRegistry::PatternLanguage::configureRuntime(*m_editorRuntime, nullptr); 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 oldPatternVariables = std::move(patternVariables); @@ -2132,7 +2132,7 @@ namespace hex::plugin::builtin { if (m_breakpoints->contains(line)) evaluator->removeBreakpoint(line); - else + else evaluator->addBreakpoint(line); m_breakpoints = evaluator->getBreakpoints(); diff --git a/plugins/builtin/source/content/welcome_screen.cpp b/plugins/builtin/source/content/welcome_screen.cpp index 58d01c6b8..4d781dbb8 100644 --- a/plugins/builtin/source/content/welcome_screen.cpp +++ b/plugins/builtin/source/content/welcome_screen.cpp @@ -1,3 +1,4 @@ +#include #include #include @@ -162,7 +163,7 @@ namespace hex::plugin::builtin { bool isAnyViewOpen() { const auto &views = ContentRegistry::Views::impl::getEntries(); - return std::any_of(views.begin(), views.end(), + return std::ranges::any_of(views, [](const auto &entry) { return entry.second->getWindowOpenState(); }); @@ -819,7 +820,7 @@ namespace hex::plugin::builtin { std::mt19937 random(daysSinceEpoch.count()); 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(); bool showTipOfTheDay = ContentRegistry::Settings::read("hex.builtin.setting.general", "hex.builtin.setting.general.show_tips", false); diff --git a/plugins/builtin/source/content/window_decoration.cpp b/plugins/builtin/source/content/window_decoration.cpp index f46ae274b..a99d2c0e7 100644 --- a/plugins/builtin/source/content/window_decoration.cpp +++ b/plugins/builtin/source/content/window_decoration.cpp @@ -1,3 +1,4 @@ +#include #include #include #include @@ -601,7 +602,7 @@ namespace hex::plugin::builtin { if (const auto &items = ContentRegistry::UserInterface::impl::getSidebarItems(); items.empty()) { return false; } else { - return std::any_of(items.begin(), items.end(), [](const auto &item) { + return std::ranges::any_of(items, [](const auto &item) { return item.enabledCallback(); }); } @@ -609,7 +610,7 @@ namespace hex::plugin::builtin { bool isAnyViewOpen() { const auto &views = ContentRegistry::Views::impl::getEntries(); - return std::any_of(views.begin(), views.end(), + return std::ranges::any_of(views, [](const auto &entry) { return entry.second->getWindowOpenState(); }); diff --git a/plugins/builtin/source/plugin_builtin.cpp b/plugins/builtin/source/plugin_builtin.cpp index 60bd04320..eedf310c1 100644 --- a/plugins/builtin/source/plugin_builtin.cpp +++ b/plugins/builtin/source/plugin_builtin.cpp @@ -1,5 +1,6 @@ -#include +#include +#include #include #include #include @@ -15,54 +16,6 @@ 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() { { "help", "h", "Print help about this command", hex::plugin::builtin::handleHelpCommand }, { "version", "", "Print ImHex version", hex::plugin::builtin::handleVersionCommand }, diff --git a/plugins/ui/include/ui/text_editor.hpp b/plugins/ui/include/ui/text_editor.hpp index 6d401fc4c..733a807a9 100644 --- a/plugins/ui/include/ui/text_editor.hpp +++ b/plugins/ui/include/ui/text_editor.hpp @@ -3,14 +3,10 @@ #include #include #include -#include -#include #include #include #include #include -#include -#include #include "imgui.h" #include "imgui_internal.h" #include @@ -107,7 +103,7 @@ namespace hex::ui { public: friend class TextEditor; 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) {} private: Range m_selection; @@ -277,37 +273,37 @@ namespace hex::ui { 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 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(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 &o) const; - i32 indexColumn(i32 stringIndex) const; - i32 maxColumn(); - i32 maxColumn() const; - i32 columnIndex(i32 column) const; - i32 textSize() const; - i32 textSize(u32 index) const; + bool operator==(const Line &line) const; + bool operator!=(const Line &line) const; + [[nodiscard]] i32 indexColumn(i32 stringIndex) const; + [[nodiscard]] i32 maxColumn(); + [[nodiscard]] i32 maxColumn() const; + [[nodiscard]] i32 columnIndex(i32 column) const; + [[nodiscard]] i32 textSize() const; + [[nodiscard]] i32 textSize(u32 index) const; 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); - LineIterator begin() const; - LineIterator end() const; + [[nodiscard]] LineIterator begin() const; + [[nodiscard]] LineIterator end() const; LineIterator begin(); LineIterator end(); Line &operator=(const Line &line); Line &operator=(Line &&line) noexcept; - u64 size() const; + [[nodiscard]] u64 size() const; TextEditor::Line trim(TrimMode trimMode); - char front(LinePart part = LinePart::Chars) const; - std::string frontUtf8(LinePart part = LinePart::Chars) const; + [[nodiscard]] char front(LinePart part = LinePart::Chars) const; + [[nodiscard]] std::string frontUtf8(LinePart part = LinePart::Chars) const; void push_back(char c); - bool empty() const; - std::string substr(u64 start, u64 length = (u64) -1, LinePart part = LinePart::Chars) const; + [[nodiscard]] bool empty() const; + [[nodiscard]] std::string substr(u64 start, u64 length = (u64) -1, LinePart part = LinePart::Chars) const; Line subLine(u64 start, u64 length = (u64) -1); char operator[](u64 index) const; // 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; void setNeedsUpdate(bool needsUpdate); void append(const char *text); - void append(const char text); + void append(char text); void append(const std::string &text); void append(const Line &line); void append(LineIterator begin, LineIterator end); 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, const Line &line); void insert(LineIterator iter, LineIterator beginLine, LineIterator endLine); @@ -330,7 +326,7 @@ namespace hex::ui { void clear(); void setLine(const std::string &text); void setLine(const Line &text); - bool needsUpdate() const; + [[nodiscard]] bool needsUpdate() const; bool isEndOfLine(i32 column); private: std::string m_chars; @@ -352,14 +348,14 @@ namespace hex::ui { Identifiers m_identifiers; Identifiers m_preprocIdentifiers; std::string m_singleLineComment, m_commentEnd, m_commentStart, m_globalDocComment, m_docComment, m_blockDocComment; - char m_preprocChar; - bool m_autoIndentation; + char m_preprocChar = '#'; + bool m_autoIndentation = true; TokenizeCallback m_tokenize; 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(""), - m_docComment(""), m_blockDocComment(""), m_preprocChar('#'), m_autoIndentation(true), m_tokenize(nullptr), m_tokenRegexStrings({}), m_caseSensitive(true) {} + LanguageDefinition() : m_keywords({}), m_identifiers({}), m_preprocIdentifiers({}), + m_tokenize(nullptr), m_tokenRegexStrings({}) {} static const LanguageDefinition &CPlusPlus(); static const LanguageDefinition &HLSL(); @@ -376,12 +372,12 @@ namespace hex::ui { class UndoRecord { public: friend class TextEditor; - UndoRecord() {} + UndoRecord() = default; ~UndoRecord() {} UndoRecord( const std::string &added, - const Range addedRange, + Range addedRange, const std::string &removed, - const Range removedRange, + Range removedRange, EditorState &before, EditorState &after); @@ -398,7 +394,7 @@ namespace hex::ui { class UndoAction { public: - UndoAction() {} + UndoAction() = default; ~UndoAction() {} explicit UndoAction(const UndoRecords &records) : m_records(records) {} void undo(TextEditor *editor); @@ -412,8 +408,8 @@ namespace hex::ui { struct MatchedBracket { bool m_active = false; bool m_changed = false; - Coordinates m_nearCursor = {}; - Coordinates m_matched = {}; + Coordinates m_nearCursor; + Coordinates m_matched; static const std::string s_separators; static const std::string s_operators; @@ -421,7 +417,7 @@ namespace hex::ui { m_nearCursor(other.m_nearCursor), 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) : 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); i32 detectDirection(TextEditor *editor, const Coordinates &from); void findMatchingBracket(TextEditor *editor); - bool isActive() const { return m_active; } - bool hasChanged() const { return m_changed; } + [[nodiscard]] bool isActive() const { return m_active; } + [[nodiscard]] bool hasChanged() const { return m_changed; } }; @@ -446,11 +442,11 @@ namespace hex::ui { void setTopLine(); void render(const char *title, const ImVec2 &size = ImVec2(), bool border = false); - inline void setShowCursor(bool value) { m_showCursor = value; } - inline void setShowLineNumbers(bool value) { m_showLineNumbers = value; } - inline void setShowWhitespaces(bool value) { m_showWhitespaces = value; } - inline bool isShowingWhitespaces() const { return m_showWhitespaces; } - inline i32 getTabSize() const { return m_tabSize; } + void setShowCursor(bool value) { m_showCursor = value; } + void setShowLineNumbers(bool value) { m_showLineNumbers = value; } + void setShowWhitespaces(bool value) { m_showWhitespaces = value; } + bool isShowingWhitespaces() const { return m_showWhitespaces; } + i32 getTabSize() const { return m_tabSize; } ImVec2 &getCharAdvance() { return m_charAdvance; } void clearGotoBoxes() { m_errorGotoBoxes.clear(); } void clearCursorBoxes() { m_cursorBoxes.clear(); } @@ -461,7 +457,7 @@ namespace hex::ui { void setLongestLineLength(u64 line) { m_longestLineLength = line; } u64 getLongestLineLength() const { return m_longestLineLength; } void setTopMarginChanged(i32 newMargin); - void setFocusAtCoords(const Coordinates &coords, bool ensureVisible = false); + void setFocusAtCoords(const Coordinates &coords, bool scrollToCursor = false); void clearErrorMarkers(); void clearActionables(); private: @@ -518,16 +514,16 @@ namespace hex::ui { std::vector getTextLines() const; std::string getSelectedText(); std::string getLineText(i32 line); - inline void setTextChanged(bool value) { m_textChanged = value; } - inline bool isTextChanged() { return m_textChanged; } - inline void setReadOnly(bool value) { m_readOnly = value; } - inline void setHandleMouseInputs(bool value) { m_handleMouseInputs = value; } - inline bool isHandleMouseInputsEnabled() const { return m_handleKeyboardInputs; } - inline void setHandleKeyboardInputs(bool value) { m_handleKeyboardInputs = value; } - inline bool isHandleKeyboardInputsEnabled() const { return m_handleKeyboardInputs; } + void setTextChanged(bool value) { m_textChanged = value; } + bool isTextChanged() { return m_textChanged; } + void setReadOnly(bool value) { m_readOnly = value; } + void setHandleMouseInputs(bool value) { m_handleMouseInputs = value; } + bool isHandleMouseInputsEnabled() const { return m_handleMouseInputs; } + void setHandleKeyboardInputs(bool value) { m_handleKeyboardInputs = value; } + bool isHandleKeyboardInputsEnabled() const { return m_handleKeyboardInputs; } private: - std::string getText(const Range &selection); - void deleteRange(const Range &selection); + std::string getText(const Range &from); + void deleteRange(const Range &rangeToDelete); i32 insertTextAt(Coordinates &where, const std::string &value); void removeLine(i32 start, i32 end); void removeLine(i32 index); @@ -575,10 +571,10 @@ namespace hex::ui { i32 getTotalLines() const { return (i32) m_lines.size(); } FindReplaceHandler *getFindReplaceHandler() { return &m_findReplaceHandler; } void setSourceCodeEditor(TextEditor *editor) { m_sourceCodeEditor = editor; } - inline void clearBreakpointsChanged() { m_breakPointsChanged = false; } - inline bool isBreakpointsChanged() { return m_breakPointsChanged; } - inline void setImGuiChildIgnored(bool value) { m_ignoreImGuiChild = value; } - inline bool isImGuiChildIgnored() const { return m_ignoreImGuiChild; } + void clearBreakpointsChanged() { m_breakPointsChanged = false; } + bool isBreakpointsChanged() { return m_breakPointsChanged; } + void setImGuiChildIgnored(bool value) { m_ignoreImGuiChild = value; } + bool isImGuiChildIgnored() const { return m_ignoreImGuiChild; } bool raiseContextMenu() { return m_raiseContextMenu; } void clearRaiseContextMenu() { m_raiseContextMenu = false; } TextEditor *getSourceCodeEditor(); @@ -610,7 +606,7 @@ namespace hex::ui { private: float m_lineSpacing = 1.0F; Lines m_lines; - EditorState m_state = {}; + EditorState m_state; UndoBuffer m_undoBuffer; i32 m_undoIndex = 0; bool m_scrollToBottom = false; @@ -638,18 +634,18 @@ namespace hex::ui { bool m_ignoreImGuiChild = false; bool m_showWhitespaces = true; - MatchedBracket m_matchedBracket = {}; + MatchedBracket m_matchedBracket; Palette m_palette = {}; - LanguageDefinition m_languageDefinition = {}; + LanguageDefinition m_languageDefinition; RegexList m_regexList; bool m_updateFlags = true; - Breakpoints m_breakpoints = {}; - ErrorMarkers m_errorMarkers = {}; - ErrorHoverBoxes m_errorHoverBoxes = {}; - ErrorGotoBoxes m_errorGotoBoxes = {}; - CursorBoxes m_cursorBoxes = {}; - ImVec2 m_charAdvance = {}; - Range m_interactiveSelection = {}; + Breakpoints m_breakpoints; + ErrorMarkers m_errorMarkers; + ErrorHoverBoxes m_errorHoverBoxes; + ErrorGotoBoxes m_errorGotoBoxes; + CursorBoxes m_cursorBoxes; + ImVec2 m_charAdvance; + Range m_interactiveSelection; u64 m_startTime = 0; std::vector m_defines; TextEditor *m_sourceCodeEditor = nullptr; @@ -663,7 +659,7 @@ namespace hex::ui { bool m_showCursor = true; bool m_showLineNumbers = true; bool m_raiseContextMenu = false; - Coordinates m_focusAtCoords = {}; + Coordinates m_focusAtCoords; bool m_updateFocus = false; std::vector m_clickableText; diff --git a/plugins/ui/source/ui/markdown.cpp b/plugins/ui/source/ui/markdown.cpp index 19020e8d3..c00a2b403 100644 --- a/plugins/ui/source/ui/markdown.cpp +++ b/plugins/ui/source/ui/markdown.cpp @@ -250,7 +250,7 @@ namespace hex::ui { return wolv::container::Lazy([data = std::move(data)]() -> ImGuiExt::Texture { if (data.empty()) - return ImGuiExt::Texture(); + return {}; auto texture = ImGuiExt::Texture::fromImage(data.data(), data.size(), ImGuiExt::Texture::Filter::Linear); if (!texture.isValid()) { diff --git a/plugins/ui/source/ui/pattern_drawer.cpp b/plugins/ui/source/ui/pattern_drawer.cpp index 75b3ab3cf..b6eca778c 100644 --- a/plugins/ui/source/ui/pattern_drawer.cpp +++ b/plugins/ui/source/ui/pattern_drawer.cpp @@ -1,3 +1,4 @@ +#include #include #include @@ -320,10 +321,9 @@ namespace hex::ui { m_filteredPatterns.push_back(pattern); } else { auto patternValue = pattern->getValue(); - if (!m_filter->inverted && (patternValue <=> *m_filter->value) == m_filter->operation) { - if (!m_filter->typeMatch || (m_filter->value->index() == patternValue.index())) - m_filteredPatterns.push_back(pattern); - } else if (m_filter->inverted && (patternValue <=> *m_filter->value) != m_filter->operation) { + auto operation = patternValue <=> *m_filter->value; + bool isOperationOk = operation == m_filter->operation; + if ((!m_filter->inverted && isOperationOk) || (m_filter->inverted && !isOperationOk)) { if (!m_filter->typeMatch || (m_filter->value->index() == patternValue.index())) m_filteredPatterns.push_back(pattern); } @@ -480,7 +480,7 @@ namespace hex::ui { pattern = pattern->getParent(); } - std::reverse(result.begin(), result.end()); + std::ranges::reverse(result); return result; } @@ -1221,7 +1221,7 @@ namespace hex::ui { if (!m_favoritesUpdateTask.isRunning()) { sortedPatterns = patterns; - std::stable_sort(sortedPatterns.begin(), sortedPatterns.end(), [this, &sortSpecs](const std::shared_ptr &left, const std::shared_ptr &right) -> bool { + std::ranges::stable_sort(sortedPatterns, [this, &sortSpecs](const std::shared_ptr &left, const std::shared_ptr &right) -> bool { return this->sortPatterns(sortSpecs, left.get(), right.get()); }); @@ -1365,7 +1365,7 @@ namespace hex::ui { for (const auto &formatter : m_formatters) { const auto name = [&]{ 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; }(); diff --git a/plugins/ui/source/ui/text_editor/editor.cpp b/plugins/ui/source/ui/text_editor/editor.cpp index 4c1658f09..3d7f7e2ae 100644 --- a/plugins/ui/source/ui/text_editor/editor.cpp +++ b/plugins/ui/source/ui/text_editor/editor.cpp @@ -1,3 +1,4 @@ +#include #include #include #include @@ -21,11 +22,10 @@ namespace hex::ui { TextEditor::TextEditor() { m_startTime = ImGui::GetTime() * 1000; 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 result; @@ -83,7 +83,7 @@ namespace hex::ui { m_lines[0].m_lineMaxColumn = -1; m_lines[0].m_lineMaxColumn = m_lines[0].maxColumn(); } else { - m_lines.push_back(Line(text)); + m_lines.emplace_back(text); auto &line = m_lines.back(); line.m_lineMaxColumn = -1; line.m_lineMaxColumn = line.maxColumn(); @@ -366,7 +366,7 @@ namespace hex::ui { u.m_addedRange.m_start = coord; if (m_lines.empty()) - m_lines.push_back(Line()); + m_lines.emplace_back(); if (character == '\n') { insertLine(coord.m_line + 1); @@ -426,9 +426,9 @@ namespace hex::ui { } u.m_addedRange.m_end = setCoordinates(m_state.m_cursorPosition); } else { - std::string buf = ""; + std::string buf; imTextCharToUtf8(buf, character); - if (buf.size() > 0) { + if (!buf.empty()) { auto &line = m_lines[coord.m_line]; auto charIndex = lineCoordinatesToIndex(coord); @@ -679,7 +679,7 @@ namespace hex::ui { if (!isEmpty()) { std::string str; 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()); } } @@ -744,7 +744,7 @@ namespace hex::ui { const char *clipText = ImGui::GetClipboardText(); if (clipText != nullptr) { 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]() { this->doPaste(clipText); }, [] {}); @@ -858,8 +858,8 @@ namespace hex::ui { } void TextEditor::UndoAction::redo(TextEditor *editor) { - for (i32 i = 0; i < (i32) m_records.size(); i++) - m_records.at(i).redo(editor); + for (auto & m_record : m_records) + m_record.redo(editor); } } \ No newline at end of file diff --git a/plugins/ui/source/ui/text_editor/highlighter.cpp b/plugins/ui/source/ui/text_editor/highlighter.cpp index f09711a09..4f2e9e5ee 100644 --- a/plugins/ui/source/ui/text_editor/highlighter.cpp +++ b/plugins/ui/source/ui/text_editor/highlighter.cpp @@ -1,7 +1,7 @@ +#include #include #include #include -#include namespace hex::ui { extern TextEditor::Palette s_paletteBase; @@ -25,7 +25,7 @@ namespace hex::ui { auto &lineTokens = m_lines[line].m_colors; if (lineTokens.size() != tokens.size()) { lineTokens.resize(tokens.size()); - std::fill(lineTokens.begin(), lineTokens.end(), 0x00); + std::ranges::fill(lineTokens, 0x00); } bool needsUpdate = false; 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 ? if (!m_languageDefinition.m_caseSensitive) - std::transform(id.begin(), id.end(), id.begin(), ::toupper); - else if (m_languageDefinition.m_keywords.count(id) != 0) + std::ranges::transform(id, id.begin(), ::toupper); + else if (m_languageDefinition.m_keywords.contains(id)) 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; else if (id == "$") token_color = PaletteIndex::GlobalVariable; @@ -105,7 +105,7 @@ namespace hex::ui { } else { if ((token_color == PaletteIndex::Identifier || flags.m_bits.preprocessor) && !flags.m_bits.deactivated && !(flags.m_value & inComment)) { 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_begin -= 1; token_length = token_end - token_begin; @@ -125,7 +125,7 @@ namespace hex::ui { token_color = PaletteIndex::PreprocessorDeactivated; token_begin -= 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_begin -= 1; token_offset -= 1; @@ -148,12 +148,12 @@ namespace hex::ui { if (token_offset + token_length >= line.m_colors.size()) { auto colors = line.m_colors; line.m_colors.resize(token_offset + token_length, static_cast(PaletteIndex::Default)); - std::copy(colors.begin(), colors.end(), line.m_colors.begin()); + std::ranges::copy(colors, line.m_colors.begin()); } try { line.m_colors.replace(token_offset, token_length, token_length, static_cast(token_color)); } catch (const std::exception &e) { - std::cerr << "Error replacing color: " << e.what() << std::endl; + fmt::print(stderr, "Error replacing color: {}\n", e.what()); return; } } @@ -184,7 +184,7 @@ namespace hex::ui { std::vector ifDefs; ifDefs.push_back(true); - m_defines.push_back("__IMHEX__"); + m_defines.emplace_back("__IMHEX__"); for (currentLine = 0; currentLine < endLine; currentLine++) { auto &line = m_lines[currentLine]; auto lineLength = line.size(); @@ -298,10 +298,10 @@ namespace hex::ui { auto definesBegin = m_defines.begin(); auto definesEnd = m_defines.end(); 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); } else if (directive == "undef") { - if (identifier.size() > 0 && !withinNotDef) + if (!identifier.empty() && !withinNotDef) m_defines.erase(std::remove(definesBegin, definesEnd, identifier), definesEnd); } else if (directive == "ifdef") { if (!withinNotDef) { @@ -407,7 +407,7 @@ namespace hex::ui { m_regexList.clear(); 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(); } @@ -649,16 +649,16 @@ namespace hex::ui { 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.push_back(std::make_pair("L?\\\"(\\\\.|[^\\\"])*\\\"", PaletteIndex::StringLiteral)); - langDef.m_tokenRegexStrings.push_back(std::make_pair("\\'\\\\?[^\\']\\'", 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.push_back(std::make_pair("[+-]?[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.push_back(std::make_pair("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.push_back(std::make_pair("[\\!\\%\\^\\&\\*\\-\\+\\=\\~\\|\\<\\>\\?\\/]", PaletteIndex::Operator)); - langDef.m_tokenRegexStrings.push_back(std::make_pair("[\\[\\]\\{\\}\\(\\)\\;\\,\\.]", PaletteIndex::Separator)); + langDef.m_tokenRegexStrings.emplace_back("[ \\t]*#[ \\t]*[a-zA-Z_]+", PaletteIndex::Directive); + langDef.m_tokenRegexStrings.emplace_back(R"(L?\"(\\.|[^\"])*\")", PaletteIndex::StringLiteral); + langDef.m_tokenRegexStrings.emplace_back(R"(\'\\?[^\']\')", PaletteIndex::CharLiteral); + langDef.m_tokenRegexStrings.emplace_back("[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)([eE][+-]?[0-9]+)?[fF]?", PaletteIndex::NumericLiteral); + langDef.m_tokenRegexStrings.emplace_back("[+-]?[0-9]+[Uu]?[lL]?[lL]?", PaletteIndex::NumericLiteral); + langDef.m_tokenRegexStrings.emplace_back("0[0-7]+[Uu]?[lL]?[lL]?", PaletteIndex::NumericLiteral); + langDef.m_tokenRegexStrings.emplace_back("0[xX][0-9a-fA-F]+[uU]?[lL]?[lL]?", PaletteIndex::NumericLiteral); + langDef.m_tokenRegexStrings.emplace_back("[a-zA-Z_][a-zA-Z0-9_]*", PaletteIndex::Identifier); + langDef.m_tokenRegexStrings.emplace_back(R"([\!\%\^\&\*\-\+\=\~\|\<\>\?\/])", PaletteIndex::Operator); + langDef.m_tokenRegexStrings.emplace_back(R"([\[\]\{\}\(\)\;\,\.])", PaletteIndex::Separator); langDef.m_commentStart = "/*"; langDef.m_commentEnd = "*/"; langDef.m_singleLineComment = "//"; @@ -700,16 +700,16 @@ namespace hex::ui { 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.push_back(std::make_pair("L?\\\"(\\\\.|[^\\\"])*\\\"", PaletteIndex::StringLiteral)); - langDef.m_tokenRegexStrings.push_back(std::make_pair("\\'\\\\?[^\\']\\'", 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.push_back(std::make_pair("[+-]?[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.push_back(std::make_pair("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.push_back(std::make_pair("[\\!\\%\\^\\&\\*\\-\\+\\=\\~\\|\\<\\>\\?\\/]", PaletteIndex::Operator)); - langDef.m_tokenRegexStrings.push_back(std::make_pair("[\\[\\]\\{\\}\\(\\)\\;\\,\\.]", PaletteIndex::Separator)); + langDef.m_tokenRegexStrings.emplace_back("[ \\t]*#[ \\t]*[a-zA-Z_]+", PaletteIndex::Directive); + langDef.m_tokenRegexStrings.emplace_back(R"(L?\"(\\.|[^\"])*\")", PaletteIndex::StringLiteral); + langDef.m_tokenRegexStrings.emplace_back(R"(\'\\?[^\']\')", PaletteIndex::CharLiteral); + langDef.m_tokenRegexStrings.emplace_back("[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)([eE][+-]?[0-9]+)?[fF]?",PaletteIndex::NumericLiteral); + langDef.m_tokenRegexStrings.emplace_back("[+-]?[0-9]+[Uu]?[lL]?[lL]?", PaletteIndex::NumericLiteral); + langDef.m_tokenRegexStrings.emplace_back("0[0-7]+[Uu]?[lL]?[lL]?", PaletteIndex::NumericLiteral); + langDef.m_tokenRegexStrings.emplace_back("0[xX][0-9a-fA-F]+[uU]?[lL]?[lL]?", PaletteIndex::NumericLiteral); + langDef.m_tokenRegexStrings.emplace_back("[a-zA-Z_][a-zA-Z0-9_]*", PaletteIndex::Identifier); + langDef.m_tokenRegexStrings.emplace_back(R"([\!\%\^\&\*\-\+\=\~\|\<\>\?\/])", PaletteIndex::Operator); + langDef.m_tokenRegexStrings.emplace_back(R"([\[\]\{\}\(\)\;\,\.])", PaletteIndex::Separator); langDef.m_commentStart = "/*"; langDef.m_commentEnd = "*/"; langDef.m_singleLineComment = "//"; @@ -844,16 +844,16 @@ namespace hex::ui { 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.push_back(std::make_pair("L?\\\"(\\\\.|[^\\\"])*\\\"", PaletteIndex::StringLiteral)); - langDef.m_tokenRegexStrings.push_back(std::make_pair("\\'\\\\?[^\\']\\'", 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.push_back(std::make_pair("[+-]?[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.push_back(std::make_pair("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.push_back(std::make_pair("[\\!\\%\\^\\&\\*\\-\\+\\=\\~\\|\\<\\>\\?\\/]", PaletteIndex::Operator)); - langDef.m_tokenRegexStrings.push_back(std::make_pair("[\\[\\]\\{\\}\\(\\)\\;\\,\\.]", PaletteIndex::Separator)); + langDef.m_tokenRegexStrings.emplace_back("[ \\t]*#[ \\t]*[a-zA-Z_]+", PaletteIndex::Directive); + langDef.m_tokenRegexStrings.emplace_back(R"(L?\"(\\.|[^\"])*\")", PaletteIndex::StringLiteral); + langDef.m_tokenRegexStrings.emplace_back(R"(\'\\?[^\']\')", PaletteIndex::CharLiteral); + langDef.m_tokenRegexStrings.emplace_back("[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)([eE][+-]?[0-9]+)?[fF]?",PaletteIndex::NumericLiteral); + langDef.m_tokenRegexStrings.emplace_back("[+-]?[0-9]+[Uu]?[lL]?[lL]?", PaletteIndex::NumericLiteral); + langDef.m_tokenRegexStrings.emplace_back("0[0-7]+[Uu]?[lL]?[lL]?", PaletteIndex::NumericLiteral); + langDef.m_tokenRegexStrings.emplace_back("0[xX][0-9a-fA-F]+[uU]?[lL]?[lL]?", PaletteIndex::NumericLiteral); + langDef.m_tokenRegexStrings.emplace_back("[a-zA-Z_][a-zA-Z0-9_]*", PaletteIndex::Identifier); + langDef.m_tokenRegexStrings.emplace_back(R"([\!\%\^\&\*\-\+\=\~\|\<\>\?\/])", PaletteIndex::Operator); + langDef.m_tokenRegexStrings.emplace_back(R"([\[\]\{\}\(\)\;\,\.])", PaletteIndex::Separator); langDef.m_commentStart = "/*"; langDef.m_commentEnd = "*/"; @@ -897,16 +897,16 @@ namespace hex::ui { 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.push_back(std::make_pair("L?\\\"(\\\\.|[^\\\"])*\\\"", PaletteIndex::StringLiteral)); - langDef.m_tokenRegexStrings.push_back(std::make_pair("\\'\\\\?[^\\']\\'", 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.push_back(std::make_pair("[+-]?[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.push_back(std::make_pair("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.push_back(std::make_pair("[\\!\\%\\^\\&\\*\\-\\+\\=\\~\\|\\<\\>\\?\\/]", PaletteIndex::Operator)); - langDef.m_tokenRegexStrings.push_back(std::make_pair("[\\[\\]\\{\\}\\(\\)\\;\\,\\.]", PaletteIndex::Separator)); + langDef.m_tokenRegexStrings.emplace_back("[ \\t]*#[ \\t]*[a-zA-Z_]+", PaletteIndex::Directive); + langDef.m_tokenRegexStrings.emplace_back(R"(L?\"(\\.|[^\"])*\")", PaletteIndex::StringLiteral); + langDef.m_tokenRegexStrings.emplace_back(R"(\'\\?[^\']\')", PaletteIndex::CharLiteral); + langDef.m_tokenRegexStrings.emplace_back("[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)([eE][+-]?[0-9]+)?[fF]?",PaletteIndex::NumericLiteral); + langDef.m_tokenRegexStrings.emplace_back("[+-]?[0-9]+[Uu]?[lL]?[lL]?", PaletteIndex::NumericLiteral); + langDef.m_tokenRegexStrings.emplace_back("0[0-7]+[Uu]?[lL]?[lL]?", PaletteIndex::NumericLiteral); + langDef.m_tokenRegexStrings.emplace_back("0[xX][0-9a-fA-F]+[uU]?[lL]?[lL]?", PaletteIndex::NumericLiteral); + langDef.m_tokenRegexStrings.emplace_back("[a-zA-Z_][a-zA-Z0-9_]*", PaletteIndex::Identifier); + langDef.m_tokenRegexStrings.emplace_back(R"([\!\%\^\&\*\-\+\=\~\|\<\>\?\/])", PaletteIndex::Operator); + langDef.m_tokenRegexStrings.emplace_back(R"([\[\]\{\}\(\)\;\,\.])", PaletteIndex::Separator); langDef.m_commentStart = "/*"; langDef.m_commentEnd = "*/"; @@ -961,16 +961,16 @@ namespace hex::ui { 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.push_back(std::make_pair("L?\\\"(\\\\.|[^\\\"])*\\\"", PaletteIndex::StringLiteral)); - langDef.m_tokenRegexStrings.push_back(std::make_pair("\\'\\\\?[^\\']\\'", 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.push_back(std::make_pair("[+-]?[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.push_back(std::make_pair("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.push_back(std::make_pair("[\\!\\%\\^\\&\\*\\-\\+\\=\\~\\|\\<\\>\\?\\/]", PaletteIndex::Operator)); - langDef.m_tokenRegexStrings.push_back(std::make_pair("[\\[\\]\\{\\}\\(\\)\\;\\,\\.]", PaletteIndex::Separator)); + langDef.m_tokenRegexStrings.emplace_back(R"([ \t]*#[ \t]*[a-zA-Z_]+)", PaletteIndex::Directive); + langDef.m_tokenRegexStrings.emplace_back(R"(L?\"(\\.|[^\"])*\")", PaletteIndex::StringLiteral); + langDef.m_tokenRegexStrings.emplace_back(R"(\'\\?[^\']\')", PaletteIndex::CharLiteral); + langDef.m_tokenRegexStrings.emplace_back("[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)([eE][+-]?[0-9]+)?[fF]?", PaletteIndex::NumericLiteral); + langDef.m_tokenRegexStrings.emplace_back("[+-]?[0-9]+[Uu]?[lL]?[lL]?", PaletteIndex::NumericLiteral); + langDef.m_tokenRegexStrings.emplace_back("0[0-7]+[Uu]?[lL]?[lL]?", PaletteIndex::NumericLiteral); + langDef.m_tokenRegexStrings.emplace_back("0[xX][0-9a-fA-F]+[uU]?[lL]?[lL]?", PaletteIndex::NumericLiteral); + langDef.m_tokenRegexStrings.emplace_back("[a-zA-Z_][a-zA-Z0-9_]*", PaletteIndex::Identifier); + langDef.m_tokenRegexStrings.emplace_back(R"([\!\%\^\&\*\-\+\=\~\|\<\>\?\/])", PaletteIndex::Operator); + langDef.m_tokenRegexStrings.emplace_back(R"([\[\]\{\}\(\)\;\,\.])", PaletteIndex::Separator); langDef.m_commentStart = "--[["; langDef.m_commentEnd = "]]"; @@ -1001,10 +1001,11 @@ namespace hex::ui { } // handle escape character for " - if (*p == '\\' && p + 1 < in_end && p[1] == '\\') - p++; - else if (*p == '\\' && p + 1 < in_end && p[1] == '"') - p++; + if (*p == '\\' && p + 1 < in_end) { + if (p[1] == '\\' || p[1] == '"') { + p++; + } + } p++; } @@ -1169,9 +1170,9 @@ namespace hex::ui { out_begin = in_begin; out_end = in_begin + 1; return true; + default: + return false; } - - return false; } bool tokenizeCStyleSeparator(strConstIter in_begin, strConstIter in_end, strConstIter &out_begin, strConstIter &out_end) { diff --git a/plugins/ui/source/ui/text_editor/navigate.cpp b/plugins/ui/source/ui/text_editor/navigate.cpp index fe5634f5a..5cde3919d 100644 --- a/plugins/ui/source/ui/text_editor/navigate.cpp +++ b/plugins/ui/source/ui/text_editor/navigate.cpp @@ -4,7 +4,7 @@ namespace hex::ui { - bool isWordChar(char c) { + static bool isWordChar(char c) { auto asUChar = static_cast(c); return std::isalnum(asUChar) || c == '_' || asUChar > 0x7F; } @@ -237,13 +237,13 @@ namespace hex::ui { return; i32 home; if (!prefix.empty()) { - auto idx = prefix.find_first_not_of(" "); + auto idx = prefix.find_first_not_of(' '); if (idx == std::string::npos) { - auto postIdx = postfix.find_first_of(" "); + auto postIdx = postfix.find_first_of(' '); if (postIdx == std::string::npos || postIdx == 0) home = 0; else { - postIdx = postfix.find_first_not_of(" "); + postIdx = postfix.find_first_not_of(' '); if (postIdx == std::string::npos) home = this->lineMaxColumn(oldPos.m_line); else if (postIdx == 0) @@ -254,11 +254,11 @@ namespace hex::ui { } else home = idx; } else { - auto postIdx = postfix.find_first_of(" "); + auto postIdx = postfix.find_first_of(' '); if (postIdx == std::string::npos) home = 0; else { - postIdx = postfix.find_first_not_of(" "); + postIdx = postfix.find_first_not_of(' '); if (postIdx == std::string::npos) home = lineMaxColumn(oldPos.m_line); else @@ -360,9 +360,7 @@ namespace hex::ui { if (std::abs(m_line) > (i32) maxLine) return false; auto maxColumn = editor->lineMaxColumn(m_line); - if (std::abs(m_column) > maxColumn) - return false; - return true; + return std::abs(m_column) <= maxColumn; } TextEditor::Coordinates TextEditor::Coordinates::sanitize(TextEditor *editor) { @@ -387,8 +385,8 @@ namespace hex::ui { TextEditor::Coordinates TextEditor::setCoordinates(i32 line, i32 column) { if (isEmpty()) - return Coordinates(0, 0); - return Coordinates(this, line, column); + return {0, 0}; + return {this, line, column}; } TextEditor::Coordinates TextEditor::setCoordinates(const Coordinates &value) { @@ -400,11 +398,11 @@ namespace hex::ui { auto start = setCoordinates(value.m_start); auto end = setCoordinates(value.m_end); if (start == Invalid || end == Invalid) - return Range(Invalid, Invalid); + return {Invalid, Invalid}; if (start > end) { std::swap(start, end); } - return Range(start, end); + return {start, end}; } void TextEditor::advance(Coordinates &coordinates) const { diff --git a/plugins/ui/source/ui/text_editor/render.cpp b/plugins/ui/source/ui/text_editor/render.cpp index 996df8160..8a003324e 100644 --- a/plugins/ui/source/ui/text_editor/render.cpp +++ b/plugins/ui/source/ui/text_editor/render.cpp @@ -453,7 +453,7 @@ namespace hex::ui { } } // 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); drawList->AddRectFilled(ImVec2(position.x, lineStartScreenPos.y), end, m_palette[(i32) PaletteIndex::Breakpoint]); @@ -501,7 +501,7 @@ namespace hex::ui { std::string errorLineColumn; bool found = false; for (auto text: m_clickableText) { - if (lineText.find(text) == 0) { + if (lineText.starts_with(text)) { errorLineColumn = lineText.substr(text.size()); if (!errorLineColumn.empty()) { found = true; @@ -511,7 +511,7 @@ namespace hex::ui { } if (found) { 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); if (!errorLine.empty()) 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]; if (box.trigger()) box.callback(); } - if (m_errorGotoBoxes.find(gotoKey) != m_errorGotoBoxes.end()) { + if (m_errorGotoBoxes.contains(gotoKey)) { auto box = m_errorGotoBoxes[gotoKey]; if (box.trigger()) box.callback(); } @@ -568,7 +568,7 @@ namespace hex::ui { ErrorHoverBox box = ErrorHoverBox(ImRect({begin, end}), key, errorMessage.c_str()); m_errorHoverBoxes[key] = box; } - if (m_errorHoverBoxes.find(key) != m_errorHoverBoxes.end()) { + if (m_errorHoverBoxes.contains(key)) { auto box = m_errorHoverBoxes[key]; if (box.trigger()) box.callback(); } @@ -626,7 +626,7 @@ namespace hex::ui { ImVec2 TextEditor::calculateCharAdvance() const { /* Compute mCharAdvance regarding scaled font size (Ctrl + mouse wheel)*/ 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) { diff --git a/plugins/ui/source/ui/text_editor/support.cpp b/plugins/ui/source/ui/text_editor/support.cpp index 7f5f188c3..d0465ac7a 100644 --- a/plugins/ui/source/ui/text_editor/support.cpp +++ b/plugins/ui/source/ui/text_editor/support.cpp @@ -1,3 +1,4 @@ +#include #include #include #include @@ -37,11 +38,11 @@ namespace hex::ui { } 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 { - 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 { @@ -52,13 +53,13 @@ namespace hex::ui { } 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() { if (isSingleLine()) - return Coordinates(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 - m_start.m_column}; + return {m_start.m_column, m_end.m_column}; } bool Range::isSingleLine() { @@ -209,14 +210,7 @@ namespace hex::ui { return iter; } - Line &Line::operator=(const Line &line) { - 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=(const Line &line) = default; Line &Line::operator=(Line &&line) noexcept { m_chars = std::move(line.m_chars); @@ -899,11 +893,11 @@ namespace hex::ui { std::string wordLower = m_findWord; if (!getMatchCase()) - std::transform(wordLower.begin(), wordLower.end(), wordLower.begin(), ::tolower); + std::ranges::transform(wordLower, wordLower.begin(), ::tolower); std::string textSrc = editor->getText(); if (!getMatchCase()) - std::transform(textSrc.begin(), textSrc.end(), textSrc.begin(), ::tolower); + std::ranges::transform(textSrc, textSrc.begin(), ::tolower); u64 textLoc; // TODO: use regexp find iterator in all cases @@ -1010,7 +1004,6 @@ namespace hex::ui { editor->m_state = saveState; editor->ensureCursorVisible(); - return; } diff --git a/plugins/ui/source/ui/text_editor/utf8.cpp b/plugins/ui/source/ui/text_editor/utf8.cpp index 5619c36a0..6888a8084 100644 --- a/plugins/ui/source/ui/text_editor/utf8.cpp +++ b/plugins/ui/source/ui/text_editor/utf8.cpp @@ -196,7 +196,7 @@ namespace hex::ui { auto result = getCharacterCoordinates(lineNo, count - increase); result = setCoordinates(result); if (result == Invalid) - return Coordinates(0, 0); + return {0, 0}; return result; } @@ -205,7 +205,7 @@ namespace hex::ui { return Invalid; 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 { @@ -218,7 +218,7 @@ namespace hex::ui { TextEditor::Coordinates TextEditor::getCharacterCoordinates(i32 lineIndex, i32 strIndex) { if (lineIndex < 0 || lineIndex >= (i32) m_lines.size()) - return Coordinates(0, 0); + return {0, 0}; auto &line = m_lines[lineIndex]; return setCoordinates(lineIndex, line.indexColumn(strIndex)); } @@ -233,7 +233,7 @@ namespace hex::ui { TextEditor::Coordinates TextEditor::stringIndexToCoordinates(i32 strIndex, const std::string &input) { if (strIndex < 0 || strIndex > (i32) input.size()) - return TextEditor::Coordinates(0, 0); + return {0, 0}; std::string str = input.substr(0, strIndex); auto line = std::count(str.begin(), str.end(), '\n'); auto index = str.find_last_of('\n'); diff --git a/tests/algorithms/source/crypto.cpp b/tests/algorithms/source/crypto.cpp index 55da31412..5e50b9aac 100644 --- a/tests/algorithms/source/crypto.cpp +++ b/tests/algorithms/source/crypto.cpp @@ -1,3 +1,4 @@ +#include #include #include #include @@ -6,12 +7,13 @@ #include #include #include -#include #include +using std::string; + struct EncodeChek { - std::vector vec; - std::string string; + std::vector vec; + std::string string; }; TEST_SEQUENCE("EncodeDecode16") { @@ -40,7 +42,7 @@ TEST_SEQUENCE("EncodeDecode16") { for (int i = 0; i < 1000; i++) { std::vector 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 decoded = hex::crypt::decode16(encoded); @@ -56,11 +58,11 @@ TEST_SEQUENCE("EncodeDecode16") { }; std::string vectorToString(std::vector in) { - return std::string(reinterpret_cast(in.data()), in.size()); + return { reinterpret_cast(in.data()), in.size() }; } std::vector stringToVector(std::string in) { - return std::vector(in.begin(), in.end()); + return { in.begin(), in.end() }; } TEST_SEQUENCE("EncodeDecode64") { @@ -90,7 +92,7 @@ TEST_SEQUENCE("EncodeDecode64") { for (int i = 0; i < 1000; i++) { std::vector 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 decoded = hex::crypt::decode64(stringToVector(encoded)); @@ -147,7 +149,7 @@ TEST_SEQUENCE("EncodeDecodeLEB128") { for (int i = 0; i < 1000; i++) { std::vector 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(original.data()); i128 s = *reinterpret_cast(original.data()); auto encodedS = hex::crypt::encodeSleb128(s); @@ -193,7 +195,7 @@ int checkCrcAgainstRandomData(Func func, int width) { std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution distribLen(0, 1024); - std::uniform_int_distribution distribPoly(0, (0b10ull << (width - 1)) - 1); + std::uniform_int_distribution distribPoly(0, (0b10ULL << (width - 1)) - 1); std::uniform_int_distribution distribData; for (int i = 0; i < 500; i++) { diff --git a/tests/helpers/source/common.cpp b/tests/helpers/source/common.cpp index 11c80afb5..64414940c 100644 --- a/tests/helpers/source/common.cpp +++ b/tests/helpers/source/common.cpp @@ -1,9 +1,9 @@ +#include #include #include #include -#include #include TEST_SEQUENCE("TestSucceeding") { @@ -21,7 +21,7 @@ TEST_SEQUENCE("TestProvider_read") { u8 buff[1024]; - std::fill(std::begin(buff), std::end(buff), 22); + std::ranges::fill(buff, 22); provider2->read(0, buff + 1, 4); TEST_ASSERT(buff[0] == 22); // should be unchanged TEST_ASSERT(buff[1] == 0xde); @@ -30,13 +30,13 @@ TEST_SEQUENCE("TestProvider_read") { TEST_ASSERT(buff[4] == 0xef); 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); TEST_ASSERT(buff[0] == 0x00); TEST_ASSERT(buff[1] == 0xff); 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); 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 }; - std::fill(std::begin(buff), std::end(buff), 22); + std::ranges::fill(buff, 22); provider2->writeRaw(1, data, 4); TEST_ASSERT(buff[0] == 22); // should be unchanged TEST_ASSERT(buff[1] == 0xde); @@ -59,19 +59,19 @@ TEST_SEQUENCE("TestProvider_write") { TEST_ASSERT(buff[4] == 0xef); 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); TEST_ASSERT(buff[0] == 0x00); TEST_ASSERT(buff[1] == 0xff); 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); TEST_ASSERT(buff[5] == 22); // should be unchanged TEST_ASSERT(buff[6] == 0xde); TEST_ASSERT(buff[7] == 0xad); - std::fill(std::begin(buff), std::end(buff), 22); + std::ranges::fill(buff, 22); provider2->writeRaw(7, data, 2); TEST_ASSERT(std::count(std::begin(buff), std::end(buff), 22) == std::size(buff)); // buff should be unchanged