diff --git a/include/helpers/encoding_file.hpp b/include/helpers/encoding_file.hpp index 8bd4b5274..2bfb23cef 100644 --- a/include/helpers/encoding_file.hpp +++ b/include/helpers/encoding_file.hpp @@ -3,6 +3,7 @@ #include #include +#include #include namespace hex { @@ -22,10 +23,10 @@ namespace hex { }; EncodingFile() = default; - EncodingFile(Type type, std::string_view path); + EncodingFile(Type type, const std::string &path); - std::pair getEncodingFor(const std::vector &buffer) const; - size_t getLongestSequence() const { return this->m_longestSequence; } + [[nodiscard]] std::pair getEncodingFor(const std::vector &buffer) const; + [[nodiscard]] size_t getLongestSequence() const { return this->m_longestSequence; } private: void parseThingyFile(std::ifstream &content); diff --git a/include/helpers/loader_script_handler.hpp b/include/helpers/loader_script_handler.hpp index 3549bf9e4..8633e9b7f 100644 --- a/include/helpers/loader_script_handler.hpp +++ b/include/helpers/loader_script_handler.hpp @@ -14,9 +14,9 @@ namespace hex { public: LoaderScript() = delete; - static bool processFile(std::string_view scriptPath); + static bool processFile(const std::string &scriptPath); - static void setFilePath(std::string_view filePath) { LoaderScript::s_filePath = filePath; } + static void setFilePath(const std::string &filePath) { LoaderScript::s_filePath = filePath; } static void setDataProvider(prv::Provider* provider) { LoaderScript::s_dataProvider = provider; } private: static inline std::string s_filePath; diff --git a/include/helpers/plugin_manager.hpp b/include/helpers/plugin_manager.hpp index b04c449c8..62f3c3e71 100644 --- a/include/helpers/plugin_manager.hpp +++ b/include/helpers/plugin_manager.hpp @@ -15,15 +15,15 @@ namespace hex { class Plugin { public: - Plugin(std::string_view path); + Plugin(const std::string &path); Plugin(const Plugin&) = delete; Plugin(Plugin &&other) noexcept; ~Plugin(); void initializePlugin() const; - std::string getPluginName() const; - std::string getPluginAuthor() const; - std::string getPluginDescription() const; + [[nodiscard]] std::string getPluginName() const; + [[nodiscard]] std::string getPluginAuthor() const; + [[nodiscard]] std::string getPluginDescription() const; void setImGuiContext(ImGuiContext *ctx) const; @@ -43,7 +43,7 @@ namespace hex { SetImGuiContextFunc m_setImGuiContextFunction = nullptr; template - auto getPluginFunction(std::string_view pluginName, std::string_view symbol) { + auto getPluginFunction(const std::string &pluginName, const std::string &symbol) { auto symbolName = hex::format(symbol.data(), pluginName.length(), pluginName.data()); return reinterpret_cast(dlsym(this->m_handle, symbolName.c_str())); }; @@ -53,7 +53,7 @@ namespace hex { public: PluginManager() = delete; - static bool load(std::string_view pluginFolder); + static bool load(const std::string &pluginFolder); static void unload(); static void reload(); diff --git a/include/helpers/project_file_handler.hpp b/include/helpers/project_file_handler.hpp index b4939784a..9be4c7c84 100644 --- a/include/helpers/project_file_handler.hpp +++ b/include/helpers/project_file_handler.hpp @@ -16,8 +16,8 @@ namespace hex { public: ProjectFile() = delete; - static bool load(std::string_view filePath); - static bool store(std::string_view filePath = ""); + static bool load(const std::string &filePath); + static bool store(std::string filePath = ""); [[nodiscard]] static bool hasUnsavedChanges() { return ProjectFile::s_hasUnsavedChanged; @@ -32,7 +32,7 @@ namespace hex { EventManager::post(std::filesystem::path(getFilePath()).filename().string()); } - [[nodiscard]] static std::string getProjectFilePath() { + [[nodiscard]] static const std::string& getProjectFilePath() { return ProjectFile::s_currProjectFilePath; } @@ -41,22 +41,22 @@ namespace hex { } - [[nodiscard]] static std::string getFilePath() { + [[nodiscard]] static const std::string& getFilePath() { return ProjectFile::s_filePath; } - static void setFilePath(std::string_view filePath) { + static void setFilePath(const std::string &filePath) { ProjectFile::s_filePath = filePath; EventManager::post(std::filesystem::path(filePath).filename().string()); } - [[nodiscard]] static std::string getPattern() { + [[nodiscard]] static const std::string& getPattern() { return ProjectFile::s_pattern; } - static void setPattern(std::string_view pattern) { + static void setPattern(const std::string &pattern) { markDirty(); ProjectFile::s_pattern = pattern; } @@ -82,11 +82,11 @@ namespace hex { } - [[nodiscard]] static const std::string_view getDataProcessorContent() { + [[nodiscard]] static const std::string& getDataProcessorContent() { return ProjectFile::s_dataProcessorContent; } - static void setDataProcessorContent(std::string_view json) { + static void setDataProcessorContent(const std::string &json) { markDirty(); ProjectFile::s_dataProcessorContent = json; } diff --git a/include/init/splash_window.hpp b/include/init/splash_window.hpp index 0d026cf8b..e360bb4d1 100644 --- a/include/init/splash_window.hpp +++ b/include/init/splash_window.hpp @@ -10,6 +10,8 @@ struct GLFWwindow; namespace hex::init { + using TaskFunction = std::function; + class WindowSplash { public: WindowSplash(int &argc, char **&argv); @@ -17,7 +19,7 @@ namespace hex::init { bool loop(); - void addStartupTask(std::string_view taskName, const std::function &task) { + void addStartupTask(const std::string &taskName, const TaskFunction &task) { this->m_tasks.emplace_back(taskName, task); } @@ -35,7 +37,7 @@ namespace hex::init { std::future processTasksAsync(); - std::vector>> m_tasks; + std::vector> m_tasks; }; } \ No newline at end of file diff --git a/include/providers/file_provider.hpp b/include/providers/file_provider.hpp index a50e55ebe..76c64b48c 100644 --- a/include/providers/file_provider.hpp +++ b/include/providers/file_provider.hpp @@ -18,7 +18,7 @@ namespace hex::prv { class FileProvider : public Provider { public: - explicit FileProvider(std::string_view path); + explicit FileProvider(std::string path); ~FileProvider() override; bool isAvailable() override; @@ -42,20 +42,20 @@ namespace hex::prv { private: #if defined(OS_WINDOWS) - HANDLE m_file; - HANDLE m_mapping; + HANDLE m_file = INVALID_HANDLE_VALUE; + HANDLE m_mapping = INVALID_HANDLE_VALUE; #else - int m_file; + int m_file = -1; #endif std::string m_path; - void *m_mappedFile; - size_t m_fileSize; + void *m_mappedFile = nullptr; + size_t m_fileSize = 0; bool m_fileStatsValid = false; struct stat m_fileStats = { 0 }; - bool m_readable, m_writable; + bool m_readable = false, m_writable = false; void open(); void close(); diff --git a/include/views/view_command_palette.hpp b/include/views/view_command_palette.hpp index 493f47507..1d4d1affe 100644 --- a/include/views/view_command_palette.hpp +++ b/include/views/view_command_palette.hpp @@ -55,7 +55,7 @@ namespace hex { this->m_focusInputTextBox = true; } - std::vector getCommandResults(std::string_view command); + std::vector getCommandResults(const std::string &command); }; } \ No newline at end of file diff --git a/include/views/view_data_processor.hpp b/include/views/view_data_processor.hpp index caadce176..3304035ca 100644 --- a/include/views/view_data_processor.hpp +++ b/include/views/view_data_processor.hpp @@ -39,7 +39,7 @@ namespace hex { void processNodes(); std::string saveNodes(); - void loadNodes(std::string_view data); + void loadNodes(const std::string &data); }; } \ No newline at end of file diff --git a/include/views/view_hexeditor.hpp b/include/views/view_hexeditor.hpp index 0b3dd6a57..6b589a06d 100644 --- a/include/views/view_hexeditor.hpp +++ b/include/views/view_hexeditor.hpp @@ -57,18 +57,18 @@ namespace hex { void drawGotoPopup(); void drawEditPopup(); - bool createFile(std::string_view path); - void openFile(std::string_view path); - bool saveToFile(std::string_view path, const std::vector& data); - bool loadFromFile(std::string_view path, std::vector& data); + bool createFile(const std::string &path); + void openFile(const std::string &path); + bool saveToFile(const std::string &path, const std::vector& data); + bool loadFromFile(const std::string &path, std::vector& data); enum class Language { C, Cpp, CSharp, Rust, Python, Java, JavaScript }; - void copyBytes(); - void pasteBytes(); - void copyString(); - void copyLanguageArray(Language language); - void copyHexView(); - void copyHexViewHTML(); + void copyBytes() const; + void pasteBytes() const; + void copyString() const; + void copyLanguageArray(Language language) const; + void copyHexView() const; + void copyHexViewHTML() const; }; diff --git a/include/views/view_pattern_data.hpp b/include/views/view_pattern_data.hpp index 6e207027f..ed67c7d2e 100644 --- a/include/views/view_pattern_data.hpp +++ b/include/views/view_pattern_data.hpp @@ -23,7 +23,7 @@ namespace hex { void drawMenu() override; private: - std::vector m_sortedPatternData; + std::vector m_sortedPatternData; }; } \ No newline at end of file diff --git a/include/views/view_pattern_editor.hpp b/include/views/view_pattern_editor.hpp index 323e16342..6b13369bb 100644 --- a/include/views/view_pattern_editor.hpp +++ b/include/views/view_pattern_editor.hpp @@ -1,8 +1,8 @@ #pragma once #include -#include -#include +#include +#include #include @@ -26,16 +26,16 @@ namespace hex { void drawContent() override; private: - lang::PatternLanguage *m_patternLanguageRuntime; + pl::PatternLanguage *m_patternLanguageRuntime; std::vector m_possiblePatternFiles; int m_selectedPatternFile = 0; bool m_runAutomatically = false; bool m_evaluatorRunning = false; TextEditor m_textEditor; - std::vector> m_console; + std::vector> m_console; - void loadPatternFile(std::string_view path); + void loadPatternFile(const std::string &path); void clearPatternData(); void parsePattern(char *buffer); }; diff --git a/plugins/builtin/CMakeLists.txt b/plugins/builtin/CMakeLists.txt index 08a140c97..a75c27a51 100644 --- a/plugins/builtin/CMakeLists.txt +++ b/plugins/builtin/CMakeLists.txt @@ -8,7 +8,7 @@ add_library(${PROJECT_NAME} SHARED source/content/command_palette_commands.cpp source/content/data_inspector.cpp - source/content/lang_builtin_functions.cpp + source/content/pl_builtin_functions.cpp source/content/settings_entries.cpp source/content/tools_entries.cpp source/content/data_processor_nodes.cpp diff --git a/plugins/builtin/source/content/command_palette_commands.cpp b/plugins/builtin/source/content/command_palette_commands.cpp index e740b3204..d3fed49c9 100644 --- a/plugins/builtin/source/content/command_palette_commands.cpp +++ b/plugins/builtin/source/content/command_palette_commands.cpp @@ -1,5 +1,8 @@ #include +#include +using namespace hex::lang_literals; + #include #include diff --git a/plugins/builtin/source/content/lang_builtin_functions.cpp b/plugins/builtin/source/content/pl_builtin_functions.cpp similarity index 98% rename from plugins/builtin/source/content/lang_builtin_functions.cpp rename to plugins/builtin/source/content/pl_builtin_functions.cpp index 727b5fd4b..0f660a62c 100644 --- a/plugins/builtin/source/content/lang_builtin_functions.cpp +++ b/plugins/builtin/source/content/pl_builtin_functions.cpp @@ -3,9 +3,9 @@ #include #include -#include -#include -#include +#include +#include +#include #include @@ -15,7 +15,7 @@ namespace hex::plugin::builtin { #define AS_TYPE(type, value) ctx.template asType(value) void registerPatternLanguageFunctions() { - using namespace hex::lang; + using namespace hex::pl; ContentRegistry::PatternLanguageFunctions::Namespace nsStd = { "std" }; { diff --git a/plugins/builtin/source/content/settings_entries.cpp b/plugins/builtin/source/content/settings_entries.cpp index bd61ad32d..15cc68fb6 100644 --- a/plugins/builtin/source/content/settings_entries.cpp +++ b/plugins/builtin/source/content/settings_entries.cpp @@ -1,6 +1,9 @@ #include #include +#include +using namespace hex::lang_literals; + #include #include diff --git a/plugins/builtin/source/lang/de_DE.cpp b/plugins/builtin/source/lang/de_DE.cpp index 6d9a9b531..cf60b7d79 100644 --- a/plugins/builtin/source/lang/de_DE.cpp +++ b/plugins/builtin/source/lang/de_DE.cpp @@ -1,4 +1,5 @@ #include +#include namespace hex::plugin::builtin { @@ -251,7 +252,7 @@ namespace hex::plugin::builtin { { "hex.view.pattern.name", "Pattern Editor" }, { "hex.view.pattern.accept_pattern", "Pattern akzeptieren" }, { "hex.view.pattern.accept_pattern.desc", "Ein oder mehrere kompatible Pattern wurden für diesen Dateityp gefunden" }, - { "hex.view.pattern.accept_pattern.patterns", "Pattern" }, + { "hex.view.pattern.accept_pattern.pattern_language", "Pattern" }, { "hex.view.pattern.accept_pattern.question", "Ausgewähltes Pattern anwenden?" }, { "hex.view.pattern.menu.file.load_pattern", "Pattern laden..." }, { "hex.view.pattern.open_pattern", "Pattern öffnen" }, diff --git a/plugins/builtin/source/lang/en_US.cpp b/plugins/builtin/source/lang/en_US.cpp index 5d871a4ff..3c4ea4718 100644 --- a/plugins/builtin/source/lang/en_US.cpp +++ b/plugins/builtin/source/lang/en_US.cpp @@ -1,4 +1,5 @@ #include +#include namespace hex::plugin::builtin { @@ -43,7 +44,7 @@ namespace hex::plugin::builtin { { "hex.welcome.learn.latest.desc", "Read ImHex' current changelog" }, { "hex.welcome.learn.latest.link", "https://github.com/WerWolv/ImHex/releases/latest" }, { "hex.welcome.learn.pattern.title", "Pattern Language Documentation" }, - { "hex.welcome.learn.pattern.desc", "Learn how to write ImHex patterns with our extensive documentation" }, + { "hex.welcome.learn.pattern.desc", "Learn how to write ImHex pattern_language with our extensive documentation" }, { "hex.welcome.learn.pattern.link", "https://github.com/WerWolv/ImHex/wiki/Pattern-Language-Guide" }, { "hex.welcome.learn.plugins.title", "Plugins API" }, { "hex.welcome.learn.plugins.desc", "Extend ImHex with additional features using plugins" }, @@ -250,8 +251,8 @@ namespace hex::plugin::builtin { { "hex.view.pattern.name", "Pattern editor" }, { "hex.view.pattern.accept_pattern", "Accept pattern" }, - { "hex.view.pattern.accept_pattern.desc", "One or more patterns compatible with this data type has been found" }, - { "hex.view.pattern.accept_pattern.patterns", "Patterns" }, + { "hex.view.pattern.accept_pattern.desc", "One or more pattern_language compatible with this data type has been found" }, + { "hex.view.pattern.accept_pattern.pattern_language", "Patterns" }, { "hex.view.pattern.accept_pattern.question", "Do you want to apply the selected pattern?" }, { "hex.view.pattern.menu.file.load_pattern", "Load pattern..." }, { "hex.view.pattern.open_pattern", "Open pattern" }, diff --git a/plugins/builtin/source/lang/it_IT.cpp b/plugins/builtin/source/lang/it_IT.cpp index 73e4017bb..d8849e0a3 100644 --- a/plugins/builtin/source/lang/it_IT.cpp +++ b/plugins/builtin/source/lang/it_IT.cpp @@ -1,4 +1,5 @@ #include +#include namespace hex::plugin::builtin { @@ -250,7 +251,7 @@ namespace hex::plugin::builtin { { "hex.view.pattern.name", "Editor dei Pattern" }, { "hex.view.pattern.accept_pattern", "Accetta pattern" }, { "hex.view.pattern.accept_pattern.desc", "Uno o più pattern compatibili con questo tipo di dati sono stati trovati!" }, - { "hex.view.pattern.accept_pattern.patterns", "Pattern" }, + { "hex.view.pattern.accept_pattern.pattern_language", "Pattern" }, { "hex.view.pattern.accept_pattern.question", "Vuoi applicare i patter selezionati" }, { "hex.view.pattern.menu.file.load_pattern", "Caricamento dei pattern..." }, { "hex.view.pattern.open_pattern", "Apri pattern" }, diff --git a/plugins/libimhex/CMakeLists.txt b/plugins/libimhex/CMakeLists.txt index 33ce5ce0b..bab4006c3 100644 --- a/plugins/libimhex/CMakeLists.txt +++ b/plugins/libimhex/CMakeLists.txt @@ -52,13 +52,15 @@ set(LIBIMHEX_SOURCES source/helpers/crypto.cpp source/helpers/lang.cpp source/helpers/net.cpp + source/helpers/file.cpp + + source/pattern_language/pattern_language.cpp + source/pattern_language/preprocessor.cpp + source/pattern_language/lexer.cpp + source/pattern_language/parser.cpp + source/pattern_language/validator.cpp + source/pattern_language/evaluator.cpp - source/lang/pattern_language.cpp - source/lang/preprocessor.cpp - source/lang/lexer.cpp - source/lang/parser.cpp - source/lang/validator.cpp - source/lang/evaluator.cpp source/providers/provider.cpp source/views/view.cpp @@ -76,7 +78,7 @@ if (APPLE) endif () endif () - set(LIBIMHEX_SOURCES ${LIBIMHEX_SOURCES} source/helpers/paths_mac.mm) + set(LIBIMHEX_SOURCES ${LIBIMHEX_SOURCES} source/helpers/paths_mac.mm include/hex/helpers/file.hpp) endif () add_library(libimhex SHARED ${LIBIMHEX_SOURCES}) diff --git a/plugins/libimhex/include/hex.hpp b/plugins/libimhex/include/hex.hpp index def511081..6d400d696 100644 --- a/plugins/libimhex/include/hex.hpp +++ b/plugins/libimhex/include/hex.hpp @@ -2,9 +2,6 @@ #include -#include -using namespace hex::lang_literals; - constexpr static const auto ImHexApiURL = "https://api.werwolv.net/imhex"; constexpr static const auto GitHubApiURL = "https://api.github.com/repos/WerWolv/ImHex"; diff --git a/plugins/libimhex/include/hex/api/content_registry.hpp b/plugins/libimhex/include/hex/api/content_registry.hpp index b3ea4e252..3cef73e00 100644 --- a/plugins/libimhex/include/hex/api/content_registry.hpp +++ b/plugins/libimhex/include/hex/api/content_registry.hpp @@ -14,8 +14,8 @@ namespace hex { class View; - namespace lang { class ASTNode; } - namespace lang { class Evaluator; } + class LanguageDefinition; + namespace pl { class ASTNode; class Evaluator; } namespace dp { class Node; } /* @@ -30,27 +30,29 @@ namespace hex { struct Settings { Settings() = delete; + using Callback = std::function; + struct Entry { std::string name; - std::function callback; + Callback callback; }; static void load(); static void store(); - static void add(std::string_view unlocalizedCategory, std::string_view unlocalizedName, s64 defaultValue, const std::function &callback); - static void add(std::string_view unlocalizedCategory, std::string_view unlocalizedName, std::string_view defaultValue, const std::function &callback); + static void add(const std::string &unlocalizedCategory, const std::string &unlocalizedName, s64 defaultValue, const Callback &callback); + static void add(const std::string &unlocalizedCategory, const std::string &unlocalizedName, const std::string &defaultValue, const Callback &callback); - static void write(std::string_view unlocalizedCategory, std::string_view unlocalizedName, s64 value); - static void write(std::string_view unlocalizedCategory, std::string_view unlocalizedName, std::string_view value); - static void write(std::string_view unlocalizedCategory, std::string_view unlocalizedName, const std::vector& value); + static void write(const std::string &unlocalizedCategory, const std::string &unlocalizedName, s64 value); + static void write(const std::string &unlocalizedCategory, const std::string &unlocalizedName, const std::string &value); + static void write(const std::string &unlocalizedCategory, const std::string &unlocalizedName, const std::vector& value); - static s64 read(std::string_view unlocalizedCategory, std::string_view unlocalizedName, s64 defaultValue); - static std::string read(std::string_view unlocalizedCategory, std::string_view unlocalizedName, std::string_view defaultValue); - static std::vector read(std::string_view unlocalizedCategory, std::string_view unlocalizedName, const std::vector& defaultValue = { }); + static s64 read(const std::string &unlocalizedCategory, const std::string &unlocalizedName, s64 defaultValue); + static std::string read(const std::string &unlocalizedCategory, const std::string &unlocalizedName, const std::string &defaultValue); + static std::vector read(const std::string &unlocalizedCategory, const std::string &unlocalizedName, const std::vector& defaultValue = { }); static std::map>& getEntries(); - static nlohmann::json getSetting(std::string_view unlocalizedCategory, std::string_view unlocalizedName); + static nlohmann::json getSetting(const std::string &unlocalizedCategory, const std::string &unlocalizedName); static nlohmann::json& getSettingsData(); }; @@ -63,15 +65,18 @@ namespace hex { KeywordCommand }; + using DisplayCallback = std::function; + using ExecuteCallback = std::function; + struct Entry { Type type; std::string command; std::string unlocalizedDescription; - std::function displayCallback; - std::function executeCallback; + DisplayCallback displayCallback; + ExecuteCallback executeCallback; }; - static void add(Type type, std::string_view command, std::string_view unlocalizedDescription, const std::function &displayCallback, const std::function &executeCallback = [](auto){}); + static void add(Type type, const std::string &command, const std::string &unlocalizedDescription, const DisplayCallback &displayCallback, const ExecuteCallback &executeCallback = [](auto){}); static std::vector& getEntries(); }; @@ -85,13 +90,14 @@ namespace hex { constexpr static u32 NoParameters = 0x0000'0000; using Namespace = std::vector; + using Callback = std::function&)>; struct Function { u32 parameterCount; - std::function&)> func; + Callback func; }; - static void add(const Namespace &ns, const std::string &name, u32 parameterCount, const std::function&)> &func); + static void add(const Namespace &ns, const std::string &name, u32 parameterCount, const Callback &func); static std::map& getEntries(); }; @@ -116,12 +122,14 @@ namespace hex { struct Tools { Tools() = delete; + using Callback = std::function; + struct Entry { std::string name; - std::function function; + Callback function; }; - static void add(std::string_view unlocalizedName, const std::function &function); + static void add(const std::string &unlocalizedName, const Callback &function); static std::vector& getEntries(); }; @@ -145,7 +153,7 @@ namespace hex { GeneratorFunction generatorFunction; }; - static void add(std::string_view unlocalizedName, size_t requiredSize, GeneratorFunction function); + static void add(const std::string &unlocalizedName, size_t requiredSize, GeneratorFunction function); static std::vector& getEntries(); }; @@ -160,11 +168,11 @@ namespace hex { }; template T, typename ... Args> - static void add(std::string_view unlocalizedCategory, std::string_view unlocalizedName, Args&& ... args) { - add(Entry{ unlocalizedCategory.data(), unlocalizedName.data(), - [args..., name = std::string(unlocalizedName)]{ + static void add(const std::string &unlocalizedCategory, const std::string &unlocalizedName, Args&& ... args) { + add(Entry{ unlocalizedCategory.c_str(), unlocalizedName.c_str(), + [=]{ auto node = new T(std::forward(args)...); - node->setUnlocalizedName(name); + node->setUnlocalizedName(unlocalizedName); return node; } }); @@ -179,8 +187,8 @@ namespace hex { /* Language Registry. Allows together with the LangEntry class and the _lang user defined literal to add new languages */ struct Language { - static void registerLanguage(std::string_view name, std::string_view languageCode); - static void addLocalizations(std::string_view languageCode, const LanguageDefinition &definition); + static void registerLanguage(const std::string &name, const std::string &languageCode); + static void addLocalizations(const std::string &languageCode, const LanguageDefinition &definition); static std::map& getLanguages(); static std::map>& getLanguageDefinitions(); diff --git a/plugins/libimhex/include/hex/api/event.hpp b/plugins/libimhex/include/hex/api/event.hpp index 7b1df7eda..15a9bc170 100644 --- a/plugins/libimhex/include/hex/api/event.hpp +++ b/plugins/libimhex/include/hex/api/event.hpp @@ -9,11 +9,11 @@ #include -#define EVENT_DEF(event_name, ...) \ - struct event_name final : public hex::Event<__VA_ARGS__> { \ - constexpr static auto id = [] { return hex::EventId(); }(); \ - event_name(Callback func) noexcept : Event(func) { } \ - }; +#define EVENT_DEF(event_name, ...) \ + struct event_name final : public hex::Event<__VA_ARGS__> { \ + constexpr static auto id = [] { return hex::EventId(); }(); \ + explicit event_name(Callback func) noexcept : Event(std::move(func)) { } \ + } class GLFWwindow; @@ -100,7 +100,6 @@ namespace hex { EVENT_DEF(EventFileUnloaded); EVENT_DEF(EventDataChanged); EVENT_DEF(EventPatternChanged); - EVENT_DEF(EventFileDropped, std::string); EVENT_DEF(EventWindowClosing, GLFWwindow*); EVENT_DEF(EventRegionSelected, Region); EVENT_DEF(EventProjectFileStore); @@ -114,6 +113,7 @@ namespace hex { EVENT_DEF(RequestAppendPatternLanguageCode, std::string); EVENT_DEF(RequestChangeWindowTitle, std::string); EVENT_DEF(RequestCloseImHex, bool); + EVENT_DEF(RequestOpenFile, std::string); EVENT_DEF(QuerySelection, Region&); diff --git a/plugins/libimhex/include/hex/api/imhex_api.hpp b/plugins/libimhex/include/hex/api/imhex_api.hpp index c33bdd78b..d85cb917d 100644 --- a/plugins/libimhex/include/hex/api/imhex_api.hpp +++ b/plugins/libimhex/include/hex/api/imhex_api.hpp @@ -4,6 +4,7 @@ #include #include +#include namespace hex { @@ -29,8 +30,8 @@ namespace hex { bool locked; }; - static void add(Region region, std::string_view name, std::string_view comment, u32 color = 0x00000000); - static void add(u64 addr, size_t size, std::string_view name, std::string_view comment, u32 color = 0x00000000); + static void add(Region region, const std::string &name, const std::string &comment, u32 color = 0x00000000); + static void add(u64 addr, size_t size, const std::string &name, const std::string &comment, u32 color = 0x00000000); static std::list& getEntries(); }; diff --git a/plugins/libimhex/include/hex/data_processor/attribute.hpp b/plugins/libimhex/include/hex/data_processor/attribute.hpp index 2570ab997..98d0aa478 100644 --- a/plugins/libimhex/include/hex/data_processor/attribute.hpp +++ b/plugins/libimhex/include/hex/data_processor/attribute.hpp @@ -2,7 +2,9 @@ #include #include +#include #include +#include #include namespace hex::dp { @@ -21,7 +23,7 @@ namespace hex::dp { In, Out }; - Attribute(IOType ioType, Type type, std::string_view unlocalizedName); + Attribute(IOType ioType, Type type, std::string unlocalizedName); ~Attribute(); [[nodiscard]] u32 getID() const { return this->m_id; } @@ -29,7 +31,7 @@ namespace hex::dp { [[nodiscard]] IOType getIOType() const { return this->m_ioType; } [[nodiscard]] Type getType() const { return this->m_type; } - [[nodiscard]] std::string_view getUnlocalizedName() const { return this->m_unlocalizedName; } + [[nodiscard]] const std::string& getUnlocalizedName() const { return this->m_unlocalizedName; } void addConnectedAttribute(u32 linkId, Attribute *to) { this->m_connectedAttributes.insert({ linkId, to }); } void removeConnectedAttribute(u32 linkId) { this->m_connectedAttributes.erase(linkId); } @@ -44,7 +46,7 @@ namespace hex::dp { Type m_type; std::string m_unlocalizedName; std::map m_connectedAttributes; - Node *m_parentNode; + Node *m_parentNode = nullptr; std::optional> m_outputData; diff --git a/plugins/libimhex/include/hex/data_processor/node.hpp b/plugins/libimhex/include/hex/data_processor/node.hpp index 662c429ba..b7cf2b9a1 100644 --- a/plugins/libimhex/include/hex/data_processor/node.hpp +++ b/plugins/libimhex/include/hex/data_processor/node.hpp @@ -15,17 +15,17 @@ namespace hex::dp { class Node { public: - Node(std::string_view unlocalizedTitle, std::vector attributes); + Node(std::string unlocalizedTitle, std::vector attributes); virtual ~Node() = default; [[nodiscard]] u32 getID() const { return this->m_id; } void setID(u32 id) { this->m_id = id; } - [[nodiscard]] std::string_view getUnlocalizedName() const { return this->m_unlocalizedName; } - void setUnlocalizedName(std::string_view unlocalizedName) { this->m_unlocalizedName = unlocalizedName; } + [[nodiscard]] const std::string& getUnlocalizedName() const { return this->m_unlocalizedName; } + void setUnlocalizedName(const std::string &unlocalizedName) { this->m_unlocalizedName = unlocalizedName; } - [[nodiscard]] std::string_view getUnlocalizedTitle() const { return this->m_unlocalizedTitle; } + [[nodiscard]] const std::string& getUnlocalizedTitle() const { return this->m_unlocalizedTitle; } [[nodiscard]] std::vector& getAttributes() { return this->m_attributes; } void setCurrentOverlay(prv::Overlay *overlay) { @@ -76,7 +76,7 @@ namespace hex::dp { protected: - [[noreturn]] void throwNodeError(std::string_view message) { + [[noreturn]] void throwNodeError(const std::string &message) { throw NodeError(this, message); } diff --git a/plugins/libimhex/include/hex/helpers/file.hpp b/plugins/libimhex/include/hex/helpers/file.hpp new file mode 100644 index 000000000..6f5d984c6 --- /dev/null +++ b/plugins/libimhex/include/hex/helpers/file.hpp @@ -0,0 +1,48 @@ +#pragma once + +#include + +#include +#include +#include + +#if defined(OS_MACOS) + #define off64_t off_t + #define fopen64 fopen + #define fseeko64 fseek + #define ftello64 ftell +#endif + +namespace hex { + + class File { + public: + enum class Mode { + Read, + Write, + Create + }; + + explicit File(const std::string &path, Mode mode); + ~File(); + + bool isValid() { return this->m_file != nullptr; } + + void seek(u64 offset); + + std::vector readBytes(size_t numBytes = 0); + std::string readString(size_t numBytes = 0); + + void write(const std::vector &bytes); + void write(const std::string &string); + + size_t getSize(); + void setSize(u64 size); + + auto getHandle() { return this->m_file; } + + private: + FILE *m_file; + }; + +} \ No newline at end of file diff --git a/plugins/libimhex/include/hex/helpers/logger.hpp b/plugins/libimhex/include/hex/helpers/logger.hpp index 58253e836..bca4e7bb1 100644 --- a/plugins/libimhex/include/hex/helpers/logger.hpp +++ b/plugins/libimhex/include/hex/helpers/logger.hpp @@ -5,7 +5,7 @@ namespace hex::log { - void debug(std::string_view fmt, auto ... args) { + void debug(const std::string &fmt, auto ... args) { #if defined(DEBUG) fmt::print(fg(fmt::color::green_yellow) | fmt::emphasis::bold, "[DEBUG] "); fmt::print(fmt::runtime(fmt), args...); @@ -13,25 +13,25 @@ namespace hex::log { #endif } - void info(std::string_view fmt, auto ... args) { + void info(const std::string &fmt, auto ... args) { fmt::print(fg(fmt::color::cadet_blue) | fmt::emphasis::bold, "[INFO] "); fmt::print(fmt::runtime(fmt), args...); fmt::print("\n"); } - void warn(std::string_view fmt, auto ... args) { + void warn(const std::string &fmt, auto ... args) { fmt::print(fg(fmt::color::light_golden_rod_yellow) | fmt::emphasis::bold, "[WARN] "); fmt::print(fmt::runtime(fmt), args...); fmt::print("\n"); } - void error(std::string_view fmt, auto ... args) { + void error(const std::string &fmt, auto ... args) { fmt::print(fg(fmt::color::red) | fmt::emphasis::bold, "[ERROR] "); fmt::print(fmt::runtime(fmt), args...); fmt::print("\n"); } - void fatal(std::string_view fmt, auto ... args) { + void fatal(const std::string &fmt, auto ... args) { fmt::print(fg(fmt::color::purple) | fmt::emphasis::bold, "[FATAL] "); fmt::print(fmt::runtime(fmt), args...); fmt::print("\n"); diff --git a/plugins/libimhex/include/hex/helpers/shared_data.hpp b/plugins/libimhex/include/hex/helpers/shared_data.hpp index 7e17111ae..9674b4cc9 100644 --- a/plugins/libimhex/include/hex/helpers/shared_data.hpp +++ b/plugins/libimhex/include/hex/helpers/shared_data.hpp @@ -25,7 +25,7 @@ namespace hex { namespace prv { class Provider; } namespace dp { class Node; } - namespace lang { class PatternData; } + namespace pl { class PatternData; } class View; @@ -64,7 +64,7 @@ namespace hex { static u32 patternPaletteOffset; static std::string errorPopupMessage; static std::list bookmarkEntries; - static std::vector patternData; + static std::vector patternData; static std::map languageNames; static std::map> languageDefinitions; diff --git a/plugins/libimhex/include/hex/helpers/utils.hpp b/plugins/libimhex/include/hex/helpers/utils.hpp index 1d164eb93..d4d4f4261 100644 --- a/plugins/libimhex/include/hex/helpers/utils.hpp +++ b/plugins/libimhex/include/hex/helpers/utils.hpp @@ -15,13 +15,6 @@ #include -#if defined(OS_MACOS) - #define off64_t off_t - #define fopen64 fopen - #define fseeko64 fseek - #define ftello64 ftell -#endif - #define TOKEN_CONCAT_IMPL(x, y) x ## y #define TOKEN_CONCAT(x, y) TOKEN_CONCAT_IMPL(x, y) #define ANONYMOUS_VARIABLE(prefix) TOKEN_CONCAT(prefix, __COUNTER__) @@ -98,13 +91,11 @@ namespace hex { return T(1) << bit_width(T(x - 1)); } - std::vector splitString(std::string_view string, std::string_view delimiter); - std::string combineStrings(const std::vector &strings, std::string_view delimiter = ""); + std::vector splitString(const std::string &string, const std::string &delimiter); + std::string combineStrings(const std::vector &strings, const std::string &delimiter = ""); std::string toEngineeringString(double value); - std::vector readFile(std::string_view path); - template std::vector toBytes(T value) { std::vector bytes(sizeof(T)); @@ -113,7 +104,7 @@ namespace hex { return bytes; } - inline std::vector parseByteString(std::string_view string) { + inline std::vector parseByteString(const std::string &string) { auto byteString = std::string(string); byteString.erase(std::remove(byteString.begin(), byteString.end(), ' '), byteString.end()); @@ -163,7 +154,7 @@ namespace hex { Folder }; - void openFileBrowser(std::string_view title, DialogMode mode, const std::vector &validExtensions, const std::function &callback); + void openFileBrowser(const std::string &title, DialogMode mode, const std::vector &validExtensions, const std::function &callback); float float16ToFloat32(u16 float16); diff --git a/plugins/libimhex/include/hex/lang/ast_node.hpp b/plugins/libimhex/include/hex/pattern_language/ast_node.hpp similarity index 91% rename from plugins/libimhex/include/hex/lang/ast_node.hpp rename to plugins/libimhex/include/hex/pattern_language/ast_node.hpp index 5b36bd184..b863fb634 100644 --- a/plugins/libimhex/include/hex/lang/ast_node.hpp +++ b/plugins/libimhex/include/hex/pattern_language/ast_node.hpp @@ -8,7 +8,7 @@ #include #include -namespace hex::lang { +namespace hex::pl { class ASTNodeAttribute; @@ -141,8 +141,8 @@ namespace hex::lang { class ASTNodeTypeDecl : public ASTNode, public Attributable { public: - ASTNodeTypeDecl(std::string_view name, ASTNode *type, std::optional endian = { }) - : ASTNode(), m_name(name), m_type(type), m_endian(endian) { } + ASTNodeTypeDecl(std::string name, ASTNode *type, std::optional endian = std::nullopt) + : ASTNode(), m_name(std::move(name)), m_type(type), m_endian(endian) { } ASTNodeTypeDecl(const ASTNodeTypeDecl& other) : ASTNode(other), Attributable(other) { this->m_name = other.m_name; @@ -162,7 +162,7 @@ namespace hex::lang { } void setName(const std::string &name) { this->m_name = name; } - [[nodiscard]] std::string_view getName() const { return this->m_name; } + [[nodiscard]] const std::string& getName() const { return this->m_name; } [[nodiscard]] ASTNode* getType() { return this->m_type; } [[nodiscard]] std::optional getEndian() const { return this->m_endian; } @@ -174,8 +174,8 @@ namespace hex::lang { class ASTNodeVariableDecl : public ASTNode, public Attributable { public: - ASTNodeVariableDecl(std::string_view name, ASTNode *type, ASTNode *placementOffset = nullptr) - : ASTNode(), m_name(name), m_type(type), m_placementOffset(placementOffset) { } + ASTNodeVariableDecl(std::string name, ASTNode *type, ASTNode *placementOffset = nullptr) + : ASTNode(), m_name(std::move(name)), m_type(type), m_placementOffset(placementOffset) { } ASTNodeVariableDecl(const ASTNodeVariableDecl &other) : ASTNode(other), Attributable(other) { this->m_name = other.m_name; @@ -196,7 +196,7 @@ namespace hex::lang { return new ASTNodeVariableDecl(*this); } - [[nodiscard]] std::string_view getName() const { return this->m_name; } + [[nodiscard]] const std::string& getName() const { return this->m_name; } [[nodiscard]] constexpr ASTNode* getType() const { return this->m_type; } [[nodiscard]] constexpr auto getPlacementOffset() const { return this->m_placementOffset; } @@ -208,8 +208,8 @@ namespace hex::lang { class ASTNodeArrayVariableDecl : public ASTNode, public Attributable { public: - ASTNodeArrayVariableDecl(std::string_view name, ASTNode *type, ASTNode *size, ASTNode *placementOffset = nullptr) - : ASTNode(), m_name(name), m_type(type), m_size(size), m_placementOffset(placementOffset) { } + ASTNodeArrayVariableDecl(std::string name, ASTNode *type, ASTNode *size, ASTNode *placementOffset = nullptr) + : ASTNode(), m_name(std::move(name)), m_type(type), m_size(size), m_placementOffset(placementOffset) { } ASTNodeArrayVariableDecl(const ASTNodeArrayVariableDecl &other) : ASTNode(other), Attributable(other) { this->m_name = other.m_name; @@ -235,7 +235,7 @@ namespace hex::lang { return new ASTNodeArrayVariableDecl(*this); } - [[nodiscard]] std::string_view getName() const { return this->m_name; } + [[nodiscard]] const std::string& getName() const { return this->m_name; } [[nodiscard]] constexpr ASTNode* getType() const { return this->m_type; } [[nodiscard]] constexpr ASTNode* getSize() const { return this->m_size; } [[nodiscard]] constexpr auto getPlacementOffset() const { return this->m_placementOffset; } @@ -249,8 +249,8 @@ namespace hex::lang { class ASTNodePointerVariableDecl : public ASTNode, public Attributable { public: - ASTNodePointerVariableDecl(std::string_view name, ASTNode *type, ASTNode *sizeType, ASTNode *placementOffset = nullptr) - : ASTNode(), m_name(name), m_type(type), m_sizeType(sizeType), m_placementOffset(placementOffset) { } + ASTNodePointerVariableDecl(std::string name, ASTNode *type, ASTNode *sizeType, ASTNode *placementOffset = nullptr) + : ASTNode(), m_name(std::move(name)), m_type(type), m_sizeType(sizeType), m_placementOffset(placementOffset) { } ASTNodePointerVariableDecl(const ASTNodePointerVariableDecl &other) : ASTNode(other), Attributable(other) { this->m_name = other.m_name; @@ -273,7 +273,7 @@ namespace hex::lang { return new ASTNodePointerVariableDecl(*this); } - [[nodiscard]] std::string_view getName() const { return this->m_name; } + [[nodiscard]] const std::string& getName() const { return this->m_name; } [[nodiscard]] constexpr ASTNode* getType() const { return this->m_type; } [[nodiscard]] constexpr ASTNode* getSizeType() const { return this->m_sizeType; } [[nodiscard]] constexpr auto getPlacementOffset() const { return this->m_placementOffset; } @@ -540,8 +540,8 @@ namespace hex::lang { class ASTNodeFunctionCall : public ASTNode { public: - explicit ASTNodeFunctionCall(std::string_view functionName, std::vector params) - : ASTNode(), m_functionName(functionName), m_params(std::move(params)) { } + explicit ASTNodeFunctionCall(std::string functionName, std::vector params) + : ASTNode(), m_functionName(std::move(functionName)), m_params(std::move(params)) { } ~ASTNodeFunctionCall() override { for (auto ¶m : this->m_params) @@ -559,7 +559,7 @@ namespace hex::lang { return new ASTNodeFunctionCall(*this); } - [[nodiscard]] std::string_view getFunctionName() { + [[nodiscard]] const std::string& getFunctionName() { return this->m_functionName; } @@ -574,7 +574,7 @@ namespace hex::lang { class ASTNodeStringLiteral : public ASTNode { public: - explicit ASTNodeStringLiteral(std::string_view string) : ASTNode(), m_string(string) { } + explicit ASTNodeStringLiteral(std::string string) : ASTNode(), m_string(std::move(string)) { } ~ASTNodeStringLiteral() override = default; @@ -586,7 +586,7 @@ namespace hex::lang { return new ASTNodeStringLiteral(*this); } - [[nodiscard]] std::string_view getString() { + [[nodiscard]] const std::string& getString() { return this->m_string; } @@ -596,8 +596,8 @@ namespace hex::lang { class ASTNodeAttribute : public ASTNode { public: - explicit ASTNodeAttribute(std::string_view attribute, std::optional value = { }) - : ASTNode(), m_attribute(attribute), m_value(value) { } + explicit ASTNodeAttribute(std::string attribute, std::optional value = std::nullopt) + : ASTNode(), m_attribute(std::move(attribute)), m_value(std::move(value)) { } ~ASTNodeAttribute() override = default; @@ -610,7 +610,7 @@ namespace hex::lang { return new ASTNodeAttribute(*this); } - [[nodiscard]] std::string_view getAttribute() const { + [[nodiscard]] const std::string& getAttribute() const { return this->m_attribute; } @@ -680,7 +680,7 @@ namespace hex::lang { delete statement; } - [[nodiscard]] std::string_view getName() const { + [[nodiscard]] const std::string& getName() const { return this->m_name; } @@ -717,7 +717,7 @@ namespace hex::lang { delete this->m_rvalue; } - [[nodiscard]] std::string_view getLValueName() const { + [[nodiscard]] const std::string& getLValueName() const { return this->m_lvalueName; } diff --git a/plugins/libimhex/include/hex/lang/evaluator.hpp b/plugins/libimhex/include/hex/pattern_language/evaluator.hpp similarity index 92% rename from plugins/libimhex/include/hex/lang/evaluator.hpp rename to plugins/libimhex/include/hex/pattern_language/evaluator.hpp index eec6b3552..2f1665c9a 100644 --- a/plugins/libimhex/include/hex/lang/evaluator.hpp +++ b/plugins/libimhex/include/hex/pattern_language/evaluator.hpp @@ -3,8 +3,8 @@ #include #include -#include -#include +#include +#include #include #include @@ -13,7 +13,7 @@ namespace hex::prv { class Provider; } -namespace hex::lang { +namespace hex::pl { class PatternData; @@ -57,8 +57,8 @@ namespace hex::lang { u32 m_recursionLimit; u32 m_currRecursionDepth; - void createLocalVariable(std::string_view varName, PatternData *pattern); - void setLocalVariableValue(std::string_view varName, const void *value, size_t size); + void createLocalVariable(const std::string &varName, PatternData *pattern); + void setLocalVariableValue(const std::string &varName, const void *value, size_t size); ASTNodeIntegerLiteral* evaluateScopeResolution(ASTNodeScopeResolution *node); ASTNodeIntegerLiteral* evaluateRValue(ASTNodeRValue *node); diff --git a/plugins/libimhex/include/hex/lang/lexer.hpp b/plugins/libimhex/include/hex/pattern_language/lexer.hpp similarity index 60% rename from plugins/libimhex/include/hex/lang/lexer.hpp rename to plugins/libimhex/include/hex/pattern_language/lexer.hpp index 389ea1f48..bc66d7844 100644 --- a/plugins/libimhex/include/hex/lang/lexer.hpp +++ b/plugins/libimhex/include/hex/pattern_language/lexer.hpp @@ -2,19 +2,19 @@ #include -#include "token.hpp" +#include #include #include #include -namespace hex::lang { +namespace hex::pl { class Lexer { public: using LexerError = std::pair; - Lexer(); + Lexer() = default; std::optional> lex(const std::string& code); const LexerError& getError() { return this->m_error; } @@ -22,8 +22,8 @@ namespace hex::lang { private: LexerError m_error; - [[noreturn]] void throwLexerError(std::string_view error, u32 lineNumber) const { - throw LexerError(lineNumber, "Lexer: " + std::string(error)); + [[noreturn]] void throwLexerError(const std::string &error, u32 lineNumber) const { + throw LexerError(lineNumber, "Lexer: " + error); } }; diff --git a/plugins/libimhex/include/hex/lang/log_console.hpp b/plugins/libimhex/include/hex/pattern_language/log_console.hpp similarity index 72% rename from plugins/libimhex/include/hex/lang/log_console.hpp rename to plugins/libimhex/include/hex/pattern_language/log_console.hpp index b5312a765..d0fbc4404 100644 --- a/plugins/libimhex/include/hex/lang/log_console.hpp +++ b/plugins/libimhex/include/hex/pattern_language/log_console.hpp @@ -7,7 +7,7 @@ #include #include -namespace hex::lang { +namespace hex::pl { class LogConsole { public: @@ -22,17 +22,17 @@ namespace hex::lang { using EvaluateError = std::string; - void log(Level level, std::string_view message) { + void log(Level level, const std::string &message) { switch (level) { default: - case Level::Debug: this->m_consoleLog.emplace_back(level, "[-] " + std::string(message)); break; - case Level::Info: this->m_consoleLog.emplace_back(level, "[i] " + std::string(message)); break; - case Level::Warning: this->m_consoleLog.emplace_back(level, "[*] " + std::string(message)); break; - case Level::Error: this->m_consoleLog.emplace_back(level, "[!] " + std::string(message)); break; + case Level::Debug: this->m_consoleLog.emplace_back(level, "[-] " + message); break; + case Level::Info: this->m_consoleLog.emplace_back(level, "[i] " + message); break; + case Level::Warning: this->m_consoleLog.emplace_back(level, "[*] " + message); break; + case Level::Error: this->m_consoleLog.emplace_back(level, "[!] " + message); break; } } - [[noreturn]] void abortEvaluation(std::string_view message) { + [[noreturn]] void abortEvaluation(const std::string &message) { throw EvaluateError(message); } diff --git a/plugins/libimhex/include/hex/lang/parser.hpp b/plugins/libimhex/include/hex/pattern_language/parser.hpp similarity index 97% rename from plugins/libimhex/include/hex/lang/parser.hpp rename to plugins/libimhex/include/hex/pattern_language/parser.hpp index 9ea58e626..8e79ffdc7 100644 --- a/plugins/libimhex/include/hex/lang/parser.hpp +++ b/plugins/libimhex/include/hex/pattern_language/parser.hpp @@ -3,15 +3,15 @@ #include #include -#include "token.hpp" -#include "ast_node.hpp" +#include +#include #include #include #include #include -namespace hex::lang { +namespace hex::pl { class Parser { public: @@ -130,8 +130,8 @@ namespace hex::lang { return program; } - [[noreturn]] void throwParseError(std::string_view error, s32 token = -1) const { - throw ParseError(this->m_curr[token].lineNumber, "Parser: " + std::string(error)); + [[noreturn]] void throwParseError(const std::string &error, s32 token = -1) const { + throw ParseError(this->m_curr[token].lineNumber, "Parser: " + error); } /* Token consuming */ diff --git a/plugins/libimhex/include/hex/lang/pattern_data.hpp b/plugins/libimhex/include/hex/pattern_language/pattern_data.hpp similarity index 99% rename from plugins/libimhex/include/hex/lang/pattern_data.hpp rename to plugins/libimhex/include/hex/pattern_language/pattern_data.hpp index 3de117555..94e5540bf 100644 --- a/plugins/libimhex/include/hex/lang/pattern_data.hpp +++ b/plugins/libimhex/include/hex/pattern_language/pattern_data.hpp @@ -5,7 +5,7 @@ #include #include -#include +#include #include #include #include @@ -17,7 +17,7 @@ #include #include -namespace hex::lang { +namespace hex::pl { using namespace ::std::literals::string_literals; @@ -113,7 +113,7 @@ namespace hex::lang { virtual void sort(ImGuiTableSortSpecs *sortSpecs, prv::Provider *provider) { } - static bool sortPatternDataTable(ImGuiTableSortSpecs *sortSpecs, prv::Provider *provider, lang::PatternData* left, lang::PatternData* right) { + static bool sortPatternDataTable(ImGuiTableSortSpecs *sortSpecs, prv::Provider *provider, pl::PatternData* left, pl::PatternData* right) { if (sortSpecs->Specs->ColumnUserID == ImGui::GetID("name")) { if (sortSpecs->Specs->SortDirection == ImGuiSortDirection_Ascending) return left->getVariableName() > right->getVariableName(); @@ -190,7 +190,7 @@ namespace hex::lang { } protected: - void createDefaultEntry(std::string_view value) const { + void createDefaultEntry(const std::string &value) const { ImGui::TableNextRow(); ImGui::TreeNodeEx(this->getVariableName().c_str(), ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_SpanFullWidth | ImGuiTreeNodeFlags_AllowItemOverlap); ImGui::TableNextColumn(); @@ -209,7 +209,7 @@ namespace hex::lang { ImGui::TableNextColumn(); ImGui::TextColored(ImColor(0xFF9BC64D), "%s", this->getFormattedName().c_str()); ImGui::TableNextColumn(); - ImGui::Text("%s", value.data()); + ImGui::Text("%s", value.c_str()); } void drawCommentTooltip() const { diff --git a/plugins/libimhex/include/hex/lang/pattern_language.hpp b/plugins/libimhex/include/hex/pattern_language/pattern_language.hpp similarity index 86% rename from plugins/libimhex/include/hex/lang/pattern_language.hpp rename to plugins/libimhex/include/hex/pattern_language/pattern_language.hpp index 306b99f19..e3649a051 100644 --- a/plugins/libimhex/include/hex/lang/pattern_language.hpp +++ b/plugins/libimhex/include/hex/pattern_language/pattern_language.hpp @@ -8,11 +8,11 @@ #include #include -#include +#include namespace hex::prv { class Provider; } -namespace hex::lang { +namespace hex::pl { class Preprocessor; class Lexer; @@ -26,8 +26,8 @@ namespace hex::lang { PatternLanguage(); ~PatternLanguage(); - std::optional> executeString(prv::Provider *provider, std::string_view string); - std::optional> executeFile(prv::Provider *provider, std::string_view path); + std::optional> executeString(prv::Provider *provider, const std::string &string); + std::optional> executeFile(prv::Provider *provider, const std::string &path); const std::vector>& getConsoleLog(); const std::optional>& getError(); diff --git a/plugins/libimhex/include/hex/lang/preprocessor.hpp b/plugins/libimhex/include/hex/pattern_language/preprocessor.hpp similarity index 85% rename from plugins/libimhex/include/hex/lang/preprocessor.hpp rename to plugins/libimhex/include/hex/pattern_language/preprocessor.hpp index f8225a5e9..238b01d09 100644 --- a/plugins/libimhex/include/hex/lang/preprocessor.hpp +++ b/plugins/libimhex/include/hex/pattern_language/preprocessor.hpp @@ -2,8 +2,6 @@ #include -#include "token.hpp" - #include #include #include @@ -11,7 +9,7 @@ #include #include -namespace hex::lang { +namespace hex::pl { class Preprocessor { public: @@ -27,8 +25,8 @@ namespace hex::lang { private: using PreprocessorError = std::pair; - [[noreturn]] void throwPreprocessorError(std::string_view error, u32 lineNumber) const { - throw PreprocessorError(lineNumber, "Preprocessor: " + std::string(error)); + [[noreturn]] void throwPreprocessorError(const std::string &error, u32 lineNumber) const { + throw PreprocessorError(lineNumber, "Preprocessor: " + error); } std::unordered_map> m_pragmaHandlers; diff --git a/plugins/libimhex/include/hex/lang/token.hpp b/plugins/libimhex/include/hex/pattern_language/token.hpp similarity index 95% rename from plugins/libimhex/include/hex/lang/token.hpp rename to plugins/libimhex/include/hex/pattern_language/token.hpp index 44e12bfb2..ac94a0976 100644 --- a/plugins/libimhex/include/hex/lang/token.hpp +++ b/plugins/libimhex/include/hex/pattern_language/token.hpp @@ -6,7 +6,7 @@ #include #include -namespace hex::lang { +namespace hex::pl { class Token { public: @@ -131,7 +131,7 @@ namespace hex::lang { return static_cast(type) >> 4; } - [[nodiscard]] constexpr static auto getTypeName(const lang::Token::ValueType type) { + [[nodiscard]] constexpr static auto getTypeName(const pl::Token::ValueType type) { switch (type) { case ValueType::Signed8Bit: return "s8"; case ValueType::Signed16Bit: return "s16"; @@ -192,7 +192,7 @@ namespace hex::lang { } -#define COMPONENT(type, value) hex::lang::Token::Type::type, hex::lang::Token::type::value +#define COMPONENT(type, value) hex::pl::Token::Type::type, hex::pl::Token::type::value #define KEYWORD_STRUCT COMPONENT(Keyword, Struct) #define KEYWORD_UNION COMPONENT(Keyword, Union) @@ -209,9 +209,9 @@ namespace hex::lang { #define KEYWORD_RETURN COMPONENT(Keyword, Return) #define KEYWORD_NAMESPACE COMPONENT(Keyword, Namespace) -#define INTEGER hex::lang::Token::Type::Integer, hex::lang::Token::IntegerLiteral(u64(0)) -#define IDENTIFIER hex::lang::Token::Type::Identifier, "" -#define STRING hex::lang::Token::Type::String, "" +#define INTEGER hex::pl::Token::Type::Integer, hex::pl::Token::IntegerLiteral(u64(0)) +#define IDENTIFIER hex::pl::Token::Type::Identifier, "" +#define STRING hex::pl::Token::Type::String, "" #define OPERATOR_AT COMPONENT(Operator, AtDeclaration) #define OPERATOR_ASSIGNMENT COMPONENT(Operator, Assignment) diff --git a/plugins/libimhex/include/hex/lang/validator.hpp b/plugins/libimhex/include/hex/pattern_language/validator.hpp similarity index 89% rename from plugins/libimhex/include/hex/lang/validator.hpp rename to plugins/libimhex/include/hex/pattern_language/validator.hpp index 96d279de2..b693eecab 100644 --- a/plugins/libimhex/include/hex/lang/validator.hpp +++ b/plugins/libimhex/include/hex/pattern_language/validator.hpp @@ -2,13 +2,12 @@ #include -#include "token.hpp" -#include "ast_node.hpp" - #include #include -namespace hex::lang { +namespace hex::pl { + + class ASTNode; class Validator { public: diff --git a/plugins/libimhex/include/hex/views/view.hpp b/plugins/libimhex/include/hex/views/view.hpp index 346a619ec..1727b0f99 100644 --- a/plugins/libimhex/include/hex/views/view.hpp +++ b/plugins/libimhex/include/hex/views/view.hpp @@ -12,6 +12,8 @@ #include #include +#include + #include #include #include @@ -19,6 +21,8 @@ namespace hex { + using namespace hex::lang_literals; + class View { public: explicit View(std::string unlocalizedViewName); @@ -36,8 +40,8 @@ namespace hex { static void drawCommonInterfaces(); - static void showErrorPopup(std::string_view errorMessage); - static void showFatalPopup(std::string_view errorMessage); + static void showErrorPopup(const std::string &errorMessage); + static void showFatalPopup(const std::string &errorMessage); virtual bool hasViewMenuItemEntry(); virtual ImVec2 getMinSize(); @@ -45,15 +49,15 @@ namespace hex { bool& getWindowOpenState(); - std::string_view getUnlocalizedName() const; + const std::string& getUnlocalizedName() const; protected: void discardNavigationRequests(); - void confirmButtons(const char *textLeft, const char *textRight, const std::function &leftButtonFn, const std::function &rightButtonFn); + void confirmButtons(const std::string &textLeft, const std::string &textRight, const std::function &leftButtonFn, const std::function &rightButtonFn); - static inline std::string toWindowName(std::string_view unlocalizedName) { - return LangEntry(unlocalizedName) + "##" + std::string(unlocalizedName); + static inline std::string toWindowName(const std::string &unlocalizedName) { + return LangEntry(unlocalizedName) + "##" + unlocalizedName; } private: diff --git a/plugins/libimhex/source/api/content_registry.cpp b/plugins/libimhex/source/api/content_registry.cpp index 191ac46ec..d9dfdfc19 100644 --- a/plugins/libimhex/source/api/content_registry.cpp +++ b/plugins/libimhex/source/api/content_registry.cpp @@ -39,87 +39,87 @@ namespace hex { } } - void ContentRegistry::Settings::add(std::string_view unlocalizedCategory, std::string_view unlocalizedName, s64 defaultValue, const std::function &callback) { - ContentRegistry::Settings::getEntries()[unlocalizedCategory.data()].emplace_back(Entry{ unlocalizedName.data(), callback }); + void ContentRegistry::Settings::add(const std::string &unlocalizedCategory, const std::string &unlocalizedName, s64 defaultValue, const ContentRegistry::Settings::Callback &callback) { + ContentRegistry::Settings::getEntries()[unlocalizedCategory.c_str()].emplace_back(Entry{ unlocalizedName.c_str(), callback }); auto &json = getSettingsData(); - if (!json.contains(unlocalizedCategory.data())) - json[unlocalizedCategory.data()] = nlohmann::json::object(); - if (!json[unlocalizedCategory.data()].contains(unlocalizedName.data()) || !json[unlocalizedCategory.data()][unlocalizedName.data()].is_number()) - json[unlocalizedCategory.data()][unlocalizedName.data()] = int(defaultValue); + if (!json.contains(unlocalizedCategory)) + json[unlocalizedCategory] = nlohmann::json::object(); + if (!json[unlocalizedCategory].contains(unlocalizedName) || !json[unlocalizedCategory][unlocalizedName].is_number()) + json[unlocalizedCategory][unlocalizedName] = int(defaultValue); } - void ContentRegistry::Settings::add(std::string_view unlocalizedCategory, std::string_view unlocalizedName, std::string_view defaultValue, const std::function &callback) { - ContentRegistry::Settings::getEntries()[unlocalizedCategory.data()].emplace_back(Entry{ unlocalizedName.data(), callback }); + void ContentRegistry::Settings::add(const std::string &unlocalizedCategory, const std::string &unlocalizedName, const std::string &defaultValue, const ContentRegistry::Settings::Callback &callback) { + ContentRegistry::Settings::getEntries()[unlocalizedCategory].emplace_back(Entry{ unlocalizedName, callback }); auto &json = getSettingsData(); - if (!json.contains(unlocalizedCategory.data())) - json[unlocalizedCategory.data()] = nlohmann::json::object(); - if (!json[unlocalizedCategory.data()].contains(unlocalizedName.data()) || !json[unlocalizedCategory.data()][unlocalizedName.data()].is_string()) - json[unlocalizedCategory.data()][unlocalizedName.data()] = std::string(defaultValue); + if (!json.contains(unlocalizedCategory)) + json[unlocalizedCategory] = nlohmann::json::object(); + if (!json[unlocalizedCategory].contains(unlocalizedName) || !json[unlocalizedCategory][unlocalizedName].is_string()) + json[unlocalizedCategory][unlocalizedName] = std::string(defaultValue); } - void ContentRegistry::Settings::write(std::string_view unlocalizedCategory, std::string_view unlocalizedName, s64 value) { + void ContentRegistry::Settings::write(const std::string &unlocalizedCategory, const std::string &unlocalizedName, s64 value) { auto &json = getSettingsData(); - if (!json.contains(unlocalizedCategory.data())) - json[unlocalizedCategory.data()] = nlohmann::json::object(); + if (!json.contains(unlocalizedCategory)) + json[unlocalizedCategory] = nlohmann::json::object(); - json[unlocalizedCategory.data()][unlocalizedName.data()] = value; + json[unlocalizedCategory][unlocalizedName] = value; } - void ContentRegistry::Settings::write(std::string_view unlocalizedCategory, std::string_view unlocalizedName, std::string_view value) { + void ContentRegistry::Settings::write(const std::string &unlocalizedCategory, const std::string &unlocalizedName, const std::string &value) { auto &json = getSettingsData(); - if (!json.contains(unlocalizedCategory.data())) - json[unlocalizedCategory.data()] = nlohmann::json::object(); + if (!json.contains(unlocalizedCategory)) + json[unlocalizedCategory] = nlohmann::json::object(); - json[unlocalizedCategory.data()][unlocalizedName.data()] = value; + json[unlocalizedCategory][unlocalizedName] = value; } - void ContentRegistry::Settings::write(std::string_view unlocalizedCategory, std::string_view unlocalizedName, const std::vector& value) { + void ContentRegistry::Settings::write(const std::string &unlocalizedCategory, const std::string &unlocalizedName, const std::vector& value) { auto &json = getSettingsData(); - if (!json.contains(unlocalizedCategory.data())) - json[unlocalizedCategory.data()] = nlohmann::json::object(); + if (!json.contains(unlocalizedCategory)) + json[unlocalizedCategory] = nlohmann::json::object(); - json[unlocalizedCategory.data()][unlocalizedName.data()] = value; + json[unlocalizedCategory][unlocalizedName] = value; } - s64 ContentRegistry::Settings::read(std::string_view unlocalizedCategory, std::string_view unlocalizedName, s64 defaultValue) { + s64 ContentRegistry::Settings::read(const std::string &unlocalizedCategory, const std::string &unlocalizedName, s64 defaultValue) { auto &json = getSettingsData(); - if (!json.contains(unlocalizedCategory.data())) + if (!json.contains(unlocalizedCategory)) return defaultValue; - if (!json[unlocalizedCategory.data()].contains(unlocalizedName.data())) + if (!json[unlocalizedCategory].contains(unlocalizedName)) return defaultValue; - return json[unlocalizedCategory.data()][unlocalizedName.data()].get(); + return json[unlocalizedCategory][unlocalizedName].get(); } - std::string ContentRegistry::Settings::read(std::string_view unlocalizedCategory, std::string_view unlocalizedName, std::string_view defaultValue) { + std::string ContentRegistry::Settings::read(const std::string &unlocalizedCategory, const std::string &unlocalizedName, const std::string &defaultValue) { auto &json = getSettingsData(); - if (!json.contains(unlocalizedCategory.data())) - return defaultValue.data(); - if (!json[unlocalizedCategory.data()].contains(unlocalizedName.data())) - return defaultValue.data(); + if (!json.contains(unlocalizedCategory)) + return defaultValue; + if (!json[unlocalizedCategory].contains(unlocalizedName)) + return defaultValue; - return json[unlocalizedCategory.data()][unlocalizedName.data()].get(); + return json[unlocalizedCategory][unlocalizedName].get(); } - std::vector ContentRegistry::Settings::read(std::string_view unlocalizedCategory, std::string_view unlocalizedName, const std::vector& defaultValue) { + std::vector ContentRegistry::Settings::read(const std::string &unlocalizedCategory, const std::string &unlocalizedName, const std::vector& defaultValue) { auto &json = getSettingsData(); - if (!json.contains(unlocalizedCategory.data())) + if (!json.contains(unlocalizedCategory)) return defaultValue; - if (!json[unlocalizedCategory.data()].contains(unlocalizedName.data())) + if (!json[unlocalizedCategory].contains(unlocalizedName)) return defaultValue; - return json[unlocalizedCategory.data()][unlocalizedName.data()].get>(); + return json[unlocalizedCategory][unlocalizedName].get>(); } @@ -127,13 +127,13 @@ namespace hex { return SharedData::settingsEntries; } - nlohmann::json ContentRegistry::Settings::getSetting(std::string_view unlocalizedCategory, std::string_view unlocalizedName) { + nlohmann::json ContentRegistry::Settings::getSetting(const std::string &unlocalizedCategory, const std::string &unlocalizedName) { auto &settings = getSettingsData(); if (!settings.contains(unlocalizedCategory)) return { }; - if (!settings[unlocalizedCategory.data()].contains(unlocalizedName)) return { }; + if (!settings[unlocalizedCategory].contains(unlocalizedName)) return { }; - return settings[unlocalizedCategory.data()][unlocalizedName.data()]; + return settings[unlocalizedCategory][unlocalizedName]; } nlohmann::json& ContentRegistry::Settings::getSettingsData() { @@ -143,8 +143,8 @@ namespace hex { /* Command Palette Commands */ - void ContentRegistry::CommandPaletteCommands::add(ContentRegistry::CommandPaletteCommands::Type type, std::string_view command, std::string_view unlocalizedDescription, const std::function &displayCallback, const std::function &executeCallback) { - getEntries().push_back(ContentRegistry::CommandPaletteCommands::Entry{ type, command.data(), unlocalizedDescription.data(), displayCallback, executeCallback }); + void ContentRegistry::CommandPaletteCommands::add(ContentRegistry::CommandPaletteCommands::Type type, const std::string &command, const std::string &unlocalizedDescription, const std::function &displayCallback, const std::function &executeCallback) { + getEntries().push_back(ContentRegistry::CommandPaletteCommands::Entry{ type, command, unlocalizedDescription, displayCallback, executeCallback }); } std::vector& ContentRegistry::CommandPaletteCommands::getEntries() { @@ -155,7 +155,7 @@ namespace hex { /* Pattern Language Functions */ - void ContentRegistry::PatternLanguageFunctions::add(const Namespace &ns, const std::string &name, u32 parameterCount, const std::function&)> &func) { + void ContentRegistry::PatternLanguageFunctions::add(const Namespace &ns, const std::string &name, u32 parameterCount, const std::function&)> &func) { std::string functionName; for (auto &scope : ns) functionName += scope + "::"; @@ -183,8 +183,8 @@ namespace hex { /* Tools */ - void ContentRegistry::Tools:: add(std::string_view unlocalizedName, const std::function &function) { - getEntries().emplace_back(Entry{ unlocalizedName.data(), function }); + void ContentRegistry::Tools:: add(const std::string &unlocalizedName, const std::function &function) { + getEntries().emplace_back(Entry{ unlocalizedName, function }); } std::vector& ContentRegistry::Tools::getEntries() { @@ -194,8 +194,8 @@ namespace hex { /* Data Inspector */ - void ContentRegistry::DataInspector::add(std::string_view unlocalizedName, size_t requiredSize, ContentRegistry::DataInspector::GeneratorFunction function) { - getEntries().push_back({ unlocalizedName.data(), requiredSize, std::move(function) }); + void ContentRegistry::DataInspector::add(const std::string &unlocalizedName, size_t requiredSize, ContentRegistry::DataInspector::GeneratorFunction function) { + getEntries().push_back({ unlocalizedName, requiredSize, std::move(function) }); } std::vector& ContentRegistry::DataInspector::getEntries() { @@ -218,12 +218,12 @@ namespace hex { /* Languages */ - void ContentRegistry::Language::registerLanguage(std::string_view name, std::string_view languageCode) { - getLanguages().insert({ languageCode.data(), name.data() }); + void ContentRegistry::Language::registerLanguage(const std::string &name, const std::string &languageCode) { + getLanguages().insert({ languageCode, name }); } - void ContentRegistry::Language::addLocalizations(std::string_view languageCode, const LanguageDefinition &definition) { - getLanguageDefinitions()[languageCode.data()].push_back(definition); + void ContentRegistry::Language::addLocalizations(const std::string &languageCode, const LanguageDefinition &definition) { + getLanguageDefinitions()[languageCode].push_back(definition); } std::map& ContentRegistry::Language::getLanguages() { diff --git a/plugins/libimhex/source/api/imhex_api.cpp b/plugins/libimhex/source/api/imhex_api.cpp index 117df8a07..7c51b902e 100644 --- a/plugins/libimhex/source/api/imhex_api.cpp +++ b/plugins/libimhex/source/api/imhex_api.cpp @@ -19,7 +19,7 @@ namespace hex { } - void ImHexApi::Bookmarks::add(Region region, std::string_view name, std::string_view comment, u32 color) { + void ImHexApi::Bookmarks::add(Region region, const std::string &name, const std::string &comment, u32 color) { Entry entry; entry.region = region; @@ -35,7 +35,7 @@ namespace hex { EventManager::post(entry); } - void ImHexApi::Bookmarks::add(u64 addr, size_t size, std::string_view name, std::string_view comment, u32 color) { + void ImHexApi::Bookmarks::add(u64 addr, size_t size, const std::string &name, const std::string &comment, u32 color) { Bookmarks::add(Region{addr, size}, name, comment, color); } diff --git a/plugins/libimhex/source/data_processor/attribute.cpp b/plugins/libimhex/source/data_processor/attribute.cpp index 1121e51c9..9dfff5144 100644 --- a/plugins/libimhex/source/data_processor/attribute.cpp +++ b/plugins/libimhex/source/data_processor/attribute.cpp @@ -4,7 +4,7 @@ namespace hex::dp { - Attribute::Attribute(IOType ioType, Type type, std::string_view unlocalizedName) : m_id(SharedData::dataProcessorAttrIdCounter++), m_ioType(ioType), m_type(type), m_unlocalizedName(unlocalizedName) { + Attribute::Attribute(IOType ioType, Type type, std::string unlocalizedName) : m_id(SharedData::dataProcessorAttrIdCounter++), m_ioType(ioType), m_type(type), m_unlocalizedName(std::move(unlocalizedName)) { } diff --git a/plugins/libimhex/source/data_processor/node.cpp b/plugins/libimhex/source/data_processor/node.cpp index b48e10ba6..1034336b6 100644 --- a/plugins/libimhex/source/data_processor/node.cpp +++ b/plugins/libimhex/source/data_processor/node.cpp @@ -6,7 +6,7 @@ namespace hex::dp { - Node::Node(std::string_view unlocalizedTitle, std::vector attributes) : m_id(SharedData::dataProcessorNodeIdCounter++), m_unlocalizedTitle(unlocalizedTitle), m_attributes(std::move(attributes)) { + Node::Node(std::string unlocalizedTitle, std::vector attributes) : m_id(SharedData::dataProcessorNodeIdCounter++), m_unlocalizedTitle(std::move(unlocalizedTitle)), m_attributes(std::move(attributes)) { for (auto &attr : this->m_attributes) attr.setParentNode(this); } diff --git a/plugins/libimhex/source/helpers/file.cpp b/plugins/libimhex/source/helpers/file.cpp new file mode 100644 index 000000000..94ac0aa01 --- /dev/null +++ b/plugins/libimhex/source/helpers/file.cpp @@ -0,0 +1,59 @@ +#include +#include + +namespace hex { + + File::File(const std::string &path, Mode mode) { + if (mode == File::Mode::Read) + this->m_file = fopen64(path.c_str(), "rb"); + else if (mode == File::Mode::Write) + this->m_file = fopen64(path.c_str(), "r+b"); + + if (mode == File::Mode::Create || this->m_file == nullptr) + this->m_file = fopen64(path.c_str(), "w+b"); + } + + File::~File() { + if (isValid()) + fclose(this->m_file); + } + + void File::seek(u64 offset) { + fseeko64(this->m_file, offset, SEEK_SET); + } + + std::vector File::readBytes(size_t numBytes) { + std::vector bytes(numBytes ?: getSize()); + auto bytesRead = fread(bytes.data(), bytes.size(), 1, this->m_file); + + bytes.resize(bytesRead); + + return bytes; + } + + std::string File::readString(size_t numBytes) { + return reinterpret_cast(readBytes(numBytes).data()); + } + + void File::write(const std::vector &bytes) { + fwrite(bytes.data(), bytes.size(), 1, this->m_file); + } + + void File::write(const std::string &string) { + fwrite(string.data(), string.size(), 1, this->m_file); + } + + size_t File::getSize() { + auto startPos = ftello64(this->m_file); + fseeko64(this->m_file, 0, SEEK_END); + size_t size = ftello64(this->m_file); + fseeko64(this->m_file, startPos, SEEK_SET); + + return size; + } + + void File::setSize(u64 size) { + ftruncate64(fileno(this->m_file), size); + } + +} \ No newline at end of file diff --git a/plugins/libimhex/source/helpers/net.cpp b/plugins/libimhex/source/helpers/net.cpp index dd2b09283..51009188d 100644 --- a/plugins/libimhex/source/helpers/net.cpp +++ b/plugins/libimhex/source/helpers/net.cpp @@ -1,6 +1,7 @@ #include #include +#include #include #include @@ -170,19 +171,15 @@ namespace hex { ON_SCOPE_EXIT { this->m_transmissionActive.unlock(); }; - FILE *file = fopen(filePath.string().c_str(), "rb"); - if (file == nullptr) + File file(filePath.string(), File::Mode::Read); + if (!file.isValid()) return Response { 400, { } }; - fseek(file, 0, SEEK_END); - size_t fileSize = ftell(file); - rewind(file); - curl_mime *mime = curl_mime_init(this->m_ctx); curl_mimepart *part = curl_mime_addpart(mime); auto fileName = filePath.filename().string(); - curl_mime_data_cb(part, fileSize, + curl_mime_data_cb(part, file.getSize(), [](char *buffer, size_t size, size_t nitems, void *arg) -> size_t { auto file = static_cast(arg); return fread(buffer, size, nitems, file); @@ -195,7 +192,7 @@ namespace hex { [](void *arg) { auto file = static_cast(arg); fclose(file); - }, file); + }, file.getHandle()); curl_mime_filename(part, fileName.c_str()); curl_mime_name(part, "file"); @@ -217,16 +214,14 @@ namespace hex { ON_SCOPE_EXIT { this->m_transmissionActive.unlock(); }; - FILE *file = fopen(filePath.string().c_str(), "wb"); - if (file == nullptr) + File file(filePath.string(), File::Mode::Create); + if (!file.isValid()) return Response { 400 }; - ON_SCOPE_EXIT { fclose(file); }; - setCommonSettings(response, url, {}); curl_easy_setopt(this->m_ctx, CURLOPT_CUSTOMREQUEST, "GET"); curl_easy_setopt(this->m_ctx, CURLOPT_WRITEFUNCTION, writeToFile); - curl_easy_setopt(this->m_ctx, CURLOPT_WRITEDATA, file); + curl_easy_setopt(this->m_ctx, CURLOPT_WRITEDATA, file.getHandle()); auto responseCode = execute(); return Response { responseCode.value_or(0) }; diff --git a/plugins/libimhex/source/helpers/paths.cpp b/plugins/libimhex/source/helpers/paths.cpp index 36fe571f0..6ef8e2d5f 100644 --- a/plugins/libimhex/source/helpers/paths.cpp +++ b/plugins/libimhex/source/helpers/paths.cpp @@ -33,7 +33,7 @@ namespace hex { switch (path) { case ImHexPath::Patterns: - return { (parentDir / "patterns").string() }; + return { (parentDir / "pattern_language").string() }; case ImHexPath::PatternsInclude: return { (parentDir / "includes").string() }; case ImHexPath::Magic: diff --git a/plugins/libimhex/source/helpers/shared_data.cpp b/plugins/libimhex/source/helpers/shared_data.cpp index ace133c4e..255aec8ca 100644 --- a/plugins/libimhex/source/helpers/shared_data.cpp +++ b/plugins/libimhex/source/helpers/shared_data.cpp @@ -16,7 +16,7 @@ namespace hex { u32 SharedData::patternPaletteOffset; std::string SharedData::errorPopupMessage; std::list SharedData::bookmarkEntries; - std::vector SharedData::patternData; + std::vector SharedData::patternData; std::map SharedData::languageNames; std::map> SharedData::languageDefinitions; diff --git a/plugins/libimhex/source/helpers/utils.cpp b/plugins/libimhex/source/helpers/utils.cpp index 38403fb93..d2107059f 100644 --- a/plugins/libimhex/source/helpers/utils.cpp +++ b/plugins/libimhex/source/helpers/utils.cpp @@ -110,12 +110,12 @@ namespace hex { } } - std::vector splitString(std::string_view string, std::string_view delimiter) { + std::vector splitString(const std::string &string, const std::string &delimiter) { size_t start = 0, end; std::string token; std::vector res; - while ((end = string.find (delimiter, start)) != std::string::npos) { + while ((end = string.find(delimiter, start)) != std::string::npos) { token = string.substr(start, end - start); start = end + delimiter.length(); res.push_back(token); @@ -125,7 +125,7 @@ namespace hex { return res; } - std::string combineStrings(const std::vector &strings, std::string_view delimiter) { + std::string combineStrings(const std::vector &strings, const std::string &delimiter) { std::string result; for (const auto &string : strings) { result += string; @@ -153,22 +153,6 @@ namespace hex { return std::to_string(value).substr(0, 5) + Suffixes[suffixIndex]; } - std::vector readFile(std::string_view path) { - FILE *file = fopen(path.data(), "rb"); - - if (file == nullptr) return { }; - - std::vector result; - - fseek(file, 0, SEEK_END); - result.resize(ftell(file)); - rewind(file); - - fread(result.data(), 1, result.size(), file); - - return result; - } - void runCommand(const std::string &command) { #if defined(OS_WINDOWS) @@ -200,7 +184,7 @@ namespace hex { } - void openFileBrowser(std::string_view title, DialogMode mode, const std::vector &validExtensions, const std::function &callback) { + void openFileBrowser(const std::string &title, DialogMode mode, const std::vector &validExtensions, const std::function &callback) { NFD::Init(); nfdchar_t *outPath; diff --git a/plugins/libimhex/source/lang/evaluator.cpp b/plugins/libimhex/source/pattern_language/evaluator.cpp similarity index 99% rename from plugins/libimhex/source/lang/evaluator.cpp rename to plugins/libimhex/source/pattern_language/evaluator.cpp index 67cce0eb8..f65dcc90f 100644 --- a/plugins/libimhex/source/lang/evaluator.cpp +++ b/plugins/libimhex/source/pattern_language/evaluator.cpp @@ -1,17 +1,17 @@ -#include +#include #include #include -#include -#include +#include +#include #include #include #include -namespace hex::lang { +namespace hex::pl { ASTNodeIntegerLiteral* Evaluator::evaluateScopeResolution(ASTNodeScopeResolution *node) { ASTNode *currScope = nullptr; @@ -471,7 +471,7 @@ namespace hex::lang { return evaluateOperator(leftInteger, rightInteger, node->getOperator()); } - void Evaluator::createLocalVariable(std::string_view varName, PatternData *pattern) { + void Evaluator::createLocalVariable(const std::string &varName, PatternData *pattern) { auto startOffset = this->m_currOffset; ON_SCOPE_EXIT { this->m_currOffset = startOffset; }; @@ -492,7 +492,7 @@ namespace hex::lang { } - void Evaluator::setLocalVariableValue(std::string_view varName, const void *value, size_t size) { + void Evaluator::setLocalVariableValue(const std::string &varName, const void *value, size_t size) { PatternData *varPattern = nullptr; for (auto &var : *this->m_localVariables.back()) { if (var->getVariableName() == varName) diff --git a/plugins/libimhex/source/lang/lexer.cpp b/plugins/libimhex/source/pattern_language/lexer.cpp similarity index 97% rename from plugins/libimhex/source/lang/lexer.cpp rename to plugins/libimhex/source/pattern_language/lexer.cpp index 15d20f811..1d06fabe4 100644 --- a/plugins/libimhex/source/lang/lexer.cpp +++ b/plugins/libimhex/source/pattern_language/lexer.cpp @@ -1,17 +1,15 @@ -#include +#include #include #include #include #include -namespace hex::lang { +namespace hex::pl { #define TOKEN(type, value) Token::Type::type, Token::type::value, lineNumber #define VALUE_TOKEN(type, value) Token::Type::type, value, lineNumber - Lexer::Lexer() { } - std::string matchTillInvalid(const char* characters, std::function predicate) { std::string ret; @@ -26,18 +24,18 @@ namespace hex::lang { return ret; } - size_t getIntegerLiteralLength(std::string_view string) { + size_t getIntegerLiteralLength(const std::string &string) { return string.find_first_not_of("0123456789ABCDEFabcdef.xUL"); } - std::optional parseIntegerLiteral(std::string_view string) { + std::optional parseIntegerLiteral(const std::string &string) { Token::ValueType type = Token::ValueType::Any; Token::IntegerLiteral result; u8 base; auto endPos = getIntegerLiteralLength(string); - std::string_view numberData = string.substr(0, endPos); + auto numberData = std::string_view(string).substr(0, endPos); if (numberData.ends_with('U')) { type = Token::ValueType::Unsigned32Bit; @@ -143,7 +141,7 @@ namespace hex::lang { return { }; } - std::optional> getCharacter(std::string_view string) { + std::optional> getCharacter(const std::string &string) { if (string.length() < 1) return { }; @@ -194,7 +192,7 @@ namespace hex::lang { } else return {{ string[0], 1 }}; } - std::optional> getStringLiteral(std::string_view string) { + std::optional> getStringLiteral(const std::string &string) { if (!string.starts_with('\"')) return { }; @@ -219,7 +217,7 @@ namespace hex::lang { return {{ result, size + 1 }}; } - std::optional> getCharacterLiteral(std::string_view string) { + std::optional> getCharacterLiteral(const std::string &string) { if (string.empty()) return { }; diff --git a/plugins/libimhex/source/lang/parser.cpp b/plugins/libimhex/source/pattern_language/parser.cpp similarity index 99% rename from plugins/libimhex/source/lang/parser.cpp rename to plugins/libimhex/source/pattern_language/parser.cpp index 8c25be33e..582fd06d7 100644 --- a/plugins/libimhex/source/lang/parser.cpp +++ b/plugins/libimhex/source/pattern_language/parser.cpp @@ -1,4 +1,4 @@ -#include +#include #include @@ -15,7 +15,7 @@ // : One or more of A // A B C : Sequence of tokens A then B then C // (parseXXXX) : Parsing handled by other function -namespace hex::lang { +namespace hex::pl { /* Mathematical expressions */ diff --git a/plugins/libimhex/source/lang/pattern_language.cpp b/plugins/libimhex/source/pattern_language/pattern_language.cpp similarity index 82% rename from plugins/libimhex/source/lang/pattern_language.cpp rename to plugins/libimhex/source/pattern_language/pattern_language.cpp index 3529fe239..7bb23a61d 100644 --- a/plugins/libimhex/source/lang/pattern_language.cpp +++ b/plugins/libimhex/source/pattern_language/pattern_language.cpp @@ -1,16 +1,17 @@ -#include +#include +#include #include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include #include -namespace hex::lang { +namespace hex::pl { class PatternData; @@ -64,12 +65,12 @@ namespace hex::lang { } - std::optional> PatternLanguage::executeString(prv::Provider *provider, std::string_view string) { + std::optional> PatternLanguage::executeString(prv::Provider *provider, const std::string &string) { this->m_currError.reset(); this->m_evaluator->getConsole().clear(); this->m_evaluator->setProvider(provider); - auto preprocessedCode = this->m_preprocessor->preprocess(string.data()); + auto preprocessedCode = this->m_preprocessor->preprocess(string); if (!preprocessedCode.has_value()) { this->m_currError = this->m_preprocessor->getError(); return { }; @@ -108,21 +109,10 @@ namespace hex::lang { return patternData.value(); } - std::optional> PatternLanguage::executeFile(prv::Provider *provider, std::string_view path) { - FILE *file = fopen(path.data(), "r"); - if (file == nullptr) - return { }; + std::optional> PatternLanguage::executeFile(prv::Provider *provider, const std::string &path) { + File file(path, File::Mode::Read); - fseek(file, 0, SEEK_END); - size_t size = ftell(file); - rewind(file); - - std::string code(size + 1, 0x00); - fread(code.data(), size, 1, file); - - fclose(file); - - return this->executeString(provider, code); + return this->executeString(provider, file.readString()); } diff --git a/plugins/libimhex/source/lang/preprocessor.cpp b/plugins/libimhex/source/pattern_language/preprocessor.cpp similarity index 94% rename from plugins/libimhex/source/lang/preprocessor.cpp rename to plugins/libimhex/source/pattern_language/preprocessor.cpp index a6658980a..982217539 100644 --- a/plugins/libimhex/source/lang/preprocessor.cpp +++ b/plugins/libimhex/source/pattern_language/preprocessor.cpp @@ -1,11 +1,12 @@ -#include +#include #include #include +#include #include -namespace hex::lang { +namespace hex::pl { Preprocessor::Preprocessor() { @@ -62,19 +63,11 @@ namespace hex::lang { includeFile = tempPath; } - FILE *file = fopen(includeFile.c_str(), "r"); - if (file == nullptr) + File file(includeFile, File::Mode::Read); + if (!file.isValid()) throwPreprocessorError(hex::format("{0}: No such file or directory", includeFile.c_str()), lineNumber); - fseek(file, 0, SEEK_END); - size_t size = ftell(file); - char *buffer = new char[size + 1]; - rewind(file); - - fread(buffer, size, 1, file); - buffer[size] = 0x00; - - auto preprocessedInclude = this->preprocess(buffer, false); + auto preprocessedInclude = this->preprocess(file.readString(), false); if (!preprocessedInclude.has_value()) throw this->m_error; @@ -84,10 +77,6 @@ namespace hex::lang { std::replace(content.begin(), content.end(), '\r', ' '); output += content; - - delete[] buffer; - - fclose(file); } else if (code.substr(offset, 6) == "define") { offset += 6; diff --git a/plugins/libimhex/source/lang/validator.cpp b/plugins/libimhex/source/pattern_language/validator.cpp similarity index 95% rename from plugins/libimhex/source/lang/validator.cpp rename to plugins/libimhex/source/pattern_language/validator.cpp index ceca514fb..576aa3bd3 100644 --- a/plugins/libimhex/source/lang/validator.cpp +++ b/plugins/libimhex/source/pattern_language/validator.cpp @@ -1,11 +1,13 @@ -#include +#include + +#include #include #include #include -namespace hex::lang { +namespace hex::pl { Validator::Validator() { diff --git a/plugins/libimhex/source/views/view.cpp b/plugins/libimhex/source/views/view.cpp index 417ab6712..83ee28f35 100644 --- a/plugins/libimhex/source/views/view.cpp +++ b/plugins/libimhex/source/views/view.cpp @@ -10,7 +10,6 @@ namespace hex { - View::View(std::string unlocalizedName) : m_unlocalizedViewName(unlocalizedName) { } void View::drawMenu() { } @@ -48,13 +47,13 @@ namespace hex { } } - void View::showErrorPopup(std::string_view errorMessage) { + void View::showErrorPopup(const std::string &errorMessage) { SharedData::errorPopupMessage = errorMessage; View::doLater([] { ImGui::OpenPopup("hex.common.error"_lang); }); } - void View::showFatalPopup(std::string_view errorMessage) { + void View::showFatalPopup(const std::string &errorMessage) { SharedData::errorPopupMessage = errorMessage; View::doLater([] { ImGui::OpenPopup("hex.common.fatal"_lang); }); @@ -77,7 +76,7 @@ namespace hex { return this->m_windowOpen; } - std::string_view View::getUnlocalizedName() const { + const std::string& View::getUnlocalizedName() const { return this->m_unlocalizedViewName; } @@ -90,14 +89,14 @@ namespace hex { SharedData::deferredCalls.push_back(function); } - void View::confirmButtons(const char *textLeft, const char *textRight, const std::function &leftButtonFn, const std::function &rightButtonFn) { + void View::confirmButtons(const std::string &textLeft, const std::string &textRight, const std::function &leftButtonFn, const std::function &rightButtonFn) { auto width = ImGui::GetWindowWidth(); ImGui::SetCursorPosX(width / 9); - if (ImGui::Button(textLeft, ImVec2(width / 3, 0))) + if (ImGui::Button(textLeft.c_str(), ImVec2(width / 3, 0))) leftButtonFn(); ImGui::SameLine(); ImGui::SetCursorPosX(width / 9 * 5); - if (ImGui::Button(textRight, ImVec2(width / 3, 0))) + if (ImGui::Button(textRight.c_str(), ImVec2(width / 3, 0))) rightButtonFn(); } diff --git a/plugins/windows/source/lang/en_US.cpp b/plugins/windows/source/lang/en_US.cpp index 50a74581f..aa697ee25 100644 --- a/plugins/windows/source/lang/en_US.cpp +++ b/plugins/windows/source/lang/en_US.cpp @@ -1,4 +1,5 @@ #include +#include namespace hex::plugin::windows { diff --git a/source/helpers/encoding_file.cpp b/source/helpers/encoding_file.cpp index 3f252a77d..bc1c7b65d 100644 --- a/source/helpers/encoding_file.cpp +++ b/source/helpers/encoding_file.cpp @@ -1,13 +1,14 @@ #include "helpers/encoding_file.hpp" +#include #include #include namespace hex { - EncodingFile::EncodingFile(Type type, std::string_view path) { - std::ifstream encodingFile(path.data()); + EncodingFile::EncodingFile(Type type, const std::string &path) { + std::ifstream encodingFile(path.c_str()); switch (type) { case Type::Thingy: parseThingyFile(encodingFile); break; @@ -16,9 +17,7 @@ namespace hex { } std::pair EncodingFile::getEncodingFor(const std::vector &buffer) const { - for (auto iter = this->m_mapping.rbegin(); iter != this->m_mapping.rend(); iter++) { - auto &[size, mapping] = *iter; - + for (const auto &[size, mapping] : this->m_mapping | std::views::reverse) { if (size > buffer.size()) continue; auto key = std::vector(buffer.begin(), buffer.begin() + size); diff --git a/source/helpers/loader_script_handler.cpp b/source/helpers/loader_script_handler.cpp index 77146555e..d2c582cdd 100644 --- a/source/helpers/loader_script_handler.cpp +++ b/source/helpers/loader_script_handler.cpp @@ -2,6 +2,7 @@ #include #include +#include #include #include @@ -177,7 +178,7 @@ namespace hex { return createStructureType("union", args); } - bool LoaderScript::processFile(std::string_view scriptPath) { + bool LoaderScript::processFile(const std::string &scriptPath) { Py_SetProgramName(Py_DecodeLocale((SharedData::mainArgv)[0], nullptr)); for (const auto &dir : hex::getPath(ImHexPath::Python)) { @@ -218,10 +219,8 @@ namespace hex { PyList_Insert(sysPath, 0, path); } - FILE *scriptFile = fopen(scriptPath.data(), "r"); - PyRun_SimpleFile(scriptFile, scriptPath.data()); - - fclose(scriptFile); + File scriptFile(scriptPath, File::Mode::Read); + PyRun_SimpleFile(scriptFile.getHandle(), scriptPath.c_str()); Py_Finalize(); diff --git a/source/helpers/patches.cpp b/source/helpers/patches.cpp index 0b13f9d22..50ca4fd17 100644 --- a/source/helpers/patches.cpp +++ b/source/helpers/patches.cpp @@ -8,10 +8,8 @@ namespace hex { - static void pushBytesBack(std::vector &buffer, const char* bytes) { - std::string_view string(bytes); - buffer.resize(buffer.size() + string.length()); - std::memcpy((&buffer.back() - string.length()) + 1, string.begin(), string.length()); + static void pushBytesBack(std::vector &buffer, const std::string &string) { + std::copy(string.begin(), string.end(), std::back_inserter(buffer)); } template diff --git a/source/helpers/plugin_manager.cpp b/source/helpers/plugin_manager.cpp index 78167c209..8514ec591 100644 --- a/source/helpers/plugin_manager.cpp +++ b/source/helpers/plugin_manager.cpp @@ -15,7 +15,7 @@ namespace hex { constexpr auto GetPluginDescriptionSymbol = "_ZN3hex6plugin{0}{1}8internal20getPluginDescriptionEv"; constexpr auto SetImGuiContextSymbol = "_ZN3hex6plugin{0}{1}8internal15setImGuiContextEP12ImGuiContext"; - Plugin::Plugin(std::string_view path) { + Plugin::Plugin(const std::string &path) { this->m_handle = dlopen(path.data(), RTLD_LAZY); if (this->m_handle == nullptr) { @@ -84,7 +84,7 @@ namespace hex { this->m_setImGuiContextFunction(ctx); } - bool PluginManager::load(std::string_view pluginFolder) { + bool PluginManager::load(const std::string &pluginFolder) { if (!std::filesystem::exists(pluginFolder)) return false; diff --git a/source/helpers/project_file_handler.cpp b/source/helpers/project_file_handler.cpp index dab4a0374..eef288ed2 100644 --- a/source/helpers/project_file_handler.cpp +++ b/source/helpers/project_file_handler.cpp @@ -27,13 +27,13 @@ namespace hex { } - bool ProjectFile::load(std::string_view filePath) { + bool ProjectFile::load(const std::string &filePath) { ProjectFile::s_hasUnsavedChanged = false; json projectFileData; try { - std::ifstream projectFile(filePath.data()); + std::ifstream projectFile(filePath.c_str()); projectFile >> projectFileData; ProjectFile::s_filePath = projectFileData["filePath"]; @@ -56,7 +56,7 @@ namespace hex { return true; } - bool ProjectFile::store(std::string_view filePath) { + bool ProjectFile::store(std::string filePath) { EventManager::post(); json projectFileData; @@ -74,7 +74,7 @@ namespace hex { projectFileData["bookmarks"].push_back(bookmark); } - std::ofstream projectFile(filePath.data(), std::fstream::trunc); + std::ofstream projectFile(filePath.c_str(), std::fstream::trunc); projectFile << projectFileData; } catch (json::exception &e) { return false; diff --git a/source/init/tasks.cpp b/source/init/tasks.cpp index 9bcbab126..d1f47872e 100644 --- a/source/init/tasks.cpp +++ b/source/init/tasks.cpp @@ -5,7 +5,7 @@ #include #include -#include +#include #include #include diff --git a/source/main.cpp b/source/main.cpp index 2902b1000..4c365db7f 100644 --- a/source/main.cpp +++ b/source/main.cpp @@ -8,6 +8,8 @@ #include "init/splash_window.hpp" #include "init/tasks.hpp" +#include + int main(int argc, char **argv) { using namespace hex; @@ -37,7 +39,7 @@ int main(int argc, char **argv) { if (argc == 1) ; // No arguments provided else if (argc == 2) - EventManager::post(argv[1]); + EventManager::post(argv[1]); else { hex::log::fatal("Usage: imhex [file_name]"); return EXIT_FAILURE; diff --git a/source/providers/file_provider.cpp b/source/providers/file_provider.cpp index 154fad18d..93f63083f 100644 --- a/source/providers/file_provider.cpp +++ b/source/providers/file_provider.cpp @@ -1,19 +1,15 @@ #include "providers/file_provider.hpp" -#include +#include #include #include +#include #include "helpers/project_file_handler.hpp" -#if defined(OS_WINDOWS) -#include -#include -#endif - namespace hex::prv { - FileProvider::FileProvider(std::string_view path) : Provider(), m_path(path) { + FileProvider::FileProvider(std::string path) : Provider(), m_path(std::move(path)) { this->open(); } @@ -92,24 +88,20 @@ namespace hex::prv { } void FileProvider::saveAs(const std::string &path) { - FILE *file = fopen(path.c_str(), "wb"); + File file(path, File::Mode::Create); - if (file != nullptr) { - std::vector buffer(0xFF'FFFF, 0x00); + if (file.isValid()) { + std::vector buffer(std::min(0xFF'FFFF, file.getSize()), 0x00); size_t bufferSize = buffer.size(); - fseek(file, 0, SEEK_SET); - auto provider = SharedData::currentProvider; for (u64 offset = 0; offset < provider->getActualSize(); offset += bufferSize) { if (bufferSize > provider->getActualSize() - offset) bufferSize = provider->getActualSize() - offset; provider->readRelative(offset, buffer.data(), bufferSize); - fwrite(buffer.data(), 1, bufferSize, file); + file.write(buffer); } - - fclose(file); } } @@ -175,7 +167,7 @@ namespace hex::prv { { auto length = this->m_path.length() + 1; auto wideLength = MultiByteToWideChar(CP_UTF8, 0, this->m_path.data(), length, 0, 0); - wchar_t* buffer = new wchar_t[wideLength]; + auto buffer = new wchar_t[wideLength]; MultiByteToWideChar(CP_UTF8, 0, this->m_path.data(), length, buffer, wideLength); widePath = buffer; delete[] buffer; diff --git a/source/views/view_command_palette.cpp b/source/views/view_command_palette.cpp index 25852fb07..380c4e785 100644 --- a/source/views/view_command_palette.cpp +++ b/source/views/view_command_palette.cpp @@ -80,8 +80,8 @@ namespace hex { return false; } - std::vector ViewCommandPalette::getCommandResults(std::string_view input) { - constexpr auto MatchCommand = [](std::string_view currCommand, std::string_view commandToMatch) -> std::pair { + std::vector ViewCommandPalette::getCommandResults(const std::string &input) { + constexpr auto MatchCommand = [](const std::string &currCommand, const std::string &commandToMatch) -> std::pair { if (currCommand.empty()) { return { MatchType::InfoMatch, "" }; } @@ -114,7 +114,7 @@ namespace hex { if (match != MatchType::PerfectMatch) results.push_back({ command + " (" + LangEntry(unlocalizedDescription) + ")", "", AutoComplete }); else { - auto matchedCommand = input.substr(command.length()).data(); + auto matchedCommand = input.substr(command.length()); results.push_back({ displayCallback(matchedCommand), matchedCommand, executeCallback }); } } @@ -123,7 +123,7 @@ namespace hex { if (match != MatchType::PerfectMatch) results.push_back({ command + " (" + LangEntry(unlocalizedDescription) + ")", "", AutoComplete }); else { - auto matchedCommand = input.substr(command.length() + 1).data(); + auto matchedCommand = input.substr(command.length() + 1); results.push_back({ displayCallback(matchedCommand), matchedCommand, executeCallback }); } } diff --git a/source/views/view_data_processor.cpp b/source/views/view_data_processor.cpp index 421ef839d..20640cdae 100644 --- a/source/views/view_data_processor.cpp +++ b/source/views/view_data_processor.cpp @@ -412,7 +412,7 @@ namespace hex { return output.dump(); } - void ViewDataProcessor::loadNodes(std::string_view data) { + void ViewDataProcessor::loadNodes(const std::string &data) { using json = nlohmann::json; json input = json::parse(data); diff --git a/source/views/view_help.cpp b/source/views/view_help.cpp index e72cf205f..d1f7aaa38 100644 --- a/source/views/view_help.cpp +++ b/source/views/view_help.cpp @@ -87,7 +87,7 @@ namespace hex { } ImGui::NewLine(); - const auto Link = [](std::string_view label, std::string_view url) { + const auto Link = [](const std::string &label, const std::string &url) { if (ImGui::BulletHyperlink(label.data())) hex::openWebpage(url.data()); }; diff --git a/source/views/view_hexeditor.cpp b/source/views/view_hexeditor.cpp index aa25c466b..9ddad85c7 100644 --- a/source/views/view_hexeditor.cpp +++ b/source/views/view_hexeditor.cpp @@ -3,7 +3,8 @@ #include #include #include -#include +#include +#include #include "providers/file_provider.hpp" #include "helpers/patches.hpp" @@ -137,7 +138,7 @@ namespace hex { return { std::string(decoded), advance, color }; }; - EventManager::subscribe(this, [this](const std::string &filePath) { + EventManager::subscribe(this, [this](const std::string &filePath) { this->openFile(filePath); this->getWindowOpenState() = true; }); @@ -159,7 +160,7 @@ namespace hex { }); EventManager::subscribe(this, []() { - EventManager::post(ProjectFile::getFilePath()); + EventManager::post(ProjectFile::getFilePath()); }); EventManager::subscribe(this, [](GLFWwindow *window) { @@ -184,12 +185,13 @@ namespace hex { View::showErrorPopup("hex.view.hexeditor.error.create"_lang); return; } - this->openFile(path); + + EventManager::post(path); this->getWindowOpenState() = true; }); } else if (name == "Open File") { hex::openFileBrowser("hex.view.hexeditor.open_file"_lang, DialogMode::Open, { }, [this](auto path) { - this->openFile(path); + EventManager::post(path); this->getWindowOpenState() = true; }); } else if (name == "Open Project") { @@ -217,7 +219,7 @@ namespace hex { } ViewHexEditor::~ViewHexEditor() { - EventManager::unsubscribe(this); + EventManager::unsubscribe(this); EventManager::unsubscribe(this); EventManager::unsubscribe(this); EventManager::unsubscribe(this); @@ -331,7 +333,7 @@ namespace hex { confirmButtons("hex.common.load"_lang, "hex.common.cancel"_lang, [this, &provider] { if (!this->m_loaderScriptScriptPath.empty() && !this->m_loaderScriptFilePath.empty()) { - EventManager::post(this->m_loaderScriptFilePath); + EventManager::post(this->m_loaderScriptFilePath); LoaderScript::setFilePath(this->m_loaderScriptFilePath); LoaderScript::setDataProvider(provider); LoaderScript::processFile(this->m_loaderScriptScriptPath); @@ -391,14 +393,14 @@ namespace hex { if (ImGui::MenuItem("hex.view.hexeditor.menu.file.open_file"_lang, "CTRL + O")) { hex::openFileBrowser("hex.view.hexeditor.open_file"_lang, DialogMode::Open, { }, [this](auto path) { - EventManager::post(path); + EventManager::post(path); }); } if (ImGui::BeginMenu("hex.view.hexeditor.menu.file.open_recent"_lang, !SharedData::recentFilePaths.empty())) { for (auto &path : SharedData::recentFilePaths) { if (ImGui::MenuItem(std::filesystem::path(path).filename().string().c_str())) { - EventManager::post(path); + EventManager::post(path); } } @@ -475,7 +477,7 @@ namespace hex { if (ImGui::MenuItem("hex.view.hexeditor.menu.file.import.ips"_lang)) { hex::openFileBrowser("hex.view.hexeditor.open_file"_lang, DialogMode::Open, { }, [this](auto path) { - auto patchData = hex::readFile(path); + auto patchData = File(path, File::Mode::Read).readBytes(); auto patch = hex::loadIPSPatch(patchData); for (auto &[address, value] : patch) { @@ -489,7 +491,7 @@ namespace hex { if (ImGui::MenuItem("hex.view.hexeditor.menu.file.import.ips32"_lang)) { hex::openFileBrowser("hex.view.hexeditor.open_file"_lang, DialogMode::Open, { }, [this](auto path) { - auto patchData = hex::readFile(path); + auto patchData = File(path, File::Mode::Read).readBytes(); auto patch = hex::loadIPS32Patch(patchData); for (auto &[address, value] : patch) { @@ -610,7 +612,7 @@ namespace hex { return false; } - bool ViewHexEditor::createFile(std::string_view path) { + bool ViewHexEditor::createFile(const std::string &path) { #if defined(OS_WINDOWS) std::wstring widePath; { @@ -644,7 +646,7 @@ namespace hex { return true; } - void ViewHexEditor::openFile(std::string_view path) { + void ViewHexEditor::openFile(const std::string &path) { auto& provider = SharedData::currentProvider; delete provider; @@ -669,41 +671,24 @@ namespace hex { this->getWindowOpenState() = true; - EventManager::post(std::string(path)); + EventManager::post(path); EventManager::post(); EventManager::post(); } - bool ViewHexEditor::saveToFile(std::string_view path, const std::vector& data) { - FILE *file = fopen(path.data(), "wb"); - - if (file == nullptr) - return false; - - fwrite(data.data(), 1, data.size(), file); - fclose(file); + bool ViewHexEditor::saveToFile(const std::string &path, const std::vector& data) { + File(path, File::Mode::Create).write(data); return true; } - bool ViewHexEditor::loadFromFile(std::string_view path, std::vector& data) { - FILE *file = fopen(path.data(), "rb"); - - if (file == nullptr) - return false; - - fseek(file, 0, SEEK_END); - size_t size = ftello64(file); - rewind(file); - - data.resize(size); - fread(data.data(), 1, data.size(), file); - fclose(file); + bool ViewHexEditor::loadFromFile(const std::string &path, std::vector& data) { + data = File(path, File::Mode::Read).readBytes(); return true; } - void ViewHexEditor::copyBytes() { + void ViewHexEditor::copyBytes() const { auto provider = SharedData::currentProvider; size_t start = std::min(this->m_memoryEditor.DataPreviewAddr, this->m_memoryEditor.DataPreviewAddrEnd); @@ -722,7 +707,7 @@ namespace hex { ImGui::SetClipboardText(str.c_str()); } - void ViewHexEditor::pasteBytes() { + void ViewHexEditor::pasteBytes() const { auto provider = SharedData::currentProvider; size_t start = std::min(this->m_memoryEditor.DataPreviewAddr, this->m_memoryEditor.DataPreviewAddrEnd); @@ -764,7 +749,7 @@ namespace hex { provider->writeRelative(start, buffer.data(), std::min(end - start + 1, buffer.size())); } - void ViewHexEditor::copyString() { + void ViewHexEditor::copyString() const { auto provider = SharedData::currentProvider; size_t start = std::min(this->m_memoryEditor.DataPreviewAddr, this->m_memoryEditor.DataPreviewAddrEnd); @@ -779,7 +764,7 @@ namespace hex { ImGui::SetClipboardText(buffer.c_str()); } - void ViewHexEditor::copyLanguageArray(Language language) { + void ViewHexEditor::copyLanguageArray(Language language) const { auto provider = SharedData::currentProvider; size_t start = std::min(this->m_memoryEditor.DataPreviewAddr, this->m_memoryEditor.DataPreviewAddrEnd); @@ -881,7 +866,7 @@ namespace hex { ImGui::SetClipboardText(str.c_str()); } - void ViewHexEditor::copyHexView() { + void ViewHexEditor::copyHexView() const { auto provider = SharedData::currentProvider; size_t start = std::min(this->m_memoryEditor.DataPreviewAddr, this->m_memoryEditor.DataPreviewAddrEnd); @@ -928,7 +913,7 @@ namespace hex { ImGui::SetClipboardText(str.c_str()); } - void ViewHexEditor::copyHexViewHTML() { + void ViewHexEditor::copyHexViewHTML() const { auto provider = SharedData::currentProvider; size_t start = std::min(this->m_memoryEditor.DataPreviewAddr, this->m_memoryEditor.DataPreviewAddrEnd); @@ -1067,7 +1052,7 @@ R"( *_this->m_lastSearchBuffer = _this->m_searchFunction(provider, data->Buf); _this->m_lastSearchIndex = 0; - if (_this->m_lastSearchBuffer->size() > 0) + if (!_this->m_lastSearchBuffer->empty()) _this->m_memoryEditor.GotoAddrAndSelect((*_this->m_lastSearchBuffer)[0].first, (*_this->m_lastSearchBuffer)[0].second); return 0; @@ -1079,12 +1064,12 @@ R"( *this->m_lastSearchBuffer = this->m_searchFunction(provider, buffer); this->m_lastSearchIndex = 0; - if (this->m_lastSearchBuffer->size() > 0) + if (!this->m_lastSearchBuffer->empty()) this->m_memoryEditor.GotoAddrAndSelect((*this->m_lastSearchBuffer)[0].first, (*this->m_lastSearchBuffer)[0].second); }; static auto FindNext = [this]() { - if (this->m_lastSearchBuffer->size() > 0) { + if (!this->m_lastSearchBuffer->empty()) { ++this->m_lastSearchIndex %= this->m_lastSearchBuffer->size(); this->m_memoryEditor.GotoAddrAndSelect((*this->m_lastSearchBuffer)[this->m_lastSearchIndex].first, (*this->m_lastSearchBuffer)[this->m_lastSearchIndex].second); @@ -1092,7 +1077,7 @@ R"( }; static auto FindPrevious = [this]() { - if (this->m_lastSearchBuffer->size() > 0) { + if (!this->m_lastSearchBuffer->empty()) { this->m_lastSearchIndex--; if (this->m_lastSearchIndex < 0) @@ -1134,7 +1119,7 @@ R"( if (ImGui::Button("hex.view.hexeditor.search.find"_lang)) Find(currBuffer->data()); - if (this->m_lastSearchBuffer->size() > 0) { + if (!this->m_lastSearchBuffer->empty()) { if ((ImGui::Button("hex.view.hexeditor.search.find_next"_lang))) FindNext(); diff --git a/source/views/view_pattern_data.cpp b/source/views/view_pattern_data.cpp index e5d87c2c3..c0d389276 100644 --- a/source/views/view_pattern_data.cpp +++ b/source/views/view_pattern_data.cpp @@ -1,7 +1,7 @@ #include "views/view_pattern_data.hpp" #include -#include +#include namespace hex { @@ -16,7 +16,7 @@ namespace hex { EventManager::unsubscribe(this); } - static bool beginPatternDataTable(prv::Provider* &provider, const std::vector &patterns, std::vector &sortedPatterns) { + static bool beginPatternDataTable(prv::Provider* &provider, const std::vector &patterns, std::vector &sortedPatterns) { if (ImGui::BeginTable("##patterndatatable", 6, ImGuiTableFlags_Borders | ImGuiTableFlags_Resizable | ImGuiTableFlags_Sortable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_RowBg | ImGuiTableFlags_ScrollY)) { ImGui::TableSetupScrollFreeze(0, 1); ImGui::TableSetupColumn("hex.view.pattern_data.name"_lang, 0, -1, ImGui::GetID("name")); @@ -31,8 +31,8 @@ namespace hex { if (sortSpecs->SpecsDirty || sortedPatterns.empty()) { sortedPatterns = patterns; - std::sort(sortedPatterns.begin(), sortedPatterns.end(), [&sortSpecs, &provider](lang::PatternData* left, lang::PatternData* right) -> bool { - return lang::PatternData::sortPatternDataTable(sortSpecs, provider, left, right); + std::sort(sortedPatterns.begin(), sortedPatterns.end(), [&sortSpecs, &provider](pl::PatternData* left, pl::PatternData* right) -> bool { + return pl::PatternData::sortPatternDataTable(sortSpecs, provider, left, right); }); for (auto &pattern : sortedPatterns) diff --git a/source/views/view_pattern_editor.cpp b/source/views/view_pattern_editor.cpp index 924d6781f..3fdd23174 100644 --- a/source/views/view_pattern_editor.cpp +++ b/source/views/view_pattern_editor.cpp @@ -1,10 +1,11 @@ #include "views/view_pattern_editor.hpp" #include "helpers/project_file_handler.hpp" -#include -#include +#include +#include #include #include +#include #include #include @@ -81,7 +82,7 @@ namespace hex { ViewPatternEditor::ViewPatternEditor() : View("hex.view.pattern.name") { - this->m_patternLanguageRuntime = new lang::PatternLanguage(); + this->m_patternLanguageRuntime = new pl::PatternLanguage(); this->m_textEditor.SetLanguageDefinition(PatternLanguage()); this->m_textEditor.SetShowWhitespaces(false); @@ -104,7 +105,7 @@ namespace hex { if (this->m_textEditor.GetText().find_first_not_of(" \f\n\r\t\v") != std::string::npos) return; - lang::Preprocessor preprocessor; + pl::Preprocessor preprocessor; auto provider = SharedData::currentProvider; if (provider == nullptr) @@ -130,20 +131,11 @@ namespace hex { if (!entry.is_regular_file()) continue; - FILE *file = fopen(entry.path().string().c_str(), "r"); - - if (file == nullptr) + File file(entry.path().string(), File::Mode::Read); + if (!file.isValid()) continue; - fseek(file, 0, SEEK_END); - size_t size = ftell(file); - rewind(file); - - std::vector patternBuffer( size + 1, 0x00); - fread(patternBuffer.data(), 1, size, file); - fclose(file); - - preprocessor.preprocess(patternBuffer.data()); + preprocessor.preprocess(file.readString()); if (foundCorrectType) this->m_possiblePatternFiles.push_back(entry.path().string()); @@ -220,16 +212,16 @@ namespace hex { if (ImGui::BeginChild("##console", consoleSize, true, ImGuiWindowFlags_AlwaysVerticalScrollbar)) { for (auto &[level, message] : this->m_console) { switch (level) { - case lang::LogConsole::Level::Debug: + case pl::LogConsole::Level::Debug: ImGui::PushStyleColor(ImGuiCol_Text, this->m_textEditor.GetPalette()[u32(TextEditor::PaletteIndex::Comment)]); break; - case lang::LogConsole::Level::Info: + case pl::LogConsole::Level::Info: ImGui::PushStyleColor(ImGuiCol_Text, this->m_textEditor.GetPalette()[u32(TextEditor::PaletteIndex::Default)]); break; - case lang::LogConsole::Level::Warning: + case pl::LogConsole::Level::Warning: ImGui::PushStyleColor(ImGuiCol_Text, this->m_textEditor.GetPalette()[u32(TextEditor::PaletteIndex::Preprocessor)]); break; - case lang::LogConsole::Level::Error: + case pl::LogConsole::Level::Error: ImGui::PushStyleColor(ImGuiCol_Text, this->m_textEditor.GetPalette()[u32(TextEditor::PaletteIndex::ErrorMarker)]); break; default: continue; @@ -285,7 +277,7 @@ namespace hex { entries[i] = std::filesystem::path(this->m_possiblePatternFiles[i]).filename().string(); } - ImGui::ListBox("hex.view.pattern.accept_pattern.patterns"_lang, &this->m_selectedPatternFile, [](void *data, int id, const char** outText) -> bool { + ImGui::ListBox("hex.view.pattern.accept_pattern.pattern_language"_lang, &this->m_selectedPatternFile, [](void *data, int id, const char** outText) -> bool { auto &entries = *static_cast*>(data); *outText = entries[id].c_str(); @@ -311,8 +303,8 @@ namespace hex { } - void ViewPatternEditor::loadPatternFile(std::string_view path) { - FILE *file = fopen(path.data(), "rb"); + void ViewPatternEditor::loadPatternFile(const std::string &path) { + FILE *file = fopen(path.c_str(), "rb"); if (file != nullptr) { char *buffer; @@ -340,7 +332,7 @@ namespace hex { delete data; SharedData::patternData.clear(); - lang::PatternData::resetPalette(); + pl::PatternData::resetPalette(); } void ViewPatternEditor::parsePattern(char *buffer) { diff --git a/source/views/view_store.cpp b/source/views/view_store.cpp index 2e77698d6..f2106a047 100644 --- a/source/views/view_store.cpp +++ b/source/views/view_store.cpp @@ -34,7 +34,7 @@ namespace hex { auto drawTab = [this](auto title, ImHexPath pathType, auto &content) { if (ImGui::BeginTabItem(title)) { - if (ImGui::BeginTable("##patterns", 3, ImGuiTableFlags_ScrollY | ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingStretchProp)) { + if (ImGui::BeginTable("##pattern_language", 3, ImGuiTableFlags_ScrollY | ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingStretchProp)) { ImGui::TableSetupScrollFreeze(0, 1); ImGui::TableSetupColumn("Name", ImGuiTableColumnFlags_None, 1.0); ImGui::TableSetupColumn("Description", ImGuiTableColumnFlags_None, 3.0); @@ -157,7 +157,7 @@ namespace hex { } }; - parseStoreEntries(json, "patterns", ImHexPath::Patterns, this->m_patterns); + parseStoreEntries(json, "pattern_language", ImHexPath::Patterns, this->m_patterns); parseStoreEntries(json, "includes", ImHexPath::PatternsInclude, this->m_includes); parseStoreEntries(json, "magic", ImHexPath::Magic, this->m_magics); diff --git a/source/views/view_yara.cpp b/source/views/view_yara.cpp index 0fa2d4aca..94c05c502 100644 --- a/source/views/view_yara.cpp +++ b/source/views/view_yara.cpp @@ -2,6 +2,7 @@ #include #include +#include #include #include @@ -137,11 +138,10 @@ namespace hex { YR_COMPILER *compiler = nullptr; yr_compiler_create(&compiler); - FILE *file = fopen(this->m_rules[this->m_selectedRule].c_str(), "r"); - if (file == nullptr) return; - ON_SCOPE_EXIT { fclose(file); }; + File file(this->m_rules[this->m_selectedRule], File::Mode::Read); + if (!file.isValid()) return; - if (yr_compiler_add_file(compiler, file, nullptr, nullptr) != 0) { + if (yr_compiler_add_file(compiler, file.getHandle(), nullptr, nullptr) != 0) { this->m_errorMessage.resize(0xFFFF); yr_compiler_get_error_message(compiler, this->m_errorMessage.data(), this->m_errorMessage.size()); this->m_matching = false; diff --git a/source/window/window.cpp b/source/window/window.cpp index 5689048c3..021eb922d 100644 --- a/source/window/window.cpp +++ b/source/window/window.cpp @@ -154,7 +154,7 @@ namespace hex { } }); - EventManager::subscribe(this, [this](const std::string &path){ + EventManager::subscribe(this, [](const std::string &path){ SharedData::recentFilePaths.push_front(path); { @@ -167,7 +167,7 @@ namespace hex { exists = true; } - if (!exists) + if (!exists && !file.empty()) uniques.push_back(file); if (uniques.size() > 5) @@ -184,6 +184,10 @@ namespace hex { } }); + EventManager::subscribe(this, []{ + EventManager::post(""); + }); + EventManager::subscribe(this, [this](bool noQuestions) { glfwSetWindowShouldClose(this->m_window, true); @@ -193,11 +197,14 @@ namespace hex { EventManager::subscribe(this, [this](std::string windowTitle) { std::string title = "ImHex"; - if (!windowTitle.empty()) - title += " - " + windowTitle; - if (ProjectFile::hasUnsavedChanges()) - title += " (*)"; + if (SharedData::currentProvider != nullptr) { + if (!windowTitle.empty()) + title += " - " + windowTitle; + + if (ProjectFile::hasUnsavedChanges()) + title += " (*)"; + } this->m_windowTitle = title; glfwSetWindowTitle(this->m_window, title.c_str()); @@ -250,8 +257,10 @@ namespace hex { EventManager::unsubscribe(this); EventManager::unsubscribe(this); + EventManager::unsubscribe(this); EventManager::unsubscribe(this); EventManager::unsubscribe(this); + EventManager::unsubscribe(this); ImGui::UnloadImage(this->m_bannerTexture); ImGui::UnloadImage(this->m_logoTexture); @@ -533,7 +542,7 @@ namespace hex { if (!SharedData::recentFilePaths.empty()) { for (auto &path : SharedData::recentFilePaths) { if (ImGui::BulletHyperlink(std::filesystem::path(path).filename().string().c_str())) { - EventManager::post(path); + EventManager::post(path); break; } } @@ -749,7 +758,7 @@ namespace hex { if (count != 1) return; - EventManager::post(paths[0]); + EventManager::post(paths[0]); }); glfwSetWindowCloseCallback(this->m_window, [](GLFWwindow *window) {