diff --git a/.clang-format b/.clang-format new file mode 100644 index 000000000..ee905c1da --- /dev/null +++ b/.clang-format @@ -0,0 +1,178 @@ +--- +Language: Cpp +# BasedOnStyle: LLVM +AccessModifierOffset: -4 +AlignAfterOpenBracket: Align +AlignArrayOfStructures: Left +AlignConsecutiveMacros: Consecutive +AlignConsecutiveAssignments: None +AlignConsecutiveBitFields: AcrossEmptyLinesAndComments +AlignConsecutiveDeclarations: None +AlignEscapedNewlines: Left +AlignOperands: Align +AlignTrailingComments: true +AllowAllArgumentsOnNextLine: true +AllowAllConstructorInitializersOnNextLine: true +AllowAllParametersOfDeclarationOnNextLine: true +AllowShortEnumsOnASingleLine: false +AllowShortBlocksOnASingleLine: Always +AllowShortCaseLabelsOnASingleLine: false +AllowShortFunctionsOnASingleLine: All +AllowShortLambdasOnASingleLine: All +AllowShortIfStatementsOnASingleLine: AllIfsAndElse +AllowShortLoopsOnASingleLine: true +AlwaysBreakAfterDefinitionReturnType: None +AlwaysBreakAfterReturnType: None +AlwaysBreakBeforeMultilineStrings: false +AlwaysBreakTemplateDeclarations: Yes +AttributeMacros: + - __capability +BinPackArguments: false +BinPackParameters: false +BraceWrapping: + AfterCaseLabel: false + AfterClass: false + AfterControlStatement: Never + AfterEnum: false + AfterFunction: false + AfterNamespace: false + AfterObjCDeclaration: false + AfterStruct: false + AfterUnion: false + AfterExternBlock: false + BeforeCatch: false + BeforeElse: false + BeforeLambdaBody: false + BeforeWhile: false + IndentBraces: false + SplitEmptyFunction: false + SplitEmptyRecord: false + SplitEmptyNamespace: false +BreakBeforeBinaryOperators: None +BreakBeforeConceptDeclarations: false +BreakBeforeBraces: Attach +BreakBeforeInheritanceComma: false +BreakInheritanceList: AfterComma +BreakBeforeTernaryOperators: true +BreakConstructorInitializersBeforeComma: false +BreakConstructorInitializers: BeforeColon +BreakAfterJavaFieldAnnotations: false +BreakStringLiterals: false +ColumnLimit: 0 +CommentPragmas: '^ IWYU pragma:' +CompactNamespaces: false +ConstructorInitializerAllOnOneLineOrOnePerLine: false +ConstructorInitializerIndentWidth: 4 +ContinuationIndentWidth: 4 +Cpp11BracedListStyle: false +DeriveLineEnding: true +DerivePointerAlignment: false +DisableFormat: false +EmptyLineAfterAccessModifier: Never +EmptyLineBeforeAccessModifier: LogicalBlock +ExperimentalAutoDetectBinPacking: true +FixNamespaceComments: false +ForEachMacros: + - foreach + - Q_FOREACH + - BOOST_FOREACH +IfMacros: + - KJ_IF_MAYBE +IncludeBlocks: Regroup +IncludeCategories: + - Regex: '^"(llvm|llvm-c|clang|clang-c)/' + Priority: 2 + SortPriority: 0 + CaseSensitive: false + - Regex: '^(<|"(gtest|gmock|isl|json)/)' + Priority: 3 + SortPriority: 0 + CaseSensitive: false + - Regex: '.*' + Priority: 1 + SortPriority: 0 + CaseSensitive: false +IncludeIsMainRegex: '(Test)?$' +IncludeIsMainSourceRegex: '' +IndentAccessModifiers: false +IndentCaseLabels: false +IndentCaseBlocks: true +IndentGotoLabels: true +IndentPPDirectives: BeforeHash +IndentExternBlock: Indent +IndentRequires: false +IndentWidth: 4 +IndentWrappedFunctionNames: false +InsertTrailingCommas: None +JavaScriptQuotes: Leave +JavaScriptWrapImports: true +KeepEmptyLinesAtTheStartOfBlocks: true +LambdaBodyIndentation: Signature +MacroBlockBegin: '' +MacroBlockEnd: '' +MaxEmptyLinesToKeep: 2 +NamespaceIndentation: All +ObjCBinPackProtocolList: Auto +ObjCBlockIndentWidth: 4 +ObjCBreakBeforeNestedBlockParam: true +ObjCSpaceAfterProperty: false +ObjCSpaceBeforeProtocolList: true +PenaltyBreakAssignment: 2 +PenaltyBreakBeforeFirstCallParameter: 19 +PenaltyBreakComment: 300 +PenaltyBreakFirstLessLess: 120 +PenaltyBreakString: 1000 +PenaltyBreakTemplateDeclaration: 10 +PenaltyExcessCharacter: 1000000 +PenaltyReturnTypeOnItsOwnLine: 60 +PenaltyIndentedWhitespace: 0 +PointerAlignment: Right +PPIndentWidth: 4 +ReferenceAlignment: Pointer +ReflowComments: true +ShortNamespaceLines: 5 +SortIncludes: Never +SortJavaStaticImport: Before +SortUsingDeclarations: true +SpaceAfterCStyleCast: false +SpaceAfterLogicalNot: false +SpaceAfterTemplateKeyword: false +SpaceBeforeAssignmentOperators: true +SpaceBeforeCaseColon: false +SpaceBeforeCpp11BracedList: true +SpaceBeforeCtorInitializerColon: true +SpaceBeforeInheritanceColon: true +SpaceBeforeParens: ControlStatements +SpaceAroundPointerQualifiers: Default +SpaceBeforeRangeBasedForLoopColon: true +SpaceInEmptyBlock: true +SpaceInEmptyParentheses: false +SpacesBeforeTrailingComments: 4 +SpacesInAngles: Never +SpacesInConditionalStatement: false +SpacesInContainerLiterals: true +SpacesInCStyleCastParentheses: false +SpacesInLineCommentPrefix: + Minimum: 1 + Maximum: -1 +SpacesInParentheses: false +SpacesInSquareBrackets: false +SpaceBeforeSquareBrackets: false +BitFieldColonSpacing: Both +Standard: Latest +StatementAttributeLikeMacros: + - Q_EMIT +StatementMacros: + - Q_UNUSED + - QT_REQUIRE_VERSION +TabWidth: 4 +UseCRLF: false +UseTab: Never +WhitespaceSensitiveMacros: + - STRINGIZE + - PP_STRINGIZE + - BOOST_PP_STRINGIZE + - NS_SWIFT_NAME + - CF_SWIFT_NAME +... + diff --git a/lib/libimhex/include/hex.hpp b/lib/libimhex/include/hex.hpp index 979bf9b29..d1e67116a 100644 --- a/lib/libimhex/include/hex.hpp +++ b/lib/libimhex/include/hex.hpp @@ -6,17 +6,17 @@ constexpr static const auto ImHexApiURL = "https://api.werwolv.net/imhex"; constexpr static const auto GitHubApiURL = "https://api.github.com/repos/WerWolv/ImHex"; -using u8 = std::uint8_t; -using u16 = std::uint16_t; -using u32 = std::uint32_t; -using u64 = std::uint64_t; -using u128 = __uint128_t; +using u8 = std::uint8_t; +using u16 = std::uint16_t; +using u32 = std::uint32_t; +using u64 = std::uint64_t; +using u128 = __uint128_t; -using i8 = std::int8_t; -using i16 = std::int16_t; -using i32 = std::int32_t; -using i64 = std::int64_t; -using i128 = __int128_t; +using i8 = std::int8_t; +using i16 = std::int16_t; +using i32 = std::int32_t; +using i64 = std::int64_t; +using i128 = __int128_t; namespace hex { @@ -26,4 +26,3 @@ namespace hex { }; } - diff --git a/lib/libimhex/include/hex/api/content_registry.hpp b/lib/libimhex/include/hex/api/content_registry.hpp index e7d792224..182db8c88 100644 --- a/lib/libimhex/include/hex/api/content_registry.hpp +++ b/lib/libimhex/include/hex/api/content_registry.hpp @@ -20,9 +20,15 @@ namespace hex { class View; class LanguageDefinition; - namespace pl { class Evaluator; } - namespace dp { class Node; } - namespace prv { class Provider; } + namespace pl { + class Evaluator; + } + namespace dp { + class Node; + } + namespace prv { + class Provider; + } /* The Content Registry is the heart of all features in ImHex that are in some way extendable by Plugins. @@ -33,7 +39,7 @@ namespace hex { /* Settings Registry. Allows adding of new entries into the ImHex preferences window. */ namespace Settings { - using Callback = std::function; + using Callback = std::function; struct Entry { std::string name; @@ -48,15 +54,15 @@ namespace hex { void write(const std::string &unlocalizedCategory, const std::string &unlocalizedName, i64 value); void write(const std::string &unlocalizedCategory, const std::string &unlocalizedName, const std::string &value); - void write(const std::string &unlocalizedCategory, const std::string &unlocalizedName, const std::vector& value); + void write(const std::string &unlocalizedCategory, const std::string &unlocalizedName, const std::vector &value); i64 read(const std::string &unlocalizedCategory, const std::string &unlocalizedName, i64 defaultValue); std::string read(const std::string &unlocalizedCategory, const std::string &unlocalizedName, const std::string &defaultValue); - std::vector read(const std::string &unlocalizedCategory, const std::string &unlocalizedName, const std::vector& defaultValue = { }); + std::vector read(const std::string &unlocalizedCategory, const std::string &unlocalizedName, const std::vector &defaultValue = {}); - std::map>& getEntries(); + std::map> &getEntries(); nlohmann::json getSetting(const std::string &unlocalizedCategory, const std::string &unlocalizedName); - nlohmann::json& getSettingsData(); + nlohmann::json &getSettingsData(); } /* Command Palette Command Registry. Allows adding of new commands to the command palette */ @@ -78,20 +84,21 @@ namespace hex { ExecuteCallback executeCallback; }; - void add(Type type, const std::string &command, const std::string &unlocalizedDescription, const DisplayCallback &displayCallback, const ExecuteCallback &executeCallback = [](auto){}); - std::vector& getEntries(); + void add( + Type type, const std::string &command, const std::string &unlocalizedDescription, const DisplayCallback &displayCallback, const ExecuteCallback &executeCallback = [](auto) {}); + std::vector &getEntries(); } /* Pattern Language Function Registry. Allows adding of new functions that may be used inside the pattern language */ namespace PatternLanguage { - constexpr static u32 UnlimitedParameters = 0xFFFF'FFFF; - constexpr static u32 MoreParametersThan = 0x8000'0000; - constexpr static u32 LessParametersThan = 0x4000'0000; - constexpr static u32 NoParameters = 0x0000'0000; + constexpr static u32 UnlimitedParameters = 0xFFFF'FFFF; + constexpr static u32 MoreParametersThan = 0x8000'0000; + constexpr static u32 LessParametersThan = 0x4000'0000; + constexpr static u32 NoParameters = 0x0000'0000; using Namespace = std::vector; - using Callback = std::function(hex::pl::Evaluator*, const std::vector&)>; + using Callback = std::function(hex::pl::Evaluator *, const std::vector &)>; struct Function { u32 parameterCount; @@ -101,7 +108,7 @@ namespace hex { void addFunction(const Namespace &ns, const std::string &name, u32 parameterCount, const Callback &func); void addDangerousFunction(const Namespace &ns, const std::string &name, u32 parameterCount, const Callback &func); - std::map& getFunctions(); + std::map &getFunctions(); } /* View Registry. Allows adding of new windows */ @@ -113,14 +120,14 @@ namespace hex { } - template T, typename ... Args> - void add(Args&& ... args) { + template T, typename... Args> + void add(Args &&...args) { return impl::add(new T(std::forward(args)...)); } - std::map& getEntries(); + std::map &getEntries(); - View* getViewByName(const std::string &unlocalizedName); + View *getViewByName(const std::string &unlocalizedName); } @@ -140,7 +147,7 @@ namespace hex { void add(const std::string &unlocalizedName, const impl::Callback &function); - std::vector& getEntries(); + std::vector &getEntries(); } /* Data Inspector Registry. Allows adding of new types to the data inspector */ @@ -155,7 +162,7 @@ namespace hex { namespace impl { using DisplayFunction = std::function; - using GeneratorFunction = std::function&, std::endian, NumberDisplayStyle)>; + using GeneratorFunction = std::function &, std::endian, NumberDisplayStyle)>; struct Entry { std::string unlocalizedName; @@ -167,7 +174,7 @@ namespace hex { void add(const std::string &unlocalizedName, size_t requiredSize, impl::GeneratorFunction function); - std::vector& getEntries(); + std::vector &getEntries(); } /* Data Processor Node Registry. Allows adding new processor nodes to be used in the data processor */ @@ -175,7 +182,7 @@ namespace hex { namespace impl { - using CreatorFunction = std::function; + using CreatorFunction = std::function; struct Entry { std::string category; @@ -188,20 +195,18 @@ namespace hex { } - template T, typename ... Args> - void add(const std::string &unlocalizedCategory, const std::string &unlocalizedName, Args&& ... args) { - add(impl::Entry{ unlocalizedCategory.c_str(), unlocalizedName.c_str(), - [=]{ - auto node = new T(std::forward(args)...); - node->setUnlocalizedName(unlocalizedName); - return node; - } - }); + template T, typename... Args> + void add(const std::string &unlocalizedCategory, const std::string &unlocalizedName, Args &&...args) { + add(impl::Entry { unlocalizedCategory.c_str(), unlocalizedName.c_str(), [=] { + auto node = new T(std::forward(args)...); + node->setUnlocalizedName(unlocalizedName); + return node; + } }); } void addSeparator(); - std::vector& getEntries(); + std::vector &getEntries(); } @@ -210,8 +215,8 @@ namespace hex { void registerLanguage(const std::string &name, const std::string &languageCode); void addLocalizations(const std::string &languageCode, const LanguageDefinition &definition); - std::map& getLanguages(); - std::map>& getLanguageDefinitions(); + std::map &getLanguages(); + std::map> &getLanguageDefinitions(); } /* Interface Registry. Allows adding new items to various interfaces */ @@ -255,15 +260,15 @@ namespace hex { void addLayout(const std::string &unlocalizedName, const impl::LayoutFunction &function); - std::multimap& getMainMenuItems(); - std::multimap& getMenuItems(); + std::multimap &getMainMenuItems(); + std::multimap &getMenuItems(); - std::vector& getWelcomeScreenEntries(); - std::vector& getFooterItems(); - std::vector& getToolbarItems(); - std::vector& getSidebarItems(); + std::vector &getWelcomeScreenEntries(); + std::vector &getFooterItems(); + std::vector &getToolbarItems(); + std::vector &getSidebarItems(); - std::vector& getLayouts(); + std::vector &getLayouts(); } /* Provider Registry. Allows adding new data providers to be created from the UI */ @@ -277,7 +282,7 @@ namespace hex { template T> void add(const std::string &unlocalizedName, bool addToList = true) { - (void) EventManager::subscribe([expectedName = unlocalizedName](const std::string &name, hex::prv::Provider **provider){ + (void)EventManager::subscribe([expectedName = unlocalizedName](const std::string &name, hex::prv::Provider **provider) { if (name != expectedName) return; auto newProvider = new T(); @@ -292,7 +297,7 @@ namespace hex { impl::addProviderName(unlocalizedName); } - const std::vector& getEntries(); + const std::vector &getEntries(); } @@ -310,7 +315,7 @@ namespace hex { void add(const std::string &unlocalizedName, const impl::Callback &callback); - std::vector& getEntries(); + std::vector &getEntries(); } @@ -328,7 +333,7 @@ namespace hex { void add(const std::vector &extensions, const impl::Callback &callback); - std::vector& getEntries(); + std::vector &getEntries(); } }; diff --git a/lib/libimhex/include/hex/api/event.hpp b/lib/libimhex/include/hex/api/event.hpp index c565ce907..1c7127f0d 100644 --- a/lib/libimhex/include/hex/api/event.hpp +++ b/lib/libimhex/include/hex/api/event.hpp @@ -10,10 +10,10 @@ #include #include -#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)) { } \ +#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; @@ -25,12 +25,12 @@ namespace hex { explicit constexpr EventId(const char *func = __builtin_FUNCTION(), u32 line = __builtin_LINE()) { this->m_hash = line ^ 123456789; for (auto c : std::string_view(func)) { - this->m_hash = (this->m_hash >> 5) | (this->m_hash << 27); + this->m_hash = (this->m_hash >> 5) | (this->m_hash << 27); this->m_hash ^= c; } } - constexpr bool operator ==(const EventId &rhs) const = default; + constexpr bool operator==(const EventId &rhs) const = default; private: u32 m_hash; @@ -40,11 +40,11 @@ namespace hex { EventBase() noexcept = default; }; - template + template struct Event : public EventBase { using Callback = std::function; - explicit Event(Callback func) noexcept : m_func(std::move(func)) {} + explicit Event(Callback func) noexcept : m_func(std::move(func)) { } void operator()(Params... params) const noexcept { this->m_func(params...); @@ -56,7 +56,7 @@ namespace hex { class EventManager { public: - using EventList = std::list>; + using EventList = std::list>; template [[nodiscard]] static EventList::iterator subscribe(typename E::Callback function) { @@ -74,7 +74,7 @@ namespace hex { template static void unsubscribe(void *token) noexcept { - auto iter = std::find_if(s_tokenStore.begin(), s_tokenStore.end(), [&](auto &item){ + auto iter = std::find_if(s_tokenStore.begin(), s_tokenStore.end(), [&](auto &item) { return item.first == token && item.second->first == E::id; }); @@ -84,33 +84,35 @@ namespace hex { } template - static void post(auto&& ... args) noexcept { + static void post(auto &&...args) noexcept { for (const auto &[id, event] : s_events) { if (id == E::id) (*reinterpret_cast(event))(std::forward(args)...); } } - + private: - static std::map s_tokenStore; + static std::map s_tokenStore; static EventList s_events; }; - namespace pl { class PatternData; } + namespace pl { + class PatternData; + } /* Default Events */ EVENT_DEF(EventFileLoaded, fs::path); EVENT_DEF(EventFileUnloaded); EVENT_DEF(EventDataChanged); - EVENT_DEF(EventPatternChanged, std::vector&); - EVENT_DEF(EventWindowClosing, GLFWwindow*); + EVENT_DEF(EventPatternChanged, std::vector &); + EVENT_DEF(EventWindowClosing, GLFWwindow *); EVENT_DEF(EventRegionSelected, Region); EVENT_DEF(EventProjectFileStore); EVENT_DEF(EventProjectFileLoad); EVENT_DEF(EventSettingsChanged); EVENT_DEF(EventAbnormalTermination, int); EVENT_DEF(EventOSThemeChanged); - EVENT_DEF(EventProviderCreated, prv::Provider*); + EVENT_DEF(EventProviderCreated, prv::Provider *); EVENT_DEF(EventFrameBegin); EVENT_DEF(EventFrameEnd); @@ -125,6 +127,6 @@ namespace hex { EVENT_DEF(RequestOpenPopup, std::string); EVENT_DEF(RequestCreateProvider, std::string, hex::prv::Provider **); - EVENT_DEF(QuerySelection, Region&); + EVENT_DEF(QuerySelection, Region &); } \ No newline at end of file diff --git a/lib/libimhex/include/hex/api/imhex_api.hpp b/lib/libimhex/include/hex/api/imhex_api.hpp index bfd543a7b..ffbd36203 100644 --- a/lib/libimhex/include/hex/api/imhex_api.hpp +++ b/lib/libimhex/include/hex/api/imhex_api.hpp @@ -12,7 +12,9 @@ namespace hex { - namespace prv { class Provider; } + namespace prv { + class Provider; + } namespace ImHexApi { namespace Common { @@ -35,20 +37,20 @@ namespace hex { void add(Region region, const std::string &name, const std::string &comment, u32 color = 0x00000000); void add(u64 addr, size_t size, const std::string &name, const std::string &comment, u32 color = 0x00000000); - std::list& getEntries(); + std::list &getEntries(); }; namespace Provider { - prv::Provider* get(); - const std::vector& getProviders(); + prv::Provider *get(); + const std::vector &getProviders(); bool isValid(); void add(prv::Provider *provider); template T> - void add(auto&& ... args) { + void add(auto &&...args) { add(new T(std::forward(args)...)); } diff --git a/lib/libimhex/include/hex/api/keybinding.hpp b/lib/libimhex/include/hex/api/keybinding.hpp index 4501464d0..8bf92c5fb 100644 --- a/lib/libimhex/include/hex/api/keybinding.hpp +++ b/lib/libimhex/include/hex/api/keybinding.hpp @@ -14,126 +14,126 @@ namespace hex { struct View; enum class Keys { - Space = GLFW_KEY_SPACE, - Apostrophe = GLFW_KEY_APOSTROPHE, - Comma = GLFW_KEY_COMMA, - Minus = GLFW_KEY_MINUS, - Period = GLFW_KEY_PERIOD, - Slash = GLFW_KEY_SLASH, - Num0 = GLFW_KEY_0, - Num1 = GLFW_KEY_1, - Num2 = GLFW_KEY_2, - Num3 = GLFW_KEY_3, - Num4 = GLFW_KEY_4, - Num5 = GLFW_KEY_5, - Num6 = GLFW_KEY_6, - Num7 = GLFW_KEY_7, - Num8 = GLFW_KEY_8, - Num9 = GLFW_KEY_9, - Semicolon = GLFW_KEY_SEMICOLON, - Equals = GLFW_KEY_EQUAL, - A = GLFW_KEY_A, - B = GLFW_KEY_B, - C = GLFW_KEY_C, - D = GLFW_KEY_D, - E = GLFW_KEY_E, - F = GLFW_KEY_F, - G = GLFW_KEY_G, - H = GLFW_KEY_H, - I = GLFW_KEY_I, - J = GLFW_KEY_J, - K = GLFW_KEY_K, - L = GLFW_KEY_L, - M = GLFW_KEY_M, - N = GLFW_KEY_N, - O = GLFW_KEY_O, - P = GLFW_KEY_P, - Q = GLFW_KEY_Q, - R = GLFW_KEY_R, - S = GLFW_KEY_S, - T = GLFW_KEY_T, - U = GLFW_KEY_U, - V = GLFW_KEY_V, - W = GLFW_KEY_W, - X = GLFW_KEY_X, - Y = GLFW_KEY_Y, - Z = GLFW_KEY_Z, - LeftBracket = GLFW_KEY_LEFT_BRACKET, - Backslash = GLFW_KEY_BACKSLASH, - RightBracket = GLFW_KEY_RIGHT_BRACKET, - GraveAccent = GLFW_KEY_GRAVE_ACCENT, - World1 = GLFW_KEY_WORLD_1, - World2 = GLFW_KEY_WORLD_2, - Escape = GLFW_KEY_ESCAPE, - Enter = GLFW_KEY_ENTER, - Tab = GLFW_KEY_TAB, - Backspace = GLFW_KEY_BACKSPACE, - Insert = GLFW_KEY_INSERT, - Delete = GLFW_KEY_DELETE, - Right = GLFW_KEY_RIGHT, - Left = GLFW_KEY_LEFT, - Down = GLFW_KEY_DOWN, - Up = GLFW_KEY_UP, - PageUp = GLFW_KEY_PAGE_UP, - PageDown = GLFW_KEY_PAGE_DOWN, - Home = GLFW_KEY_HOME, - End = GLFW_KEY_END, - CapsLock = GLFW_KEY_CAPS_LOCK, - ScrollLock = GLFW_KEY_SCROLL_LOCK, - NumLock = GLFW_KEY_NUM_LOCK, - PrintScreen = GLFW_KEY_PRINT_SCREEN, - Pause = GLFW_KEY_PAUSE, - F1 = GLFW_KEY_F1, - F2 = GLFW_KEY_F2, - F3 = GLFW_KEY_F3, - F4 = GLFW_KEY_F4, - F5 = GLFW_KEY_F5, - F6 = GLFW_KEY_F6, - F7 = GLFW_KEY_F7, - F8 = GLFW_KEY_F8, - F9 = GLFW_KEY_F9, - F10 = GLFW_KEY_F10, - F11 = GLFW_KEY_F11, - F12 = GLFW_KEY_F12, - F13 = GLFW_KEY_F13, - F14 = GLFW_KEY_F14, - F15 = GLFW_KEY_F15, - F16 = GLFW_KEY_F16, - F17 = GLFW_KEY_F17, - F18 = GLFW_KEY_F18, - F19 = GLFW_KEY_F19, - F20 = GLFW_KEY_F20, - F21 = GLFW_KEY_F21, - F22 = GLFW_KEY_F22, - F23 = GLFW_KEY_F23, - F24 = GLFW_KEY_F24, - F25 = GLFW_KEY_F25, - KeyPad0 = GLFW_KEY_KP_0, - KeyPad1 = GLFW_KEY_KP_1, - KeyPad2 = GLFW_KEY_KP_2, - KeyPad3 = GLFW_KEY_KP_3, - KeyPad4 = GLFW_KEY_KP_4, - KeyPad5 = GLFW_KEY_KP_5, - KeyPad6 = GLFW_KEY_KP_6, - KeyPad7 = GLFW_KEY_KP_7, - KeyPad8 = GLFW_KEY_KP_8, - KeyPad9 = GLFW_KEY_KP_9, - KeyPadDecimal = GLFW_KEY_KP_DECIMAL, - KeyPadDivide = GLFW_KEY_KP_DIVIDE, - KeyPadMultiply = GLFW_KEY_KP_MULTIPLY, - KeyPadSubtract = GLFW_KEY_KP_SUBTRACT, - KeyPadAdd = GLFW_KEY_KP_ADD, - KeyPadEnter = GLFW_KEY_KP_ENTER, - KeyPadEqual = GLFW_KEY_KP_EQUAL, - Menu = GLFW_KEY_MENU, + Space = GLFW_KEY_SPACE, + Apostrophe = GLFW_KEY_APOSTROPHE, + Comma = GLFW_KEY_COMMA, + Minus = GLFW_KEY_MINUS, + Period = GLFW_KEY_PERIOD, + Slash = GLFW_KEY_SLASH, + Num0 = GLFW_KEY_0, + Num1 = GLFW_KEY_1, + Num2 = GLFW_KEY_2, + Num3 = GLFW_KEY_3, + Num4 = GLFW_KEY_4, + Num5 = GLFW_KEY_5, + Num6 = GLFW_KEY_6, + Num7 = GLFW_KEY_7, + Num8 = GLFW_KEY_8, + Num9 = GLFW_KEY_9, + Semicolon = GLFW_KEY_SEMICOLON, + Equals = GLFW_KEY_EQUAL, + A = GLFW_KEY_A, + B = GLFW_KEY_B, + C = GLFW_KEY_C, + D = GLFW_KEY_D, + E = GLFW_KEY_E, + F = GLFW_KEY_F, + G = GLFW_KEY_G, + H = GLFW_KEY_H, + I = GLFW_KEY_I, + J = GLFW_KEY_J, + K = GLFW_KEY_K, + L = GLFW_KEY_L, + M = GLFW_KEY_M, + N = GLFW_KEY_N, + O = GLFW_KEY_O, + P = GLFW_KEY_P, + Q = GLFW_KEY_Q, + R = GLFW_KEY_R, + S = GLFW_KEY_S, + T = GLFW_KEY_T, + U = GLFW_KEY_U, + V = GLFW_KEY_V, + W = GLFW_KEY_W, + X = GLFW_KEY_X, + Y = GLFW_KEY_Y, + Z = GLFW_KEY_Z, + LeftBracket = GLFW_KEY_LEFT_BRACKET, + Backslash = GLFW_KEY_BACKSLASH, + RightBracket = GLFW_KEY_RIGHT_BRACKET, + GraveAccent = GLFW_KEY_GRAVE_ACCENT, + World1 = GLFW_KEY_WORLD_1, + World2 = GLFW_KEY_WORLD_2, + Escape = GLFW_KEY_ESCAPE, + Enter = GLFW_KEY_ENTER, + Tab = GLFW_KEY_TAB, + Backspace = GLFW_KEY_BACKSPACE, + Insert = GLFW_KEY_INSERT, + Delete = GLFW_KEY_DELETE, + Right = GLFW_KEY_RIGHT, + Left = GLFW_KEY_LEFT, + Down = GLFW_KEY_DOWN, + Up = GLFW_KEY_UP, + PageUp = GLFW_KEY_PAGE_UP, + PageDown = GLFW_KEY_PAGE_DOWN, + Home = GLFW_KEY_HOME, + End = GLFW_KEY_END, + CapsLock = GLFW_KEY_CAPS_LOCK, + ScrollLock = GLFW_KEY_SCROLL_LOCK, + NumLock = GLFW_KEY_NUM_LOCK, + PrintScreen = GLFW_KEY_PRINT_SCREEN, + Pause = GLFW_KEY_PAUSE, + F1 = GLFW_KEY_F1, + F2 = GLFW_KEY_F2, + F3 = GLFW_KEY_F3, + F4 = GLFW_KEY_F4, + F5 = GLFW_KEY_F5, + F6 = GLFW_KEY_F6, + F7 = GLFW_KEY_F7, + F8 = GLFW_KEY_F8, + F9 = GLFW_KEY_F9, + F10 = GLFW_KEY_F10, + F11 = GLFW_KEY_F11, + F12 = GLFW_KEY_F12, + F13 = GLFW_KEY_F13, + F14 = GLFW_KEY_F14, + F15 = GLFW_KEY_F15, + F16 = GLFW_KEY_F16, + F17 = GLFW_KEY_F17, + F18 = GLFW_KEY_F18, + F19 = GLFW_KEY_F19, + F20 = GLFW_KEY_F20, + F21 = GLFW_KEY_F21, + F22 = GLFW_KEY_F22, + F23 = GLFW_KEY_F23, + F24 = GLFW_KEY_F24, + F25 = GLFW_KEY_F25, + KeyPad0 = GLFW_KEY_KP_0, + KeyPad1 = GLFW_KEY_KP_1, + KeyPad2 = GLFW_KEY_KP_2, + KeyPad3 = GLFW_KEY_KP_3, + KeyPad4 = GLFW_KEY_KP_4, + KeyPad5 = GLFW_KEY_KP_5, + KeyPad6 = GLFW_KEY_KP_6, + KeyPad7 = GLFW_KEY_KP_7, + KeyPad8 = GLFW_KEY_KP_8, + KeyPad9 = GLFW_KEY_KP_9, + KeyPadDecimal = GLFW_KEY_KP_DECIMAL, + KeyPadDivide = GLFW_KEY_KP_DIVIDE, + KeyPadMultiply = GLFW_KEY_KP_MULTIPLY, + KeyPadSubtract = GLFW_KEY_KP_SUBTRACT, + KeyPadAdd = GLFW_KEY_KP_ADD, + KeyPadEnter = GLFW_KEY_KP_ENTER, + KeyPadEqual = GLFW_KEY_KP_EQUAL, + Menu = GLFW_KEY_MENU, }; class Key { public: - constexpr Key(Keys key) :m_key(static_cast(key)) { } + constexpr Key(Keys key) : m_key(static_cast(key)) { } - auto operator<=>(const Key&) const = default; + auto operator<=>(const Key &) const = default; private: u32 m_key; @@ -141,7 +141,6 @@ namespace hex { class Shortcut { public: - Shortcut operator+(const Key &other) const { Shortcut result = *this; result.m_keys.insert(other); @@ -149,7 +148,7 @@ namespace hex { return result; } - Shortcut& operator+=(const Key &other) { + Shortcut &operator+=(const Key &other) { this->m_keys.insert(other); return *this; @@ -162,6 +161,7 @@ namespace hex { bool operator==(const Shortcut &other) const { return this->m_keys == other.m_keys; } + private: friend Shortcut operator+(const Key &lhs, const Key &rhs); @@ -175,8 +175,8 @@ namespace hex { return result; } - static constexpr auto CTRL = Key(static_cast(0x1000'0000)); - static constexpr auto ALT = Key(static_cast(0x2000'0000)); + static constexpr auto CTRL = Key(static_cast(0x1000'0000)); + static constexpr auto ALT = Key(static_cast(0x2000'0000)); static constexpr auto SHIFT = Key(static_cast(0x3000'0000)); static constexpr auto SUPER = Key(static_cast(0x4000'0000)); diff --git a/lib/libimhex/include/hex/api/task.hpp b/lib/libimhex/include/hex/api/task.hpp index 9002a1dd7..f5a4e3d5b 100644 --- a/lib/libimhex/include/hex/api/task.hpp +++ b/lib/libimhex/include/hex/api/task.hpp @@ -8,21 +8,18 @@ namespace hex { class Task { public: - Task(const std::string& unlocalizedName, u64 maxValue); + Task(const std::string &unlocalizedName, u64 maxValue); ~Task(); void setMaxValue(u64 maxValue); void update(u64 currValue); void finish(); - [[nodiscard]] - double getProgress() const; + [[nodiscard]] double getProgress() const; - [[nodiscard]] - const std::string& getName() const; + [[nodiscard]] const std::string &getName() const; - [[nodiscard]] - bool isPending() const; + [[nodiscard]] bool isPending() const; private: std::string m_name; diff --git a/lib/libimhex/include/hex/data_processor/attribute.hpp b/lib/libimhex/include/hex/data_processor/attribute.hpp index 98d0aa478..9d40c65f5 100644 --- a/lib/libimhex/include/hex/data_processor/attribute.hpp +++ b/lib/libimhex/include/hex/data_processor/attribute.hpp @@ -20,7 +20,8 @@ namespace hex::dp { }; enum class IOType { - In, Out + In, + Out }; Attribute(IOType ioType, Type type, std::string unlocalizedName); @@ -31,21 +32,22 @@ namespace hex::dp { [[nodiscard]] IOType getIOType() const { return this->m_ioType; } [[nodiscard]] Type getType() const { return this->m_type; } - [[nodiscard]] const std::string& 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); } - [[nodiscard]] std::map& getConnectedAttributes() { return this->m_connectedAttributes; } + [[nodiscard]] std::map &getConnectedAttributes() { return this->m_connectedAttributes; } - [[nodiscard]] Node* getParentNode() { return this->m_parentNode; } + [[nodiscard]] Node *getParentNode() { return this->m_parentNode; } + + [[nodiscard]] std::optional> &getOutputData() { return this->m_outputData; } - [[nodiscard]] std::optional>& getOutputData() { return this->m_outputData; } private: u32 m_id; IOType m_ioType; Type m_type; std::string m_unlocalizedName; - std::map m_connectedAttributes; + std::map m_connectedAttributes; Node *m_parentNode = nullptr; std::optional> m_outputData; diff --git a/lib/libimhex/include/hex/data_processor/link.hpp b/lib/libimhex/include/hex/data_processor/link.hpp index 715831861..c0eed809a 100644 --- a/lib/libimhex/include/hex/data_processor/link.hpp +++ b/lib/libimhex/include/hex/data_processor/link.hpp @@ -8,11 +8,11 @@ namespace hex::dp { public: Link(u32 from, u32 to); - [[nodiscard]] u32 getID() const { return this->m_id; } + [[nodiscard]] u32 getID() const { return this->m_id; } void setID(u32 id) { this->m_id = id; } [[nodiscard]] u32 getFromID() const { return this->m_from; } - [[nodiscard]] u32 getToID() const { return this->m_to; } + [[nodiscard]] u32 getToID() const { return this->m_to; } private: u32 m_id; diff --git a/lib/libimhex/include/hex/data_processor/node.hpp b/lib/libimhex/include/hex/data_processor/node.hpp index b7cf2b9a1..26f09c1ad 100644 --- a/lib/libimhex/include/hex/data_processor/node.hpp +++ b/lib/libimhex/include/hex/data_processor/node.hpp @@ -9,7 +9,10 @@ #include -namespace hex::prv { class Provider; class Overlay; } +namespace hex::prv { + class Provider; + class Overlay; +} namespace hex::dp { @@ -22,11 +25,11 @@ namespace hex::dp { [[nodiscard]] u32 getID() const { return this->m_id; } void setID(u32 id) { this->m_id = id; } - [[nodiscard]] const std::string& getUnlocalizedName() const { return this->m_unlocalizedName; } + [[nodiscard]] const std::string &getUnlocalizedName() const { return this->m_unlocalizedName; } void setUnlocalizedName(const std::string &unlocalizedName) { this->m_unlocalizedName = unlocalizedName; } - [[nodiscard]] const std::string& getUnlocalizedTitle() const { return this->m_unlocalizedTitle; } - [[nodiscard]] std::vector& getAttributes() { return this->m_attributes; } + [[nodiscard]] const std::string &getUnlocalizedTitle() const { return this->m_unlocalizedTitle; } + [[nodiscard]] std::vector &getAttributes() { return this->m_attributes; } void setCurrentOverlay(prv::Overlay *overlay) { this->m_overlay = overlay; @@ -38,7 +41,7 @@ namespace hex::dp { virtual void store(nlohmann::json &j) { } virtual void load(nlohmann::json &j) { } - using NodeError = std::pair; + using NodeError = std::pair; void resetOutputData() { for (auto &attribute : this->m_attributes) @@ -56,7 +59,7 @@ namespace hex::dp { std::set m_processedInputs; prv::Overlay *m_overlay = nullptr; - Attribute* getConnectedInputAttribute(u32 index) { + Attribute *getConnectedInputAttribute(u32 index) { if (index >= this->getAttributes().size()) throw std::runtime_error("Attribute index out of bounds!"); @@ -75,7 +78,6 @@ namespace hex::dp { } protected: - [[noreturn]] void throwNodeError(const std::string &message) { throw NodeError(this, message); } @@ -89,7 +91,6 @@ namespace hex::dp { void setFloatOnOutput(u32 index, float floatingPoint); void setOverlayData(u64 address, const std::vector &data); - }; } \ No newline at end of file diff --git a/lib/libimhex/include/hex/helpers/concepts.hpp b/lib/libimhex/include/hex/helpers/concepts.hpp index 29a07f10f..100147034 100644 --- a/lib/libimhex/include/hex/helpers/concepts.hpp +++ b/lib/libimhex/include/hex/helpers/concepts.hpp @@ -113,21 +113,21 @@ namespace hex { } #if defined(_LIBCPP_VERSION) && _LIBCPP_VERSION <= 12000 -#if __has_include() -// Make sure we break when derived_from is implemented in libc++. Then we can fix a compatibility version above -#include -#endif + #if __has_include() + // Make sure we break when derived_from is implemented in libc++. Then we can fix a compatibility version above + #include + #endif // libcxx 12 still doesn't have many default concepts implemented, as a result we need to define it ourself using clang built-ins. // [concept.derived] (patch from https://reviews.llvm.org/D74292) namespace hex { -template -concept derived_from = - __is_base_of(_Bp, _Dp) && __is_convertible_to(const volatile _Dp*, const volatile _Bp*); + template + concept derived_from = + __is_base_of(_Bp, _Dp) && __is_convertible_to(const volatile _Dp *, const volatile _Bp *); } #else -// Assume supported -#include + // Assume supported + #include namespace hex { using std::derived_from; } @@ -153,10 +153,9 @@ namespace hex { namespace hex { template - struct always_false : std::false_type {}; + struct always_false : std::false_type { }; template concept has_size = sizeof(T) == Size; } - diff --git a/lib/libimhex/include/hex/helpers/crypto.hpp b/lib/libimhex/include/hex/helpers/crypto.hpp index 79f2ac60c..3af32c150 100644 --- a/lib/libimhex/include/hex/helpers/crypto.hpp +++ b/lib/libimhex/include/hex/helpers/crypto.hpp @@ -7,23 +7,25 @@ #include #include -namespace hex::prv { class Provider; } +namespace hex::prv { + class Provider; +} namespace hex::crypt { void initialize(); void exit(); - u16 crc8(prv::Provider* &data, u64 offset, size_t size, u32 polynomial, u32 init, u32 xorout, bool reflectIn, bool reflectOut); - u16 crc16(prv::Provider* &data, u64 offset, size_t size, u32 polynomial, u32 init, u32 xorout, bool reflectIn, bool reflectOut); - u32 crc32(prv::Provider* &data, u64 offset, size_t size, u32 polynomial, u32 init, u32 xorout, bool reflectIn, bool reflectOut); + u16 crc8(prv::Provider *&data, u64 offset, size_t size, u32 polynomial, u32 init, u32 xorout, bool reflectIn, bool reflectOut); + u16 crc16(prv::Provider *&data, u64 offset, size_t size, u32 polynomial, u32 init, u32 xorout, bool reflectIn, bool reflectOut); + u32 crc32(prv::Provider *&data, u64 offset, size_t size, u32 polynomial, u32 init, u32 xorout, bool reflectIn, bool reflectOut); - std::array md5(prv::Provider* &data, u64 offset, size_t size); - std::array sha1(prv::Provider* &data, u64 offset, size_t size); - std::array sha224(prv::Provider* &data, u64 offset, size_t size); - std::array sha256(prv::Provider* &data, u64 offset, size_t size); - std::array sha384(prv::Provider* &data, u64 offset, size_t size); - std::array sha512(prv::Provider* &data, u64 offset, size_t size); + std::array md5(prv::Provider *&data, u64 offset, size_t size); + std::array sha1(prv::Provider *&data, u64 offset, size_t size); + std::array sha224(prv::Provider *&data, u64 offset, size_t size); + std::array sha256(prv::Provider *&data, u64 offset, size_t size); + std::array sha384(prv::Provider *&data, u64 offset, size_t size); + std::array sha512(prv::Provider *&data, u64 offset, size_t size); std::array md5(const std::vector &data); std::array sha1(const std::vector &data); @@ -38,14 +40,14 @@ namespace hex::crypt { std::string encode16(const std::vector &input); enum class AESMode : u8 { - ECB = 0, - CBC = 1, - CFB128 = 2, - CTR = 3, - GCM = 4, - CCM = 5, - OFB = 6, - XTS = 7 + ECB = 0, + CBC = 1, + CFB128 = 2, + CTR = 3, + GCM = 4, + CCM = 5, + OFB = 6, + XTS = 7 }; enum class KeyLength : u8 { diff --git a/lib/libimhex/include/hex/helpers/disassembler.hpp b/lib/libimhex/include/hex/helpers/disassembler.hpp index 36f73e482..28168f6fb 100644 --- a/lib/libimhex/include/hex/helpers/disassembler.hpp +++ b/lib/libimhex/include/hex/helpers/disassembler.hpp @@ -1,9 +1,9 @@ #pragma once #if __has_include() -#include + #include #else -#include + #include #endif #include @@ -41,7 +41,7 @@ namespace hex { return cs_support(toCapstoneArchictecture(architecture)); } - constexpr static const char * const ArchitectureNames[] = { "ARM32", "ARM64", "MIPS", "x86", "PowerPC", "Sparc", "SystemZ", "XCore", "68K", "TMS320C64x", "680X", "Ethereum", "MOS65XX", "WebAssembly", "Berkeley Packet Filter", "RISC-V" }; + constexpr static const char *const ArchitectureNames[] = { "ARM32", "ARM64", "MIPS", "x86", "PowerPC", "Sparc", "SystemZ", "XCore", "68K", "TMS320C64x", "680X", "Ethereum", "MOS65XX", "WebAssembly", "Berkeley Packet Filter", "RISC-V" }; static inline i32 getArchitectureSupportedCount() { static i32 supportedCount = -1; diff --git a/lib/libimhex/include/hex/helpers/file.hpp b/lib/libimhex/include/hex/helpers/file.hpp index 33834f298..db826f4df 100644 --- a/lib/libimhex/include/hex/helpers/file.hpp +++ b/lib/libimhex/include/hex/helpers/file.hpp @@ -9,10 +9,10 @@ #include #if defined(OS_MACOS) - #define off64_t off_t - #define fopen64 fopen - #define fseeko64 fseek - #define ftello64 ftell + #define off64_t off_t + #define fopen64 fopen + #define fseeko64 fseek + #define ftello64 ftell #define ftruncate64 ftruncate #endif @@ -28,12 +28,12 @@ namespace hex { explicit File(const fs::path &path, Mode mode) noexcept; File() noexcept; - File(const File&) = delete; + File(const File &) = delete; File(File &&other) noexcept; ~File(); - File& operator=(File &&other) noexcept; + File &operator=(File &&other) noexcept; [[nodiscard]] bool isValid() const { return this->m_file != nullptr; } @@ -56,7 +56,7 @@ namespace hex { void remove(); auto getHandle() { return this->m_file; } - const fs::path& getPath() { return this->m_path; } + const fs::path &getPath() { return this->m_path; } private: FILE *m_file; diff --git a/lib/libimhex/include/hex/helpers/fmt.hpp b/lib/libimhex/include/hex/helpers/fmt.hpp index 11b65b30a..df87ca2e6 100644 --- a/lib/libimhex/include/hex/helpers/fmt.hpp +++ b/lib/libimhex/include/hex/helpers/fmt.hpp @@ -6,13 +6,13 @@ namespace hex { - template - inline std::string format(std::string_view format, Args ... args) { + template + inline std::string format(std::string_view format, Args... args) { return fmt::format(fmt::runtime(format), args...); } - template - inline void print(std::string_view format, Args ... args) { + template + inline void print(std::string_view format, Args... args) { fmt::print(fmt::runtime(format), args...); } diff --git a/lib/libimhex/include/hex/helpers/lang.hpp b/lib/libimhex/include/hex/helpers/lang.hpp index 5ca8e1f7b..7ee720fa9 100644 --- a/lib/libimhex/include/hex/helpers/lang.hpp +++ b/lib/libimhex/include/hex/helpers/lang.hpp @@ -11,7 +11,7 @@ namespace hex { public: LanguageDefinition(std::initializer_list> entries); - const std::map& getEntries() const; + const std::map &getEntries() const; private: std::map m_entries; @@ -25,15 +25,15 @@ namespace hex { operator std::string() const; operator std::string_view() const; - operator const char*() const; + operator const char *() const; - [[nodiscard]] const std::string& get() const; + [[nodiscard]] const std::string &get() const; static void loadLanguage(const std::string &language); - static const std::map& getSupportedLanguages(); + static const std::map &getSupportedLanguages(); static void setFallbackLanguage(const std::string &language); - static const std::string& getFallbackLanguage(); + static const std::string &getFallbackLanguage(); private: std::string m_unlocalizedString; @@ -58,5 +58,4 @@ namespace hex { } - } \ No newline at end of file diff --git a/lib/libimhex/include/hex/helpers/literals.hpp b/lib/libimhex/include/hex/helpers/literals.hpp index 334b9bb94..ab07ed724 100644 --- a/lib/libimhex/include/hex/helpers/literals.hpp +++ b/lib/libimhex/include/hex/helpers/literals.hpp @@ -4,20 +4,20 @@ namespace hex::literals { /* Byte literals */ - constexpr static inline unsigned long long operator ""_Bytes(unsigned long long bytes) noexcept { + constexpr static inline unsigned long long operator""_Bytes(unsigned long long bytes) noexcept { return bytes; } - constexpr static inline unsigned long long operator ""_KiB(unsigned long long kiB) noexcept { - return operator ""_Bytes(kiB * 1024); + constexpr static inline unsigned long long operator""_KiB(unsigned long long kiB) noexcept { + return operator""_Bytes(kiB * 1024); } - constexpr static inline unsigned long long operator ""_MiB(unsigned long long MiB) noexcept { - return operator ""_KiB(MiB * 1024); + constexpr static inline unsigned long long operator""_MiB(unsigned long long MiB) noexcept { + return operator""_KiB(MiB * 1024); } - constexpr static inline unsigned long long operator ""_GiB(unsigned long long GiB) noexcept { - return operator ""_MiB(GiB * 1024); + constexpr static inline unsigned long long operator""_GiB(unsigned long long GiB) noexcept { + return operator""_MiB(GiB * 1024); } } \ No newline at end of file diff --git a/lib/libimhex/include/hex/helpers/loader_script_handler.hpp b/lib/libimhex/include/hex/helpers/loader_script_handler.hpp index 9b9992765..874acff99 100644 --- a/lib/libimhex/include/hex/helpers/loader_script_handler.hpp +++ b/lib/libimhex/include/hex/helpers/loader_script_handler.hpp @@ -10,7 +10,9 @@ typedef struct _object PyObject; namespace hex { - namespace prv { class Provider; } + namespace prv { + class Provider; + } class LoaderScript { public: @@ -19,17 +21,18 @@ namespace hex { static bool processFile(const fs::path &scriptPath); static void setFilePath(const fs::path &filePath) { LoaderScript::s_filePath = filePath; } - static void setDataProvider(prv::Provider* provider) { LoaderScript::s_dataProvider = provider; } + static void setDataProvider(prv::Provider *provider) { LoaderScript::s_dataProvider = provider; } + private: static inline fs::path s_filePath; - static inline prv::Provider* s_dataProvider; + static inline prv::Provider *s_dataProvider; - static PyObject* Py_getFilePath(PyObject *self, PyObject *args); - static PyObject* Py_addPatch(PyObject *self, PyObject *args); - static PyObject* Py_addBookmark(PyObject *self, PyObject *args); + static PyObject *Py_getFilePath(PyObject *self, PyObject *args); + static PyObject *Py_addPatch(PyObject *self, PyObject *args); + static PyObject *Py_addBookmark(PyObject *self, PyObject *args); - static PyObject* Py_addStruct(PyObject *self, PyObject *args); - static PyObject* Py_addUnion(PyObject *self, PyObject *args); + static PyObject *Py_addStruct(PyObject *self, PyObject *args); + static PyObject *Py_addUnion(PyObject *self, PyObject *args); }; } \ No newline at end of file diff --git a/lib/libimhex/include/hex/helpers/logger.hpp b/lib/libimhex/include/hex/helpers/logger.hpp index 01b568e42..1fbf0149b 100644 --- a/lib/libimhex/include/hex/helpers/logger.hpp +++ b/lib/libimhex/include/hex/helpers/logger.hpp @@ -8,46 +8,46 @@ namespace hex::log { FILE *getDestination(); bool isRedirected(); - template - void print(fmt::format_string fmt, T&&... args) { + template + void print(fmt::format_string fmt, T &&...args) { fmt::print(getDestination(), fmt, args...); } - template - void print(const fmt::text_style& ts, const S& fmt, const Args&... args) { + template + void print(const fmt::text_style &ts, const S &fmt, const Args &...args) { if (isRedirected()) fmt::print(getDestination(), fmt::runtime(fmt), args...); else fmt::print(getDestination(), ts, fmt, args...); } - void debug(const std::string &fmt, auto ... args) { - #if defined(DEBUG) - log::print(fg(fmt::color::green_yellow) | fmt::emphasis::bold, "[DEBUG] "); - log::print(fmt::runtime(fmt), args...); - log::print("\n"); - #endif + void debug(const std::string &fmt, auto... args) { +#if defined(DEBUG) + log::print(fg(fmt::color::green_yellow) | fmt::emphasis::bold, "[DEBUG] "); + log::print(fmt::runtime(fmt), args...); + log::print("\n"); +#endif } - void info(const std::string &fmt, auto ... args) { + void info(const std::string &fmt, auto... args) { log::print(fg(fmt::color::cadet_blue) | fmt::emphasis::bold, "[INFO] "); log::print(fmt::runtime(fmt), args...); log::print("\n"); } - void warn(const std::string &fmt, auto ... args) { + void warn(const std::string &fmt, auto... args) { log::print(fg(fmt::color::orange) | fmt::emphasis::bold, "[WARN] "); log::print(fmt::runtime(fmt), args...); log::print("\n"); } - void error(const std::string &fmt, auto ... args) { + void error(const std::string &fmt, auto... args) { log::print(fg(fmt::color::red) | fmt::emphasis::bold, "[ERROR] "); log::print(fmt::runtime(fmt), args...); log::print("\n"); } - void fatal(const std::string &fmt, auto ... args) { + void fatal(const std::string &fmt, auto... args) { log::print(fg(fmt::color::purple) | fmt::emphasis::bold, "[FATAL] "); log::print(fmt::runtime(fmt), args...); log::print("\n"); diff --git a/lib/libimhex/include/hex/helpers/magic.hpp b/lib/libimhex/include/hex/helpers/magic.hpp index 6b5deeabc..c54235e15 100644 --- a/lib/libimhex/include/hex/helpers/magic.hpp +++ b/lib/libimhex/include/hex/helpers/magic.hpp @@ -7,7 +7,9 @@ #include #include -namespace hex::prv { class Provider; } +namespace hex::prv { + class Provider; +} namespace hex::magic { diff --git a/lib/libimhex/include/hex/helpers/net.hpp b/lib/libimhex/include/hex/helpers/net.hpp index 63d3a0c64..e02499b55 100644 --- a/lib/libimhex/include/hex/helpers/net.hpp +++ b/lib/libimhex/include/hex/helpers/net.hpp @@ -41,19 +41,18 @@ namespace hex { std::future> uploadFile(const std::string &url, const fs::path &filePath, u32 timeout = 2000); std::future> downloadFile(const std::string &url, const fs::path &filePath, u32 timeout = 2000); - [[nodiscard]] - std::string encode(const std::string &input); + [[nodiscard]] std::string encode(const std::string &input); - [[nodiscard]] - float getProgress() const { return this->m_progress; } + [[nodiscard]] float getProgress() const { return this->m_progress; } void cancel() { this->m_shouldCancel = true; } private: - void setCommonSettings(std::string &response, const std::string &url, u32 timeout = 2000, const std::map &extraHeaders = { }, const std::string &body = { }); + void setCommonSettings(std::string &response, const std::string &url, u32 timeout = 2000, const std::map &extraHeaders = {}, const std::string &body = {}); std::optional execute(); friend int progressCallback(void *contents, curl_off_t dlTotal, curl_off_t dlNow, curl_off_t ulTotal, curl_off_t ulNow); + private: CURL *m_ctx; curl_slist *m_headers = nullptr; diff --git a/lib/libimhex/include/hex/helpers/paths_mac.h b/lib/libimhex/include/hex/helpers/paths_mac.h index 6f826921e..0d48e94f2 100644 --- a/lib/libimhex/include/hex/helpers/paths_mac.h +++ b/lib/libimhex/include/hex/helpers/paths_mac.h @@ -3,8 +3,8 @@ #if defined(OS_MACOS) #include - namespace hex { - std::string getMacExecutableDirectoryPath(); - std::string getMacApplicationSupportDirectoryPath(); - } +namespace hex { + std::string getMacExecutableDirectoryPath(); + std::string getMacApplicationSupportDirectoryPath(); +} #endif diff --git a/lib/libimhex/include/hex/helpers/project_file_handler.hpp b/lib/libimhex/include/hex/helpers/project_file_handler.hpp index ce8ca05ef..7dfabbb83 100644 --- a/lib/libimhex/include/hex/helpers/project_file_handler.hpp +++ b/lib/libimhex/include/hex/helpers/project_file_handler.hpp @@ -17,7 +17,7 @@ namespace hex { ProjectFile() = delete; static bool load(const fs::path &filePath); - static bool store(fs::path filePath = { }); + static bool store(fs::path filePath = {}); [[nodiscard]] static bool hasUnsavedChanges() { return ProjectFile::s_hasUnsavedChanged; @@ -32,7 +32,7 @@ namespace hex { EventManager::post(fs::path(getFilePath()).filename().string()); } - [[nodiscard]] static const fs::path& getProjectFilePath() { + [[nodiscard]] static const fs::path &getProjectFilePath() { return ProjectFile::s_currProjectFilePath; } @@ -41,7 +41,7 @@ namespace hex { } - [[nodiscard]] static const fs::path& getFilePath() { + [[nodiscard]] static const fs::path &getFilePath() { return ProjectFile::s_filePath; } @@ -52,7 +52,7 @@ namespace hex { } - [[nodiscard]] static const std::string& getPattern() { + [[nodiscard]] static const std::string &getPattern() { return ProjectFile::s_pattern; } @@ -62,7 +62,7 @@ namespace hex { } - [[nodiscard]] static const Patches& getPatches() { + [[nodiscard]] static const Patches &getPatches() { return ProjectFile::s_patches; } @@ -72,7 +72,7 @@ namespace hex { } - [[nodiscard]] static const std::list& getBookmarks() { + [[nodiscard]] static const std::list &getBookmarks() { return ProjectFile::s_bookmarks; } @@ -82,7 +82,7 @@ namespace hex { } - [[nodiscard]] static const std::string& getDataProcessorContent() { + [[nodiscard]] static const std::string &getDataProcessorContent() { return ProjectFile::s_dataProcessorContent; } diff --git a/lib/libimhex/include/hex/helpers/shared_data.hpp b/lib/libimhex/include/hex/helpers/shared_data.hpp index ea1bf98d8..c30024848 100644 --- a/lib/libimhex/include/hex/helpers/shared_data.hpp +++ b/lib/libimhex/include/hex/helpers/shared_data.hpp @@ -17,7 +17,9 @@ #include -namespace hex { class SharedData; } +namespace hex { + class SharedData; +} namespace hex::plugin::internal { void initializePlugin(SharedData &sharedData); @@ -25,23 +27,30 @@ namespace hex::plugin::internal { namespace hex { - namespace prv { class Provider; } - namespace dp { class Node; } - namespace pl { class PatternData; } + namespace prv { + class Provider; + } + namespace dp { + class Node; + } + namespace pl { + class PatternData; + } class View; class SharedData { SharedData() = default; + public: - SharedData(const SharedData&) = delete; - SharedData(SharedData&&) = delete; + SharedData(const SharedData &) = delete; + SharedData(SharedData &&) = delete; friend class Window; template - static T& getVariable(std::string variableName) { - return std::any_cast(SharedData::sharedVariables[variableName]); + static T &getVariable(std::string variableName) { + return std::any_cast(SharedData::sharedVariables[variableName]); } template @@ -56,20 +65,20 @@ namespace hex { public: static std::vector> deferredCalls; - static std::vector providers; + static std::vector providers; static u32 currentProvider; static std::map> settingsEntries; static nlohmann::json settingsJson; static std::vector commandPaletteCommands; static std::map patternLanguageFunctions; - static std::map views; + static std::map views; static std::vector toolsEntries; static std::vector dataInspectorEntries; static u32 patternPaletteOffset; static std::string popupMessage; static std::list bookmarkEntries; - static std::vector patternData; + static std::vector patternData; static u32 selectableFileIndex; static std::vector selectableFiles; @@ -93,7 +102,7 @@ namespace hex { static std::map> globalShortcuts; static std::mutex tasksMutex; - static std::list runningTasks; + static std::list runningTasks; static std::vector providerNames; diff --git a/lib/libimhex/include/hex/helpers/socket.hpp b/lib/libimhex/include/hex/helpers/socket.hpp index 40f187479..7eff3ae83 100644 --- a/lib/libimhex/include/hex/helpers/socket.hpp +++ b/lib/libimhex/include/hex/helpers/socket.hpp @@ -25,7 +25,7 @@ namespace hex { class Socket { public: Socket() = default; - Socket(const Socket&) = delete; + Socket(const Socket &) = delete; Socket(Socket &&other); Socket(const std::string &address, u16 port); @@ -34,8 +34,7 @@ namespace hex { void connect(const std::string &address, u16 port); void disconnect(); - [[nodiscard]] - bool isConnected() const; + [[nodiscard]] bool isConnected() const; std::string readString(size_t size = 0x1000) const; std::vector readBytes(size_t size = 0x1000) const; @@ -45,11 +44,11 @@ namespace hex { private: bool m_connected = false; - #if defined(OS_WINDOWS) - SOCKET m_socket = SOCKET_NONE; - #else - int m_socket = SOCKET_NONE; - #endif +#if defined(OS_WINDOWS) + SOCKET m_socket = SOCKET_NONE; +#else + int m_socket = SOCKET_NONE; +#endif }; } \ No newline at end of file diff --git a/lib/libimhex/include/hex/helpers/utils.hpp b/lib/libimhex/include/hex/helpers/utils.hpp index d54c25bec..4d829b6cd 100644 --- a/lib/libimhex/include/hex/helpers/utils.hpp +++ b/lib/libimhex/include/hex/helpers/utils.hpp @@ -20,8 +20,8 @@ #include -#define TOKEN_CONCAT_IMPL(x, y) x ## y -#define TOKEN_CONCAT(x, y) TOKEN_CONCAT_IMPL(x, y) +#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__) struct ImVec2; @@ -50,7 +50,7 @@ namespace hex { [[nodiscard]] inline u64 extract(u32 from, u32 to, const std::vector &bytes) { u8 index = 0; - while(from > 32 && to > 32) { + while (from > 32 && to > 32) { if (from - 8 < 0 || to - 8 < 0) return 0; @@ -71,17 +71,24 @@ namespace hex { return (value ^ mask) - mask; } - template struct overloaded : Ts... { using Ts::operator()...; }; - template overloaded(Ts...) -> overloaded; + template + struct overloaded : Ts... { using Ts::operator()...; }; + template + overloaded(Ts...) -> overloaded; template struct SizeTypeImpl { }; - template<> struct SizeTypeImpl<1> { using Type = u8; }; - template<> struct SizeTypeImpl<2> { using Type = u16; }; - template<> struct SizeTypeImpl<4> { using Type = u32; }; - template<> struct SizeTypeImpl<8> { using Type = u64; }; - template<> struct SizeTypeImpl<16> { using Type = u128; }; + template<> + struct SizeTypeImpl<1> { using Type = u8; }; + template<> + struct SizeTypeImpl<2> { using Type = u16; }; + template<> + struct SizeTypeImpl<4> { using Type = u32; }; + template<> + struct SizeTypeImpl<8> { using Type = u64; }; + template<> + struct SizeTypeImpl<16> { using Type = u128; }; template using SizeType = typename SizeTypeImpl::Type; @@ -99,15 +106,26 @@ namespace hex { SizeType swapped; if constexpr (!std::has_single_bit(Size) || Size > 16) - static_assert(always_false::value, "Invalid type provided!"); + static_assert(always_false::value, "Invalid type provided!"); switch (Size) { - case 1: swapped = unswapped; break; - case 2: swapped = __builtin_bswap16(unswapped); break; - case 4: swapped = __builtin_bswap32(unswapped); break; - case 8: swapped = __builtin_bswap64(unswapped); break; - case 16: swapped = (u128(__builtin_bswap64(unswapped & 0xFFFF'FFFF'FFFF'FFFF)) << 64) | __builtin_bswap64(u128(unswapped) >> 64); break; - default: __builtin_unreachable(); + case 1: + swapped = unswapped; + break; + case 2: + swapped = __builtin_bswap16(unswapped); + break; + case 4: + swapped = __builtin_bswap32(unswapped); + break; + case 8: + swapped = __builtin_bswap64(unswapped); + break; + case 16: + swapped = (u128(__builtin_bswap64(unswapped & 0xFFFF'FFFF'FFFF'FFFF)) << 64) | __builtin_bswap64(u128(unswapped) >> 64); + break; + default: + __builtin_unreachable(); } T result; @@ -116,8 +134,7 @@ namespace hex { return result; } - [[nodiscard]] - constexpr u128 bitmask(u8 bits) { + [[nodiscard]] constexpr u128 bitmask(u8 bits) { return u128(-1) >> (128 - bits); } @@ -132,12 +149,23 @@ namespace hex { u128 swapped; switch (size) { - case 1: swapped = unswapped; break; - case 2: swapped = __builtin_bswap16(unswapped); break; - case 4: swapped = __builtin_bswap32(unswapped); break; - case 8: swapped = __builtin_bswap64(unswapped); break; - case 16: swapped = (u128(__builtin_bswap64(unswapped & 0xFFFF'FFFF'FFFF'FFFF)) << 64) | __builtin_bswap64(u128(unswapped) >> 64); break; - default: __builtin_unreachable(); + case 1: + swapped = unswapped; + break; + case 2: + swapped = __builtin_bswap16(unswapped); + break; + case 4: + swapped = __builtin_bswap32(unswapped); + break; + case 8: + swapped = __builtin_bswap64(unswapped); + break; + case 16: + swapped = (u128(__builtin_bswap64(unswapped & 0xFFFF'FFFF'FFFF'FFFF)) << 64) | __builtin_bswap64(u128(unswapped) >> 64); + break; + default: + __builtin_unreachable(); } T result = 0; @@ -146,7 +174,7 @@ namespace hex { return result; } - template< class T > + template constexpr T bit_width(T x) noexcept { return std::numeric_limits::digits - std::countl_zero(x); } @@ -176,12 +204,12 @@ namespace hex { auto byteString = std::string(string); byteString.erase(std::remove(byteString.begin(), byteString.end(), ' '), byteString.end()); - if ((byteString.length() % 2) != 0) return { }; + if ((byteString.length() % 2) != 0) return {}; std::vector result; for (u32 i = 0; i < byteString.length(); i += 2) { if (!std::isxdigit(byteString[i]) || !std::isxdigit(byteString[i + 1])) - return { }; + return {}; result.push_back(std::strtoul(byteString.substr(i, 2).c_str(), nullptr, 16)); } @@ -201,14 +229,15 @@ namespace hex { inline void trimLeft(std::string &s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](unsigned char ch) { - return !std::isspace(ch) && ch >= 0x20; - })); + return !std::isspace(ch) && ch >= 0x20; + })); } - inline void trimRight(std::string &s) { + inline void trimRight(std::string &s) { s.erase(std::find_if(s.rbegin(), s.rend(), [](unsigned char ch) { - return !std::isspace(ch) && ch >= 0x20; - }).base(), s.end()); + return !std::isspace(ch) && ch >= 0x20; + }).base(), + s.end()); } inline void trim(std::string &s) { @@ -233,14 +262,14 @@ namespace hex { } inline bool containsIgnoreCase(const std::string &a, const std::string &b) { - auto iter = std::search(a.begin(), a.end(), b.begin(), b.end(), [](char ch1, char ch2) { + auto iter = std::search(a.begin(), a.end(), b.begin(), b.end(), [](char ch1, char ch2) { return std::toupper(ch1) == std::toupper(ch2); }); return iter != a.end(); } - template + template T get_or(const std::variant &variant, T alt) { const T *value = std::get_if(&variant); if (value == nullptr) @@ -253,30 +282,33 @@ namespace hex { namespace scope_guard { - #define SCOPE_GUARD ::hex::scope_guard::ScopeGuardOnExit() + [&]() - #define ON_SCOPE_EXIT auto ANONYMOUS_VARIABLE(SCOPE_EXIT_) = SCOPE_GUARD +#define SCOPE_GUARD ::hex::scope_guard::ScopeGuardOnExit() + [&]() +#define ON_SCOPE_EXIT auto ANONYMOUS_VARIABLE(SCOPE_EXIT_) = SCOPE_GUARD template class ScopeGuard { private: F m_func; bool m_active; + public: constexpr ScopeGuard(F func) : m_func(std::move(func)), m_active(true) { } - ~ScopeGuard() { if (this->m_active) { this->m_func(); } } + ~ScopeGuard() { + if (this->m_active) { this->m_func(); } + } void release() { this->m_active = false; } ScopeGuard(ScopeGuard &&other) noexcept : m_func(std::move(other.m_func)), m_active(other.m_active) { other.cancel(); } - ScopeGuard& operator=(ScopeGuard &&) = delete; + ScopeGuard &operator=(ScopeGuard &&) = delete; }; enum class ScopeGuardOnExit { }; - template - constexpr ScopeGuard operator+(ScopeGuardOnExit, F&& f) { + template + constexpr ScopeGuard operator+(ScopeGuardOnExit, F &&f) { return ScopeGuard(std::forward(f)); } @@ -284,20 +316,20 @@ namespace hex { namespace first_time_exec { - #define FIRST_TIME static auto ANONYMOUS_VARIABLE(FIRST_TIME_) = ::hex::first_time_exec::FirstTimeExecutor() + [&]() +#define FIRST_TIME static auto ANONYMOUS_VARIABLE(FIRST_TIME_) = ::hex::first_time_exec::FirstTimeExecutor() + [&]() template class FirstTimeExecute { public: constexpr FirstTimeExecute(F func) { func(); } - FirstTimeExecute& operator=(FirstTimeExecute &&) = delete; + FirstTimeExecute &operator=(FirstTimeExecute &&) = delete; }; enum class FirstTimeExecutor { }; - template - constexpr FirstTimeExecute operator+(FirstTimeExecutor, F&& f) { + template + constexpr FirstTimeExecute operator+(FirstTimeExecutor, F &&f) { return FirstTimeExecute(std::forward(f)); } @@ -305,22 +337,23 @@ namespace hex { namespace final_cleanup { - #define FINAL_CLEANUP static auto ANONYMOUS_VARIABLE(ON_EXIT_) = ::hex::final_cleanup::FinalCleanupExecutor() + [&]() +#define FINAL_CLEANUP static auto ANONYMOUS_VARIABLE(ON_EXIT_) = ::hex::final_cleanup::FinalCleanupExecutor() + [&]() template class FinalCleanupExecute { F m_func; + public: constexpr FinalCleanupExecute(F func) : m_func(func) { } constexpr ~FinalCleanupExecute() { this->m_func(); } - FinalCleanupExecute& operator=(FinalCleanupExecute &&) = delete; + FinalCleanupExecute &operator=(FinalCleanupExecute &&) = delete; }; enum class FinalCleanupExecutor { }; - template - constexpr FinalCleanupExecute operator+(FinalCleanupExecutor, F&& f) { + template + constexpr FinalCleanupExecute operator+(FinalCleanupExecutor, F &&f) { return FinalCleanupExecute(std::forward(f)); } diff --git a/lib/libimhex/include/hex/pattern_language/ast_node.hpp b/lib/libimhex/include/hex/pattern_language/ast_node.hpp index c293415ad..b88d372dc 100644 --- a/lib/libimhex/include/hex/pattern_language/ast_node.hpp +++ b/lib/libimhex/include/hex/pattern_language/ast_node.hpp @@ -22,8 +22,7 @@ namespace hex::pl { class Clonable { public: - [[nodiscard]] - virtual ASTNode* clone() const = 0; + [[nodiscard]] virtual ASTNode *clone() const = 0; }; class ASTNode : public Clonable { @@ -52,7 +51,7 @@ namespace hex::pl { class ASTNodeAttribute : public ASTNode { public: explicit ASTNodeAttribute(std::string attribute, std::optional value = std::nullopt) - : ASTNode(), m_attribute(std::move(attribute)), m_value(std::move(value)) { } + : ASTNode(), m_attribute(std::move(attribute)), m_value(std::move(value)) { } ~ASTNodeAttribute() override = default; @@ -61,15 +60,15 @@ namespace hex::pl { this->m_value = other.m_value; } - [[nodiscard]] ASTNode* clone() const override { + [[nodiscard]] ASTNode *clone() const override { return new ASTNodeAttribute(*this); } - [[nodiscard]] const std::string& getAttribute() const { + [[nodiscard]] const std::string &getAttribute() const { return this->m_attribute; } - [[nodiscard]] const std::optional& getValue() const { + [[nodiscard]] const std::optional &getValue() const { return this->m_value; } @@ -88,11 +87,10 @@ namespace hex::pl { Attributable(const Attributable &other) { for (auto &attribute : other.m_attributes) - this->m_attributes.push_back(static_cast(attribute->clone())); + this->m_attributes.push_back(static_cast(attribute->clone())); } public: - void addAttribute(ASTNodeAttribute *attribute) { this->m_attributes.push_back(attribute); } @@ -109,13 +107,13 @@ namespace hex::pl { public: explicit ASTNodeLiteral(Token::Literal literal) : ASTNode(), m_literal(std::move(literal)) { } - ASTNodeLiteral(const ASTNodeLiteral&) = default; + ASTNodeLiteral(const ASTNodeLiteral &) = default; - [[nodiscard]] ASTNode* clone() const override { + [[nodiscard]] ASTNode *clone() const override { return new ASTNodeLiteral(*this); } - [[nodiscard]] const auto& getValue() const { + [[nodiscard]] const auto &getValue() const { return this->m_literal; } @@ -124,11 +122,20 @@ namespace hex::pl { }; class ASTNodeMathematicalExpression : public ASTNode { -#define FLOAT_BIT_OPERATION(name) \ - auto name(hex::floating_point auto left, auto right) const { LogConsole::abortEvaluation("invalid floating point operation", this); return 0; } \ - auto name(auto left, hex::floating_point auto right) const { LogConsole::abortEvaluation("invalid floating point operation", this); return 0; } \ - auto name(hex::floating_point auto left, hex::floating_point auto right) const { LogConsole::abortEvaluation("invalid floating point operation", this); return 0; } \ - auto name(hex::integral auto left, hex::integral auto right) const +#define FLOAT_BIT_OPERATION(name) \ + auto name(hex::floating_point auto left, auto right) const { \ + LogConsole::abortEvaluation("invalid floating point operation", this); \ + return 0; \ + } \ + auto name(auto left, hex::floating_point auto right) const { \ + LogConsole::abortEvaluation("invalid floating point operation", this); \ + return 0; \ + } \ + auto name(hex::floating_point auto left, hex::floating_point auto right) const { \ + LogConsole::abortEvaluation("invalid floating point operation", this); \ + return 0; \ + } \ + auto name(hex::integral auto left, hex::integral auto right) const FLOAT_BIT_OPERATION(shiftLeft) { return left << right; @@ -161,7 +168,7 @@ namespace hex::pl { #undef FLOAT_BIT_OPERATION public: ASTNodeMathematicalExpression(ASTNode *left, ASTNode *right, Token::Operator op) - : ASTNode(), m_left(left), m_right(right), m_operator(op) { } + : ASTNode(), m_left(left), m_right(right), m_operator(op) { } ~ASTNodeMathematicalExpression() override { delete this->m_left; @@ -174,134 +181,139 @@ namespace hex::pl { this->m_right = other.m_right->clone(); } - [[nodiscard]] ASTNode* clone() const override { + [[nodiscard]] ASTNode *clone() const override { return new ASTNodeMathematicalExpression(*this); } - [[nodiscard]] ASTNode* evaluate(Evaluator *evaluator) const override { + [[nodiscard]] ASTNode *evaluate(Evaluator *evaluator) const override { if (this->getLeftOperand() == nullptr || this->getRightOperand() == nullptr) LogConsole::abortEvaluation("attempted to use void expression in mathematical expression", this); - auto *left = dynamic_cast(this->getLeftOperand()->evaluate(evaluator)); - auto *right = dynamic_cast(this->getRightOperand()->evaluate(evaluator)); - ON_SCOPE_EXIT { delete left; delete right; }; + auto *left = dynamic_cast(this->getLeftOperand()->evaluate(evaluator)); + auto *right = dynamic_cast(this->getRightOperand()->evaluate(evaluator)); + ON_SCOPE_EXIT { + delete left; + delete right; + }; return std::visit(overloaded { - // TODO: :notlikethis: - [this](u128 left, PatternData * const &right) -> ASTNode* { LogConsole::abortEvaluation("invalid operand used in mathematical expression", this); }, - [this](i128 left, PatternData * const &right) -> ASTNode* { LogConsole::abortEvaluation("invalid operand used in mathematical expression", this); }, - [this](double left, PatternData * const &right) -> ASTNode* { LogConsole::abortEvaluation("invalid operand used in mathematical expression", this); }, - [this](char left, PatternData * const &right) -> ASTNode* { LogConsole::abortEvaluation("invalid operand used in mathematical expression", this); }, - [this](bool left, PatternData * const &right) -> ASTNode* { LogConsole::abortEvaluation("invalid operand used in mathematical expression", this); }, - [this](std::string left, PatternData * const &right) -> ASTNode* { LogConsole::abortEvaluation("invalid operand used in mathematical expression", this); }, - [this](PatternData * const &left, u128 right) -> ASTNode* { LogConsole::abortEvaluation("invalid operand used in mathematical expression", this); }, - [this](PatternData * const &left, i128 right) -> ASTNode* { LogConsole::abortEvaluation("invalid operand used in mathematical expression", this); }, - [this](PatternData * const &left, double right) -> ASTNode* { LogConsole::abortEvaluation("invalid operand used in mathematical expression", this); }, - [this](PatternData * const &left, char right) -> ASTNode* { LogConsole::abortEvaluation("invalid operand used in mathematical expression", this); }, - [this](PatternData * const &left, bool right) -> ASTNode* { LogConsole::abortEvaluation("invalid operand used in mathematical expression", this); }, - [this](PatternData * const &left, std::string right) -> ASTNode* { LogConsole::abortEvaluation("invalid operand used in mathematical expression", this); }, - [this](PatternData * const &left, PatternData *right) -> ASTNode* { LogConsole::abortEvaluation("invalid operand used in mathematical expression", this); }, + // TODO: :notlikethis: + [this](u128 left, PatternData *const &right) -> ASTNode * { LogConsole::abortEvaluation("invalid operand used in mathematical expression", this); }, + [this](i128 left, PatternData *const &right) -> ASTNode * { LogConsole::abortEvaluation("invalid operand used in mathematical expression", this); }, + [this](double left, PatternData *const &right) -> ASTNode * { LogConsole::abortEvaluation("invalid operand used in mathematical expression", this); }, + [this](char left, PatternData *const &right) -> ASTNode * { LogConsole::abortEvaluation("invalid operand used in mathematical expression", this); }, + [this](bool left, PatternData *const &right) -> ASTNode * { LogConsole::abortEvaluation("invalid operand used in mathematical expression", this); }, + [this](std::string left, PatternData *const &right) -> ASTNode * { LogConsole::abortEvaluation("invalid operand used in mathematical expression", this); }, + [this](PatternData *const &left, u128 right) -> ASTNode * { LogConsole::abortEvaluation("invalid operand used in mathematical expression", this); }, + [this](PatternData *const &left, i128 right) -> ASTNode * { LogConsole::abortEvaluation("invalid operand used in mathematical expression", this); }, + [this](PatternData *const &left, double right) -> ASTNode * { LogConsole::abortEvaluation("invalid operand used in mathematical expression", this); }, + [this](PatternData *const &left, char right) -> ASTNode * { LogConsole::abortEvaluation("invalid operand used in mathematical expression", this); }, + [this](PatternData *const &left, bool right) -> ASTNode * { LogConsole::abortEvaluation("invalid operand used in mathematical expression", this); }, + [this](PatternData *const &left, std::string right) -> ASTNode * { LogConsole::abortEvaluation("invalid operand used in mathematical expression", this); }, + [this](PatternData *const &left, PatternData *right) -> ASTNode * { LogConsole::abortEvaluation("invalid operand used in mathematical expression", this); }, - [this](auto&& left, std::string right) -> ASTNode* { LogConsole::abortEvaluation("invalid operand used in mathematical expression", this); }, - [this](std::string left, auto&& right) -> ASTNode* { - switch (this->getOperator()) { - case Token::Operator::Star: { - std::string result; - for (auto i = 0; i < right; i++) - result += left; - return new ASTNodeLiteral(result); - } - default: - LogConsole::abortEvaluation("invalid operand used in mathematical expression", this); - } - }, - [this](std::string left, std::string right) -> ASTNode* { - switch (this->getOperator()) { - case Token::Operator::Plus: - return new ASTNodeLiteral(left + right); - case Token::Operator::BoolEquals: - return new ASTNodeLiteral(left == right); - case Token::Operator::BoolNotEquals: - return new ASTNodeLiteral(left != right); - case Token::Operator::BoolGreaterThan: - return new ASTNodeLiteral(left > right); - case Token::Operator::BoolLessThan: - return new ASTNodeLiteral(left < right); - case Token::Operator::BoolGreaterThanOrEquals: - return new ASTNodeLiteral(left >= right); - case Token::Operator::BoolLessThanOrEquals: - return new ASTNodeLiteral(left <= right); - default: - LogConsole::abortEvaluation("invalid operand used in mathematical expression", this); - } - }, - [this](std::string left, char right) -> ASTNode* { - switch (this->getOperator()) { - case Token::Operator::Plus: - return new ASTNodeLiteral(left + right); - default: - LogConsole::abortEvaluation("invalid operand used in mathematical expression", this); - } - }, - [this](char left, std::string right) -> ASTNode* { - switch (this->getOperator()) { - case Token::Operator::Plus: - return new ASTNodeLiteral(left + right); - default: - LogConsole::abortEvaluation("invalid operand used in mathematical expression", this); - } - }, - [this](auto &&left, auto &&right) -> ASTNode* { - switch (this->getOperator()) { - case Token::Operator::Plus: - return new ASTNodeLiteral(left + right); - case Token::Operator::Minus: - return new ASTNodeLiteral(left - right); - case Token::Operator::Star: - return new ASTNodeLiteral(left * right); - case Token::Operator::Slash: - if (right == 0) LogConsole::abortEvaluation("division by zero!", this); - return new ASTNodeLiteral(left / right); - case Token::Operator::Percent: - if (right == 0) LogConsole::abortEvaluation("division by zero!", this); - return new ASTNodeLiteral(modulus(left, right)); - case Token::Operator::ShiftLeft: - return new ASTNodeLiteral(shiftLeft(left, right)); - case Token::Operator::ShiftRight: - return new ASTNodeLiteral(shiftRight(left, right)); - case Token::Operator::BitAnd: - return new ASTNodeLiteral(bitAnd(left, right)); - case Token::Operator::BitXor: - return new ASTNodeLiteral(bitXor(left, right)); - case Token::Operator::BitOr: - return new ASTNodeLiteral(bitOr(left, right)); - case Token::Operator::BitNot: - return new ASTNodeLiteral(bitNot(left, right)); - case Token::Operator::BoolEquals: - return new ASTNodeLiteral(bool(left == right)); - case Token::Operator::BoolNotEquals: - return new ASTNodeLiteral(bool(left != right)); - case Token::Operator::BoolGreaterThan: - return new ASTNodeLiteral(bool(left > right)); - case Token::Operator::BoolLessThan: - return new ASTNodeLiteral(bool(left < right)); - case Token::Operator::BoolGreaterThanOrEquals: - return new ASTNodeLiteral(bool(left >= right)); - case Token::Operator::BoolLessThanOrEquals: - return new ASTNodeLiteral(bool(left <= right)); - case Token::Operator::BoolAnd: - return new ASTNodeLiteral(bool(left && right)); - case Token::Operator::BoolXor: - return new ASTNodeLiteral(bool(left && !right || !left && right)); - case Token::Operator::BoolOr: - return new ASTNodeLiteral(bool(left || right)); - case Token::Operator::BoolNot: - return new ASTNodeLiteral(bool(!right)); - default: - LogConsole::abortEvaluation("invalid operand used in mathematical expression", this); - } - } - }, left->getValue(), right->getValue()); + [this](auto &&left, std::string right) -> ASTNode * { LogConsole::abortEvaluation("invalid operand used in mathematical expression", this); }, + [this](std::string left, auto &&right) -> ASTNode * { + switch (this->getOperator()) { + case Token::Operator::Star: + { + std::string result; + for (auto i = 0; i < right; i++) + result += left; + return new ASTNodeLiteral(result); + } + default: + LogConsole::abortEvaluation("invalid operand used in mathematical expression", this); + } + }, + [this](std::string left, std::string right) -> ASTNode * { + switch (this->getOperator()) { + case Token::Operator::Plus: + return new ASTNodeLiteral(left + right); + case Token::Operator::BoolEquals: + return new ASTNodeLiteral(left == right); + case Token::Operator::BoolNotEquals: + return new ASTNodeLiteral(left != right); + case Token::Operator::BoolGreaterThan: + return new ASTNodeLiteral(left > right); + case Token::Operator::BoolLessThan: + return new ASTNodeLiteral(left < right); + case Token::Operator::BoolGreaterThanOrEquals: + return new ASTNodeLiteral(left >= right); + case Token::Operator::BoolLessThanOrEquals: + return new ASTNodeLiteral(left <= right); + default: + LogConsole::abortEvaluation("invalid operand used in mathematical expression", this); + } + }, + [this](std::string left, char right) -> ASTNode * { + switch (this->getOperator()) { + case Token::Operator::Plus: + return new ASTNodeLiteral(left + right); + default: + LogConsole::abortEvaluation("invalid operand used in mathematical expression", this); + } + }, + [this](char left, std::string right) -> ASTNode * { + switch (this->getOperator()) { + case Token::Operator::Plus: + return new ASTNodeLiteral(left + right); + default: + LogConsole::abortEvaluation("invalid operand used in mathematical expression", this); + } + }, + [this](auto &&left, auto &&right) -> ASTNode * { + switch (this->getOperator()) { + case Token::Operator::Plus: + return new ASTNodeLiteral(left + right); + case Token::Operator::Minus: + return new ASTNodeLiteral(left - right); + case Token::Operator::Star: + return new ASTNodeLiteral(left * right); + case Token::Operator::Slash: + if (right == 0) LogConsole::abortEvaluation("division by zero!", this); + return new ASTNodeLiteral(left / right); + case Token::Operator::Percent: + if (right == 0) LogConsole::abortEvaluation("division by zero!", this); + return new ASTNodeLiteral(modulus(left, right)); + case Token::Operator::ShiftLeft: + return new ASTNodeLiteral(shiftLeft(left, right)); + case Token::Operator::ShiftRight: + return new ASTNodeLiteral(shiftRight(left, right)); + case Token::Operator::BitAnd: + return new ASTNodeLiteral(bitAnd(left, right)); + case Token::Operator::BitXor: + return new ASTNodeLiteral(bitXor(left, right)); + case Token::Operator::BitOr: + return new ASTNodeLiteral(bitOr(left, right)); + case Token::Operator::BitNot: + return new ASTNodeLiteral(bitNot(left, right)); + case Token::Operator::BoolEquals: + return new ASTNodeLiteral(bool(left == right)); + case Token::Operator::BoolNotEquals: + return new ASTNodeLiteral(bool(left != right)); + case Token::Operator::BoolGreaterThan: + return new ASTNodeLiteral(bool(left > right)); + case Token::Operator::BoolLessThan: + return new ASTNodeLiteral(bool(left < right)); + case Token::Operator::BoolGreaterThanOrEquals: + return new ASTNodeLiteral(bool(left >= right)); + case Token::Operator::BoolLessThanOrEquals: + return new ASTNodeLiteral(bool(left <= right)); + case Token::Operator::BoolAnd: + return new ASTNodeLiteral(bool(left && right)); + case Token::Operator::BoolXor: + return new ASTNodeLiteral(bool(left && !right || !left && right)); + case Token::Operator::BoolOr: + return new ASTNodeLiteral(bool(left || right)); + case Token::Operator::BoolNot: + return new ASTNodeLiteral(bool(!right)); + default: + LogConsole::abortEvaluation("invalid operand used in mathematical expression", this); + } + } }, + left->getValue(), + right->getValue()); } [[nodiscard]] ASTNode *getLeftOperand() const { return this->m_left; } @@ -316,7 +328,7 @@ namespace hex::pl { class ASTNodeTernaryExpression : public ASTNode { public: ASTNodeTernaryExpression(ASTNode *first, ASTNode *second, ASTNode *third, Token::Operator op) - : ASTNode(), m_first(first), m_second(second), m_third(third), m_operator(op) { } + : ASTNode(), m_first(first), m_second(second), m_third(third), m_operator(op) { } ~ASTNodeTernaryExpression() override { delete this->m_first; @@ -331,29 +343,34 @@ namespace hex::pl { this->m_third = other.m_third->clone(); } - [[nodiscard]] ASTNode* clone() const override { + [[nodiscard]] ASTNode *clone() const override { return new ASTNodeTernaryExpression(*this); } - [[nodiscard]] ASTNode* evaluate(Evaluator *evaluator) const override { + [[nodiscard]] ASTNode *evaluate(Evaluator *evaluator) const override { if (this->getFirstOperand() == nullptr || this->getSecondOperand() == nullptr || this->getThirdOperand() == nullptr) LogConsole::abortEvaluation("attempted to use void expression in mathematical expression", this); - auto *first = dynamic_cast(this->getFirstOperand()->evaluate(evaluator)); - auto *second = dynamic_cast(this->getSecondOperand()->evaluate(evaluator)); - auto *third = dynamic_cast(this->getThirdOperand()->evaluate(evaluator)); - ON_SCOPE_EXIT { delete first; delete second; delete third; }; + auto *first = dynamic_cast(this->getFirstOperand()->evaluate(evaluator)); + auto *second = dynamic_cast(this->getSecondOperand()->evaluate(evaluator)); + auto *third = dynamic_cast(this->getThirdOperand()->evaluate(evaluator)); + ON_SCOPE_EXIT { + delete first; + delete second; + delete third; + }; auto condition = std::visit(overloaded { - [this](std::string value) -> bool { return !value.empty(); }, - [this](PatternData * const &) -> bool { LogConsole::abortEvaluation("cannot cast custom type to bool", this); }, - [](auto &&value) -> bool { return bool(value); } - }, first->getValue()); + [this](std::string value) -> bool { return !value.empty(); }, + [this](PatternData *const &) -> bool { LogConsole::abortEvaluation("cannot cast custom type to bool", this); }, + [](auto &&value) -> bool { return bool(value); } }, + first->getValue()); return std::visit(overloaded { - [condition](const T &second, const T &third) -> ASTNode* { return new ASTNodeLiteral(condition ? second : third); }, - [this](auto &&second, auto &&third) -> ASTNode* { LogConsole::abortEvaluation("operands to ternary expression have different types", this); } - }, second->getValue(), third->getValue()); + [condition](const T &second, const T &third) -> ASTNode * { return new ASTNodeLiteral(condition ? second : third); }, + [this](auto &&second, auto &&third) -> ASTNode * { LogConsole::abortEvaluation("operands to ternary expression have different types", this); } }, + second->getValue(), + third->getValue()); } [[nodiscard]] ASTNode *getFirstOperand() const { return this->m_first; } @@ -369,15 +386,15 @@ namespace hex::pl { class ASTNodeBuiltinType : public ASTNode { public: constexpr explicit ASTNodeBuiltinType(Token::ValueType type) - : ASTNode(), m_type(type) { } + : ASTNode(), m_type(type) { } - [[nodiscard]] constexpr const auto& getType() const { return this->m_type; } + [[nodiscard]] constexpr const auto &getType() const { return this->m_type; } - [[nodiscard]] ASTNode* clone() const override { + [[nodiscard]] ASTNode *clone() const override { return new ASTNodeBuiltinType(*this); } - [[nodiscard]] std::vector createPatterns(Evaluator *evaluator) const override { + [[nodiscard]] std::vector createPatterns(Evaluator *evaluator) const override { auto offset = evaluator->dataOffset(); auto size = Token::getTypeSize(this->m_type); @@ -414,38 +431,39 @@ namespace hex::pl { const Token::ValueType m_type; }; - class ASTNodeTypeDecl : public ASTNode, public Attributable { + class ASTNodeTypeDecl : public ASTNode, + public Attributable { public: ASTNodeTypeDecl(std::string name, ASTNode *type, std::optional endian = std::nullopt) - : ASTNode(), m_name(std::move(name)), m_type(type), m_endian(endian) { } + : ASTNode(), m_name(std::move(name)), m_type(type), m_endian(endian) { } - ASTNodeTypeDecl(const ASTNodeTypeDecl& other) : ASTNode(other), Attributable(other) { + ASTNodeTypeDecl(const ASTNodeTypeDecl &other) : ASTNode(other), Attributable(other) { this->m_name = other.m_name; this->m_type = other.m_type; this->m_endian = other.m_endian; } - [[nodiscard]] ASTNode* clone() const override { + [[nodiscard]] ASTNode *clone() const override { return new ASTNodeTypeDecl(*this); } void setName(const std::string &name) { this->m_name = name; } - [[nodiscard]] const std::string& getName() const { return this->m_name; } - [[nodiscard]] ASTNode* getType() { return this->m_type; } + [[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; } [[nodiscard]] ASTNode *evaluate(Evaluator *evaluator) const override { auto type = this->m_type->evaluate(evaluator); - if (auto attributable = dynamic_cast(type)) { + if (auto attributable = dynamic_cast(type)) { for (auto &attribute : this->getAttributes()) - attributable->addAttribute(static_cast(attribute->clone())); + attributable->addAttribute(static_cast(attribute->clone())); } return type; } - [[nodiscard]] std::vector createPatterns(Evaluator *evaluator) const override { + [[nodiscard]] std::vector createPatterns(Evaluator *evaluator) const override { auto patterns = this->m_type->createPatterns(evaluator); for (auto &pattern : patterns) { @@ -479,74 +497,75 @@ namespace hex::pl { delete this->m_type; } - [[nodiscard]] ASTNode* clone() const override { + [[nodiscard]] ASTNode *clone() const override { return new ASTNodeCast(*this); } - [[nodiscard]] ASTNode* evaluate(Evaluator *evaluator) const override { - auto literal = dynamic_cast(this->m_value->evaluate(evaluator)); - auto type = dynamic_cast(this->m_type->evaluate(evaluator))->getType(); + [[nodiscard]] ASTNode *evaluate(Evaluator *evaluator) const override { + auto literal = dynamic_cast(this->m_value->evaluate(evaluator)); + auto type = dynamic_cast(this->m_type->evaluate(evaluator))->getType(); - auto startOffset= evaluator->dataOffset(); + auto startOffset = evaluator->dataOffset(); auto typePattern = this->m_type->createPatterns(evaluator).front(); ON_SCOPE_EXIT { - evaluator->dataOffset() = startOffset; - delete typePattern; - }; + evaluator->dataOffset() = startOffset; + delete typePattern; + }; return std::visit(overloaded { - [&, this](PatternData * value) -> ASTNode* { LogConsole::abortEvaluation(hex::format("cannot cast custom type '{}' to '{}'", value->getTypeName(), Token::getTypeName(type)), this); }, - [&, this](const std::string&) -> ASTNode* { LogConsole::abortEvaluation(hex::format("cannot cast string to '{}'", Token::getTypeName(type)), this); }, - [&, this](auto &&value) -> ASTNode* { - auto endianAdjustedValue = hex::changeEndianess(value, typePattern->getSize(), typePattern->getEndian()); - switch (type) { - case Token::ValueType::Unsigned8Bit: - return new ASTNodeLiteral(u128(u8(endianAdjustedValue))); - case Token::ValueType::Unsigned16Bit: - return new ASTNodeLiteral(u128(u16(endianAdjustedValue))); - case Token::ValueType::Unsigned32Bit: - return new ASTNodeLiteral(u128(u32(endianAdjustedValue))); - case Token::ValueType::Unsigned64Bit: - return new ASTNodeLiteral(u128(u64(endianAdjustedValue))); - case Token::ValueType::Unsigned128Bit: - return new ASTNodeLiteral(u128(endianAdjustedValue)); - case Token::ValueType::Signed8Bit: - return new ASTNodeLiteral(i128(i8(endianAdjustedValue))); - case Token::ValueType::Signed16Bit: - return new ASTNodeLiteral(i128(i16(endianAdjustedValue))); - case Token::ValueType::Signed32Bit: - return new ASTNodeLiteral(i128(i32(endianAdjustedValue))); - case Token::ValueType::Signed64Bit: - return new ASTNodeLiteral(i128(i64(endianAdjustedValue))); - case Token::ValueType::Signed128Bit: - return new ASTNodeLiteral(i128(endianAdjustedValue)); - case Token::ValueType::Float: - return new ASTNodeLiteral(double(float(endianAdjustedValue))); - case Token::ValueType::Double: - return new ASTNodeLiteral(double(endianAdjustedValue)); - case Token::ValueType::Character: - return new ASTNodeLiteral(char(endianAdjustedValue)); - case Token::ValueType::Character16: - return new ASTNodeLiteral(u128(char16_t(endianAdjustedValue))); - case Token::ValueType::Boolean: - return new ASTNodeLiteral(bool(endianAdjustedValue)); - case Token::ValueType::String: - { - std::string string(sizeof(value), '\x00'); - std::memcpy(string.data(), &value, string.size()); - hex::trim(string); + [&, this](PatternData *value) -> ASTNode * { LogConsole::abortEvaluation(hex::format("cannot cast custom type '{}' to '{}'", value->getTypeName(), Token::getTypeName(type)), this); }, + [&, this](const std::string &) -> ASTNode * { LogConsole::abortEvaluation(hex::format("cannot cast string to '{}'", Token::getTypeName(type)), this); }, + [&, this](auto &&value) -> ASTNode * { + auto endianAdjustedValue = hex::changeEndianess(value, typePattern->getSize(), typePattern->getEndian()); + switch (type) { + case Token::ValueType::Unsigned8Bit: + return new ASTNodeLiteral(u128(u8(endianAdjustedValue))); + case Token::ValueType::Unsigned16Bit: + return new ASTNodeLiteral(u128(u16(endianAdjustedValue))); + case Token::ValueType::Unsigned32Bit: + return new ASTNodeLiteral(u128(u32(endianAdjustedValue))); + case Token::ValueType::Unsigned64Bit: + return new ASTNodeLiteral(u128(u64(endianAdjustedValue))); + case Token::ValueType::Unsigned128Bit: + return new ASTNodeLiteral(u128(endianAdjustedValue)); + case Token::ValueType::Signed8Bit: + return new ASTNodeLiteral(i128(i8(endianAdjustedValue))); + case Token::ValueType::Signed16Bit: + return new ASTNodeLiteral(i128(i16(endianAdjustedValue))); + case Token::ValueType::Signed32Bit: + return new ASTNodeLiteral(i128(i32(endianAdjustedValue))); + case Token::ValueType::Signed64Bit: + return new ASTNodeLiteral(i128(i64(endianAdjustedValue))); + case Token::ValueType::Signed128Bit: + return new ASTNodeLiteral(i128(endianAdjustedValue)); + case Token::ValueType::Float: + return new ASTNodeLiteral(double(float(endianAdjustedValue))); + case Token::ValueType::Double: + return new ASTNodeLiteral(double(endianAdjustedValue)); + case Token::ValueType::Character: + return new ASTNodeLiteral(char(endianAdjustedValue)); + case Token::ValueType::Character16: + return new ASTNodeLiteral(u128(char16_t(endianAdjustedValue))); + case Token::ValueType::Boolean: + return new ASTNodeLiteral(bool(endianAdjustedValue)); + case Token::ValueType::String: + { + std::string string(sizeof(value), '\x00'); + std::memcpy(string.data(), &value, string.size()); + hex::trim(string); - if (typePattern->getEndian() != std::endian::native) - std::reverse(string.begin(), string.end()); + if (typePattern->getEndian() != std::endian::native) + std::reverse(string.begin(), string.end()); - return new ASTNodeLiteral(string); - } - default: - LogConsole::abortEvaluation(hex::format("cannot cast value to '{}'", Token::getTypeName(type)), this); - } - }, - }, literal->getValue()); + return new ASTNodeLiteral(string); + } + default: + LogConsole::abortEvaluation(hex::format("cannot cast value to '{}'", Token::getTypeName(type)), this); + } + }, + }, + literal->getValue()); } private: @@ -556,8 +575,8 @@ namespace hex::pl { class ASTNodeWhileStatement : public ASTNode { public: - explicit ASTNodeWhileStatement(ASTNode *condition, std::vector body, ASTNode *postExpression = nullptr) - : ASTNode(), m_condition(condition), m_body(std::move(body)), m_postExpression(postExpression) { } + explicit ASTNodeWhileStatement(ASTNode *condition, std::vector body, ASTNode *postExpression = nullptr) + : ASTNode(), m_condition(condition), m_body(std::move(body)), m_postExpression(postExpression) { } ~ASTNodeWhileStatement() override { delete this->m_condition; @@ -580,15 +599,15 @@ namespace hex::pl { this->m_postExpression = nullptr; } - [[nodiscard]] ASTNode* clone() const override { + [[nodiscard]] ASTNode *clone() const override { return new ASTNodeWhileStatement(*this); } - [[nodiscard]] ASTNode* getCondition() { + [[nodiscard]] ASTNode *getCondition() { return this->m_condition; } - [[nodiscard]] const std::vector& getBody() { + [[nodiscard]] const std::vector &getBody() { return this->m_body; } @@ -601,14 +620,14 @@ namespace hex::pl { auto variables = *evaluator->getScope(0).scope; u32 startVariableCount = variables.size(); ON_SCOPE_EXIT { - i64 stackSize = evaluator->getStack().size(); - for (u32 i = startVariableCount; i < variables.size(); i++) { - stackSize--; - delete variables[i]; - } - if (stackSize < 0) LogConsole::abortEvaluation("stack pointer underflow!", this); - evaluator->getStack().resize(stackSize); - }; + i64 stackSize = evaluator->getStack().size(); + for (u32 i = startVariableCount; i < variables.size(); i++) { + stackSize--; + delete variables[i]; + } + if (stackSize < 0) LogConsole::abortEvaluation("stack pointer underflow!", this); + evaluator->getStack().resize(stackSize); + }; evaluator->pushScope(nullptr, variables); ON_SCOPE_EXIT { evaluator->popScope(); }; @@ -640,24 +659,23 @@ namespace hex::pl { continue; } - return { }; + return {}; } - [[nodiscard]] - bool evaluateCondition(Evaluator *evaluator) const { - auto literal = dynamic_cast(this->m_condition->evaluate(evaluator)); + [[nodiscard]] bool evaluateCondition(Evaluator *evaluator) const { + auto literal = dynamic_cast(this->m_condition->evaluate(evaluator)); ON_SCOPE_EXIT { delete literal; }; return std::visit(overloaded { - [](std::string value) -> bool { return !value.empty(); }, - [this](PatternData * const &) -> bool { LogConsole::abortEvaluation("cannot cast custom type to bool", this); }, - [](auto &&value) -> bool { return value != 0; } - }, literal->getValue()); + [](std::string value) -> bool { return !value.empty(); }, + [this](PatternData *const &) -> bool { LogConsole::abortEvaluation("cannot cast custom type to bool", this); }, + [](auto &&value) -> bool { return value != 0; } }, + literal->getValue()); } private: ASTNode *m_condition; - std::vector m_body; + std::vector m_body; ASTNode *m_postExpression; }; @@ -670,7 +688,7 @@ namespace hex::pl { auto &name = attribute->getAttribute(); auto value = attribute->getValue(); - auto node = reinterpret_cast(attributable); + auto node = reinterpret_cast(attributable); auto requiresValue = [&]() { if (!value.has_value()) @@ -696,7 +714,7 @@ namespace hex::pl { } else if (name == "no_unique_address" && noValue()) { endOffset -= pattern->getSize(); } else if (name == "inline" && noValue()) { - auto inlinable = dynamic_cast(pattern); + auto inlinable = dynamic_cast(pattern); if (inlinable == nullptr) LogConsole::abortEvaluation("inline attribute can only be applied to nested types", node); @@ -732,7 +750,7 @@ namespace hex::pl { if (function.parameterCount != 1) LogConsole::abortEvaluation("pointer base function needs exactly one parameter", node); - if (auto pointerPattern = dynamic_cast(pattern)) { + if (auto pointerPattern = dynamic_cast(pattern)) { u128 pointerValue = pointerPattern->getPointedAtAddress(); auto result = function.func(evaluator, { pointerValue }); @@ -748,10 +766,11 @@ namespace hex::pl { } } - class ASTNodeVariableDecl : public ASTNode, public Attributable { + class ASTNodeVariableDecl : public ASTNode, + public Attributable { public: ASTNodeVariableDecl(std::string name, ASTNode *type, ASTNode *placementOffset = nullptr, bool inVariable = false, bool outVariable = false) - : ASTNode(), m_name(std::move(name)), m_type(type), m_placementOffset(placementOffset), m_inVariable(inVariable), m_outVariable(outVariable) { } + : ASTNode(), m_name(std::move(name)), m_type(type), m_placementOffset(placementOffset), m_inVariable(inVariable), m_outVariable(outVariable) { } ASTNodeVariableDecl(const ASTNodeVariableDecl &other) : ASTNode(other), Attributable(other) { this->m_name = other.m_name; @@ -768,27 +787,27 @@ namespace hex::pl { delete this->m_placementOffset; } - [[nodiscard]] ASTNode* clone() const override { + [[nodiscard]] ASTNode *clone() const override { return new ASTNodeVariableDecl(*this); } - [[nodiscard]] const std::string& getName() const { return this->m_name; } - [[nodiscard]] constexpr ASTNode* getType() const { return this->m_type; } + [[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; } [[nodiscard]] constexpr bool isInVariable() const { return this->m_inVariable; } [[nodiscard]] constexpr bool isOutVariable() const { return this->m_outVariable; } - [[nodiscard]] std::vector createPatterns(Evaluator *evaluator) const override { + [[nodiscard]] std::vector createPatterns(Evaluator *evaluator) const override { if (this->m_placementOffset != nullptr) { auto offset = dynamic_cast(this->m_placementOffset->evaluate(evaluator)); ON_SCOPE_EXIT { delete offset; }; evaluator->dataOffset() = std::visit(overloaded { - [this](std::string) -> u64 { LogConsole::abortEvaluation("placement offset cannot be a string", this); }, - [this](PatternData * const &) -> u64 { LogConsole::abortEvaluation("placement offset cannot be a custom type", this); }, - [](auto &&offset) -> u64 { return offset; } - }, offset->getValue()); + [this](std::string) -> u64 { LogConsole::abortEvaluation("placement offset cannot be a string", this); }, + [this](PatternData *const &) -> u64 { LogConsole::abortEvaluation("placement offset cannot be a custom type", this); }, + [](auto &&offset) -> u64 { return offset; } }, + offset->getValue()); } auto pattern = this->m_type->createPatterns(evaluator).front(); @@ -802,7 +821,7 @@ namespace hex::pl { FunctionResult execute(Evaluator *evaluator) const override { evaluator->createVariable(this->getName(), this->getType()); - return { }; + return {}; } private: @@ -813,10 +832,11 @@ namespace hex::pl { bool m_inVariable, m_outVariable; }; - class ASTNodeArrayVariableDecl : public ASTNode, public Attributable { + class ASTNodeArrayVariableDecl : public ASTNode, + public Attributable { public: 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) { } + : 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; @@ -838,29 +858,29 @@ namespace hex::pl { delete this->m_placementOffset; } - [[nodiscard]] ASTNode* clone() const override { + [[nodiscard]] ASTNode *clone() const override { return new ASTNodeArrayVariableDecl(*this); } - [[nodiscard]] std::vector createPatterns(Evaluator *evaluator) const override { + [[nodiscard]] std::vector createPatterns(Evaluator *evaluator) const override { if (this->m_placementOffset != nullptr) { - auto offset = dynamic_cast(this->m_placementOffset->evaluate(evaluator)); + auto offset = dynamic_cast(this->m_placementOffset->evaluate(evaluator)); ON_SCOPE_EXIT { delete offset; }; evaluator->dataOffset() = std::visit(overloaded { - [this](std::string) -> u64 { LogConsole::abortEvaluation("placement offset cannot be a string", this); }, - [this](PatternData * const &) -> u64 { LogConsole::abortEvaluation("placement offset cannot be a custom type", this); }, - [](auto &&offset) -> u64 { return offset; } - }, offset->getValue()); + [this](std::string) -> u64 { LogConsole::abortEvaluation("placement offset cannot be a string", this); }, + [this](PatternData *const &) -> u64 { LogConsole::abortEvaluation("placement offset cannot be a custom type", this); }, + [](auto &&offset) -> u64 { return offset; } }, + offset->getValue()); } auto type = this->m_type->evaluate(evaluator); ON_SCOPE_EXIT { delete type; }; PatternData *pattern; - if (dynamic_cast(type)) + if (dynamic_cast(type)) pattern = createStaticArray(evaluator); - else if (auto attributable = dynamic_cast(type)) { + else if (auto attributable = dynamic_cast(type)) { auto &attributes = attributable->getAttributes(); bool isStaticType = std::any_of(attributes.begin(), attributes.end(), [](ASTNodeAttribute *attribute) { @@ -879,9 +899,9 @@ namespace hex::pl { return { pattern }; } - [[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]] 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; } private: @@ -890,7 +910,7 @@ namespace hex::pl { ASTNode *m_size; ASTNode *m_placementOffset; - PatternData* createStaticArray(Evaluator *evaluator) const { + PatternData *createStaticArray(Evaluator *evaluator) const { u64 startOffset = evaluator->dataOffset(); PatternData *templatePattern = this->m_type->createPatterns(evaluator).front(); @@ -904,13 +924,13 @@ namespace hex::pl { auto sizeNode = this->m_size->evaluate(evaluator); ON_SCOPE_EXIT { delete sizeNode; }; - if (auto literal = dynamic_cast(sizeNode)) { + if (auto literal = dynamic_cast(sizeNode)) { entryCount = std::visit(overloaded { - [this](std::string) -> u128 { LogConsole::abortEvaluation("cannot use string to index array", this); }, - [this](PatternData*) -> u128 { LogConsole::abortEvaluation("cannot use custom type to index array", this); }, - [](auto &&size) -> u128 { return size; } - }, literal->getValue()); - } else if (auto whileStatement = dynamic_cast(sizeNode)) { + [this](std::string) -> u128 { LogConsole::abortEvaluation("cannot use string to index array", this); }, + [this](PatternData *) -> u128 { LogConsole::abortEvaluation("cannot use custom type to index array", this); }, + [](auto &&size) -> u128 { return size; } }, + literal->getValue()); + } else if (auto whileStatement = dynamic_cast(sizeNode)) { while (whileStatement->evaluateCondition(evaluator)) { entryCount++; evaluator->dataOffset() += templatePattern->getSize(); @@ -942,11 +962,11 @@ namespace hex::pl { } PatternData *outputPattern; - if (dynamic_cast(templatePattern)) { + if (dynamic_cast(templatePattern)) { outputPattern = new PatternDataPadding(startOffset, 0, evaluator); - } else if (dynamic_cast(templatePattern)) { + } else if (dynamic_cast(templatePattern)) { outputPattern = new PatternDataString(startOffset, 0, evaluator); - } else if (dynamic_cast(templatePattern)) { + } else if (dynamic_cast(templatePattern)) { outputPattern = new PatternDataString16(startOffset, 0, evaluator); } else { auto arrayPattern = new PatternDataStaticArray(startOffset, 0, evaluator); @@ -965,7 +985,7 @@ namespace hex::pl { return outputPattern; } - PatternData* createDynamicArray(Evaluator *evaluator) const { + PatternData *createDynamicArray(Evaluator *evaluator) const { auto arrayPattern = new PatternDataDynamicArray(evaluator->dataOffset(), 0, evaluator); arrayPattern->setVariableName(this->m_name); @@ -978,7 +998,7 @@ namespace hex::pl { size_t size = 0; u64 entryIndex = 0; - auto addEntries = [&](const std::vector &patterns) { + auto addEntries = [&](const std::vector &patterns) { for (auto pattern : patterns) { pattern->setVariableName(hex::format("[{}]", entryIndex)); pattern->setEndian(arrayPattern->getEndian()); @@ -1003,12 +1023,12 @@ namespace hex::pl { auto sizeNode = this->m_size->evaluate(evaluator); ON_SCOPE_EXIT { delete sizeNode; }; - if (auto literal = dynamic_cast(sizeNode)) { - auto entryCount = std::visit(overloaded{ - [this](std::string) -> u128 { LogConsole::abortEvaluation("cannot use string to index array", this); }, - [this](PatternData*) -> u128 { LogConsole::abortEvaluation("cannot use custom type to index array", this); }, - [](auto &&size) -> u128 { return size; } - }, literal->getValue()); + if (auto literal = dynamic_cast(sizeNode)) { + auto entryCount = std::visit(overloaded { + [this](std::string) -> u128 { LogConsole::abortEvaluation("cannot use string to index array", this); }, + [this](PatternData *) -> u128 { LogConsole::abortEvaluation("cannot use custom type to index array", this); }, + [](auto &&size) -> u128 { return size; } }, + literal->getValue()); auto limit = evaluator->getArrayLimit(); if (entryCount > limit) @@ -1031,7 +1051,7 @@ namespace hex::pl { continue; } } - } else if (auto whileStatement = dynamic_cast(sizeNode)) { + } else if (auto whileStatement = dynamic_cast(sizeNode)) { while (whileStatement->evaluateCondition(evaluator)) { auto limit = evaluator->getArrayLimit(); if (entryIndex > limit) @@ -1114,10 +1134,11 @@ namespace hex::pl { } }; - class ASTNodePointerVariableDecl : public ASTNode, public Attributable { + class ASTNodePointerVariableDecl : public ASTNode, + public Attributable { public: 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) { } + : 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; @@ -1136,25 +1157,25 @@ namespace hex::pl { delete this->m_placementOffset; } - [[nodiscard]] ASTNode* clone() const override { + [[nodiscard]] ASTNode *clone() const override { return new ASTNodePointerVariableDecl(*this); } - [[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]] 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; } - [[nodiscard]] std::vector createPatterns(Evaluator *evaluator) const override { + [[nodiscard]] std::vector createPatterns(Evaluator *evaluator) const override { if (this->m_placementOffset != nullptr) { auto offset = dynamic_cast(this->m_placementOffset->evaluate(evaluator)); ON_SCOPE_EXIT { delete offset; }; evaluator->dataOffset() = std::visit(overloaded { - [this](std::string) -> u64 { LogConsole::abortEvaluation("placement offset cannot be a string", this); }, - [this](PatternData*) -> u64 { LogConsole::abortEvaluation("placement offset cannot be a custom type", this); }, - [](auto &&offset) -> u64 { return u64(offset); } - }, offset->getValue()); + [this](std::string) -> u64 { LogConsole::abortEvaluation("placement offset cannot be a string", this); }, + [this](PatternData *) -> u64 { LogConsole::abortEvaluation("placement offset cannot be a custom type", this); }, + [](auto &&offset) -> u64 { return u64(offset); } }, + offset->getValue()); } auto startOffset = evaluator->dataOffset(); @@ -1199,7 +1220,7 @@ namespace hex::pl { class ASTNodeMultiVariableDecl : public ASTNode { public: - explicit ASTNodeMultiVariableDecl(std::vector variables) : m_variables(std::move(variables)) { } + explicit ASTNodeMultiVariableDecl(std::vector variables) : m_variables(std::move(variables)) { } ASTNodeMultiVariableDecl(const ASTNodeMultiVariableDecl &other) : ASTNode(other) { for (auto &variable : other.m_variables) @@ -1211,16 +1232,16 @@ namespace hex::pl { delete variable; } - [[nodiscard]] ASTNode* clone() const override { + [[nodiscard]] ASTNode *clone() const override { return new ASTNodeMultiVariableDecl(*this); } - [[nodiscard]] std::vector getVariables() { + [[nodiscard]] std::vector getVariables() { return this->m_variables; } - [[nodiscard]] std::vector createPatterns(Evaluator *evaluator) const override { - std::vector patterns; + [[nodiscard]] std::vector createPatterns(Evaluator *evaluator) const override { + std::vector patterns; for (auto &node : this->m_variables) { auto newPatterns = node->createPatterns(evaluator); @@ -1232,19 +1253,20 @@ namespace hex::pl { FunctionResult execute(Evaluator *evaluator) const override { for (auto &variable : this->m_variables) { - auto variableDecl = dynamic_cast(variable); + auto variableDecl = dynamic_cast(variable); evaluator->createVariable(variableDecl->getName(), variableDecl->getType()->evaluate(evaluator)); } - return { }; + return {}; } private: - std::vector m_variables; + std::vector m_variables; }; - class ASTNodeStruct : public ASTNode, public Attributable { + class ASTNodeStruct : public ASTNode, + public Attributable { public: ASTNodeStruct() : ASTNode() { } @@ -1262,15 +1284,15 @@ namespace hex::pl { delete inheritance; } - [[nodiscard]] ASTNode* clone() const override { + [[nodiscard]] ASTNode *clone() const override { return new ASTNodeStruct(*this); } - [[nodiscard]] std::vector createPatterns(Evaluator *evaluator) const override { + [[nodiscard]] std::vector createPatterns(Evaluator *evaluator) const override { auto pattern = new PatternDataStruct(evaluator->dataOffset(), 0, evaluator); u64 startOffset = evaluator->dataOffset(); - std::vector memberPatterns; + std::vector memberPatterns; auto structCleanup = SCOPE_GUARD { delete pattern; for (auto member : memberPatterns) @@ -1282,10 +1304,10 @@ namespace hex::pl { for (auto inheritance : this->m_inheritance) { auto inheritancePatterns = inheritance->createPatterns(evaluator).front(); ON_SCOPE_EXIT { - delete inheritancePatterns; - }; + delete inheritancePatterns; + }; - if (auto structPattern = dynamic_cast(inheritancePatterns)) { + if (auto structPattern = dynamic_cast(inheritancePatterns)) { for (auto member : structPattern->getMembers()) { memberPatterns.push_back(member->clone()); } @@ -1308,18 +1330,19 @@ namespace hex::pl { return { pattern }; } - [[nodiscard]] const std::vector& getMembers() const { return this->m_members; } + [[nodiscard]] const std::vector &getMembers() const { return this->m_members; } void addMember(ASTNode *node) { this->m_members.push_back(node); } - [[nodiscard]] const std::vector& getInheritance() const { return this->m_inheritance; } + [[nodiscard]] const std::vector &getInheritance() const { return this->m_inheritance; } void addInheritance(ASTNode *node) { this->m_inheritance.push_back(node); } private: - std::vector m_members; - std::vector m_inheritance; + std::vector m_members; + std::vector m_inheritance; }; - class ASTNodeUnion : public ASTNode, public Attributable { + class ASTNodeUnion : public ASTNode, + public Attributable { public: ASTNodeUnion() : ASTNode() { } @@ -1333,15 +1356,15 @@ namespace hex::pl { delete member; } - [[nodiscard]] ASTNode* clone() const override { + [[nodiscard]] ASTNode *clone() const override { return new ASTNodeUnion(*this); } - [[nodiscard]] std::vector createPatterns(Evaluator *evaluator) const override { + [[nodiscard]] std::vector createPatterns(Evaluator *evaluator) const override { auto pattern = new PatternDataUnion(evaluator->dataOffset(), 0, evaluator); size_t size = 0; - std::vector memberPatterns; + std::vector memberPatterns; u64 startOffset = evaluator->dataOffset(); auto unionCleanup = SCOPE_GUARD { @@ -1369,14 +1392,15 @@ namespace hex::pl { return { pattern }; } - [[nodiscard]] const std::vector& getMembers() const { return this->m_members; } + [[nodiscard]] const std::vector &getMembers() const { return this->m_members; } void addMember(ASTNode *node) { this->m_members.push_back(node); } private: - std::vector m_members; + std::vector m_members; }; - class ASTNodeEnum : public ASTNode, public Attributable { + class ASTNodeEnum : public ASTNode, + public Attributable { public: explicit ASTNodeEnum(ASTNode *underlyingType) : ASTNode(), m_underlyingType(underlyingType) { } @@ -1392,18 +1416,18 @@ namespace hex::pl { delete this->m_underlyingType; } - [[nodiscard]] ASTNode* clone() const override { + [[nodiscard]] ASTNode *clone() const override { return new ASTNodeEnum(*this); } - [[nodiscard]] std::vector createPatterns(Evaluator *evaluator) const override { + [[nodiscard]] std::vector createPatterns(Evaluator *evaluator) const override { auto pattern = new PatternDataEnum(evaluator->dataOffset(), 0, evaluator); auto enumCleanup = SCOPE_GUARD { delete pattern; }; std::vector> enumEntries; for (const auto &[name, value] : this->m_entries) { - auto literal = dynamic_cast(value->evaluate(evaluator)); + auto literal = dynamic_cast(value->evaluate(evaluator)); ON_SCOPE_EXIT { delete literal; }; enumEntries.emplace_back(literal->getValue(), name); @@ -1421,17 +1445,18 @@ namespace hex::pl { return { pattern }; } - [[nodiscard]] const std::map& getEntries() const { return this->m_entries; } - void addEntry(const std::string &name, ASTNode* expression) { this->m_entries.insert({ name, expression }); } + [[nodiscard]] const std::map &getEntries() const { return this->m_entries; } + void addEntry(const std::string &name, ASTNode *expression) { this->m_entries.insert({ name, expression }); } [[nodiscard]] ASTNode *getUnderlyingType() { return this->m_underlyingType; } private: - std::map m_entries; + std::map m_entries; ASTNode *m_underlyingType; }; - class ASTNodeBitfield : public ASTNode, public Attributable { + class ASTNodeBitfield : public ASTNode, + public Attributable { public: ASTNodeBitfield() : ASTNode() { } @@ -1445,18 +1470,18 @@ namespace hex::pl { delete expr; } - [[nodiscard]] ASTNode* clone() const override { + [[nodiscard]] ASTNode *clone() const override { return new ASTNodeBitfield(*this); } - [[nodiscard]] const std::vector>& getEntries() const { return this->m_entries; } - void addEntry(const std::string &name, ASTNode* size) { this->m_entries.emplace_back(name, size); } + [[nodiscard]] const std::vector> &getEntries() const { return this->m_entries; } + void addEntry(const std::string &name, ASTNode *size) { this->m_entries.emplace_back(name, size); } - [[nodiscard]] std::vector createPatterns(Evaluator *evaluator) const override { + [[nodiscard]] std::vector createPatterns(Evaluator *evaluator) const override { auto pattern = new PatternDataBitfield(evaluator->dataOffset(), 0, evaluator); size_t bitOffset = 0; - std::vector fields; + std::vector fields; auto bitfieldCleanup = SCOPE_GUARD { delete pattern; @@ -1470,10 +1495,10 @@ namespace hex::pl { ON_SCOPE_EXIT { delete literal; }; u8 bitSize = std::visit(overloaded { - [this](std::string) -> u8 { LogConsole::abortEvaluation("bitfield field size cannot be a string", this); }, - [this](PatternData*) -> u8 { LogConsole::abortEvaluation("bitfield field size cannot be a custom type", this); }, - [](auto &&offset) -> u8 { return static_cast(offset); } - }, dynamic_cast(literal)->getValue()); + [this](std::string) -> u8 { LogConsole::abortEvaluation("bitfield field size cannot be a string", this); }, + [this](PatternData *) -> u8 { LogConsole::abortEvaluation("bitfield field size cannot be a custom type", this); }, + [](auto &&offset) -> u8 { return static_cast(offset); } }, + dynamic_cast(literal)->getValue()); // If a field is named padding, it was created through a padding expression and only advances the bit position if (name != "padding") { @@ -1497,34 +1522,33 @@ namespace hex::pl { } private: - std::vector> m_entries; + std::vector> m_entries; }; class ASTNodeRValue : public ASTNode { public: - using Path = std::vector>; + using Path = std::vector>; explicit ASTNodeRValue(Path path) : ASTNode(), m_path(std::move(path)) { } - ASTNodeRValue(const ASTNodeRValue&) = default; + ASTNodeRValue(const ASTNodeRValue &) = default; ~ASTNodeRValue() override { for (auto &part : this->m_path) { - if (auto node = std::get_if(&part); node != nullptr) + if (auto node = std::get_if(&part); node != nullptr) delete *node; } } - [[nodiscard]] ASTNode* clone() const override { + [[nodiscard]] ASTNode *clone() const override { return new ASTNodeRValue(*this); } - [[nodiscard]] - const Path& getPath() const { + [[nodiscard]] const Path &getPath() const { return this->m_path; } - [[nodiscard]] ASTNode* evaluate(Evaluator *evaluator) const override { + [[nodiscard]] ASTNode *evaluate(Evaluator *evaluator) const override { if (this->getPath().size() == 1) { if (auto name = std::get_if(&this->getPath().front()); name != nullptr) { if (*name == "$") return new ASTNodeLiteral(u128(evaluator->dataOffset())); @@ -1535,16 +1559,16 @@ namespace hex::pl { ON_SCOPE_EXIT { delete pattern; }; Token::Literal literal; - if (dynamic_cast(pattern) || dynamic_cast(pattern)) { + if (dynamic_cast(pattern) || dynamic_cast(pattern)) { u128 value = 0; readVariable(evaluator, value, pattern); literal = value; - } else if (dynamic_cast(pattern)) { + } else if (dynamic_cast(pattern)) { i128 value = 0; readVariable(evaluator, value, pattern); value = hex::signExtend(pattern->getSize() * 8, value); literal = value; - } else if (dynamic_cast(pattern)) { + } else if (dynamic_cast(pattern)) { if (pattern->getSize() == sizeof(u16)) { u16 value = 0; readVariable(evaluator, value, pattern); @@ -1558,40 +1582,39 @@ namespace hex::pl { readVariable(evaluator, value, pattern); literal = value; } else LogConsole::abortEvaluation("invalid floating point type access", this); - } else if (dynamic_cast(pattern)) { + } else if (dynamic_cast(pattern)) { char value = 0; readVariable(evaluator, value, pattern); literal = value; - } else if (dynamic_cast(pattern)) { + } else if (dynamic_cast(pattern)) { bool value = false; readVariable(evaluator, value, pattern); literal = value; - } else if (dynamic_cast(pattern)) { + } else if (dynamic_cast(pattern)) { std::string value; if (pattern->isLocal()) { auto &literal = evaluator->getStack()[pattern->getOffset()]; std::visit(overloaded { - [&](char assignmentValue) { if (assignmentValue != 0x00) value = std::string({ assignmentValue }); }, - [&](std::string assignmentValue) { value = assignmentValue; }, - [&, this](PatternData * const &assignmentValue) { - if (!dynamic_cast(assignmentValue) && !dynamic_cast(assignmentValue)) - LogConsole::abortEvaluation(hex::format("cannot assign '{}' to string", pattern->getTypeName()), this); + [&](char assignmentValue) { if (assignmentValue != 0x00) value = std::string({ assignmentValue }); }, + [&](std::string assignmentValue) { value = assignmentValue; }, + [&, this](PatternData *const &assignmentValue) { + if (!dynamic_cast(assignmentValue) && !dynamic_cast(assignmentValue)) + LogConsole::abortEvaluation(hex::format("cannot assign '{}' to string", pattern->getTypeName()), this); - readVariable(evaluator, value, assignmentValue); - }, - [&, this](auto &&assignmentValue) { LogConsole::abortEvaluation(hex::format("cannot assign '{}' to string", pattern->getTypeName()), this); } - }, literal); - } - else { + readVariable(evaluator, value, assignmentValue); + }, + [&, this](auto &&assignmentValue) { LogConsole::abortEvaluation(hex::format("cannot assign '{}' to string", pattern->getTypeName()), this); } }, + literal); + } else { value.resize(pattern->getSize()); evaluator->getProvider()->read(pattern->getOffset(), value.data(), value.size()); value.erase(std::find(value.begin(), value.end(), '\0'), value.end()); } literal = value; - } else if (auto bitfieldFieldPattern = dynamic_cast(pattern)) { + } else if (auto bitfieldFieldPattern = dynamic_cast(pattern)) { u64 value = 0; readVariable(evaluator, value, pattern); literal = u128(hex::extract(bitfieldFieldPattern->getBitOffset() + (bitfieldFieldPattern->getBitSize() - 1), bitfieldFieldPattern->getBitOffset(), value)); @@ -1610,12 +1633,12 @@ namespace hex::pl { return new ASTNodeLiteral(literal); } - [[nodiscard]] std::vector createPatterns(Evaluator *evaluator) const override { - std::vector searchScope; + [[nodiscard]] std::vector createPatterns(Evaluator *evaluator) const override { + std::vector searchScope; PatternData *currPattern = nullptr; i32 scopeIndex = 0; - if (!evaluator->isGlobalScope()){ + if (!evaluator->isGlobalScope()) { auto globalScope = evaluator->getGlobalScope().scope; std::copy(globalScope->begin(), globalScope->end(), std::back_inserter(searchScope)); } @@ -1677,38 +1700,37 @@ namespace hex::pl { } } else { // Array indexing - auto index = dynamic_cast(std::get(part)->evaluate(evaluator)); + auto index = dynamic_cast(std::get(part)->evaluate(evaluator)); ON_SCOPE_EXIT { delete index; }; std::visit(overloaded { - [](std::string) { throw std::string("cannot use string to index array"); }, - [](PatternData * const &) { throw std::string("cannot use custom type to index array"); }, - [&, this](auto &&index) { - if (auto dynamicArrayPattern = dynamic_cast(currPattern)) { - if (index >= searchScope.size() || index < 0) - LogConsole::abortEvaluation("array index out of bounds", this); + [](std::string) { throw std::string("cannot use string to index array"); }, + [](PatternData *const &) { throw std::string("cannot use custom type to index array"); }, + [&, this](auto &&index) { + if (auto dynamicArrayPattern = dynamic_cast(currPattern)) { + if (index >= searchScope.size() || index < 0) + LogConsole::abortEvaluation("array index out of bounds", this); - auto newPattern = searchScope[index]->clone(); - delete currPattern; - currPattern = newPattern; - } - else if (auto staticArrayPattern = dynamic_cast(currPattern)) { - if (index >= staticArrayPattern->getEntryCount() || index < 0) - LogConsole::abortEvaluation("array index out of bounds", this); + auto newPattern = searchScope[index]->clone(); + delete currPattern; + currPattern = newPattern; + } else if (auto staticArrayPattern = dynamic_cast(currPattern)) { + if (index >= staticArrayPattern->getEntryCount() || index < 0) + LogConsole::abortEvaluation("array index out of bounds", this); - auto newPattern = searchScope.front()->clone(); - newPattern->setOffset(staticArrayPattern->getOffset() + index * staticArrayPattern->getTemplate()->getSize()); - delete currPattern; - currPattern = newPattern; - } - } - }, index->getValue()); + auto newPattern = searchScope.front()->clone(); + newPattern->setOffset(staticArrayPattern->getOffset() + index * staticArrayPattern->getTemplate()->getSize()); + delete currPattern; + currPattern = newPattern; + } + } }, + index->getValue()); } if (currPattern == nullptr) break; - if (auto pointerPattern = dynamic_cast(currPattern)) { + if (auto pointerPattern = dynamic_cast(currPattern)) { auto newPattern = pointerPattern->getPointedAtPattern()->clone(); delete currPattern; currPattern = newPattern; @@ -1717,25 +1739,23 @@ namespace hex::pl { PatternData *indexPattern; if (currPattern->isLocal()) { auto stackLiteral = evaluator->getStack()[currPattern->getOffset()]; - if (auto stackPattern = std::get_if(&stackLiteral); stackPattern != nullptr) + if (auto stackPattern = std::get_if(&stackLiteral); stackPattern != nullptr) indexPattern = *stackPattern; else return { currPattern }; - } - else + } else indexPattern = currPattern; - if (auto structPattern = dynamic_cast(indexPattern)) + if (auto structPattern = dynamic_cast(indexPattern)) searchScope = structPattern->getMembers(); - else if (auto unionPattern = dynamic_cast(indexPattern)) + else if (auto unionPattern = dynamic_cast(indexPattern)) searchScope = unionPattern->getMembers(); - else if (auto bitfieldPattern = dynamic_cast(indexPattern)) + else if (auto bitfieldPattern = dynamic_cast(indexPattern)) searchScope = bitfieldPattern->getFields(); - else if (auto dynamicArrayPattern = dynamic_cast(indexPattern)) + else if (auto dynamicArrayPattern = dynamic_cast(indexPattern)) searchScope = dynamicArrayPattern->getEntries(); - else if (auto staticArrayPattern = dynamic_cast(indexPattern)) + else if (auto staticArrayPattern = dynamic_cast(indexPattern)) searchScope = { staticArrayPattern->getTemplate() }; - } if (currPattern == nullptr) @@ -1754,14 +1774,13 @@ namespace hex::pl { auto &literal = evaluator->getStack()[variablePattern->getOffset()]; std::visit(overloaded { - [&](std::string &assignmentValue) { - if constexpr (isString) value = assignmentValue; - }, - [&](PatternData *assignmentValue) { readVariable(evaluator, value, assignmentValue); }, - [&](auto &&assignmentValue) { value = assignmentValue; } - }, literal); - } - else { + [&](std::string &assignmentValue) { + if constexpr (isString) value = assignmentValue; + }, + [&](PatternData *assignmentValue) { readVariable(evaluator, value, assignmentValue); }, + [&](auto &&assignmentValue) { value = assignmentValue; } }, + literal); + } else { if constexpr (isString) { value.resize(variablePattern->getSize()); evaluator->getProvider()->read(variablePattern->getOffset(), value.data(), value.size()); @@ -1789,15 +1808,15 @@ namespace hex::pl { delete this->m_type; } - [[nodiscard]] ASTNode* clone() const override { + [[nodiscard]] ASTNode *clone() const override { return new ASTNodeScopeResolution(*this); } - [[nodiscard]] ASTNode* evaluate(Evaluator *evaluator) const override { + [[nodiscard]] ASTNode *evaluate(Evaluator *evaluator) const override { auto type = this->m_type->evaluate(evaluator); ON_SCOPE_EXIT { delete type; }; - if (auto enumType = dynamic_cast(type)) { + if (auto enumType = dynamic_cast(type)) { for (auto &[name, value] : enumType->getEntries()) { if (name == this->m_name) return value->evaluate(evaluator); @@ -1816,8 +1835,8 @@ namespace hex::pl { class ASTNodeConditionalStatement : public ASTNode { public: - explicit ASTNodeConditionalStatement(ASTNode *condition, std::vector trueBody, std::vector falseBody) - : ASTNode(), m_condition(condition), m_trueBody(std::move(trueBody)), m_falseBody(std::move(falseBody)) { } + explicit ASTNodeConditionalStatement(ASTNode *condition, std::vector trueBody, std::vector falseBody) + : ASTNode(), m_condition(condition), m_trueBody(std::move(trueBody)), m_falseBody(std::move(falseBody)) { } ~ASTNodeConditionalStatement() override { delete this->m_condition; @@ -1837,11 +1856,11 @@ namespace hex::pl { this->m_falseBody.push_back(statement->clone()); } - [[nodiscard]] ASTNode* clone() const override { + [[nodiscard]] ASTNode *clone() const override { return new ASTNodeConditionalStatement(*this); } - [[nodiscard]] std::vector createPatterns(Evaluator *evaluator) const override { + [[nodiscard]] std::vector createPatterns(Evaluator *evaluator) const override { auto &scope = *evaluator->getScope(0).scope; auto &body = evaluateCondition(evaluator) ? this->m_trueBody : this->m_falseBody; @@ -1852,18 +1871,18 @@ namespace hex::pl { } } - return { }; + return {}; } - [[nodiscard]] ASTNode* getCondition() { + [[nodiscard]] ASTNode *getCondition() { return this->m_condition; } - [[nodiscard]] const std::vector& getTrueBody() const { + [[nodiscard]] const std::vector &getTrueBody() const { return this->m_trueBody; } - [[nodiscard]] const std::vector& getFalseBody() const { + [[nodiscard]] const std::vector &getFalseBody() const { return this->m_falseBody; } @@ -1873,14 +1892,14 @@ namespace hex::pl { auto variables = *evaluator->getScope(0).scope; u32 startVariableCount = variables.size(); ON_SCOPE_EXIT { - i64 stackSize = evaluator->getStack().size(); - for (u32 i = startVariableCount; i < variables.size(); i++) { - stackSize--; - delete variables[i]; - } - if (stackSize < 0) LogConsole::abortEvaluation("stack pointer underflow!", this); - evaluator->getStack().resize(stackSize); - }; + i64 stackSize = evaluator->getStack().size(); + for (u32 i = startVariableCount; i < variables.size(); i++) { + stackSize--; + delete variables[i]; + } + if (stackSize < 0) LogConsole::abortEvaluation("stack pointer underflow!", this); + evaluator->getStack().resize(stackSize); + }; evaluator->pushScope(nullptr, variables); ON_SCOPE_EXIT { evaluator->popScope(); }; @@ -1891,30 +1910,29 @@ namespace hex::pl { } } - return { }; + return {}; } private: - [[nodiscard]] - bool evaluateCondition(Evaluator *evaluator) const { - auto literal = dynamic_cast(this->m_condition->evaluate(evaluator)); + [[nodiscard]] bool evaluateCondition(Evaluator *evaluator) const { + auto literal = dynamic_cast(this->m_condition->evaluate(evaluator)); ON_SCOPE_EXIT { delete literal; }; return std::visit(overloaded { - [](std::string value) -> bool { return !value.empty(); }, - [this](PatternData * const &) -> bool { LogConsole::abortEvaluation("cannot cast custom type to bool", this); }, - [](auto &&value) -> bool { return value != 0; } - }, literal->getValue()); + [](std::string value) -> bool { return !value.empty(); }, + [this](PatternData *const &) -> bool { LogConsole::abortEvaluation("cannot cast custom type to bool", this); }, + [](auto &&value) -> bool { return value != 0; } }, + literal->getValue()); } ASTNode *m_condition; - std::vector m_trueBody, m_falseBody; + std::vector m_trueBody, m_falseBody; }; class ASTNodeFunctionCall : public ASTNode { public: - explicit ASTNodeFunctionCall(std::string functionName, std::vector params) - : ASTNode(), m_functionName(std::move(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) @@ -1928,32 +1946,32 @@ namespace hex::pl { this->m_params.push_back(param->clone()); } - [[nodiscard]] ASTNode* clone() const override { + [[nodiscard]] ASTNode *clone() const override { return new ASTNodeFunctionCall(*this); } - [[nodiscard]] const std::string& getFunctionName() { + [[nodiscard]] const std::string &getFunctionName() { return this->m_functionName; } - [[nodiscard]] const std::vector& getParams() const { + [[nodiscard]] const std::vector &getParams() const { return this->m_params; } - [[nodiscard]] std::vector createPatterns(Evaluator *evaluator) const override { + [[nodiscard]] std::vector createPatterns(Evaluator *evaluator) const override { this->execute(evaluator); - return { }; + return {}; } - [[nodiscard]] ASTNode* evaluate(Evaluator *evaluator) const override { + [[nodiscard]] ASTNode *evaluate(Evaluator *evaluator) const override { std::vector evaluatedParams; for (auto param : this->m_params) { auto expression = param->evaluate(evaluator); ON_SCOPE_EXIT { delete expression; }; - auto literal = dynamic_cast(expression->evaluate(evaluator)); + auto literal = dynamic_cast(expression->evaluate(evaluator)); ON_SCOPE_EXIT { delete literal; }; evaluatedParams.push_back(literal->getValue()); @@ -1970,9 +1988,8 @@ namespace hex::pl { auto function = functions[this->m_functionName]; if (function.parameterCount == ContentRegistry::PatternLanguage::UnlimitedParameters) { - ; // Don't check parameter count - } - else if (function.parameterCount & ContentRegistry::PatternLanguage::LessParametersThan) { + ; // Don't check parameter count + } else if (function.parameterCount & ContentRegistry::PatternLanguage::LessParametersThan) { if (evaluatedParams.size() >= (function.parameterCount & ~ContentRegistry::PatternLanguage::LessParametersThan)) LogConsole::abortEvaluation(hex::format("too many parameters for function '{0}'. Expected {1}", this->m_functionName, function.parameterCount & ~ContentRegistry::PatternLanguage::LessParametersThan), this); } else if (function.parameterCount & ContentRegistry::PatternLanguage::MoreParametersThan) { @@ -2015,18 +2032,17 @@ namespace hex::pl { FunctionResult execute(Evaluator *evaluator) const override { delete this->evaluate(evaluator); - return { }; + return {}; } private: std::string m_functionName; - std::vector m_params; + std::vector m_params; }; class ASTNodeTypeOperator : public ASTNode { public: ASTNodeTypeOperator(Token::Operator op, ASTNode *expression) : m_op(op), m_expression(expression) { - } ASTNodeTypeOperator(const ASTNodeTypeOperator &other) : ASTNode(other) { @@ -2034,7 +2050,7 @@ namespace hex::pl { this->m_expression = other.m_expression->clone(); } - [[nodiscard]] ASTNode* clone() const override { + [[nodiscard]] ASTNode *clone() const override { return new ASTNodeTypeOperator(*this); } @@ -2042,28 +2058,25 @@ namespace hex::pl { delete this->m_expression; } - [[nodiscard]] - Token::Operator getOperator() const { + [[nodiscard]] Token::Operator getOperator() const { return this->m_op; } - [[nodiscard]] - ASTNode* getExpression() const { + [[nodiscard]] ASTNode *getExpression() const { return this->m_expression; } - [[nodiscard]] - ASTNode* evaluate(Evaluator *evaluator) const override { + [[nodiscard]] ASTNode *evaluate(Evaluator *evaluator) const override { auto pattern = this->m_expression->createPatterns(evaluator).front(); ON_SCOPE_EXIT { delete pattern; }; switch (this->getOperator()) { - case Token::Operator::AddressOf: - return new ASTNodeLiteral(u128(pattern->getOffset())); - case Token::Operator::SizeOf: - return new ASTNodeLiteral(u128(pattern->getSize())); - default: - LogConsole::abortEvaluation("invalid type operator", this); + case Token::Operator::AddressOf: + return new ASTNodeLiteral(u128(pattern->getOffset())); + case Token::Operator::SizeOf: + return new ASTNodeLiteral(u128(pattern->getSize())); + default: + LogConsole::abortEvaluation("invalid type operator", this); } } @@ -2077,7 +2090,6 @@ namespace hex::pl { class ASTNodeAssignment : public ASTNode { public: ASTNodeAssignment(std::string lvalueName, ASTNode *rvalue) : m_lvalueName(std::move(lvalueName)), m_rvalue(rvalue) { - } ASTNodeAssignment(const ASTNodeAssignment &other) : ASTNode(other) { @@ -2085,7 +2097,7 @@ namespace hex::pl { this->m_rvalue = other.m_rvalue->clone(); } - [[nodiscard]] ASTNode* clone() const override { + [[nodiscard]] ASTNode *clone() const override { return new ASTNodeAssignment(*this); } @@ -2093,21 +2105,21 @@ namespace hex::pl { delete this->m_rvalue; } - [[nodiscard]] const std::string& getLValueName() const { + [[nodiscard]] const std::string &getLValueName() const { return this->m_lvalueName; } - [[nodiscard]] ASTNode* getRValue() const { + [[nodiscard]] ASTNode *getRValue() const { return this->m_rvalue; } FunctionResult execute(Evaluator *evaluator) const override { - auto literal = dynamic_cast(this->getRValue()->evaluate(evaluator)); + auto literal = dynamic_cast(this->getRValue()->evaluate(evaluator)); ON_SCOPE_EXIT { delete literal; }; evaluator->setVariable(this->getLValueName(), literal->getValue()); - return { }; + return {}; } private: @@ -2118,7 +2130,6 @@ namespace hex::pl { class ASTNodeControlFlowStatement : public ASTNode { public: explicit ASTNodeControlFlowStatement(ControlFlowStatement type, ASTNode *rvalue) : m_type(type), m_rvalue(rvalue) { - } ASTNodeControlFlowStatement(const ASTNodeControlFlowStatement &other) : ASTNode(other) { @@ -2130,7 +2141,7 @@ namespace hex::pl { this->m_rvalue = nullptr; } - [[nodiscard]] ASTNode* clone() const override { + [[nodiscard]] ASTNode *clone() const override { return new ASTNodeControlFlowStatement(*this); } @@ -2138,15 +2149,15 @@ namespace hex::pl { delete this->m_rvalue; } - [[nodiscard]] ASTNode* getReturnValue() const { + [[nodiscard]] ASTNode *getReturnValue() const { return this->m_rvalue; } - [[nodiscard]] std::vector createPatterns(Evaluator *evaluator) const override { + [[nodiscard]] std::vector createPatterns(Evaluator *evaluator) const override { this->execute(evaluator); - return { }; + return {}; } FunctionResult execute(Evaluator *evaluator) const override { @@ -2157,7 +2168,7 @@ namespace hex::pl { if (returnValue == nullptr) return std::nullopt; else { - auto literal = dynamic_cast(returnValue->evaluate(evaluator)); + auto literal = dynamic_cast(returnValue->evaluate(evaluator)); ON_SCOPE_EXIT { delete literal; }; return literal->getValue(); @@ -2171,9 +2182,8 @@ namespace hex::pl { class ASTNodeFunctionDefinition : public ASTNode { public: - ASTNodeFunctionDefinition(std::string name, std::vector> params, std::vector body) - : m_name(std::move(name)), m_params(std::move(params)), m_body(std::move(body)) { - + ASTNodeFunctionDefinition(std::string name, std::vector> params, std::vector body) + : m_name(std::move(name)), m_params(std::move(params)), m_body(std::move(body)) { } ASTNodeFunctionDefinition(const ASTNodeFunctionDefinition &other) : ASTNode(other) { @@ -2189,7 +2199,7 @@ namespace hex::pl { } } - [[nodiscard]] ASTNode* clone() const override { + [[nodiscard]] ASTNode *clone() const override { return new ASTNodeFunctionDefinition(*this); } @@ -2200,30 +2210,30 @@ namespace hex::pl { delete statement; } - [[nodiscard]] const std::string& getName() const { + [[nodiscard]] const std::string &getName() const { return this->m_name; } - [[nodiscard]] const auto& getParams() const { + [[nodiscard]] const auto &getParams() const { return this->m_params; } - [[nodiscard]] const auto& getBody() const { + [[nodiscard]] const auto &getBody() const { return this->m_body; } - [[nodiscard]] ASTNode* evaluate(Evaluator *evaluator) const override { + [[nodiscard]] ASTNode *evaluate(Evaluator *evaluator) const override { - evaluator->addCustomFunction(this->m_name, this->m_params.size(), [this](Evaluator *ctx, const std::vector& params) -> std::optional { - std::vector variables; + evaluator->addCustomFunction(this->m_name, this->m_params.size(), [this](Evaluator *ctx, const std::vector ¶ms) -> std::optional { + std::vector variables; ctx->pushScope(nullptr, variables); ON_SCOPE_EXIT { - for (auto variable : variables) - delete variable; + for (auto variable : variables) + delete variable; - ctx->popScope(); - }; + ctx->popScope(); + }; u32 paramIndex = 0; for (const auto &[name, type] : this->m_params) { @@ -2238,11 +2248,12 @@ namespace hex::pl { if (ctx->getCurrentControlFlowStatement() != ControlFlowStatement::None) { switch (ctx->getCurrentControlFlowStatement()) { - case ControlFlowStatement::Break: - ctx->getConsole().abortEvaluation("break statement not within a loop", statement); - case ControlFlowStatement::Continue: - ctx->getConsole().abortEvaluation("continue statement not within a loop", statement); - default: break; + case ControlFlowStatement::Break: + ctx->getConsole().abortEvaluation("break statement not within a loop", statement); + case ControlFlowStatement::Continue: + ctx->getConsole().abortEvaluation("continue statement not within a loop", statement); + default: + break; } ctx->setCurrentControlFlowStatement(ControlFlowStatement::None); @@ -2250,7 +2261,7 @@ namespace hex::pl { } } - return { }; + return {}; }); return nullptr; @@ -2259,15 +2270,13 @@ namespace hex::pl { private: std::string m_name; - std::vector> m_params; - std::vector m_body; + std::vector> m_params; + std::vector m_body; }; class ASTNodeCompoundStatement : public ASTNode { public: - - ASTNodeCompoundStatement(std::vector statements, bool newScope = false) : m_statements(std::move(statements)), m_newScope(newScope) { - + ASTNodeCompoundStatement(std::vector statements, bool newScope = false) : m_statements(std::move(statements)), m_newScope(newScope) { } ASTNodeCompoundStatement(const ASTNodeCompoundStatement &other) : ASTNode(other) { @@ -2276,7 +2285,7 @@ namespace hex::pl { } } - [[nodiscard]] ASTNode* clone() const override { + [[nodiscard]] ASTNode *clone() const override { return new ASTNodeCompoundStatement(*this); } @@ -2286,7 +2295,7 @@ namespace hex::pl { } } - [[nodiscard]] ASTNode* evaluate(Evaluator *evaluator) const override { + [[nodiscard]] ASTNode *evaluate(Evaluator *evaluator) const override { ASTNode *result = nullptr; for (const auto &statement : this->m_statements) { @@ -2297,8 +2306,8 @@ namespace hex::pl { return result; } - [[nodiscard]] std::vector createPatterns(Evaluator *evaluator) const override { - std::vector result; + [[nodiscard]] std::vector createPatterns(Evaluator *evaluator) const override { + std::vector result; for (const auto &statement : this->m_statements) { auto patterns = statement->createPatterns(evaluator); @@ -2340,7 +2349,7 @@ namespace hex::pl { } public: - std::vector m_statements; + std::vector m_statements; bool m_newScope; }; diff --git a/lib/libimhex/include/hex/pattern_language/evaluator.hpp b/lib/libimhex/include/hex/pattern_language/evaluator.hpp index e4a9b1779..cf99d9deb 100644 --- a/lib/libimhex/include/hex/pattern_language/evaluator.hpp +++ b/lib/libimhex/include/hex/pattern_language/evaluator.hpp @@ -13,7 +13,9 @@ #include #include -namespace hex::prv { class Provider; } +namespace hex::prv { + class Provider; +} namespace hex::pl { @@ -38,15 +40,17 @@ namespace hex::pl { public: Evaluator() = default; - std::optional> evaluate(const std::vector &ast); + std::optional> evaluate(const std::vector &ast); - [[nodiscard]] - LogConsole& getConsole() { + [[nodiscard]] LogConsole &getConsole() { return this->m_console; } - struct Scope { PatternData *parent; std::vector* scope; }; - void pushScope(PatternData *parent, std::vector &scope) { + struct Scope { + PatternData *parent; + std::vector *scope; + }; + void pushScope(PatternData *parent, std::vector &scope) { if (this->m_scopes.size() > this->getEvaluationDepth()) LogConsole::abortEvaluation(hex::format("evaluation depth exceeded set limit of {}", this->getEvaluationDepth())); @@ -59,11 +63,11 @@ namespace hex::pl { this->m_scopes.pop_back(); } - const Scope& getScope(i32 index) { + const Scope &getScope(i32 index) { return this->m_scopes[this->m_scopes.size() - 1 + index]; } - const Scope& getGlobalScope() { + const Scope &getGlobalScope() { return this->m_scopes.front(); } @@ -83,8 +87,7 @@ namespace hex::pl { this->m_inVariables = inVariables; } - [[nodiscard]] - std::map getOutVariables() const { + [[nodiscard]] std::map getOutVariables() const { std::map result; for (const auto &[name, offset] : this->m_outVariables) { @@ -94,8 +97,7 @@ namespace hex::pl { return result; } - [[nodiscard]] - prv::Provider *getProvider() const { + [[nodiscard]] prv::Provider *getProvider() const { return this->m_provider; } @@ -103,8 +105,7 @@ namespace hex::pl { this->m_defaultEndian = endian; } - [[nodiscard]] - std::endian getDefaultEndian() const { + [[nodiscard]] std::endian getDefaultEndian() const { return this->m_defaultEndian; } @@ -112,8 +113,7 @@ namespace hex::pl { this->m_evalDepth = evalDepth; } - [[nodiscard]] - u64 getEvaluationDepth() const { + [[nodiscard]] u64 getEvaluationDepth() const { return this->m_evalDepth; } @@ -121,8 +121,7 @@ namespace hex::pl { this->m_arrayLimit = arrayLimit; } - [[nodiscard]] - u64 getArrayLimit() const { + [[nodiscard]] u64 getArrayLimit() const { return this->m_arrayLimit; } @@ -130,13 +129,11 @@ namespace hex::pl { this->m_patternLimit = limit; } - [[nodiscard]] - u64 getPatternLimit() { + [[nodiscard]] u64 getPatternLimit() { return this->m_patternLimit; } - [[nodiscard]] - u64 getPatternCount() { + [[nodiscard]] u64 getPatternCount() { return this->m_currPatternCount; } @@ -144,36 +141,34 @@ namespace hex::pl { this->m_loopLimit = limit; } - [[nodiscard]] - u64 getLoopLimit() { + [[nodiscard]] u64 getLoopLimit() { return this->m_loopLimit; } - u64& dataOffset() { return this->m_currOffset; } + u64 &dataOffset() { return this->m_currOffset; } bool addCustomFunction(const std::string &name, u32 numParams, const ContentRegistry::PatternLanguage::Callback &function) { - const auto [iter, inserted] = this->m_customFunctions.insert({ name, { numParams, function } }); + const auto [iter, inserted] = this->m_customFunctions.insert({ + name, {numParams, function} + }); return inserted; } - [[nodiscard]] - const std::map& getCustomFunctions() const { + [[nodiscard]] const std::map &getCustomFunctions() const { return this->m_customFunctions; } - [[nodiscard]] - std::vector& getStack() { + [[nodiscard]] std::vector &getStack() { return this->m_stack; } - [[nodiscard]] - const std::vector& getStack() const { + [[nodiscard]] const std::vector &getStack() const { return this->m_stack; } void createVariable(const std::string &name, ASTNode *type, const std::optional &value = std::nullopt, bool outVariable = false); - void setVariable(const std::string &name, const Token::Literal& value); + void setVariable(const std::string &name, const Token::Literal &value); void abort() { this->m_aborted = true; @@ -184,8 +179,7 @@ namespace hex::pl { LogConsole::abortEvaluation("evaluation aborted by user"); } - [[nodiscard]] - std::optional getEnvVariable(const std::string &name) const { + [[nodiscard]] std::optional getEnvVariable(const std::string &name) const { if (this->m_envVariables.contains(name)) return this->m_envVariables.at(name); else @@ -196,8 +190,7 @@ namespace hex::pl { this->m_envVariables[name] = value; } - [[nodiscard]] - bool hasDangerousFunctionBeenCalled() const { + [[nodiscard]] bool hasDangerousFunctionBeenCalled() const { return this->m_dangerousFunctionCalled; } @@ -210,8 +203,7 @@ namespace hex::pl { this->m_dangerousFunctionCalled = false; } - [[nodiscard]] - DangerousFunctionPermission getDangerousFunctionPermission() const { + [[nodiscard]] DangerousFunctionPermission getDangerousFunctionPermission() const { return this->m_allowDangerousFunctions; } @@ -219,13 +211,11 @@ namespace hex::pl { this->m_currControlFlowStatement = statement; } - [[nodiscard]] - ControlFlowStatement getCurrentControlFlowStatement() const { + [[nodiscard]] ControlFlowStatement getCurrentControlFlowStatement() const { return this->m_currControlFlowStatement; } private: - void patternCreated(); void patternDestroyed(); @@ -246,7 +236,7 @@ namespace hex::pl { std::vector m_scopes; std::map m_customFunctions; - std::vector m_customFunctionDefinitions; + std::vector m_customFunctionDefinitions; std::vector m_stack; std::map m_envVariables; diff --git a/lib/libimhex/include/hex/pattern_language/lexer.hpp b/lib/libimhex/include/hex/pattern_language/lexer.hpp index 3317c82d6..1e480f96a 100644 --- a/lib/libimhex/include/hex/pattern_language/lexer.hpp +++ b/lib/libimhex/include/hex/pattern_language/lexer.hpp @@ -16,8 +16,8 @@ namespace hex::pl { Lexer() = default; - std::optional> lex(const std::string& code); - const std::optional& getError() { return this->m_error; } + std::optional> lex(const std::string &code); + const std::optional &getError() { return this->m_error; } private: std::optional m_error; diff --git a/lib/libimhex/include/hex/pattern_language/log_console.hpp b/lib/libimhex/include/hex/pattern_language/log_console.hpp index 78a49d4a0..503a7972f 100644 --- a/lib/libimhex/include/hex/pattern_language/log_console.hpp +++ b/lib/libimhex/include/hex/pattern_language/log_console.hpp @@ -21,25 +21,21 @@ namespace hex::pl { Error }; - [[nodiscard]] - const auto& getLog() const { return this->m_consoleLog; } + [[nodiscard]] const auto &getLog() const { return this->m_consoleLog; } using EvaluateError = std::pair; void log(Level level, const std::string &message); - [[noreturn]] - static void abortEvaluation(const std::string &message); + [[noreturn]] static void abortEvaluation(const std::string &message); - [[noreturn]] - static void abortEvaluation(const std::string &message, const ASTNode *node); + [[noreturn]] static void abortEvaluation(const std::string &message, const ASTNode *node); void clear(); void setHardError(const EvaluateError &error) { this->m_lastHardError = error; } - [[nodiscard]] - const std::optional& getLastHardError() { return this->m_lastHardError; }; + [[nodiscard]] const std::optional &getLastHardError() { return this->m_lastHardError; }; private: std::vector> m_consoleLog; diff --git a/lib/libimhex/include/hex/pattern_language/parser.hpp b/lib/libimhex/include/hex/pattern_language/parser.hpp index c4a0ff7ef..928462193 100644 --- a/lib/libimhex/include/hex/pattern_language/parser.hpp +++ b/lib/libimhex/include/hex/pattern_language/parser.hpp @@ -21,15 +21,15 @@ namespace hex::pl { Parser() = default; ~Parser() = default; - std::optional> parse(const std::vector &tokens); - const std::optional& getError() { return this->m_error; } + std::optional> parse(const std::vector &tokens); + const std::optional &getError() { return this->m_error; } private: std::optional m_error; TokenIter m_curr; TokenIter m_originalPosition; - std::unordered_map m_types; + std::unordered_map m_types; std::vector m_matchedOptionals; std::vector> m_currNamespace; @@ -37,13 +37,13 @@ namespace hex::pl { return this->m_curr[index].lineNumber; } - auto* create(auto *node) { + auto *create(auto *node) { node->setLineNumber(this->getLineNumber(-1)); return node; } template - const T& getValue(i32 index) const { + const T &getValue(i32 index) const { auto value = std::get_if(&this->m_curr[index].value); if (value == nullptr) @@ -67,63 +67,63 @@ namespace hex::pl { return result; } - ASTNode* parseFunctionCall(); - ASTNode* parseStringLiteral(); + ASTNode *parseFunctionCall(); + ASTNode *parseStringLiteral(); std::string parseNamespaceResolution(); - ASTNode* parseScopeResolution(); - ASTNode* parseRValue(ASTNodeRValue::Path &path); - ASTNode* parseFactor(); - ASTNode* parseCastExpression(); - ASTNode* parseUnaryExpression(); - ASTNode* parseMultiplicativeExpression(); - ASTNode* parseAdditiveExpression(); - ASTNode* parseShiftExpression(); - ASTNode* parseRelationExpression(); - ASTNode* parseEqualityExpression(); - ASTNode* parseBinaryAndExpression(); - ASTNode* parseBinaryXorExpression(); - ASTNode* parseBinaryOrExpression(); - ASTNode* parseBooleanAnd(); - ASTNode* parseBooleanXor(); - ASTNode* parseBooleanOr(); - ASTNode* parseTernaryConditional(); - ASTNode* parseMathematicalExpression(); + ASTNode *parseScopeResolution(); + ASTNode *parseRValue(ASTNodeRValue::Path &path); + ASTNode *parseFactor(); + ASTNode *parseCastExpression(); + ASTNode *parseUnaryExpression(); + ASTNode *parseMultiplicativeExpression(); + ASTNode *parseAdditiveExpression(); + ASTNode *parseShiftExpression(); + ASTNode *parseRelationExpression(); + ASTNode *parseEqualityExpression(); + ASTNode *parseBinaryAndExpression(); + ASTNode *parseBinaryXorExpression(); + ASTNode *parseBinaryOrExpression(); + ASTNode *parseBooleanAnd(); + ASTNode *parseBooleanXor(); + ASTNode *parseBooleanOr(); + ASTNode *parseTernaryConditional(); + ASTNode *parseMathematicalExpression(); - ASTNode* parseFunctionDefinition(); - ASTNode* parseFunctionVariableDecl(); - ASTNode* parseFunctionStatement(); - ASTNode* parseFunctionVariableAssignment(); - ASTNode* parseFunctionControlFlowStatement(); - std::vector parseStatementBody(); - ASTNode* parseFunctionConditional(); - ASTNode* parseFunctionWhileLoop(); - ASTNode* parseFunctionForLoop(); + ASTNode *parseFunctionDefinition(); + ASTNode *parseFunctionVariableDecl(); + ASTNode *parseFunctionStatement(); + ASTNode *parseFunctionVariableAssignment(); + ASTNode *parseFunctionControlFlowStatement(); + std::vector parseStatementBody(); + ASTNode *parseFunctionConditional(); + ASTNode *parseFunctionWhileLoop(); + ASTNode *parseFunctionForLoop(); void parseAttribute(Attributable *currNode); - ASTNode* parseConditional(); - ASTNode* parseWhileStatement(); - ASTNodeTypeDecl* parseType(bool allowFunctionTypes = false); - ASTNode* parseUsingDeclaration(); - ASTNode* parsePadding(); - ASTNode* parseMemberVariable(ASTNodeTypeDecl *type); - ASTNode* parseMemberArrayVariable(ASTNodeTypeDecl *type); - ASTNode* parseMemberPointerVariable(ASTNodeTypeDecl *type); - ASTNode* parseMember(); - ASTNode* parseStruct(); - ASTNode* parseUnion(); - ASTNode* parseEnum(); - ASTNode* parseBitfield(); - ASTNode* parseVariablePlacement(ASTNodeTypeDecl *type); - ASTNode* parseArrayVariablePlacement(ASTNodeTypeDecl *type); - ASTNode* parsePointerVariablePlacement(ASTNodeTypeDecl *type); - ASTNode* parsePlacement(); - std::vector parseNamespace(); - std::vector parseStatements(); + ASTNode *parseConditional(); + ASTNode *parseWhileStatement(); + ASTNodeTypeDecl *parseType(bool allowFunctionTypes = false); + ASTNode *parseUsingDeclaration(); + ASTNode *parsePadding(); + ASTNode *parseMemberVariable(ASTNodeTypeDecl *type); + ASTNode *parseMemberArrayVariable(ASTNodeTypeDecl *type); + ASTNode *parseMemberPointerVariable(ASTNodeTypeDecl *type); + ASTNode *parseMember(); + ASTNode *parseStruct(); + ASTNode *parseUnion(); + ASTNode *parseEnum(); + ASTNode *parseBitfield(); + ASTNode *parseVariablePlacement(ASTNodeTypeDecl *type); + ASTNode *parseArrayVariablePlacement(ASTNodeTypeDecl *type); + ASTNode *parsePointerVariablePlacement(ASTNodeTypeDecl *type); + ASTNode *parsePlacement(); + std::vector parseNamespace(); + std::vector parseStatements(); - ASTNodeTypeDecl* addType(const std::string &name, ASTNode *node, std::optional endian = std::nullopt); + ASTNodeTypeDecl *addType(const std::string &name, ASTNode *node, std::optional endian = std::nullopt); - std::vector parseTillToken(Token::Type endTokenType, const auto value) { - std::vector program; + std::vector parseTillToken(Token::Type endTokenType, const auto value) { + std::vector program; auto guard = SCOPE_GUARD { for (auto &node : program) delete node; @@ -147,7 +147,7 @@ namespace hex::pl { /* Token consuming */ - enum class Setting{ }; + enum class Setting { }; constexpr static auto Normal = static_cast(0); constexpr static auto Not = static_cast(1); @@ -173,7 +173,7 @@ namespace hex::pl { } template - bool sequence(Token::Type type, auto value, auto ... args) { + bool sequence(Token::Type type, auto value, auto... args) { if constexpr (S == Normal) { if (!peek(type, value)) { reset(); @@ -214,7 +214,7 @@ namespace hex::pl { } template - bool oneOf(Token::Type type, auto value, auto ... args) { + bool oneOf(Token::Type type, auto value, auto... args) { if constexpr (S == Normal) return sequence(type, value) || oneOf(args...); else if constexpr (S == Not) @@ -248,7 +248,6 @@ namespace hex::pl { bool peek(Token::Type type, auto value, i32 index = 0) { return this->m_curr[index].type == type && this->m_curr[index] == value; } - }; } \ No newline at end of file diff --git a/lib/libimhex/include/hex/pattern_language/pattern_data.hpp b/lib/libimhex/include/hex/pattern_language/pattern_data.hpp index 11f095a6c..f44915628 100644 --- a/lib/libimhex/include/hex/pattern_language/pattern_data.hpp +++ b/lib/libimhex/include/hex/pattern_language/pattern_data.hpp @@ -30,7 +30,7 @@ namespace hex::pl { template T> std::string makeDisplayable(T *data, size_t size) { std::string result; - for (T* c = data; c < (data + size); c++) { + for (T *c = data; c < (data + size); c++) { if (iscntrl(*c) || *c > 0x7F) result += " "; else @@ -49,6 +49,7 @@ namespace hex::pl { public: [[nodiscard]] bool isInlined() const { return this->m_inlined; } void setInlined(bool inlined) { this->m_inlined = inlined; } + private: bool m_inlined = false; }; @@ -81,7 +82,7 @@ namespace hex::pl { class PatternData : public PatternCreationLimiter { public: PatternData(u64 offset, size_t size, Evaluator *evaluator, u32 color = 0) - : PatternCreationLimiter(evaluator), m_offset(offset), m_size(size), m_color(color) { + : PatternCreationLimiter(evaluator), m_offset(offset), m_size(size), m_color(color) { constexpr u32 Palette[] = { 0x70b4771f, 0x700e7fff, 0x702ca02c, 0x702827d6, 0x70bd6794, 0x704b568c, 0x70c277e3, 0x707f7f7f, 0x7022bdbc, 0x70cfbe17 }; if (color != 0) @@ -98,7 +99,7 @@ namespace hex::pl { virtual ~PatternData() = default; - virtual PatternData* clone() = 0; + virtual PatternData *clone() = 0; [[nodiscard]] u64 getOffset() const { return this->m_offset; } virtual void setOffset(u64 offset) { this->m_offset = offset; } @@ -106,37 +107,39 @@ namespace hex::pl { [[nodiscard]] size_t getSize() const { return this->m_size; } void setSize(size_t size) { this->m_size = size; } - [[nodiscard]] const std::string& getVariableName() const { return this->m_variableName; } + [[nodiscard]] const std::string &getVariableName() const { return this->m_variableName; } void setVariableName(std::string name) { this->m_variableName = std::move(name); } - [[nodiscard]] const std::optional& getComment() const { return this->m_comment; } + [[nodiscard]] const std::optional &getComment() const { return this->m_comment; } void setComment(std::string comment) { this->m_comment = std::move(comment); } - [[nodiscard]] const std::string& getTypeName() const { return this->m_typeName; } + [[nodiscard]] const std::string &getTypeName() const { return this->m_typeName; } void setTypeName(std::string name) { this->m_typeName = std::move(name); } [[nodiscard]] u32 getColor() const { return this->m_color; } - virtual void setColor(u32 color) { this->m_color = color; this->m_manualColor = true; } + virtual void setColor(u32 color) { + this->m_color = color; + this->m_manualColor = true; + } [[nodiscard]] bool hasOverriddenColor() const { return this->m_manualColor; } [[nodiscard]] std::endian getEndian() const { return this->m_endian; } void setEndian(std::endian endian) { this->m_endian = endian; } - [[nodiscard]] std::string getDisplayName() const { return this->m_displayName.value_or(this->m_variableName); } + [[nodiscard]] std::string getDisplayName() const { return this->m_displayName.value_or(this->m_variableName); } void setDisplayName(const std::string &name) { this->m_displayName = name; } - [[nodiscard]] Evaluator* getEvaluator() const { return this->m_evaluator; } + [[nodiscard]] Evaluator *getEvaluator() const { return this->m_evaluator; } - [[nodiscard]] const auto& getTransformFunction() const { return this->m_transformFunction; } + [[nodiscard]] const auto &getTransformFunction() const { return this->m_transformFunction; } void setTransformFunction(const ContentRegistry::PatternLanguage::Function &function) { this->m_transformFunction = function; } - [[nodiscard]] const auto& getFormatterFunction() const { return this->m_formatterFunction; } + [[nodiscard]] const auto &getFormatterFunction() const { return this->m_formatterFunction; } void setFormatterFunction(const ContentRegistry::PatternLanguage::Function &function) { this->m_formatterFunction = function; } - virtual void createEntry(prv::Provider* &provider) = 0; + virtual void createEntry(prv::Provider *&provider) = 0; [[nodiscard]] virtual std::string getFormattedName() const = 0; - [[nodiscard]] - virtual const PatternData* getPattern(u64 offset) const { + [[nodiscard]] virtual const PatternData *getPattern(u64 offset) const { if (offset >= this->getOffset() && offset < (this->getOffset() + this->getSize()) && !this->isHidden()) return this; else @@ -154,31 +157,27 @@ namespace hex::pl { virtual void sort(ImGuiTableSortSpecs *sortSpecs, prv::Provider *provider) { } - [[nodiscard]] - virtual std::string toString(prv::Provider *provider) const { + [[nodiscard]] virtual std::string toString(prv::Provider *provider) const { return hex::format("{} {} @ 0x{:X}", this->getTypeName(), this->getVariableName(), this->getOffset()); } - static bool sortPatternDataTable(ImGuiTableSortSpecs *sortSpecs, prv::Provider *provider, pl::PatternData* left, pl::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->getDisplayName() > right->getDisplayName(); else return left->getDisplayName() < right->getDisplayName(); - } - else if (sortSpecs->Specs->ColumnUserID == ImGui::GetID("offset")) { + } else if (sortSpecs->Specs->ColumnUserID == ImGui::GetID("offset")) { if (sortSpecs->Specs->SortDirection == ImGuiSortDirection_Ascending) return left->getOffset() > right->getOffset(); else return left->getOffset() < right->getOffset(); - } - else if (sortSpecs->Specs->ColumnUserID == ImGui::GetID("size")) { + } else if (sortSpecs->Specs->ColumnUserID == ImGui::GetID("size")) { if (sortSpecs->Specs->SortDirection == ImGuiSortDirection_Ascending) return left->getSize() > right->getSize(); else return left->getSize() < right->getSize(); - } - else if (sortSpecs->Specs->ColumnUserID == ImGui::GetID("value")) { + } else if (sortSpecs->Specs->ColumnUserID == ImGui::GetID("value")) { size_t biggerSize = std::max(left->getSize(), right->getSize()); std::vector leftBuffer(biggerSize, 0x00), rightBuffer(biggerSize, 0x00); @@ -194,14 +193,12 @@ namespace hex::pl { return leftBuffer > rightBuffer; else return leftBuffer < rightBuffer; - } - else if (sortSpecs->Specs->ColumnUserID == ImGui::GetID("type")) { + } else if (sortSpecs->Specs->ColumnUserID == ImGui::GetID("type")) { if (sortSpecs->Specs->SortDirection == ImGuiSortDirection_Ascending) return left->getTypeName() > right->getTypeName(); else return left->getTypeName() < right->getTypeName(); - } - else if (sortSpecs->Specs->ColumnUserID == ImGui::GetID("color")) { + } else if (sortSpecs->Specs->ColumnUserID == ImGui::GetID("color")) { if (sortSpecs->Specs->SortDirection == ImGuiSortDirection_Ascending) return left->getColor() > right->getColor(); else @@ -240,20 +237,18 @@ namespace hex::pl { template [[nodiscard]] bool areCommonPropertiesEqual(const PatternData &other) const { - return - typeid(other) == typeid(std::remove_cvref_t) && - this->m_offset == other.m_offset && - this->m_size == other.m_size && - this->m_hidden == other.m_hidden && - this->m_endian == other.m_endian && - this->m_variableName == other.m_variableName && - this->m_typeName == other.m_typeName && - this->m_comment == other.m_comment && - this->m_local == other.m_local; + return typeid(other) == typeid(std::remove_cvref_t) && + this->m_offset == other.m_offset && + this->m_size == other.m_size && + this->m_hidden == other.m_hidden && + this->m_endian == other.m_endian && + this->m_variableName == other.m_variableName && + this->m_typeName == other.m_typeName && + this->m_comment == other.m_comment && + this->m_local == other.m_local; } - [[nodiscard]] - std::string formatDisplayValue(const std::string &value, const Token::Literal &literal) const { + [[nodiscard]] std::string formatDisplayValue(const std::string &value, const Token::Literal &literal) const { if (!this->m_formatterFunction.has_value()) return value; else { @@ -330,11 +325,11 @@ namespace hex::pl { public: PatternDataPadding(u64 offset, size_t size, Evaluator *evaluator) : PatternData(offset, size, evaluator, 0xFF000000) { } - PatternData* clone() override { + PatternData *clone() override { return new PatternDataPadding(*this); } - void createEntry(prv::Provider* &provider) override { + void createEntry(prv::Provider *&provider) override { } [[nodiscard]] std::string getFormattedName() const override { @@ -347,7 +342,7 @@ namespace hex::pl { class PatternDataPointer : public PatternData { public: PatternDataPointer(u64 offset, size_t size, Evaluator *evaluator, u32 color = 0) - : PatternData(offset, size, evaluator, color), m_pointedAt(nullptr) { + : PatternData(offset, size, evaluator, color), m_pointedAt(nullptr) { } PatternDataPointer(const PatternDataPointer &other) : PatternData(other) { @@ -358,11 +353,11 @@ namespace hex::pl { delete this->m_pointedAt; } - PatternData* clone() override { + PatternData *clone() override { return new PatternDataPointer(*this); } - void createEntry(prv::Provider* &provider) override { + void createEntry(prv::Provider *&provider) override { u64 data = 0; provider->read(this->getOffset(), &data, this->getSize()); data = hex::changeEndianess(data, this->getSize(), this->getEndian()); @@ -397,11 +392,21 @@ namespace hex::pl { [[nodiscard]] std::string getFormattedName() const override { std::string result = this->m_pointedAt->getFormattedName() + "* : "; switch (this->getSize()) { - case 1: result += "u8"; break; - case 2: result += "u16"; break; - case 4: result += "u32"; break; - case 8: result += "u64"; break; - case 16: result += "u128"; break; + case 1: + result += "u8"; + break; + case 2: + result += "u16"; + break; + case 4: + result += "u32"; + break; + case 8: + result += "u64"; + break; + case 16: + result += "u128"; + break; } return result; @@ -421,7 +426,7 @@ namespace hex::pl { return this->m_pointedAtAddress; } - [[nodiscard]] PatternData* getPointedAtPattern() { + [[nodiscard]] PatternData *getPointedAtPattern() { return this->m_pointedAt; } @@ -432,7 +437,7 @@ namespace hex::pl { [[nodiscard]] bool operator==(const PatternData &other) const override { return areCommonPropertiesEqual(other) && - *static_cast(&other)->m_pointedAt == *this->m_pointedAt; + *static_cast(&other)->m_pointedAt == *this->m_pointedAt; } void rebase(u64 base) { @@ -444,8 +449,7 @@ namespace hex::pl { this->m_pointerBase = base; } - [[nodiscard]] - const PatternData* getPattern(u64 offset) const override { + [[nodiscard]] const PatternData *getPattern(u64 offset) const override { if (offset >= this->getOffset() && offset < (this->getOffset() + this->getSize()) && !this->isHidden()) return this; else @@ -464,11 +468,11 @@ namespace hex::pl { PatternDataUnsigned(u64 offset, size_t size, Evaluator *evaluator, u32 color = 0) : PatternData(offset, size, evaluator, color) { } - PatternData* clone() override { + PatternData *clone() override { return new PatternDataUnsigned(*this); } - void createEntry(prv::Provider* &provider) override { + void createEntry(prv::Provider *&provider) override { u128 data = 0; provider->read(this->getOffset(), &data, this->getSize()); data = hex::changeEndianess(data, this->getSize(), this->getEndian()); @@ -478,12 +482,18 @@ namespace hex::pl { [[nodiscard]] std::string getFormattedName() const override { switch (this->getSize()) { - case 1: return "u8"; - case 2: return "u16"; - case 4: return "u32"; - case 8: return "u64"; - case 16: return "u128"; - default: return "Unsigned data"; + case 1: + return "u8"; + case 2: + return "u16"; + case 4: + return "u32"; + case 8: + return "u64"; + case 16: + return "u128"; + default: + return "Unsigned data"; } } @@ -495,11 +505,11 @@ namespace hex::pl { PatternDataSigned(u64 offset, size_t size, Evaluator *evaluator, u32 color = 0) : PatternData(offset, size, evaluator, color) { } - PatternData* clone() override { + PatternData *clone() override { return new PatternDataSigned(*this); } - void createEntry(prv::Provider* &provider) override { + void createEntry(prv::Provider *&provider) override { i128 data = 0; provider->read(this->getOffset(), &data, this->getSize()); data = hex::changeEndianess(data, this->getSize(), this->getEndian()); @@ -510,12 +520,18 @@ namespace hex::pl { [[nodiscard]] std::string getFormattedName() const override { switch (this->getSize()) { - case 1: return "s8"; - case 2: return "s16"; - case 4: return "s32"; - case 8: return "s64"; - case 16: return "s128"; - default: return "Signed data"; + case 1: + return "s8"; + case 2: + return "s16"; + case 4: + return "s32"; + case 8: + return "s64"; + case 16: + return "s128"; + default: + return "Signed data"; } } @@ -527,31 +543,34 @@ namespace hex::pl { PatternDataFloat(u64 offset, size_t size, Evaluator *evaluator, u32 color = 0) : PatternData(offset, size, evaluator, color) { } - PatternData* clone() override { + PatternData *clone() override { return new PatternDataFloat(*this); } - void createEntry(prv::Provider* &provider) override { + void createEntry(prv::Provider *&provider) override { if (this->getSize() == 4) { u32 data = 0; provider->read(this->getOffset(), &data, 4); data = hex::changeEndianess(data, 4, this->getEndian()); - this->createDefaultEntry(hex::format("{:e} (0x{:0{}X})", *reinterpret_cast(&data), data, this->getSize() * 2), *reinterpret_cast(&data)); + this->createDefaultEntry(hex::format("{:e} (0x{:0{}X})", *reinterpret_cast(&data), data, this->getSize() * 2), *reinterpret_cast(&data)); } else if (this->getSize() == 8) { u64 data = 0; provider->read(this->getOffset(), &data, 8); data = hex::changeEndianess(data, 8, this->getEndian()); - this->createDefaultEntry(hex::format("{:e} (0x{:0{}X})", *reinterpret_cast(&data), data, this->getSize() * 2), *reinterpret_cast(&data)); + this->createDefaultEntry(hex::format("{:e} (0x{:0{}X})", *reinterpret_cast(&data), data, this->getSize() * 2), *reinterpret_cast(&data)); } } [[nodiscard]] std::string getFormattedName() const override { switch (this->getSize()) { - case 4: return "float"; - case 8: return "double"; - default: return "Floating point data"; + case 4: + return "float"; + case 8: + return "double"; + default: + return "Floating point data"; } } @@ -561,13 +580,13 @@ namespace hex::pl { class PatternDataBoolean : public PatternData { public: explicit PatternDataBoolean(u64 offset, Evaluator *evaluator, u32 color = 0) - : PatternData(offset, 1, evaluator, color) { } + : PatternData(offset, 1, evaluator, color) { } - PatternData* clone() override { + PatternData *clone() override { return new PatternDataBoolean(*this); } - void createEntry(prv::Provider* &provider) override { + void createEntry(prv::Provider *&provider) override { u8 boolean; provider->read(this->getOffset(), &boolean, 1); @@ -591,11 +610,11 @@ namespace hex::pl { explicit PatternDataCharacter(u64 offset, Evaluator *evaluator, u32 color = 0) : PatternData(offset, 1, evaluator, color) { } - PatternData* clone() override { + PatternData *clone() override { return new PatternDataCharacter(*this); } - void createEntry(prv::Provider* &provider) override { + void createEntry(prv::Provider *&provider) override { char character; provider->read(this->getOffset(), &character, 1); @@ -612,19 +631,19 @@ namespace hex::pl { class PatternDataCharacter16 : public PatternData { public: explicit PatternDataCharacter16(u64 offset, Evaluator *evaluator, u32 color = 0) - : PatternData(offset, 2, evaluator, color) { } + : PatternData(offset, 2, evaluator, color) { } - PatternData* clone() override { + PatternData *clone() override { return new PatternDataCharacter16(*this); } - void createEntry(prv::Provider* &provider) override { + void createEntry(prv::Provider *&provider) override { char16_t character; provider->read(this->getOffset(), &character, 2); character = hex::changeEndianess(character, this->getEndian()); u128 literal = character; - this->createDefaultEntry(hex::format("'{0}'", std::wstring_convert, char16_t>{}.to_bytes(character)), literal); + this->createDefaultEntry(hex::format("'{0}'", std::wstring_convert, char16_t> {}.to_bytes(character)), literal); } [[nodiscard]] std::string getFormattedName() const override { @@ -636,7 +655,7 @@ namespace hex::pl { provider->read(this->getOffset(), &character, 2); character = hex::changeEndianess(character, this->getEndian()); - return std::wstring_convert, char16_t>{}.to_bytes(character); + return std::wstring_convert, char16_t> {}.to_bytes(character); } [[nodiscard]] bool operator==(const PatternData &other) const override { return areCommonPropertiesEqual(other); } @@ -647,11 +666,11 @@ namespace hex::pl { PatternDataString(u64 offset, size_t size, Evaluator *evaluator, u32 color = 0) : PatternData(offset, size, evaluator, color) { } - PatternData* clone() override { + PatternData *clone() override { return new PatternDataString(*this); } - void createEntry(prv::Provider* &provider) override { + void createEntry(prv::Provider *&provider) override { auto size = std::min(this->getSize(), 0x7F); if (size == 0) @@ -661,7 +680,7 @@ namespace hex::pl { provider->read(this->getOffset(), buffer.data(), size); - std::erase_if(buffer, [](auto c){ + std::erase_if(buffer, [](auto c) { return c == 0x00; }); @@ -669,14 +688,14 @@ namespace hex::pl { } [[nodiscard]] std::string getFormattedName() const override { - return "String"; + return "String"; } [[nodiscard]] std::string toString(prv::Provider *provider) const override { std::string buffer(this->getSize(), 0x00); provider->read(this->getOffset(), buffer.data(), buffer.size()); - std::erase_if(buffer, [](auto c){ + std::erase_if(buffer, [](auto c) { return c == 0x00; }); @@ -689,29 +708,29 @@ namespace hex::pl { class PatternDataString16 : public PatternData { public: PatternDataString16(u64 offset, size_t size, Evaluator *evaluator, u32 color = 0) - : PatternData(offset, size, evaluator, color) { } + : PatternData(offset, size, evaluator, color) { } - PatternData* clone() override { + PatternData *clone() override { return new PatternDataString16(*this); } - void createEntry(prv::Provider* &provider) override { + void createEntry(prv::Provider *&provider) override { auto size = std::min(this->getSize(), 0x100); if (size == 0) return; - std::u16string buffer(this->getSize()/sizeof(char16_t), 0x00); + std::u16string buffer(this->getSize() / sizeof(char16_t), 0x00); provider->read(this->getOffset(), buffer.data(), size); for (auto &c : buffer) c = hex::changeEndianess(c, 2, this->getEndian()); - std::erase_if(buffer, [](auto c){ + std::erase_if(buffer, [](auto c) { return c == 0x00; }); - auto utf8String = std::wstring_convert, char16_t>{}.to_bytes(buffer); + auto utf8String = std::wstring_convert, char16_t> {}.to_bytes(buffer); this->createDefaultEntry(hex::format("\"{0}\" {1}", utf8String, size > this->getSize() ? "(truncated)" : ""), utf8String); } @@ -721,30 +740,31 @@ namespace hex::pl { } [[nodiscard]] std::string toString(prv::Provider *provider) const override { - std::u16string buffer(this->getSize()/sizeof(char16_t), 0x00); + std::u16string buffer(this->getSize() / sizeof(char16_t), 0x00); provider->read(this->getOffset(), buffer.data(), this->getSize()); for (auto &c : buffer) c = hex::changeEndianess(c, 2, this->getEndian()); - std::erase_if(buffer, [](auto c){ + std::erase_if(buffer, [](auto c) { return c == 0x00; }); - return std::wstring_convert, char16_t>{}.to_bytes(buffer); + return std::wstring_convert, char16_t> {}.to_bytes(buffer); } [[nodiscard]] bool operator==(const PatternData &other) const override { return areCommonPropertiesEqual(other); } }; - class PatternDataDynamicArray : public PatternData, public Inlinable { + class PatternDataDynamicArray : public PatternData, + public Inlinable { public: PatternDataDynamicArray(u64 offset, size_t size, Evaluator *evaluator, u32 color = 0) : PatternData(offset, size, evaluator, color) { } PatternDataDynamicArray(const PatternDataDynamicArray &other) : PatternData(other) { - std::vector entries; + std::vector entries; for (const auto &entry : other.m_entries) entries.push_back(entry->clone()); @@ -756,7 +776,7 @@ namespace hex::pl { delete entry; } - PatternData* clone() override { + PatternData *clone() override { return new PatternDataDynamicArray(*this); } @@ -766,7 +786,7 @@ namespace hex::pl { entry->setColor(color); } - void createEntry(prv::Provider* &provider) override { + void createEntry(prv::Provider *&provider) override { if (this->m_entries.empty()) return; @@ -836,11 +856,11 @@ namespace hex::pl { PatternData::setOffset(offset); } - [[nodiscard]] const std::vector& getEntries() { + [[nodiscard]] const std::vector &getEntries() { return this->m_entries; } - void setEntries(const std::vector &entries) { + void setEntries(const std::vector &entries) { this->m_entries = entries; if (this->hasOverriddenColor()) { @@ -854,7 +874,7 @@ namespace hex::pl { if (!areCommonPropertiesEqual(other)) return false; - auto &otherArray = *static_cast(&other); + auto &otherArray = *static_cast(&other); if (this->m_entries.size() != otherArray.m_entries.size()) return false; @@ -866,12 +886,11 @@ namespace hex::pl { return true; } - [[nodiscard]] - const PatternData* getPattern(u64 offset) const override { + [[nodiscard]] const PatternData *getPattern(u64 offset) const override { if (this->isHidden()) return nullptr; - auto iter = std::find_if(this->m_entries.begin(), this->m_entries.end(), [this, offset](PatternData *pattern){ - return offset >= pattern->getOffset() && offset < (pattern->getOffset() + pattern->getSize()); + auto iter = std::find_if(this->m_entries.begin(), this->m_entries.end(), [this, offset](PatternData *pattern) { + return offset >= pattern->getOffset() && offset < (pattern->getOffset() + pattern->getSize()); }); if (iter == this->m_entries.end()) @@ -881,14 +900,15 @@ namespace hex::pl { } private: - std::vector m_entries; + std::vector m_entries; u64 m_displayEnd = 50; }; - class PatternDataStaticArray : public PatternData, public Inlinable { + class PatternDataStaticArray : public PatternData, + public Inlinable { public: PatternDataStaticArray(u64 offset, size_t size, Evaluator *evaluator, u32 color = 0) - : PatternData(offset, size, evaluator, color) { + : PatternData(offset, size, evaluator, color) { } PatternDataStaticArray(const PatternDataStaticArray &other) : PatternData(other) { @@ -900,11 +920,11 @@ namespace hex::pl { delete this->m_highlightTemplate; } - PatternData* clone() override { + PatternData *clone() override { return new PatternDataStaticArray(*this); } - void createEntry(prv::Provider* &provider) override { + void createEntry(prv::Provider *&provider) override { if (this->getEntryCount() == 0) return; @@ -988,7 +1008,7 @@ namespace hex::pl { return this->m_template->getTypeName() + "[" + std::to_string(this->m_entryCount) + "]"; } - [[nodiscard]] PatternData* getTemplate() const { + [[nodiscard]] PatternData *getTemplate() const { return this->m_template; } @@ -1000,7 +1020,7 @@ namespace hex::pl { this->m_entryCount = count; } - void setEntries(PatternData* templ, size_t count) { + void setEntries(PatternData *templ, size_t count) { this->m_template = templ; this->m_highlightTemplate = this->m_template->clone(); this->m_entryCount = count; @@ -1013,12 +1033,11 @@ namespace hex::pl { if (!areCommonPropertiesEqual(other)) return false; - auto &otherArray = *static_cast(&other); + auto &otherArray = *static_cast(&other); return *this->m_template == *otherArray.m_template && this->m_entryCount == otherArray.m_entryCount; } - [[nodiscard]] - const PatternData* getPattern(u64 offset) const override { + [[nodiscard]] const PatternData *getPattern(u64 offset) const override { if (this->isHidden()) return nullptr; if (offset >= this->getOffset() && offset < (this->getOffset() + this->getSize())) { @@ -1036,10 +1055,11 @@ namespace hex::pl { u64 m_displayEnd = 50; }; - class PatternDataStruct : public PatternData, public Inlinable { + class PatternDataStruct : public PatternData, + public Inlinable { public: PatternDataStruct(u64 offset, size_t size, Evaluator *evaluator, u32 color = 0) - : PatternData(offset, size, evaluator, color){ + : PatternData(offset, size, evaluator, color) { } PatternDataStruct(const PatternDataStruct &other) : PatternData(other) { @@ -1053,11 +1073,11 @@ namespace hex::pl { delete member; } - PatternData* clone() override { + PatternData *clone() override { return new PatternDataStruct(*this); } - void createEntry(prv::Provider* &provider) override { + void createEntry(prv::Provider *&provider) override { bool open = true; if (!this->isInlined()) { @@ -1071,7 +1091,9 @@ namespace hex::pl { ImGui::TableNextColumn(); ImGui::TextFormatted("0x{0:04X}", this->getSize()); ImGui::TableNextColumn(); - ImGui::TextFormattedColored(ImColor(0xFFD69C56), "struct"); ImGui::SameLine(); ImGui::TextUnformatted(this->getTypeName().c_str()); + ImGui::TextFormattedColored(ImColor(0xFFD69C56), "struct"); + ImGui::SameLine(); + ImGui::TextUnformatted(this->getTypeName().c_str()); ImGui::TableNextColumn(); ImGui::TextFormatted("{}", this->formatDisplayValue("{ ... }", this)); } @@ -1083,7 +1105,6 @@ namespace hex::pl { if (!this->isInlined()) ImGui::TreePop(); } - } void getHighlightedAddresses(std::map &highlight) const override { @@ -1120,11 +1141,11 @@ namespace hex::pl { return "struct " + PatternData::getTypeName(); } - [[nodiscard]] const auto& getMembers() const { + [[nodiscard]] const auto &getMembers() const { return this->m_members; } - void setMembers(const std::vector & members) { + void setMembers(const std::vector &members) { this->m_members.clear(); for (auto &member : members) { @@ -1140,7 +1161,7 @@ namespace hex::pl { if (!areCommonPropertiesEqual(other)) return false; - auto &otherStruct = *static_cast(&other); + auto &otherStruct = *static_cast(&other); if (this->m_members.size() != otherStruct.m_members.size()) return false; @@ -1152,11 +1173,10 @@ namespace hex::pl { return true; } - [[nodiscard]] - const PatternData* getPattern(u64 offset) const override { + [[nodiscard]] const PatternData *getPattern(u64 offset) const override { if (this->isHidden()) return nullptr; - auto iter = std::find_if(this->m_members.begin(), this->m_members.end(), [offset](PatternData *pattern){ + auto iter = std::find_if(this->m_members.begin(), this->m_members.end(), [offset](PatternData *pattern) { return offset >= pattern->getOffset() && offset < (pattern->getOffset() + pattern->getSize()); }); @@ -1167,15 +1187,15 @@ namespace hex::pl { } private: - std::vector m_members; - std::vector m_sortedMembers; + std::vector m_members; + std::vector m_sortedMembers; }; - class PatternDataUnion : public PatternData, public Inlinable { + class PatternDataUnion : public PatternData, + public Inlinable { public: PatternDataUnion(u64 offset, size_t size, Evaluator *evaluator, u32 color = 0) : PatternData(offset, size, evaluator, color) { - } PatternDataUnion(const PatternDataUnion &other) : PatternData(other) { @@ -1189,11 +1209,11 @@ namespace hex::pl { delete member; } - PatternData* clone() override { + PatternData *clone() override { return new PatternDataUnion(*this); } - void createEntry(prv::Provider* &provider) override { + void createEntry(prv::Provider *&provider) override { bool open = true; if (!this->isInlined()) { @@ -1207,7 +1227,9 @@ namespace hex::pl { ImGui::TableNextColumn(); ImGui::TextFormatted("0x{0:04X}", this->getSize()); ImGui::TableNextColumn(); - ImGui::TextFormattedColored(ImColor(0xFFD69C56), "union"); ImGui::SameLine(); ImGui::TextUnformatted(PatternData::getTypeName().c_str()); + ImGui::TextFormattedColored(ImColor(0xFFD69C56), "union"); + ImGui::SameLine(); + ImGui::TextUnformatted(PatternData::getTypeName().c_str()); ImGui::TableNextColumn(); ImGui::TextFormatted("{}", this->formatDisplayValue("{ ... }", this)); @@ -1218,9 +1240,8 @@ namespace hex::pl { member->draw(provider); if (!this->isInlined()) - ImGui::TreePop(); + ImGui::TreePop(); } - } void getHighlightedAddresses(std::map &highlight) const override { @@ -1254,14 +1275,15 @@ namespace hex::pl { } [[nodiscard]] std::string getFormattedName() const override { - return "union " + PatternData::getTypeName();; + return "union " + PatternData::getTypeName(); + ; } - [[nodiscard]] const auto& getMembers() const { + [[nodiscard]] const auto &getMembers() const { return this->m_members; } - void setMembers(const std::vector & members) { + void setMembers(const std::vector &members) { this->m_members.clear(); for (auto &member : members) { if (member == nullptr) continue; @@ -1276,7 +1298,7 @@ namespace hex::pl { if (!areCommonPropertiesEqual(other)) return false; - auto &otherUnion = *static_cast(&other); + auto &otherUnion = *static_cast(&other); if (this->m_members.size() != otherUnion.m_members.size()) return false; @@ -1288,8 +1310,7 @@ namespace hex::pl { return true; } - [[nodiscard]] - const PatternData* getPattern(u64 offset) const override { + [[nodiscard]] const PatternData *getPattern(u64 offset) const override { if (this->isHidden()) return nullptr; auto largestMember = std::find_if(this->m_members.begin(), this->m_members.end(), [this](PatternData *pattern) { @@ -1299,26 +1320,26 @@ namespace hex::pl { if (largestMember == this->m_members.end()) return nullptr; else - return (*largestMember)->getPattern(offset);; + return (*largestMember)->getPattern(offset); + ; } private: - std::vector m_members; - std::vector m_sortedMembers; + std::vector m_members; + std::vector m_sortedMembers; }; class PatternDataEnum : public PatternData { public: PatternDataEnum(u64 offset, size_t size, Evaluator *evaluator, u32 color = 0) : PatternData(offset, size, evaluator, color) { - } - PatternData* clone() override { + PatternData *clone() override { return new PatternDataEnum(*this); } - void createEntry(prv::Provider* &provider) override { + void createEntry(prv::Provider *&provider) override { u64 value = 0; provider->read(this->getOffset(), &value, this->getSize()); value = hex::changeEndianess(value, this->getSize(), this->getEndian()); @@ -1328,18 +1349,18 @@ namespace hex::pl { bool foundValue = false; for (auto &[entryValueLiteral, entryName] : this->m_enumValues) { bool matches = std::visit(overloaded { - [&, name = entryName](auto &&entryValue) { - if (value == entryValue) { - valueString += name; - foundValue = true; - return true; - } + [&, name = entryName](auto &&entryValue) { + if (value == entryValue) { + valueString += name; + foundValue = true; + return true; + } - return false; - }, - [](std::string) { return false; }, - [](PatternData*) { return false; } - }, entryValueLiteral); + return false; + }, + [](std::string) { return false; }, + [](PatternData *) { return false; } }, + entryValueLiteral); if (matches) break; } @@ -1363,7 +1384,9 @@ namespace hex::pl { ImGui::TableNextColumn(); ImGui::TextFormatted("0x{0:04X}", this->getSize()); ImGui::TableNextColumn(); - ImGui::TextFormattedColored(ImColor(0xFFD69C56), "enum"); ImGui::SameLine(); ImGui::TextUnformatted(PatternData::getTypeName().c_str()); + ImGui::TextFormattedColored(ImColor(0xFFD69C56), "enum"); + ImGui::SameLine(); + ImGui::TextUnformatted(PatternData::getTypeName().c_str()); ImGui::TableNextColumn(); ImGui::TextFormatted("{}", this->formatDisplayValue(hex::format("{} (0x{:0{}X})", valueString.c_str(), value, this->getSize() * 2), this)); } @@ -1372,7 +1395,7 @@ namespace hex::pl { return "enum " + PatternData::getTypeName(); } - [[nodiscard]] const auto& getEnumValues() const { + [[nodiscard]] const auto &getEnumValues() const { return this->m_enumValues; } @@ -1384,7 +1407,7 @@ namespace hex::pl { if (!areCommonPropertiesEqual(other)) return false; - auto &otherEnum = *static_cast(&other); + auto &otherEnum = *static_cast(&other); if (this->m_enumValues.size() != otherEnum.m_enumValues.size()) return false; @@ -1404,15 +1427,14 @@ namespace hex::pl { class PatternDataBitfieldField : public PatternData { public: PatternDataBitfieldField(u64 offset, u8 bitOffset, u8 bitSize, PatternData *bitField, Evaluator *evaluator, u32 color = 0) - : m_bitOffset(bitOffset), m_bitSize(bitSize), m_bitField(bitField), PatternData(offset, 0, evaluator, color) { - + : m_bitOffset(bitOffset), m_bitSize(bitSize), m_bitField(bitField), PatternData(offset, 0, evaluator, color) { } - PatternData* clone() override { + PatternData *clone() override { return new PatternDataBitfieldField(*this); } - void createEntry(prv::Provider* &provider) override { + void createEntry(prv::Provider *&provider) override { std::vector value(this->m_bitField->getSize(), 0); provider->read(this->m_bitField->getOffset(), &value[0], value.size()); @@ -1443,7 +1465,6 @@ namespace hex::pl { u64 extractedValue = hex::extract(this->m_bitOffset + (this->m_bitSize - 1), this->m_bitOffset, value); ImGui::TextFormatted("{}", this->formatDisplayValue(hex::format("{0} (0x{1:X})", extractedValue, extractedValue), this)); } - } [[nodiscard]] std::string getFormattedName() const override { @@ -1462,7 +1483,7 @@ namespace hex::pl { if (!areCommonPropertiesEqual(other)) return false; - auto &otherBitfieldField = *static_cast(&other); + auto &otherBitfieldField = *static_cast(&other); return this->m_bitOffset == otherBitfieldField.m_bitOffset && this->m_bitSize == otherBitfieldField.m_bitSize; } @@ -1471,11 +1492,11 @@ namespace hex::pl { PatternData *m_bitField; }; - class PatternDataBitfield : public PatternData, public Inlinable { + class PatternDataBitfield : public PatternData, + public Inlinable { public: PatternDataBitfield(u64 offset, size_t size, Evaluator *evaluator, u32 color = 0) : PatternData(offset, size, evaluator, color) { - } PatternDataBitfield(const PatternDataBitfield &other) : PatternData(other) { @@ -1488,11 +1509,11 @@ namespace hex::pl { delete field; } - PatternData* clone() override { + PatternData *clone() override { return new PatternDataBitfield(*this); } - void createEntry(prv::Provider* &provider) override { + void createEntry(prv::Provider *&provider) override { std::vector value(this->getSize(), 0); provider->read(this->getOffset(), &value[0], value.size()); @@ -1511,7 +1532,9 @@ namespace hex::pl { ImGui::TableNextColumn(); ImGui::TextFormatted("0x{0:04X}", this->getSize()); ImGui::TableNextColumn(); - ImGui::TextFormattedColored(ImColor(0xFFD69C56), "bitfield"); ImGui::SameLine(); ImGui::TextUnformatted(PatternData::getTypeName().c_str()); + ImGui::TextFormattedColored(ImColor(0xFFD69C56), "bitfield"); + ImGui::SameLine(); + ImGui::TextUnformatted(PatternData::getTypeName().c_str()); ImGui::TableNextColumn(); std::string valueString = "{ "; @@ -1530,7 +1553,6 @@ namespace hex::pl { if (!this->isInlined()) ImGui::TreePop(); } - } void setOffset(u64 offset) override { @@ -1544,11 +1566,11 @@ namespace hex::pl { return "bitfield " + PatternData::getTypeName(); } - [[nodiscard]] const auto& getFields() const { + [[nodiscard]] const auto &getFields() const { return this->m_fields; } - void setFields(const std::vector &fields) { + void setFields(const std::vector &fields) { this->m_fields = fields; for (auto &field : this->m_fields) { @@ -1567,7 +1589,7 @@ namespace hex::pl { if (!areCommonPropertiesEqual(other)) return false; - auto &otherBitfield = *static_cast(&other); + auto &otherBitfield = *static_cast(&other); if (this->m_fields.size() != otherBitfield.m_fields.size()) return false; @@ -1580,7 +1602,7 @@ namespace hex::pl { } private: - std::vector m_fields; + std::vector m_fields; }; } \ No newline at end of file diff --git a/lib/libimhex/include/hex/pattern_language/pattern_language.hpp b/lib/libimhex/include/hex/pattern_language/pattern_language.hpp index efc5a021b..d2152bec0 100644 --- a/lib/libimhex/include/hex/pattern_language/pattern_language.hpp +++ b/lib/libimhex/include/hex/pattern_language/pattern_language.hpp @@ -12,7 +12,9 @@ #include #include -namespace hex::prv { class Provider; } +namespace hex::prv { + class Provider; +} namespace hex::pl { @@ -30,31 +32,21 @@ namespace hex::pl { PatternLanguage(); ~PatternLanguage(); - [[nodiscard]] - std::optional> parseString(const std::string &code); - [[nodiscard]] - std::optional> executeString(prv::Provider *provider, const std::string &string, const std::map &envVars = { }, const std::map &inVariables = { }); - [[nodiscard]] - std::optional> executeFile(prv::Provider *provider, const fs::path &path, const std::map &envVars = { }, const std::map &inVariables = { }); - [[nodiscard]] - const std::vector& getCurrentAST() const; + [[nodiscard]] std::optional> parseString(const std::string &code); + [[nodiscard]] std::optional> executeString(prv::Provider *provider, const std::string &string, const std::map &envVars = {}, const std::map &inVariables = {}); + [[nodiscard]] std::optional> executeFile(prv::Provider *provider, const fs::path &path, const std::map &envVars = {}, const std::map &inVariables = {}); + [[nodiscard]] const std::vector &getCurrentAST() const; void abort(); - [[nodiscard]] - const std::vector>& getConsoleLog(); - [[nodiscard]] - const std::optional>& getError(); - [[nodiscard]] - std::map getOutVariables() const; + [[nodiscard]] const std::vector> &getConsoleLog(); + [[nodiscard]] const std::optional> &getError(); + [[nodiscard]] std::map getOutVariables() const; - [[nodiscard]] - u32 getCreatedPatternCount(); - [[nodiscard]] - u32 getMaximumPatternCount(); + [[nodiscard]] u32 getCreatedPatternCount(); + [[nodiscard]] u32 getMaximumPatternCount(); - [[nodiscard]] - bool hasDangerousFunctionBeenCalled() const; + [[nodiscard]] bool hasDangerousFunctionBeenCalled() const; void allowDangerousFunctions(bool allow); private: @@ -64,7 +56,7 @@ namespace hex::pl { Validator *m_validator; Evaluator *m_evaluator; - std::vector m_currAST; + std::vector m_currAST; std::optional> m_currError; }; diff --git a/lib/libimhex/include/hex/pattern_language/preprocessor.hpp b/lib/libimhex/include/hex/pattern_language/preprocessor.hpp index 238b01d09..2499777f8 100644 --- a/lib/libimhex/include/hex/pattern_language/preprocessor.hpp +++ b/lib/libimhex/include/hex/pattern_language/preprocessor.hpp @@ -15,12 +15,12 @@ namespace hex::pl { public: Preprocessor(); - std::optional preprocess(const std::string& code, bool initialRun = true); + std::optional preprocess(const std::string &code, bool initialRun = true); - void addPragmaHandler(const std::string &pragmaType, const std::function &function); + void addPragmaHandler(const std::string &pragmaType, const std::function &function); void addDefaultPragmaHandlers(); - const std::pair& getError() { return this->m_error; } + const std::pair &getError() { return this->m_error; } private: using PreprocessorError = std::pair; diff --git a/lib/libimhex/include/hex/pattern_language/token.hpp b/lib/libimhex/include/hex/pattern_language/token.hpp index c632e8f05..d6bed5044 100644 --- a/lib/libimhex/include/hex/pattern_language/token.hpp +++ b/lib/libimhex/include/hex/pattern_language/token.hpp @@ -80,31 +80,31 @@ namespace hex::pl { }; enum class ValueType { - Unsigned8Bit = 0x10, - Signed8Bit = 0x11, - Unsigned16Bit = 0x20, - Signed16Bit = 0x21, - Unsigned32Bit = 0x40, - Signed32Bit = 0x41, - Unsigned64Bit = 0x80, - Signed64Bit = 0x81, - Unsigned128Bit = 0x100, - Signed128Bit = 0x101, - Character = 0x13, - Character16 = 0x23, - Boolean = 0x14, - Float = 0x42, - Double = 0x82, - String = 0x15, - Auto = 0x16, - CustomType = 0x00, - Padding = 0x1F, + Unsigned8Bit = 0x10, + Signed8Bit = 0x11, + Unsigned16Bit = 0x20, + Signed16Bit = 0x21, + Unsigned32Bit = 0x40, + Signed32Bit = 0x41, + Unsigned64Bit = 0x80, + Signed64Bit = 0x81, + Unsigned128Bit = 0x100, + Signed128Bit = 0x101, + Character = 0x13, + Character16 = 0x23, + Boolean = 0x14, + Float = 0x42, + Double = 0x82, + String = 0x15, + Auto = 0x16, + CustomType = 0x00, + Padding = 0x1F, - Unsigned = 0xFF00, - Signed = 0xFF01, - FloatingPoint = 0xFF02, - Integer = 0xFF03, - Any = 0xFFFF + Unsigned = 0xFF00, + Signed = 0xFF01, + FloatingPoint = 0xFF02, + Integer = 0xFF03, + Any = 0xFFFF }; enum class Separator { @@ -123,21 +123,19 @@ namespace hex::pl { struct Identifier { explicit Identifier(std::string identifier) : m_identifier(std::move(identifier)) { } - [[nodiscard]] - const std::string &get() const { return this->m_identifier; } + [[nodiscard]] const std::string &get() const { return this->m_identifier; } - auto operator<=>(const Identifier&) const = default; - bool operator==(const Identifier&) const = default; + auto operator<=>(const Identifier &) const = default; + bool operator==(const Identifier &) const = default; private: std::string m_identifier; }; - using Literal = std::variant; + using Literal = std::variant; using ValueTypes = std::variant; Token(Type type, auto value, u32 lineNumber) : type(type), value(value), lineNumber(lineNumber) { - } [[nodiscard]] constexpr static inline bool isUnsigned(const ValueType type) { @@ -158,37 +156,33 @@ namespace hex::pl { static u128 literalToUnsigned(const pl::Token::Literal &literal) { return std::visit(overloaded { - [](std::string) -> u128 { throw std::string("expected integral type, got string"); }, - [](PatternData*) -> u128 { throw std::string("expected integral type, got custom type"); }, - [](auto &&value) -> u128 { return value; } - }, + [](std::string) -> u128 { throw std::string("expected integral type, got string"); }, + [](PatternData *) -> u128 { throw std::string("expected integral type, got custom type"); }, + [](auto &&value) -> u128 { return value; } }, literal); } static i128 literalToSigned(const pl::Token::Literal &literal) { return std::visit(overloaded { - [](std::string) -> i128 { throw std::string("expected integral type, got string"); }, - [](PatternData*) -> i128 { throw std::string("expected integral type, got custom type"); }, - [](auto &&value) -> i128 { return value; } - }, + [](std::string) -> i128 { throw std::string("expected integral type, got string"); }, + [](PatternData *) -> i128 { throw std::string("expected integral type, got custom type"); }, + [](auto &&value) -> i128 { return value; } }, literal); } static double literalToFloatingPoint(const pl::Token::Literal &literal) { return std::visit(overloaded { - [](std::string) -> double { throw std::string("expected integral type, got string"); }, - [](PatternData*) -> double { throw std::string("expected integral type, got custom type"); }, - [](auto &&value) -> double { return value; } - }, + [](std::string) -> double { throw std::string("expected integral type, got string"); }, + [](PatternData *) -> double { throw std::string("expected integral type, got custom type"); }, + [](auto &&value) -> double { return value; } }, literal); } static bool literalToBoolean(const pl::Token::Literal &literal) { return std::visit(overloaded { - [](std::string) -> bool { throw std::string("expected integral type, got string"); }, - [](PatternData*) -> bool { throw std::string("expected integral type, got custom type"); }, - [](auto &&value) -> bool { return value != 0; } - }, + [](std::string) -> bool { throw std::string("expected integral type, got string"); }, + [](PatternData *) -> bool { throw std::string("expected integral type, got custom type"); }, + [](auto &&value) -> bool { return value != 0; } }, literal); } @@ -197,36 +191,52 @@ namespace hex::pl { throw std::string("expected string type, got integral"); return std::visit(overloaded { - [](std::string value) -> std::string { return value; }, - [](u128 value) -> std::string { return std::to_string(u64(value)); }, - [](i128 value) -> std::string { return std::to_string(i64(value)); }, - [](bool value) -> std::string { return value ? "true" : "false"; }, - [](char value) -> std::string { return std::string() + value; }, - [](PatternData*) -> std::string { throw std::string("expected integral type, got custom type"); }, - [](auto &&value) -> std::string { return std::to_string(value); } - }, + [](std::string value) -> std::string { return value; }, + [](u128 value) -> std::string { return std::to_string(u64(value)); }, + [](i128 value) -> std::string { return std::to_string(i64(value)); }, + [](bool value) -> std::string { return value ? "true" : "false"; }, + [](char value) -> std::string { return std::string() + value; }, + [](PatternData *) -> std::string { throw std::string("expected integral type, got custom type"); }, + [](auto &&value) -> std::string { return std::to_string(value); } }, literal); } [[nodiscard]] constexpr static auto getTypeName(const pl::Token::ValueType type) { switch (type) { - case ValueType::Signed8Bit: return "s8"; - case ValueType::Signed16Bit: return "s16"; - case ValueType::Signed32Bit: return "s32"; - case ValueType::Signed64Bit: return "s64"; - case ValueType::Signed128Bit: return "s128"; - case ValueType::Unsigned8Bit: return "u8"; - case ValueType::Unsigned16Bit: return "u16"; - case ValueType::Unsigned32Bit: return "u32"; - case ValueType::Unsigned64Bit: return "u64"; - case ValueType::Unsigned128Bit: return "u128"; - case ValueType::Float: return "float"; - case ValueType::Double: return "double"; - case ValueType::Character: return "char"; - case ValueType::Character16: return "char16"; - case ValueType::Padding: return "padding"; - case ValueType::String: return "str"; - default: return "< ??? >"; + case ValueType::Signed8Bit: + return "s8"; + case ValueType::Signed16Bit: + return "s16"; + case ValueType::Signed32Bit: + return "s32"; + case ValueType::Signed64Bit: + return "s64"; + case ValueType::Signed128Bit: + return "s128"; + case ValueType::Unsigned8Bit: + return "u8"; + case ValueType::Unsigned16Bit: + return "u16"; + case ValueType::Unsigned32Bit: + return "u32"; + case ValueType::Unsigned64Bit: + return "u64"; + case ValueType::Unsigned128Bit: + return "u128"; + case ValueType::Float: + return "float"; + case ValueType::Double: + return "double"; + case ValueType::Character: + return "char"; + case ValueType::Character16: + return "char16"; + case ValueType::Padding: + return "padding"; + case ValueType::String: + return "str"; + default: + return "< ??? >"; } } @@ -234,8 +244,8 @@ namespace hex::pl { if (this->type == Type::Integer || this->type == Type::Identifier || this->type == Type::String) return true; else if (this->type == Type::ValueType) { - auto otherValueType = std::get_if(&other); - auto valueType = std::get_if(&this->value); + auto otherValueType = std::get_if(&other); + auto valueType = std::get_if(&this->value); if (otherValueType == nullptr) return false; if (valueType == nullptr) return false; @@ -252,8 +262,7 @@ namespace hex::pl { return isFloatingPoint(*valueType); else if (*otherValueType == ValueType::Integer) return isUnsigned(*valueType) || isSigned(*valueType); - } - else + } else return other == this->value; return false; @@ -266,83 +275,82 @@ namespace hex::pl { Type type; ValueTypes value; u32 lineNumber; - }; } #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) -#define KEYWORD_USING COMPONENT(Keyword, Using) -#define KEYWORD_ENUM COMPONENT(Keyword, Enum) -#define KEYWORD_BITFIELD COMPONENT(Keyword, Bitfield) -#define KEYWORD_LE COMPONENT(Keyword, LittleEndian) -#define KEYWORD_BE COMPONENT(Keyword, BigEndian) -#define KEYWORD_IF COMPONENT(Keyword, If) -#define KEYWORD_ELSE COMPONENT(Keyword, Else) -#define KEYWORD_PARENT COMPONENT(Keyword, Parent) -#define KEYWORD_THIS COMPONENT(Keyword, This) -#define KEYWORD_WHILE COMPONENT(Keyword, While) -#define KEYWORD_FOR COMPONENT(Keyword, For) -#define KEYWORD_FUNCTION COMPONENT(Keyword, Function) -#define KEYWORD_RETURN COMPONENT(Keyword, Return) -#define KEYWORD_NAMESPACE COMPONENT(Keyword, Namespace) -#define KEYWORD_IN COMPONENT(Keyword, In) -#define KEYWORD_OUT COMPONENT(Keyword, Out) -#define KEYWORD_BREAK COMPONENT(Keyword, Break) -#define KEYWORD_CONTINUE COMPONENT(Keyword, Continue) +#define KEYWORD_STRUCT COMPONENT(Keyword, Struct) +#define KEYWORD_UNION COMPONENT(Keyword, Union) +#define KEYWORD_USING COMPONENT(Keyword, Using) +#define KEYWORD_ENUM COMPONENT(Keyword, Enum) +#define KEYWORD_BITFIELD COMPONENT(Keyword, Bitfield) +#define KEYWORD_LE COMPONENT(Keyword, LittleEndian) +#define KEYWORD_BE COMPONENT(Keyword, BigEndian) +#define KEYWORD_IF COMPONENT(Keyword, If) +#define KEYWORD_ELSE COMPONENT(Keyword, Else) +#define KEYWORD_PARENT COMPONENT(Keyword, Parent) +#define KEYWORD_THIS COMPONENT(Keyword, This) +#define KEYWORD_WHILE COMPONENT(Keyword, While) +#define KEYWORD_FOR COMPONENT(Keyword, For) +#define KEYWORD_FUNCTION COMPONENT(Keyword, Function) +#define KEYWORD_RETURN COMPONENT(Keyword, Return) +#define KEYWORD_NAMESPACE COMPONENT(Keyword, Namespace) +#define KEYWORD_IN COMPONENT(Keyword, In) +#define KEYWORD_OUT COMPONENT(Keyword, Out) +#define KEYWORD_BREAK COMPONENT(Keyword, Break) +#define KEYWORD_CONTINUE COMPONENT(Keyword, Continue) -#define INTEGER hex::pl::Token::Type::Integer, hex::pl::Token::Literal(u128(0)) -#define IDENTIFIER hex::pl::Token::Type::Identifier, "" -#define STRING hex::pl::Token::Type::String, hex::pl::Token::Literal("") +#define INTEGER hex::pl::Token::Type::Integer, hex::pl::Token::Literal(u128(0)) +#define IDENTIFIER hex::pl::Token::Type::Identifier, "" +#define STRING hex::pl::Token::Type::String, hex::pl::Token::Literal("") -#define OPERATOR_AT COMPONENT(Operator, AtDeclaration) -#define OPERATOR_ASSIGNMENT COMPONENT(Operator, Assignment) -#define OPERATOR_INHERIT COMPONENT(Operator, Inherit) -#define OPERATOR_PLUS COMPONENT(Operator, Plus) -#define OPERATOR_MINUS COMPONENT(Operator, Minus) -#define OPERATOR_STAR COMPONENT(Operator, Star) -#define OPERATOR_SLASH COMPONENT(Operator, Slash) -#define OPERATOR_PERCENT COMPONENT(Operator, Percent) -#define OPERATOR_SHIFTLEFT COMPONENT(Operator, ShiftLeft) -#define OPERATOR_SHIFTRIGHT COMPONENT(Operator, ShiftRight) -#define OPERATOR_BITOR COMPONENT(Operator, BitOr) -#define OPERATOR_BITAND COMPONENT(Operator, BitAnd) -#define OPERATOR_BITXOR COMPONENT(Operator, BitXor) -#define OPERATOR_BITNOT COMPONENT(Operator, BitNot) -#define OPERATOR_BOOLEQUALS COMPONENT(Operator, BoolEquals) -#define OPERATOR_BOOLNOTEQUALS COMPONENT(Operator, BoolNotEquals) -#define OPERATOR_BOOLGREATERTHAN COMPONENT(Operator, BoolGreaterThan) -#define OPERATOR_BOOLLESSTHAN COMPONENT(Operator, BoolLessThan) -#define OPERATOR_BOOLGREATERTHANOREQUALS COMPONENT(Operator, BoolGreaterThanOrEquals) -#define OPERATOR_BOOLLESSTHANOREQUALS COMPONENT(Operator, BoolLessThanOrEquals) -#define OPERATOR_BOOLAND COMPONENT(Operator, BoolAnd) -#define OPERATOR_BOOLOR COMPONENT(Operator, BoolOr) -#define OPERATOR_BOOLXOR COMPONENT(Operator, BoolXor) -#define OPERATOR_BOOLNOT COMPONENT(Operator, BoolNot) -#define OPERATOR_TERNARYCONDITIONAL COMPONENT(Operator, TernaryConditional) -#define OPERATOR_DOLLAR COMPONENT(Operator, Dollar) -#define OPERATOR_ADDRESSOF COMPONENT(Operator, AddressOf) -#define OPERATOR_SIZEOF COMPONENT(Operator, SizeOf) -#define OPERATOR_SCOPERESOLUTION COMPONENT(Operator, ScopeResolution) +#define OPERATOR_AT COMPONENT(Operator, AtDeclaration) +#define OPERATOR_ASSIGNMENT COMPONENT(Operator, Assignment) +#define OPERATOR_INHERIT COMPONENT(Operator, Inherit) +#define OPERATOR_PLUS COMPONENT(Operator, Plus) +#define OPERATOR_MINUS COMPONENT(Operator, Minus) +#define OPERATOR_STAR COMPONENT(Operator, Star) +#define OPERATOR_SLASH COMPONENT(Operator, Slash) +#define OPERATOR_PERCENT COMPONENT(Operator, Percent) +#define OPERATOR_SHIFTLEFT COMPONENT(Operator, ShiftLeft) +#define OPERATOR_SHIFTRIGHT COMPONENT(Operator, ShiftRight) +#define OPERATOR_BITOR COMPONENT(Operator, BitOr) +#define OPERATOR_BITAND COMPONENT(Operator, BitAnd) +#define OPERATOR_BITXOR COMPONENT(Operator, BitXor) +#define OPERATOR_BITNOT COMPONENT(Operator, BitNot) +#define OPERATOR_BOOLEQUALS COMPONENT(Operator, BoolEquals) +#define OPERATOR_BOOLNOTEQUALS COMPONENT(Operator, BoolNotEquals) +#define OPERATOR_BOOLGREATERTHAN COMPONENT(Operator, BoolGreaterThan) +#define OPERATOR_BOOLLESSTHAN COMPONENT(Operator, BoolLessThan) +#define OPERATOR_BOOLGREATERTHANOREQUALS COMPONENT(Operator, BoolGreaterThanOrEquals) +#define OPERATOR_BOOLLESSTHANOREQUALS COMPONENT(Operator, BoolLessThanOrEquals) +#define OPERATOR_BOOLAND COMPONENT(Operator, BoolAnd) +#define OPERATOR_BOOLOR COMPONENT(Operator, BoolOr) +#define OPERATOR_BOOLXOR COMPONENT(Operator, BoolXor) +#define OPERATOR_BOOLNOT COMPONENT(Operator, BoolNot) +#define OPERATOR_TERNARYCONDITIONAL COMPONENT(Operator, TernaryConditional) +#define OPERATOR_DOLLAR COMPONENT(Operator, Dollar) +#define OPERATOR_ADDRESSOF COMPONENT(Operator, AddressOf) +#define OPERATOR_SIZEOF COMPONENT(Operator, SizeOf) +#define OPERATOR_SCOPERESOLUTION COMPONENT(Operator, ScopeResolution) -#define VALUETYPE_CUSTOMTYPE COMPONENT(ValueType, CustomType) -#define VALUETYPE_PADDING COMPONENT(ValueType, Padding) -#define VALUETYPE_UNSIGNED COMPONENT(ValueType, Unsigned) -#define VALUETYPE_SIGNED COMPONENT(ValueType, Signed) -#define VALUETYPE_FLOATINGPOINT COMPONENT(ValueType, FloatingPoint) -#define VALUETYPE_INTEGER COMPONENT(ValueType, Integer) -#define VALUETYPE_ANY COMPONENT(ValueType, Any) +#define VALUETYPE_CUSTOMTYPE COMPONENT(ValueType, CustomType) +#define VALUETYPE_PADDING COMPONENT(ValueType, Padding) +#define VALUETYPE_UNSIGNED COMPONENT(ValueType, Unsigned) +#define VALUETYPE_SIGNED COMPONENT(ValueType, Signed) +#define VALUETYPE_FLOATINGPOINT COMPONENT(ValueType, FloatingPoint) +#define VALUETYPE_INTEGER COMPONENT(ValueType, Integer) +#define VALUETYPE_ANY COMPONENT(ValueType, Any) -#define SEPARATOR_ROUNDBRACKETOPEN COMPONENT(Separator, RoundBracketOpen) -#define SEPARATOR_ROUNDBRACKETCLOSE COMPONENT(Separator, RoundBracketClose) -#define SEPARATOR_CURLYBRACKETOPEN COMPONENT(Separator, CurlyBracketOpen) -#define SEPARATOR_CURLYBRACKETCLOSE COMPONENT(Separator, CurlyBracketClose) -#define SEPARATOR_SQUAREBRACKETOPEN COMPONENT(Separator, SquareBracketOpen) -#define SEPARATOR_SQUAREBRACKETCLOSE COMPONENT(Separator, SquareBracketClose) -#define SEPARATOR_COMMA COMPONENT(Separator, Comma) -#define SEPARATOR_DOT COMPONENT(Separator, Dot) -#define SEPARATOR_ENDOFEXPRESSION COMPONENT(Separator, EndOfExpression) -#define SEPARATOR_ENDOFPROGRAM COMPONENT(Separator, EndOfProgram) \ No newline at end of file +#define SEPARATOR_ROUNDBRACKETOPEN COMPONENT(Separator, RoundBracketOpen) +#define SEPARATOR_ROUNDBRACKETCLOSE COMPONENT(Separator, RoundBracketClose) +#define SEPARATOR_CURLYBRACKETOPEN COMPONENT(Separator, CurlyBracketOpen) +#define SEPARATOR_CURLYBRACKETCLOSE COMPONENT(Separator, CurlyBracketClose) +#define SEPARATOR_SQUAREBRACKETOPEN COMPONENT(Separator, SquareBracketOpen) +#define SEPARATOR_SQUAREBRACKETCLOSE COMPONENT(Separator, SquareBracketClose) +#define SEPARATOR_COMMA COMPONENT(Separator, Comma) +#define SEPARATOR_DOT COMPONENT(Separator, Dot) +#define SEPARATOR_ENDOFEXPRESSION COMPONENT(Separator, EndOfExpression) +#define SEPARATOR_ENDOFPROGRAM COMPONENT(Separator, EndOfProgram) \ No newline at end of file diff --git a/lib/libimhex/include/hex/pattern_language/validator.hpp b/lib/libimhex/include/hex/pattern_language/validator.hpp index b693eecab..2c0863f5a 100644 --- a/lib/libimhex/include/hex/pattern_language/validator.hpp +++ b/lib/libimhex/include/hex/pattern_language/validator.hpp @@ -13,9 +13,9 @@ namespace hex::pl { public: Validator(); - bool validate(const std::vector& ast); + bool validate(const std::vector &ast); - const std::pair& getError() { return this->m_error; } + const std::pair &getError() { return this->m_error; } private: std::pair m_error; @@ -25,7 +25,6 @@ namespace hex::pl { [[noreturn]] void throwValidateError(std::string_view error, u32 lineNumber) const { throw ValidatorError(lineNumber, error); } - }; } \ No newline at end of file diff --git a/lib/libimhex/include/hex/plugin.hpp b/lib/libimhex/include/hex/plugin.hpp index aa63536eb..ee7fed788 100644 --- a/lib/libimhex/include/hex/plugin.hpp +++ b/lib/libimhex/include/hex/plugin.hpp @@ -8,10 +8,13 @@ #define IMHEX_PLUGIN_SETUP(name, author, description) IMHEX_PLUGIN_SETUP_IMPL(IMHEX_PLUGIN_NAME, name, author, description) -#define IMHEX_PLUGIN_SETUP_IMPL(namespaceName, name, author, description) \ - extern "C" [[gnu::visibility("default")]] const char* getPluginName() { return name; } \ - extern "C" [[gnu::visibility("default")]] const char* getPluginAuthor() { return author; } \ - extern "C" [[gnu::visibility("default")]] const char* getPluginDescription() { return description; } \ - extern "C" [[gnu::visibility("default")]] const char* getCompatibleVersion() { return IMHEX_VERSION; } \ - extern "C" [[gnu::visibility("default")]] void setImGuiContext(ImGuiContext *ctx) { ImGui::SetCurrentContext(ctx); GImGui = ctx; } \ +#define IMHEX_PLUGIN_SETUP_IMPL(namespaceName, name, author, description) \ + extern "C" [[gnu::visibility("default")]] const char *getPluginName() { return name; } \ + extern "C" [[gnu::visibility("default")]] const char *getPluginAuthor() { return author; } \ + extern "C" [[gnu::visibility("default")]] const char *getPluginDescription() { return description; } \ + extern "C" [[gnu::visibility("default")]] const char *getCompatibleVersion() { return IMHEX_VERSION; } \ + extern "C" [[gnu::visibility("default")]] void setImGuiContext(ImGuiContext *ctx) { \ + ImGui::SetCurrentContext(ctx); \ + GImGui = ctx; \ + } \ extern "C" [[gnu::visibility("default")]] void initializePlugin() diff --git a/lib/libimhex/include/hex/providers/overlay.hpp b/lib/libimhex/include/hex/providers/overlay.hpp index 10a64d585..02c40bda7 100644 --- a/lib/libimhex/include/hex/providers/overlay.hpp +++ b/lib/libimhex/include/hex/providers/overlay.hpp @@ -14,7 +14,7 @@ namespace hex::prv { [[nodiscard]] u64 getAddress() const { return this->m_address; } [[nodiscard]] u64 getSize() const { return this->m_data.size(); } - [[nodiscard]] std::vector& getData() { return this->m_data; } + [[nodiscard]] std::vector &getData() { return this->m_data; } private: u64 m_address = 0; diff --git a/lib/libimhex/include/hex/providers/provider.hpp b/lib/libimhex/include/hex/providers/provider.hpp index 7eacfe3bc..fa12738a4 100644 --- a/lib/libimhex/include/hex/providers/provider.hpp +++ b/lib/libimhex/include/hex/providers/provider.hpp @@ -36,17 +36,17 @@ namespace hex::prv { virtual void readRaw(u64 offset, void *buffer, size_t size) = 0; virtual void writeRaw(u64 offset, const void *buffer, size_t size) = 0; - [[nodiscard]] virtual size_t getActualSize() const = 0; + [[nodiscard]] virtual size_t getActualSize() const = 0; void applyOverlays(u64 offset, void *buffer, size_t size); - [[nodiscard]] std::map& getPatches(); - [[nodiscard]] const std::map& getPatches() const; + [[nodiscard]] std::map &getPatches(); + [[nodiscard]] const std::map &getPatches() const; void applyPatches(); - [[nodiscard]] Overlay* newOverlay(); + [[nodiscard]] Overlay *newOverlay(); void deleteOverlay(Overlay *overlay); - [[nodiscard]] const std::list& getOverlays(); + [[nodiscard]] const std::list &getOverlays(); [[nodiscard]] u32 getPageCount() const; [[nodiscard]] u32 getCurrentPage() const; @@ -84,7 +84,7 @@ namespace hex::prv { u32 m_patchTreeOffset = 0; std::list> m_patches; - std::list m_overlays; + std::list m_overlays; }; } \ No newline at end of file diff --git a/lib/libimhex/include/hex/ui/imgui_imhex_extensions.h b/lib/libimhex/include/hex/ui/imgui_imhex_extensions.h index ea37b0003..713a0582d 100644 --- a/lib/libimhex/include/hex/ui/imgui_imhex_extensions.h +++ b/lib/libimhex/include/hex/ui/imgui_imhex_extensions.h @@ -32,42 +32,39 @@ namespace ImGui { ImTextureID textureId; int width, height; - [[nodiscard]] - constexpr bool valid() const noexcept { + [[nodiscard]] constexpr bool valid() const noexcept { return this->textureId != nullptr; } - [[nodiscard]] - constexpr operator ImTextureID() { + [[nodiscard]] constexpr operator ImTextureID() { return this->textureId; } - [[nodiscard]] - auto size() const noexcept { + [[nodiscard]] auto size() const noexcept { return ImVec2(this->width, this->height); } }; int UpdateStringSizeCallback(ImGuiInputTextCallbackData *data); - bool IconHyperlink(const char *icon, const char* label, const ImVec2& size_arg = ImVec2(0, 0), ImGuiButtonFlags flags = 0); - bool Hyperlink(const char* label, const ImVec2& size_arg = ImVec2(0, 0), ImGuiButtonFlags flags = 0); - bool BulletHyperlink(const char* label, const ImVec2& size_arg = ImVec2(0, 0), ImGuiButtonFlags flags = 0); - bool DescriptionButton(const char* label, const char* description, const ImVec2& size_arg = ImVec2(0, 0), ImGuiButtonFlags flags = 0); + bool IconHyperlink(const char *icon, const char *label, const ImVec2 &size_arg = ImVec2(0, 0), ImGuiButtonFlags flags = 0); + bool Hyperlink(const char *label, const ImVec2 &size_arg = ImVec2(0, 0), ImGuiButtonFlags flags = 0); + bool BulletHyperlink(const char *label, const ImVec2 &size_arg = ImVec2(0, 0), ImGuiButtonFlags flags = 0); + bool DescriptionButton(const char *label, const char *description, const ImVec2 &size_arg = ImVec2(0, 0), ImGuiButtonFlags flags = 0); - void UnderlinedText(const char* label, ImColor color = ImGui::GetStyleColorVec4(ImGuiCol_Text), const ImVec2& size_arg = ImVec2(0, 0)); + void UnderlinedText(const char *label, ImColor color = ImGui::GetStyleColorVec4(ImGuiCol_Text), const ImVec2 &size_arg = ImVec2(0, 0)); void Disabled(const std::function &widgets, bool disabled); - void TextSpinner(const char* label); + void TextSpinner(const char *label); void Header(const char *label, bool firstEntry = false); void HeaderColored(const char *label, ImColor color, bool firstEntry); void InfoTooltip(const char *text); - bool TitleBarButton(const char* label, ImVec2 size_arg); - bool ToolBarButton(const char* symbol, ImVec4 color); - bool IconButton(const char* symbol, ImVec4 color, ImVec2 size_arg = ImVec2(0, 0)); + bool TitleBarButton(const char *label, ImVec2 size_arg); + bool ToolBarButton(const char *symbol, ImVec4 color); + bool IconButton(const char *symbol, ImVec4 color, ImVec2 size_arg = ImVec2(0, 0)); inline bool HasSecondPassed() { return static_cast(ImGui::GetTime() * 100) % 100 <= static_cast(ImGui::GetIO().DeltaTime * 100); @@ -92,23 +89,23 @@ namespace ImGui { void SmallProgressBar(float fraction, float yOffset = 0.0F); - void TextFormatted(const std::string &fmt, auto&& ... args) { + void TextFormatted(const std::string &fmt, auto &&...args) { ImGui::TextUnformatted(hex::format(fmt, std::forward(args)...).c_str()); } - void TextFormattedColored(ImColor color, const std::string &fmt, auto&& ... args) { + void TextFormattedColored(ImColor color, const std::string &fmt, auto &&...args) { ImGui::TextColored(color, "%s", hex::format(fmt, std::forward(args)...).c_str()); } - void TextFormattedDisabled(const std::string &fmt, auto&& ... args) { + void TextFormattedDisabled(const std::string &fmt, auto &&...args) { ImGui::TextDisabled("%s", hex::format(fmt, std::forward(args)...).c_str()); } - void TextFormattedWrapped(const std::string &fmt, auto&& ... args) { + void TextFormattedWrapped(const std::string &fmt, auto &&...args) { ImGui::TextWrapped("%s", hex::format(fmt, std::forward(args)...).c_str()); } - void TextFormattedCentered(const std::string &fmt, auto&& ... args) { + void TextFormattedCentered(const std::string &fmt, auto &&...args) { auto text = hex::format(fmt); auto availableSpace = ImGui::GetContentRegionAvail(); auto textSize = ImGui::CalcTextSize(text.c_str(), nullptr, false, availableSpace.x * 0.75F); diff --git a/lib/libimhex/include/hex/views/view.hpp b/lib/libimhex/include/hex/views/view.hpp index 9b626b706..074a2c999 100644 --- a/lib/libimhex/include/hex/views/view.hpp +++ b/lib/libimhex/include/hex/views/view.hpp @@ -36,7 +36,7 @@ namespace hex { virtual bool shouldProcess() const { return this->isAvailable() && this->getWindowOpenState(); } static void doLater(std::function &&function); - static std::vector>& getDeferedCalls(); + static std::vector> &getDeferedCalls(); static void drawCommonInterfaces(); @@ -50,10 +50,10 @@ namespace hex { virtual ImVec2 getMinSize() const; virtual ImVec2 getMaxSize() const; - bool& getWindowOpenState(); - const bool& getWindowOpenState() const; + bool &getWindowOpenState(); + const bool &getWindowOpenState() const; - [[nodiscard]] const std::string& getUnlocalizedName() const; + [[nodiscard]] const std::string &getUnlocalizedName() const; [[nodiscard]] std::string getName() const; static void confirmButtons(const std::string &textLeft, const std::string &textRight, const std::function &leftButtonFn, const std::function &rightButtonFn); diff --git a/lib/libimhex/source/api/content_registry.cpp b/lib/libimhex/source/api/content_registry.cpp index eb10ea9d3..a8640b226 100644 --- a/lib/libimhex/source/api/content_registry.cpp +++ b/lib/libimhex/source/api/content_registry.cpp @@ -43,7 +43,7 @@ namespace hex { void ContentRegistry::Settings::add(const std::string &unlocalizedCategory, const std::string &unlocalizedName, i64 defaultValue, const ContentRegistry::Settings::Callback &callback) { log::info("Registered new integer setting: [{}]: {}", unlocalizedCategory, unlocalizedName); - ContentRegistry::Settings::getEntries()[unlocalizedCategory.c_str()].emplace_back(Entry{ unlocalizedName.c_str(), callback }); + ContentRegistry::Settings::getEntries()[unlocalizedCategory.c_str()].emplace_back(Entry { unlocalizedName.c_str(), callback }); auto &json = getSettingsData(); @@ -56,7 +56,7 @@ namespace hex { void ContentRegistry::Settings::add(const std::string &unlocalizedCategory, const std::string &unlocalizedName, const std::string &defaultValue, const ContentRegistry::Settings::Callback &callback) { log::info("Registered new string setting: [{}]: {}", unlocalizedCategory, unlocalizedName); - ContentRegistry::Settings::getEntries()[unlocalizedCategory].emplace_back(Entry{ unlocalizedName, callback }); + ContentRegistry::Settings::getEntries()[unlocalizedCategory].emplace_back(Entry { unlocalizedName, callback }); auto &json = getSettingsData(); @@ -84,7 +84,7 @@ namespace hex { json[unlocalizedCategory][unlocalizedName] = value; } - void ContentRegistry::Settings::write(const std::string &unlocalizedCategory, const std::string &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)) @@ -122,7 +122,7 @@ namespace hex { return json[unlocalizedCategory][unlocalizedName].get(); } - std::vector ContentRegistry::Settings::read(const std::string &unlocalizedCategory, const std::string &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)) @@ -140,20 +140,20 @@ namespace hex { } - std::map>& ContentRegistry::Settings::getEntries() { + std::map> &ContentRegistry::Settings::getEntries() { return SharedData::settingsEntries; } nlohmann::json ContentRegistry::Settings::getSetting(const std::string &unlocalizedCategory, const std::string &unlocalizedName) { auto &settings = getSettingsData(); - if (!settings.contains(unlocalizedCategory)) return { }; - if (!settings[unlocalizedCategory].contains(unlocalizedName)) return { }; + if (!settings.contains(unlocalizedCategory)) return {}; + if (!settings[unlocalizedCategory].contains(unlocalizedName)) return {}; return settings[unlocalizedCategory][unlocalizedName]; } - nlohmann::json& ContentRegistry::Settings::getSettingsData() { + nlohmann::json &ContentRegistry::Settings::getSettingsData() { return SharedData::settingsJson; } @@ -163,10 +163,10 @@ namespace hex { void ContentRegistry::CommandPaletteCommands::add(ContentRegistry::CommandPaletteCommands::Type type, const std::string &command, const std::string &unlocalizedDescription, const std::function &displayCallback, const std::function &executeCallback) { log::info("Registered new command palette command: {}", command); - getEntries().push_back(ContentRegistry::CommandPaletteCommands::Entry{ type, command, unlocalizedDescription, displayCallback, executeCallback }); + getEntries().push_back(ContentRegistry::CommandPaletteCommands::Entry { type, command, unlocalizedDescription, displayCallback, executeCallback }); } - std::vector& ContentRegistry::CommandPaletteCommands::getEntries() { + std::vector &ContentRegistry::CommandPaletteCommands::getEntries() { return SharedData::commandPaletteCommands; } @@ -196,7 +196,7 @@ namespace hex { getFunctions()[getFunctionName(ns, name)] = Function { parameterCount, func, true }; } - std::map& ContentRegistry::PatternLanguage::getFunctions() { + std::map &ContentRegistry::PatternLanguage::getFunctions() { return SharedData::patternLanguageFunctions; } @@ -209,7 +209,7 @@ namespace hex { getEntries().insert({ view->getUnlocalizedName(), view }); } - std::map& ContentRegistry::Views::getEntries() { + std::map &ContentRegistry::Views::getEntries() { return SharedData::views; } @@ -225,13 +225,13 @@ namespace hex { /* Tools */ - void ContentRegistry::Tools:: add(const std::string &unlocalizedName, const std::function &function) { + void ContentRegistry::Tools::add(const std::string &unlocalizedName, const std::function &function) { log::info("Registered new tool: {}", unlocalizedName); - getEntries().emplace_back(impl::Entry{ unlocalizedName, function }); + getEntries().emplace_back(impl::Entry { unlocalizedName, function }); } - std::vector& ContentRegistry::Tools::getEntries() { + std::vector &ContentRegistry::Tools::getEntries() { return SharedData::toolsEntries; } @@ -244,7 +244,7 @@ namespace hex { getEntries().push_back({ unlocalizedName, requiredSize, std::move(function) }); } - std::vector& ContentRegistry::DataInspector::getEntries() { + std::vector &ContentRegistry::DataInspector::getEntries() { return SharedData::dataInspectorEntries; } @@ -257,10 +257,10 @@ namespace hex { } void ContentRegistry::DataProcessorNode::addSeparator() { - getEntries().push_back({ "", "", []{ return nullptr; } }); + getEntries().push_back({ "", "", [] { return nullptr; } }); } - std::vector& ContentRegistry::DataProcessorNode::getEntries() { + std::vector &ContentRegistry::DataProcessorNode::getEntries() { return SharedData::dataProcessorNodes; } @@ -278,16 +278,15 @@ namespace hex { getLanguageDefinitions()[languageCode].push_back(definition); } - std::map& ContentRegistry::Language::getLanguages() { + std::map &ContentRegistry::Language::getLanguages() { return SharedData::languageNames; } - std::map>& ContentRegistry::Language::getLanguageDefinitions() { + std::map> &ContentRegistry::Language::getLanguageDefinitions() { return SharedData::languageDefinitions; } - /* Interface */ u32 ContentRegistry::Interface::getDockSpaceId() { @@ -303,18 +302,20 @@ namespace hex { void ContentRegistry::Interface::addMenuItem(const std::string &unlocalizedMainMenuName, u32 priority, const impl::DrawCallback &function) { log::info("Added new menu item to menu {} with priority {}", unlocalizedMainMenuName, priority); - getMenuItems().insert({ priority, { unlocalizedMainMenuName, function }}); + getMenuItems().insert({ + priority, {unlocalizedMainMenuName, function} + }); } void ContentRegistry::Interface::addWelcomeScreenEntry(const ContentRegistry::Interface::impl::DrawCallback &function) { getWelcomeScreenEntries().push_back(function); } - void ContentRegistry::Interface::addFooterItem(const ContentRegistry::Interface::impl::DrawCallback &function){ + void ContentRegistry::Interface::addFooterItem(const ContentRegistry::Interface::impl::DrawCallback &function) { getFooterItems().push_back(function); } - void ContentRegistry::Interface::addToolbarItem(const ContentRegistry::Interface::impl::DrawCallback &function){ + void ContentRegistry::Interface::addToolbarItem(const ContentRegistry::Interface::impl::DrawCallback &function) { getToolbarItems().push_back(function); } @@ -329,27 +330,27 @@ namespace hex { } - std::multimap& ContentRegistry::Interface::getMainMenuItems() { + std::multimap &ContentRegistry::Interface::getMainMenuItems() { return SharedData::mainMenuItems; } - std::multimap& ContentRegistry::Interface::getMenuItems() { + std::multimap &ContentRegistry::Interface::getMenuItems() { return SharedData::menuItems; } - std::vector& ContentRegistry::Interface::getWelcomeScreenEntries() { + std::vector &ContentRegistry::Interface::getWelcomeScreenEntries() { return SharedData::welcomeScreenEntries; } - std::vector& ContentRegistry::Interface::getFooterItems() { + std::vector &ContentRegistry::Interface::getFooterItems() { return SharedData::footerItems; } - std::vector& ContentRegistry::Interface::getToolbarItems() { + std::vector &ContentRegistry::Interface::getToolbarItems() { return SharedData::toolbarItems; } - std::vector& ContentRegistry::Interface::getSidebarItems() { + std::vector &ContentRegistry::Interface::getSidebarItems() { return SharedData::sidebarItems; } - std::vector& ContentRegistry::Interface::getLayouts() { + std::vector &ContentRegistry::Interface::getLayouts() { return SharedData::layouts; } @@ -367,7 +368,6 @@ namespace hex { } - /* Data Formatters */ void ContentRegistry::DataFormatter::add(const std::string &unlocalizedName, const impl::Callback &callback) { @@ -381,14 +381,13 @@ namespace hex { } - /* File Handlers */ void ContentRegistry::FileHandler::add(const std::vector &extensions, const impl::Callback &callback) { for (const auto &extension : extensions) log::info("Registered new data handler for extensions: {}", extension); - ContentRegistry::FileHandler::getEntries().push_back({ extensions, callback }); + ContentRegistry::FileHandler::getEntries().push_back({ extensions, callback }); } std::vector &ContentRegistry::FileHandler::getEntries() { diff --git a/lib/libimhex/source/api/event.cpp b/lib/libimhex/source/api/event.cpp index 326a1f395..2526dee7f 100644 --- a/lib/libimhex/source/api/event.cpp +++ b/lib/libimhex/source/api/event.cpp @@ -3,6 +3,6 @@ namespace hex { EventManager::EventList EventManager::s_events; - std::map EventManager::s_tokenStore; + std::map EventManager::s_tokenStore; } \ No newline at end of file diff --git a/lib/libimhex/source/api/imhex_api.cpp b/lib/libimhex/source/api/imhex_api.cpp index 15f2b0d60..804d13249 100644 --- a/lib/libimhex/source/api/imhex_api.cpp +++ b/lib/libimhex/source/api/imhex_api.cpp @@ -15,7 +15,7 @@ namespace hex { void ImHexApi::Common::restartImHex() { EventManager::post(false); - std::atexit([]{ + std::atexit([] { execve(SharedData::mainArgv[0], SharedData::mainArgv, SharedData::mainEnvp); }); } @@ -38,22 +38,22 @@ namespace hex { } 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); + Bookmarks::add(Region { addr, size }, name, comment, color); } - std::list& ImHexApi::Bookmarks::getEntries() { + std::list &ImHexApi::Bookmarks::getEntries() { return SharedData::bookmarkEntries; } - prv::Provider* ImHexApi::Provider::get() { + prv::Provider *ImHexApi::Provider::get() { if (!ImHexApi::Provider::isValid()) return nullptr; return SharedData::providers[SharedData::currentProvider]; } - const std::vector& ImHexApi::Provider::getProviders() { + const std::vector &ImHexApi::Provider::getProviders() { return SharedData::providers; } diff --git a/lib/libimhex/source/api/keybinding.cpp b/lib/libimhex/source/api/keybinding.cpp index 149923358..f0990616a 100644 --- a/lib/libimhex/source/api/keybinding.cpp +++ b/lib/libimhex/source/api/keybinding.cpp @@ -11,7 +11,7 @@ namespace hex { } void ShortcutManager::addShortcut(View *view, const Shortcut &shortcut, const std::function &callback) { - view->m_shortcuts.insert({ shortcut, callback }); + view->m_shortcuts.insert({ shortcut, callback }); } void ShortcutManager::process(View *currentView, bool ctrl, bool alt, bool shift, bool super, bool focused, u32 keyCode) { diff --git a/lib/libimhex/source/api/task.cpp b/lib/libimhex/source/api/task.cpp index e74529529..306b043e0 100644 --- a/lib/libimhex/source/api/task.cpp +++ b/lib/libimhex/source/api/task.cpp @@ -4,7 +4,7 @@ namespace hex { - Task::Task(const std::string& unlocalizedName, u64 maxValue) : m_name(LangEntry(unlocalizedName)), m_maxValue(maxValue), m_currValue(0) { + Task::Task(const std::string &unlocalizedName, u64 maxValue) : m_name(LangEntry(unlocalizedName)), m_maxValue(maxValue), m_currValue(0) { SharedData::runningTasks.push_back(this); } @@ -36,7 +36,7 @@ namespace hex { return this->m_maxValue == 0; } - const std::string& Task::getName() const { + const std::string &Task::getName() const { return this->m_name; } diff --git a/lib/libimhex/source/data_processor/attribute.cpp b/lib/libimhex/source/data_processor/attribute.cpp index 9dfff5144..28b47b4bd 100644 --- a/lib/libimhex/source/data_processor/attribute.cpp +++ b/lib/libimhex/source/data_processor/attribute.cpp @@ -5,7 +5,6 @@ namespace hex::dp { Attribute::Attribute(IOType ioType, Type type, std::string unlocalizedName) : m_id(SharedData::dataProcessorAttrIdCounter++), m_ioType(ioType), m_type(type), m_unlocalizedName(std::move(unlocalizedName)) { - } Attribute::~Attribute() { diff --git a/lib/libimhex/source/data_processor/node.cpp b/lib/libimhex/source/data_processor/node.cpp index 5e01e9786..8e0d062cd 100644 --- a/lib/libimhex/source/data_processor/node.cpp +++ b/lib/libimhex/source/data_processor/node.cpp @@ -51,7 +51,7 @@ namespace hex::dp { if (outputData->size() < sizeof(u64)) throw std::runtime_error("Not enough data provided for integer"); - return *reinterpret_cast(outputData->data()); + return *reinterpret_cast(outputData->data()); } float Node::getFloatOnInput(u32 index) { @@ -74,7 +74,7 @@ namespace hex::dp { if (outputData->size() < sizeof(float)) throw std::runtime_error("Not enough data provided for float"); - return *reinterpret_cast(outputData->data()); + return *reinterpret_cast(outputData->data()); } void Node::setBufferOnOutput(u32 index, std::vector data) { diff --git a/lib/libimhex/source/helpers/crypto.cpp b/lib/libimhex/source/helpers/crypto.cpp index 304544fba..167459c92 100644 --- a/lib/libimhex/source/helpers/crypto.cpp +++ b/lib/libimhex/source/helpers/crypto.cpp @@ -23,30 +23,29 @@ #if MBEDTLS_VERSION_MAJOR <= 2 -#define mbedtls_md5_starts mbedtls_md5_starts_ret -#define mbedtls_md5_update mbedtls_md5_update_ret -#define mbedtls_md5_finish mbedtls_md5_finish_ret + #define mbedtls_md5_starts mbedtls_md5_starts_ret + #define mbedtls_md5_update mbedtls_md5_update_ret + #define mbedtls_md5_finish mbedtls_md5_finish_ret -#define mbedtls_sha1_starts mbedtls_sha1_starts_ret -#define mbedtls_sha1_update mbedtls_sha1_update_ret -#define mbedtls_sha1_finish mbedtls_sha1_finish_ret + #define mbedtls_sha1_starts mbedtls_sha1_starts_ret + #define mbedtls_sha1_update mbedtls_sha1_update_ret + #define mbedtls_sha1_finish mbedtls_sha1_finish_ret -#define mbedtls_sha256_starts mbedtls_sha256_starts_ret -#define mbedtls_sha256_update mbedtls_sha256_update_ret -#define mbedtls_sha256_finish mbedtls_sha256_finish_ret + #define mbedtls_sha256_starts mbedtls_sha256_starts_ret + #define mbedtls_sha256_update mbedtls_sha256_update_ret + #define mbedtls_sha256_finish mbedtls_sha256_finish_ret -#define mbedtls_sha512_starts mbedtls_sha512_starts_ret -#define mbedtls_sha512_update mbedtls_sha512_update_ret -#define mbedtls_sha512_finish mbedtls_sha512_finish_ret + #define mbedtls_sha512_starts mbedtls_sha512_starts_ret + #define mbedtls_sha512_update mbedtls_sha512_update_ret + #define mbedtls_sha512_finish mbedtls_sha512_finish_ret #endif namespace hex::crypt { using namespace std::placeholders; - template Func> - void processDataByChunks(prv::Provider* data, u64 offset, size_t size, Func func) - { + template Func> + void processDataByChunks(prv::Provider *data, u64 offset, size_t size, Func func) { std::array buffer = { 0 }; for (size_t bufferOffset = 0; bufferOffset < size; bufferOffset += buffer.size()) { const auto readSize = std::min(buffer.size(), size - bufferOffset); @@ -56,12 +55,10 @@ namespace hex::crypt { } template - T reflect(T in, std::size_t bits) - { - T out{}; + T reflect(T in, std::size_t bits) { + T out {}; - for(std::size_t i = 0; i < bits; i++) - { + for (std::size_t i = 0; i < bits; i++) { out <<= 1; if (in & 0b1) out |= 1; @@ -71,21 +68,17 @@ namespace hex::crypt { } template - T reflect(T in) - { - if constexpr (sizeof(T) == 1) - { - T out{in}; + T reflect(T in) { + if constexpr (sizeof(T) == 1) { + T out { in }; out = ((out & 0xf0u) >> 4) | ((out & 0x0fu) << 4); out = ((out & 0xccu) >> 2) | ((out & 0x33u) << 2); out = ((out & 0xaau) >> 1) | ((out & 0x55u) << 1); return out; - } - else - { - return reflect(in, sizeof(T) *8 ); + } else { + return reflect(in, sizeof(T) * 8); } } @@ -96,29 +89,28 @@ namespace hex::crypt { public: using calc_type = uint64_t; - Crc(int bits, calc_type polynomial, calc_type init, calc_type xorout, bool refin, bool refout) : - m_bits(bits), - m_init(init & ((0b10ull << (bits-1)) - 1)), - m_xorout(xorout & ((0b10ull << (bits-1)) - 1)), - m_refin(refin), - m_refout(refout), - table([polynomial, bits](){ - auto reflectedpoly= reflect(polynomial & ((0b10ull << (bits-1)) - 1), bits); - std::array table = {0}; + Crc(int bits, calc_type polynomial, calc_type init, calc_type xorout, bool refin, bool refout) : m_bits(bits), + m_init(init & ((0b10ull << (bits - 1)) - 1)), + m_xorout(xorout & ((0b10ull << (bits - 1)) - 1)), + m_refin(refin), + m_refout(refout), + table([polynomial, bits]() { + auto reflectedpoly = reflect(polynomial & ((0b10ull << (bits - 1)) - 1), bits); + std::array table = { 0 }; - for (uint32_t i = 0; i < 256; i++) { - uint64_t c = i; - for (std::size_t j = 0; j < 8; j++) { - if (c & 0b1) - c = reflectedpoly ^ (c >> 1); - else - c >>= 1; - } - table[i] = c; - } + for (uint32_t i = 0; i < 256; i++) { + uint64_t c = i; + for (std::size_t j = 0; j < 8; j++) { + if (c & 0b1) + c = reflectedpoly ^ (c >> 1); + else + c >>= 1; + } + table[i] = c; + } - return table; - }()) { + return table; + }()) { reset(); }; @@ -157,7 +149,7 @@ namespace hex::crypt { }; template - auto calcCrc(prv::Provider* data, u64 offset, std::size_t size, u32 polynomial, u32 init, u32 xorout, bool reflectIn, bool reflectOut) { + auto calcCrc(prv::Provider *data, u64 offset, std::size_t size, u32 polynomial, u32 init, u32 xorout, bool reflectIn, bool reflectOut) { Crc crc(bits, polynomial, init, xorout, reflectIn, reflectOut); processDataByChunks(data, offset, size, std::bind(&Crc::processBytes, &crc, _1, _2)); @@ -165,20 +157,20 @@ namespace hex::crypt { return crc.checksum(); } - u16 crc8(prv::Provider* &data, u64 offset, size_t size, u32 polynomial, u32 init, u32 xorout, bool reflectIn, bool reflectOut) { + u16 crc8(prv::Provider *&data, u64 offset, size_t size, u32 polynomial, u32 init, u32 xorout, bool reflectIn, bool reflectOut) { return calcCrc<8>(data, offset, size, polynomial, init, xorout, reflectIn, reflectOut); } - u16 crc16(prv::Provider* &data, u64 offset, size_t size, u32 polynomial, u32 init, u32 xorout, bool reflectIn, bool reflectOut) { + u16 crc16(prv::Provider *&data, u64 offset, size_t size, u32 polynomial, u32 init, u32 xorout, bool reflectIn, bool reflectOut) { return calcCrc<16>(data, offset, size, polynomial, init, xorout, reflectIn, reflectOut); } - u32 crc32(prv::Provider* &data, u64 offset, size_t size, u32 polynomial, u32 init, u32 xorout, bool reflectIn, bool reflectOut) { + u32 crc32(prv::Provider *&data, u64 offset, size_t size, u32 polynomial, u32 init, u32 xorout, bool reflectIn, bool reflectOut) { return calcCrc<32>(data, offset, size, polynomial, init, xorout, reflectIn, reflectOut); } - std::array md5(prv::Provider* &data, u64 offset, size_t size) { + std::array md5(prv::Provider *&data, u64 offset, size_t size) { std::array result = { 0 }; mbedtls_md5_context ctx; @@ -210,7 +202,7 @@ namespace hex::crypt { return result; } - std::array sha1(prv::Provider* &data, u64 offset, size_t size) { + std::array sha1(prv::Provider *&data, u64 offset, size_t size) { std::array result = { 0 }; mbedtls_sha1_context ctx; @@ -242,7 +234,7 @@ namespace hex::crypt { return result; } - std::array sha224(prv::Provider* &data, u64 offset, size_t size) { + std::array sha224(prv::Provider *&data, u64 offset, size_t size) { std::array result = { 0 }; mbedtls_sha256_context ctx; @@ -274,7 +266,7 @@ namespace hex::crypt { return result; } - std::array sha256(prv::Provider* &data, u64 offset, size_t size) { + std::array sha256(prv::Provider *&data, u64 offset, size_t size) { std::array result = { 0 }; mbedtls_sha256_context ctx; @@ -306,7 +298,7 @@ namespace hex::crypt { return result; } - std::array sha384(prv::Provider* &data, u64 offset, size_t size) { + std::array sha384(prv::Provider *&data, u64 offset, size_t size) { std::array result = { 0 }; mbedtls_sha512_context ctx; @@ -338,7 +330,7 @@ namespace hex::crypt { return result; } - std::array sha512(prv::Provider* &data, u64 offset, size_t size) { + std::array sha512(prv::Provider *&data, u64 offset, size_t size) { std::array result = { 0 }; mbedtls_sha512_context ctx; @@ -377,7 +369,7 @@ namespace hex::crypt { mbedtls_base64_decode(nullptr, 0, &written, reinterpret_cast(input.data()), input.size()); std::vector output(written, 0x00); if (mbedtls_base64_decode(output.data(), output.size(), &written, reinterpret_cast(input.data()), input.size())) - return { }; + return {}; output.resize(written); @@ -391,7 +383,7 @@ namespace hex::crypt { std::vector output(written, 0x00); if (mbedtls_base64_encode(output.data(), output.size(), &written, reinterpret_cast(input.data()), input.size())) - return { }; + return {}; output.resize(written); @@ -407,10 +399,10 @@ namespace hex::crypt { ON_SCOPE_EXIT { mbedtls_mpi_free(&ctx); }; if (mbedtls_mpi_read_string(&ctx, 16, input.c_str())) - return { }; + return {}; if (mbedtls_mpi_write_binary(&ctx, output.data(), output.size())) - return { }; + return {}; return output; } @@ -418,13 +410,13 @@ namespace hex::crypt { std::string encode16(const std::vector &input) { if (input.empty()) - return { }; + return {}; std::string output(input.size() * 2, '\0'); - for(int i = 0; i < input.size(); i++) { - output[2*i+0] = "0123456789ABCDEF"[input[i] / 16]; - output[2*i+1] = "0123456789ABCDEF"[input[i] % 16]; + for (int i = 0; i < input.size(); i++) { + output[2 * i + 0] = "0123456789ABCDEF"[input[i] / 16]; + output[2 * i + 1] = "0123456789ABCDEF"[input[i] % 16]; } return output; @@ -434,7 +426,7 @@ namespace hex::crypt { std::vector output; if (input.empty()) - return { }; + return {}; mbedtls_cipher_context_t ctx; auto cipherInfo = mbedtls_cipher_info_from_type(type); @@ -460,23 +452,47 @@ namespace hex::crypt { std::vector aesDecrypt(AESMode mode, KeyLength keyLength, const std::vector &key, std::array nonce, std::array iv, const std::vector &input) { switch (keyLength) { - case KeyLength::Key128Bits: if (key.size() != 128 / 8) return { }; break; - case KeyLength::Key192Bits: if (key.size() != 192 / 8) return { }; break; - case KeyLength::Key256Bits: if (key.size() != 256 / 8) return { }; break; - default: return { }; + case KeyLength::Key128Bits: + if (key.size() != 128 / 8) return {}; + break; + case KeyLength::Key192Bits: + if (key.size() != 192 / 8) return {}; + break; + case KeyLength::Key256Bits: + if (key.size() != 256 / 8) return {}; + break; + default: + return {}; } mbedtls_cipher_type_t type; switch (mode) { - case AESMode::ECB: type = MBEDTLS_CIPHER_AES_128_ECB; break; - case AESMode::CBC: type = MBEDTLS_CIPHER_AES_128_CBC; break; - case AESMode::CFB128: type = MBEDTLS_CIPHER_AES_128_CFB128; break; - case AESMode::CTR: type = MBEDTLS_CIPHER_AES_128_CTR; break; - case AESMode::GCM: type = MBEDTLS_CIPHER_AES_128_GCM; break; - case AESMode::CCM: type = MBEDTLS_CIPHER_AES_128_CCM; break; - case AESMode::OFB: type = MBEDTLS_CIPHER_AES_128_OFB; break; - case AESMode::XTS: type = MBEDTLS_CIPHER_AES_128_XTS; break; - default: return { }; + case AESMode::ECB: + type = MBEDTLS_CIPHER_AES_128_ECB; + break; + case AESMode::CBC: + type = MBEDTLS_CIPHER_AES_128_CBC; + break; + case AESMode::CFB128: + type = MBEDTLS_CIPHER_AES_128_CFB128; + break; + case AESMode::CTR: + type = MBEDTLS_CIPHER_AES_128_CTR; + break; + case AESMode::GCM: + type = MBEDTLS_CIPHER_AES_128_GCM; + break; + case AESMode::CCM: + type = MBEDTLS_CIPHER_AES_128_CCM; + break; + case AESMode::OFB: + type = MBEDTLS_CIPHER_AES_128_OFB; + break; + case AESMode::XTS: + type = MBEDTLS_CIPHER_AES_128_XTS; + break; + default: + return {}; } type = mbedtls_cipher_type_t(type + u8(keyLength)); diff --git a/lib/libimhex/source/helpers/encoding_file.cpp b/lib/libimhex/source/helpers/encoding_file.cpp index 8eb4453db..e5cffa365 100644 --- a/lib/libimhex/source/helpers/encoding_file.cpp +++ b/lib/libimhex/source/helpers/encoding_file.cpp @@ -10,8 +10,11 @@ namespace hex { std::ifstream encodingFile(path.c_str()); switch (type) { - case Type::Thingy: parseThingyFile(encodingFile); break; - default: return; + case Type::Thingy: + parseThingyFile(encodingFile); + break; + default: + return; } this->m_valid = true; @@ -55,7 +58,7 @@ namespace hex { if (fromBytes.empty()) continue; if (!this->m_mapping.contains(fromBytes.size())) - this->m_mapping.insert({ fromBytes.size(), { } }); + this->m_mapping.insert({ fromBytes.size(), {} }); this->m_mapping[fromBytes.size()].insert({ fromBytes, to }); this->m_longestSequence = std::max(this->m_longestSequence, fromBytes.size()); diff --git a/lib/libimhex/source/helpers/file.cpp b/lib/libimhex/source/helpers/file.cpp index 35767c6e0..d6311c098 100644 --- a/lib/libimhex/source/helpers/file.cpp +++ b/lib/libimhex/source/helpers/file.cpp @@ -26,7 +26,7 @@ namespace hex { this->close(); } - File& File::operator=(File &&other) noexcept { + File &File::operator=(File &&other) noexcept { this->m_file = other.m_file; other.m_file = nullptr; @@ -54,10 +54,10 @@ namespace hex { } std::vector File::readBytes(size_t numBytes) { - if (!isValid()) return { }; + if (!isValid()) return {}; std::vector bytes(numBytes ?: getSize()); - auto bytesRead = fread(bytes.data(), 1, bytes.size(), this->m_file); + auto bytesRead = fread(bytes.data(), 1, bytes.size(), this->m_file); bytes.resize(bytesRead); @@ -65,13 +65,13 @@ namespace hex { } std::string File::readString(size_t numBytes) { - if (!isValid()) return { }; + if (!isValid()) return {}; - if (getSize() == 0) return { }; + if (getSize() == 0) return {}; auto bytes = readBytes(numBytes); - return { reinterpret_cast(bytes.data()), bytes.size() }; + return { reinterpret_cast(bytes.data()), bytes.size() }; } void File::write(const u8 *buffer, size_t size) { diff --git a/lib/libimhex/source/helpers/lang.cpp b/lib/libimhex/source/helpers/lang.cpp index 9ddc557f5..1a44c07de 100644 --- a/lib/libimhex/source/helpers/lang.cpp +++ b/lib/libimhex/source/helpers/lang.cpp @@ -11,7 +11,7 @@ namespace hex { this->m_entries.insert(pair); } - const std::map& LanguageDefinition::getEntries() const { + const std::map &LanguageDefinition::getEntries() const { return this->m_entries; } @@ -27,7 +27,7 @@ namespace hex { return get(); } - LangEntry::operator const char*() const { + LangEntry::operator const char *() const { return get().c_str(); } @@ -59,7 +59,7 @@ namespace hex { return static_cast(left) + right; } - const std::string& LangEntry::get() const { + const std::string &LangEntry::get() const { auto &lang = SharedData::loadedLanguageStrings; if (lang.contains(this->m_unlocalizedString)) return lang[this->m_unlocalizedString]; @@ -85,7 +85,7 @@ namespace hex { } } - const std::map& LangEntry::getSupportedLanguages() { + const std::map &LangEntry::getSupportedLanguages() { return ContentRegistry::Language::getLanguages(); } @@ -93,7 +93,7 @@ namespace hex { LangEntry::s_fallbackLanguage = language; } - const std::string& LangEntry::getFallbackLanguage() { + const std::string &LangEntry::getFallbackLanguage() { return LangEntry::s_fallbackLanguage; } diff --git a/lib/libimhex/source/helpers/loader_script_handler.cpp b/lib/libimhex/source/helpers/loader_script_handler.cpp index 41e524583..39008d070 100644 --- a/lib/libimhex/source/helpers/loader_script_handler.cpp +++ b/lib/libimhex/source/helpers/loader_script_handler.cpp @@ -17,11 +17,11 @@ using namespace std::literals::string_literals; namespace hex { - PyObject* LoaderScript::Py_getFilePath(PyObject *self, PyObject *args) { + PyObject *LoaderScript::Py_getFilePath(PyObject *self, PyObject *args) { return PyUnicode_FromString(LoaderScript::s_filePath.string().c_str()); } - PyObject* LoaderScript::Py_addPatch(PyObject *self, PyObject *args) { + PyObject *LoaderScript::Py_addPatch(PyObject *self, PyObject *args) { u64 address; u8 *patches; Py_ssize_t count; @@ -46,7 +46,7 @@ namespace hex { Py_RETURN_NONE; } - PyObject* LoaderScript::Py_addBookmark(PyObject *self, PyObject *args) { + PyObject *LoaderScript::Py_addBookmark(PyObject *self, PyObject *args) { u64 address; size_t size; @@ -68,7 +68,7 @@ namespace hex { Py_RETURN_NONE; } - static PyObject* createStructureType(std::string keyword, PyObject *args) { + static PyObject *createStructureType(std::string keyword, PyObject *args) { auto type = PyTuple_GetItem(args, 0); if (type == nullptr) { PyErr_BadArgument(); @@ -170,11 +170,11 @@ namespace hex { Py_RETURN_NONE; } - PyObject* LoaderScript::Py_addStruct(PyObject *self, PyObject *args) { + PyObject *LoaderScript::Py_addStruct(PyObject *self, PyObject *args) { return createStructureType("struct", args); } - PyObject* LoaderScript::Py_addUnion(PyObject *self, PyObject *args) { + PyObject *LoaderScript::Py_addUnion(PyObject *self, PyObject *args) { return createStructureType("union", args); } @@ -188,22 +188,21 @@ namespace hex { } } - PyImport_AppendInittab("_imhex", []() -> PyObject* { - + PyImport_AppendInittab("_imhex", []() -> PyObject * { static PyMethodDef ImHexMethods[] = { - { "get_file_path", &LoaderScript::Py_getFilePath, METH_NOARGS, "Returns the path of the file being loaded." }, - { "patch", &LoaderScript::Py_addPatch, METH_VARARGS, "Patches a region of memory" }, - { "add_bookmark", &LoaderScript::Py_addBookmark, METH_VARARGS, "Adds a bookmark" }, - { "add_struct", &LoaderScript::Py_addStruct, METH_VARARGS, "Adds a struct" }, - { "add_union", &LoaderScript::Py_addUnion, METH_VARARGS, "Adds a union" }, - { nullptr, nullptr, 0, nullptr } + {"get_file_path", &LoaderScript::Py_getFilePath, METH_NOARGS, "Returns the path of the file being loaded."}, + { "patch", &LoaderScript::Py_addPatch, METH_VARARGS, "Patches a region of memory" }, + { "add_bookmark", &LoaderScript::Py_addBookmark, METH_VARARGS, "Adds a bookmark" }, + { "add_struct", &LoaderScript::Py_addStruct, METH_VARARGS, "Adds a struct" }, + { "add_union", &LoaderScript::Py_addUnion, METH_VARARGS, "Adds a union" }, + { nullptr, nullptr, 0, nullptr } }; static PyModuleDef ImHexModule = { PyModuleDef_HEAD_INIT, "imhex", nullptr, -1, ImHexMethods, nullptr, nullptr, nullptr, nullptr }; - auto module = PyModule_Create(&ImHexModule); + auto module = PyModule_Create(&ImHexModule); if (module == nullptr) return nullptr; diff --git a/lib/libimhex/source/helpers/logger.cpp b/lib/libimhex/source/helpers/logger.cpp index 18ea0bf25..75b48a530 100644 --- a/lib/libimhex/source/helpers/logger.cpp +++ b/lib/libimhex/source/helpers/logger.cpp @@ -9,7 +9,7 @@ namespace hex::log { static File g_loggerFile; - FILE* getDestination() { + FILE *getDestination() { if (g_loggerFile.isValid()) return g_loggerFile.getHandle(); else diff --git a/lib/libimhex/source/helpers/magic.cpp b/lib/libimhex/source/helpers/magic.cpp index 57fed605d..8f0a23a48 100644 --- a/lib/libimhex/source/helpers/magic.cpp +++ b/lib/libimhex/source/helpers/magic.cpp @@ -32,7 +32,7 @@ namespace hex::magic { } if (error) - return { }; + return {}; else return magicFiles; } @@ -70,7 +70,7 @@ namespace hex::magic { return getDescription(buffer); } - std::string getMIMEType(const std::vector &data){ + std::string getMIMEType(const std::vector &data) { auto magicFiles = getMagicFiles(); if (magicFiles.has_value()) { diff --git a/lib/libimhex/source/helpers/net.cpp b/lib/libimhex/source/helpers/net.cpp index 4c58e8195..301bbf240 100644 --- a/lib/libimhex/source/helpers/net.cpp +++ b/lib/libimhex/source/helpers/net.cpp @@ -33,31 +33,31 @@ namespace hex { curl_easy_cleanup(this->m_ctx); } - static size_t writeToString(void *contents, size_t size, size_t nmemb, void *userdata){ - static_cast(userdata)->append((char*)contents, size * nmemb); + static size_t writeToString(void *contents, size_t size, size_t nmemb, void *userdata) { + static_cast(userdata)->append((char *)contents, size * nmemb); return size * nmemb; } static size_t readFromFile(void *contents, size_t size, size_t nmemb, void *userdata) { - FILE *file = static_cast(userdata); + FILE *file = static_cast(userdata); return fread(contents, size, nmemb, file); } static size_t writeToFile(void *contents, size_t size, size_t nmemb, void *userdata) { - FILE *file = static_cast(userdata); + FILE *file = static_cast(userdata); return fwrite(contents, size, nmemb, file); } static CURLcode sslCtxFunction(CURL *ctx, void *sslctx, void *userdata) { - auto* cfg = static_cast(sslctx); + auto *cfg = static_cast(sslctx); static mbedtls_x509_crt crt; mbedtls_x509_crt_init(&crt); auto cacert = romfs::get("cacert.pem").string(); - mbedtls_x509_crt_parse(&crt, reinterpret_cast(cacert.data()), cacert.size()); + mbedtls_x509_crt_parse(&crt, reinterpret_cast(cacert.data()), cacert.size()); mbedtls_ssl_conf_ca_chain(cfg, &crt, nullptr); @@ -65,7 +65,7 @@ namespace hex { } int progressCallback(void *contents, curl_off_t dlTotal, curl_off_t dlNow, curl_off_t ulTotal, curl_off_t ulNow) { - auto &net = *static_cast(contents); + auto &net = *static_cast(contents); if (dlTotal > 0) net.m_progress = float(dlNow) / dlTotal; @@ -129,7 +129,7 @@ namespace hex { this->m_shouldCancel = false; if (result != CURLE_OK) - return { }; + return {}; else return responseCode; } @@ -137,7 +137,7 @@ namespace hex { std::future> Net::getString(const std::string &url, u32 timeout) { this->m_transmissionActive.lock(); - return std::async(std::launch::async, [=, this]{ + return std::async(std::launch::async, [=, this] { std::string response; ON_SCOPE_EXIT { this->m_transmissionActive.unlock(); }; @@ -154,7 +154,7 @@ namespace hex { std::future> Net::getJson(const std::string &url, u32 timeout) { this->m_transmissionActive.lock(); - return std::async(std::launch::async, [=, this]{ + return std::async(std::launch::async, [=, this] { std::string response; ON_SCOPE_EXIT { this->m_transmissionActive.unlock(); }; @@ -178,26 +178,21 @@ namespace hex { File file(filePath.string(), File::Mode::Read); if (!file.isValid()) - return Response { 400, { } }; + return Response { 400, {} }; 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, file.getSize(), - [](char *buffer, size_t size, size_t nitems, void *arg) -> size_t { + 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); - }, - [](void *arg, curl_off_t offset, int origin) -> int { + return fread(buffer, size, nitems, file); }, [](void *arg, curl_off_t offset, int origin) -> int { auto file = static_cast(arg); fseek(file, offset, origin); - return CURL_SEEKFUNC_OK; - }, - [](void *arg) { + return CURL_SEEKFUNC_OK; }, [](void *arg) { auto file = static_cast(arg); - fclose(file); - }, file.getHandle()); + fclose(file); }, file.getHandle()); curl_mime_filename(part, fileName.c_str()); curl_mime_name(part, "file"); @@ -214,7 +209,7 @@ namespace hex { std::future> Net::downloadFile(const std::string &url, const fs::path &filePath, u32 timeout) { this->m_transmissionActive.lock(); - return std::async(std::launch::async, [=, this]{ + return std::async(std::launch::async, [=, this] { std::string response; ON_SCOPE_EXIT { this->m_transmissionActive.unlock(); }; @@ -243,7 +238,7 @@ namespace hex { return output; } - return { }; + return {}; } } \ No newline at end of file diff --git a/lib/libimhex/source/helpers/patches.cpp b/lib/libimhex/source/helpers/patches.cpp index 8c21c1ec6..24db249b5 100644 --- a/lib/libimhex/source/helpers/patches.cpp +++ b/lib/libimhex/source/helpers/patches.cpp @@ -17,7 +17,7 @@ namespace hex { buffer.resize(buffer.size() + sizeof(T)); std::memcpy((&buffer.back() - sizeof(T)) + 1, &bytes, sizeof(T)); } - + std::vector generateIPSPatch(const Patches &patches) { std::vector result; @@ -43,19 +43,21 @@ namespace hex { bytes.push_back(values[i]); if (bytes.size() > 0xFFFF || startAddress > 0xFF'FFFF) - return { }; + return {}; u32 address = startAddress.value(); - auto addressBytes = reinterpret_cast(&address); + auto addressBytes = reinterpret_cast(&address); - result.push_back(addressBytes[2]); result.push_back(addressBytes[1]); result.push_back(addressBytes[0]); + result.push_back(addressBytes[2]); + result.push_back(addressBytes[1]); + result.push_back(addressBytes[0]); pushBytesBack(result, changeEndianess(bytes.size(), std::endian::big)); for (auto byte : bytes) result.push_back(byte); bytes.clear(); - startAddress = { }; + startAddress = {}; } } @@ -89,19 +91,22 @@ namespace hex { bytes.push_back(values[i]); if (bytes.size() > 0xFFFF || startAddress > 0xFFFF'FFFF) - return { }; + return {}; u32 address = startAddress.value(); - auto addressBytes = reinterpret_cast(&address); + auto addressBytes = reinterpret_cast(&address); - result.push_back(addressBytes[3]); result.push_back(addressBytes[2]); result.push_back(addressBytes[1]); result.push_back(addressBytes[0]); + result.push_back(addressBytes[3]); + result.push_back(addressBytes[2]); + result.push_back(addressBytes[1]); + result.push_back(addressBytes[0]); pushBytesBack(result, changeEndianess(bytes.size(), std::endian::big)); for (auto byte : bytes) result.push_back(byte); bytes.clear(); - startAddress = { }; + startAddress = {}; } } @@ -112,10 +117,10 @@ namespace hex { Patches loadIPSPatch(const std::vector &ipsPatch) { if (ipsPatch.size() < (5 + 3)) - return { }; + return {}; if (std::memcmp(ipsPatch.data(), "PATCH", 5) != 0) - return { }; + return {}; Patches result; bool foundEOF = false; @@ -130,7 +135,7 @@ namespace hex { // Handle normal record if (size > 0x0000) { if (ipsOffset + size > ipsPatch.size() - 3) - return { }; + return {}; for (u16 i = 0; i < size; i++) result[offset + i] = ipsPatch[ipsOffset + i]; @@ -139,7 +144,7 @@ namespace hex { // Handle RLE record else { if (ipsOffset + 3 > ipsPatch.size() - 3) - return { }; + return {}; u16 rleSize = ipsPatch[ipsOffset + 0] | (ipsPatch[ipsOffset + 1] << 8); @@ -158,15 +163,15 @@ namespace hex { if (foundEOF) return result; else - return { }; + return {}; } Patches loadIPS32Patch(const std::vector &ipsPatch) { if (ipsPatch.size() < (5 + 4)) - return { }; + return {}; if (std::memcmp(ipsPatch.data(), "IPS32", 5) != 0) - return { }; + return {}; Patches result; bool foundEEOF = false; @@ -181,7 +186,7 @@ namespace hex { // Handle normal record if (size > 0x0000) { if (ipsOffset + size > ipsPatch.size() - 3) - return { }; + return {}; for (u16 i = 0; i < size; i++) result[offset + i] = ipsPatch[ipsOffset + i]; @@ -190,7 +195,7 @@ namespace hex { // Handle RLE record else { if (ipsOffset + 3 > ipsPatch.size() - 3) - return { }; + return {}; u16 rleSize = ipsPatch[ipsOffset + 0] | (ipsPatch[ipsOffset + 1] << 8); @@ -209,7 +214,7 @@ namespace hex { if (foundEEOF) return result; else - return { }; + return {}; } } \ No newline at end of file diff --git a/lib/libimhex/source/helpers/paths.cpp b/lib/libimhex/source/helpers/paths.cpp index 2346446ef..288c12a36 100644 --- a/lib/libimhex/source/helpers/paths.cpp +++ b/lib/libimhex/source/helpers/paths.cpp @@ -19,210 +19,203 @@ namespace hex { std::string getExecutablePath() { - #if defined(OS_WINDOWS) - std::string exePath(MAX_PATH, '\0'); - GetModuleFileName(nullptr, exePath.data(), exePath.length()); +#if defined(OS_WINDOWS) + std::string exePath(MAX_PATH, '\0'); + GetModuleFileName(nullptr, exePath.data(), exePath.length()); - return exePath; - #elif defined(OS_LINUX) - std::string exePath(PATH_MAX, '\0'); - readlink("/proc/self/exe", exePath.data(), PATH_MAX); + return exePath; +#elif defined(OS_LINUX) + std::string exePath(PATH_MAX, '\0'); + readlink("/proc/self/exe", exePath.data(), PATH_MAX); - return exePath; - #elif defined(OS_MACOS) - return getMacExecutableDirectoryPath(); - #else - return ""; - #endif + return exePath; +#elif defined(OS_MACOS) + return getMacExecutableDirectoryPath(); +#else + return ""; +#endif } std::vector getPath(ImHexPath path, bool listNonExisting) { std::vector result; - #if defined(OS_WINDOWS) - const auto exePath = getExecutablePath(); - const auto parentDir = fs::path(exePath).parent_path(); +#if defined(OS_WINDOWS) + const auto exePath = getExecutablePath(); + const auto parentDir = fs::path(exePath).parent_path(); - fs::path appDataDir; - { - LPWSTR wAppDataPath = nullptr; - if (!SUCCEEDED(SHGetKnownFolderPath(FOLDERID_LocalAppData, KF_FLAG_CREATE, nullptr, &wAppDataPath))) - throw std::runtime_error("Failed to get APPDATA folder path"); + fs::path appDataDir; + { + LPWSTR wAppDataPath = nullptr; + if (!SUCCEEDED(SHGetKnownFolderPath(FOLDERID_LocalAppData, KF_FLAG_CREATE, nullptr, &wAppDataPath))) + throw std::runtime_error("Failed to get APPDATA folder path"); - appDataDir = wAppDataPath; - CoTaskMemFree(wAppDataPath); - } + appDataDir = wAppDataPath; + CoTaskMemFree(wAppDataPath); + } - std::vector paths = { parentDir, appDataDir / "imhex" }; + std::vector paths = { parentDir, appDataDir / "imhex" }; - switch (path) { - case ImHexPath::Patterns: - std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path){ - return (path / "patterns").string(); - }); - break; - case ImHexPath::PatternsInclude: - std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path){ - return (path / "includes").string(); - }); - break; - case ImHexPath::Magic: - std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path){ - return (path / "magic").string(); - }); - break; - case ImHexPath::Python: - std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path){ - return (path / "python").string(); - }); - break; - case ImHexPath::Plugins: - std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path){ - return (path / "plugins").string(); - }); - break; - case ImHexPath::Yara: - std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path){ - return (path / "yara").string(); - }); - break; - case ImHexPath::Config: - return { (appDataDir / "imhex" / "config").string() }; - case ImHexPath::Resources: - std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path){ - return (path / "resources").string(); - }); - break; - case ImHexPath::Constants: - std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path){ - return (path / "constants").string(); - }); - break; - case ImHexPath::Encodings: - std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path){ - return (path / "encodings").string(); - }); - break; - case ImHexPath::Logs: - std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path){ - return (path / "logs").string(); - }); - break; - default: __builtin_unreachable(); - } - #elif defined(OS_MACOS) - // Get path to special directories - const auto exePath = getExecutablePath(); - const fs::path applicationSupportDir(getMacApplicationSupportDirectoryPath()); + switch (path) { + case ImHexPath::Patterns: + std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path) { + return (path / "patterns").string(); + }); + break; + case ImHexPath::PatternsInclude: + std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path) { + return (path / "includes").string(); + }); + break; + case ImHexPath::Magic: + std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path) { + return (path / "magic").string(); + }); + break; + case ImHexPath::Python: + std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path) { + return (path / "python").string(); + }); + break; + case ImHexPath::Plugins: + std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path) { + return (path / "plugins").string(); + }); + break; + case ImHexPath::Yara: + std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path) { + return (path / "yara").string(); + }); + break; + case ImHexPath::Config: + return { (appDataDir / "imhex" / "config").string() }; + case ImHexPath::Resources: + std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path) { + return (path / "resources").string(); + }); + break; + case ImHexPath::Constants: + std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path) { + return (path / "constants").string(); + }); + break; + case ImHexPath::Encodings: + std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path) { + return (path / "encodings").string(); + }); + break; + case ImHexPath::Logs: + std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path) { + return (path / "logs").string(); + }); + break; + default: + __builtin_unreachable(); + } +#elif defined(OS_MACOS) + // Get path to special directories + const auto exePath = getExecutablePath(); + const fs::path applicationSupportDir(getMacApplicationSupportDirectoryPath()); - std::vector paths = { exePath, applicationSupportDir }; + std::vector paths = { exePath, applicationSupportDir }; - switch (path) { - case ImHexPath::Patterns: - result.push_back((applicationSupportDir / "patterns").string()); - break; - case ImHexPath::PatternsInclude: - result.push_back((applicationSupportDir / "includes").string()); - break; - case ImHexPath::Magic: - result.push_back((applicationSupportDir / "magic").string()); - break; - case ImHexPath::Python: - result.push_back((applicationSupportDir / "python").string()); - break; - case ImHexPath::Plugins: - std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path){ - return (path / "plugins").string(); - }); - break; - case ImHexPath::Yara: - result.push_back((applicationSupportDir / "yara").string()); - break; - case ImHexPath::Config: - result.push_back((applicationSupportDir / "config").string()); - break; - case ImHexPath::Resources: - result.push_back((applicationSupportDir / "resources").string()); - break; - case ImHexPath::Constants: - result.push_back((applicationSupportDir / "constants").string()); - break; - case ImHexPath::Encodings: - result.push_back((applicationSupportDir / "encodings").string()); - break; - case ImHexPath::Logs: - result.push_back((applicationSupportDir / "logs").string()); - break; - default: __builtin_unreachable(); - } - #else - std::vector configDirs = xdg::ConfigDirs(); - std::vector dataDirs = xdg::DataDirs(); + switch (path) { + case ImHexPath::Patterns: + result.push_back((applicationSupportDir / "patterns").string()); + break; + case ImHexPath::PatternsInclude: + result.push_back((applicationSupportDir / "includes").string()); + break; + case ImHexPath::Magic: + result.push_back((applicationSupportDir / "magic").string()); + break; + case ImHexPath::Python: + result.push_back((applicationSupportDir / "python").string()); + break; + case ImHexPath::Plugins: + std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path) { + return (path / "plugins").string(); + }); + break; + case ImHexPath::Yara: + result.push_back((applicationSupportDir / "yara").string()); + break; + case ImHexPath::Config: + result.push_back((applicationSupportDir / "config").string()); + break; + case ImHexPath::Resources: + result.push_back((applicationSupportDir / "resources").string()); + break; + case ImHexPath::Constants: + result.push_back((applicationSupportDir / "constants").string()); + break; + case ImHexPath::Encodings: + result.push_back((applicationSupportDir / "encodings").string()); + break; + case ImHexPath::Logs: + result.push_back((applicationSupportDir / "logs").string()); + break; + default: + __builtin_unreachable(); + } +#else + std::vector configDirs = xdg::ConfigDirs(); + std::vector dataDirs = xdg::DataDirs(); - configDirs.insert(configDirs.begin(), xdg::ConfigHomeDir()); - dataDirs.insert(dataDirs.begin(), xdg::DataHomeDir()); + configDirs.insert(configDirs.begin(), xdg::ConfigHomeDir()); + dataDirs.insert(dataDirs.begin(), xdg::DataHomeDir()); - for (auto &dir : dataDirs) - dir = dir / "imhex"; + for (auto &dir : dataDirs) + dir = dir / "imhex"; - const auto exePath = getExecutablePath(); + const auto exePath = getExecutablePath(); - if (!exePath.empty()) - dataDirs.emplace(dataDirs.begin(), fs::path(exePath.data()).parent_path()); + if (!exePath.empty()) + dataDirs.emplace(dataDirs.begin(), fs::path(exePath.data()).parent_path()); - switch (path) { - case ImHexPath::Patterns: - std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result), - [](auto p) { return (p / "patterns").string(); }); - break; - case ImHexPath::PatternsInclude: - std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result), - [](auto p) { return (p / "includes").string(); }); - break; - case ImHexPath::Magic: - std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result), - [](auto p) { return (p / "magic").string(); }); - break; - case ImHexPath::Python: - std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result), - [](auto p) { return (p).string(); }); - break; - case ImHexPath::Plugins: - std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result), - [](auto p) { return (p / "plugins").string(); }); - break; - case ImHexPath::Yara: - std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result), - [](auto p) { return (p / "yara").string(); }); - break; - case ImHexPath::Config: - std::transform(configDirs.begin(), configDirs.end(), std::back_inserter(result), - [](auto p) { return (p / "imhex").string(); }); - break; - case ImHexPath::Resources: - std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result), - [](auto p) { return (p / "resources").string(); }); - break; - case ImHexPath::Constants: - std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result), - [](auto p) { return (p / "constants").string(); }); - break; - case ImHexPath::Encodings: - std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result), - [](auto p) { return (p / "encodings").string(); }); - break; - case ImHexPath::Logs: - std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result), - [](auto p) { return (p / "logs").string(); }); - break; - default: __builtin_unreachable(); - } - #endif + switch (path) { + case ImHexPath::Patterns: + std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result), [](auto p) { return (p / "patterns").string(); }); + break; + case ImHexPath::PatternsInclude: + std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result), [](auto p) { return (p / "includes").string(); }); + break; + case ImHexPath::Magic: + std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result), [](auto p) { return (p / "magic").string(); }); + break; + case ImHexPath::Python: + std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result), [](auto p) { return (p).string(); }); + break; + case ImHexPath::Plugins: + std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result), [](auto p) { return (p / "plugins").string(); }); + break; + case ImHexPath::Yara: + std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result), [](auto p) { return (p / "yara").string(); }); + break; + case ImHexPath::Config: + std::transform(configDirs.begin(), configDirs.end(), std::back_inserter(result), [](auto p) { return (p / "imhex").string(); }); + break; + case ImHexPath::Resources: + std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result), [](auto p) { return (p / "resources").string(); }); + break; + case ImHexPath::Constants: + std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result), [](auto p) { return (p / "constants").string(); }); + break; + case ImHexPath::Encodings: + std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result), [](auto p) { return (p / "encodings").string(); }); + break; + case ImHexPath::Logs: + std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result), [](auto p) { return (p / "logs").string(); }); + break; + default: + __builtin_unreachable(); + } +#endif if (!listNonExisting) { - result.erase(std::remove_if(result.begin(), result.end(), [](const auto& path){ - return !fs::is_directory(path); - }), result.end()); + result.erase(std::remove_if(result.begin(), result.end(), [](const auto &path) { + return !fs::is_directory(path); + }), + result.end()); } return result; diff --git a/lib/libimhex/source/helpers/project_file_handler.cpp b/lib/libimhex/source/helpers/project_file_handler.cpp index ac0ee135c..ac21dc47c 100644 --- a/lib/libimhex/source/helpers/project_file_handler.cpp +++ b/lib/libimhex/source/helpers/project_file_handler.cpp @@ -18,11 +18,18 @@ namespace hex { std::list ProjectFile::s_bookmarks; std::string ProjectFile::s_dataProcessorContent; - void to_json(json& j, const ImHexApi::Bookmarks::Entry& b) { - j = json{ { "address", b.region.address }, { "size", b.region.size }, { "name", b.name.data() }, { "comment", b.comment.data() }, { "locked", b.locked }, { "color", b.color } }; + void to_json(json &j, const ImHexApi::Bookmarks::Entry &b) { + j = json { + {"address", b.region.address}, + { "size", b.region.size }, + { "name", b.name.data() }, + { "comment", b.comment.data()}, + { "locked", b.locked }, + { "color", b.color } + }; } - void from_json(const json& j, ImHexApi::Bookmarks::Entry& b) { + void from_json(const json &j, ImHexApi::Bookmarks::Entry &b) { std::string name, comment; if (j.contains("address")) j.at("address").get_to(b.region.address); @@ -48,9 +55,9 @@ namespace hex { std::ifstream projectFile(filePath.c_str()); projectFile >> projectFileData; - ProjectFile::s_filePath = fs::path(projectFileData["filePath"].get()); - ProjectFile::s_pattern = projectFileData["pattern"]; - ProjectFile::s_patches = projectFileData["patches"].get(); + ProjectFile::s_filePath = fs::path(projectFileData["filePath"].get()); + ProjectFile::s_pattern = projectFileData["pattern"]; + ProjectFile::s_patches = projectFileData["patches"].get(); ProjectFile::s_dataProcessorContent = projectFileData["dataProcessor"]; ProjectFile::s_bookmarks.clear(); @@ -82,10 +89,10 @@ namespace hex { filePath = ProjectFile::s_currProjectFilePath; try { - projectFileData["filePath"] = ProjectFile::s_filePath; - projectFileData["pattern"] = ProjectFile::s_pattern; - projectFileData["patches"] = ProjectFile::s_patches; - projectFileData["dataProcessor"] = ProjectFile::s_dataProcessorContent; + projectFileData["filePath"] = ProjectFile::s_filePath; + projectFileData["pattern"] = ProjectFile::s_pattern; + projectFileData["patches"] = ProjectFile::s_patches; + projectFileData["dataProcessor"] = ProjectFile::s_dataProcessorContent; for (auto &bookmark : ProjectFile::s_bookmarks) { to_json(projectFileData["bookmarks"].emplace_back(), bookmark); diff --git a/lib/libimhex/source/helpers/shared_data.cpp b/lib/libimhex/source/helpers/shared_data.cpp index 5038c0e0d..fe12de7fd 100644 --- a/lib/libimhex/source/helpers/shared_data.cpp +++ b/lib/libimhex/source/helpers/shared_data.cpp @@ -6,20 +6,20 @@ namespace hex { std::vector> SharedData::deferredCalls; - std::vector SharedData::providers; + std::vector SharedData::providers; u32 SharedData::currentProvider; std::map> SharedData::settingsEntries; nlohmann::json SharedData::settingsJson; std::vector SharedData::commandPaletteCommands; std::map SharedData::patternLanguageFunctions; - std::map SharedData::views; + std::map SharedData::views; std::vector SharedData::toolsEntries; std::vector SharedData::dataInspectorEntries; u32 SharedData::patternPaletteOffset; std::string SharedData::popupMessage; std::list SharedData::bookmarkEntries; - std::vector SharedData::patternData; + std::vector SharedData::patternData; u32 SharedData::selectableFileIndex; std::vector SharedData::selectableFiles; @@ -37,14 +37,14 @@ namespace hex { std::vector SharedData::welcomeScreenEntries; std::vector SharedData::footerItems; - std::vector SharedData::sidebarItems; + std::vector SharedData::sidebarItems; std::vector SharedData::toolbarItems; std::vector SharedData::layouts; std::map> SharedData::globalShortcuts; std::mutex SharedData::tasksMutex; - std::list SharedData::runningTasks; + std::list SharedData::runningTasks; std::vector SharedData::providerNames; diff --git a/lib/libimhex/source/helpers/socket.cpp b/lib/libimhex/source/helpers/socket.cpp index d80bec83a..de2aedaf1 100644 --- a/lib/libimhex/source/helpers/socket.cpp +++ b/lib/libimhex/source/helpers/socket.cpp @@ -6,16 +6,16 @@ namespace hex { Socket::Socket(const std::string &address, u16 port) { - #if defined(OS_WINDOWS) - FIRST_TIME { - WSAData wsa; - WSAStartup(MAKEWORD(2, 2), &wsa); - }; +#if defined(OS_WINDOWS) + FIRST_TIME { + WSAData wsa; + WSAStartup(MAKEWORD(2, 2), &wsa); + }; - FINAL_CLEANUP { - WSACleanup(); - }; - #endif + FINAL_CLEANUP { + WSACleanup(); + }; +#endif this->connect(address, port); } @@ -34,7 +34,7 @@ namespace hex { void Socket::writeBytes(const std::vector &bytes) const { if (!this->isConnected()) return; - ::send(this->m_socket, reinterpret_cast(bytes.data()), bytes.size(), 0); + ::send(this->m_socket, reinterpret_cast(bytes.data()), bytes.size(), 0); } void Socket::writeString(const std::string &string) const { @@ -50,7 +50,7 @@ namespace hex { auto receivedSize = ::recv(this->m_socket, reinterpret_cast(data.data()), size, 0); if (receivedSize < 0) - return { }; + return {}; data.resize(receivedSize); @@ -80,22 +80,22 @@ namespace hex { client.sin_family = AF_INET; client.sin_port = htons(port); - #if defined(OS_WINDOWS) - client.sin_addr.S_un.S_addr = ::inet_addr(address.c_str()); - #else - client.sin_addr.s_addr = ::inet_addr(address.c_str()); - #endif +#if defined(OS_WINDOWS) + client.sin_addr.S_un.S_addr = ::inet_addr(address.c_str()); +#else + client.sin_addr.s_addr = ::inet_addr(address.c_str()); +#endif - this->m_connected = ::connect(this->m_socket, reinterpret_cast(&client), sizeof(client)) == 0; + this->m_connected = ::connect(this->m_socket, reinterpret_cast(&client), sizeof(client)) == 0; } void Socket::disconnect() { if (this->m_socket != SOCKET_NONE) { - #if defined(OS_WINDOWS) - closesocket(this->m_socket); - #else - close(this->m_socket); - #endif +#if defined(OS_WINDOWS) + closesocket(this->m_socket); +#else + close(this->m_socket); +#endif } this->m_connected = false; diff --git a/lib/libimhex/source/helpers/utils.cpp b/lib/libimhex/source/helpers/utils.cpp index f87edaaa8..2a81fe041 100644 --- a/lib/libimhex/source/helpers/utils.cpp +++ b/lib/libimhex/source/helpers/utils.cpp @@ -8,11 +8,11 @@ #include #include -#if defined (OS_WINDOWS) +#if defined(OS_WINDOWS) #include -#elif defined (OS_LINUX) +#elif defined(OS_LINUX) #include -#elif defined (OS_MACOS) +#elif defined(OS_MACOS) #include #include #endif @@ -78,14 +78,29 @@ namespace hex { std::string result = hex::format("{0:.2f}", value); switch (unitIndex) { - case 0: result += " Bytes"; break; - case 1: result += " kB"; break; - case 2: result += " MB"; break; - case 3: result += " GB"; break; - case 4: result += " TB"; break; - case 5: result += " PB"; break; - case 6: result += " EB"; break; - default: result = "A lot!"; + case 0: + result += " Bytes"; + break; + case 1: + result += " kB"; + break; + case 2: + result += " MB"; + break; + case 3: + result += " GB"; + break; + case 4: + result += " TB"; + break; + case 5: + result += " PB"; + break; + case 6: + result += " EB"; + break; + default: + result = "A lot!"; } return result; @@ -93,42 +108,78 @@ namespace hex { std::string makePrintable(u8 c) { switch (c) { - case 0: return "NUL"; - case 1: return "SOH"; - case 2: return "STX"; - case 3: return "ETX"; - case 4: return "EOT"; - case 5: return "ENQ"; - case 6: return "ACK"; - case 7: return "BEL"; - case 8: return "BS"; - case 9: return "TAB"; - case 10: return "LF"; - case 11: return "VT"; - case 12: return "FF"; - case 13: return "CR"; - case 14: return "SO"; - case 15: return "SI"; - case 16: return "DLE"; - case 17: return "DC1"; - case 18: return "DC2"; - case 19: return "DC3"; - case 20: return "DC4"; - case 21: return "NAK"; - case 22: return "SYN"; - case 23: return "ETB"; - case 24: return "CAN"; - case 25: return "EM"; - case 26: return "SUB"; - case 27: return "ESC"; - case 28: return "FS"; - case 29: return "GS"; - case 30: return "RS"; - case 31: return "US"; - case 32: return "Space"; - case 127: return "DEL"; - case 128 ... 255: return " "; - default: return std::string() + static_cast(c); + case 0: + return "NUL"; + case 1: + return "SOH"; + case 2: + return "STX"; + case 3: + return "ETX"; + case 4: + return "EOT"; + case 5: + return "ENQ"; + case 6: + return "ACK"; + case 7: + return "BEL"; + case 8: + return "BS"; + case 9: + return "TAB"; + case 10: + return "LF"; + case 11: + return "VT"; + case 12: + return "FF"; + case 13: + return "CR"; + case 14: + return "SO"; + case 15: + return "SI"; + case 16: + return "DLE"; + case 17: + return "DC1"; + case 18: + return "DC2"; + case 19: + return "DC3"; + case 20: + return "DC4"; + case 21: + return "NAK"; + case 22: + return "SYN"; + case 23: + return "ETB"; + case 24: + return "CAN"; + case 25: + return "EM"; + case 26: + return "SUB"; + case 27: + return "ESC"; + case 28: + return "FS"; + case 29: + return "GS"; + case 30: + return "RS"; + case 31: + return "US"; + case 32: + return "Space"; + case 127: + return "DEL"; + case 128 ... 255: + return " "; + default: + return std::string() + static_cast(c); } } @@ -177,16 +228,15 @@ namespace hex { void runCommand(const std::string &command) { - #if defined(OS_WINDOWS) +#if defined(OS_WINDOWS) system(hex::format("start {0}", command).c_str()); - #elif defined(OS_MACOS) +#elif defined(OS_MACOS) system(hex::format("open {0}", command).c_str()); - #elif defined(OS_LINUX) +#elif defined(OS_LINUX) system(hex::format("xdg-open {0}", command).c_str()); - #else - #warning "Unknown OS, can't open webpages" - #endif - +#else + #warning "Unknown OS, can't open webpages" +#endif } void openWebpage(std::string url) { @@ -194,18 +244,17 @@ namespace hex { if (url.find("://") == std::string::npos) url = "https://" + url; - #if defined(OS_WINDOWS) - ShellExecute(nullptr, "open", url.c_str(), nullptr, nullptr, SW_SHOWNORMAL); - #elif defined(OS_MACOS) - CFURLRef urlRef = CFURLCreateWithBytes(nullptr, reinterpret_cast(url.data()), url.length(), kCFStringEncodingASCII, nullptr); - LSOpenCFURLRef(urlRef, nullptr); - CFRelease(urlRef); - #elif defined(OS_LINUX) - system(hex::format("xdg-open {0}", url).c_str()); - #else - #warning "Unknown OS, can't open webpages" - #endif - +#if defined(OS_WINDOWS) + ShellExecute(nullptr, "open", url.c_str(), nullptr, nullptr, SW_SHOWNORMAL); +#elif defined(OS_MACOS) + CFURLRef urlRef = CFURLCreateWithBytes(nullptr, reinterpret_cast(url.data()), url.length(), kCFStringEncodingASCII, nullptr); + LSOpenCFURLRef(urlRef, nullptr); + CFRelease(urlRef); +#elif defined(OS_LINUX) + system(hex::format("xdg-open {0}", url).c_str()); +#else + #warning "Unknown OS, can't open webpages" +#endif } void openFileBrowser(const std::string &title, DialogMode mode, const std::vector &validExtensions, const std::function &callback, const std::string &defaultPath) { @@ -214,16 +263,17 @@ namespace hex { nfdchar_t *outPath; nfdresult_t result; switch (mode) { - case DialogMode::Open: - result = NFD::OpenDialog(outPath, validExtensions.data(), validExtensions.size(), defaultPath.c_str()); - break; - case DialogMode::Save: - result = NFD::SaveDialog(outPath, validExtensions.data(), validExtensions.size(), defaultPath.c_str()); - break; - case DialogMode::Folder: - result = NFD::PickFolder(outPath, defaultPath.c_str()); - break; - default: __builtin_unreachable(); + case DialogMode::Open: + result = NFD::OpenDialog(outPath, validExtensions.data(), validExtensions.size(), defaultPath.c_str()); + break; + case DialogMode::Save: + result = NFD::SaveDialog(outPath, validExtensions.data(), validExtensions.size(), defaultPath.c_str()); + break; + case DialogMode::Folder: + result = NFD::PickFolder(outPath, defaultPath.c_str()); + break; + default: + __builtin_unreachable(); } if (result == NFD_OKAY) { @@ -265,30 +315,30 @@ namespace hex { result = (sign << 31) | ((exponent + (0x7F - 15)) << 23) | (mantissa << 13); } - return reinterpret_cast(result); + return reinterpret_cast(result); } bool isProcessElevated() { - #if defined (OS_WINDOWS) - bool elevated = false; - HANDLE token = INVALID_HANDLE_VALUE; +#if defined(OS_WINDOWS) + bool elevated = false; + HANDLE token = INVALID_HANDLE_VALUE; - if (::OpenProcessToken(::GetCurrentProcess(), TOKEN_QUERY, &token)) { - TOKEN_ELEVATION elevation; - DWORD elevationSize = sizeof(TOKEN_ELEVATION); + if (::OpenProcessToken(::GetCurrentProcess(), TOKEN_QUERY, &token)) { + TOKEN_ELEVATION elevation; + DWORD elevationSize = sizeof(TOKEN_ELEVATION); - if (::GetTokenInformation(token, TokenElevation, &elevation, sizeof(elevation), &elevationSize)) - elevated = elevation.TokenIsElevated; - } + if (::GetTokenInformation(token, TokenElevation, &elevation, sizeof(elevation), &elevationSize)) + elevated = elevation.TokenIsElevated; + } - if (token != INVALID_HANDLE_VALUE) - ::CloseHandle(token); + if (token != INVALID_HANDLE_VALUE) + ::CloseHandle(token); - return elevated; + return elevated; - #elif defined(OS_LINUX) || defined (OS_MACOS) - return getuid() < 0 || getuid() != geteuid(); - #endif +#elif defined(OS_LINUX) || defined(OS_MACOS) + return getuid() < 0 || getuid() != geteuid(); +#endif } } \ No newline at end of file diff --git a/lib/libimhex/source/pattern_language/evaluator.cpp b/lib/libimhex/source/pattern_language/evaluator.cpp index 54b54d567..78b4e098d 100644 --- a/lib/libimhex/source/pattern_language/evaluator.cpp +++ b/lib/libimhex/source/pattern_language/evaluator.cpp @@ -30,8 +30,8 @@ namespace hex::pl { pattern = new PatternDataBoolean(0, this); else if (std::get_if(&value.value()) != nullptr) pattern = new PatternDataCharacter(0, this); - else if (std::get_if(&value.value()) != nullptr) - pattern = std::get(value.value())->clone(); + else if (std::get_if(&value.value()) != nullptr) + pattern = std::get(value.value())->clone(); else if (std::get_if(&value.value()) != nullptr) pattern = new PatternDataString(0, 1, this); else @@ -49,7 +49,7 @@ namespace hex::pl { this->m_outVariables[name] = pattern->getOffset(); } - void Evaluator::setVariable(const std::string &name, const Token::Literal& value) { + void Evaluator::setVariable(const std::string &name, const Token::Literal &value) { PatternData *pattern = nullptr; { @@ -79,49 +79,48 @@ namespace hex::pl { LogConsole::abortEvaluation(hex::format("no variable with name '{}' found", name)); Token::Literal castedLiteral = std::visit(overloaded { - [&](double &value) -> Token::Literal { - if (dynamic_cast(pattern)) - return u128(value) & bitmask(pattern->getSize() * 8); - else if (dynamic_cast(pattern)) - return i128(value) & bitmask(pattern->getSize() * 8); - else if (dynamic_cast(pattern)) - return pattern->getSize() == sizeof(float) ? double(float(value)) : value; - else - LogConsole::abortEvaluation(hex::format("cannot cast type 'double' to type '{}'", pattern->getTypeName())); - }, - [&](const std::string &value) -> Token::Literal { - if (dynamic_cast(pattern)) - return value; - else - LogConsole::abortEvaluation(hex::format("cannot cast type 'string' to type '{}'", pattern->getTypeName())); - }, - [&](PatternData * const &value) -> Token::Literal { - if (value->getTypeName() == pattern->getTypeName()) - return value; - else - LogConsole::abortEvaluation(hex::format("cannot cast type '{}' to type '{}'", value->getTypeName(), pattern->getTypeName())); - }, - [&](auto &&value) -> Token::Literal { - if (dynamic_cast(pattern) || dynamic_cast(pattern)) - return u128(value) & bitmask(pattern->getSize() * 8); - else if (dynamic_cast(pattern)) - return i128(value) & bitmask(pattern->getSize() * 8); - else if (dynamic_cast(pattern)) - return char(value); - else if (dynamic_cast(pattern)) - return bool(value); - else if (dynamic_cast(pattern)) - return pattern->getSize() == sizeof(float) ? double(float(value)) : value; - else - LogConsole::abortEvaluation(hex::format("cannot cast integer literal to type '{}'", pattern->getTypeName())); - } - }, value); + [&](double &value) -> Token::Literal { + if (dynamic_cast(pattern)) + return u128(value) & bitmask(pattern->getSize() * 8); + else if (dynamic_cast(pattern)) + return i128(value) & bitmask(pattern->getSize() * 8); + else if (dynamic_cast(pattern)) + return pattern->getSize() == sizeof(float) ? double(float(value)) : value; + else + LogConsole::abortEvaluation(hex::format("cannot cast type 'double' to type '{}'", pattern->getTypeName())); + }, + [&](const std::string &value) -> Token::Literal { + if (dynamic_cast(pattern)) + return value; + else + LogConsole::abortEvaluation(hex::format("cannot cast type 'string' to type '{}'", pattern->getTypeName())); + }, + [&](PatternData *const &value) -> Token::Literal { + if (value->getTypeName() == pattern->getTypeName()) + return value; + else + LogConsole::abortEvaluation(hex::format("cannot cast type '{}' to type '{}'", value->getTypeName(), pattern->getTypeName())); + }, + [&](auto &&value) -> Token::Literal { + if (dynamic_cast(pattern) || dynamic_cast(pattern)) + return u128(value) & bitmask(pattern->getSize() * 8); + else if (dynamic_cast(pattern)) + return i128(value) & bitmask(pattern->getSize() * 8); + else if (dynamic_cast(pattern)) + return char(value); + else if (dynamic_cast(pattern)) + return bool(value); + else if (dynamic_cast(pattern)) + return pattern->getSize() == sizeof(float) ? double(float(value)) : value; + else + LogConsole::abortEvaluation(hex::format("cannot cast integer literal to type '{}'", pattern->getTypeName())); + } }, + value); this->getStack()[pattern->getOffset()] = castedLiteral; - } - std::optional> Evaluator::evaluate(const std::vector &ast) { + std::optional> Evaluator::evaluate(const std::vector &ast) { this->m_stack.clear(); this->m_customFunctions.clear(); this->m_scopes.clear(); @@ -143,20 +142,20 @@ namespace hex::pl { delete func; this->m_customFunctionDefinitions.clear(); - std::vector patterns; + std::vector patterns; try { this->setCurrentControlFlowStatement(ControlFlowStatement::None); pushScope(nullptr, patterns); for (auto node : ast) { - if (dynamic_cast(node)) { - ;// Don't create patterns from type declarations - } else if (dynamic_cast(node)) { + if (dynamic_cast(node)) { + ; // Don't create patterns from type declarations + } else if (dynamic_cast(node)) { delete node->evaluate(this); - } else if (dynamic_cast(node)) { + } else if (dynamic_cast(node)) { this->m_customFunctionDefinitions.push_back(node->evaluate(this)); - } else if (auto varDeclNode = dynamic_cast(node)) { + } else if (auto varDeclNode = dynamic_cast(node)) { auto pattern = node->createPatterns(this).front(); if (varDeclNode->getPlacementOffset() == nullptr) { @@ -170,9 +169,9 @@ namespace hex::pl { this->setVariable(name, this->m_inVariables[name]); delete pattern; - } else { - patterns.push_back(pattern); - } + } else { + patterns.push_back(pattern); + } } else { auto newPatterns = node->createPatterns(this); std::copy(newPatterns.begin(), newPatterns.end(), std::back_inserter(patterns)); @@ -185,7 +184,7 @@ namespace hex::pl { if (mainFunction.parameterCount > 0) LogConsole::abortEvaluation("main function may not accept any arguments"); - auto result = mainFunction.func(this, { }); + auto result = mainFunction.func(this, {}); if (result) { auto returnCode = Token::literalToSigned(*result); diff --git a/lib/libimhex/source/pattern_language/lexer.cpp b/lib/libimhex/source/pattern_language/lexer.cpp index d4bf14306..0bfa6d8a0 100644 --- a/lib/libimhex/source/pattern_language/lexer.cpp +++ b/lib/libimhex/source/pattern_language/lexer.cpp @@ -7,10 +7,10 @@ namespace hex::pl { -#define TOKEN(type, value) Token::Type::type, Token::type::value, lineNumber +#define TOKEN(type, value) Token::Type::type, Token::type::value, lineNumber #define VALUE_TOKEN(type, value) Token::Type::type, value, lineNumber - std::string matchTillInvalid(const char* characters, std::function predicate) { + std::string matchTillInvalid(const char *characters, std::function predicate) { std::string ret; while (*characters != 0x00) { @@ -55,46 +55,46 @@ namespace hex::pl { base = 16; if (Token::isFloatingPoint(type)) - return { }; + return {}; if (numberData.find_first_not_of("0123456789ABCDEFabcdef") != std::string_view::npos) - return { }; + return {}; } else if (numberData.starts_with("0b")) { numberData = numberData.substr(2); base = 2; if (Token::isFloatingPoint(type)) - return { }; + return {}; if (numberData.find_first_not_of("01") != std::string_view::npos) - return { }; + return {}; } else if (numberData.find('.') != std::string_view::npos || Token::isFloatingPoint(type)) { base = 10; if (type == Token::ValueType::Any) type = Token::ValueType::Double; if (std::count(numberData.begin(), numberData.end(), '.') > 1 || numberData.find_first_not_of("0123456789.") != std::string_view::npos) - return { }; + return {}; if (numberData.ends_with('.')) - return { }; + return {}; } else if (isdigit(numberData[0])) { base = 10; if (numberData.find_first_not_of("0123456789") != std::string_view::npos) - return { }; - } else return { }; + return {}; + } else return {}; if (type == Token::ValueType::Any) type = Token::ValueType::Signed128Bit; if (numberData.length() == 0) - return { }; + return {}; if (Token::isUnsigned(type) || Token::isSigned(type)) { u128 integer = 0; - for (const char& c : numberData) { + for (const char &c : numberData) { integer *= base; if (isdigit(c)) @@ -103,82 +103,124 @@ namespace hex::pl { integer += 10 + (c - 'A'); else if (c >= 'a' && c <= 'f') integer += 10 + (c - 'a'); - else return { }; + else return {}; } switch (type) { - case Token::ValueType::Unsigned128Bit: return { u128(integer) }; - case Token::ValueType::Signed128Bit: return { i128(integer) }; - default: return { }; + case Token::ValueType::Unsigned128Bit: + return { u128(integer) }; + case Token::ValueType::Signed128Bit: + return { i128(integer) }; + default: + return {}; } } else if (Token::isFloatingPoint(type)) { double floatingPoint = strtod(numberData.data(), nullptr); switch (type) { - case Token::ValueType::Float: return { float(floatingPoint) }; - case Token::ValueType::Double: return { double(floatingPoint) }; - default: return { }; + case Token::ValueType::Float: + return { float(floatingPoint) }; + case Token::ValueType::Double: + return { double(floatingPoint) }; + default: + return {}; } } - return { }; + return {}; } std::optional> getCharacter(const std::string &string) { if (string.length() < 1) - return { }; + return {}; // Escape sequences if (string[0] == '\\') { if (string.length() < 2) - return { }; + return {}; // Handle simple escape sequences switch (string[1]) { - case 'a': return {{ '\a', 2 }}; - case 'b': return {{ '\b', 2 }}; - case 'f': return {{ '\f', 2 }}; - case 'n': return {{ '\n', 2 }}; - case 'r': return {{ '\r', 2 }}; - case 't': return {{ '\t', 2 }}; - case 'v': return {{ '\v', 2 }}; - case '\\': return {{ '\\', 2 }}; - case '\'': return {{ '\'', 2 }}; - case '\"': return {{ '\"', 2 }}; + case 'a': + return { + {'\a', 2} + }; + case 'b': + return { + {'\b', 2} + }; + case 'f': + return { + {'\f', 2} + }; + case 'n': + return { + {'\n', 2} + }; + case 'r': + return { + {'\r', 2} + }; + case 't': + return { + {'\t', 2} + }; + case 'v': + return { + {'\v', 2} + }; + case '\\': + return { + {'\\', 2} + }; + case '\'': + return { + {'\'', 2} + }; + case '\"': + return { + {'\"', 2} + }; } // Hexadecimal number if (string[1] == 'x') { if (string.length() != 4) - return { }; + return {}; if (!isxdigit(string[2]) || !isxdigit(string[3])) - return { }; + return {}; - return {{ std::strtoul(&string[2], nullptr, 16), 4 }}; + return { + {std::strtoul(&string[2], nullptr, 16), 4} + }; } // Octal number if (string[1] == 'o') { if (string.length() != 5) - return { }; + return {}; if (string[2] < '0' || string[2] > '7' || string[3] < '0' || string[3] > '7' || string[4] < '0' || string[4] > '7') - return { }; + return {}; - return {{ std::strtoul(&string[2], nullptr, 8), 5 }}; + return { + {std::strtoul(&string[2], nullptr, 8), 5} + }; } - return { }; - } else return {{ string[0], 1 }}; + return {}; + } else return { + {string[0], 1} + }; } std::optional> getStringLiteral(const std::string &string) { if (!string.starts_with('\"')) - return { }; + return {}; size_t size = 1; @@ -187,7 +229,7 @@ namespace hex::pl { auto character = getCharacter(string.substr(size)); if (!character.has_value()) - return { }; + return {}; auto &[c, charSize] = character.value(); @@ -195,34 +237,38 @@ namespace hex::pl { size += charSize; if (size >= string.length()) - return { }; + return {}; } - return {{ result, size + 1 }}; + return { + {result, size + 1} + }; } std::optional> getCharacterLiteral(const std::string &string) { if (string.empty()) - return { }; + return {}; if (string[0] != '\'') - return { }; + return {}; auto character = getCharacter(string.substr(1)); if (!character.has_value()) - return { }; + return {}; auto &[c, charSize] = character.value(); if (string.length() >= charSize + 2 && string[charSize + 1] != '\'') - return { }; + return {}; - return {{ c, charSize + 2 }}; + return { + {c, charSize + 2} + }; } - std::optional> Lexer::lex(const std::string& code) { + std::optional> Lexer::lex(const std::string &code) { std::vector tokens; u32 offset = 0; @@ -231,7 +277,7 @@ namespace hex::pl { try { while (offset < code.length()) { - const char& c = code[offset]; + const char &c = code[offset]; if (c == 0x00) break; @@ -350,12 +396,10 @@ namespace hex::pl { } else if (code.substr(offset, 9) == "addressof") { tokens.emplace_back(TOKEN(Operator, AddressOf)); offset += 9; - } - else if (code.substr(offset, 6) == "sizeof") { + } else if (code.substr(offset, 6) == "sizeof") { tokens.emplace_back(TOKEN(Operator, SizeOf)); offset += 6; - } - else if (c == '\'') { + } else if (c == '\'') { auto character = getCharacterLiteral(code.substr(offset)); if (!character.has_value()) @@ -425,7 +469,7 @@ namespace hex::pl { else if (identifier == "continue") tokens.emplace_back(TOKEN(Keyword, Continue)); - // Check for built-in types + // Check for built-in types else if (identifier == "u8") tokens.emplace_back(TOKEN(ValueType, Unsigned8Bit)); else if (identifier == "s8") @@ -480,13 +524,12 @@ namespace hex::pl { offset += getIntegerLiteralLength(&code[offset]); } else throwLexerError("unknown token", lineNumber); - } tokens.emplace_back(TOKEN(Separator, EndOfProgram)); } catch (LexerError &e) { this->m_error = e; - return { }; + return {}; } diff --git a/lib/libimhex/source/pattern_language/log_console.cpp b/lib/libimhex/source/pattern_language/log_console.cpp index 23180040b..76cf74db8 100644 --- a/lib/libimhex/source/pattern_language/log_console.cpp +++ b/lib/libimhex/source/pattern_language/log_console.cpp @@ -8,19 +8,17 @@ namespace hex::pl { this->m_consoleLog.emplace_back(level, message); } - [[noreturn]] - void LogConsole::abortEvaluation(const std::string &message) { + [[noreturn]] void LogConsole::abortEvaluation(const std::string &message) { throw EvaluateError(0, message); } - [[noreturn]] - void LogConsole::abortEvaluation(const std::string &message, const ASTNode *node) { - throw EvaluateError(static_cast(node)->getLineNumber(), message); + [[noreturn]] void LogConsole::abortEvaluation(const std::string &message, const ASTNode *node) { + throw EvaluateError(static_cast(node)->getLineNumber(), message); } void LogConsole::clear() { this->m_consoleLog.clear(); - this->m_lastHardError = { }; + this->m_lastHardError = {}; } } \ No newline at end of file diff --git a/lib/libimhex/source/pattern_language/parser.cpp b/lib/libimhex/source/pattern_language/parser.cpp index 31fcd3394..4678e3490 100644 --- a/lib/libimhex/source/pattern_language/parser.cpp +++ b/lib/libimhex/source/pattern_language/parser.cpp @@ -16,13 +16,13 @@ namespace hex::pl { /* Mathematical expressions */ // Identifier([(parseMathematicalExpression)|<(parseMathematicalExpression),...>(parseMathematicalExpression)] - ASTNode* Parser::parseFunctionCall() { + ASTNode *Parser::parseFunctionCall() { std::string functionName = parseNamespaceResolution(); if (!MATCHES(sequence(SEPARATOR_ROUNDBRACKETOPEN))) throwParseError("expected '(' after function name"); - std::vector params; + std::vector params; auto paramCleanup = SCOPE_GUARD { for (auto ¶m : params) delete param; @@ -37,7 +37,6 @@ namespace hex::pl { break; else if (!MATCHES(sequence(SEPARATOR_COMMA))) throwParseError("missing ',' between parameters", -1); - } paramCleanup.release(); @@ -45,7 +44,7 @@ namespace hex::pl { return create(new ASTNodeFunctionCall(functionName, params)); } - ASTNode* Parser::parseStringLiteral() { + ASTNode *Parser::parseStringLiteral() { return create(new ASTNodeLiteral(getValue(-1))); } @@ -58,15 +57,14 @@ namespace hex::pl { if (MATCHES(sequence(OPERATOR_SCOPERESOLUTION, IDENTIFIER))) { name += "::"; continue; - } - else + } else break; } return name; } - ASTNode* Parser::parseScopeResolution() { + ASTNode *Parser::parseScopeResolution() { std::string typeName; while (true) { @@ -75,15 +73,14 @@ namespace hex::pl { if (MATCHES(sequence(OPERATOR_SCOPERESOLUTION, IDENTIFIER))) { if (peek(OPERATOR_SCOPERESOLUTION, 0) && peek(IDENTIFIER, 1)) { typeName += "::"; - continue; + continue; } else { if (!this->m_types.contains(typeName)) throwParseError(hex::format("cannot access scope of invalid type '{}'", typeName), -1); return create(new ASTNodeScopeResolution(this->m_types[typeName]->clone(), getValue(-1).get())); } - } - else + } else break; } @@ -91,7 +88,7 @@ namespace hex::pl { } // - ASTNode* Parser::parseRValue(ASTNodeRValue::Path &path) { + ASTNode *Parser::parseRValue(ASTNodeRValue::Path &path) { if (peek(IDENTIFIER, -1)) path.push_back(getValue(-1).get()); else if (peek(KEYWORD_PARENT, -1)) @@ -115,7 +112,7 @@ namespace hex::pl { } // - ASTNode* Parser::parseFactor() { + ASTNode *Parser::parseFactor() { if (MATCHES(sequence(INTEGER))) return new ASTNodeLiteral(getValue(-1)); else if (peek(OPERATOR_PLUS) || peek(OPERATOR_MINUS) || peek(OPERATOR_BITNOT) || peek(OPERATOR_BOOLNOT)) @@ -165,10 +162,10 @@ namespace hex::pl { throwParseError("expected value or parenthesis"); } - ASTNode* Parser::parseCastExpression() { + ASTNode *Parser::parseCastExpression() { if (peek(KEYWORD_BE) || peek(KEYWORD_LE) || peek(VALUETYPE_ANY)) { auto type = parseType(true); - auto builtinType = dynamic_cast(type->getType()); + auto builtinType = dynamic_cast(type->getType()); if (builtinType == nullptr) throwParseError("invalid type used for pointer size", -1); @@ -183,7 +180,7 @@ namespace hex::pl { } // <+|-|!|~> (parseFactor) - ASTNode* Parser::parseUnaryExpression() { + ASTNode *Parser::parseUnaryExpression() { if (MATCHES(oneOf(OPERATOR_PLUS, OPERATOR_MINUS, OPERATOR_BOOLNOT, OPERATOR_BITNOT))) { auto op = getValue(-1); @@ -196,7 +193,7 @@ namespace hex::pl { } // (parseUnaryExpression) <*|/|%> (parseUnaryExpression) - ASTNode* Parser::parseMultiplicativeExpression() { + ASTNode *Parser::parseMultiplicativeExpression() { auto node = this->parseUnaryExpression(); auto nodeCleanup = SCOPE_GUARD { delete node; }; @@ -212,7 +209,7 @@ namespace hex::pl { } // (parseMultiplicativeExpression) <+|-> (parseMultiplicativeExpression) - ASTNode* Parser::parseAdditiveExpression() { + ASTNode *Parser::parseAdditiveExpression() { auto node = this->parseMultiplicativeExpression(); auto nodeCleanup = SCOPE_GUARD { delete node; }; @@ -228,7 +225,7 @@ namespace hex::pl { } // (parseAdditiveExpression) < >>|<< > (parseAdditiveExpression) - ASTNode* Parser::parseShiftExpression() { + ASTNode *Parser::parseShiftExpression() { auto node = this->parseAdditiveExpression(); auto nodeCleanup = SCOPE_GUARD { delete node; }; @@ -244,10 +241,10 @@ namespace hex::pl { } // (parseAdditiveExpression) < >=|<=|>|< > (parseAdditiveExpression) - ASTNode* Parser::parseRelationExpression() { + ASTNode *Parser::parseRelationExpression() { auto node = this->parseShiftExpression(); - auto nodeCleanup = SCOPE_GUARD{ delete node; }; + auto nodeCleanup = SCOPE_GUARD { delete node; }; while (MATCHES(sequence(OPERATOR_BOOLGREATERTHAN) || sequence(OPERATOR_BOOLLESSTHAN) || sequence(OPERATOR_BOOLGREATERTHANOREQUALS) || sequence(OPERATOR_BOOLLESSTHANOREQUALS))) { auto op = getValue(-1); @@ -260,7 +257,7 @@ namespace hex::pl { } // (parseRelationExpression) <==|!=> (parseRelationExpression) - ASTNode* Parser::parseEqualityExpression() { + ASTNode *Parser::parseEqualityExpression() { auto node = this->parseRelationExpression(); auto nodeCleanup = SCOPE_GUARD { delete node; }; @@ -276,7 +273,7 @@ namespace hex::pl { } // (parseEqualityExpression) & (parseEqualityExpression) - ASTNode* Parser::parseBinaryAndExpression() { + ASTNode *Parser::parseBinaryAndExpression() { auto node = this->parseEqualityExpression(); auto nodeCleanup = SCOPE_GUARD { delete node; }; @@ -291,7 +288,7 @@ namespace hex::pl { } // (parseBinaryAndExpression) ^ (parseBinaryAndExpression) - ASTNode* Parser::parseBinaryXorExpression() { + ASTNode *Parser::parseBinaryXorExpression() { auto node = this->parseBinaryAndExpression(); auto nodeCleanup = SCOPE_GUARD { delete node; }; @@ -306,7 +303,7 @@ namespace hex::pl { } // (parseBinaryXorExpression) | (parseBinaryXorExpression) - ASTNode* Parser::parseBinaryOrExpression() { + ASTNode *Parser::parseBinaryOrExpression() { auto node = this->parseBinaryXorExpression(); auto nodeCleanup = SCOPE_GUARD { delete node; }; @@ -321,7 +318,7 @@ namespace hex::pl { } // (parseBinaryOrExpression) && (parseBinaryOrExpression) - ASTNode* Parser::parseBooleanAnd() { + ASTNode *Parser::parseBooleanAnd() { auto node = this->parseBinaryOrExpression(); auto nodeCleanup = SCOPE_GUARD { delete node; }; @@ -336,7 +333,7 @@ namespace hex::pl { } // (parseBooleanAnd) ^^ (parseBooleanAnd) - ASTNode* Parser::parseBooleanXor() { + ASTNode *Parser::parseBooleanXor() { auto node = this->parseBooleanAnd(); auto nodeCleanup = SCOPE_GUARD { delete node; }; @@ -351,7 +348,7 @@ namespace hex::pl { } // (parseBooleanXor) || (parseBooleanXor) - ASTNode* Parser::parseBooleanOr() { + ASTNode *Parser::parseBooleanOr() { auto node = this->parseBooleanXor(); auto nodeCleanup = SCOPE_GUARD { delete node; }; @@ -366,7 +363,7 @@ namespace hex::pl { } // (parseBooleanOr) ? (parseBooleanOr) : (parseBooleanOr) - ASTNode* Parser::parseTernaryConditional() { + ASTNode *Parser::parseTernaryConditional() { auto node = this->parseBooleanOr(); auto nodeCleanup = SCOPE_GUARD { delete node; }; @@ -387,7 +384,7 @@ namespace hex::pl { } // (parseTernaryConditional) - ASTNode* Parser::parseMathematicalExpression() { + ASTNode *Parser::parseMathematicalExpression() { return this->parseTernaryConditional(); } @@ -410,8 +407,7 @@ namespace hex::pl { throwParseError("expected string attribute argument"); currNode->addAttribute(create(new ASTNodeAttribute(attribute, *string))); - } - else + } else currNode->addAttribute(create(new ASTNodeAttribute(attribute))); } while (MATCHES(sequence(SEPARATOR_COMMA))); @@ -422,9 +418,9 @@ namespace hex::pl { /* Functions */ - ASTNode* Parser::parseFunctionDefinition() { + ASTNode *Parser::parseFunctionDefinition() { const auto &functionName = getValue(-2).get(); - std::vector> params; + std::vector> params; // Parse parameter list bool hasParams = !peek(SEPARATOR_ROUNDBRACKETCLOSE); @@ -456,7 +452,7 @@ namespace hex::pl { // Parse function body - std::vector body; + std::vector body; auto bodyCleanup = SCOPE_GUARD { for (auto &node : body) delete node; @@ -470,7 +466,7 @@ namespace hex::pl { return create(new ASTNodeFunctionDefinition(getNamespacePrefixedName(functionName), params, body)); } - ASTNode* Parser::parseFunctionVariableDecl() { + ASTNode *Parser::parseFunctionVariableDecl() { ASTNode *statement; auto type = parseType(true); @@ -483,14 +479,13 @@ namespace hex::pl { statement = create(new ASTNodeCompoundStatement({ statement, create(new ASTNodeAssignment(identifier, expression)) })); } - } - else + } else throwParseError("invalid variable declaration"); return statement; } - ASTNode* Parser::parseFunctionStatement() { + ASTNode *Parser::parseFunctionStatement() { bool needsSemicolon = true; ASTNode *statement; @@ -515,16 +510,13 @@ namespace hex::pl { if (isFunction) { this->m_curr = originalPos; statement = parseFunctionCall(); - } - else { + } else { this->m_curr = originalPos - 1; statement = parseFunctionVariableDecl(); } - } - else if (peek(KEYWORD_BE) || peek(KEYWORD_LE) || peek(VALUETYPE_ANY)) { + } else if (peek(KEYWORD_BE) || peek(KEYWORD_LE) || peek(VALUETYPE_ANY)) { statement = parseFunctionVariableDecl(); - } - else + } else throwParseError("invalid sequence", 0); if (needsSemicolon && !MATCHES(sequence(SEPARATOR_ENDOFEXPRESSION))) { @@ -533,12 +525,13 @@ namespace hex::pl { } // Consume superfluous semicolons - while (needsSemicolon && MATCHES(sequence(SEPARATOR_ENDOFEXPRESSION))); + while (needsSemicolon && MATCHES(sequence(SEPARATOR_ENDOFEXPRESSION))) + ; return statement; } - ASTNode* Parser::parseFunctionVariableAssignment() { + ASTNode *Parser::parseFunctionVariableAssignment() { const auto &lvalue = getValue(-2).get(); auto rvalue = this->parseMathematicalExpression(); @@ -546,7 +539,7 @@ namespace hex::pl { return create(new ASTNodeAssignment(lvalue, rvalue)); } - ASTNode* Parser::parseFunctionControlFlowStatement() { + ASTNode *Parser::parseFunctionControlFlowStatement() { ControlFlowStatement type; if (peek(KEYWORD_RETURN, -1)) type = ControlFlowStatement::Return; @@ -563,8 +556,8 @@ namespace hex::pl { return create(new ASTNodeControlFlowStatement(type, this->parseMathematicalExpression())); } - std::vector Parser::parseStatementBody() { - std::vector body; + std::vector Parser::parseStatementBody() { + std::vector body; auto bodyCleanup = SCOPE_GUARD { for (auto &node : body) @@ -584,9 +577,9 @@ namespace hex::pl { return body; } - ASTNode* Parser::parseFunctionConditional() { + ASTNode *Parser::parseFunctionConditional() { auto condition = parseMathematicalExpression(); - std::vector trueBody, falseBody; + std::vector trueBody, falseBody; auto cleanup = SCOPE_GUARD { delete condition; @@ -609,9 +602,9 @@ namespace hex::pl { return create(new ASTNodeConditionalStatement(condition, trueBody, falseBody)); } - ASTNode* Parser::parseFunctionWhileLoop() { + ASTNode *Parser::parseFunctionWhileLoop() { auto condition = parseMathematicalExpression(); - std::vector body; + std::vector body; auto cleanup = SCOPE_GUARD { delete condition; @@ -629,7 +622,7 @@ namespace hex::pl { return create(new ASTNodeWhileStatement(condition, body)); } - ASTNode* Parser::parseFunctionForLoop() { + ASTNode *Parser::parseFunctionForLoop() { auto variable = parseFunctionVariableDecl(); auto variableCleanup = SCOPE_GUARD { delete variable; }; @@ -648,7 +641,7 @@ namespace hex::pl { auto postExpression = parseFunctionVariableAssignment(); auto postExpressionCleanup = SCOPE_GUARD { delete postExpression; }; - std::vector body; + std::vector body; auto bodyCleanup = SCOPE_GUARD { for (auto &statement : body) @@ -671,9 +664,9 @@ namespace hex::pl { /* Control flow */ // if ((parseMathematicalExpression)) { (parseMember) } - ASTNode* Parser::parseConditional() { + ASTNode *Parser::parseConditional() { auto condition = parseMathematicalExpression(); - std::vector trueBody, falseBody; + std::vector trueBody, falseBody; auto cleanup = SCOPE_GUARD { delete condition; @@ -706,7 +699,7 @@ namespace hex::pl { } // while ((parseMathematicalExpression)) - ASTNode* Parser::parseWhileStatement() { + ASTNode *Parser::parseWhileStatement() { auto condition = parseMathematicalExpression(); auto cleanup = SCOPE_GUARD { @@ -718,13 +711,13 @@ namespace hex::pl { cleanup.release(); - return create(new ASTNodeWhileStatement(condition, { })); + return create(new ASTNodeWhileStatement(condition, {})); } /* Type declarations */ // [be|le] - ASTNodeTypeDecl* Parser::parseType(bool allowFunctionTypes) { + ASTNodeTypeDecl *Parser::parseType(bool allowFunctionTypes) { std::optional endian; if (MATCHES(sequence(KEYWORD_LE))) @@ -732,17 +725,16 @@ namespace hex::pl { else if (MATCHES(sequence(KEYWORD_BE))) endian = std::endian::big; - if (MATCHES(sequence(IDENTIFIER))) { // Custom type + if (MATCHES(sequence(IDENTIFIER))) { // Custom type std::string typeName = parseNamespaceResolution(); if (this->m_types.contains(typeName)) - return create(new ASTNodeTypeDecl({ }, this->m_types[typeName]->clone(), endian)); + return create(new ASTNodeTypeDecl({}, this->m_types[typeName]->clone(), endian)); else if (this->m_types.contains(getNamespacePrefixedName(typeName))) - return create(new ASTNodeTypeDecl({ }, this->m_types[getNamespacePrefixedName(typeName)]->clone(), endian)); + return create(new ASTNodeTypeDecl({}, this->m_types[getNamespacePrefixedName(typeName)]->clone(), endian)); else throwParseError(hex::format("unknown type '{}'", typeName)); - } - else if (MATCHES(sequence(VALUETYPE_ANY))) { // Builtin type + } else if (MATCHES(sequence(VALUETYPE_ANY))) { // Builtin type auto type = getValue(-1); if (!allowFunctionTypes) { if (type == Token::ValueType::String) @@ -751,12 +743,12 @@ namespace hex::pl { throwParseError("cannot use 'auto' in this context"); } - return create(new ASTNodeTypeDecl({ }, new ASTNodeBuiltinType(type), endian)); + return create(new ASTNodeTypeDecl({}, new ASTNodeBuiltinType(type), endian)); } else throwParseError("failed to parse type. Expected identifier or builtin type"); } // using Identifier = (parseType) - ASTNode* Parser::parseUsingDeclaration() { + ASTNode *Parser::parseUsingDeclaration() { auto name = parseNamespaceResolution(); if (!MATCHES(sequence(OPERATOR_ASSIGNMENT))) @@ -769,7 +761,7 @@ namespace hex::pl { } // padding[(parseMathematicalExpression)] - ASTNode* Parser::parsePadding() { + ASTNode *Parser::parsePadding() { auto size = parseMathematicalExpression(); if (!MATCHES(sequence(SEPARATOR_SQUAREBRACKETCLOSE))) { @@ -777,15 +769,17 @@ namespace hex::pl { throwParseError("expected closing ']' at end of array declaration", -1); } - return create(new ASTNodeArrayVariableDecl({ }, new ASTNodeTypeDecl({ }, new ASTNodeBuiltinType(Token::ValueType::Padding)), size)); + return create(new ASTNodeArrayVariableDecl({}, new ASTNodeTypeDecl({}, new ASTNodeBuiltinType(Token::ValueType::Padding)), size)); } // (parseType) Identifier - ASTNode* Parser::parseMemberVariable(ASTNodeTypeDecl *type) { + ASTNode *Parser::parseMemberVariable(ASTNodeTypeDecl *type) { if (peek(SEPARATOR_COMMA)) { - std::vector variables; - auto variableCleanup = SCOPE_GUARD { for (auto var : variables) delete var; }; + std::vector variables; + auto variableCleanup = SCOPE_GUARD { + for (auto var : variables) delete var; + }; do { variables.push_back(create(new ASTNodeVariableDecl(getValue(-1).get(), type->clone()))); @@ -800,7 +794,7 @@ namespace hex::pl { } // (parseType) Identifier[(parseMathematicalExpression)] - ASTNode* Parser::parseMemberArrayVariable(ASTNodeTypeDecl *type) { + ASTNode *Parser::parseMemberArrayVariable(ASTNodeTypeDecl *type) { auto name = getValue(-2).get(); ASTNode *size = nullptr; @@ -822,13 +816,13 @@ namespace hex::pl { } // (parseType) *Identifier : (parseType) - ASTNode* Parser::parseMemberPointerVariable(ASTNodeTypeDecl *type) { + ASTNode *Parser::parseMemberPointerVariable(ASTNodeTypeDecl *type) { auto name = getValue(-2).get(); auto sizeType = parseType(); { - auto builtinType = dynamic_cast(sizeType->getType()); + auto builtinType = dynamic_cast(sizeType->getType()); if (builtinType == nullptr || !Token::isUnsigned(builtinType->getType())) throwParseError("invalid type used for pointer size", -1); @@ -838,7 +832,7 @@ namespace hex::pl { } // [(parsePadding)|(parseMemberVariable)|(parseMemberArrayVariable)|(parseMemberPointerVariable)] - ASTNode* Parser::parseMember() { + ASTNode *Parser::parseMember() { ASTNode *member; @@ -873,8 +867,7 @@ namespace hex::pl { else throwParseError("invalid variable declaration"); } - } - else if (MATCHES(sequence(VALUETYPE_PADDING, SEPARATOR_SQUAREBRACKETOPEN))) + } else if (MATCHES(sequence(VALUETYPE_PADDING, SEPARATOR_SQUAREBRACKETOPEN))) member = parsePadding(); else if (MATCHES(sequence(KEYWORD_IF, SEPARATOR_ROUNDBRACKETOPEN))) return parseConditional(); @@ -894,18 +887,22 @@ namespace hex::pl { throwParseError("missing ';' at end of expression", -1); // Consume superfluous semicolons - while (MATCHES(sequence(SEPARATOR_ENDOFEXPRESSION))); + while (MATCHES(sequence(SEPARATOR_ENDOFEXPRESSION))) + ; return member; } // struct Identifier { <(parseMember)...> } - ASTNode* Parser::parseStruct() { + ASTNode *Parser::parseStruct() { const auto &typeName = getValue(-1).get(); const auto structNode = create(new ASTNodeStruct()); const auto typeDecl = addType(typeName, structNode); - auto structGuard = SCOPE_GUARD { delete structNode; delete typeDecl; }; + auto structGuard = SCOPE_GUARD { + delete structNode; + delete typeDecl; + }; if (MATCHES(sequence(OPERATOR_INHERIT, IDENTIFIER))) { // Inheritance @@ -935,12 +932,15 @@ namespace hex::pl { } // union Identifier { <(parseMember)...> } - ASTNode* Parser::parseUnion() { + ASTNode *Parser::parseUnion() { const auto &typeName = getValue(-2).get(); const auto unionNode = create(new ASTNodeUnion()); const auto typeDecl = addType(typeName, unionNode); - auto unionGuard = SCOPE_GUARD { delete unionNode; delete typeDecl; }; + auto unionGuard = SCOPE_GUARD { + delete unionNode; + delete typeDecl; + }; while (!MATCHES(sequence(SEPARATOR_CURLYBRACKETCLOSE))) { unionNode->addMember(parseMember()); @@ -952,7 +952,7 @@ namespace hex::pl { } // enum Identifier : (parseType) { <...> } - ASTNode* Parser::parseEnum() { + ASTNode *Parser::parseEnum() { auto typeName = getValue(-2).get(); auto underlyingType = parseType(); @@ -960,7 +960,10 @@ namespace hex::pl { const auto enumNode = create(new ASTNodeEnum(underlyingType)); const auto typeDecl = addType(typeName, enumNode); - auto enumGuard = SCOPE_GUARD { delete enumNode; delete typeDecl; }; + auto enumGuard = SCOPE_GUARD { + delete enumNode; + delete typeDecl; + }; if (!MATCHES(sequence(SEPARATOR_CURLYBRACKETOPEN))) throwParseError("expected '{' after enum definition", -1); @@ -973,8 +976,7 @@ namespace hex::pl { enumNode->addEntry(name, value); lastEntry = value; - } - else if (MATCHES(sequence(IDENTIFIER))) { + } else if (MATCHES(sequence(IDENTIFIER))) { ASTNode *valueExpr; auto name = getValue(-1).get(); if (enumNode->getEntries().empty()) @@ -983,8 +985,7 @@ namespace hex::pl { valueExpr = lastEntry = create(new ASTNodeMathematicalExpression(lastEntry->clone(), new ASTNodeLiteral(u128(1)), Token::Operator::Plus)); enumNode->addEntry(name, valueExpr); - } - else if (MATCHES(sequence(SEPARATOR_ENDOFPROGRAM))) + } else if (MATCHES(sequence(SEPARATOR_ENDOFPROGRAM))) throwParseError("unexpected end of program", -2); else throwParseError("invalid enum entry", -1); @@ -1003,20 +1004,23 @@ namespace hex::pl { } // bitfield Identifier { } - ASTNode* Parser::parseBitfield() { + ASTNode *Parser::parseBitfield() { std::string typeName = getValue(-2).get(); const auto bitfieldNode = create(new ASTNodeBitfield()); const auto typeDecl = addType(typeName, bitfieldNode); - auto enumGuard = SCOPE_GUARD { delete bitfieldNode; delete typeDecl; }; + auto enumGuard = SCOPE_GUARD { + delete bitfieldNode; + delete typeDecl; + }; while (!MATCHES(sequence(SEPARATOR_CURLYBRACKETCLOSE))) { if (MATCHES(sequence(IDENTIFIER, OPERATOR_INHERIT))) { auto name = getValue(-2).get(); bitfieldNode->addEntry(name, parseMathematicalExpression()); } else if (MATCHES(sequence(VALUETYPE_PADDING, OPERATOR_INHERIT))) { - bitfieldNode->addEntry("padding", parseMathematicalExpression()); + bitfieldNode->addEntry("padding", parseMathematicalExpression()); } else if (MATCHES(sequence(SEPARATOR_ENDOFPROGRAM))) throwParseError("unexpected end of program", -2); else @@ -1026,7 +1030,8 @@ namespace hex::pl { throwParseError("missing ';' at end of expression", -1); // Consume superfluous semicolons - while (MATCHES(sequence(SEPARATOR_ENDOFEXPRESSION))); + while (MATCHES(sequence(SEPARATOR_ENDOFEXPRESSION))) + ; } enumGuard.release(); @@ -1035,7 +1040,7 @@ namespace hex::pl { } // (parseType) Identifier @ Integer - ASTNode* Parser::parseVariablePlacement(ASTNodeTypeDecl *type) { + ASTNode *Parser::parseVariablePlacement(ASTNodeTypeDecl *type) { bool inVariable = false; bool outVariable = false; @@ -1046,8 +1051,7 @@ namespace hex::pl { placementOffset = parseMathematicalExpression(); } else if (MATCHES(sequence(KEYWORD_IN))) { inVariable = true; - } - else if (MATCHES(sequence(KEYWORD_OUT))) { + } else if (MATCHES(sequence(KEYWORD_OUT))) { outVariable = true; } @@ -1055,7 +1059,7 @@ namespace hex::pl { } // (parseType) Identifier[[(parseMathematicalExpression)]] @ Integer - ASTNode* Parser::parseArrayVariablePlacement(ASTNodeTypeDecl *type) { + ASTNode *Parser::parseArrayVariablePlacement(ASTNodeTypeDecl *type) { auto name = getValue(-2).get(); ASTNode *size = nullptr; @@ -1082,14 +1086,14 @@ namespace hex::pl { } // (parseType) *Identifier : (parseType) @ Integer - ASTNode* Parser::parsePointerVariablePlacement(ASTNodeTypeDecl *type) { + ASTNode *Parser::parsePointerVariablePlacement(ASTNodeTypeDecl *type) { auto name = getValue(-2).get(); auto sizeType = parseType(); auto sizeCleanup = SCOPE_GUARD { delete sizeType; }; { - auto builtinType = dynamic_cast(sizeType->getType()); + auto builtinType = dynamic_cast(sizeType->getType()); if (builtinType == nullptr || !Token::isUnsigned(builtinType->getType())) throwParseError("invalid type used for pointer size", -1); @@ -1105,8 +1109,8 @@ namespace hex::pl { return create(new ASTNodePointerVariableDecl(name, type->clone(), sizeType, placementOffset)); } - std::vector Parser::parseNamespace() { - std::vector statements; + std::vector Parser::parseNamespace() { + std::vector statements; if (!MATCHES(sequence(IDENTIFIER))) throwParseError("expected namespace identifier"); @@ -1135,7 +1139,7 @@ namespace hex::pl { return statements; } - ASTNode* Parser::parsePlacement() { + ASTNode *Parser::parsePlacement() { auto type = parseType(); ON_SCOPE_EXIT { delete type; }; @@ -1151,7 +1155,7 @@ namespace hex::pl { /* Program */ // <(parseUsingDeclaration)|(parseVariablePlacement)|(parseStruct)> - std::vector Parser::parseStatements() { + std::vector Parser::parseStatements() { ASTNode *statement = nullptr; auto statementGuard = SCOPE_GUARD { delete statement; @@ -1169,11 +1173,9 @@ namespace hex::pl { if (isFunction) { this->m_curr++; statement = parseFunctionCall(); - } - else + } else statement = parsePlacement(); - } - else if (peek(KEYWORD_BE) || peek(KEYWORD_LE) || peek(VALUETYPE_ANY)) + } else if (peek(KEYWORD_BE) || peek(KEYWORD_LE) || peek(VALUETYPE_ANY)) statement = parsePlacement(); else if (MATCHES(sequence(KEYWORD_STRUCT, IDENTIFIER))) statement = parseStruct(); @@ -1196,27 +1198,28 @@ namespace hex::pl { throwParseError("missing ';' at end of expression", -1); // Consume superfluous semicolons - while (MATCHES(sequence(SEPARATOR_ENDOFEXPRESSION))); + while (MATCHES(sequence(SEPARATOR_ENDOFEXPRESSION))) + ; statementGuard.release(); return { statement }; } - ASTNodeTypeDecl* Parser::addType(const std::string &name, ASTNode *node, std::optional endian) { + ASTNodeTypeDecl *Parser::addType(const std::string &name, ASTNode *node, std::optional endian) { auto typeName = getNamespacePrefixedName(name); if (this->m_types.contains(typeName)) throwParseError(hex::format("redefinition of type '{}'", typeName)); auto typeDecl = create(new ASTNodeTypeDecl(typeName, node, endian)); - this->m_types.insert({ typeName, typeDecl }); + this->m_types.insert({ typeName, typeDecl }); return typeDecl; } // <(parseNamespace)...> EndOfProgram - std::optional> Parser::parse(const std::vector &tokens) { + std::optional> Parser::parse(const std::vector &tokens) { this->m_curr = tokens.begin(); this->m_types.clear(); @@ -1235,7 +1238,7 @@ namespace hex::pl { this->m_error = e; } - return { }; + return {}; } } \ No newline at end of file diff --git a/lib/libimhex/source/pattern_language/pattern_language.cpp b/lib/libimhex/source/pattern_language/pattern_language.cpp index 6b4b294bf..f34206d71 100644 --- a/lib/libimhex/source/pattern_language/pattern_language.cpp +++ b/lib/libimhex/source/pattern_language/pattern_language.cpp @@ -94,29 +94,29 @@ namespace hex::pl { delete this->m_validator; } - std::optional> PatternLanguage::parseString(const std::string &code) { + std::optional> PatternLanguage::parseString(const std::string &code) { auto preprocessedCode = this->m_preprocessor->preprocess(code); if (!preprocessedCode.has_value()) { this->m_currError = this->m_preprocessor->getError(); - return { }; + return {}; } auto tokens = this->m_lexer->lex(preprocessedCode.value()); if (!tokens.has_value()) { this->m_currError = this->m_lexer->getError(); - return { }; + return {}; } auto ast = this->m_parser->parse(tokens.value()); if (!ast.has_value()) { this->m_currError = this->m_parser->getError(); - return { }; + return {}; } return ast; } - std::optional> PatternLanguage::executeString(prv::Provider *provider, const std::string &code, const std::map &envVars, const std::map &inVariables) { + std::optional> PatternLanguage::executeString(prv::Provider *provider, const std::string &code, const std::map &envVars, const std::map &inVariables) { this->m_currError.reset(); this->m_evaluator->getConsole().clear(); this->m_evaluator->setProvider(provider); @@ -136,20 +136,20 @@ namespace hex::pl { auto ast = this->parseString(code); if (!ast) - return { }; + return {}; this->m_currAST = ast.value(); auto patterns = this->m_evaluator->evaluate(ast.value()); if (!patterns.has_value()) { this->m_currError = this->m_evaluator->getConsole().getLastHardError(); - return { }; + return {}; } return patterns; } - std::optional> PatternLanguage::executeFile(prv::Provider *provider, const fs::path &path, const std::map &envVars, const std::map &inVariables) { + std::optional> PatternLanguage::executeFile(prv::Provider *provider, const fs::path &path, const std::map &envVars, const std::map &inVariables) { File file(path, File::Mode::Read); return this->executeString(provider, file.readString(), envVars, inVariables); @@ -159,21 +159,20 @@ namespace hex::pl { this->m_evaluator->abort(); } - const std::vector &PatternLanguage::getCurrentAST() const { + const std::vector &PatternLanguage::getCurrentAST() const { return this->m_currAST; } - [[nodiscard]] - std::map PatternLanguage::getOutVariables() const { + [[nodiscard]] std::map PatternLanguage::getOutVariables() const { return this->m_evaluator->getOutVariables(); } - const std::vector>& PatternLanguage::getConsoleLog() { + const std::vector> &PatternLanguage::getConsoleLog() { return this->m_evaluator->getConsole().getLog(); } - const std::optional>& PatternLanguage::getError() { + const std::optional> &PatternLanguage::getError() { return this->m_currError; } diff --git a/lib/libimhex/source/pattern_language/preprocessor.cpp b/lib/libimhex/source/pattern_language/preprocessor.cpp index e7881ae09..1a3d32ec4 100644 --- a/lib/libimhex/source/pattern_language/preprocessor.cpp +++ b/lib/libimhex/source/pattern_language/preprocessor.cpp @@ -9,10 +9,9 @@ namespace hex::pl { Preprocessor::Preprocessor() { - } - std::optional Preprocessor::preprocess(const std::string& code, bool initialRun) { + std::optional Preprocessor::preprocess(const std::string &code, bool initialRun) { u32 offset = 0; u32 lineNumber = 1; bool isInString = false; @@ -67,7 +66,7 @@ namespace hex::pl { if (includeFile[0] != '/') { for (const auto &dir : hex::getPath(ImHexPath::PatternsInclude)) { - std::string tempPath = hex::format("{0}/{1}", dir.string().c_str(), includeFile.c_str()); + std::string tempPath = hex::format("{0}/{1}", dir.string().c_str(), includeFile.c_str()); if (fs::exists(tempPath)) { includePath = tempPath; break; @@ -191,12 +190,12 @@ namespace hex::pl { std::vector> sortedDefines; std::copy(this->m_defines.begin(), this->m_defines.end(), std::back_inserter(sortedDefines)); std::sort(sortedDefines.begin(), sortedDefines.end(), [](const auto &left, const auto &right) { - return std::get<0>(left).size() > std::get<0>(right).size(); + return std::get<0>(left).size() > std::get<0>(right).size(); }); for (const auto &[define, value, defineLine] : sortedDefines) { i32 index = 0; - while((index = output.find(define, index)) != std::string::npos) { + while ((index = output.find(define, index)) != std::string::npos) { output.replace(index, define.length(), value); index += value.length(); } @@ -213,13 +212,13 @@ namespace hex::pl { } } catch (PreprocessorError &e) { this->m_error = e; - return { }; + return {}; } return output; } - void Preprocessor::addPragmaHandler(const std::string &pragmaType, const std::function &function) { + void Preprocessor::addPragmaHandler(const std::string &pragmaType, const std::function &function) { if (!this->m_pragmaHandlers.contains(pragmaType)) this->m_pragmaHandlers.emplace(pragmaType, function); } diff --git a/lib/libimhex/source/pattern_language/validator.cpp b/lib/libimhex/source/pattern_language/validator.cpp index 576aa3bd3..9e4893568 100644 --- a/lib/libimhex/source/pattern_language/validator.cpp +++ b/lib/libimhex/source/pattern_language/validator.cpp @@ -10,10 +10,9 @@ namespace hex::pl { Validator::Validator() { - } - bool Validator::validate(const std::vector& ast) { + bool Validator::validate(const std::vector &ast) { std::unordered_set identifiers; try { @@ -22,21 +21,21 @@ namespace hex::pl { if (node == nullptr) throwValidateError("nullptr in AST. This is a bug!", 1); - if (auto variableDeclNode = dynamic_cast(node); variableDeclNode != nullptr) { + if (auto variableDeclNode = dynamic_cast(node); variableDeclNode != nullptr) { if (!identifiers.insert(variableDeclNode->getName().data()).second) throwValidateError(hex::format("redefinition of identifier '{0}'", variableDeclNode->getName().data()), variableDeclNode->getLineNumber()); this->validate({ variableDeclNode->getType() }); - } else if (auto typeDeclNode = dynamic_cast(node); typeDeclNode != nullptr) { + } else if (auto typeDeclNode = dynamic_cast(node); typeDeclNode != nullptr) { if (!identifiers.insert(typeDeclNode->getName().data()).second) throwValidateError(hex::format("redefinition of identifier '{0}'", typeDeclNode->getName().data()), typeDeclNode->getLineNumber()); this->validate({ typeDeclNode->getType() }); - } else if (auto structNode = dynamic_cast(node); structNode != nullptr) { + } else if (auto structNode = dynamic_cast(node); structNode != nullptr) { this->validate(structNode->getMembers()); - } else if (auto unionNode = dynamic_cast(node); unionNode != nullptr) { + } else if (auto unionNode = dynamic_cast(node); unionNode != nullptr) { this->validate(unionNode->getMembers()); - } else if (auto enumNode = dynamic_cast(node); enumNode != nullptr) { + } else if (auto enumNode = dynamic_cast(node); enumNode != nullptr) { std::unordered_set enumIdentifiers; for (auto &[name, value] : enumNode->getEntries()) { if (!enumIdentifiers.insert(name).second) diff --git a/lib/libimhex/source/providers/provider.cpp b/lib/libimhex/source/providers/provider.cpp index 3c7df8772..fa7109f94 100644 --- a/lib/libimhex/source/providers/provider.cpp +++ b/lib/libimhex/source/providers/provider.cpp @@ -59,13 +59,13 @@ namespace hex::prv { i128 overlapMin = std::max(offset, overlayOffset); i128 overlapMax = std::min(offset + size, overlayOffset + overlaySize); - if (overlapMax > overlapMin) - std::memcpy(static_cast(buffer) + std::max(0, overlapMin - offset), overlay->getData().data() + std::max(0, overlapMin - overlayOffset), overlapMax - overlapMin); + if (overlapMax > overlapMin) + std::memcpy(static_cast(buffer) + std::max(0, overlapMin - offset), overlay->getData().data() + std::max(0, overlapMin - overlayOffset), overlapMax - overlapMin); } } - std::map& Provider::getPatches() { + std::map &Provider::getPatches() { auto iter = this->m_patches.end(); for (auto i = 0; i < this->m_patchTreeOffset + 1; i++) iter--; @@ -73,7 +73,7 @@ namespace hex::prv { return *(iter); } - const std::map& Provider::getPatches() const { + const std::map &Provider::getPatches() const { auto iter = this->m_patches.end(); for (auto i = 0; i < this->m_patchTreeOffset + 1; i++) iter--; @@ -88,7 +88,7 @@ namespace hex::prv { } - Overlay* Provider::newOverlay() { + Overlay *Provider::newOverlay() { return this->m_overlays.emplace_back(new Overlay()); } @@ -97,7 +97,7 @@ namespace hex::prv { delete overlay; } - const std::list& Provider::getOverlays() { + const std::list &Provider::getOverlays() { return this->m_overlays; } @@ -136,7 +136,7 @@ namespace hex::prv { u32 page = std::floor((address - this->getBaseAddress()) / double(PageSize)); if (page >= this->getPageCount()) - return { }; + return {}; return page; } @@ -155,7 +155,7 @@ namespace hex::prv { createUndoPoint(); for (u64 i = 0; i < size; i++) - getPatches()[offset + i] = reinterpret_cast(buffer)[i]; + getPatches()[offset + i] = reinterpret_cast(buffer)[i]; } void Provider::createUndoPoint() { @@ -190,11 +190,9 @@ namespace hex::prv { } void Provider::drawLoadInterface() { - } void Provider::drawInterface() { - } } diff --git a/lib/libimhex/source/ui/imgui_imhex_extensions.cpp b/lib/libimhex/source/ui/imgui_imhex_extensions.cpp index 37d0d96a1..a811ec9bb 100644 --- a/lib/libimhex/source/ui/imgui_imhex_extensions.cpp +++ b/lib/libimhex/source/ui/imgui_imhex_extensions.cpp @@ -16,19 +16,19 @@ namespace ImGui { int UpdateStringSizeCallback(ImGuiInputTextCallbackData *data) { - auto &mathInput = *static_cast(data->UserData); + auto &mathInput = *static_cast(data->UserData); mathInput.resize(data->BufTextLen); return 0; } - bool IconHyperlink(const char *icon, const char* label, const ImVec2& size_arg, ImGuiButtonFlags flags) { - ImGuiWindow* window = GetCurrentWindow(); + bool IconHyperlink(const char *icon, const char *label, const ImVec2 &size_arg, ImGuiButtonFlags flags) { + ImGuiWindow *window = GetCurrentWindow(); if (window->SkipItems) return false; - ImGuiContext& g = *GImGui; - const ImGuiStyle& style = g.Style; + ImGuiContext &g = *GImGui; + const ImGuiStyle &style = g.Style; const ImGuiID id = window->GetID(label); ImVec2 label_size = CalcTextSize(icon, NULL, false); label_size.x += CalcTextSize(" ", NULL, false).x + CalcTextSize(label, NULL, false).x; @@ -57,13 +57,13 @@ namespace ImGui { return pressed; } - bool Hyperlink(const char* label, const ImVec2& size_arg, ImGuiButtonFlags flags) { - ImGuiWindow* window = GetCurrentWindow(); + bool Hyperlink(const char *label, const ImVec2 &size_arg, ImGuiButtonFlags flags) { + ImGuiWindow *window = GetCurrentWindow(); if (window->SkipItems) return false; - ImGuiContext& g = *GImGui; - const ImGuiStyle& style = g.Style; + ImGuiContext &g = *GImGui; + const ImGuiStyle &style = g.Style; const ImGuiID id = window->GetID(label); const ImVec2 label_size = CalcTextSize(label, NULL, true); @@ -82,7 +82,7 @@ namespace ImGui { // Render const ImU32 col = hovered ? GetColorU32(ImGuiCol_ButtonHovered) : GetColorU32(ImGuiCol_ButtonActive); PushStyleColor(ImGuiCol_Text, ImU32(col)); - TextEx(label, NULL, ImGuiTextFlags_NoWidthForLargeClippedText); // Skip formatting + TextEx(label, NULL, ImGuiTextFlags_NoWidthForLargeClippedText); // Skip formatting GetWindowDrawList()->AddLine(ImVec2(pos.x, pos.y + size.y), pos + size, ImU32(col)); PopStyleColor(); @@ -90,13 +90,13 @@ namespace ImGui { return pressed; } - bool BulletHyperlink(const char* label, const ImVec2& size_arg, ImGuiButtonFlags flags) { - ImGuiWindow* window = GetCurrentWindow(); + bool BulletHyperlink(const char *label, const ImVec2 &size_arg, ImGuiButtonFlags flags) { + ImGuiWindow *window = GetCurrentWindow(); if (window->SkipItems) return false; - ImGuiContext& g = *GImGui; - const ImGuiStyle& style = g.Style; + ImGuiContext &g = *GImGui; + const ImGuiStyle &style = g.Style; const ImGuiID id = window->GetID(label); const ImVec2 label_size = CalcTextSize(label, NULL, true); @@ -125,19 +125,19 @@ namespace ImGui { return pressed; } - bool DescriptionButton(const char* label, const char* description, const ImVec2& size_arg, ImGuiButtonFlags flags) { - ImGuiWindow* window = GetCurrentWindow(); + bool DescriptionButton(const char *label, const char *description, const ImVec2 &size_arg, ImGuiButtonFlags flags) { + ImGuiWindow *window = GetCurrentWindow(); if (window->SkipItems) return false; - ImGuiContext& g = *GImGui; - const ImGuiStyle& style = g.Style; + ImGuiContext &g = *GImGui; + const ImGuiStyle &style = g.Style; const ImGuiID id = window->GetID(label); const ImVec2 text_size = CalcTextSize((std::string(label) + "\n " + std::string(description)).c_str(), NULL, true); const ImVec2 label_size = CalcTextSize(label, NULL, true); ImVec2 pos = window->DC.CursorPos; - if ((flags & ImGuiButtonFlags_AlignTextBaseLine) && style.FramePadding.y < window->DC.CurrLineTextBaseOffset) // Try to vertically align buttons that are smaller/have no padding so that text baseline matches (bit hacky, since it shouldn't be a flag) + if ((flags & ImGuiButtonFlags_AlignTextBaseLine) && style.FramePadding.y < window->DC.CurrLineTextBaseOffset) // Try to vertically align buttons that are smaller/have no padding so that text baseline matches (bit hacky, since it shouldn't be a flag) pos.y += window->DC.CurrLineTextBaseOffset - style.FramePadding.y; ImVec2 size = CalcItemSize(size_arg, text_size.x + style.FramePadding.x * 4.0f, text_size.y + style.FramePadding.y * 4.0f); @@ -154,7 +154,8 @@ namespace ImGui { ImGui::PushStyleVar(ImGuiStyleVar_ButtonTextAlign, ImVec2(0.0, 0.5)); // Render - const ImU32 col = GetCustomColorU32((held && hovered) ? ImGuiCustomCol_DescButtonActive : hovered ? ImGuiCustomCol_DescButtonHovered : ImGuiCustomCol_DescButton); + const ImU32 col = GetCustomColorU32((held && hovered) ? ImGuiCustomCol_DescButtonActive : hovered ? ImGuiCustomCol_DescButtonHovered + : ImGuiCustomCol_DescButton); RenderNavHighlight(bb, id); RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding); PushStyleColor(ImGuiCol_Text, GetColorU32(ImGuiCol_ButtonActive)); @@ -167,15 +168,15 @@ namespace ImGui { ImGui::PopStyleVar(); // Automatically close popups - //if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup)) + // if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup)) // CloseCurrentPopup(); IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags); return pressed; } - void UnderlinedText(const char* label, ImColor color, const ImVec2& size_arg) { - ImGuiWindow* window = GetCurrentWindow(); + void UnderlinedText(const char *label, ImColor color, const ImVec2 &size_arg) { + ImGuiWindow *window = GetCurrentWindow(); const ImVec2 label_size = CalcTextSize(label, NULL, true); @@ -183,7 +184,7 @@ namespace ImGui { ImVec2 size = CalcItemSize(size_arg, label_size.x, label_size.y); PushStyleColor(ImGuiCol_Text, ImU32(color)); - TextEx(label, NULL, ImGuiTextFlags_NoWidthForLargeClippedText); // Skip formatting + TextEx(label, NULL, ImGuiTextFlags_NoWidthForLargeClippedText); // Skip formatting GetWindowDrawList()->AddLine(ImVec2(pos.x, pos.y + size.y), pos + size, ImU32(color)); PopStyleColor(); } @@ -196,10 +197,9 @@ namespace ImGui { } else { widgets(); } - } - void TextSpinner(const char* label) { + void TextSpinner(const char *label) { ImGui::Text("[%c] %s", "|/-\\"[ImU32(ImGui::GetTime() * 20) % 4], label); } @@ -237,78 +237,78 @@ namespace ImGui { } ImU32 GetCustomColorU32(ImGuiCustomCol idx, float alpha_mul) { - auto& customData = *static_cast(GImGui->IO.UserData); + auto &customData = *static_cast(GImGui->IO.UserData); ImVec4 c = customData.Colors[idx]; c.w *= GImGui->Style.Alpha * alpha_mul; return ColorConvertFloat4ToU32(c); } ImVec4 GetCustomColorVec4(ImGuiCustomCol idx, float alpha_mul) { - auto& customData = *static_cast(GImGui->IO.UserData); + auto &customData = *static_cast(GImGui->IO.UserData); ImVec4 c = customData.Colors[idx]; c.w *= GImGui->Style.Alpha * alpha_mul; return c; } void StyleCustomColorsDark() { - auto &colors = static_cast(GImGui->IO.UserData)->Colors; + auto &colors = static_cast(GImGui->IO.UserData)->Colors; - colors[ImGuiCustomCol_DescButton] = ImColor(20, 20, 20); - colors[ImGuiCustomCol_DescButtonHovered] = ImColor(40, 40, 40); - colors[ImGuiCustomCol_DescButtonActive] = ImColor(60, 60, 60); + colors[ImGuiCustomCol_DescButton] = ImColor(20, 20, 20); + colors[ImGuiCustomCol_DescButtonHovered] = ImColor(40, 40, 40); + colors[ImGuiCustomCol_DescButtonActive] = ImColor(60, 60, 60); - colors[ImGuiCustomCol_ToolbarGray] = ImColor(230, 230, 230); - colors[ImGuiCustomCol_ToolbarRed] = ImColor(231, 76, 60); - colors[ImGuiCustomCol_ToolbarYellow] = ImColor(241, 196, 15); - colors[ImGuiCustomCol_ToolbarGreen] = ImColor(56, 139, 66); - colors[ImGuiCustomCol_ToolbarBlue] = ImColor(6, 83, 155); - colors[ImGuiCustomCol_ToolbarPurple] = ImColor(103, 42, 120); - colors[ImGuiCustomCol_ToolbarBrown] = ImColor(219, 179, 119); + colors[ImGuiCustomCol_ToolbarGray] = ImColor(230, 230, 230); + colors[ImGuiCustomCol_ToolbarRed] = ImColor(231, 76, 60); + colors[ImGuiCustomCol_ToolbarYellow] = ImColor(241, 196, 15); + colors[ImGuiCustomCol_ToolbarGreen] = ImColor(56, 139, 66); + colors[ImGuiCustomCol_ToolbarBlue] = ImColor(6, 83, 155); + colors[ImGuiCustomCol_ToolbarPurple] = ImColor(103, 42, 120); + colors[ImGuiCustomCol_ToolbarBrown] = ImColor(219, 179, 119); - colors[ImGuiCustomCol_Highlight] = ImColor(77, 198, 155); + colors[ImGuiCustomCol_Highlight] = ImColor(77, 198, 155); } void StyleCustomColorsLight() { - auto &colors = static_cast(GImGui->IO.UserData)->Colors; + auto &colors = static_cast(GImGui->IO.UserData)->Colors; - colors[ImGuiCustomCol_DescButton] = ImColor(230, 230, 230); - colors[ImGuiCustomCol_DescButtonHovered] = ImColor(210, 210, 210); - colors[ImGuiCustomCol_DescButtonActive] = ImColor(190, 190, 190); + colors[ImGuiCustomCol_DescButton] = ImColor(230, 230, 230); + colors[ImGuiCustomCol_DescButtonHovered] = ImColor(210, 210, 210); + colors[ImGuiCustomCol_DescButtonActive] = ImColor(190, 190, 190); - colors[ImGuiCustomCol_ToolbarGray] = ImColor(25, 25, 25); - colors[ImGuiCustomCol_ToolbarRed] = ImColor(231, 76, 60); - colors[ImGuiCustomCol_ToolbarYellow] = ImColor(241, 196, 15); - colors[ImGuiCustomCol_ToolbarGreen] = ImColor(56, 139, 66); - colors[ImGuiCustomCol_ToolbarBlue] = ImColor(6, 83, 155); - colors[ImGuiCustomCol_ToolbarPurple] = ImColor(103, 42, 120); - colors[ImGuiCustomCol_ToolbarBrown] = ImColor(219, 179, 119); + colors[ImGuiCustomCol_ToolbarGray] = ImColor(25, 25, 25); + colors[ImGuiCustomCol_ToolbarRed] = ImColor(231, 76, 60); + colors[ImGuiCustomCol_ToolbarYellow] = ImColor(241, 196, 15); + colors[ImGuiCustomCol_ToolbarGreen] = ImColor(56, 139, 66); + colors[ImGuiCustomCol_ToolbarBlue] = ImColor(6, 83, 155); + colors[ImGuiCustomCol_ToolbarPurple] = ImColor(103, 42, 120); + colors[ImGuiCustomCol_ToolbarBrown] = ImColor(219, 179, 119); - colors[ImGuiCustomCol_Highlight] = ImColor(41, 151, 112); + colors[ImGuiCustomCol_Highlight] = ImColor(41, 151, 112); } void StyleCustomColorsClassic() { - auto &colors = static_cast(GImGui->IO.UserData)->Colors; + auto &colors = static_cast(GImGui->IO.UserData)->Colors; - colors[ImGuiCustomCol_DescButton] = ImColor(40, 40, 80); - colors[ImGuiCustomCol_DescButtonHovered] = ImColor(60, 60, 100); - colors[ImGuiCustomCol_DescButtonActive] = ImColor(80, 80, 120); + colors[ImGuiCustomCol_DescButton] = ImColor(40, 40, 80); + colors[ImGuiCustomCol_DescButtonHovered] = ImColor(60, 60, 100); + colors[ImGuiCustomCol_DescButtonActive] = ImColor(80, 80, 120); - colors[ImGuiCustomCol_ToolbarGray] = ImColor(230, 230, 230); - colors[ImGuiCustomCol_ToolbarRed] = ImColor(231, 76, 60); - colors[ImGuiCustomCol_ToolbarYellow] = ImColor(241, 196, 15); - colors[ImGuiCustomCol_ToolbarGreen] = ImColor(56, 139, 66); - colors[ImGuiCustomCol_ToolbarBlue] = ImColor(6, 83, 155); - colors[ImGuiCustomCol_ToolbarPurple] = ImColor(103, 42, 120); - colors[ImGuiCustomCol_ToolbarBrown] = ImColor(219, 179, 119); + colors[ImGuiCustomCol_ToolbarGray] = ImColor(230, 230, 230); + colors[ImGuiCustomCol_ToolbarRed] = ImColor(231, 76, 60); + colors[ImGuiCustomCol_ToolbarYellow] = ImColor(241, 196, 15); + colors[ImGuiCustomCol_ToolbarGreen] = ImColor(56, 139, 66); + colors[ImGuiCustomCol_ToolbarBlue] = ImColor(6, 83, 155); + colors[ImGuiCustomCol_ToolbarPurple] = ImColor(103, 42, 120); + colors[ImGuiCustomCol_ToolbarBrown] = ImColor(219, 179, 119); - colors[ImGuiCustomCol_Highlight] = ImColor(77, 198, 155); + colors[ImGuiCustomCol_Highlight] = ImColor(77, 198, 155); } Texture LoadImageFromPath(const char *path) { int imageWidth = 0; int imageHeight = 0; - unsigned char* imageData = stbi_load(path, &imageWidth, &imageHeight, nullptr, 4); + unsigned char *imageData = stbi_load(path, &imageWidth, &imageHeight, nullptr, 4); if (imageData == nullptr) return { nullptr, -1, -1 }; @@ -320,9 +320,9 @@ namespace ImGui { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - #if defined(GL_UNPACK_ROW_LENGTH) - glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); - #endif +#if defined(GL_UNPACK_ROW_LENGTH) + glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); +#endif glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, imageWidth, imageHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, imageData); stbi_image_free(imageData); @@ -334,7 +334,7 @@ namespace ImGui { int imageHeight = 0; - unsigned char* imageData = stbi_load_from_memory(buffer, size, &imageWidth, &imageHeight, nullptr, 4); + unsigned char *imageData = stbi_load_from_memory(buffer, size, &imageWidth, &imageHeight, nullptr, 4); if (imageData == nullptr) return { nullptr, -1, -1 }; @@ -345,9 +345,9 @@ namespace ImGui { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - #if defined(GL_UNPACK_ROW_LENGTH) +#if defined(GL_UNPACK_ROW_LENGTH) glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); - #endif +#endif glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, imageWidth, imageHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, imageData); stbi_image_free(imageData); @@ -372,13 +372,13 @@ namespace ImGui { } - bool TitleBarButton(const char* label, ImVec2 size_arg) { - ImGuiWindow* window = GetCurrentWindow(); + bool TitleBarButton(const char *label, ImVec2 size_arg) { + ImGuiWindow *window = GetCurrentWindow(); if (window->SkipItems) return false; - ImGuiContext& g = *GImGui; - const ImGuiStyle& style = g.Style; + ImGuiContext &g = *GImGui; + const ImGuiStyle &style = g.Style; const ImGuiID id = window->GetID(label); const ImVec2 label_size = CalcTextSize(label, NULL, true); @@ -395,28 +395,29 @@ namespace ImGui { bool pressed = ButtonBehavior(bb, id, &hovered, &held); // Render - const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); + const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered + : ImGuiCol_Button); RenderNavHighlight(bb, id); RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding); RenderTextClipped(bb.Min + style.FramePadding * ImVec2(1, 2), bb.Max - style.FramePadding, label, NULL, &label_size, style.ButtonTextAlign, &bb); // Automatically close popups - //if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup)) + // if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup)) // CloseCurrentPopup(); IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags); return pressed; } - bool ToolBarButton(const char* symbol, ImVec4 color) { - ImGuiWindow* window = GetCurrentWindow(); + bool ToolBarButton(const char *symbol, ImVec4 color) { + ImGuiWindow *window = GetCurrentWindow(); if (window->SkipItems) return false; color.w = 1.0F; - ImGuiContext& g = *GImGui; - const ImGuiStyle& style = g.Style; + ImGuiContext &g = *GImGui; + const ImGuiStyle &style = g.Style; const ImGuiID id = window->GetID(symbol); const ImVec2 label_size = CalcTextSize(symbol, NULL, true); @@ -435,7 +436,8 @@ namespace ImGui { PushStyleColor(ImGuiCol_Text, color); // Render - const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ScrollbarGrabActive : hovered ? ImGuiCol_ScrollbarGrabHovered : ImGuiCol_MenuBarBg); + const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ScrollbarGrabActive : hovered ? ImGuiCol_ScrollbarGrabHovered + : ImGuiCol_MenuBarBg); RenderNavHighlight(bb, id); RenderFrame(bb.Min, bb.Max, col, false, style.FrameRounding); RenderTextClipped(bb.Min + style.FramePadding * ImVec2(1, 2), bb.Max - style.FramePadding, symbol, NULL, &label_size, style.ButtonTextAlign, &bb); @@ -443,22 +445,22 @@ namespace ImGui { PopStyleColor(); // Automatically close popups - //if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup)) + // if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup)) // CloseCurrentPopup(); IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags); return pressed; } - bool IconButton(const char* symbol, ImVec4 color, ImVec2 size_arg) { - ImGuiWindow* window = GetCurrentWindow(); + bool IconButton(const char *symbol, ImVec4 color, ImVec2 size_arg) { + ImGuiWindow *window = GetCurrentWindow(); if (window->SkipItems) return false; color.w = 1.0F; - ImGuiContext& g = *GImGui; - const ImGuiStyle& style = g.Style; + ImGuiContext &g = *GImGui; + const ImGuiStyle &style = g.Style; const ImGuiID id = window->GetID(symbol); const ImVec2 label_size = CalcTextSize(symbol, NULL, true); @@ -477,7 +479,8 @@ namespace ImGui { PushStyleColor(ImGuiCol_Text, color); // Render - const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); + const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered + : ImGuiCol_Button); RenderNavHighlight(bb, id); RenderFrame(bb.Min, bb.Max, col, false, style.FrameRounding); RenderTextClipped(bb.Min + style.FramePadding * ImVec2(1, 2), bb.Max - style.FramePadding, symbol, NULL, &label_size, style.ButtonTextAlign, &bb); @@ -485,7 +488,7 @@ namespace ImGui { PopStyleColor(); // Automatically close popups - //if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup)) + // if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup)) // CloseCurrentPopup(); IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags); @@ -493,12 +496,12 @@ namespace ImGui { } void SmallProgressBar(float fraction, float yOffset) { - ImGuiWindow* window = GetCurrentWindow(); + ImGuiWindow *window = GetCurrentWindow(); if (window->SkipItems) return; - ImGuiContext& g = *GImGui; - const ImGuiStyle& style = g.Style; + ImGuiContext &g = *GImGui; + const ImGuiStyle &style = g.Style; ImVec2 pos = window->DC.CursorPos + ImVec2(0, yOffset); ImVec2 size = CalcItemSize(ImVec2(100, 5), 100, g.FontSize + style.FramePadding.y * 2.0f); diff --git a/lib/libimhex/source/views/view.cpp b/lib/libimhex/source/views/view.cpp index e55a7285a..0dedb50a2 100644 --- a/lib/libimhex/source/views/view.cpp +++ b/lib/libimhex/source/views/view.cpp @@ -16,7 +16,7 @@ namespace hex { return ImHexApi::Provider::isValid() && ImHexApi::Provider::get()->isAvailable(); } - std::vector>& View::getDeferedCalls() { + std::vector> &View::getDeferedCalls() { return SharedData::deferredCalls; } @@ -133,15 +133,15 @@ namespace hex { } - bool& View::getWindowOpenState() { + bool &View::getWindowOpenState() { return this->m_windowOpen; } - const bool& View::getWindowOpenState() const { + const bool &View::getWindowOpenState() const { return this->m_windowOpen; } - const std::string& View::getUnlocalizedName() const { + const std::string &View::getUnlocalizedName() const { return this->m_unlocalizedViewName; } diff --git a/main/include/helpers/plugin_manager.hpp b/main/include/helpers/plugin_manager.hpp index 17c34ed54..e06315e9c 100644 --- a/main/include/helpers/plugin_manager.hpp +++ b/main/include/helpers/plugin_manager.hpp @@ -14,7 +14,7 @@ namespace hex { class Plugin { public: explicit Plugin(const fs::path &path); - Plugin(const Plugin&) = delete; + Plugin(const Plugin &) = delete; Plugin(Plugin &&other) noexcept; ~Plugin(); @@ -25,28 +25,29 @@ namespace hex { [[nodiscard]] std::string getCompatibleVersion() const; void setImGuiContext(ImGuiContext *ctx) const; - [[nodiscard]] const fs::path& getPath() const; + [[nodiscard]] const fs::path &getPath() const; [[nodiscard]] bool isLoaded() const; + private: - using InitializePluginFunc = void(*)(); - using GetPluginNameFunc = const char*(*)(); - using GetPluginAuthorFunc = const char*(*)(); - using GetPluginDescriptionFunc = const char*(*)(); - using GetCompatibleVersionFunc = const char*(*)(); - using SetImGuiContextFunc = void(*)(ImGuiContext*); + using InitializePluginFunc = void (*)(); + using GetPluginNameFunc = const char *(*)(); + using GetPluginAuthorFunc = const char *(*)(); + using GetPluginDescriptionFunc = const char *(*)(); + using GetCompatibleVersionFunc = const char *(*)(); + using SetImGuiContextFunc = void (*)(ImGuiContext *); void *m_handle = nullptr; fs::path m_path; mutable bool m_initialized = false; - InitializePluginFunc m_initializePluginFunction = nullptr; - GetPluginNameFunc m_getPluginNameFunction = nullptr; - GetPluginAuthorFunc m_getPluginAuthorFunction = nullptr; - GetPluginDescriptionFunc m_getPluginDescriptionFunction = nullptr; - GetCompatibleVersionFunc m_getCompatibleVersionFunction = nullptr; - SetImGuiContextFunc m_setImGuiContextFunction = nullptr; + InitializePluginFunc m_initializePluginFunction = nullptr; + GetPluginNameFunc m_getPluginNameFunction = nullptr; + GetPluginAuthorFunc m_getPluginAuthorFunction = nullptr; + GetPluginDescriptionFunc m_getPluginDescriptionFunction = nullptr; + GetCompatibleVersionFunc m_getCompatibleVersionFunction = nullptr; + SetImGuiContextFunc m_setImGuiContextFunction = nullptr; template [[nodiscard]] auto getPluginFunction(const std::string &symbol) { @@ -54,7 +55,7 @@ namespace hex { } private: - [[nodiscard]] void* getPluginFunction(const std::string &symbol); + [[nodiscard]] void *getPluginFunction(const std::string &symbol); }; class PluginManager { @@ -65,7 +66,7 @@ namespace hex { static void unload(); static void reload(); - static const auto& getPlugins() { + static const auto &getPlugins() { return PluginManager::s_plugins; } diff --git a/main/include/init/tasks.hpp b/main/include/init/tasks.hpp index 6e37873a9..56c5c7bff 100644 --- a/main/include/init/tasks.hpp +++ b/main/include/init/tasks.hpp @@ -18,5 +18,5 @@ namespace hex::init { std::vector getInitTasks(); std::vector getExitTasks(); - std::vector& getInitArguments(); + std::vector &getInitArguments(); } \ No newline at end of file diff --git a/main/include/window.hpp b/main/include/window.hpp index 725929c09..77d02c38b 100644 --- a/main/include/window.hpp +++ b/main/include/window.hpp @@ -42,10 +42,10 @@ namespace hex { void exitImGui(); friend void *ImHexSettingsHandler_ReadOpenFn(ImGuiContext *ctx, ImGuiSettingsHandler *, const char *); - friend void ImHexSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler *handler, void *, const char* line); - friend void ImHexSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler *handler, ImGuiTextBuffer *buf); + friend void ImHexSettingsHandler_ReadLine(ImGuiContext *, ImGuiSettingsHandler *handler, void *, const char *line); + friend void ImHexSettingsHandler_WriteAll(ImGuiContext *ctx, ImGuiSettingsHandler *handler, ImGuiTextBuffer *buf); - GLFWwindow* m_window = nullptr; + GLFWwindow *m_window = nullptr; double m_targetFps = 60.0; bool m_layoutConfigured = false; diff --git a/main/source/helpers/plugin_manager.cpp b/main/source/helpers/plugin_manager.cpp index e42223ee6..3519b7a38 100644 --- a/main/source/helpers/plugin_manager.cpp +++ b/main/source/helpers/plugin_manager.cpp @@ -17,32 +17,32 @@ namespace hex { auto pluginName = fs::path(path).stem().string(); - this->m_initializePluginFunction = getPluginFunction("initializePlugin"); - this->m_getPluginNameFunction = getPluginFunction("getPluginName"); - this->m_getPluginAuthorFunction = getPluginFunction("getPluginAuthor"); - this->m_getPluginDescriptionFunction = getPluginFunction("getPluginDescription"); - this->m_getCompatibleVersionFunction = getPluginFunction("getCompatibleVersion"); - this->m_setImGuiContextFunction = getPluginFunction("setImGuiContext"); + this->m_initializePluginFunction = getPluginFunction("initializePlugin"); + this->m_getPluginNameFunction = getPluginFunction("getPluginName"); + this->m_getPluginAuthorFunction = getPluginFunction("getPluginAuthor"); + this->m_getPluginDescriptionFunction = getPluginFunction("getPluginDescription"); + this->m_getCompatibleVersionFunction = getPluginFunction("getCompatibleVersion"); + this->m_setImGuiContextFunction = getPluginFunction("setImGuiContext"); } Plugin::Plugin(Plugin &&other) noexcept { this->m_handle = other.m_handle; this->m_path = std::move(other.m_path); - this->m_initializePluginFunction = other.m_initializePluginFunction; - this->m_getPluginNameFunction = other.m_getPluginNameFunction; - this->m_getPluginAuthorFunction = other.m_getPluginAuthorFunction; - this->m_getPluginDescriptionFunction = other.m_getPluginDescriptionFunction; - this->m_getCompatibleVersionFunction = other.m_getCompatibleVersionFunction; - this->m_setImGuiContextFunction = other.m_setImGuiContextFunction; + this->m_initializePluginFunction = other.m_initializePluginFunction; + this->m_getPluginNameFunction = other.m_getPluginNameFunction; + this->m_getPluginAuthorFunction = other.m_getPluginAuthorFunction; + this->m_getPluginDescriptionFunction = other.m_getPluginDescriptionFunction; + this->m_getCompatibleVersionFunction = other.m_getCompatibleVersionFunction; + this->m_setImGuiContextFunction = other.m_setImGuiContextFunction; other.m_handle = nullptr; - other.m_initializePluginFunction = nullptr; - other.m_getPluginNameFunction = nullptr; - other.m_getPluginAuthorFunction = nullptr; - other.m_getPluginDescriptionFunction = nullptr; - other.m_getCompatibleVersionFunction = nullptr; - other.m_setImGuiContextFunction = nullptr; + other.m_initializePluginFunction = nullptr; + other.m_getPluginNameFunction = nullptr; + other.m_getPluginAuthorFunction = nullptr; + other.m_getPluginDescriptionFunction = nullptr; + other.m_getCompatibleVersionFunction = nullptr; + other.m_setImGuiContextFunction = nullptr; } Plugin::~Plugin() { @@ -100,7 +100,7 @@ namespace hex { this->m_setImGuiContextFunction(ctx); } - const fs::path& Plugin::getPath() const { + const fs::path &Plugin::getPath() const { return this->m_path; } @@ -109,7 +109,7 @@ namespace hex { } - void* Plugin::getPluginFunction(const std::string &symbol) { + void *Plugin::getPluginFunction(const std::string &symbol) { return dlsym(this->m_handle, symbol.c_str()); } @@ -120,7 +120,7 @@ namespace hex { PluginManager::s_pluginFolder = pluginFolder; - for (auto& pluginPath : fs::directory_iterator(pluginFolder)) { + for (auto &pluginPath : fs::directory_iterator(pluginFolder)) { if (pluginPath.is_regular_file() && pluginPath.path().extension() == ".hexplug") PluginManager::s_plugins.emplace_back(pluginPath.path().string()); } diff --git a/main/source/init/splash_window.cpp b/main/source/init/splash_window.cpp index 8f4a78f1f..0d0b414fd 100644 --- a/main/source/init/splash_window.cpp +++ b/main/source/init/splash_window.cpp @@ -69,7 +69,7 @@ namespace hex::init { bool WindowSplash::loop() { auto splash = romfs::get("splash.png"); - ImGui::Texture splashTexture = ImGui::LoadImageFromMemory(reinterpret_cast(splash.data()), splash.size()); + ImGui::Texture splashTexture = ImGui::LoadImageFromMemory(reinterpret_cast(splash.data()), splash.size()); if (splashTexture == nullptr) { log::fatal("Could not load splash screen image!"); @@ -98,15 +98,14 @@ namespace hex::init { drawList->AddText(ImVec2(15, 120) * scale, ImColor(0xFF, 0xFF, 0xFF, 0xFF), hex::format("WerWolv 2020 - {0}", &__DATE__[7]).c_str()); - #if defined(DEBUG) - drawList->AddText(ImVec2(15, 140) * scale, ImColor(0xFF, 0xFF, 0xFF, 0xFF), hex::format("{0} : {1} {2}@{3}", IMHEX_VERSION, ICON_FA_CODE_BRANCH, GIT_BRANCH, GIT_COMMIT_HASH).c_str()); - #else - drawList->AddText(ImVec2(15, 140) * scale, ImColor(0xFF, 0xFF, 0xFF, 0xFF), hex::format("{0}", IMHEX_VERSION).c_str()); - #endif +#if defined(DEBUG) + drawList->AddText(ImVec2(15, 140) * scale, ImColor(0xFF, 0xFF, 0xFF, 0xFF), hex::format("{0} : {1} {2}@{3}", IMHEX_VERSION, ICON_FA_CODE_BRANCH, GIT_BRANCH, GIT_COMMIT_HASH).c_str()); +#else + drawList->AddText(ImVec2(15, 140) * scale, ImColor(0xFF, 0xFF, 0xFF, 0xFF), hex::format("{0}", IMHEX_VERSION).c_str()); +#endif drawList->AddRectFilled(ImVec2(0, splashTexture.size().y - 5) * scale, ImVec2(splashTexture.size().x * this->m_progress, splashTexture.size().y) * scale, 0xFFFFFFFF); - drawList->AddText(ImVec2(15, splashTexture.size().y - 25) * scale, ImColor(0xFF, 0xFF, 0xFF, 0xFF), - hex::format("[{}] {}", "|/-\\"[ImU32(ImGui::GetTime() * 15) % 4], this->m_currTaskName).c_str()); + drawList->AddText(ImVec2(15, splashTexture.size().y - 25) * scale, ImColor(0xFF, 0xFF, 0xFF, 0xFF), hex::format("[{}] {}", "|/-\\"[ImU32(ImGui::GetTime() * 15) % 4], this->m_currTaskName).c_str()); } ImGui::Render(); @@ -171,12 +170,12 @@ namespace hex::init { SharedData::globalScale = SharedData::fontScale = std::midpoint(xScale, yScale); - // On Macs with a retina display (basically all modern ones we care about), the OS reports twice - // the actual monitor scale for some obscure reason. Get rid of this here so ImHex doesn't look - // extremely huge with native scaling on MacOS. - #if defined(OS_MACOS) - SharedData::globalScale /= 2; - #endif +// On Macs with a retina display (basically all modern ones we care about), the OS reports twice +// the actual monitor scale for some obscure reason. Get rid of this here so ImHex doesn't look +// extremely huge with native scaling on MacOS. +#if defined(OS_MACOS) + SharedData::globalScale /= 2; +#endif if (SharedData::globalScale <= 0) { SharedData::globalScale = 1.0; @@ -217,8 +216,7 @@ namespace hex::init { cfg.MergeMode = true; ImWchar fontAwesomeRange[] = { - ICON_MIN_FA, ICON_MAX_FA, - 0 + ICON_MIN_FA, ICON_MAX_FA, 0 }; std::uint8_t *px; int w, h; diff --git a/main/source/init/tasks.cpp b/main/source/init/tasks.cpp index 848bbec1e..0d072a158 100644 --- a/main/source/init/tasks.cpp +++ b/main/source/init/tasks.cpp @@ -83,7 +83,7 @@ namespace hex::init { } if (!result) - getInitArguments().push_back({ "folder-creation-error", { } }); + getInitArguments().push_back({ "folder-creation-error", {} }); return result; } @@ -93,7 +93,7 @@ namespace hex::init { auto &cfg = SharedData::fontConfig; fonts = IM_NEW(ImFontAtlas)(); - cfg = { }; + cfg = {}; fs::path fontFile; for (const auto &dir : hex::getPath(ImHexPath::Resources)) { @@ -120,18 +120,15 @@ namespace hex::init { } ImWchar fontAwesomeRange[] = { - ICON_MIN_FA, ICON_MAX_FA, - 0 + ICON_MIN_FA, ICON_MAX_FA, 0 }; ImWchar codiconsRange[] = { - ICON_MIN_VS, ICON_MAX_VS, - 0 + ICON_MIN_VS, ICON_MAX_VS, 0 }; ImWchar unifontRange[] = { - 0x0020, 0xFFF0, - 0 + 0x0020, 0xFFF0, 0 }; @@ -151,7 +148,7 @@ namespace hex::init { cfg.OversampleH = cfg.OversampleV = 1, cfg.PixelSnapH = true; cfg.SizePixels = fontSize * SharedData::fontScale; - fonts->AddFontFromFileTTF(fontFile.string().c_str(), std::floor(fontSize * SharedData::fontScale), &cfg, ranges.Data); // Needs conversion to char for Windows + fonts->AddFontFromFileTTF(fontFile.string().c_str(), std::floor(fontSize * SharedData::fontScale), &cfg, ranges.Data); // Needs conversion to char for Windows } cfg.MergeMode = true; @@ -224,7 +221,7 @@ namespace hex::init { if (PluginManager::getPlugins().empty()) { log::error("No plugins found!"); - getInitArguments().push_back({ "no-plugins", { } }); + getInitArguments().push_back({ "no-plugins", {} }); return false; } @@ -251,22 +248,22 @@ namespace hex::init { } switch (ContentRegistry::Settings::read("hex.builtin.setting.interface", "hex.builtin.setting.interface.scaling", 0)) { - default: - case 0: - // Native scaling - break; - case 1: - SharedData::globalScale = SharedData::fontScale = 0.5F; - break; - case 2: - SharedData::globalScale = SharedData::fontScale = 1.0F; - break; - case 3: - SharedData::globalScale = SharedData::fontScale = 1.5F; - break; - case 4: - SharedData::globalScale = SharedData::fontScale = 2.0F; - break; + default: + case 0: + // Native scaling + break; + case 1: + SharedData::globalScale = SharedData::fontScale = 0.5F; + break; + case 2: + SharedData::globalScale = SharedData::fontScale = 1.0F; + break; + case 3: + SharedData::globalScale = SharedData::fontScale = 1.5F; + break; + case 4: + SharedData::globalScale = SharedData::fontScale = 2.0F; + break; } return true; @@ -284,24 +281,24 @@ namespace hex::init { std::vector getInitTasks() { return { - { "Checking for updates...", checkForUpdates }, - { "Downloading information...", downloadInformation }, - { "Creating directories...", createDirectories }, - { "Loading settings...", loadSettings }, - { "Loading plugins...", loadPlugins }, - { "Loading fonts...", loadFonts }, + {"Checking for updates...", checkForUpdates }, + { "Downloading information...", downloadInformation}, + { "Creating directories...", createDirectories }, + { "Loading settings...", loadSettings }, + { "Loading plugins...", loadPlugins }, + { "Loading fonts...", loadFonts }, }; } std::vector getExitTasks() { return { - { "Saving settings...", storeSettings }, - { "Cleaning up shared data...", deleteSharedData }, - { "Unloading plugins...", unloadPlugins }, + {"Saving settings...", storeSettings }, + { "Cleaning up shared data...", deleteSharedData}, + { "Unloading plugins...", unloadPlugins }, }; } - std::vector& getInitArguments() { + std::vector &getInitArguments() { static std::vector initArguments; return initArguments; diff --git a/main/source/main.cpp b/main/source/main.cpp index 553b45a12..9134e127d 100644 --- a/main/source/main.cpp +++ b/main/source/main.cpp @@ -30,7 +30,7 @@ int main(int argc, char **argv, char **envp) { splashWindow.addStartupTask(name, task); if (!splashWindow.loop()) - init::getInitArguments().push_back({ "tasks-failed", { } }); + init::getInitArguments().push_back({ "tasks-failed", {} }); } // Clean up @@ -44,7 +44,7 @@ int main(int argc, char **argv, char **envp) { Window window; if (argc == 1) - ; // No arguments provided + ; // No arguments provided else if (argc == 2) EventManager::post(argv[1]); else { diff --git a/main/source/window/linux_window.cpp b/main/source/window/linux_window.cpp index 5f9b9e5e9..155ac05de 100644 --- a/main/source/window/linux_window.cpp +++ b/main/source/window/linux_window.cpp @@ -9,51 +9,48 @@ #include #include - namespace hex { +namespace hex { - void Window::initNative() { - if (!isatty(STDOUT_FILENO)) { - log::redirectToFile(); - } + void Window::initNative() { + if (!isatty(STDOUT_FILENO)) { + log::redirectToFile(); } - - void Window::setupNativeWindow() { - bool themeFollowSystem = ContentRegistry::Settings::getSetting("hex.builtin.setting.interface", "hex.builtin.setting.interface.color") == 0; - EventManager::subscribe(this, [themeFollowSystem]{ - if (!themeFollowSystem) return; - - std::array buffer = { 0 }; - std::string result; - - // TODO: In the future maybe support more DEs instead of just GNOME - FILE* pipe = popen("gsettings get org.gnome.desktop.interface gtk-theme 2>&1", "r"); - if (pipe == nullptr) return; - - while (fgets(buffer.data(), buffer.size(), pipe) != nullptr) - result += buffer.data(); - - auto exitCode = WEXITSTATUS(pclose(pipe)); - if (exitCode != 0) return; - - EventManager::post(hex::containsIgnoreCase(result, "dark") ? 1 : 2); - }); - - if (themeFollowSystem) - EventManager::post(); - } - - void Window::beginNativeWindowFrame() { - - } - - void Window::endNativeWindowFrame() { - - } - - void Window::drawTitleBar() { - - } - } + void Window::setupNativeWindow() { + bool themeFollowSystem = ContentRegistry::Settings::getSetting("hex.builtin.setting.interface", "hex.builtin.setting.interface.color") == 0; + EventManager::subscribe(this, [themeFollowSystem] { + if (!themeFollowSystem) return; + + std::array buffer = { 0 }; + std::string result; + + // TODO: In the future maybe support more DEs instead of just GNOME + FILE *pipe = popen("gsettings get org.gnome.desktop.interface gtk-theme 2>&1", "r"); + if (pipe == nullptr) return; + + while (fgets(buffer.data(), buffer.size(), pipe) != nullptr) + result += buffer.data(); + + auto exitCode = WEXITSTATUS(pclose(pipe)); + if (exitCode != 0) return; + + EventManager::post(hex::containsIgnoreCase(result, "dark") ? 1 : 2); + }); + + if (themeFollowSystem) + EventManager::post(); + } + + void Window::beginNativeWindowFrame() { + } + + void Window::endNativeWindowFrame() { + } + + void Window::drawTitleBar() { + } + +} + #endif \ No newline at end of file diff --git a/main/source/window/macos_window.cpp b/main/source/window/macos_window.cpp index 2e1fec93d..f1acfc929 100644 --- a/main/source/window/macos_window.cpp +++ b/main/source/window/macos_window.cpp @@ -7,39 +7,36 @@ #include #include - namespace hex { +namespace hex { - void Window::initNative() { - if (!isatty(STDOUT_FILENO)) { - log::redirectToFile(); - } + void Window::initNative() { + if (!isatty(STDOUT_FILENO)) { + log::redirectToFile(); } - - void Window::setupNativeWindow() { - bool themeFollowSystem = ContentRegistry::Settings::getSetting("hex.builtin.setting.interface", "hex.builtin.setting.interface.color") == 0; - EventManager::subscribe(this, [themeFollowSystem]{ - if (!themeFollowSystem) return; - - // TODO: Implement this when MacOS build is working again - EventManager::post(1); - }); - - if (themeFollowSystem) - EventManager::post(); - } - - void Window::beginNativeWindowFrame() { - - } - - void Window::endNativeWindowFrame() { - - } - - void Window::drawTitleBar() { - - } - } + void Window::setupNativeWindow() { + bool themeFollowSystem = ContentRegistry::Settings::getSetting("hex.builtin.setting.interface", "hex.builtin.setting.interface.color") == 0; + EventManager::subscribe(this, [themeFollowSystem] { + if (!themeFollowSystem) return; + + // TODO: Implement this when MacOS build is working again + EventManager::post(1); + }); + + if (themeFollowSystem) + EventManager::post(); + } + + void Window::beginNativeWindowFrame() { + } + + void Window::endNativeWindowFrame() { + } + + void Window::drawTitleBar() { + } + +} + #endif \ No newline at end of file diff --git a/main/source/window/win_window.cpp b/main/source/window/win_window.cpp index 504253fd5..8b471b04f 100644 --- a/main/source/window/win_window.cpp +++ b/main/source/window/win_window.cpp @@ -21,349 +21,354 @@ #include #include - namespace hex { +namespace hex { - static LONG_PTR g_oldWndProc; - static float g_titleBarHeight; - static ImGuiMouseCursor g_mouseCursorIcon; - static BOOL g_compositionEnabled = false; + static LONG_PTR g_oldWndProc; + static float g_titleBarHeight; + static ImGuiMouseCursor g_mouseCursorIcon; + static BOOL g_compositionEnabled = false; - static LRESULT windowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { - switch (uMsg) { - case WM_NCACTIVATE: - case WM_NCPAINT: - return DefWindowProcW(hwnd, uMsg, wParam, lParam); - case WM_NCCALCSIZE: { - RECT &rect = *reinterpret_cast(lParam); - RECT client = rect; + static LRESULT windowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { + switch (uMsg) { + case WM_NCACTIVATE: + case WM_NCPAINT: + return DefWindowProcW(hwnd, uMsg, wParam, lParam); + case WM_NCCALCSIZE: + { + RECT &rect = *reinterpret_cast(lParam); + RECT client = rect; - CallWindowProc((WNDPROC)g_oldWndProc, hwnd, uMsg, wParam, lParam); + CallWindowProc((WNDPROC)g_oldWndProc, hwnd, uMsg, wParam, lParam); - if (IsMaximized(hwnd)) { - WINDOWINFO windowInfo = { .cbSize = sizeof(WINDOWINFO) }; - GetWindowInfo(hwnd, &windowInfo); - rect = RECT { - .left = static_cast(client.left + windowInfo.cyWindowBorders), - .top = static_cast(client.top + windowInfo.cyWindowBorders), - .right = static_cast(client.right - windowInfo.cyWindowBorders), - .bottom = static_cast(client.bottom - windowInfo.cyWindowBorders) + 1 - }; - } else { - rect = client; - } - - return 0; + if (IsMaximized(hwnd)) { + WINDOWINFO windowInfo = { .cbSize = sizeof(WINDOWINFO) }; + GetWindowInfo(hwnd, &windowInfo); + rect = RECT { + .left = static_cast(client.left + windowInfo.cyWindowBorders), + .top = static_cast(client.top + windowInfo.cyWindowBorders), + .right = static_cast(client.right - windowInfo.cyWindowBorders), + .bottom = static_cast(client.bottom - windowInfo.cyWindowBorders) + 1 + }; + } else { + rect = client; } - case WM_SETCURSOR: { - auto cursorPos = LOWORD(lParam); - switch (cursorPos) { - case HTRIGHT: - case HTLEFT: - g_mouseCursorIcon = ImGuiMouseCursor_ResizeEW; - break; - case HTTOP: - case HTBOTTOM: - g_mouseCursorIcon = ImGuiMouseCursor_ResizeNS; - break; - case HTTOPLEFT: - case HTBOTTOMRIGHT: - g_mouseCursorIcon = ImGuiMouseCursor_ResizeNWSE; - break; - case HTTOPRIGHT: - case HTBOTTOMLEFT: - g_mouseCursorIcon = ImGuiMouseCursor_ResizeNESW; - break; - case HTCAPTION: - case HTCLIENT: - g_mouseCursorIcon = ImGuiMouseCursor_None; - break; + return 0; + } + case WM_SETCURSOR: + { + auto cursorPos = LOWORD(lParam); + + switch (cursorPos) { + case HTRIGHT: + case HTLEFT: + g_mouseCursorIcon = ImGuiMouseCursor_ResizeEW; + break; + case HTTOP: + case HTBOTTOM: + g_mouseCursorIcon = ImGuiMouseCursor_ResizeNS; + break; + case HTTOPLEFT: + case HTBOTTOMRIGHT: + g_mouseCursorIcon = ImGuiMouseCursor_ResizeNWSE; + break; + case HTTOPRIGHT: + case HTBOTTOMLEFT: + g_mouseCursorIcon = ImGuiMouseCursor_ResizeNESW; + break; + case HTCAPTION: + case HTCLIENT: + g_mouseCursorIcon = ImGuiMouseCursor_None; + break; + } + + return TRUE; + } + case WM_NCHITTEST: + { + POINT cursor = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) }; + + const POINT border { + static_cast((::GetSystemMetrics(SM_CXFRAME) + ::GetSystemMetrics(SM_CXPADDEDBORDER)) * SharedData::globalScale / 1.5F), + static_cast((::GetSystemMetrics(SM_CYFRAME) + ::GetSystemMetrics(SM_CXPADDEDBORDER)) * SharedData::globalScale / 1.5F) + }; + + RECT window; + if (!::GetWindowRect(hwnd, &window)) { + return HTNOWHERE; + } + + constexpr auto RegionClient = 0b0000; + constexpr auto RegionLeft = 0b0001; + constexpr auto RegionRight = 0b0010; + constexpr auto RegionTop = 0b0100; + constexpr auto RegionBottom = 0b1000; + + const auto result = + RegionLeft * (cursor.x < (window.left + border.x)) | + RegionRight * (cursor.x >= (window.right - border.x)) | + RegionTop * (cursor.y < (window.top + border.y)) | + RegionBottom * (cursor.y >= (window.bottom - border.y)); + + if (result != 0 && (ImGui::IsItemHovered() || ImGui::IsPopupOpen(nullptr, ImGuiPopupFlags_AnyPopupId))) + break; + + switch (result) { + case RegionLeft: + return HTLEFT; + case RegionRight: + return HTRIGHT; + case RegionTop: + return HTTOP; + case RegionBottom: + return HTBOTTOM; + case RegionTop | RegionLeft: + return HTTOPLEFT; + case RegionTop | RegionRight: + return HTTOPRIGHT; + case RegionBottom | RegionLeft: + return HTBOTTOMLEFT; + case RegionBottom | RegionRight: + return HTBOTTOMRIGHT; + case RegionClient: + default: + if ((cursor.y < (window.top + g_titleBarHeight * 2)) && !(ImGui::IsAnyItemHovered() || ImGui::IsPopupOpen(nullptr, ImGuiPopupFlags_AnyPopupId))) + return HTCAPTION; + else break; + } + break; + } + case WM_SETTINGCHANGE: + { + if (lParam == 0) break; + + if (LPCTSTR(lParam) == std::string_view("ImmersiveColorSet")) { + EventManager::post(); + } + + break; + } + case WM_COPYDATA: + { + auto message = reinterpret_cast(lParam); + if (message == nullptr) break; + + auto path = reinterpret_cast(message->lpData); + if (path == nullptr) break; + + log::info("Opening file in existing instance: {}", path); + EventManager::post(path); + break; + } + + default: + break; + } + + return CallWindowProc((WNDPROC)g_oldWndProc, hwnd, uMsg, wParam, lParam); + } + + + void Window::initNative() { + // Attach to parent console if one exists + if (AttachConsole(ATTACH_PARENT_PROCESS)) { + + // Redirect cin, cout and cerr to that console + freopen("CONIN$", "r", stdin); + freopen("CONOUT$", "w", stdout); + freopen("CONOUT$", "w", stderr); + setvbuf(stdin, nullptr, _IONBF, 0); + setvbuf(stdout, nullptr, _IONBF, 0); + setvbuf(stderr, nullptr, _IONBF, 0); + + fmt::print("\n"); + + // Enable color format specifiers in console + { + auto hConsole = ::GetStdHandle(STD_OUTPUT_HANDLE); + if (hConsole != INVALID_HANDLE_VALUE) { + DWORD mode = 0; + if (::GetConsoleMode(hConsole, &mode)) { + mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING | ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT; + ::SetConsoleMode(hConsole, mode); + } + } + } + } else { + log::redirectToFile(); + } + + // Open new files in already existing ImHex instance + constexpr static auto UniqueMutexId = "ImHex/a477ea68-e334-4d07-a439-4f159c683763"; + + HANDLE globalMutex = OpenMutex(MUTEX_ALL_ACCESS, FALSE, UniqueMutexId); + if (!globalMutex) { + globalMutex = CreateMutex(nullptr, FALSE, UniqueMutexId); + } else { + if (SharedData::mainArgc > 1) { + ::EnumWindows([](HWND hWnd, LPARAM lparam) -> BOOL { + auto length = ::GetWindowTextLength(hWnd); + std::string windowName(length + 1, '\x00'); + ::GetWindowText(hWnd, windowName.data(), windowName.size()); + + if (::IsWindowVisible(hWnd) && length != 0) { + if (windowName.starts_with("ImHex")) { + COPYDATASTRUCT message = { + .dwData = 0, + .cbData = static_cast(std::strlen(SharedData::mainArgv[1])) + 1, + .lpData = SharedData::mainArgv[1] + }; + + SendMessage(hWnd, WM_COPYDATA, reinterpret_cast(hWnd), reinterpret_cast(&message)); + + return FALSE; + } } return TRUE; - } - case WM_NCHITTEST: { - POINT cursor = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) }; + }, + 0); - const POINT border{ - static_cast((::GetSystemMetrics(SM_CXFRAME) + ::GetSystemMetrics(SM_CXPADDEDBORDER)) * SharedData::globalScale / 1.5F), - static_cast((::GetSystemMetrics(SM_CYFRAME) + ::GetSystemMetrics(SM_CXPADDEDBORDER)) * SharedData::globalScale / 1.5F) - }; - - RECT window; - if (!::GetWindowRect(hwnd, &window)) { - return HTNOWHERE; - } - - constexpr auto RegionClient = 0b0000; - constexpr auto RegionLeft = 0b0001; - constexpr auto RegionRight = 0b0010; - constexpr auto RegionTop = 0b0100; - constexpr auto RegionBottom = 0b1000; - - const auto result = - RegionLeft * (cursor.x < (window.left + border.x)) | - RegionRight * (cursor.x >= (window.right - border.x)) | - RegionTop * (cursor.y < (window.top + border.y)) | - RegionBottom * (cursor.y >= (window.bottom - border.y)); - - if (result != 0 && (ImGui::IsItemHovered() || ImGui::IsPopupOpen(nullptr, ImGuiPopupFlags_AnyPopupId))) - break; - - switch (result) { - case RegionLeft: - return HTLEFT; - case RegionRight: - return HTRIGHT; - case RegionTop: - return HTTOP; - case RegionBottom: - return HTBOTTOM; - case RegionTop | RegionLeft: - return HTTOPLEFT; - case RegionTop | RegionRight: - return HTTOPRIGHT; - case RegionBottom | RegionLeft: - return HTBOTTOMLEFT; - case RegionBottom | RegionRight: - return HTBOTTOMRIGHT; - case RegionClient: - default: - if ((cursor.y < (window.top + g_titleBarHeight * 2)) && !(ImGui::IsAnyItemHovered() || ImGui::IsPopupOpen(nullptr, ImGuiPopupFlags_AnyPopupId))) - return HTCAPTION; - else break; - } - break; - } - case WM_SETTINGCHANGE: - { - if (lParam == 0) break; - - if (LPCTSTR(lParam) == std::string_view("ImmersiveColorSet")) { - EventManager::post(); - } - - break; - } - case WM_COPYDATA: - { - auto message = reinterpret_cast(lParam); - if (message == nullptr) break; - - auto path = reinterpret_cast(message->lpData); - if (path == nullptr) break; - - log::info("Opening file in existing instance: {}", path); - EventManager::post(path); - break; - } - - default: break; - } - - return CallWindowProc((WNDPROC)g_oldWndProc, hwnd, uMsg, wParam, lParam); - } - - - void Window::initNative() { - // Attach to parent console if one exists - if (AttachConsole(ATTACH_PARENT_PROCESS)) { - - // Redirect cin, cout and cerr to that console - freopen("CONIN$", "r", stdin); - freopen("CONOUT$", "w", stdout); - freopen("CONOUT$", "w", stderr); - setvbuf(stdin, nullptr, _IONBF, 0); - setvbuf(stdout, nullptr, _IONBF, 0); - setvbuf(stderr, nullptr, _IONBF, 0); - - fmt::print("\n"); - - // Enable color format specifiers in console - { - auto hConsole = ::GetStdHandle(STD_OUTPUT_HANDLE); - if (hConsole != INVALID_HANDLE_VALUE) { - DWORD mode = 0; - if (::GetConsoleMode(hConsole, &mode)) { - mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING | ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT; - ::SetConsoleMode(hConsole, mode); - } - } - } - } else { - log::redirectToFile(); - } - - // Open new files in already existing ImHex instance - constexpr static auto UniqueMutexId = "ImHex/a477ea68-e334-4d07-a439-4f159c683763"; - - HANDLE globalMutex = OpenMutex(MUTEX_ALL_ACCESS, FALSE, UniqueMutexId); - if (!globalMutex) { - globalMutex = CreateMutex(nullptr, FALSE, UniqueMutexId); - } else { - if (SharedData::mainArgc > 1) { - ::EnumWindows([](HWND hWnd, LPARAM lparam) -> BOOL { - auto length = ::GetWindowTextLength(hWnd); - std::string windowName(length + 1, '\x00'); - ::GetWindowText(hWnd, windowName.data(), windowName.size()); - - if (::IsWindowVisible(hWnd) && length != 0) { - if (windowName.starts_with("ImHex")) { - COPYDATASTRUCT message = { - .dwData = 0, - .cbData = static_cast(std::strlen(SharedData::mainArgv[1])) + 1, - .lpData = SharedData::mainArgv[1] - }; - - SendMessage(hWnd, WM_COPYDATA, reinterpret_cast(hWnd), reinterpret_cast(&message)); - - return FALSE; - } - } - - return TRUE; - }, 0); - - std::exit(0); - } + std::exit(0); } } - - void Window::setupNativeWindow() { - // Setup borderless window - auto hwnd = glfwGetWin32Window(this->m_window); - - g_oldWndProc = ::SetWindowLongPtr(hwnd, GWLP_WNDPROC, (LONG_PTR)windowProc); - - MARGINS borderless = { 1, 1, 1, 1 }; - ::DwmExtendFrameIntoClientArea(hwnd, &borderless); - - DWORD attribute = DWMNCRP_ENABLED; - ::DwmSetWindowAttribute(hwnd, DWMWA_NCRENDERING_POLICY, &attribute, sizeof(attribute)); - - ::SetWindowPos(hwnd, nullptr, 0, 0, 0, 0, SWP_NOZORDER | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSIZE | SWP_NOMOVE); - ::SetWindowLong(hwnd, GWL_STYLE, GetWindowLong(hwnd, GWL_STYLE) | WS_OVERLAPPEDWINDOW); - - // Setup system theme change detector - bool themeFollowSystem = ContentRegistry::Settings::getSetting("hex.builtin.setting.interface", "hex.builtin.setting.interface.color") == 0; - EventManager::subscribe(this, [themeFollowSystem]{ - if (!themeFollowSystem) return; - - HKEY hkey; - if (RegOpenKey(HKEY_CURRENT_USER, R"(Software\Microsoft\Windows\CurrentVersion\Themes\Personalize)", &hkey) == ERROR_SUCCESS) { - DWORD value = 0; - DWORD size = sizeof(DWORD); - - auto error = RegQueryValueEx(hkey, "AppsUseLightTheme", nullptr, nullptr, reinterpret_cast(&value), &size); - if (error == ERROR_SUCCESS) { - EventManager::post(value == 0 ? 1 : 2); - } - } - }); - - if (themeFollowSystem) - EventManager::post(); - } - - void Window::beginNativeWindowFrame() { - g_titleBarHeight = ImGui::GetCurrentWindow()->MenuBarHeight(); - } - - void Window::endNativeWindowFrame() { - if (g_mouseCursorIcon != ImGuiMouseCursor_None) { - ImGui::SetMouseCursor(g_mouseCursorIcon); - } - - switch (ImGui::GetMouseCursor()) { - case ImGuiMouseCursor_Arrow: - SetCursor(LoadCursor(nullptr, IDC_ARROW)); - break; - case ImGuiMouseCursor_Hand: - SetCursor(LoadCursor(nullptr, IDC_HAND)); - break; - case ImGuiMouseCursor_ResizeEW: - SetCursor(LoadCursor(nullptr, IDC_SIZEWE)); - break; - case ImGuiMouseCursor_ResizeNS: - SetCursor(LoadCursor(nullptr, IDC_SIZENS)); - break; - case ImGuiMouseCursor_ResizeNWSE: - SetCursor(LoadCursor(nullptr, IDC_SIZENWSE)); - break; - case ImGuiMouseCursor_ResizeNESW: - SetCursor(LoadCursor(nullptr, IDC_SIZENESW)); - break; - case ImGuiMouseCursor_ResizeAll: - SetCursor(LoadCursor(nullptr, IDC_SIZEALL)); - break; - case ImGuiMouseCursor_NotAllowed: - SetCursor(LoadCursor(nullptr, IDC_NO)); - break; - case ImGuiMouseCursor_TextInput: - SetCursor(LoadCursor(nullptr, IDC_IBEAM)); - break; - default: - case ImGuiMouseCursor_None: - SetCursor(LoadCursor(nullptr, IDC_ARROW)); - break; - } - } - - void Window::drawTitleBar() { - auto buttonSize = ImVec2(g_titleBarHeight * 1.5F, g_titleBarHeight - 1); - - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0)); - ImGui::PushStyleColor(ImGuiCol_Button, ImGui::GetColorU32(ImGuiCol_MenuBarBg)); - ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImGui::GetColorU32(ImGuiCol_ScrollbarGrabActive)); - ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImGui::GetColorU32(ImGuiCol_ScrollbarGrabHovered)); - - ImGui::SetCursorPosX(ImGui::GetWindowWidth() - buttonSize.x * 6); - #if defined(DEBUG) - if (ImGui::TitleBarButton(ICON_VS_DEBUG, buttonSize)) { - if (ImGui::GetIO().KeyCtrl) { - // Explicitly trigger a segfault by writing to an invalid memory location - // Used for debugging crashes - *reinterpret_cast(0x10) = 0x10; - } else if (ImGui::GetIO().KeyShift) { - // Explicitly trigger an abort by throwing an uncaught exception - // Used for debugging exception errors - throw std::runtime_error("Debug Error"); - } else { - hex::openWebpage("https://imhex.werwolv.net/debug"); - } - } - ImGui::InfoTooltip("hex.menu.debug_build"_lang); - #endif - if (ImGui::TitleBarButton(ICON_VS_SMILEY, buttonSize)) - hex::openWebpage("mailto://hey@werwolv.net"); - ImGui::InfoTooltip("hex.menu.feedback"_lang); - - ImGui::SetCursorPosX(ImGui::GetWindowWidth() - buttonSize.x * 3); - if (ImGui::TitleBarButton(ICON_VS_CHROME_MINIMIZE, buttonSize)) - glfwIconifyWindow(this->m_window); - if (glfwGetWindowAttrib(this->m_window, GLFW_MAXIMIZED)) { - if (ImGui::TitleBarButton(ICON_VS_CHROME_RESTORE, buttonSize)) - glfwRestoreWindow(this->m_window); - } else { - if (ImGui::TitleBarButton(ICON_VS_CHROME_MAXIMIZE, buttonSize)) - glfwMaximizeWindow(this->m_window); - } - - ImGui::PushStyleColor(ImGuiCol_ButtonActive, 0xFF7A70F1); - ImGui::PushStyleColor(ImGuiCol_ButtonHovered, 0xFF2311E8); - - - if (ImGui::TitleBarButton(ICON_VS_CHROME_CLOSE, buttonSize)) { - ImHexApi::Common::closeImHex(); - } - - ImGui::PopStyleColor(5); - ImGui::PopStyleVar(); - - ImGui::SetCursorPosX((ImGui::GetWindowWidth() - ImGui::CalcTextSize(this->m_windowTitle.c_str()).x) / 2); - ImGui::TextUnformatted(this->m_windowTitle.c_str()); - } - } + void Window::setupNativeWindow() { + // Setup borderless window + auto hwnd = glfwGetWin32Window(this->m_window); + + g_oldWndProc = ::SetWindowLongPtr(hwnd, GWLP_WNDPROC, (LONG_PTR)windowProc); + + MARGINS borderless = { 1, 1, 1, 1 }; + ::DwmExtendFrameIntoClientArea(hwnd, &borderless); + + DWORD attribute = DWMNCRP_ENABLED; + ::DwmSetWindowAttribute(hwnd, DWMWA_NCRENDERING_POLICY, &attribute, sizeof(attribute)); + + ::SetWindowPos(hwnd, nullptr, 0, 0, 0, 0, SWP_NOZORDER | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSIZE | SWP_NOMOVE); + ::SetWindowLong(hwnd, GWL_STYLE, GetWindowLong(hwnd, GWL_STYLE) | WS_OVERLAPPEDWINDOW); + + // Setup system theme change detector + bool themeFollowSystem = ContentRegistry::Settings::getSetting("hex.builtin.setting.interface", "hex.builtin.setting.interface.color") == 0; + EventManager::subscribe(this, [themeFollowSystem] { + if (!themeFollowSystem) return; + + HKEY hkey; + if (RegOpenKey(HKEY_CURRENT_USER, R"(Software\Microsoft\Windows\CurrentVersion\Themes\Personalize)", &hkey) == ERROR_SUCCESS) { + DWORD value = 0; + DWORD size = sizeof(DWORD); + + auto error = RegQueryValueEx(hkey, "AppsUseLightTheme", nullptr, nullptr, reinterpret_cast(&value), &size); + if (error == ERROR_SUCCESS) { + EventManager::post(value == 0 ? 1 : 2); + } + } + }); + + if (themeFollowSystem) + EventManager::post(); + } + + void Window::beginNativeWindowFrame() { + g_titleBarHeight = ImGui::GetCurrentWindow()->MenuBarHeight(); + } + + void Window::endNativeWindowFrame() { + if (g_mouseCursorIcon != ImGuiMouseCursor_None) { + ImGui::SetMouseCursor(g_mouseCursorIcon); + } + + switch (ImGui::GetMouseCursor()) { + case ImGuiMouseCursor_Arrow: + SetCursor(LoadCursor(nullptr, IDC_ARROW)); + break; + case ImGuiMouseCursor_Hand: + SetCursor(LoadCursor(nullptr, IDC_HAND)); + break; + case ImGuiMouseCursor_ResizeEW: + SetCursor(LoadCursor(nullptr, IDC_SIZEWE)); + break; + case ImGuiMouseCursor_ResizeNS: + SetCursor(LoadCursor(nullptr, IDC_SIZENS)); + break; + case ImGuiMouseCursor_ResizeNWSE: + SetCursor(LoadCursor(nullptr, IDC_SIZENWSE)); + break; + case ImGuiMouseCursor_ResizeNESW: + SetCursor(LoadCursor(nullptr, IDC_SIZENESW)); + break; + case ImGuiMouseCursor_ResizeAll: + SetCursor(LoadCursor(nullptr, IDC_SIZEALL)); + break; + case ImGuiMouseCursor_NotAllowed: + SetCursor(LoadCursor(nullptr, IDC_NO)); + break; + case ImGuiMouseCursor_TextInput: + SetCursor(LoadCursor(nullptr, IDC_IBEAM)); + break; + default: + case ImGuiMouseCursor_None: + SetCursor(LoadCursor(nullptr, IDC_ARROW)); + break; + } + } + + void Window::drawTitleBar() { + auto buttonSize = ImVec2(g_titleBarHeight * 1.5F, g_titleBarHeight - 1); + + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0)); + ImGui::PushStyleColor(ImGuiCol_Button, ImGui::GetColorU32(ImGuiCol_MenuBarBg)); + ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImGui::GetColorU32(ImGuiCol_ScrollbarGrabActive)); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImGui::GetColorU32(ImGuiCol_ScrollbarGrabHovered)); + + ImGui::SetCursorPosX(ImGui::GetWindowWidth() - buttonSize.x * 6); + #if defined(DEBUG) + if (ImGui::TitleBarButton(ICON_VS_DEBUG, buttonSize)) { + if (ImGui::GetIO().KeyCtrl) { + // Explicitly trigger a segfault by writing to an invalid memory location + // Used for debugging crashes + *reinterpret_cast(0x10) = 0x10; + } else if (ImGui::GetIO().KeyShift) { + // Explicitly trigger an abort by throwing an uncaught exception + // Used for debugging exception errors + throw std::runtime_error("Debug Error"); + } else { + hex::openWebpage("https://imhex.werwolv.net/debug"); + } + } + ImGui::InfoTooltip("hex.menu.debug_build"_lang); + #endif + if (ImGui::TitleBarButton(ICON_VS_SMILEY, buttonSize)) + hex::openWebpage("mailto://hey@werwolv.net"); + ImGui::InfoTooltip("hex.menu.feedback"_lang); + + ImGui::SetCursorPosX(ImGui::GetWindowWidth() - buttonSize.x * 3); + if (ImGui::TitleBarButton(ICON_VS_CHROME_MINIMIZE, buttonSize)) + glfwIconifyWindow(this->m_window); + if (glfwGetWindowAttrib(this->m_window, GLFW_MAXIMIZED)) { + if (ImGui::TitleBarButton(ICON_VS_CHROME_RESTORE, buttonSize)) + glfwRestoreWindow(this->m_window); + } else { + if (ImGui::TitleBarButton(ICON_VS_CHROME_MAXIMIZE, buttonSize)) + glfwMaximizeWindow(this->m_window); + } + + ImGui::PushStyleColor(ImGuiCol_ButtonActive, 0xFF7A70F1); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, 0xFF2311E8); + + + if (ImGui::TitleBarButton(ICON_VS_CHROME_CLOSE, buttonSize)) { + ImHexApi::Common::closeImHex(); + } + + ImGui::PopStyleColor(5); + ImGui::PopStyleVar(); + + ImGui::SetCursorPosX((ImGui::GetWindowWidth() - ImGui::CalcTextSize(this->m_windowTitle.c_str()).x) / 2); + ImGui::TextUnformatted(this->m_windowTitle.c_str()); + } + +} + #endif \ No newline at end of file diff --git a/main/source/window/window.cpp b/main/source/window/window.cpp index 3cdb49647..d721ea93b 100644 --- a/main/source/window/window.cpp +++ b/main/source/window/window.cpp @@ -46,18 +46,18 @@ namespace hex { using namespace std::literals::chrono_literals; void *ImHexSettingsHandler_ReadOpenFn(ImGuiContext *ctx, ImGuiSettingsHandler *, const char *) { - return ctx; // Unused, but the return value has to be non-null + return ctx; // Unused, but the return value has to be non-null } - void ImHexSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler *handler, void *, const char* line) { + void ImHexSettingsHandler_ReadLine(ImGuiContext *, ImGuiSettingsHandler *handler, void *, const char *line) { for (auto &[name, view] : ContentRegistry::Views::getEntries()) { std::string format = std::string(view->getUnlocalizedName()) + "=%d"; sscanf(line, format.c_str(), &view->getWindowOpenState()); } } - void ImHexSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler *handler, ImGuiTextBuffer *buf) { - buf->reserve(buf->size() + 0x20); // Ballpark reserve + void ImHexSettingsHandler_WriteAll(ImGuiContext *ctx, ImGuiSettingsHandler *handler, ImGuiTextBuffer *buf) { + buf->reserve(buf->size() + 0x20); // Ballpark reserve buf->appendf("[%s][General]\n", handler->TypeName); @@ -74,13 +74,13 @@ namespace hex { if (argument == "update-available") { this->m_availableUpdate = value; } else if (argument == "no-plugins") { - View::doLater([]{ ImGui::OpenPopup("No Plugins"); }); + View::doLater([] { ImGui::OpenPopup("No Plugins"); }); } else if (argument == "tip-of-the-day") { this->m_tipOfTheDay = value; this->m_showTipOfTheDay = ContentRegistry::Settings::read("hex.builtin.setting.general", "hex.builtin.setting.general.show_tips", 1); if (this->m_showTipOfTheDay) - View::doLater([]{ ImGui::OpenPopup("hex.welcome.tip_of_the_day"_lang); }); + View::doLater([] { ImGui::OpenPopup("hex.welcome.tip_of_the_day"_lang); }); } } } @@ -128,37 +128,37 @@ namespace hex { ImGui::UnloadImage(this->m_bannerTexture); switch (theme) { - default: - case 1: /* Dark theme */ + default: + case 1: /* Dark theme */ { ImGui::StyleColorsDark(); ImGui::StyleCustomColorsDark(); ImPlot::StyleColorsDark(); auto banner = romfs::get("banner_dark.png"); - this->m_bannerTexture = ImGui::LoadImageFromMemory(reinterpret_cast(banner.data()), banner.size()); + this->m_bannerTexture = ImGui::LoadImageFromMemory(reinterpret_cast(banner.data()), banner.size()); break; } - case 2: /* Light theme */ + case 2: /* Light theme */ { ImGui::StyleColorsLight(); ImGui::StyleCustomColorsLight(); ImPlot::StyleColorsLight(); auto banner = romfs::get("banner_light.png"); - this->m_bannerTexture = ImGui::LoadImageFromMemory(reinterpret_cast(banner.data()), banner.size()); + this->m_bannerTexture = ImGui::LoadImageFromMemory(reinterpret_cast(banner.data()), banner.size()); break; } - case 3: /* Classic theme */ + case 3: /* Classic theme */ { ImGui::StyleColorsClassic(); ImGui::StyleCustomColorsClassic(); ImPlot::StyleColorsClassic(); auto banner = romfs::get("banner_dark.png"); - this->m_bannerTexture = ImGui::LoadImageFromMemory(reinterpret_cast(banner.data()), banner.size()); + this->m_bannerTexture = ImGui::LoadImageFromMemory(reinterpret_cast(banner.data()), banner.size()); break; } @@ -175,7 +175,7 @@ namespace hex { } }); - EventManager::subscribe(this, [](const auto &path){ + EventManager::subscribe(this, [](const auto &path) { SharedData::recentFilePaths.push_front(path); { @@ -206,7 +206,7 @@ namespace hex { } }); - EventManager::subscribe(this, []{ + EventManager::subscribe(this, [] { EventManager::post(""); }); @@ -244,14 +244,14 @@ namespace hex { } }); - EventManager::subscribe(this, [this](auto name){ + EventManager::subscribe(this, [this](auto name) { this->m_popupsToOpen.push_back(name); }); for (const auto &path : hex::getPath(ImHexPath::Config)) { if (auto filePath = fs::path(path) / CrashBackupFileName; fs::exists(filePath)) { this->m_safetyBackupPath = filePath; - View::doLater([]{ ImGui::OpenPopup("hex.safety_backup.title"_lang); }); + View::doLater([] { ImGui::OpenPopup("hex.safety_backup.title"_lang); }); } } @@ -269,23 +269,22 @@ namespace hex { // Let's not loop on this... std::signal(signalNumber, nullptr); - #if defined(DEBUG) - assert(false); - #else - std::raise(signalNumber); - #endif - +#if defined(DEBUG) + assert(false); +#else + std::raise(signalNumber); +#endif }; std::signal(SIGTERM, signalHandler); std::signal(SIGSEGV, signalHandler); - std::signal(SIGINT, signalHandler); - std::signal(SIGILL, signalHandler); + std::signal(SIGINT, signalHandler); + std::signal(SIGILL, signalHandler); std::signal(SIGABRT, signalHandler); - std::signal(SIGFPE, signalHandler); + std::signal(SIGFPE, signalHandler); auto imhexLogo = romfs::get("logo.png"); - this->m_logoTexture = ImGui::LoadImageFromMemory(reinterpret_cast(imhexLogo.data()), imhexLogo.size()); + this->m_logoTexture = ImGui::LoadImageFromMemory(reinterpret_cast(imhexLogo.data()), imhexLogo.size()); ContentRegistry::Settings::store(); EventManager::post(); @@ -333,7 +332,7 @@ namespace hex { ImGui_ImplGlfw_NewFrame(); ImGui::NewFrame(); - ImGuiViewport* viewport = ImGui::GetMainViewport(); + ImGuiViewport *viewport = ImGui::GetMainViewport(); ImGui::SetNextWindowPos(viewport->WorkPos); ImGui::SetNextWindowSize(viewport->WorkSize); ImGui::SetNextWindowViewport(viewport->ID); @@ -341,11 +340,7 @@ namespace hex { ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f); ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0)); - ImGuiWindowFlags windowFlags = ImGuiWindowFlags_MenuBar | ImGuiWindowFlags_NoDocking - | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse - | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize - | ImGuiWindowFlags_NoNavFocus | ImGuiWindowFlags_NoBringToFrontOnFocus - | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse; + ImGuiWindowFlags windowFlags = ImGuiWindowFlags_MenuBar | ImGuiWindowFlags_NoDocking | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoNavFocus | ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse; ImGui::GetIO().ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; @@ -617,7 +612,7 @@ namespace hex { glClear(GL_COLOR_BUFFER_BIT); ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); - GLFWwindow* backup_current_context = glfwGetCurrentContext(); + GLFWwindow *backup_current_context = glfwGetCurrentContext(); ImGui::UpdatePlatformWindows(); ImGui::RenderPlatformWindowsDefault(); glfwMakeContextCurrent(backup_current_context); @@ -700,7 +695,7 @@ namespace hex { ImGui::TableNextRow(ImGuiTableRowFlags_None, ImGui::GetTextLineHeightWithSpacing() * 6); ImGui::TableNextColumn(); - ImGui:: UnderlinedText("hex.welcome.header.help"_lang); + ImGui::UnderlinedText("hex.welcome.header.help"_lang); ImGui::SetCursorPosY(ImGui::GetCursorPosY() + 5_scaled); { if (ImGui::IconHyperlink(ICON_VS_GITHUB, "hex.welcome.help.repo"_lang)) hex::openWebpage("hex.welcome.help.repo.link"_lang); @@ -796,11 +791,10 @@ namespace hex { function(ContentRegistry::Interface::getDockSpaceId()); } - } void Window::initGLFW() { - glfwSetErrorCallback([](int error, const char* desc) { + glfwSetErrorCallback([](int error, const char *desc) { log::error("GLFW Error [{}] : {}", error, desc); }); @@ -809,11 +803,11 @@ namespace hex { std::abort(); } - #if defined(OS_WINDOWS) - glfwWindowHint(GLFW_DECORATED, GLFW_FALSE); - #elif defined(OS_MACOS) - glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); - #endif +#if defined(OS_WINDOWS) + glfwWindowHint(GLFW_DECORATED, GLFW_FALSE); +#elif defined(OS_MACOS) + glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); +#endif glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); @@ -866,7 +860,7 @@ namespace hex { if (auto g = ImGui::GetCurrentContext(); g == nullptr || g->WithinFrameScope) return; - auto win = static_cast(glfwGetWindowUserPointer(window)); + auto win = static_cast(glfwGetWindowUserPointer(window)); win->frameBegin(); win->frame(); win->frameEnd(); @@ -877,35 +871,33 @@ namespace hex { if (auto g = ImGui::GetCurrentContext(); g == nullptr || g->WithinFrameScope) return; - auto win = static_cast(glfwGetWindowUserPointer(window)); + auto win = static_cast(glfwGetWindowUserPointer(window)); win->frameBegin(); win->frame(); win->frameEnd(); }); glfwSetKeyCallback(this->m_window, [](GLFWwindow *window, int key, int scancode, int action, int mods) { - auto keyName = glfwGetKeyName(key, scancode); if (keyName != nullptr) key = std::toupper(keyName[0]); - auto win = static_cast(glfwGetWindowUserPointer(window)); + auto win = static_cast(glfwGetWindowUserPointer(window)); if (action == GLFW_PRESS) { auto &io = ImGui::GetIO(); win->m_pressedKeys.push_back(key); io.KeysDown[key] = true; - io.KeyCtrl = (mods & GLFW_MOD_CONTROL) != 0; + io.KeyCtrl = (mods & GLFW_MOD_CONTROL) != 0; io.KeyShift = (mods & GLFW_MOD_SHIFT) != 0; - io.KeyAlt = (mods & GLFW_MOD_ALT) != 0; - } - else if (action == GLFW_RELEASE) { + io.KeyAlt = (mods & GLFW_MOD_ALT) != 0; + } else if (action == GLFW_RELEASE) { auto &io = ImGui::GetIO(); io.KeysDown[key] = false; - io.KeyCtrl = (mods & GLFW_MOD_CONTROL) != 0; + io.KeyCtrl = (mods & GLFW_MOD_CONTROL) != 0; io.KeyShift = (mods & GLFW_MOD_SHIFT) != 0; - io.KeyAlt = (mods & GLFW_MOD_ALT) != 0; + io.KeyAlt = (mods & GLFW_MOD_ALT) != 0; } }); @@ -950,43 +942,43 @@ namespace hex { GImPlot = ImPlot::CreateContext(); GImNodes = ImNodes::CreateContext(); - ImGuiIO& io = ImGui::GetIO(); - ImGuiStyle& style = ImGui::GetStyle(); + ImGuiIO &io = ImGui::GetIO(); + ImGuiStyle &style = ImGui::GetStyle(); style.Alpha = 1.0F; style.WindowRounding = 0.0F; io.ConfigFlags |= ImGuiConfigFlags_DockingEnable | ImGuiConfigFlags_NavEnableKeyboard; - #if !defined(OS_LINUX) +#if !defined(OS_LINUX) io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; - #endif +#endif for (auto &entry : SharedData::fontAtlas->ConfigData) io.Fonts->ConfigData.push_back(entry); io.ConfigViewportsNoTaskBarIcon = false; - io.KeyMap[ImGuiKey_Tab] = GLFW_KEY_TAB; - io.KeyMap[ImGuiKey_LeftArrow] = GLFW_KEY_LEFT; - io.KeyMap[ImGuiKey_RightArrow] = GLFW_KEY_RIGHT; - io.KeyMap[ImGuiKey_UpArrow] = GLFW_KEY_UP; - io.KeyMap[ImGuiKey_DownArrow] = GLFW_KEY_DOWN; - io.KeyMap[ImGuiKey_PageUp] = GLFW_KEY_PAGE_UP; - io.KeyMap[ImGuiKey_PageDown] = GLFW_KEY_PAGE_DOWN; - io.KeyMap[ImGuiKey_Home] = GLFW_KEY_HOME; - io.KeyMap[ImGuiKey_End] = GLFW_KEY_END; - io.KeyMap[ImGuiKey_Insert] = GLFW_KEY_INSERT; - io.KeyMap[ImGuiKey_Delete] = GLFW_KEY_DELETE; - io.KeyMap[ImGuiKey_Backspace] = GLFW_KEY_BACKSPACE; - io.KeyMap[ImGuiKey_Space] = GLFW_KEY_SPACE; - io.KeyMap[ImGuiKey_Enter] = GLFW_KEY_ENTER; - io.KeyMap[ImGuiKey_Escape] = GLFW_KEY_ESCAPE; + io.KeyMap[ImGuiKey_Tab] = GLFW_KEY_TAB; + io.KeyMap[ImGuiKey_LeftArrow] = GLFW_KEY_LEFT; + io.KeyMap[ImGuiKey_RightArrow] = GLFW_KEY_RIGHT; + io.KeyMap[ImGuiKey_UpArrow] = GLFW_KEY_UP; + io.KeyMap[ImGuiKey_DownArrow] = GLFW_KEY_DOWN; + io.KeyMap[ImGuiKey_PageUp] = GLFW_KEY_PAGE_UP; + io.KeyMap[ImGuiKey_PageDown] = GLFW_KEY_PAGE_DOWN; + io.KeyMap[ImGuiKey_Home] = GLFW_KEY_HOME; + io.KeyMap[ImGuiKey_End] = GLFW_KEY_END; + io.KeyMap[ImGuiKey_Insert] = GLFW_KEY_INSERT; + io.KeyMap[ImGuiKey_Delete] = GLFW_KEY_DELETE; + io.KeyMap[ImGuiKey_Backspace] = GLFW_KEY_BACKSPACE; + io.KeyMap[ImGuiKey_Space] = GLFW_KEY_SPACE; + io.KeyMap[ImGuiKey_Enter] = GLFW_KEY_ENTER; + io.KeyMap[ImGuiKey_Escape] = GLFW_KEY_ESCAPE; io.KeyMap[ImGuiKey_KeyPadEnter] = GLFW_KEY_KP_ENTER; - io.KeyMap[ImGuiKey_A] = GLFW_KEY_A; - io.KeyMap[ImGuiKey_C] = GLFW_KEY_C; - io.KeyMap[ImGuiKey_V] = GLFW_KEY_V; - io.KeyMap[ImGuiKey_X] = GLFW_KEY_X; - io.KeyMap[ImGuiKey_Y] = GLFW_KEY_Y; - io.KeyMap[ImGuiKey_Z] = GLFW_KEY_Z; + io.KeyMap[ImGuiKey_A] = GLFW_KEY_A; + io.KeyMap[ImGuiKey_C] = GLFW_KEY_C; + io.KeyMap[ImGuiKey_V] = GLFW_KEY_V; + io.KeyMap[ImGuiKey_X] = GLFW_KEY_X; + io.KeyMap[ImGuiKey_Y] = GLFW_KEY_Y; + io.KeyMap[ImGuiKey_Z] = GLFW_KEY_Z; ImNodes::PushAttributeFlag(ImNodesAttributeFlags_EnableLinkDetachWithDragClick); ImNodes::PushAttributeFlag(ImNodesAttributeFlags_EnableLinkCreationOnSnap); @@ -1026,7 +1018,7 @@ namespace hex { handler.ReadOpenFn = ImHexSettingsHandler_ReadOpenFn; handler.ReadLineFn = ImHexSettingsHandler_ReadLine; handler.WriteAllFn = ImHexSettingsHandler_WriteAll; - handler.UserData = this; + handler.UserData = this; ImGui::GetCurrentContext()->SettingsHandlers.push_back(handler); static std::string iniFileName; @@ -1052,7 +1044,7 @@ namespace hex { } void Window::exitImGui() { - delete static_cast(ImGui::GetIO().UserData); + delete static_cast(ImGui::GetIO().UserData); ImNodes::PopAttributeFlag(); ImNodes::PopAttributeFlag(); diff --git a/plugins/builtin/include/content/providers/disk_provider.hpp b/plugins/builtin/include/content/providers/disk_provider.hpp index b5f4039fc..f87bdb249 100644 --- a/plugins/builtin/include/content/providers/disk_provider.hpp +++ b/plugins/builtin/include/content/providers/disk_provider.hpp @@ -44,12 +44,12 @@ namespace hex::plugin::builtin::prv { std::set m_availableDrives; fs::path m_path; - #if defined(OS_WINDOWS) - HANDLE m_diskHandle = INVALID_HANDLE_VALUE; - #else - std::string m_pathBuffer; - int m_diskHandle = -1; - #endif +#if defined(OS_WINDOWS) + HANDLE m_diskHandle = INVALID_HANDLE_VALUE; +#else + std::string m_pathBuffer; + int m_diskHandle = -1; +#endif size_t m_diskSize; size_t m_sectorSize; diff --git a/plugins/builtin/include/content/providers/file_provider.hpp b/plugins/builtin/include/content/providers/file_provider.hpp index 67985ee42..9de3881c5 100644 --- a/plugins/builtin/include/content/providers/file_provider.hpp +++ b/plugins/builtin/include/content/providers/file_provider.hpp @@ -7,11 +7,11 @@ #include #if defined(OS_WINDOWS) -#include + #include #else -#include -#include -#include + #include + #include + #include #endif namespace hex::plugin::builtin::prv { @@ -49,12 +49,12 @@ namespace hex::plugin::builtin::prv { void close() override; protected: - #if defined(OS_WINDOWS) +#if defined(OS_WINDOWS) HANDLE m_file = INVALID_HANDLE_VALUE; HANDLE m_mapping = INVALID_HANDLE_VALUE; - #else +#else int m_file = -1; - #endif +#endif fs::path m_path; void *m_mappedFile = nullptr; diff --git a/plugins/builtin/include/content/providers/gdb_provider.hpp b/plugins/builtin/include/content/providers/gdb_provider.hpp index 654eac6e9..db0b5c105 100644 --- a/plugins/builtin/include/content/providers/gdb_provider.hpp +++ b/plugins/builtin/include/content/providers/gdb_provider.hpp @@ -9,7 +9,7 @@ namespace hex::plugin::builtin::prv { -class GDBProvider : public hex::prv::Provider { + class GDBProvider : public hex::prv::Provider { public: explicit GDBProvider(); ~GDBProvider() override; diff --git a/plugins/builtin/include/content/views/view_bookmarks.hpp b/plugins/builtin/include/content/views/view_bookmarks.hpp index 1bc42d1c4..56197fca5 100644 --- a/plugins/builtin/include/content/views/view_bookmarks.hpp +++ b/plugins/builtin/include/content/views/view_bookmarks.hpp @@ -7,7 +7,9 @@ namespace hex::plugin::builtin { - namespace prv { class Provider; } + namespace prv { + class Provider; + } class ViewBookmarks : public View { public: diff --git a/plugins/builtin/include/content/views/view_data_inspector.hpp b/plugins/builtin/include/content/views/view_data_inspector.hpp index 9c88073aa..e02decf4e 100644 --- a/plugins/builtin/include/content/views/view_data_inspector.hpp +++ b/plugins/builtin/include/content/views/view_data_inspector.hpp @@ -10,7 +10,9 @@ namespace hex::plugin::builtin { - namespace prv { class Provider; } + namespace prv { + class Provider; + } class ViewDataInspector : public View { public: @@ -28,7 +30,7 @@ namespace hex::plugin::builtin { bool m_shouldInvalidate = true; std::endian m_endian = std::endian::native; - ContentRegistry::DataInspector::NumberDisplayStyle m_numberDisplayStyle =ContentRegistry::DataInspector::NumberDisplayStyle::Decimal; + ContentRegistry::DataInspector::NumberDisplayStyle m_numberDisplayStyle = ContentRegistry::DataInspector::NumberDisplayStyle::Decimal; u64 m_startAddress = 0; size_t m_validBytes = 0; diff --git a/plugins/builtin/include/content/views/view_data_processor.hpp b/plugins/builtin/include/content/views/view_data_processor.hpp index 85f48efb5..38a2bf46f 100644 --- a/plugins/builtin/include/content/views/view_data_processor.hpp +++ b/plugins/builtin/include/content/views/view_data_processor.hpp @@ -12,7 +12,9 @@ namespace hex::plugin::builtin { - namespace prv { class Provider; } + namespace prv { + class Provider; + } class ViewDataProcessor : public View { public: @@ -22,11 +24,11 @@ namespace hex::plugin::builtin { void drawContent() override; private: - std::list m_endNodes; - std::list m_nodes; - std::list m_links; + std::list m_endNodes; + std::list m_nodes; + std::list m_links; - std::vector m_dataOverlays; + std::vector m_dataOverlays; int m_rightClickedId = -1; ImVec2 m_rightClickedCoords; diff --git a/plugins/builtin/include/content/views/view_diff.hpp b/plugins/builtin/include/content/views/view_diff.hpp index 379b04ddc..dc70a78b0 100644 --- a/plugins/builtin/include/content/views/view_diff.hpp +++ b/plugins/builtin/include/content/views/view_diff.hpp @@ -11,7 +11,9 @@ namespace hex::plugin::builtin { - namespace prv { class Provider; } + namespace prv { + class Provider; + } class ViewDiff : public View { public: diff --git a/plugins/builtin/include/content/views/view_disassembler.hpp b/plugins/builtin/include/content/views/view_disassembler.hpp index 8b39bb229..ef1cb9ae4 100644 --- a/plugins/builtin/include/content/views/view_disassembler.hpp +++ b/plugins/builtin/include/content/views/view_disassembler.hpp @@ -10,7 +10,9 @@ namespace hex::plugin::builtin { - namespace prv { class Provider; } + namespace prv { + class Provider; + } struct Disassembly { u64 address; diff --git a/plugins/builtin/include/content/views/view_hashes.hpp b/plugins/builtin/include/content/views/view_hashes.hpp index a469abaaf..f6d7fb887 100644 --- a/plugins/builtin/include/content/views/view_hashes.hpp +++ b/plugins/builtin/include/content/views/view_hashes.hpp @@ -8,7 +8,9 @@ namespace hex::plugin::builtin { - namespace prv { class Provider; } + namespace prv { + class Provider; + } class ViewHashes : public View { public: @@ -18,7 +20,17 @@ namespace hex::plugin::builtin { void drawContent() override; private: - enum class HashFunctions { Crc8, Crc16, Crc32, Md5, Sha1, Sha224, Sha256, Sha384, Sha512 }; + enum class HashFunctions { + Crc8, + Crc16, + Crc32, + Md5, + Sha1, + Sha224, + Sha256, + Sha384, + Sha512 + }; bool m_shouldInvalidate = true; int m_currHashFunction = 0; @@ -26,15 +38,15 @@ namespace hex::plugin::builtin { bool m_shouldMatchSelection = false; static constexpr std::array hashFunctionNames { - std::pair{HashFunctions::Crc8, "CRC8"}, - std::pair{HashFunctions::Crc16, "CRC16"}, - std::pair{HashFunctions::Crc32, "CRC32"}, - std::pair{HashFunctions::Md5, "MD5"}, - std::pair{HashFunctions::Sha1, "SHA-1"}, - std::pair{HashFunctions::Sha224, "SHA-224"}, - std::pair{HashFunctions::Sha256, "SHA-256"}, - std::pair{HashFunctions::Sha384, "SHA-384"}, - std::pair{HashFunctions::Sha512, "SHA-512"}, + std::pair {HashFunctions::Crc8, "CRC8" }, + std::pair { HashFunctions::Crc16, "CRC16" }, + std::pair { HashFunctions::Crc32, "CRC32" }, + std::pair { HashFunctions::Md5, "MD5" }, + std::pair { HashFunctions::Sha1, "SHA-1" }, + std::pair { HashFunctions::Sha224, "SHA-224"}, + std::pair { HashFunctions::Sha256, "SHA-256"}, + std::pair { HashFunctions::Sha384, "SHA-384"}, + std::pair { HashFunctions::Sha512, "SHA-512"}, }; }; diff --git a/plugins/builtin/include/content/views/view_help.hpp b/plugins/builtin/include/content/views/view_help.hpp index 6742b5ae9..c294605a7 100644 --- a/plugins/builtin/include/content/views/view_help.hpp +++ b/plugins/builtin/include/content/views/view_help.hpp @@ -11,7 +11,9 @@ namespace hex::plugin::builtin { - namespace prv { class Provider; } + namespace prv { + class Provider; + } class ViewHelp : public View { public: diff --git a/plugins/builtin/include/content/views/view_hexeditor.hpp b/plugins/builtin/include/content/views/view_hexeditor.hpp index 3e59dd09f..726be5801 100644 --- a/plugins/builtin/include/content/views/view_hexeditor.hpp +++ b/plugins/builtin/include/content/views/view_hexeditor.hpp @@ -10,13 +10,15 @@ #include #include -namespace hex::prv { class Provider; } +namespace hex::prv { + class Provider; +} namespace hex::plugin::builtin { - using SearchFunction = std::vector> (*)(prv::Provider* &provider, std::string string); + using SearchFunction = std::vector> (*)(prv::Provider *&provider, std::string string); class ViewHexEditor : public View { public: @@ -44,7 +46,7 @@ namespace hex::plugin::builtin { u64 m_resizeSize = 0; std::vector m_dataToSave; - std::set m_highlightedPatterns; + std::set m_highlightedPatterns; std::string m_loaderScriptScriptPath; std::string m_loaderScriptFilePath; diff --git a/plugins/builtin/include/content/views/view_information.hpp b/plugins/builtin/include/content/views/view_information.hpp index e06d5685a..7c4551e4f 100644 --- a/plugins/builtin/include/content/views/view_information.hpp +++ b/plugins/builtin/include/content/views/view_information.hpp @@ -10,7 +10,9 @@ namespace hex::plugin::builtin { - namespace prv { class Provider; } + namespace prv { + class Provider; + } class ViewInformation : public View { public: diff --git a/plugins/builtin/include/content/views/view_patches.hpp b/plugins/builtin/include/content/views/view_patches.hpp index 6b6f81603..ca4d86f90 100644 --- a/plugins/builtin/include/content/views/view_patches.hpp +++ b/plugins/builtin/include/content/views/view_patches.hpp @@ -9,7 +9,9 @@ namespace hex::plugin::builtin { - namespace prv { class Provider; } + namespace prv { + class Provider; + } class ViewPatches : public View { public: diff --git a/plugins/builtin/include/content/views/view_pattern_data.hpp b/plugins/builtin/include/content/views/view_pattern_data.hpp index eacc184e2..f5549bdd3 100644 --- a/plugins/builtin/include/content/views/view_pattern_data.hpp +++ b/plugins/builtin/include/content/views/view_pattern_data.hpp @@ -11,8 +11,12 @@ namespace hex { - namespace prv { class Provider; } - namespace lang { class PatternData; } + namespace prv { + class Provider; + } + namespace lang { + class PatternData; + } } @@ -27,7 +31,7 @@ namespace hex::plugin::builtin { void drawContent() override; private: - std::vector m_sortedPatternData; + std::vector m_sortedPatternData; }; } \ No newline at end of file diff --git a/plugins/builtin/include/content/views/view_strings.hpp b/plugins/builtin/include/content/views/view_strings.hpp index 6167d7a84..72846cc85 100644 --- a/plugins/builtin/include/content/views/view_strings.hpp +++ b/plugins/builtin/include/content/views/view_strings.hpp @@ -7,7 +7,9 @@ namespace hex::plugin::builtin { - namespace prv { class Provider; } + namespace prv { + class Provider; + } struct FoundString { u64 offset; diff --git a/plugins/builtin/include/content/views/view_tools.hpp b/plugins/builtin/include/content/views/view_tools.hpp index 0409e5883..1026c09e2 100644 --- a/plugins/builtin/include/content/views/view_tools.hpp +++ b/plugins/builtin/include/content/views/view_tools.hpp @@ -10,7 +10,9 @@ namespace hex::plugin::builtin { - namespace prv { class Provider; } + namespace prv { + class Provider; + } class ViewTools : public View { public: @@ -18,7 +20,6 @@ namespace hex::plugin::builtin { ~ViewTools() override; void drawContent() override; - }; } \ No newline at end of file diff --git a/plugins/builtin/include/math_evaluator.hpp b/plugins/builtin/include/math_evaluator.hpp index 4c93e4b7e..939839ee5 100644 --- a/plugins/builtin/include/math_evaluator.hpp +++ b/plugins/builtin/include/math_evaluator.hpp @@ -20,31 +20,31 @@ namespace hex { }; enum class Operator : u16 { - Invalid = 0x000, - Assign = 0x010, - Or = 0x020, - Xor = 0x030, - And = 0x040, - BitwiseOr = 0x050, - BitwiseXor = 0x060, - BitwiseAnd = 0x070, - Equals = 0x080, - NotEquals = 0x081, - GreaterThan = 0x090, - LessThan = 0x091, - GreaterThanOrEquals = 0x092, - LessThanOrEquals = 0x093, - ShiftLeft = 0x0A0, - ShiftRight = 0x0A1, - Addition = 0x0B0, - Subtraction = 0x0B1, - Multiplication = 0x0C0, - Division = 0x0C1, - Modulus = 0x0C2, - Exponentiation = 0x1D0, - Combine = 0x0E0, - BitwiseNot = 0x0F0, - Not = 0x0F1 + Invalid = 0x000, + Assign = 0x010, + Or = 0x020, + Xor = 0x030, + And = 0x040, + BitwiseOr = 0x050, + BitwiseXor = 0x060, + BitwiseAnd = 0x070, + Equals = 0x080, + NotEquals = 0x081, + GreaterThan = 0x090, + LessThan = 0x091, + GreaterThanOrEquals = 0x092, + LessThanOrEquals = 0x093, + ShiftLeft = 0x0A0, + ShiftRight = 0x0A1, + Addition = 0x0B0, + Subtraction = 0x0B1, + Multiplication = 0x0C0, + Division = 0x0C1, + Modulus = 0x0C2, + Exponentiation = 0x1D0, + Combine = 0x0E0, + BitwiseNot = 0x0F0, + Not = 0x0F1 }; enum class BracketType : std::uint8_t { @@ -74,7 +74,7 @@ namespace hex { void setVariable(std::string name, long double value); void setFunction(std::string name, std::function(std::vector)> function, size_t minNumArgs, size_t maxNumArgs); - std::unordered_map& getVariables() { return this->m_variables; } + std::unordered_map &getVariables() { return this->m_variables; } private: std::queue parseInput(const char *input); diff --git a/plugins/builtin/source/content/command_palette_commands.cpp b/plugins/builtin/source/content/command_palette_commands.cpp index c12b8e464..b6ee9a8a8 100644 --- a/plugins/builtin/source/content/command_palette_commands.cpp +++ b/plugins/builtin/source/content/command_palette_commands.cpp @@ -13,46 +13,48 @@ namespace hex::plugin::builtin { void registerCommandPaletteCommands() { ContentRegistry::CommandPaletteCommands::add( - ContentRegistry::CommandPaletteCommands::Type::SymbolCommand, - "#", "hex.builtin.command.calc.desc", - [](auto input) { - hex::MathEvaluator evaluator; - evaluator.registerStandardVariables(); - evaluator.registerStandardFunctions(); + ContentRegistry::CommandPaletteCommands::Type::SymbolCommand, + "#", + "hex.builtin.command.calc.desc", + [](auto input) { + hex::MathEvaluator evaluator; + evaluator.registerStandardVariables(); + evaluator.registerStandardFunctions(); - std::optional result; + std::optional result; - try { - result = evaluator.evaluate(input); - } catch (std::exception &e) {} + try { + result = evaluator.evaluate(input); + } catch (std::exception &e) { } - if (result.has_value()) - return hex::format("#{0} = {1}", input.data(), result.value()); - else - return std::string("???"); - }); + if (result.has_value()) + return hex::format("#{0} = {1}", input.data(), result.value()); + else + return std::string("???"); + }); ContentRegistry::CommandPaletteCommands::add( - ContentRegistry::CommandPaletteCommands::Type::KeywordCommand, - "/web", "hex.builtin.command.web.desc", - [](auto input) { - return hex::format("hex.builtin.command.web.result"_lang, input.data()); - }, - [](auto input) { - hex::openWebpage(input); - }); + ContentRegistry::CommandPaletteCommands::Type::KeywordCommand, + "/web", + "hex.builtin.command.web.desc", + [](auto input) { + return hex::format("hex.builtin.command.web.result"_lang, input.data()); + }, + [](auto input) { + hex::openWebpage(input); + }); ContentRegistry::CommandPaletteCommands::add( - ContentRegistry::CommandPaletteCommands::Type::SymbolCommand, - "$", "hex.builtin.command.cmd.desc", - [](auto input) { - return hex::format("hex.builtin.command.cmd.result"_lang, input.data()); - }, - [](auto input) { - hex::runCommand(input); - }); - + ContentRegistry::CommandPaletteCommands::Type::SymbolCommand, + "$", + "hex.builtin.command.cmd.desc", + [](auto input) { + return hex::format("hex.builtin.command.cmd.result"_lang, input.data()); + }, + [](auto input) { + hex::runCommand(input); + }); } } \ No newline at end of file diff --git a/plugins/builtin/source/content/data_formatters.cpp b/plugins/builtin/source/content/data_formatters.cpp index 637d3546f..156a63420 100644 --- a/plugins/builtin/source/content/data_formatters.cpp +++ b/plugins/builtin/source/content/data_formatters.cpp @@ -23,7 +23,8 @@ namespace hex::plugin::builtin { } // Remove trailing comma - result.pop_back(); result.pop_back(); + result.pop_back(); + result.pop_back(); } result += "\n"; @@ -35,52 +36,31 @@ namespace hex::plugin::builtin { void registerDataFormatters() { ContentRegistry::DataFormatter::add("hex.builtin.view.hexeditor.copy.c", [](prv::Provider *provider, u64 offset, size_t size) { - return formatLanguageArray(provider, offset, size, - hex::format("const uint8_t data[{0}] = {{", size), - "0x{0:02X}, ", - "};"); + return formatLanguageArray(provider, offset, size, hex::format("const uint8_t data[{0}] = {{", size), "0x{0:02X}, ", "};"); }); ContentRegistry::DataFormatter::add("hex.builtin.view.hexeditor.copy.cpp", [](prv::Provider *provider, u64 offset, size_t size) { - return formatLanguageArray(provider, offset, size, - hex::format("constexpr std::array data = {{", size), - "0x{0:02X}, ", - "};"); + return formatLanguageArray(provider, offset, size, hex::format("constexpr std::array data = {{", size), "0x{0:02X}, ", "};"); }); ContentRegistry::DataFormatter::add("hex.builtin.view.hexeditor.copy.java", [](prv::Provider *provider, u64 offset, size_t size) { - return formatLanguageArray(provider, offset, size, - "final byte[] data = {", - "0x{0:02X}, ", - "};"); + return formatLanguageArray(provider, offset, size, "final byte[] data = {", "0x{0:02X}, ", "};"); }); ContentRegistry::DataFormatter::add("hex.builtin.view.hexeditor.copy.csharp", [](prv::Provider *provider, u64 offset, size_t size) { - return formatLanguageArray(provider, offset, size, - "const byte[] data = {", - "0x{0:02X}, ", - "};"); + return formatLanguageArray(provider, offset, size, "const byte[] data = {", "0x{0:02X}, ", "};"); }); ContentRegistry::DataFormatter::add("hex.builtin.view.hexeditor.copy.rust", [](prv::Provider *provider, u64 offset, size_t size) { - return formatLanguageArray(provider, offset, size, - hex::format("let data: [u8; 0x{0:02X}] = [", size), - "0x{0:02X}, ", - "];"); + return formatLanguageArray(provider, offset, size, hex::format("let data: [u8; 0x{0:02X}] = [", size), "0x{0:02X}, ", "];"); }); ContentRegistry::DataFormatter::add("hex.builtin.view.hexeditor.copy.python", [](prv::Provider *provider, u64 offset, size_t size) { - return formatLanguageArray(provider, offset, size, - "data = bytes([", - "0x{0:02X}, ", - "]);"); + return formatLanguageArray(provider, offset, size, "data = bytes([", "0x{0:02X}, ", "]);"); }); ContentRegistry::DataFormatter::add("hex.builtin.view.hexeditor.copy.js", [](prv::Provider *provider, u64 offset, size_t size) { - return formatLanguageArray(provider, offset, size, - "const data = new Uint8Array([", - "0x{0:02X}, ", - "]);"); + return formatLanguageArray(provider, offset, size, "const data = new Uint8Array([", "0x{0:02X}, ", "]);"); }); ContentRegistry::DataFormatter::add("hex.builtin.view.hexeditor.copy.ascii", [](prv::Provider *provider, u64 offset, size_t size) { @@ -95,7 +75,7 @@ namespace hex::plugin::builtin { for (u32 col = offset >> 4; col <= (end >> 4); col++) { result += hex::format("{0:08X} ", col << 4); - for (u64 i = 0 ; i < 16; i++) { + for (u64 i = 0; i < 16; i++) { if (col == (offset >> 4) && i < (offset & 0xF) || col == (end >> 4) && i > (end & 0xF)) result += " "; @@ -108,7 +88,7 @@ namespace hex::plugin::builtin { result += " "; - for (u64 i = 0 ; i < 16; i++) { + for (u64 i = 0; i < 16; i++) { if (col == (offset >> 4) && i < (offset & 0xF) || col == (end >> 4) && i > (end & 0xF)) result += " "; @@ -121,22 +101,21 @@ namespace hex::plugin::builtin { result += "\n"; } - } return result; }); ContentRegistry::DataFormatter::add("hex.builtin.view.hexeditor.copy.html", [](prv::Provider *provider, u64 offset, size_t size) { std::string result = - "
\n" - " \n\n" - " \n" - " Hex View  00 01 02 03 04 05 06 07  08 09 0A 0B 0C 0D 0E 0F
\n"; + "
\n" + " \n\n" + " \n" + " Hex View  00 01 02 03 04 05 06 07  08 09 0A 0B 0C 0D 0E 0F
\n"; std::vector buffer(0x1'0000, 0x00); @@ -148,7 +127,7 @@ namespace hex::plugin::builtin { for (u32 col = offset >> 4; col <= (end >> 4); col++) { result += hex::format(" {0:08X}  ", col << 4); - for (u64 i = 0 ; i < 16; i++) { + for (u64 i = 0; i < 16; i++) { if (col == (offset >> 4) && i < (offset & 0xF) || col == (end >> 4) && i > (end & 0xF)) result += "   "; @@ -161,7 +140,7 @@ namespace hex::plugin::builtin { result += "  "; - for (u64 i = 0 ; i < 16; i++) { + for (u64 i = 0; i < 16; i++) { if (col == (offset >> 4) && i < (offset & 0xF) || col == (end >> 4) && i > (end & 0xF)) result += " "; @@ -174,16 +153,14 @@ namespace hex::plugin::builtin { result += "
\n"; } - } result += - "
\n" - "
\n"; + "
\n" + "
\n"; return result; }); - } } \ No newline at end of file diff --git a/plugins/builtin/source/content/data_inspector.cpp b/plugins/builtin/source/content/data_inspector.cpp index 8fde204f5..09fe872ef 100644 --- a/plugins/builtin/source/content/data_inspector.cpp +++ b/plugins/builtin/source/content/data_inspector.cpp @@ -19,7 +19,7 @@ namespace hex::plugin::builtin { u32 data1; u16 data2; u16 data3; - u8 data4[8]; + u8 data4[8]; }; void registerDataInspectorEntries() { @@ -40,7 +40,7 @@ namespace hex::plugin::builtin { ContentRegistry::DataInspector::add("hex.builtin.inspector.u8", sizeof(u8), [](auto buffer, auto endian, auto style) { auto format = (style == Style::Decimal) ? "{0:d}" : ((style == Style::Hexadecimal) ? "0x{0:02X}" : "0o{0:03o}"); - auto value = hex::format(format, *reinterpret_cast(buffer.data())); + auto value = hex::format(format, *reinterpret_cast(buffer.data())); return [value] { ImGui::TextUnformatted(value.c_str()); return value; }; }); @@ -48,7 +48,7 @@ namespace hex::plugin::builtin { ContentRegistry::DataInspector::add("hex.builtin.inspector.i8", sizeof(i8), [](auto buffer, auto endian, auto style) { auto format = (style == Style::Decimal) ? "{0}{1:d}" : ((style == Style::Hexadecimal) ? "{0}0x{1:02X}" : "{0}0o{1:03o}"); - auto number = hex::changeEndianess(*reinterpret_cast(buffer.data()), endian); + auto number = hex::changeEndianess(*reinterpret_cast(buffer.data()), endian); bool negative = number < 0; auto value = hex::format(format, negative ? "-" : "", std::abs(number)); @@ -58,7 +58,7 @@ namespace hex::plugin::builtin { ContentRegistry::DataInspector::add("hex.builtin.inspector.u16", sizeof(u16), [](auto buffer, auto endian, auto style) { auto format = (style == Style::Decimal) ? "{0:d}" : ((style == Style::Hexadecimal) ? "0x{0:04X}" : "0o{0:06o}"); - auto value = hex::format(format, hex::changeEndianess(*reinterpret_cast(buffer.data()), endian)); + auto value = hex::format(format, hex::changeEndianess(*reinterpret_cast(buffer.data()), endian)); return [value] { ImGui::TextUnformatted(value.c_str()); return value; }; }); @@ -66,7 +66,7 @@ namespace hex::plugin::builtin { ContentRegistry::DataInspector::add("hex.builtin.inspector.i16", sizeof(i16), [](auto buffer, auto endian, auto style) { auto format = (style == Style::Decimal) ? "{0}{1:d}" : ((style == Style::Hexadecimal) ? "{0}0x{1:04X}" : "{0}0o{1:06o}"); - auto number = hex::changeEndianess(*reinterpret_cast(buffer.data()), endian); + auto number = hex::changeEndianess(*reinterpret_cast(buffer.data()), endian); bool negative = number < 0; auto value = hex::format(format, negative ? "-" : "", std::abs(number)); @@ -76,7 +76,7 @@ namespace hex::plugin::builtin { ContentRegistry::DataInspector::add("hex.builtin.inspector.u32", sizeof(u32), [](auto buffer, auto endian, auto style) { auto format = (style == Style::Decimal) ? "{0:d}" : ((style == Style::Hexadecimal) ? "0x{0:08X}" : "0o{0:011o}"); - auto value = hex::format(format, hex::changeEndianess(*reinterpret_cast(buffer.data()), endian)); + auto value = hex::format(format, hex::changeEndianess(*reinterpret_cast(buffer.data()), endian)); return [value] { ImGui::TextUnformatted(value.c_str()); return value; }; }); @@ -84,7 +84,7 @@ namespace hex::plugin::builtin { ContentRegistry::DataInspector::add("hex.builtin.inspector.i32", sizeof(i32), [](auto buffer, auto endian, auto style) { auto format = (style == Style::Decimal) ? "{0}{1:d}" : ((style == Style::Hexadecimal) ? "{0}0x{1:08X}" : "{0}0o{1:011o}"); - auto number = hex::changeEndianess(*reinterpret_cast(buffer.data()), endian); + auto number = hex::changeEndianess(*reinterpret_cast(buffer.data()), endian); bool negative = number < 0; auto value = hex::format(format, negative ? "-" : "", std::abs(number)); @@ -94,7 +94,7 @@ namespace hex::plugin::builtin { ContentRegistry::DataInspector::add("hex.builtin.inspector.u64", sizeof(u64), [](auto buffer, auto endian, auto style) { auto format = (style == Style::Decimal) ? "{0:d}" : ((style == Style::Hexadecimal) ? "0x{0:016X}" : "0o{0:022o}"); - auto value = hex::format(format, hex::changeEndianess(*reinterpret_cast(buffer.data()), endian)); + auto value = hex::format(format, hex::changeEndianess(*reinterpret_cast(buffer.data()), endian)); return [value] { ImGui::TextUnformatted(value.c_str()); return value; }; }); @@ -102,7 +102,7 @@ namespace hex::plugin::builtin { ContentRegistry::DataInspector::add("hex.builtin.inspector.i64", sizeof(i64), [](auto buffer, auto endian, auto style) { auto format = (style == Style::Decimal) ? "{0}{1:d}" : ((style == Style::Hexadecimal) ? "{0}0x{1:016X}" : "{0}0o{1:022o}"); - auto number = hex::changeEndianess(*reinterpret_cast(buffer.data()), endian); + auto number = hex::changeEndianess(*reinterpret_cast(buffer.data()), endian); bool negative = number < 0; auto value = hex::format(format, negative ? "-" : "", std::abs(number)); @@ -110,22 +110,22 @@ namespace hex::plugin::builtin { }); ContentRegistry::DataInspector::add("hex.builtin.inspector.float16", sizeof(u16), [](auto buffer, auto endian, auto style) { - auto value = hex::format("{0:G}", hex::changeEndianess(float16ToFloat32(*reinterpret_cast(buffer.data())), endian)); + auto value = hex::format("{0:G}", hex::changeEndianess(float16ToFloat32(*reinterpret_cast(buffer.data())), endian)); return [value] { ImGui::TextUnformatted(value.c_str()); return value; }; }); ContentRegistry::DataInspector::add("hex.builtin.inspector.float", sizeof(float), [](auto buffer, auto endian, auto style) { - auto value = hex::format("{0:G}", hex::changeEndianess(*reinterpret_cast(buffer.data()), endian)); + auto value = hex::format("{0:G}", hex::changeEndianess(*reinterpret_cast(buffer.data()), endian)); return [value] { ImGui::TextUnformatted(value.c_str()); return value; }; }); ContentRegistry::DataInspector::add("hex.builtin.inspector.double", sizeof(double), [](auto buffer, auto endian, auto style) { - auto value = hex::format("{0:G}", hex::changeEndianess(*reinterpret_cast(buffer.data()), endian)); + auto value = hex::format("{0:G}", hex::changeEndianess(*reinterpret_cast(buffer.data()), endian)); return [value] { ImGui::TextUnformatted(value.c_str()); return value; }; }); ContentRegistry::DataInspector::add("hex.builtin.inspector.ascii", sizeof(char8_t), [](auto buffer, auto endian, auto style) { - auto value = hex::format("'{0}'", makePrintable(*reinterpret_cast(buffer.data())).c_str()); + auto value = hex::format("'{0}'", makePrintable(*reinterpret_cast(buffer.data())).c_str()); return [value] { ImGui::TextUnformatted(value.c_str()); return value; }; }); @@ -146,7 +146,7 @@ namespace hex::plugin::builtin { char codepointString[5] = { 0 }; u32 codepoint = 0; - std::memcpy(utf8Buffer, reinterpret_cast(buffer.data()), 4); + std::memcpy(utf8Buffer, reinterpret_cast(buffer.data()), 4); u8 codepointSize = ImTextCharFromUtf8(&codepoint, utf8Buffer, utf8Buffer + 4); std::memcpy(codepointString, utf8Buffer, std::min(codepointSize, u8(4))); @@ -181,35 +181,35 @@ namespace hex::plugin::builtin { #if defined(OS_WINDOWS) && defined(ARCH_64_BIT) ContentRegistry::DataInspector::add("hex.builtin.inspector.time32", sizeof(u32), [](auto buffer, auto endian, auto style) { - auto endianAdjustedTime = hex::changeEndianess(*reinterpret_cast(buffer.data()), endian); + auto endianAdjustedTime = hex::changeEndianess(*reinterpret_cast(buffer.data()), endian); - std::string value; - try { - value = hex::format("{0:%a, %d.%m.%Y %H:%M:%S}", fmt::localtime(endianAdjustedTime)); - } catch (fmt::format_error &e) { - value = "Invalid"; - } + std::string value; + try { + value = hex::format("{0:%a, %d.%m.%Y %H:%M:%S}", fmt::localtime(endianAdjustedTime)); + } catch (fmt::format_error &e) { + value = "Invalid"; + } - return [value] { ImGui::TextUnformatted(value.c_str()); return value; }; - }); + return [value] { ImGui::TextUnformatted(value.c_str()); return value; }; + }); - ContentRegistry::DataInspector::add("hex.builtin.inspector.time64", sizeof(u64), [](auto buffer, auto endian, auto style) { - auto endianAdjustedTime = hex::changeEndianess(*reinterpret_cast(buffer.data()), endian); + ContentRegistry::DataInspector::add("hex.builtin.inspector.time64", sizeof(u64), [](auto buffer, auto endian, auto style) { + auto endianAdjustedTime = hex::changeEndianess(*reinterpret_cast(buffer.data()), endian); - std::string value; - try { - value = hex::format("{0:%a, %d.%m.%Y %H:%M:%S}", fmt::localtime(endianAdjustedTime)); - } catch (fmt::format_error &e) { - value = "Invalid"; - } + std::string value; + try { + value = hex::format("{0:%a, %d.%m.%Y %H:%M:%S}", fmt::localtime(endianAdjustedTime)); + } catch (fmt::format_error &e) { + value = "Invalid"; + } - return [value] { ImGui::TextUnformatted(value.c_str()); return value; }; - }); + return [value] { ImGui::TextUnformatted(value.c_str()); return value; }; + }); #else ContentRegistry::DataInspector::add("hex.builtin.inspector.time", sizeof(time_t), [](auto buffer, auto endian, auto style) { - auto endianAdjustedTime = hex::changeEndianess(*reinterpret_cast(buffer.data()), endian); + auto endianAdjustedTime = hex::changeEndianess(*reinterpret_cast(buffer.data()), endian); std::string value; try { @@ -231,25 +231,28 @@ namespace hex::plugin::builtin { hex::changeEndianess(guid.data1, endian), hex::changeEndianess(guid.data2, endian), hex::changeEndianess(guid.data3, endian), - guid.data4[0], guid.data4[1], guid.data4[2], guid.data4[3], - guid.data4[4], guid.data4[5], guid.data4[6], guid.data4[7]); + guid.data4[0], + guid.data4[1], + guid.data4[2], + guid.data4[3], + guid.data4[4], + guid.data4[5], + guid.data4[6], + guid.data4[7]); return [value] { ImGui::TextUnformatted(value.c_str()); return value; }; }); ContentRegistry::DataInspector::add("hex.builtin.inspector.rgba8", sizeof(u32), [](auto buffer, auto endian, auto style) { - ImColor value(hex::changeEndianess(*reinterpret_cast(buffer.data()), endian)); + ImColor value(hex::changeEndianess(*reinterpret_cast(buffer.data()), endian)); auto stringValue = hex::format("(0x{:02X}, 0x{:02X}, 0x{:02X}, 0x{:02X})", u8(0xFF * (value.Value.x)), u8(0xFF * (value.Value.y)), u8(0xFF * (value.Value.z)), u8(0xFF * (value.Value.w))); return [value, stringValue] { - ImGui::ColorButton("##inspectorColor", value, - ImGuiColorEditFlags_None, - ImVec2(ImGui::GetColumnWidth(), ImGui::GetTextLineHeight())); + ImGui::ColorButton("##inspectorColor", value, ImGuiColorEditFlags_None, ImVec2(ImGui::GetColumnWidth(), ImGui::GetTextLineHeight())); return stringValue; }; }); - } } \ No newline at end of file diff --git a/plugins/builtin/source/content/data_processor_nodes.cpp b/plugins/builtin/source/content/data_processor_nodes.cpp index 2a77d317e..a00a94780 100644 --- a/plugins/builtin/source/content/data_processor_nodes.cpp +++ b/plugins/builtin/source/content/data_processor_nodes.cpp @@ -15,20 +15,16 @@ namespace hex::plugin::builtin { class NodeNullptr : public dp::Node { public: - NodeNullptr() : Node("hex.builtin.nodes.constants.nullptr.header", { - dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "hex.builtin.nodes.constants.nullptr.output") - }) {} + NodeNullptr() : Node("hex.builtin.nodes.constants.nullptr.header", { dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "hex.builtin.nodes.constants.nullptr.output") }) { } void process() override { - this->setBufferOnOutput(0, { }); + this->setBufferOnOutput(0, {}); } }; class NodeBuffer : public dp::Node { public: - NodeBuffer() : Node("hex.builtin.nodes.constants.buffer.header", { - dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "hex.builtin.nodes.constants.buffer.output") - }) {} + NodeBuffer() : Node("hex.builtin.nodes.constants.buffer.header", { dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "hex.builtin.nodes.constants.buffer.output") }) { } void drawNode() override { constexpr int StepSize = 1, FastStepSize = 10; @@ -64,21 +60,19 @@ namespace hex::plugin::builtin { class NodeString : public dp::Node { public: - NodeString() : Node("hex.builtin.nodes.constants.string.header", { - dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "hex.builtin.nodes.constants.string.output") - }) { + NodeString() : Node("hex.builtin.nodes.constants.string.header", { dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "hex.builtin.nodes.constants.string.output") }) { this->m_value.resize(0xFFF, 0x00); } void drawNode() override { ImGui::PushItemWidth(100); - ImGui::InputText("##string", reinterpret_cast(this->m_value.data()), this->m_value.size() - 1); + ImGui::InputText("##string", reinterpret_cast(this->m_value.data()), this->m_value.size() - 1); ImGui::PopItemWidth(); } void process() override { std::vector output(std::strlen(this->m_value.c_str()) + 1, 0x00); - std::strcpy(reinterpret_cast(output.data()), this->m_value.c_str()); + std::strcpy(reinterpret_cast(output.data()), this->m_value.c_str()); output.pop_back(); @@ -101,9 +95,7 @@ namespace hex::plugin::builtin { class NodeInteger : public dp::Node { public: - NodeInteger() : Node("hex.builtin.nodes.constants.int.header", { - dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.constants.int.output") - }) {} + NodeInteger() : Node("hex.builtin.nodes.constants.int.header", { dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.constants.int.output") }) { } void drawNode() override { ImGui::PushItemWidth(100); @@ -134,9 +126,7 @@ namespace hex::plugin::builtin { class NodeFloat : public dp::Node { public: - NodeFloat() : Node("hex.builtin.nodes.constants.float.header", { - dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Float, "hex.builtin.nodes.constants.float.output") - }) {} + NodeFloat() : Node("hex.builtin.nodes.constants.float.header", { dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Float, "hex.builtin.nodes.constants.float.output") }) { } void drawNode() override { ImGui::PushItemWidth(100); @@ -170,9 +160,9 @@ namespace hex::plugin::builtin { public: NodeRGBA8() : Node("hex.builtin.nodes.constants.rgba8.header", { dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.constants.rgba8.output.r"), - dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.constants.rgba8.output.g"), - dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.constants.rgba8.output.b"), - dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.constants.rgba8.output.a")}) {} + dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.constants.rgba8.output.g"), + dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.constants.rgba8.output.b"), + dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.constants.rgba8.output.a") }) { } void drawNode() override { ImGui::PushItemWidth(200); @@ -185,7 +175,6 @@ namespace hex::plugin::builtin { this->setBufferOnOutput(1, hex::toBytes(this->m_color.Value.y * 0xFF)); this->setBufferOnOutput(2, hex::toBytes(this->m_color.Value.z * 0xFF)); this->setBufferOnOutput(3, hex::toBytes(this->m_color.Value.w * 0xFF)); - } void store(nlohmann::json &j) override { @@ -208,16 +197,15 @@ namespace hex::plugin::builtin { class NodeComment : public dp::Node { public: - NodeComment() : Node("hex.builtin.nodes.constants.comment.header", { }) { + NodeComment() : Node("hex.builtin.nodes.constants.comment.header", {}) { this->m_comment.resize(0xFFF, 0x00); } void drawNode() override { - ImGui::InputTextMultiline("##string", reinterpret_cast(this->m_comment.data()), this->m_comment.size() - 1, ImVec2(150, 100)); + ImGui::InputTextMultiline("##string", reinterpret_cast(this->m_comment.data()), this->m_comment.size() - 1, ImVec2(150, 100)); } void process() override { - } void store(nlohmann::json &j) override { @@ -237,9 +225,7 @@ namespace hex::plugin::builtin { class NodeDisplayInteger : public dp::Node { public: - NodeDisplayInteger() : Node("hex.builtin.nodes.display.int.header", { - dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.display.int.input") - }) {} + NodeDisplayInteger() : Node("hex.builtin.nodes.display.int.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.display.int.input") }) { } void drawNode() override { ImGui::PushItemWidth(150); @@ -263,9 +249,7 @@ namespace hex::plugin::builtin { class NodeDisplayFloat : public dp::Node { public: - NodeDisplayFloat() : Node("hex.builtin.nodes.display.float.header", { - dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Float, "hex.builtin.nodes.display.float.input") - }) {} + NodeDisplayFloat() : Node("hex.builtin.nodes.display.float.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Float, "hex.builtin.nodes.display.float.input") }) { } void drawNode() override { ImGui::PushItemWidth(150); @@ -290,9 +274,7 @@ namespace hex::plugin::builtin { class NodeBitwiseNOT : public dp::Node { public: - NodeBitwiseNOT() : Node("hex.builtin.nodes.bitwise.not.header", { - dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.bitwise.not.input"), - dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "hex.builtin.nodes.bitwise.not.output") }) {} + NodeBitwiseNOT() : Node("hex.builtin.nodes.bitwise.not.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.bitwise.not.input"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "hex.builtin.nodes.bitwise.not.output") }) { } void process() override { auto input = this->getBufferOnInput(0); @@ -307,10 +289,7 @@ namespace hex::plugin::builtin { class NodeBitwiseAND : public dp::Node { public: - NodeBitwiseAND() : Node("hex.builtin.nodes.bitwise.and.header", { - dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.bitwise.and.input.a"), - dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.bitwise.and.input.b"), - dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "hex.builtin.nodes.bitwise.and.output") }) {} + NodeBitwiseAND() : Node("hex.builtin.nodes.bitwise.and.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.bitwise.and.input.a"), dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.bitwise.and.input.b"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "hex.builtin.nodes.bitwise.and.output") }) { } void process() override { auto inputA = this->getBufferOnInput(0); @@ -327,10 +306,7 @@ namespace hex::plugin::builtin { class NodeBitwiseOR : public dp::Node { public: - NodeBitwiseOR() : Node("hex.builtin.nodes.bitwise.or.header", { - dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.bitwise.or.input.a"), - dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.bitwise.or.input.b"), - dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "hex.builtin.nodes.bitwise.or.output") }) {} + NodeBitwiseOR() : Node("hex.builtin.nodes.bitwise.or.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.bitwise.or.input.a"), dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.bitwise.or.input.b"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "hex.builtin.nodes.bitwise.or.output") }) { } void process() override { auto inputA = this->getBufferOnInput(0); @@ -347,10 +323,7 @@ namespace hex::plugin::builtin { class NodeBitwiseXOR : public dp::Node { public: - NodeBitwiseXOR() : Node("hex.builtin.nodes.bitwise.xor.header", { - dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.bitwise.xor.input.a"), - dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.bitwise.xor.input.b"), - dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "hex.builtin.nodes.bitwise.xor.output") }) {} + NodeBitwiseXOR() : Node("hex.builtin.nodes.bitwise.xor.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.bitwise.xor.input.a"), dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.bitwise.xor.input.b"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "hex.builtin.nodes.bitwise.xor.output") }) { } void process() override { auto inputA = this->getBufferOnInput(0); @@ -367,11 +340,7 @@ namespace hex::plugin::builtin { class NodeReadData : public dp::Node { public: - NodeReadData() : Node("hex.builtin.nodes.data_access.read.header", { - dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.data_access.read.address"), - dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.data_access.read.size"), - dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "hex.builtin.nodes.data_access.read.data") - }) { } + NodeReadData() : Node("hex.builtin.nodes.data_access.read.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.data_access.read.address"), dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.data_access.read.size"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "hex.builtin.nodes.data_access.read.data") }) { } void process() override { auto address = this->getIntegerOnInput(0); @@ -388,9 +357,7 @@ namespace hex::plugin::builtin { class NodeWriteData : public dp::Node { public: - NodeWriteData() : Node("hex.builtin.nodes.data_access.write.header", { - dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.data_access.write.address"), - dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.data_access.write.data") }) {} + NodeWriteData() : Node("hex.builtin.nodes.data_access.write.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.data_access.write.address"), dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.data_access.write.data") }) { } void process() override { auto address = this->getIntegerOnInput(0); @@ -402,9 +369,7 @@ namespace hex::plugin::builtin { class NodeDataSize : public dp::Node { public: - NodeDataSize() : Node("hex.builtin.nodes.data_access.size.header", { - dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.data_access.size.size") - }) { } + NodeDataSize() : Node("hex.builtin.nodes.data_access.size.header", { dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.data_access.size.size") }) { } void process() override { auto size = ImHexApi::Provider::get()->getActualSize(); @@ -415,9 +380,7 @@ namespace hex::plugin::builtin { class NodeCastIntegerToBuffer : public dp::Node { public: - NodeCastIntegerToBuffer() : Node("hex.builtin.nodes.casting.int_to_buffer.header", { - dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.casting.int_to_buffer.input"), - dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "hex.builtin.nodes.casting.int_to_buffer.output") }) {} + NodeCastIntegerToBuffer() : Node("hex.builtin.nodes.casting.int_to_buffer.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.casting.int_to_buffer.input"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "hex.builtin.nodes.casting.int_to_buffer.output") }) { } void process() override { auto input = this->getIntegerOnInput(0); @@ -431,9 +394,7 @@ namespace hex::plugin::builtin { class NodeCastBufferToInteger : public dp::Node { public: - NodeCastBufferToInteger() : Node("hex.builtin.nodes.casting.buffer_to_int.header", { - dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.casting.buffer_to_int.input"), - dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.casting.buffer_to_int.output") }) {} + NodeCastBufferToInteger() : Node("hex.builtin.nodes.casting.buffer_to_int.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.casting.buffer_to_int.input"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.casting.buffer_to_int.output") }) { } void process() override { auto input = this->getBufferOnInput(0); @@ -447,10 +408,7 @@ namespace hex::plugin::builtin { class NodeArithmeticAdd : public dp::Node { public: - NodeArithmeticAdd() : Node("hex.builtin.nodes.arithmetic.add.header", { - dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.arithmetic.add.input.a"), - dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.arithmetic.add.input.b"), - dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.arithmetic.add.output") }) {} + NodeArithmeticAdd() : Node("hex.builtin.nodes.arithmetic.add.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.arithmetic.add.input.a"), dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.arithmetic.add.input.b"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.arithmetic.add.output") }) { } void process() override { auto inputA = this->getIntegerOnInput(0); @@ -464,10 +422,7 @@ namespace hex::plugin::builtin { class NodeArithmeticSubtract : public dp::Node { public: - NodeArithmeticSubtract() : Node("hex.builtin.nodes.arithmetic.sub.header", { - dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.arithmetic.sub.input.a"), - dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.arithmetic.sub.input.b"), - dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.arithmetic.sub.output") }) {} + NodeArithmeticSubtract() : Node("hex.builtin.nodes.arithmetic.sub.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.arithmetic.sub.input.a"), dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.arithmetic.sub.input.b"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.arithmetic.sub.output") }) { } void process() override { auto inputA = this->getIntegerOnInput(0); @@ -481,10 +436,7 @@ namespace hex::plugin::builtin { class NodeArithmeticMultiply : public dp::Node { public: - NodeArithmeticMultiply() : Node("hex.builtin.nodes.arithmetic.mul.header", { - dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.arithmetic.mul.input.a"), - dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.arithmetic.mul.input.b"), - dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.arithmetic.mul.output") }) {} + NodeArithmeticMultiply() : Node("hex.builtin.nodes.arithmetic.mul.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.arithmetic.mul.input.a"), dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.arithmetic.mul.input.b"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.arithmetic.mul.output") }) { } void process() override { auto inputA = this->getIntegerOnInput(0); @@ -498,10 +450,7 @@ namespace hex::plugin::builtin { class NodeArithmeticDivide : public dp::Node { public: - NodeArithmeticDivide() : Node("hex.builtin.nodes.arithmetic.div.header", { - dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.arithmetic.div.input.a"), - dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.arithmetic.div.input.b"), - dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.arithmetic.div.output") }) {} + NodeArithmeticDivide() : Node("hex.builtin.nodes.arithmetic.div.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.arithmetic.div.input.a"), dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.arithmetic.div.input.b"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.arithmetic.div.output") }) { } void process() override { auto inputA = this->getIntegerOnInput(0); @@ -518,10 +467,7 @@ namespace hex::plugin::builtin { class NodeArithmeticModulus : public dp::Node { public: - NodeArithmeticModulus() : Node("hex.builtin.nodes.arithmetic.mod.header", { - dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.arithmetic.mod.input.a"), - dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.arithmetic.mod.input.b"), - dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.arithmetic.mod.output") }) {} + NodeArithmeticModulus() : Node("hex.builtin.nodes.arithmetic.mod.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.arithmetic.mod.input.a"), dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.arithmetic.mod.input.b"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.arithmetic.mod.output") }) { } void process() override { auto inputA = this->getIntegerOnInput(0); @@ -538,10 +484,7 @@ namespace hex::plugin::builtin { class NodeBufferCombine : public dp::Node { public: - NodeBufferCombine() : Node("hex.builtin.nodes.buffer.combine.header", { - dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.buffer.combine.input.a"), - dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.buffer.combine.input.b"), - dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "hex.builtin.nodes.buffer.combine.output") }) {} + NodeBufferCombine() : Node("hex.builtin.nodes.buffer.combine.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.buffer.combine.input.a"), dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.buffer.combine.input.b"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "hex.builtin.nodes.buffer.combine.output") }) { } void process() override { auto inputA = this->getBufferOnInput(0); @@ -556,11 +499,7 @@ namespace hex::plugin::builtin { class NodeBufferSlice : public dp::Node { public: - NodeBufferSlice() : Node("hex.builtin.nodes.buffer.slice.header", { - dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.buffer.slice.input.buffer"), - dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.buffer.slice.input.from"), - dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.buffer.slice.input.to"), - dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "hex.builtin.nodes.buffer.slice.output") }) {} + NodeBufferSlice() : Node("hex.builtin.nodes.buffer.slice.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.buffer.slice.input.buffer"), dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.buffer.slice.input.from"), dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.buffer.slice.input.to"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "hex.builtin.nodes.buffer.slice.output") }) { } void process() override { auto input = this->getBufferOnInput(0); @@ -580,10 +519,7 @@ namespace hex::plugin::builtin { class NodeBufferRepeat : public dp::Node { public: - NodeBufferRepeat() : Node("hex.builtin.nodes.buffer.repeat.header", { - dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.buffer.repeat.input.buffer"), - dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.buffer.repeat.input.count"), - dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "hex.builtin.nodes.buffer.combine.output") }) {} + NodeBufferRepeat() : Node("hex.builtin.nodes.buffer.repeat.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.buffer.repeat.input.buffer"), dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.buffer.repeat.input.count"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "hex.builtin.nodes.buffer.combine.output") }) { } void process() override { auto buffer = this->getBufferOnInput(0); @@ -602,10 +538,10 @@ namespace hex::plugin::builtin { class NodeIf : public dp::Node { public: NodeIf() : Node("ex.builtin.nodes.control_flow.if.header", - { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.if.condition"), - dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.control_flow.if.true"), - dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.control_flow.if.false"), - dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "hex.builtin.nodes.control_flow.if.output") }) {} + { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.if.condition"), + dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.control_flow.if.true"), + dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.control_flow.if.false"), + dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "hex.builtin.nodes.control_flow.if.output") }) { } void process() override { auto cond = this->getIntegerOnInput(0); @@ -616,7 +552,6 @@ namespace hex::plugin::builtin { this->setBufferOnOutput(3, trueData); else this->setBufferOnOutput(3, falseData); - } }; @@ -624,8 +559,8 @@ namespace hex::plugin::builtin { public: NodeEquals() : Node("hex.builtin.nodes.control_flow.equals.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.equals.input.a"), - dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.equals.input.b"), - dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.equals.output") }) {} + dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.equals.input.b"), + dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.equals.output") }) { } void process() override { auto inputA = this->getIntegerOnInput(0); @@ -638,8 +573,8 @@ namespace hex::plugin::builtin { class NodeNot : public dp::Node { public: NodeNot() : Node("hex.builtin.nodes.control_flow.not.header", - { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.not.input"), - dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.not.output") }) {} + { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.not.input"), + dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.not.output") }) { } void process() override { auto input = this->getIntegerOnInput(0); @@ -652,8 +587,8 @@ namespace hex::plugin::builtin { public: NodeGreaterThan() : Node("hex.builtin.nodes.control_flow.gt.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.gt.input.a"), - dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.gt.input.b"), - dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.gt.output") }) {} + dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.gt.input.b"), + dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.gt.output") }) { } void process() override { auto inputA = this->getIntegerOnInput(0); @@ -667,8 +602,8 @@ namespace hex::plugin::builtin { public: NodeLessThan() : Node("hex.builtin.nodes.control_flow.lt.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.lt.input.a"), - dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.lt.input.b"), - dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.lt.output") }) {} + dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.lt.input.b"), + dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.lt.output") }) { } void process() override { auto inputA = this->getIntegerOnInput(0); @@ -682,8 +617,8 @@ namespace hex::plugin::builtin { public: NodeBoolAND() : Node("hex.builtin.nodes.control_flow.and.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.and.input.a"), - dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.and.input.b"), - dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.and.output") }) {} + dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.and.input.b"), + dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.and.output") }) { } void process() override { auto inputA = this->getIntegerOnInput(0); @@ -697,8 +632,8 @@ namespace hex::plugin::builtin { public: NodeBoolOR() : Node("hex.builtin.nodes.control_flow.or.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.or.input.a"), - dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.or.input.b"), - dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.or.output") }) {} + dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.or.input.b"), + dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.or.output") }) { } void process() override { auto inputA = this->getIntegerOnInput(0); @@ -712,10 +647,10 @@ namespace hex::plugin::builtin { public: NodeCryptoAESDecrypt() : Node("hex.builtin.nodes.crypto.aes.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.crypto.aes.key"), - dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.crypto.aes.iv"), - dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.crypto.aes.nonce"), - dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.crypto.aes.input"), - dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "hex.builtin.nodes.crypto.aes.output") }) {} + dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.crypto.aes.iv"), + dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.crypto.aes.nonce"), + dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.crypto.aes.input"), + dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "hex.builtin.nodes.crypto.aes.output") }) { } void drawNode() override { ImGui::PushItemWidth(100); @@ -766,9 +701,7 @@ namespace hex::plugin::builtin { class NodeDecodingBase64 : public dp::Node { public: - NodeDecodingBase64() : Node("hex.builtin.nodes.decoding.base64.header", { - dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.decoding.base64.input"), - dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "hex.builtin.nodes.decoding.base64.output") }) {} + NodeDecodingBase64() : Node("hex.builtin.nodes.decoding.base64.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.decoding.base64.input"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "hex.builtin.nodes.decoding.base64.output") }) { } void process() override { auto input = this->getBufferOnInput(0); @@ -781,9 +714,7 @@ namespace hex::plugin::builtin { class NodeDecodingHex : public dp::Node { public: - NodeDecodingHex() : Node("hex.builtin.nodes.decoding.hex.header", { - dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.decoding.hex.input"), - dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "hex.builtin.nodes.decoding.hex.output") }) {} + NodeDecodingHex() : Node("hex.builtin.nodes.decoding.hex.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.decoding.hex.input"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "hex.builtin.nodes.decoding.hex.output") }) { } void process() override { auto input = this->getBufferOnInput(0); diff --git a/plugins/builtin/source/content/layouts.cpp b/plugins/builtin/source/content/layouts.cpp index a29d6b28e..f2245da46 100644 --- a/plugins/builtin/source/content/layouts.cpp +++ b/plugins/builtin/source/content/layouts.cpp @@ -10,30 +10,27 @@ namespace hex::plugin::builtin { if (view != nullptr) { view->getWindowOpenState() = true; ImGui::DockBuilderDockWindow(view->getName().c_str(), dockId); - } } void registerLayouts() { ContentRegistry::Interface::addLayout("hex.builtin.layouts.default", [](ImGuiID dockMain) { - ImGuiID hexEditor = ImGui::DockBuilderSplitNode(dockMain, ImGuiDir_Left, 0.7F, nullptr, &dockMain); - ImGuiID utils = ImGui::DockBuilderSplitNode(dockMain, ImGuiDir_Right, 0.8F, nullptr, &dockMain); - ImGuiID patternData = ImGui::DockBuilderSplitNode(hexEditor, ImGuiDir_Down, 0.3F, nullptr, &hexEditor); - ImGuiID inspector = ImGui::DockBuilderSplitNode(hexEditor, ImGuiDir_Right, 0.3F, nullptr, &hexEditor); + ImGuiID hexEditor = ImGui::DockBuilderSplitNode(dockMain, ImGuiDir_Left, 0.7F, nullptr, &dockMain); + ImGuiID utils = ImGui::DockBuilderSplitNode(dockMain, ImGuiDir_Right, 0.8F, nullptr, &dockMain); + ImGuiID patternData = ImGui::DockBuilderSplitNode(hexEditor, ImGuiDir_Down, 0.3F, nullptr, &hexEditor); + ImGuiID inspector = ImGui::DockBuilderSplitNode(hexEditor, ImGuiDir_Right, 0.3F, nullptr, &hexEditor); - openViewAndDockTo("hex.builtin.view.hexeditor.name", hexEditor); - openViewAndDockTo("hex.builtin.view.data_inspector.name", inspector); - openViewAndDockTo("hex.builtin.view.pattern_data.name", patternData); + openViewAndDockTo("hex.builtin.view.hexeditor.name", hexEditor); + openViewAndDockTo("hex.builtin.view.data_inspector.name", inspector); + openViewAndDockTo("hex.builtin.view.pattern_data.name", patternData); - openViewAndDockTo("hex.builtin.view.pattern_editor.name", utils); - openViewAndDockTo("hex.builtin.view.hashes.name", utils); + openViewAndDockTo("hex.builtin.view.pattern_editor.name", utils); + openViewAndDockTo("hex.builtin.view.hashes.name", utils); openViewAndDockTo("hex.builtin.view.data_information.name", utils); - openViewAndDockTo("hex.builtin.view.strings.name", utils); - openViewAndDockTo("hex.builtin.view.bookmarks.name", utils); - + openViewAndDockTo("hex.builtin.view.strings.name", utils); + openViewAndDockTo("hex.builtin.view.bookmarks.name", utils); }); - } } \ No newline at end of file diff --git a/plugins/builtin/source/content/main_menu_items.cpp b/plugins/builtin/source/content/main_menu_items.cpp index 62c448338..a992ae1a1 100644 --- a/plugins/builtin/source/content/main_menu_items.cpp +++ b/plugins/builtin/source/content/main_menu_items.cpp @@ -11,24 +11,24 @@ namespace hex::plugin::builtin { void registerMainMenuEntries() { - ContentRegistry::Interface::registerMainMenuItem("hex.builtin.menu.file", 1000); - ContentRegistry::Interface::registerMainMenuItem("hex.builtin.menu.edit", 2000); - ContentRegistry::Interface::registerMainMenuItem("hex.builtin.menu.view", 3000); + ContentRegistry::Interface::registerMainMenuItem("hex.builtin.menu.file", 1000); + ContentRegistry::Interface::registerMainMenuItem("hex.builtin.menu.edit", 2000); + ContentRegistry::Interface::registerMainMenuItem("hex.builtin.menu.view", 3000); ContentRegistry::Interface::registerMainMenuItem("hex.builtin.menu.layout", 4000); - ContentRegistry::Interface::registerMainMenuItem("hex.builtin.menu.help", 5000); + ContentRegistry::Interface::registerMainMenuItem("hex.builtin.menu.help", 5000); - ContentRegistry::Interface::addMenuItem("hex.builtin.menu.view", 1000, []{ + ContentRegistry::Interface::addMenuItem("hex.builtin.menu.view", 1000, [] { for (auto &[name, view] : ContentRegistry::Views::getEntries()) { if (view->hasViewMenuItemEntry()) ImGui::MenuItem(LangEntry(view->getUnlocalizedName()), "", &view->getWindowOpenState()); } }); - #if defined(DEBUG) - ContentRegistry::Interface::addMenuItem("hex.builtin.menu.view", 2000, []{ - ImGui::MenuItem("hex.builtin.menu.view.demo"_lang, "", &g_demoWindowOpen); - }); - #endif +#if defined(DEBUG) + ContentRegistry::Interface::addMenuItem("hex.builtin.menu.view", 2000, [] { + ImGui::MenuItem("hex.builtin.menu.view.demo"_lang, "", &g_demoWindowOpen); + }); +#endif ContentRegistry::Interface::addMenuItem("hex.builtin.menu.layout", 1000, [] { for (auto &[layoutName, func] : ContentRegistry::Interface::getLayouts()) { @@ -48,7 +48,7 @@ namespace hex::plugin::builtin { }); - (void) EventManager::subscribe([]{ + (void)EventManager::subscribe([] { if (g_demoWindowOpen) { ImGui::ShowDemoWindow(&g_demoWindowOpen); ImPlot::ShowDemoWindow(&g_demoWindowOpen); diff --git a/plugins/builtin/source/content/pl_builtin_functions.cpp b/plugins/builtin/source/content/pl_builtin_functions.cpp index 57226813e..fe3eb2935 100644 --- a/plugins/builtin/source/content/pl_builtin_functions.cpp +++ b/plugins/builtin/source/content/pl_builtin_functions.cpp @@ -25,13 +25,13 @@ namespace hex::plugin::builtin { auto ¶m = params[i]; std::visit(overloaded { - [&](pl::PatternData* value) { - formatArgs.push_back(value->toString(ctx->getProvider())); - }, - [&](auto &&value) { - formatArgs.push_back(value); - } - }, param); + [&](pl::PatternData *value) { + formatArgs.push_back(value->toString(ctx->getProvider())); + }, + [&](auto &&value) { + formatArgs.push_back(value); + } }, + param); } try { @@ -93,7 +93,6 @@ namespace hex::plugin::builtin { return ""; } }); - } ContentRegistry::PatternLanguage::Namespace nsStdMem = { "std", "mem" }; @@ -188,7 +187,6 @@ namespace hex::plugin::builtin { return result; }); - } ContentRegistry::PatternLanguage::Namespace nsStdString = { "std", "string" }; @@ -205,12 +203,12 @@ namespace hex::plugin::builtin { auto string = Token::literalToString(params[0], false); auto index = Token::literalToSigned(params[1]); - #if defined(OS_MACOS) - const auto signIndex = index >> (sizeof(index) * 8 - 1); - const auto absIndex = (index ^ signIndex) - signIndex; - #else +#if defined(OS_MACOS) + const auto signIndex = index >> (sizeof(index) * 8 - 1); + const auto absIndex = (index ^ signIndex) - signIndex; +#else const auto absIndex = std::abs(index); - #endif +#endif if (absIndex > string.length()) LogConsole::abortEvaluation("character index out of range"); @@ -247,7 +245,6 @@ namespace hex::plugin::builtin { return double(std::strtod(string.c_str(), nullptr)); }); - } ContentRegistry::PatternLanguage::Namespace nsStdHttp = { "std", "http" }; @@ -275,11 +272,17 @@ namespace hex::plugin::builtin { File::Mode mode; switch (modeEnum) { - case 1: mode = File::Mode::Read; break; - case 2: mode = File::Mode::Write; break; - case 3: mode = File::Mode::Create; break; - default: - LogConsole::abortEvaluation("invalid file open mode"); + case 1: + mode = File::Mode::Read; + break; + case 2: + mode = File::Mode::Write; + break; + case 3: + mode = File::Mode::Create; + break; + default: + LogConsole::abortEvaluation("invalid file open mode"); } auto file = File(path, mode); @@ -288,7 +291,7 @@ namespace hex::plugin::builtin { LogConsole::abortEvaluation(hex::format("failed to open file {}", path)); fileCounter++; - openFiles.emplace(std::pair{ fileCounter, std::move(file) }); + openFiles.emplace(std::pair { fileCounter, std::move(file) }); return u128(fileCounter); }); @@ -302,7 +305,7 @@ namespace hex::plugin::builtin { openFiles.erase(file); - return { }; + return {}; }); /* read(file, size) */ @@ -326,7 +329,7 @@ namespace hex::plugin::builtin { openFiles[file].write(data); - return { }; + return {}; }); /* seek(file, offset) */ @@ -339,7 +342,7 @@ namespace hex::plugin::builtin { openFiles[file].seek(offset); - return { }; + return {}; }); /* size(file) */ @@ -362,7 +365,7 @@ namespace hex::plugin::builtin { openFiles[file].setSize(size); - return { }; + return {}; }); /* flush(file) */ @@ -374,7 +377,7 @@ namespace hex::plugin::builtin { openFiles[file].flush(); - return { }; + return {}; }); /* remove(file) */ @@ -386,7 +389,7 @@ namespace hex::plugin::builtin { openFiles[file].remove(); - return { }; + return {}; }); } } diff --git a/plugins/builtin/source/content/providers.cpp b/plugins/builtin/source/content/providers.cpp index 50b260de8..1d5e10187 100644 --- a/plugins/builtin/source/content/providers.cpp +++ b/plugins/builtin/source/content/providers.cpp @@ -11,7 +11,6 @@ namespace hex::plugin::builtin { ContentRegistry::Provider::add("hex.builtin.provider.file", false); ContentRegistry::Provider::add("hex.builtin.provider.gdb"); ContentRegistry::Provider::add("hex.builtin.provider.disk"); - } } \ No newline at end of file diff --git a/plugins/builtin/source/content/providers/disk_provider.cpp b/plugins/builtin/source/content/providers/disk_provider.cpp index 99921e7a3..1700dc748 100644 --- a/plugins/builtin/source/content/providers/disk_provider.cpp +++ b/plugins/builtin/source/content/providers/disk_provider.cpp @@ -5,14 +5,14 @@ #include #include -#if defined (OS_LINUX) +#if defined(OS_LINUX) #include #include #include #include #define lseek lseek64 -#elif defined (OS_MACOS) +#elif defined(OS_MACOS) #include #include #include @@ -30,11 +30,11 @@ namespace hex::plugin::builtin::prv { } bool DiskProvider::isAvailable() const { - #if defined (OS_WINDOWS) - return this->m_diskHandle != INVALID_HANDLE_VALUE; - #else - return this->m_diskHandle != -1; - #endif +#if defined(OS_WINDOWS) + return this->m_diskHandle != INVALID_HANDLE_VALUE; +#else + return this->m_diskHandle != -1; +#endif } bool DiskProvider::isReadable() const { @@ -62,176 +62,176 @@ namespace hex::plugin::builtin::prv { this->m_readable = true; this->m_writable = true; - #if defined (OS_WINDOWS) +#if defined(OS_WINDOWS) - const auto &path = this->m_path.native(); + const auto &path = this->m_path.native(); - this->m_diskHandle = reinterpret_cast(CreateFileW(path.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr)); - if (this->m_diskHandle == INVALID_HANDLE_VALUE) { - this->m_diskHandle = reinterpret_cast(CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr)); - this->m_writable = false; - - if (this->m_diskHandle == INVALID_HANDLE_VALUE) - return false; - } - - { - DISK_GEOMETRY_EX diskGeometry = { 0 }; - DWORD bytesRead = 0; - if (DeviceIoControl( - this->m_diskHandle, - IOCTL_DISK_GET_DRIVE_GEOMETRY_EX, - nullptr, 0, - &diskGeometry, sizeof(DISK_GEOMETRY_EX), - &bytesRead, - nullptr)) - { - this->m_diskSize = diskGeometry.DiskSize.QuadPart; - this->m_sectorSize = diskGeometry.Geometry.BytesPerSector; - this->m_sectorBuffer.resize(this->m_sectorSize); - } - } - - if (this->m_diskHandle == nullptr || this->m_diskHandle == INVALID_HANDLE_VALUE) { - this->m_readable = false; - this->m_diskHandle = nullptr; - CloseHandle(this->m_diskHandle); + this->m_diskHandle = reinterpret_cast(CreateFileW(path.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr)); + if (this->m_diskHandle == INVALID_HANDLE_VALUE) { + this->m_diskHandle = reinterpret_cast(CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr)); + this->m_writable = false; + if (this->m_diskHandle == INVALID_HANDLE_VALUE) return false; + } + + { + DISK_GEOMETRY_EX diskGeometry = { 0 }; + DWORD bytesRead = 0; + if (DeviceIoControl( + this->m_diskHandle, + IOCTL_DISK_GET_DRIVE_GEOMETRY_EX, + nullptr, + 0, + &diskGeometry, + sizeof(DISK_GEOMETRY_EX), + &bytesRead, + nullptr)) { + this->m_diskSize = diskGeometry.DiskSize.QuadPart; + this->m_sectorSize = diskGeometry.Geometry.BytesPerSector; + this->m_sectorBuffer.resize(this->m_sectorSize); } + } + + if (this->m_diskHandle == nullptr || this->m_diskHandle == INVALID_HANDLE_VALUE) { + this->m_readable = false; + this->m_diskHandle = nullptr; + CloseHandle(this->m_diskHandle); + + return false; + } +#else + const auto &path = this->m_path.native(); - #else - const auto &path = this->m_path.native(); + struct stat driveStat; - struct stat driveStat; + ::stat(path.c_str(), &driveStat) == 0; + this->m_diskSize = driveStat.st_size; + this->m_sectorSize = 0; - ::stat(path.c_str(), &driveStat) == 0; - this->m_diskSize = driveStat.st_size; - this->m_sectorSize = 0; + this->m_diskHandle = ::open(path.c_str(), O_RDWR); + if (this->m_diskHandle == -1) { + this->m_diskHandle = ::open(path.c_str(), O_RDONLY); + this->m_writable = false; + } - this->m_diskHandle = ::open(path.c_str(), O_RDWR); - if (this->m_diskHandle == -1) { - this->m_diskHandle = ::open(path.c_str(), O_RDONLY); - this->m_writable = false; - } + if (this->m_diskHandle == -1) { + this->m_readable = false; + return false; + } - if (this->m_diskHandle == -1) { - this->m_readable = false; - return false; - } - - #endif +#endif return true; } void DiskProvider::close() { - #if defined (OS_WINDOWS) - if (this->m_diskHandle != INVALID_HANDLE_VALUE) - ::CloseHandle(this->m_diskHandle); +#if defined(OS_WINDOWS) + if (this->m_diskHandle != INVALID_HANDLE_VALUE) + ::CloseHandle(this->m_diskHandle); - this->m_diskHandle = INVALID_HANDLE_VALUE; - #else - if (this->m_diskHandle != -1) - ::close(this->m_diskHandle); + this->m_diskHandle = INVALID_HANDLE_VALUE; +#else + if (this->m_diskHandle != -1) + ::close(this->m_diskHandle); - this->m_diskHandle = -1; - #endif + this->m_diskHandle = -1; +#endif } void DiskProvider::readRaw(u64 offset, void *buffer, size_t size) { - #if defined (OS_WINDOWS) - DWORD bytesRead = 0; +#if defined(OS_WINDOWS) + DWORD bytesRead = 0; - u64 startOffset = offset; + u64 startOffset = offset; - while (size > 0) { - LARGE_INTEGER seekPosition; - seekPosition.LowPart = (offset & 0xFFFF'FFFF) - (offset % this->m_sectorSize); - seekPosition.HighPart = offset >> 32; + while (size > 0) { + LARGE_INTEGER seekPosition; + seekPosition.LowPart = (offset & 0xFFFF'FFFF) - (offset % this->m_sectorSize); + seekPosition.HighPart = offset >> 32; - if (this->m_sectorBufferAddress != seekPosition.QuadPart) { - ::SetFilePointer(this->m_diskHandle, seekPosition.LowPart, &seekPosition.HighPart, FILE_BEGIN); - ::ReadFile(this->m_diskHandle, this->m_sectorBuffer.data(), this->m_sectorBuffer.size(), &bytesRead, nullptr); - this->m_sectorBufferAddress = seekPosition.QuadPart; - } - - std::memcpy(reinterpret_cast(buffer) + (offset - startOffset), this->m_sectorBuffer.data() + (offset & (this->m_sectorSize - 1)), std::min(this->m_sectorSize, size)); - - size = std::max(static_cast(size) - this->m_sectorSize, 0); - offset += this->m_sectorSize; + if (this->m_sectorBufferAddress != seekPosition.QuadPart) { + ::SetFilePointer(this->m_diskHandle, seekPosition.LowPart, &seekPosition.HighPart, FILE_BEGIN); + ::ReadFile(this->m_diskHandle, this->m_sectorBuffer.data(), this->m_sectorBuffer.size(), &bytesRead, nullptr); + this->m_sectorBufferAddress = seekPosition.QuadPart; } - #else - u64 startOffset = offset; - while (size > 0) { - u64 seekPosition = offset - (offset % this->m_sectorSize); + std::memcpy(reinterpret_cast(buffer) + (offset - startOffset), this->m_sectorBuffer.data() + (offset & (this->m_sectorSize - 1)), std::min(this->m_sectorSize, size)); - if (this->m_sectorBufferAddress != seekPosition) { - ::lseek(this->m_diskHandle, seekPosition, SEEK_SET); - ::read(this->m_diskHandle, buffer, size); - this->m_sectorBufferAddress = seekPosition; - } + size = std::max(static_cast(size) - this->m_sectorSize, 0); + offset += this->m_sectorSize; + } +#else + u64 startOffset = offset; - std::memcpy(reinterpret_cast(buffer) + (offset - startOffset), this->m_sectorBuffer.data() + (offset & (this->m_sectorSize - 1)), std::min(this->m_sectorSize, size)); + while (size > 0) { + u64 seekPosition = offset - (offset % this->m_sectorSize); - size = std::max(static_cast(size) - this->m_sectorSize, 0); - offset += this->m_sectorSize; + if (this->m_sectorBufferAddress != seekPosition) { + ::lseek(this->m_diskHandle, seekPosition, SEEK_SET); + ::read(this->m_diskHandle, buffer, size); + this->m_sectorBufferAddress = seekPosition; } - #endif + + std::memcpy(reinterpret_cast(buffer) + (offset - startOffset), this->m_sectorBuffer.data() + (offset & (this->m_sectorSize - 1)), std::min(this->m_sectorSize, size)); + + size = std::max(static_cast(size) - this->m_sectorSize, 0); + offset += this->m_sectorSize; + } +#endif } void DiskProvider::writeRaw(u64 offset, const void *buffer, size_t size) { - #if defined (OS_WINDOWS) - DWORD bytesWritten = 0; +#if defined(OS_WINDOWS) + DWORD bytesWritten = 0; - u64 startOffset = offset; + u64 startOffset = offset; - std::vector modifiedSectorBuffer; - modifiedSectorBuffer.resize(this->m_sectorSize); + std::vector modifiedSectorBuffer; + modifiedSectorBuffer.resize(this->m_sectorSize); - while (size > 0) { - u64 sectorBase = offset - (offset % this->m_sectorSize); - size_t currSize = std::min(size, this->m_sectorSize); + while (size > 0) { + u64 sectorBase = offset - (offset % this->m_sectorSize); + size_t currSize = std::min(size, this->m_sectorSize); - this->readRaw(sectorBase, modifiedSectorBuffer.data(), modifiedSectorBuffer.size()); - std::memcpy(modifiedSectorBuffer.data() + ((offset - sectorBase) % this->m_sectorSize), reinterpret_cast(buffer) + (startOffset - offset), currSize); + this->readRaw(sectorBase, modifiedSectorBuffer.data(), modifiedSectorBuffer.size()); + std::memcpy(modifiedSectorBuffer.data() + ((offset - sectorBase) % this->m_sectorSize), reinterpret_cast(buffer) + (startOffset - offset), currSize); - LARGE_INTEGER seekPosition; - seekPosition.LowPart = (offset & 0xFFFF'FFFF) - (offset % this->m_sectorSize); - seekPosition.HighPart = offset >> 32; + LARGE_INTEGER seekPosition; + seekPosition.LowPart = (offset & 0xFFFF'FFFF) - (offset % this->m_sectorSize); + seekPosition.HighPart = offset >> 32; - ::SetFilePointer(this->m_diskHandle, seekPosition.LowPart, &seekPosition.HighPart, FILE_BEGIN); - ::WriteFile(this->m_diskHandle, modifiedSectorBuffer.data(), modifiedSectorBuffer.size(), &bytesWritten, nullptr); + ::SetFilePointer(this->m_diskHandle, seekPosition.LowPart, &seekPosition.HighPart, FILE_BEGIN); + ::WriteFile(this->m_diskHandle, modifiedSectorBuffer.data(), modifiedSectorBuffer.size(), &bytesWritten, nullptr); - offset += currSize; - size -= currSize; - } + offset += currSize; + size -= currSize; + } - #else +#else - u64 startOffset = offset; + u64 startOffset = offset; - std::vector modifiedSectorBuffer; - modifiedSectorBuffer.resize(this->m_sectorSize); + std::vector modifiedSectorBuffer; + modifiedSectorBuffer.resize(this->m_sectorSize); - while (size > 0) { - u64 sectorBase = offset - (offset % this->m_sectorSize); - size_t currSize = std::min(size, this->m_sectorSize); + while (size > 0) { + u64 sectorBase = offset - (offset % this->m_sectorSize); + size_t currSize = std::min(size, this->m_sectorSize); - this->readRaw(sectorBase, modifiedSectorBuffer.data(), modifiedSectorBuffer.size()); - std::memcpy(modifiedSectorBuffer.data() + ((offset - sectorBase) % this->m_sectorSize), reinterpret_cast(buffer) + (startOffset - offset), currSize); + this->readRaw(sectorBase, modifiedSectorBuffer.data(), modifiedSectorBuffer.size()); + std::memcpy(modifiedSectorBuffer.data() + ((offset - sectorBase) % this->m_sectorSize), reinterpret_cast(buffer) + (startOffset - offset), currSize); - ::lseek(this->m_diskHandle, sectorBase, SEEK_SET); - ::write(this->m_diskHandle, modifiedSectorBuffer.data(), modifiedSectorBuffer.size()); + ::lseek(this->m_diskHandle, sectorBase, SEEK_SET); + ::write(this->m_diskHandle, modifiedSectorBuffer.data(), modifiedSectorBuffer.size()); - offset += currSize; - size -= currSize; - } + offset += currSize; + size -= currSize; + } - #endif +#endif } size_t DiskProvider::getActualSize() const { @@ -244,74 +244,74 @@ namespace hex::plugin::builtin::prv { std::vector> DiskProvider::getDataInformation() const { return { - { "hex.builtin.provider.disk.selected_disk"_lang, this->m_path.string() }, - { "hex.builtin.provider.disk.disk_size"_lang, hex::toByteString(this->m_diskSize) }, - { "hex.builtin.provider.disk.sector_size"_lang, hex::toByteString(this->m_sectorSize) } + {"hex.builtin.provider.disk.selected_disk"_lang, this->m_path.string() }, + { "hex.builtin.provider.disk.disk_size"_lang, hex::toByteString(this->m_diskSize) }, + { "hex.builtin.provider.disk.sector_size"_lang, hex::toByteString(this->m_sectorSize)} }; } void DiskProvider::reloadDrives() { - #if defined (OS_WINDOWS) - this->m_availableDrives.clear(); - std::bitset<32> drives = ::GetLogicalDrives(); - for (char i = 0; i < 26; i++) { - if (drives[i]) - this->m_availableDrives.insert(hex::format(R"(\\.\{:c}:)", 'A' + i)); +#if defined(OS_WINDOWS) + this->m_availableDrives.clear(); + std::bitset<32> drives = ::GetLogicalDrives(); + for (char i = 0; i < 26; i++) { + if (drives[i]) + this->m_availableDrives.insert(hex::format(R"(\\.\{:c}:)", 'A' + i)); + } + + auto logicalDrives = this->m_availableDrives; + for (const auto &drive : logicalDrives) { + auto handle = reinterpret_cast(::CreateFile(drive.data(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0, nullptr)); + + if (handle == INVALID_HANDLE_VALUE) continue; + + VOLUME_DISK_EXTENTS diskExtents = { 0 }; + DWORD bytesRead = 0; + auto result = ::DeviceIoControl( + handle, + IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, + nullptr, + 0, + &diskExtents, + sizeof(VOLUME_DISK_EXTENTS), + &bytesRead, + nullptr); + + if (result) { + auto diskPath = hex::format(R"(\\.\PhysicalDrive{})", diskExtents.Extents[0].DiskNumber); + this->m_availableDrives.insert(diskPath); } - auto logicalDrives = this->m_availableDrives; - for (const auto &drive : logicalDrives) { - auto handle = reinterpret_cast(::CreateFile(drive.data(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0, nullptr)); - - if (handle == INVALID_HANDLE_VALUE) continue; - - VOLUME_DISK_EXTENTS diskExtents = { 0 }; - DWORD bytesRead = 0; - auto result = ::DeviceIoControl( - handle, - IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, - nullptr, - 0, - &diskExtents, - sizeof(VOLUME_DISK_EXTENTS), - &bytesRead, - nullptr); - - if (result) { - auto diskPath = hex::format(R"(\\.\PhysicalDrive{})", diskExtents.Extents[0].DiskNumber); - this->m_availableDrives.insert(diskPath); - } - - ::CloseHandle(handle); - } - #endif + ::CloseHandle(handle); + } +#endif } void DiskProvider::drawLoadInterface() { - #if defined (OS_WINDOWS) - if (ImGui::BeginListBox("hex.builtin.provider.disk.selected_disk"_lang)) { +#if defined(OS_WINDOWS) + if (ImGui::BeginListBox("hex.builtin.provider.disk.selected_disk"_lang)) { - for (const auto &drive : this->m_availableDrives) { - if (ImGui::Selectable(drive.c_str(), this->m_path == drive)) - this->m_path = drive; - } - - ImGui::EndListBox(); + for (const auto &drive : this->m_availableDrives) { + if (ImGui::Selectable(drive.c_str(), this->m_path == drive)) + this->m_path = drive; } - ImGui::SameLine(); + ImGui::EndListBox(); + } - if (ImGui::Button("hex.builtin.provider.disk.reload"_lang)) { - this->reloadDrives(); - } + ImGui::SameLine(); - #else + if (ImGui::Button("hex.builtin.provider.disk.reload"_lang)) { + this->reloadDrives(); + } - if (ImGui::InputText("hex.builtin.provider.disk.selected_disk"_lang, this->m_pathBuffer.data(), this->m_pathBuffer.capacity(), ImGuiInputTextFlags_CallbackResize, ImGui::UpdateStringSizeCallback, &this->m_pathBuffer)) - this->m_path = this->m_pathBuffer; +#else - #endif + if (ImGui::InputText("hex.builtin.provider.disk.selected_disk"_lang, this->m_pathBuffer.data(), this->m_pathBuffer.capacity(), ImGuiInputTextFlags_CallbackResize, ImGui::UpdateStringSizeCallback, &this->m_pathBuffer)) + this->m_path = this->m_pathBuffer; + +#endif } } \ No newline at end of file diff --git a/plugins/builtin/source/content/providers/file_provider.cpp b/plugins/builtin/source/content/providers/file_provider.cpp index 96d3157b8..e7b2771d4 100644 --- a/plugins/builtin/source/content/providers/file_provider.cpp +++ b/plugins/builtin/source/content/providers/file_provider.cpp @@ -10,7 +10,6 @@ namespace hex::plugin::builtin::prv { FileProvider::FileProvider() : Provider() { - } FileProvider::~FileProvider() { @@ -19,11 +18,11 @@ namespace hex::plugin::builtin::prv { bool FileProvider::isAvailable() const { - #if defined(OS_WINDOWS) +#if defined(OS_WINDOWS) return this->m_file != INVALID_HANDLE_VALUE && this->m_mapping != INVALID_HANDLE_VALUE && this->m_mappedFile != nullptr; - #else +#else return this->m_file != -1 && this->m_mappedFile != nullptr; - #endif +#endif } bool FileProvider::isReadable() const { @@ -51,7 +50,7 @@ namespace hex::plugin::builtin::prv { for (u64 i = 0; i < size; i++) if (getPatches().contains(offset + i)) - reinterpret_cast(buffer)[i] = getPatches()[offset + PageSize * this->m_currPage + i]; + reinterpret_cast(buffer)[i] = getPatches()[offset + PageSize * this->m_currPage + i]; if (overlays) this->applyOverlays(offset, buffer, size); @@ -68,14 +67,14 @@ namespace hex::plugin::builtin::prv { if ((offset + size) > this->getActualSize() || buffer == nullptr || size == 0) return; - std::memcpy(buffer, reinterpret_cast(this->m_mappedFile) + offset, size); + std::memcpy(buffer, reinterpret_cast(this->m_mappedFile) + offset, size); } void FileProvider::writeRaw(u64 offset, const void *buffer, size_t size) { if ((offset + size) > this->getActualSize() || buffer == nullptr || size == 0) return; - std::memcpy(reinterpret_cast(this->m_mappedFile) + offset, buffer, size); + std::memcpy(reinterpret_cast(this->m_mappedFile) + offset, buffer, size); } void FileProvider::save() { @@ -168,113 +167,113 @@ namespace hex::plugin::builtin::prv { this->m_readable = true; this->m_writable = true; - #if defined(OS_WINDOWS) - const auto &path = this->m_path.native(); +#if defined(OS_WINDOWS) + const auto &path = this->m_path.native(); - LARGE_INTEGER fileSize = { 0 }; + LARGE_INTEGER fileSize = { 0 }; + this->m_file = reinterpret_cast(CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr)); + + GetFileSizeEx(this->m_file, &fileSize); + this->m_fileSize = fileSize.QuadPart; + CloseHandle(this->m_file); + + this->m_file = reinterpret_cast(CreateFileW(path.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr)); + if (this->m_file == nullptr || this->m_file == INVALID_HANDLE_VALUE) { this->m_file = reinterpret_cast(CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr)); + this->m_writable = false; + } - GetFileSizeEx(this->m_file, &fileSize); - this->m_fileSize = fileSize.QuadPart; + auto fileCleanup = SCOPE_GUARD { CloseHandle(this->m_file); - this->m_file = reinterpret_cast(CreateFileW(path.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr)); - if (this->m_file == nullptr || this->m_file == INVALID_HANDLE_VALUE) { - this->m_file = reinterpret_cast(CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr)); - this->m_writable = false; + this->m_readable = false; + this->m_file = nullptr; + }; + + if (this->m_file == nullptr || this->m_file == INVALID_HANDLE_VALUE) { + return false; + } + + if (this->m_fileSize > 0) { + this->m_mapping = CreateFileMapping(this->m_file, nullptr, PAGE_READWRITE, 0, 0, nullptr); + if (this->m_mapping == nullptr || this->m_mapping == INVALID_HANDLE_VALUE) { + + this->m_mapping = CreateFileMapping(this->m_file, nullptr, PAGE_READONLY, 0, 0, nullptr); + + if (this->m_mapping == nullptr || this->m_mapping == INVALID_HANDLE_VALUE) + return false; } - auto fileCleanup = SCOPE_GUARD { - CloseHandle(this->m_file); + auto mappingCleanup = SCOPE_GUARD { + CloseHandle(this->m_mapping); + this->m_mapping = nullptr; this->m_readable = false; - this->m_file = nullptr; }; - if (this->m_file == nullptr || this->m_file == INVALID_HANDLE_VALUE) { - return false; - } - - if (this->m_fileSize > 0) { - this->m_mapping = CreateFileMapping(this->m_file, nullptr, PAGE_READWRITE, 0, 0, nullptr); - if (this->m_mapping == nullptr || this->m_mapping == INVALID_HANDLE_VALUE) { - - this->m_mapping = CreateFileMapping(this->m_file, nullptr, PAGE_READONLY, 0, 0, nullptr); - - if (this->m_mapping == nullptr || this->m_mapping == INVALID_HANDLE_VALUE) - return false; - } - - auto mappingCleanup = SCOPE_GUARD { - CloseHandle(this->m_mapping); - - this->m_mapping = nullptr; - this->m_readable = false; - }; - - this->m_mappedFile = MapViewOfFile(this->m_mapping, FILE_MAP_ALL_ACCESS, 0, 0, this->m_fileSize); - if (this->m_mappedFile == nullptr) { - - this->m_mappedFile = MapViewOfFile(this->m_mapping, FILE_MAP_READ, 0, 0, this->m_fileSize); - if (this->m_mappedFile == nullptr) { - this->m_readable = false; - - return false; - } - } - - mappingCleanup.release(); - - ProjectFile::setFilePath(this->m_path); - } else if (!this->m_emptyFile) { - this->m_emptyFile = true; - this->resize(1); - } else { - return false; - } - - fileCleanup.release(); - - #else - const auto &path = this->m_path.native(); - - this->m_file = ::open(path.c_str(), O_RDWR); - if (this->m_file == -1) { - this->m_file = ::open(path.c_str(), O_RDONLY); - this->m_writable = false; - } - - if (this->m_file == -1) { - this->m_readable = false; - return false; - } - - this->m_fileSize = this->m_fileStats.st_size; - - this->m_mappedFile = ::mmap(nullptr, this->m_fileSize, PROT_READ | PROT_WRITE, MAP_SHARED, this->m_file, 0); + this->m_mappedFile = MapViewOfFile(this->m_mapping, FILE_MAP_ALL_ACCESS, 0, 0, this->m_fileSize); if (this->m_mappedFile == nullptr) { - ::close(this->m_file); - this->m_file = -1; - return false; + this->m_mappedFile = MapViewOfFile(this->m_mapping, FILE_MAP_READ, 0, 0, this->m_fileSize); + if (this->m_mappedFile == nullptr) { + this->m_readable = false; + + return false; + } } - #endif + + mappingCleanup.release(); + + ProjectFile::setFilePath(this->m_path); + } else if (!this->m_emptyFile) { + this->m_emptyFile = true; + this->resize(1); + } else { + return false; + } + + fileCleanup.release(); + +#else + const auto &path = this->m_path.native(); + + this->m_file = ::open(path.c_str(), O_RDWR); + if (this->m_file == -1) { + this->m_file = ::open(path.c_str(), O_RDONLY); + this->m_writable = false; + } + + if (this->m_file == -1) { + this->m_readable = false; + return false; + } + + this->m_fileSize = this->m_fileStats.st_size; + + this->m_mappedFile = ::mmap(nullptr, this->m_fileSize, PROT_READ | PROT_WRITE, MAP_SHARED, this->m_file, 0); + if (this->m_mappedFile == nullptr) { + ::close(this->m_file); + this->m_file = -1; + + return false; + } +#endif return true; } void FileProvider::close() { - #if defined(OS_WINDOWS) - if (this->m_mappedFile != nullptr) - ::UnmapViewOfFile(this->m_mappedFile); - if (this->m_mapping != nullptr) - ::CloseHandle(this->m_mapping); - if (this->m_file != nullptr) - ::CloseHandle(this->m_file); - #else - ::munmap(this->m_mappedFile, this->m_fileSize); - ::close(this->m_file); - #endif +#if defined(OS_WINDOWS) + if (this->m_mappedFile != nullptr) + ::UnmapViewOfFile(this->m_mappedFile); + if (this->m_mapping != nullptr) + ::CloseHandle(this->m_mapping); + if (this->m_file != nullptr) + ::CloseHandle(this->m_file); +#else + ::munmap(this->m_mappedFile, this->m_fileSize); + ::close(this->m_file); +#endif } } diff --git a/plugins/builtin/source/content/providers/gdb_provider.cpp b/plugins/builtin/source/content/providers/gdb_provider.cpp index 034cba187..9830ee6d0 100644 --- a/plugins/builtin/source/content/providers/gdb_provider.cpp +++ b/plugins/builtin/source/content/providers/gdb_provider.cpp @@ -61,14 +61,14 @@ namespace hex::plugin::builtin::prv { auto receivedPacket = socket.readString(size * 2 + 4); if (receivedPacket.empty()) - return { }; + return {}; auto receivedData = parsePacket(receivedPacket); if (!receivedData.has_value()) - return { }; + return {}; if (receivedData->size() == 3 && receivedData->starts_with("E")) - return { }; + return {}; auto data = crypt::decode16(receivedData.value()); @@ -113,7 +113,6 @@ namespace hex::plugin::builtin::prv { } GDBProvider::GDBProvider() : Provider(), m_size(0xFFFF'FFFF) { - } GDBProvider::~GDBProvider() { @@ -153,7 +152,7 @@ namespace hex::plugin::builtin::prv { if (size <= CacheLineSize) { std::scoped_lock lock(this->m_cacheLock); - const auto &cacheLine = std::find_if(this->m_cache.begin(), this->m_cache.end(), [&](auto &line){ + const auto &cacheLine = std::find_if(this->m_cache.begin(), this->m_cache.end(), [&](auto &line) { return line.address == alignedOffset; }); @@ -180,7 +179,7 @@ namespace hex::plugin::builtin::prv { for (u64 i = 0; i < size; i++) if (getPatches().contains(offset + i)) - reinterpret_cast(buffer)[i] = getPatches()[offset + PageSize * this->m_currPage + i]; + reinterpret_cast(buffer)[i] = getPatches()[offset + PageSize * this->m_currPage + i]; if (overlays) this->applyOverlays(offset, buffer, size); @@ -215,7 +214,6 @@ namespace hex::plugin::builtin::prv { } void GDBProvider::saveAs(const fs::path &path) { - } size_t GDBProvider::getActualSize() const { @@ -238,7 +236,7 @@ namespace hex::plugin::builtin::prv { std::vector> GDBProvider::getDataInformation() const { return { - { "hex.builtin.provider.gdb.server"_lang, hex::format("{}:{}", this->m_ipAddress, this->m_port) }, + {"hex.builtin.provider.gdb.server"_lang, hex::format("{}:{}", this->m_ipAddress, this->m_port)}, }; } @@ -294,7 +292,6 @@ namespace hex::plugin::builtin::prv { } - void GDBProvider::drawLoadInterface() { ImGui::InputText("hex.builtin.provider.gdb.ip"_lang, this->m_ipAddress.data(), this->m_ipAddress.capacity(), ImGuiInputTextFlags_CallbackEdit, ImGui::UpdateStringSizeCallback, &this->m_ipAddress); ImGui::InputInt("hex.builtin.provider.gdb.port"_lang, &this->m_port, 0, 0); diff --git a/plugins/builtin/source/content/settings_entries.cpp b/plugins/builtin/source/content/settings_entries.cpp index 9a740ecc0..6a06c237b 100644 --- a/plugins/builtin/source/content/settings_entries.cpp +++ b/plugins/builtin/source/content/settings_entries.cpp @@ -41,11 +41,11 @@ namespace hex::plugin::builtin { ContentRegistry::Settings::add("hex.builtin.setting.interface", "hex.builtin.setting.interface.color", 0, [](auto name, nlohmann::json &setting) { static int selection = static_cast(setting); - const char* themes[] = { - "hex.builtin.setting.interface.color.system"_lang, - "hex.builtin.setting.interface.color.dark"_lang, - "hex.builtin.setting.interface.color.light"_lang, - "hex.builtin.setting.interface.color.classic"_lang + const char *themes[] = { + "hex.builtin.setting.interface.color.system"_lang, + "hex.builtin.setting.interface.color.dark"_lang, + "hex.builtin.setting.interface.color.light"_lang, + "hex.builtin.setting.interface.color.classic"_lang }; if (ImGui::Combo(name.data(), &selection, themes, IM_ARRAYSIZE(themes))) { @@ -59,12 +59,12 @@ namespace hex::plugin::builtin { ContentRegistry::Settings::add("hex.builtin.setting.interface", "hex.builtin.setting.interface.scaling", 0, [](auto name, nlohmann::json &setting) { static int selection = static_cast(setting); - const char* scaling[] = { - "hex.builtin.setting.interface.scaling.native"_lang, - "hex.builtin.setting.interface.scaling.x0_5"_lang, - "hex.builtin.setting.interface.scaling.x1_0"_lang, - "hex.builtin.setting.interface.scaling.x1_5"_lang, - "hex.builtin.setting.interface.scaling.x2_0"_lang, + const char *scaling[] = { + "hex.builtin.setting.interface.scaling.native"_lang, + "hex.builtin.setting.interface.scaling.x0_5"_lang, + "hex.builtin.setting.interface.scaling.x1_0"_lang, + "hex.builtin.setting.interface.scaling.x1_5"_lang, + "hex.builtin.setting.interface.scaling.x2_0"_lang, }; if (ImGui::Combo(name.data(), &selection, scaling, IM_ARRAYSIZE(scaling))) { @@ -83,7 +83,7 @@ namespace hex::plugin::builtin { static int selection = [&]() -> int { u16 index = 0; - for (auto &[languageCode, languageName] : languages){ + for (auto &[languageCode, languageName] : languages) { if (languageCode == setting) return index; index++; @@ -93,7 +93,7 @@ namespace hex::plugin::builtin { }(); static auto languageNames = [&]() { - std::vector result; + std::vector result; result.reserve(languages.size()); for (auto &[languageCode, languageName] : languages) @@ -106,7 +106,7 @@ namespace hex::plugin::builtin { if (ImGui::Combo(name.data(), &selection, languageNames.data(), languageNames.size())) { u16 index = 0; - for (auto &[languageCode, languageName] : languages){ + for (auto &[languageCode, languageName] : languages) { if (selection == index) { setting = languageCode; break; @@ -220,7 +220,6 @@ namespace hex::plugin::builtin { return false; }); - } } \ No newline at end of file diff --git a/plugins/builtin/source/content/tools_entries.cpp b/plugins/builtin/source/content/tools_entries.cpp index a6824cc59..7f85b063e 100644 --- a/plugins/builtin/source/content/tools_entries.cpp +++ b/plugins/builtin/source/content/tools_entries.cpp @@ -97,10 +97,10 @@ namespace hex::plugin::builtin { } void drawRegexReplacer() { - static auto regexInput = []{ std::string s; s.reserve(0xFFF); return s; }(); - static auto regexPattern = []{ std::string s; s.reserve(0xFFF); return s; }(); - static auto replacePattern = []{ std::string s; s.reserve(0xFFF); return s; }(); - static auto regexOutput = []{ std::string s; s.reserve(0xFFF); return s; }(); + static auto regexInput = [] { std::string s; s.reserve(0xFFF); return s; }(); + static auto regexPattern = [] { std::string s; s.reserve(0xFFF); return s; }(); + static auto replacePattern = [] { std::string s; s.reserve(0xFFF); return s; }(); + static auto regexOutput = [] { std::string s; s.reserve(0xFFF); return s; }(); bool changed1 = ImGui::InputText("hex.builtin.tools.regex_replacer.pattern"_lang, regexPattern.data(), regexPattern.capacity(), ImGuiInputTextFlags_CallbackEdit, ImGui::UpdateStringSizeCallback, ®exPattern); bool changed2 = ImGui::InputText("hex.builtin.tools.regex_replacer.replace"_lang, replacePattern.data(), replacePattern.capacity(), ImGuiInputTextFlags_CallbackEdit, ImGui::UpdateStringSizeCallback, &replacePattern); @@ -109,7 +109,7 @@ namespace hex::plugin::builtin { if (changed1 || changed2 || changed3) { try { regexOutput = std::regex_replace(regexInput.data(), std::regex(regexPattern.data()), replacePattern.data()); - } catch (std::regex_error&) {} + } catch (std::regex_error &) { } } ImGui::InputTextMultiline("hex.builtin.tools.regex_replacer.output"_lang, regexOutput.data(), regexOutput.size(), ImVec2(0, 0), ImGuiInputTextFlags_ReadOnly); @@ -120,15 +120,14 @@ namespace hex::plugin::builtin { static std::array pickedColor = { 0 }; ImGui::SetNextItemWidth(300.0F); - ImGui::ColorPicker4("hex.builtin.tools.color"_lang, pickedColor.data(), - ImGuiColorEditFlags_Uint8 | ImGuiColorEditFlags_AlphaBar | ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_DisplayHSV | ImGuiColorEditFlags_DisplayHex); + ImGui::ColorPicker4("hex.builtin.tools.color"_lang, pickedColor.data(), ImGuiColorEditFlags_Uint8 | ImGuiColorEditFlags_AlphaBar | ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_DisplayHSV | ImGuiColorEditFlags_DisplayHex); ImGui::NewLine(); } void drawMathEvaluator() { static std::vector mathHistory; static std::string lastMathError; - static auto mathInput = []{ + static auto mathInput = [] { std::string s; s.reserve(0xFFFF); std::memset(s.data(), 0x00, s.capacity()); @@ -137,52 +136,66 @@ namespace hex::plugin::builtin { }(); bool evaluate = false; - static MathEvaluator mathEvaluator = [&]{ + static MathEvaluator mathEvaluator = [&] { MathEvaluator evaluator; evaluator.registerStandardVariables(); evaluator.registerStandardFunctions(); - evaluator.setFunction("clear", [&](auto args) -> std::optional { - mathHistory.clear(); - lastMathError.clear(); - mathEvaluator.getVariables().clear(); - mathEvaluator.registerStandardVariables(); - mathInput.clear(); + evaluator.setFunction( + "clear", [&](auto args) -> std::optional { + mathHistory.clear(); + lastMathError.clear(); + mathEvaluator.getVariables().clear(); + mathEvaluator.registerStandardVariables(); + mathInput.clear(); - return { }; - }, 0, 0); + return {}; + }, + 0, + 0); - evaluator.setFunction("read", [](auto args) -> std::optional { - u8 value = 0; + evaluator.setFunction( + "read", [](auto args) -> std::optional { + u8 value = 0; - auto provider = ImHexApi::Provider::get(); - if (!ImHexApi::Provider::isValid() || !provider->isReadable() || args[0] >= provider->getActualSize()) - return { }; + auto provider = ImHexApi::Provider::get(); + if (!ImHexApi::Provider::isValid() || !provider->isReadable() || args[0] >= provider->getActualSize()) + return {}; - provider->read(args[0], &value, sizeof(u8)); + provider->read(args[0], &value, sizeof(u8)); - return value; - }, 1, 1); + return value; + }, + 1, + 1); - evaluator.setFunction("write", [](auto args) -> std::optional { - auto provider = ImHexApi::Provider::get(); - if (!ImHexApi::Provider::isValid() || !provider->isWritable() || args[0] >= provider->getActualSize()) - return { }; + evaluator.setFunction( + "write", [](auto args) -> std::optional { + auto provider = ImHexApi::Provider::get(); + if (!ImHexApi::Provider::isValid() || !provider->isWritable() || args[0] >= provider->getActualSize()) + return {}; - if (args[1] > 0xFF) - return { }; + if (args[1] > 0xFF) + return {}; - u8 value = args[1]; - provider->write(args[0], &value, sizeof(u8)); + u8 value = args[1]; + provider->write(args[0], &value, sizeof(u8)); - return { }; - }, 2, 2); + return {}; + }, + 2, + 2); return std::move(evaluator); }(); - enum class MathDisplayType { Standard, Scientific, Engineering, Programmer } mathDisplayType; + enum class MathDisplayType { + Standard, + Scientific, + Engineering, + Programmer + } mathDisplayType; if (ImGui::BeginTabBar("##mathFormatTabBar")) { if (ImGui::BeginTabItem("hex.builtin.tools.format.standard"_lang)) { mathDisplayType = MathDisplayType::Standard; @@ -214,64 +227,104 @@ namespace hex::plugin::builtin { auto buttonSize = ImVec2(3, 2) * ImGui::GetTextLineHeightWithSpacing(); - if (ImGui::Button("Ans", buttonSize)) mathInput += "ans"; ImGui::SameLine(); - if (ImGui::Button("Pi", buttonSize)) mathInput += "pi"; ImGui::SameLine(); - if (ImGui::Button("e", buttonSize)) mathInput += "e"; ImGui::SameLine(); - if (ImGui::Button("CE", buttonSize)) mathInput.clear(); ImGui::SameLine(); - if (ImGui::Button(ICON_FA_BACKSPACE, buttonSize)) mathInput.clear(); ImGui::SameLine(); + if (ImGui::Button("Ans", buttonSize)) mathInput += "ans"; + ImGui::SameLine(); + if (ImGui::Button("Pi", buttonSize)) mathInput += "pi"; + ImGui::SameLine(); + if (ImGui::Button("e", buttonSize)) mathInput += "e"; + ImGui::SameLine(); + if (ImGui::Button("CE", buttonSize)) mathInput.clear(); + ImGui::SameLine(); + if (ImGui::Button(ICON_FA_BACKSPACE, buttonSize)) mathInput.clear(); + ImGui::SameLine(); ImGui::NewLine(); switch (mathDisplayType) { - case MathDisplayType::Standard: - case MathDisplayType::Scientific: - case MathDisplayType::Engineering: - if (ImGui::Button("x²", buttonSize)) mathInput += "** 2"; ImGui::SameLine(); - if (ImGui::Button("1/x", buttonSize)) mathInput += "1/"; ImGui::SameLine(); - if (ImGui::Button("|x|", buttonSize)) mathInput += "abs"; ImGui::SameLine(); - if (ImGui::Button("exp", buttonSize)) mathInput += "e ** "; ImGui::SameLine(); - if (ImGui::Button("%", buttonSize)) mathInput += "%"; ImGui::SameLine(); - break; - case MathDisplayType::Programmer: - if (ImGui::Button("<<", buttonSize)) mathInput += "<<"; ImGui::SameLine(); - if (ImGui::Button(">>", buttonSize)) mathInput += ">>"; ImGui::SameLine(); - if (ImGui::Button("&", buttonSize)) mathInput += "&"; ImGui::SameLine(); - if (ImGui::Button("|", buttonSize)) mathInput += "|"; ImGui::SameLine(); - if (ImGui::Button("^", buttonSize)) mathInput += "^"; ImGui::SameLine(); - break; + case MathDisplayType::Standard: + case MathDisplayType::Scientific: + case MathDisplayType::Engineering: + if (ImGui::Button("x²", buttonSize)) mathInput += "** 2"; + ImGui::SameLine(); + if (ImGui::Button("1/x", buttonSize)) mathInput += "1/"; + ImGui::SameLine(); + if (ImGui::Button("|x|", buttonSize)) mathInput += "abs"; + ImGui::SameLine(); + if (ImGui::Button("exp", buttonSize)) mathInput += "e ** "; + ImGui::SameLine(); + if (ImGui::Button("%", buttonSize)) mathInput += "%"; + ImGui::SameLine(); + break; + case MathDisplayType::Programmer: + if (ImGui::Button("<<", buttonSize)) mathInput += "<<"; + ImGui::SameLine(); + if (ImGui::Button(">>", buttonSize)) mathInput += ">>"; + ImGui::SameLine(); + if (ImGui::Button("&", buttonSize)) mathInput += "&"; + ImGui::SameLine(); + if (ImGui::Button("|", buttonSize)) mathInput += "|"; + ImGui::SameLine(); + if (ImGui::Button("^", buttonSize)) mathInput += "^"; + ImGui::SameLine(); + break; } ImGui::NewLine(); - if (ImGui::Button("sqrt", buttonSize)) mathInput += "sqrt"; ImGui::SameLine(); - if (ImGui::Button("(", buttonSize)) mathInput += "("; ImGui::SameLine(); - if (ImGui::Button(")", buttonSize)) mathInput += ")"; ImGui::SameLine(); - if (ImGui::Button("sign", buttonSize)) mathInput += "sign"; ImGui::SameLine(); - if (ImGui::Button("÷", buttonSize)) mathInput += "/"; ImGui::SameLine(); + if (ImGui::Button("sqrt", buttonSize)) mathInput += "sqrt"; + ImGui::SameLine(); + if (ImGui::Button("(", buttonSize)) mathInput += "("; + ImGui::SameLine(); + if (ImGui::Button(")", buttonSize)) mathInput += ")"; + ImGui::SameLine(); + if (ImGui::Button("sign", buttonSize)) mathInput += "sign"; + ImGui::SameLine(); + if (ImGui::Button("÷", buttonSize)) mathInput += "/"; + ImGui::SameLine(); ImGui::NewLine(); - if (ImGui::Button("xª", buttonSize)) mathInput += "**"; ImGui::SameLine(); - if (ImGui::Button("7", buttonSize)) mathInput += "7"; ImGui::SameLine(); - if (ImGui::Button("8", buttonSize)) mathInput += "8"; ImGui::SameLine(); - if (ImGui::Button("9", buttonSize)) mathInput += "9"; ImGui::SameLine(); - if (ImGui::Button("×", buttonSize)) mathInput += "*"; ImGui::SameLine(); + if (ImGui::Button("xª", buttonSize)) mathInput += "**"; + ImGui::SameLine(); + if (ImGui::Button("7", buttonSize)) mathInput += "7"; + ImGui::SameLine(); + if (ImGui::Button("8", buttonSize)) mathInput += "8"; + ImGui::SameLine(); + if (ImGui::Button("9", buttonSize)) mathInput += "9"; + ImGui::SameLine(); + if (ImGui::Button("×", buttonSize)) mathInput += "*"; + ImGui::SameLine(); ImGui::NewLine(); - if (ImGui::Button("log", buttonSize)) mathInput += "log"; ImGui::SameLine(); - if (ImGui::Button("4", buttonSize)) mathInput += "4"; ImGui::SameLine(); - if (ImGui::Button("5", buttonSize)) mathInput += "5"; ImGui::SameLine(); - if (ImGui::Button("6", buttonSize)) mathInput += "6"; ImGui::SameLine(); - if (ImGui::Button("-", buttonSize)) mathInput += "-"; ImGui::SameLine(); + if (ImGui::Button("log", buttonSize)) mathInput += "log"; + ImGui::SameLine(); + if (ImGui::Button("4", buttonSize)) mathInput += "4"; + ImGui::SameLine(); + if (ImGui::Button("5", buttonSize)) mathInput += "5"; + ImGui::SameLine(); + if (ImGui::Button("6", buttonSize)) mathInput += "6"; + ImGui::SameLine(); + if (ImGui::Button("-", buttonSize)) mathInput += "-"; + ImGui::SameLine(); ImGui::NewLine(); - if (ImGui::Button("ln", buttonSize)) mathInput += "ln"; ImGui::SameLine(); - if (ImGui::Button("1", buttonSize)) mathInput += "1"; ImGui::SameLine(); - if (ImGui::Button("2", buttonSize)) mathInput += "2"; ImGui::SameLine(); - if (ImGui::Button("3", buttonSize)) mathInput += "3"; ImGui::SameLine(); - if (ImGui::Button("+", buttonSize)) mathInput += "+"; ImGui::SameLine(); + if (ImGui::Button("ln", buttonSize)) mathInput += "ln"; + ImGui::SameLine(); + if (ImGui::Button("1", buttonSize)) mathInput += "1"; + ImGui::SameLine(); + if (ImGui::Button("2", buttonSize)) mathInput += "2"; + ImGui::SameLine(); + if (ImGui::Button("3", buttonSize)) mathInput += "3"; + ImGui::SameLine(); + if (ImGui::Button("+", buttonSize)) mathInput += "+"; + ImGui::SameLine(); ImGui::NewLine(); - if (ImGui::Button("lb", buttonSize)) mathInput += "lb"; ImGui::SameLine(); - if (ImGui::Button("x=", buttonSize)) mathInput += "="; ImGui::SameLine(); - if (ImGui::Button("0", buttonSize)) mathInput += "0"; ImGui::SameLine(); - if (ImGui::Button(".", buttonSize)) mathInput += "."; ImGui::SameLine(); + if (ImGui::Button("lb", buttonSize)) mathInput += "lb"; + ImGui::SameLine(); + if (ImGui::Button("x=", buttonSize)) mathInput += "="; + ImGui::SameLine(); + if (ImGui::Button("0", buttonSize)) mathInput += "0"; + ImGui::SameLine(); + if (ImGui::Button(".", buttonSize)) mathInput += "."; + ImGui::SameLine(); ImGui::PushStyleColor(ImGuiCol_Button, ImGui::GetCustomColorVec4(ImGuiCustomCol_DescButtonHovered)); ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImGui::GetCustomColorVec4(ImGuiCustomCol_DescButton)); ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImGui::GetCustomColorVec4(ImGuiCustomCol_DescButtonActive)); - if (ImGui::Button("=", buttonSize)) evaluate = true; ImGui::SameLine(); + if (ImGui::Button("=", buttonSize)) evaluate = true; + ImGui::SameLine(); ImGui::PopStyleColor(3); ImGui::NewLine(); @@ -295,20 +348,20 @@ namespace hex::plugin::builtin { ImGui::TableNextColumn(); switch (mathDisplayType) { - case MathDisplayType::Standard: - ImGui::TextFormatted("{0:.3Lf}", mathHistory[(mathHistory.size() - 1) - i]); - break; - case MathDisplayType::Scientific: - ImGui::TextFormatted("{0:.6Le}", mathHistory[(mathHistory.size() - 1) - i]); - break; - case MathDisplayType::Engineering: - ImGui::TextFormatted("{0}", hex::toEngineeringString(mathHistory[(mathHistory.size() - 1) - i]).c_str()); - break; - case MathDisplayType::Programmer: - ImGui::TextFormatted("0x{0:X} ({1})", - u64(mathHistory[(mathHistory.size() - 1) - i]), - u64(mathHistory[(mathHistory.size() - 1) - i])); - break; + case MathDisplayType::Standard: + ImGui::TextFormatted("{0:.3Lf}", mathHistory[(mathHistory.size() - 1) - i]); + break; + case MathDisplayType::Scientific: + ImGui::TextFormatted("{0:.6Le}", mathHistory[(mathHistory.size() - 1) - i]); + break; + case MathDisplayType::Engineering: + ImGui::TextFormatted("{0}", hex::toEngineeringString(mathHistory[(mathHistory.size() - 1) - i]).c_str()); + break; + case MathDisplayType::Programmer: + ImGui::TextFormatted("0x{0:X} ({1})", + u64(mathHistory[(mathHistory.size() - 1) - i]), + u64(mathHistory[(mathHistory.size() - 1) - i])); + break; } if (i == 0) @@ -335,18 +388,18 @@ namespace hex::plugin::builtin { ImGui::TableNextColumn(); switch (mathDisplayType) { - case MathDisplayType::Standard: - ImGui::TextFormatted("{0:.3Lf}", value); - break; - case MathDisplayType::Scientific: - ImGui::TextFormatted("{0:.6Le}", value); - break; - case MathDisplayType::Engineering: - ImGui::TextFormatted("{}", hex::toEngineeringString(value)); - break; - case MathDisplayType::Programmer: - ImGui::TextFormatted("0x{0:X} ({1})", u64(value), u64(value)); - break; + case MathDisplayType::Standard: + ImGui::TextFormatted("{0:.3Lf}", value); + break; + case MathDisplayType::Scientific: + ImGui::TextFormatted("{0:.6Le}", value); + break; + case MathDisplayType::Engineering: + ImGui::TextFormatted("{}", hex::toEngineeringString(value)); + break; + case MathDisplayType::Programmer: + ImGui::TextFormatted("0x{0:X} ({1})", u64(value), u64(value)); + break; } } @@ -383,19 +436,23 @@ namespace hex::plugin::builtin { lastMathError.clear(); } } - } void drawBaseConverter() { static char buffer[4][0xFFF] = { { '0' }, { '0' }, { '0' }, { '0' } }; static auto CharFilter = [](ImGuiInputTextCallbackData *data) -> int { - switch (*static_cast(data->UserData)) { - case 16: return std::isxdigit(data->EventChar); - case 10: return std::isdigit(data->EventChar); - case 8: return std::isdigit(data->EventChar) && data->EventChar < '8'; - case 2: return data->EventChar == '0' || data->EventChar == '1'; - default: return false; + switch (*static_cast(data->UserData)) { + case 16: + return std::isxdigit(data->EventChar); + case 10: + return std::isdigit(data->EventChar); + case 8: + return std::isdigit(data->EventChar) && data->EventChar < '8'; + case 2: + return data->EventChar == '0' || data->EventChar == '1'; + default: + return false; } }; @@ -404,22 +461,31 @@ namespace hex::plugin::builtin { errno = 0; switch (base) { - case 16: number = std::strtoull(buffer[1], nullptr, base); break; - case 10: number = std::strtoull(buffer[0], nullptr, base); break; - case 8: number = std::strtoull(buffer[2], nullptr, base); break; - case 2: number = std::strtoull(buffer[3], nullptr, base); break; - default: return; + case 16: + number = std::strtoull(buffer[1], nullptr, base); + break; + case 10: + number = std::strtoull(buffer[0], nullptr, base); + break; + case 8: + number = std::strtoull(buffer[2], nullptr, base); + break; + case 2: + number = std::strtoull(buffer[3], nullptr, base); + break; + default: + return; } - auto base10String = std::to_string(number); - auto base16String = hex::format("0x{0:X}", number); - auto base8String = hex::format("{0:#o}", number); - auto base2String = hex::toBinaryString(number); + auto base10String = std::to_string(number); + auto base16String = hex::format("0x{0:X}", number); + auto base8String = hex::format("{0:#o}", number); + auto base2String = hex::toBinaryString(number); std::strncpy(buffer[0], base10String.c_str(), sizeof(buffer[0])); std::strncpy(buffer[1], base16String.c_str(), sizeof(buffer[1])); - std::strncpy(buffer[2], base8String.c_str(), sizeof(buffer[2])); - std::strncpy(buffer[3], base2String.c_str(), sizeof(buffer[3])); + std::strncpy(buffer[2], base8String.c_str(), sizeof(buffer[2])); + std::strncpy(buffer[3], base2String.c_str(), sizeof(buffer[3])); }; u8 base = 10; @@ -497,7 +563,6 @@ namespace hex::plugin::builtin { ImGui::TextFormattedColored(WarningColor, "{}", "hex.builtin.tools.permissions.setgid_error"_lang); if (sticky && !x[2]) ImGui::TextFormattedColored(WarningColor, "{}", "hex.builtin.tools.permissions.sticky_error"_lang); - } void drawFileUploader() { @@ -515,7 +580,7 @@ namespace hex::plugin::builtin { ImGui::Header("hex.builtin.tools.file_uploader.control"_lang, true); if (!uploading) { if (ImGui::Button("hex.builtin.tools.file_uploader.upload"_lang)) { - hex::openFileBrowser("hex.builtin.tools.file_uploader.done"_lang, DialogMode::Open, { }, [&](auto path){ + hex::openFileBrowser("hex.builtin.tools.file_uploader.done"_lang, DialogMode::Open, {}, [&](auto path) { uploadProcess = net.uploadFile("https://api.anonfiles.com/upload", path); currFile = path; }); @@ -575,11 +640,9 @@ namespace hex::plugin::builtin { if (response.code == 200) { try { auto json = nlohmann::json::parse(response.body); - links.push_back({ - currFile.filename().string(), - json["data"]["file"]["url"]["short"], - json["data"]["file"]["metadata"]["size"]["readable"] - }); + links.push_back({ currFile.filename().string(), + json["data"]["file"]["url"]["short"], + json["data"]["file"]["metadata"]["size"]["readable"] }); } catch (...) { View::showErrorPopup("hex.builtin.tools.file_uploader.invalid_response"_lang); } @@ -587,7 +650,7 @@ namespace hex::plugin::builtin { // Canceled by user, no action needed } else View::showErrorPopup(hex::format("hex.builtin.tools.file_uploader.error"_lang, response.code)); - uploadProcess = { }; + uploadProcess = {}; currFile.clear(); } } @@ -599,7 +662,7 @@ namespace hex::plugin::builtin { static std::future> searchProcess; static bool extendedSearch = false; - static auto searchString = []{ + static auto searchString = [] { std::string s; s.reserve(0xFFFF); std::memset(s.data(), 0x00, s.capacity()); @@ -617,7 +680,7 @@ namespace hex::plugin::builtin { ImGui::SameLine(); ImGui::BeginDisabled(searchProcess.valid() && searchProcess.wait_for(0s) != std::future_status::ready || searchString.empty()); - startSearch = ImGui::Button("hex.builtin.tools.wiki_explain.search"_lang) || startSearch; + startSearch = ImGui::Button("hex.builtin.tools.wiki_explain.search"_lang) || startSearch; ImGui::EndDisabled(); if (startSearch && !searchString.empty()) { @@ -628,7 +691,7 @@ namespace hex::plugin::builtin { if (ImGui::BeginChild("##summary", ImVec2(0, 300), true)) { if (!resultTitle.empty() && !resultExtract.empty()) { - ImGui::HeaderColored(resultTitle.c_str(), ImGui::GetCustomColorVec4(ImGuiCustomCol_Highlight),true); + ImGui::HeaderColored(resultTitle.c_str(), ImGui::GetCustomColorVec4(ImGuiCustomCol_Highlight), true); ImGui::TextFormattedWrapped("{}", resultExtract.c_str()); } } @@ -657,7 +720,7 @@ namespace hex::plugin::builtin { resultTitle.clear(); resultExtract.clear(); extendedSearch = false; - searchProcess = { }; + searchProcess = {}; resultTitle = "???"; resultExtract = "hex.builtin.tools.wiki_explain.invalid_response"_lang.get(); @@ -668,7 +731,7 @@ namespace hex::plugin::builtin { void drawFileToolShredder() { static bool shredding = false; - static auto selectedFile = []{ std::string s; s.reserve(0x1000); return s; }(); + static auto selectedFile = [] { std::string s; s.reserve(0x1000); return s; }(); static bool fastMode = false; ImGui::TextUnformatted("hex.builtin.tools.file_tools.shredder.warning"_lang); @@ -701,8 +764,11 @@ namespace hex::plugin::builtin { if (ImGui::Button("hex.builtin.tools.file_tools.shredder.shred"_lang)) { shredding = true; - std::thread([]{ - ON_SCOPE_EXIT { shredding = false; selectedFile.clear(); }; + std::thread([] { + ON_SCOPE_EXIT { + shredding = false; + selectedFile.clear(); + }; File file(selectedFile, File::Mode::Write); if (!file.isValid()) { @@ -715,23 +781,47 @@ namespace hex::plugin::builtin { /* Should be sufficient for modern disks */ overwritePattern.push_back({ 0x00, 0x00, 0x00 }); overwritePattern.push_back({ 0xFF, 0xFF, 0xFF }); - } - else { + } else { /* Gutmann's method. Secure for magnetic storage */ std::random_device rd; std::uniform_int_distribution dist(0x00, 0xFF); /* Fill fixed patterns */ overwritePattern = { - {}, {}, {}, {}, - { 0x55, 0x55, 0x55 }, { 0xAA, 0xAA, 0xAA }, { 0x92, 0x49, 0x24 }, { 0x49, 0x24, 0x92 }, - { 0x24, 0x92, 0x49 }, { 0x00, 0x00, 0x00 }, { 0x11, 0x11, 0x11 }, { 0x22, 0x22, 0x22 }, - { 0x33, 0x33, 0x44 }, { 0x55, 0x55, 0x55 }, { 0x66, 0x66, 0x66 }, { 0x77, 0x77, 0x77 }, - { 0x88, 0x88, 0x88 }, { 0x99, 0x99, 0x99 }, { 0xAA, 0xAA, 0xAA }, { 0xBB, 0xBB, 0xBB }, - { 0xCC, 0xCC, 0xCC }, { 0xDD, 0xDD, 0xDD }, { 0xEE, 0xEE, 0xEE }, { 0xFF, 0xFF, 0xFF }, - { 0x92, 0x49, 0x24 }, { 0x49, 0x24, 0x92 }, { 0x24, 0x92, 0x49 }, { 0x6D, 0xB6, 0xDB }, - { 0xB6, 0xDB, 0x6D }, { 0xBD, 0x6D, 0xB6 }, - {}, {}, {}, {} + { }, + { }, + {}, + {}, + { 0x55, 0x55, 0x55 }, + { 0xAA, 0xAA, 0xAA }, + { 0x92, 0x49, 0x24 }, + { 0x49, 0x24, 0x92 }, + { 0x24, 0x92, 0x49 }, + { 0x00, 0x00, 0x00 }, + { 0x11, 0x11, 0x11 }, + { 0x22, 0x22, 0x22 }, + { 0x33, 0x33, 0x44 }, + { 0x55, 0x55, 0x55 }, + { 0x66, 0x66, 0x66 }, + { 0x77, 0x77, 0x77 }, + { 0x88, 0x88, 0x88 }, + { 0x99, 0x99, 0x99 }, + { 0xAA, 0xAA, 0xAA }, + { 0xBB, 0xBB, 0xBB }, + { 0xCC, 0xCC, 0xCC }, + { 0xDD, 0xDD, 0xDD }, + { 0xEE, 0xEE, 0xEE }, + { 0xFF, 0xFF, 0xFF }, + { 0x92, 0x49, 0x24 }, + { 0x49, 0x24, 0x92 }, + { 0x24, 0x92, 0x49 }, + { 0x6D, 0xB6, 0xDB }, + { 0xB6, 0xDB, 0x6D }, + { 0xBD, 0x6D, 0xB6 }, + {}, + {}, + {}, + {} }; /* Fill random patterns */ @@ -756,7 +846,6 @@ namespace hex::plugin::builtin { file.remove(); View::showMessagePopup("hex.builtin.tools.file_tools.shredder.success"_lang); - }).detach(); } } @@ -766,29 +855,29 @@ namespace hex::plugin::builtin { void drawFileToolSplitter() { std::array sizeText = { - (const char*)"hex.builtin.tools.file_tools.splitter.sizes.5_75_floppy"_lang, - (const char*)"hex.builtin.tools.file_tools.splitter.sizes.3_5_floppy"_lang, - (const char*)"hex.builtin.tools.file_tools.splitter.sizes.zip100"_lang, - (const char*)"hex.builtin.tools.file_tools.splitter.sizes.zip200"_lang, - (const char*)"hex.builtin.tools.file_tools.splitter.sizes.cdrom650"_lang, - (const char*)"hex.builtin.tools.file_tools.splitter.sizes.cdrom700"_lang, - (const char*)"hex.builtin.tools.file_tools.splitter.sizes.fat32"_lang, - (const char*)"hex.builtin.tools.file_tools.splitter.sizes.custom"_lang + (const char *)"hex.builtin.tools.file_tools.splitter.sizes.5_75_floppy"_lang, + (const char *)"hex.builtin.tools.file_tools.splitter.sizes.3_5_floppy"_lang, + (const char *)"hex.builtin.tools.file_tools.splitter.sizes.zip100"_lang, + (const char *)"hex.builtin.tools.file_tools.splitter.sizes.zip200"_lang, + (const char *)"hex.builtin.tools.file_tools.splitter.sizes.cdrom650"_lang, + (const char *)"hex.builtin.tools.file_tools.splitter.sizes.cdrom700"_lang, + (const char *)"hex.builtin.tools.file_tools.splitter.sizes.fat32"_lang, + (const char *)"hex.builtin.tools.file_tools.splitter.sizes.custom"_lang }; std::array sizes = { - 1200_KiB, - 1400_KiB, - 100_MiB, - 200_MiB, - 650_MiB, - 700_MiB, - 4_GiB, - 1 + 1200_KiB, + 1400_KiB, + 100_MiB, + 200_MiB, + 650_MiB, + 700_MiB, + 4_GiB, + 1 }; - static bool splitting = false; - static auto selectedFile = []{ std::string s; s.reserve(0x1000); return s; }(); - static auto baseOutputPath = []{ std::string s; s.reserve(0x1000); return s; }(); + static bool splitting = false; + static auto selectedFile = [] { std::string s; s.reserve(0x1000); return s; }(); + static auto baseOutputPath = [] { std::string s; s.reserve(0x1000); return s; }(); static u64 splitSize = sizes[0]; static int selectedItem = 0; @@ -820,7 +909,6 @@ namespace hex::plugin::builtin { if (ImGui::Combo("###part_size", &selectedItem, sizeText.data(), sizeText.size())) { splitSize = sizes[selectedItem]; } - } ImGui::EndDisabled(); ImGui::BeginDisabled(splitting || selectedItem != sizes.size() - 1); @@ -841,8 +929,12 @@ namespace hex::plugin::builtin { if (ImGui::Button("hex.builtin.tools.file_tools.splitter.split"_lang)) { splitting = true; - std::thread([]{ - ON_SCOPE_EXIT { splitting = false; selectedFile.clear(); baseOutputPath.clear(); }; + std::thread([] { + ON_SCOPE_EXIT { + splitting = false; + selectedFile.clear(); + baseOutputPath.clear(); + }; File file(selectedFile, File::Mode::Read); if (!file.isValid()) { @@ -887,7 +979,7 @@ namespace hex::plugin::builtin { void drawFileToolCombiner() { static bool combining = false; static std::vector files; - static auto outputPath = []{ std::string s; s.reserve(0x1000); return s; }(); + static auto outputPath = [] { std::string s; s.reserve(0x1000); return s; }(); static i32 selectedIndex; if (ImGui::BeginTable("files_table", 2, ImGuiTableFlags_SizingStretchProp)) { @@ -910,7 +1002,7 @@ namespace hex::plugin::builtin { ImGui::TableNextColumn(); - ImGui::BeginDisabled(selectedIndex <= 0) ; + ImGui::BeginDisabled(selectedIndex <= 0); { if (ImGui::ArrowButton("move_up", ImGuiDir_Up)) { std::iter_swap(files.begin() + selectedIndex, files.begin() + selectedIndex - 1); @@ -919,7 +1011,7 @@ namespace hex::plugin::builtin { } ImGui::EndDisabled(); - ImGui::BeginDisabled(files.empty() || selectedIndex >= files.size() - 1) ; + ImGui::BeginDisabled(files.empty() || selectedIndex >= files.size() - 1); { if (ImGui::ArrowButton("move_down", ImGuiDir_Down)) { std::iter_swap(files.begin() + selectedIndex, files.begin() + selectedIndex + 1); @@ -975,7 +1067,7 @@ namespace hex::plugin::builtin { if (ImGui::Button("hex.builtin.tools.file_tools.combiner.combine"_lang)) { combining = true; - std::thread([]{ + std::thread([] { ON_SCOPE_EXIT { combining = false; }; File output(outputPath, File::Mode::Create); @@ -1016,7 +1108,6 @@ namespace hex::plugin::builtin { } } ImGui::EndDisabled(); - } void drawFileTools() { @@ -1043,16 +1134,16 @@ namespace hex::plugin::builtin { } void registerToolEntries() { - ContentRegistry::Tools::add("hex.builtin.tools.demangler", drawDemangler); - ContentRegistry::Tools::add("hex.builtin.tools.ascii_table", drawASCIITable); - ContentRegistry::Tools::add("hex.builtin.tools.regex_replacer", drawRegexReplacer); - ContentRegistry::Tools::add("hex.builtin.tools.color", drawColorPicker); - ContentRegistry::Tools::add("hex.builtin.tools.calc", drawMathEvaluator); - ContentRegistry::Tools::add("hex.builtin.tools.base_converter", drawBaseConverter); - ContentRegistry::Tools::add("hex.builtin.tools.permissions", drawPermissionsCalculator); - ContentRegistry::Tools::add("hex.builtin.tools.file_uploader", drawFileUploader); - ContentRegistry::Tools::add("hex.builtin.tools.wiki_explain", drawWikiExplainer); - ContentRegistry::Tools::add("hex.builtin.tools.file_tools", drawFileTools); + ContentRegistry::Tools::add("hex.builtin.tools.demangler", drawDemangler); + ContentRegistry::Tools::add("hex.builtin.tools.ascii_table", drawASCIITable); + ContentRegistry::Tools::add("hex.builtin.tools.regex_replacer", drawRegexReplacer); + ContentRegistry::Tools::add("hex.builtin.tools.color", drawColorPicker); + ContentRegistry::Tools::add("hex.builtin.tools.calc", drawMathEvaluator); + ContentRegistry::Tools::add("hex.builtin.tools.base_converter", drawBaseConverter); + ContentRegistry::Tools::add("hex.builtin.tools.permissions", drawPermissionsCalculator); + ContentRegistry::Tools::add("hex.builtin.tools.file_uploader", drawFileUploader); + ContentRegistry::Tools::add("hex.builtin.tools.wiki_explain", drawWikiExplainer); + ContentRegistry::Tools::add("hex.builtin.tools.file_tools", drawFileTools); } } \ No newline at end of file diff --git a/plugins/builtin/source/content/ui_items.cpp b/plugins/builtin/source/content/ui_items.cpp index 8a095d171..e479edf9d 100644 --- a/plugins/builtin/source/content/ui_items.cpp +++ b/plugins/builtin/source/content/ui_items.cpp @@ -22,14 +22,12 @@ namespace hex::plugin::builtin { } ContentRegistry::Interface::addFooterItem([] { - static float framerate = 0; if (ImGui::HasSecondPassed()) { framerate = 1.0F / ImGui::GetIO().DeltaTime; } ImGui::TextFormatted("FPS {0:2}.{1:02}", u32(framerate), u32(framerate * 100) % 100); - }); ContentRegistry::Interface::addFooterItem([] { @@ -58,9 +56,7 @@ namespace hex::plugin::builtin { ImGui::SmallProgressBar(taskProgress, (ImGui::GetCurrentWindow()->MenuBarHeight() - 10_scaled) / 2.0); ImGui::InfoTooltip(taskName.c_str()); } - }); - } void addToolbarItems() { @@ -71,13 +67,15 @@ namespace hex::plugin::builtin { ImGui::Disabled([&provider] { if (ImGui::ToolBarButton(ICON_VS_DISCARD, ImGui::GetCustomColorVec4(ImGuiCustomCol_ToolbarBlue))) provider->undo(); - }, !ImHexApi::Provider::isValid() || !provider->canUndo()); + }, + !ImHexApi::Provider::isValid() || !provider->canUndo()); // Redo ImGui::Disabled([&provider] { if (ImGui::ToolBarButton(ICON_VS_REDO, ImGui::GetCustomColorVec4(ImGuiCustomCol_ToolbarBlue))) provider->redo(); - }, !ImHexApi::Provider::isValid() || !provider->canRedo()); + }, + !ImHexApi::Provider::isValid() || !provider->canRedo()); ImGui::SeparatorEx(ImGuiSeparatorFlags_Vertical); @@ -97,15 +95,17 @@ namespace hex::plugin::builtin { ImGui::Disabled([&provider] { if (ImGui::ToolBarButton(ICON_VS_SAVE, ImGui::GetCustomColorVec4(ImGuiCustomCol_ToolbarBlue))) provider->save(); - }, !ImHexApi::Provider::isValid() || !provider->isWritable() || !provider->isSavable()); + }, + !ImHexApi::Provider::isValid() || !provider->isWritable() || !provider->isSavable()); // Save file as ImGui::Disabled([&provider] { if (ImGui::ToolBarButton(ICON_VS_SAVE_AS, ImGui::GetCustomColorVec4(ImGuiCustomCol_ToolbarBlue))) - hex::openFileBrowser("hex.builtin.view.hexeditor.save_as"_lang, DialogMode::Save, { }, [&provider](auto path) { + hex::openFileBrowser("hex.builtin.view.hexeditor.save_as"_lang, DialogMode::Save, {}, [&provider](auto path) { provider->saveAs(path); }); - }, !ImHexApi::Provider::isValid() || !provider->isSavable()); + }, + !ImHexApi::Provider::isValid() || !provider->isSavable()); ImGui::SeparatorEx(ImGuiSeparatorFlags_Vertical); @@ -117,9 +117,10 @@ namespace hex::plugin::builtin { Region region = { 0 }; EventManager::post(region); - ImHexApi::Bookmarks::add(region.address, region.size, { }, { }); + ImHexApi::Bookmarks::add(region.address, region.size, {}, {}); } - }, !ImHexApi::Provider::isValid() || !provider->isReadable()); + }, + !ImHexApi::Provider::isValid() || !provider->isReadable()); ImGui::SeparatorEx(ImGuiSeparatorFlags_Vertical); @@ -144,10 +145,9 @@ namespace hex::plugin::builtin { ImGui::EndCombo(); } - - }, !ImHexApi::Provider::isValid()); + }, + !ImHexApi::Provider::isValid()); }); - } } \ No newline at end of file diff --git a/plugins/builtin/source/content/views/view_bookmarks.cpp b/plugins/builtin/source/content/views/view_bookmarks.cpp index e25f2c9bd..3b1440127 100644 --- a/plugins/builtin/source/content/views/view_bookmarks.cpp +++ b/plugins/builtin/source/content/views/view_bookmarks.cpp @@ -16,9 +16,7 @@ namespace hex::plugin::builtin { if (bookmark.name.empty()) { bookmark.name.resize(64); std::memset(bookmark.name.data(), 0x00, 64); - std::strcpy(bookmark.name.data(), hex::format("hex.builtin.view.bookmarks.default_title"_lang, - bookmark.region.address, - bookmark.region.address + bookmark.region.size - 1).c_str()); + std::strcpy(bookmark.name.data(), hex::format("hex.builtin.view.bookmarks.default_title"_lang, bookmark.region.address, bookmark.region.address + bookmark.region.size - 1).c_str()); } if (bookmark.comment.empty()) @@ -30,15 +28,15 @@ namespace hex::plugin::builtin { ProjectFile::markDirty(); }); - EventManager::subscribe(this, []{ + EventManager::subscribe(this, [] { SharedData::bookmarkEntries = ProjectFile::getBookmarks(); }); - EventManager::subscribe(this, []{ + EventManager::subscribe(this, [] { ProjectFile::setBookmarks(SharedData::bookmarkEntries); }); - EventManager::subscribe(this, []{ + EventManager::subscribe(this, [] { ImHexApi::Bookmarks::getEntries().clear(); }); } @@ -141,7 +139,7 @@ namespace hex::plugin::builtin { ImGui::TextUnformatted("hex.builtin.view.bookmarks.header.name"_lang); ImGui::Separator(); - ImGui::ColorEdit4("hex.builtin.view.bookmarks.header.color"_lang, (float*)&headerColor.Value, ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_NoAlpha | (locked ? ImGuiColorEditFlags_NoPicker : ImGuiColorEditFlags_None)); + ImGui::ColorEdit4("hex.builtin.view.bookmarks.header.color"_lang, (float *)&headerColor.Value, ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_NoAlpha | (locked ? ImGuiColorEditFlags_NoPicker : ImGuiColorEditFlags_None)); color = headerColor; ImGui::SameLine(); @@ -160,7 +158,6 @@ namespace hex::plugin::builtin { ImGui::InputTextMultiline("##commentInput", comment.data(), 0xF'FFFF); ImGui::NewLine(); - } ImGui::PopID(); ImGui::PopStyleColor(3); @@ -171,7 +168,6 @@ namespace hex::plugin::builtin { bookmarks.erase(bookmarkToRemove); ProjectFile::markDirty(); } - } ImGui::EndChild(); } diff --git a/plugins/builtin/source/content/views/view_command_palette.cpp b/plugins/builtin/source/content/views/view_command_palette.cpp index 5723f63bd..6fdd7e25f 100644 --- a/plugins/builtin/source/content/views/view_command_palette.cpp +++ b/plugins/builtin/source/content/views/view_command_palette.cpp @@ -15,26 +15,26 @@ namespace hex::plugin::builtin { } ViewCommandPalette::~ViewCommandPalette() { - } void ViewCommandPalette::drawContent() { if (!this->m_commandPaletteOpen) return; - ImGui::SetNextWindowPos(ImVec2(SharedData::windowPos.x + SharedData::windowSize.x * 0.5F, SharedData::windowPos.y), ImGuiCond_Always, ImVec2(0.5F,0.0F)); + ImGui::SetNextWindowPos(ImVec2(SharedData::windowPos.x + SharedData::windowSize.x * 0.5F, SharedData::windowPos.y), ImGuiCond_Always, ImVec2(0.5F, 0.0F)); if (ImGui::BeginPopup("hex.builtin.view.command_palette.name"_lang)) { if (ImGui::IsKeyDown(ImGui::GetKeyIndex(ImGuiKey_Escape))) ImGui::CloseCurrentPopup(); ImGui::PushItemWidth(-1); - if (ImGui::InputText("##command_input", this->m_commandBuffer.data(), this->m_commandBuffer.size(), ImGuiInputTextFlags_CallbackEdit | ImGuiInputTextFlags_EnterReturnsTrue, - [](ImGuiInputTextCallbackData *callbackData) -> int { - auto _this = static_cast(callbackData->UserData); - _this->m_lastResults = _this->getCommandResults(callbackData->Buf); + if (ImGui::InputText( + "##command_input", this->m_commandBuffer.data(), this->m_commandBuffer.size(), ImGuiInputTextFlags_CallbackEdit | ImGuiInputTextFlags_EnterReturnsTrue, [](ImGuiInputTextCallbackData *callbackData) -> int { + auto _this = static_cast(callbackData->UserData); + _this->m_lastResults = _this->getCommandResults(callbackData->Buf); - return 0; - }, this)) { + return 0; + }, + this)) { if (!this->m_lastResults.empty()) { auto &[displayResult, matchedCommand, callback] = this->m_lastResults.front(); callback(matchedCommand); @@ -71,25 +71,22 @@ namespace hex::plugin::builtin { } else { this->m_commandPaletteOpen = false; } - } 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, "" }; - } - else if (currCommand.size() <= commandToMatch.size()) { + } else if (currCommand.size() <= commandToMatch.size()) { if (commandToMatch.starts_with(currCommand)) return { MatchType::PartialMatch, currCommand }; else - return { MatchType::NoMatch, { } }; - } - else { + return { MatchType::NoMatch, {} }; + } else { if (currCommand.starts_with(commandToMatch)) return { MatchType::PerfectMatch, currCommand.substr(commandToMatch.length()) }; else - return { MatchType::NoMatch, { } }; + return { MatchType::NoMatch, {} }; } }; @@ -122,7 +119,6 @@ namespace hex::plugin::builtin { } } } - } return results; diff --git a/plugins/builtin/source/content/views/view_constants.cpp b/plugins/builtin/source/content/views/view_constants.cpp index 40af8eb61..83bfbcb41 100644 --- a/plugins/builtin/source/content/views/view_constants.cpp +++ b/plugins/builtin/source/content/views/view_constants.cpp @@ -18,7 +18,6 @@ namespace hex::plugin::builtin { } ViewConstants::~ViewConstants() { - } void ViewConstants::reloadConstants() { @@ -67,26 +66,26 @@ namespace hex::plugin::builtin { void ViewConstants::drawContent() { if (ImGui::Begin(View::toWindowName("hex.builtin.view.constants.name").c_str(), &this->getWindowOpenState(), ImGuiWindowFlags_NoCollapse)) { - ImGui::InputText("##search", this->m_filter.data(), this->m_filter.capacity(), ImGuiInputTextFlags_CallbackEdit, [](ImGuiInputTextCallbackData *data) { - auto &view = *static_cast(data->UserData); - view.m_filter.resize(data->BufTextLen); + ImGui::InputText( + "##search", this->m_filter.data(), this->m_filter.capacity(), ImGuiInputTextFlags_CallbackEdit, [](ImGuiInputTextCallbackData *data) { + auto &view = *static_cast(data->UserData); + view.m_filter.resize(data->BufTextLen); - view.m_filterIndices.clear(); - for (u64 i = 0; i < view.m_constants.size(); i++) { - auto &constant = view.m_constants[i]; - if (hex::containsIgnoreCase(constant.name, data->Buf) || - hex::containsIgnoreCase(constant.category, data->Buf) || - hex::containsIgnoreCase(constant.description, data->Buf) || - hex::containsIgnoreCase(constant.value, data->Buf)) + view.m_filterIndices.clear(); + for (u64 i = 0; i < view.m_constants.size(); i++) { + auto &constant = view.m_constants[i]; + if (hex::containsIgnoreCase(constant.name, data->Buf) || + hex::containsIgnoreCase(constant.category, data->Buf) || + hex::containsIgnoreCase(constant.description, data->Buf) || + hex::containsIgnoreCase(constant.value, data->Buf)) view.m_filterIndices.push_back(i); - } + } - return 0; - }, this); + return 0; + }, + this); - if (ImGui::BeginTable("##strings", 4, - ImGuiTableFlags_Borders | ImGuiTableFlags_Resizable | ImGuiTableFlags_Sortable | - ImGuiTableFlags_Reorderable | ImGuiTableFlags_RowBg | ImGuiTableFlags_ScrollY)) { + if (ImGui::BeginTable("##strings", 4, ImGuiTableFlags_Borders | ImGuiTableFlags_Resizable | ImGuiTableFlags_Sortable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_RowBg | ImGuiTableFlags_ScrollY)) { ImGui::TableSetupScrollFreeze(0, 1); ImGui::TableSetupColumn("hex.builtin.view.constants.row.category"_lang, 0, -1, ImGui::GetID("category")); ImGui::TableSetupColumn("hex.builtin.view.constants.row.name"_lang, 0, -1, ImGui::GetID("name")); @@ -96,8 +95,7 @@ namespace hex::plugin::builtin { auto sortSpecs = ImGui::TableGetSortSpecs(); if (sortSpecs->SpecsDirty) { - std::sort(this->m_constants.begin(), this->m_constants.end(), - [&sortSpecs](Constant &left, Constant &right) -> bool { + std::sort(this->m_constants.begin(), this->m_constants.end(), [&sortSpecs](Constant &left, Constant &right) -> bool { if (sortSpecs->Specs->ColumnUserID == ImGui::GetID("category")) { if (sortSpecs->Specs->SortDirection == ImGuiSortDirection_Ascending) return left.category > right.category; diff --git a/plugins/builtin/source/content/views/view_data_inspector.cpp b/plugins/builtin/source/content/views/view_data_inspector.cpp index 99831929e..03b523c60 100644 --- a/plugins/builtin/source/content/views/view_data_inspector.cpp +++ b/plugins/builtin/source/content/views/view_data_inspector.cpp @@ -4,7 +4,7 @@ #include -extern int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end); +extern int ImTextCharFromUtf8(unsigned int *out_char, const char *in_text, const char *in_text_end); namespace hex::plugin::builtin { @@ -51,9 +51,7 @@ namespace hex::plugin::builtin { auto provider = ImHexApi::Provider::get(); if (ImHexApi::Provider::isValid() && provider->isReadable() && this->m_validBytes > 0) { - if (ImGui::BeginTable("##datainspector", 2, - ImGuiTableFlags_ScrollY | ImGuiTableFlags_Borders | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_RowBg, - ImVec2(0, ImGui::GetTextLineHeightWithSpacing() * (this->m_cachedData.size() + 1)))) { + if (ImGui::BeginTable("##datainspector", 2, ImGuiTableFlags_ScrollY | ImGuiTableFlags_Borders | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_RowBg, ImVec2(0, ImGui::GetTextLineHeightWithSpacing() * (this->m_cachedData.size() + 1)))) { ImGui::TableSetupScrollFreeze(0, 1); ImGui::TableSetupColumn("hex.builtin.view.data_inspector.table.name"_lang); ImGui::TableSetupColumn("hex.builtin.view.data_inspector.table.value"_lang); diff --git a/plugins/builtin/source/content/views/view_data_processor.cpp b/plugins/builtin/source/content/views/view_data_processor.cpp index 2ab67ad48..f8496ecf3 100644 --- a/plugins/builtin/source/content/views/view_data_processor.cpp +++ b/plugins/builtin/source/content/views/view_data_processor.cpp @@ -13,16 +13,16 @@ namespace hex::plugin::builtin { ViewDataProcessor::ViewDataProcessor() : View("hex.builtin.view.data_processor.name") { EventManager::subscribe(this, [](u32 theme) { switch (theme) { - default: - case 1: /* Dark theme */ - ImNodes::StyleColorsDark(); - break; - case 2: /* Light theme */ - ImNodes::StyleColorsLight(); - break; - case 3: /* Classic theme */ - ImNodes::StyleColorsClassic(); - break; + default: + case 1: /* Dark theme */ + ImNodes::StyleColorsDark(); + break; + case 2: /* Light theme */ + ImNodes::StyleColorsLight(); + break; + case 3: /* Classic theme */ + ImNodes::StyleColorsClassic(); + break; } ImNodes::GetStyle().Flags = ImNodesStyleFlags_NodeOutline | ImNodesStyleFlags_GridLines; @@ -36,11 +36,10 @@ namespace hex::plugin::builtin { try { this->loadNodes(ProjectFile::getDataProcessorContent()); } catch (nlohmann::json::exception &e) { - } }); - EventManager::subscribe(this, [this](const fs::path &path){ + EventManager::subscribe(this, [this](const fs::path &path) { for (auto &node : this->m_nodes) { node->setCurrentOverlay(nullptr); } @@ -49,20 +48,25 @@ namespace hex::plugin::builtin { ContentRegistry::Interface::addMenuItem("hex.builtin.menu.file", 3000, [&, this] { if (ImGui::MenuItem("hex.builtin.view.data_processor.menu.file.load_processor"_lang)) { - hex::openFileBrowser("hex.builtin.view.data_processor.menu.file.load_processor"_lang, DialogMode::Open, { { "hex.builtin.view.data_processor.name"_lang, "hexnode"} }, [this](const fs::path &path){ - File file(path, File::Mode::Read); - if (file.isValid()) - this->loadNodes(file.readString()); - }); + hex::openFileBrowser("hex.builtin.view.data_processor.menu.file.load_processor"_lang, DialogMode::Open, { + {"hex.builtin.view.data_processor.name"_lang, "hexnode"} + }, + [this](const fs::path &path) { + File file(path, File::Mode::Read); + if (file.isValid()) + this->loadNodes(file.readString()); + }); } if (ImGui::MenuItem("hex.builtin.view.data_processor.menu.file.save_processor"_lang, nullptr, false, !this->m_nodes.empty())) { - hex::openFileBrowser("hex.builtin.view.data_processor.menu.file.save_processor"_lang, DialogMode::Save, { { "hex.builtin.view.data_processor.name"_lang, "hexnode"} }, [this](const fs::path &path){ - File file(path, File::Mode::Create); - if (file.isValid()) - file.write(this->saveNodes()); - }); - + hex::openFileBrowser("hex.builtin.view.data_processor.menu.file.save_processor"_lang, DialogMode::Save, { + {"hex.builtin.view.data_processor.name"_lang, "hexnode"} + }, + [this](const fs::path &path) { + File file(path, File::Mode::Create); + if (file.isValid()) + file.write(this->saveNodes()); + }); } }); } @@ -79,7 +83,7 @@ namespace hex::plugin::builtin { void ViewDataProcessor::eraseLink(u32 id) { - auto link = std::find_if(this->m_links.begin(), this->m_links.end(), [&id](auto link){ return link.getID() == id; }); + auto link = std::find_if(this->m_links.begin(), this->m_links.end(), [&id](auto link) { return link.getID() == id; }); if (link == this->m_links.end()) return; @@ -97,7 +101,7 @@ namespace hex::plugin::builtin { void ViewDataProcessor::eraseNodes(const std::vector &ids) { for (const int id : ids) { - auto node = std::find_if(this->m_nodes.begin(), this->m_nodes.end(), [&id](auto node){ return node->getID() == id; }); + auto node = std::find_if(this->m_nodes.begin(), this->m_nodes.end(), [&id](auto node) { return node->getID() == id; }); for (auto &attr : (*node)->getAttributes()) { std::vector linksToRemove; @@ -110,9 +114,9 @@ namespace hex::plugin::builtin { } for (const int id : ids) { - auto node = std::find_if(this->m_nodes.begin(), this->m_nodes.end(), [&id](auto node){ return node->getID() == id; }); + auto node = std::find_if(this->m_nodes.begin(), this->m_nodes.end(), [&id](auto node) { return node->getID() == id; }); - std::erase_if(this->m_endNodes, [&id](auto node){ return node->getID() == id; }); + std::erase_if(this->m_endNodes, [&id](auto node) { return node->getID() == id; }); delete *node; @@ -159,7 +163,6 @@ namespace hex::plugin::builtin { } catch (std::runtime_error &e) { printf("Node implementation bug! %s\n", e.what()); } - } void ViewDataProcessor::drawContent() { @@ -268,7 +271,7 @@ namespace hex::plugin::builtin { ImNodes::BeginNodeEditor(); - for (auto& node : this->m_nodes) { + for (auto &node : this->m_nodes) { const bool hasError = this->m_currNodeError.has_value() && this->m_currNodeError->first == node; if (hasError) @@ -282,13 +285,19 @@ namespace hex::plugin::builtin { node->drawNode(); - for (auto& attribute : node->getAttributes()) { + for (auto &attribute : node->getAttributes()) { ImNodesPinShape pinShape; switch (attribute.getType()) { - case dp::Attribute::Type::Integer: pinShape = ImNodesPinShape_Circle; break; - case dp::Attribute::Type::Float: pinShape = ImNodesPinShape_Triangle; break; - case dp::Attribute::Type::Buffer: pinShape = ImNodesPinShape_Quad; break; + case dp::Attribute::Type::Integer: + pinShape = ImNodesPinShape_Circle; + break; + case dp::Attribute::Type::Float: + pinShape = ImNodesPinShape_Triangle; + break; + case dp::Attribute::Type::Buffer: + pinShape = ImNodesPinShape_Quad; + break; } if (attribute.getIOType() == dp::Attribute::IOType::In) { @@ -354,7 +363,6 @@ namespace hex::plugin::builtin { fromAttr->addConnectedAttribute(newLink.getID(), toAttr); toAttr->addConnectedAttribute(newLink.getID(), fromAttr); } while (false); - } } @@ -368,7 +376,6 @@ namespace hex::plugin::builtin { for (const int id : selectedLinks) { eraseLink(id); } - } } @@ -380,12 +387,10 @@ namespace hex::plugin::builtin { ImNodes::GetSelectedNodes(selectedNodes.data()); this->eraseNodes(selectedNodes); - } } this->processNodes(); - } ImGui::End(); } @@ -401,7 +406,10 @@ namespace hex::plugin::builtin { auto pos = ImNodes::GetNodeGridSpacePos(id); currNodeOutput["type"] = node->getUnlocalizedName(); - currNodeOutput["pos"] = { { "x", pos.x }, { "y", pos.y } }; + currNodeOutput["pos"] = { + {"x", pos.x}, + { "y", pos.y} + }; currNodeOutput["attrs"] = json::array(); currNodeOutput["id"] = id; diff --git a/plugins/builtin/source/content/views/view_diff.cpp b/plugins/builtin/source/content/views/view_diff.cpp index bcd30012c..de7dcb605 100644 --- a/plugins/builtin/source/content/views/view_diff.cpp +++ b/plugins/builtin/source/content/views/view_diff.cpp @@ -12,7 +12,7 @@ namespace hex::plugin::builtin { ViewDiff::ViewDiff() : View("hex.builtin.view.diff.name") { - EventManager::subscribe(this, [this]{ + EventManager::subscribe(this, [this] { { auto columnCount = ContentRegistry::Settings::getSetting("hex.builtin.setting.hex_editor", "hex.builtin.setting.hex_editor.column_count"); @@ -34,7 +34,6 @@ namespace hex::plugin::builtin { this->m_upperCaseHex = static_cast(upperCaseHex); } }); - } ViewDiff::~ViewDiff() { @@ -65,7 +64,12 @@ namespace hex::plugin::builtin { return (color & 0x00FFFFFF) | 0x40000000; } - enum class DiffResult { Same, Changed, Added, Removed }; + enum class DiffResult { + Same, + Changed, + Added, + Removed + }; struct LineInfo { std::vector bytes; i64 validBytes = 0; @@ -107,7 +111,7 @@ namespace hex::plugin::builtin { addressDigitCount = std::max(addressDigits, addressDigitCount); } - ImDrawList* drawList = ImGui::GetWindowDrawList(); + ImDrawList *drawList = ImGui::GetWindowDrawList(); auto glyphWidth = ImGui::CalcTextSize("0").x + 1; static auto highlightSize = ImGui::CalcTextSize("00"); @@ -133,19 +137,19 @@ namespace hex::plugin::builtin { // Diff bytes std::optional highlightColor; switch (diffBytes(col, lineInfo[curr], lineInfo[other])) { - default: - case DiffResult::Same: - /* No highlight */ - break; - case DiffResult::Changed: - highlightColor = getDiffColor(ImGui::GetCustomColorU32(ImGuiCustomCol_ToolbarYellow)); - break; - case DiffResult::Added: - highlightColor = getDiffColor(ImGui::GetCustomColorU32(ImGuiCustomCol_ToolbarGreen)); - break; - case DiffResult::Removed: - highlightColor = getDiffColor(ImGui::GetCustomColorU32(ImGuiCustomCol_ToolbarRed)); - break; + default: + case DiffResult::Same: + /* No highlight */ + break; + case DiffResult::Changed: + highlightColor = getDiffColor(ImGui::GetCustomColorU32(ImGuiCustomCol_ToolbarYellow)); + break; + case DiffResult::Added: + highlightColor = getDiffColor(ImGui::GetCustomColorU32(ImGuiCustomCol_ToolbarGreen)); + break; + case DiffResult::Removed: + highlightColor = getDiffColor(ImGui::GetCustomColorU32(ImGuiCustomCol_ToolbarRed)); + break; } // Draw byte @@ -165,7 +169,6 @@ namespace hex::plugin::builtin { } ImGui::TableNextColumn(); } - } void ViewDiff::drawContent() { @@ -217,14 +220,13 @@ namespace hex::plugin::builtin { for (u64 row = clipper.DisplayStart; row < clipper.DisplayEnd; row++) { ImGui::TableNextRow(); ImGui::TableNextColumn(); - drawDiffLine({this->m_providerA, this->m_providerB}, row); + drawDiffLine({ this->m_providerA, this->m_providerB }, row); } } } ImGui::EndTable(); } ImGui::PopStyleVar(); - } ImGui::End(); } diff --git a/plugins/builtin/source/content/views/view_disassembler.cpp b/plugins/builtin/source/content/views/view_disassembler.cpp index 57e8417c5..6a53a58fd 100644 --- a/plugins/builtin/source/content/views/view_disassembler.cpp +++ b/plugins/builtin/source/content/views/view_disassembler.cpp @@ -26,7 +26,7 @@ namespace hex::plugin::builtin { } }); - EventManager::subscribe(this, [this]{ + EventManager::subscribe(this, [this] { this->m_disassembly.clear(); }); } @@ -107,7 +107,6 @@ namespace hex::plugin::builtin { this->m_disassembling = false; }).detach(); - } void ViewDisassembler::drawContent() { @@ -125,14 +124,14 @@ namespace hex::plugin::builtin { ImGui::Checkbox("hex.common.match_selection"_lang, &this->m_shouldMatchSelection); if (ImGui::IsItemEdited()) { // Force execution of Region Selection Event - EventManager::post(Region{ 0, 0 }); + EventManager::post(Region { 0, 0 }); } ImGui::NewLine(); ImGui::TextUnformatted("hex.builtin.view.disassembler.settings.header"_lang); ImGui::Separator(); - ImGui::Combo("hex.builtin.view.disassembler.arch"_lang, reinterpret_cast(&this->m_architecture), Disassembler::ArchitectureNames, Disassembler::getArchitectureSupportedCount()); + ImGui::Combo("hex.builtin.view.disassembler.arch"_lang, reinterpret_cast(&this->m_architecture), Disassembler::ArchitectureNames, Disassembler::getArchitectureSupportedCount()); if (ImGui::BeginChild("modes", ImVec2(0, ImGui::GetTextLineHeightWithSpacing() * 6), true, ImGuiWindowFlags_AlwaysAutoResize)) { @@ -146,123 +145,123 @@ namespace hex::plugin::builtin { ImGui::NewLine(); switch (this->m_architecture) { - case Architecture::ARM: - this->m_modeBasicMIPS = cs_mode(0); - this->m_modeBasicX86 = cs_mode(0); - this->m_modeBasicPPC = cs_mode(0); - this->m_micoMode = false; - this->m_sparcV9Mode = false; + case Architecture::ARM: + this->m_modeBasicMIPS = cs_mode(0); + this->m_modeBasicX86 = cs_mode(0); + this->m_modeBasicPPC = cs_mode(0); + this->m_micoMode = false; + this->m_sparcV9Mode = false; - if (this->m_modeBasicARM == cs_mode(0)) - this->m_modeBasicARM = CS_MODE_ARM; + if (this->m_modeBasicARM == cs_mode(0)) + this->m_modeBasicARM = CS_MODE_ARM; - if (ImGui::RadioButton("hex.builtin.view.disassembler.arm.arm"_lang, this->m_modeBasicARM == CS_MODE_ARM)) - this->m_modeBasicARM = CS_MODE_ARM; - ImGui::SameLine(); - if (ImGui::RadioButton("hex.builtin.view.disassembler.arm.thumb"_lang, this->m_modeBasicARM == CS_MODE_THUMB)) - this->m_modeBasicARM = CS_MODE_THUMB; + if (ImGui::RadioButton("hex.builtin.view.disassembler.arm.arm"_lang, this->m_modeBasicARM == CS_MODE_ARM)) + this->m_modeBasicARM = CS_MODE_ARM; + ImGui::SameLine(); + if (ImGui::RadioButton("hex.builtin.view.disassembler.arm.thumb"_lang, this->m_modeBasicARM == CS_MODE_THUMB)) + this->m_modeBasicARM = CS_MODE_THUMB; - if (ImGui::RadioButton("hex.builtin.view.disassembler.arm.default"_lang, (this->m_modeExtraARM & (CS_MODE_MCLASS | CS_MODE_V8)) == 0)) - this->m_modeExtraARM = cs_mode(0); - ImGui::SameLine(); - if (ImGui::RadioButton("hex.builtin.view.disassembler.arm.cortex_m"_lang, (this->m_modeExtraARM & (CS_MODE_MCLASS | CS_MODE_V8)) == CS_MODE_MCLASS)) - this->m_modeExtraARM = CS_MODE_MCLASS; - ImGui::SameLine(); - if (ImGui::RadioButton("hex.builtin.view.disassembler.arm.armv8"_lang, (this->m_modeExtraARM & (CS_MODE_MCLASS | CS_MODE_V8)) == CS_MODE_V8)) - this->m_modeExtraARM = CS_MODE_V8; - break; - case Architecture::MIPS: - this->m_modeBasicARM = cs_mode(0); + if (ImGui::RadioButton("hex.builtin.view.disassembler.arm.default"_lang, (this->m_modeExtraARM & (CS_MODE_MCLASS | CS_MODE_V8)) == 0)) this->m_modeExtraARM = cs_mode(0); - this->m_modeBasicX86 = cs_mode(0); - this->m_modeBasicPPC = cs_mode(0); - this->m_sparcV9Mode = false; + ImGui::SameLine(); + if (ImGui::RadioButton("hex.builtin.view.disassembler.arm.cortex_m"_lang, (this->m_modeExtraARM & (CS_MODE_MCLASS | CS_MODE_V8)) == CS_MODE_MCLASS)) + this->m_modeExtraARM = CS_MODE_MCLASS; + ImGui::SameLine(); + if (ImGui::RadioButton("hex.builtin.view.disassembler.arm.armv8"_lang, (this->m_modeExtraARM & (CS_MODE_MCLASS | CS_MODE_V8)) == CS_MODE_V8)) + this->m_modeExtraARM = CS_MODE_V8; + break; + case Architecture::MIPS: + this->m_modeBasicARM = cs_mode(0); + this->m_modeExtraARM = cs_mode(0); + this->m_modeBasicX86 = cs_mode(0); + this->m_modeBasicPPC = cs_mode(0); + this->m_sparcV9Mode = false; - if (this->m_modeBasicMIPS == cs_mode(0)) - this->m_modeBasicMIPS = CS_MODE_MIPS32; + if (this->m_modeBasicMIPS == cs_mode(0)) + this->m_modeBasicMIPS = CS_MODE_MIPS32; - if (ImGui::RadioButton("hex.builtin.view.disassembler.mips.mips32"_lang, this->m_modeBasicMIPS == CS_MODE_MIPS32)) - this->m_modeBasicMIPS = CS_MODE_MIPS32; - ImGui::SameLine(); - if (ImGui::RadioButton("hex.builtin.view.disassembler.mips.mips64"_lang, this->m_modeBasicMIPS == CS_MODE_MIPS64)) - this->m_modeBasicMIPS = CS_MODE_MIPS64; - ImGui::SameLine(); - if (ImGui::RadioButton("hex.builtin.view.disassembler.mips.mips32R6"_lang, this->m_modeBasicMIPS == CS_MODE_MIPS32R6)) - this->m_modeBasicMIPS = CS_MODE_MIPS32R6; + if (ImGui::RadioButton("hex.builtin.view.disassembler.mips.mips32"_lang, this->m_modeBasicMIPS == CS_MODE_MIPS32)) + this->m_modeBasicMIPS = CS_MODE_MIPS32; + ImGui::SameLine(); + if (ImGui::RadioButton("hex.builtin.view.disassembler.mips.mips64"_lang, this->m_modeBasicMIPS == CS_MODE_MIPS64)) + this->m_modeBasicMIPS = CS_MODE_MIPS64; + ImGui::SameLine(); + if (ImGui::RadioButton("hex.builtin.view.disassembler.mips.mips32R6"_lang, this->m_modeBasicMIPS == CS_MODE_MIPS32R6)) + this->m_modeBasicMIPS = CS_MODE_MIPS32R6; - ImGui::Checkbox("hex.builtin.view.disassembler.mips.micro"_lang, &this->m_micoMode); - break; - case Architecture::X86: - this->m_modeBasicARM = cs_mode(0); - this->m_modeExtraARM = cs_mode(0); - this->m_modeBasicMIPS = cs_mode(0); - this->m_modeBasicPPC = cs_mode(0); - this->m_micoMode = false; - this->m_sparcV9Mode = false; + ImGui::Checkbox("hex.builtin.view.disassembler.mips.micro"_lang, &this->m_micoMode); + break; + case Architecture::X86: + this->m_modeBasicARM = cs_mode(0); + this->m_modeExtraARM = cs_mode(0); + this->m_modeBasicMIPS = cs_mode(0); + this->m_modeBasicPPC = cs_mode(0); + this->m_micoMode = false; + this->m_sparcV9Mode = false; - if (this->m_modeBasicX86 == cs_mode(0)) - this->m_modeBasicX86 = CS_MODE_16; + if (this->m_modeBasicX86 == cs_mode(0)) + this->m_modeBasicX86 = CS_MODE_16; - if (ImGui::RadioButton("hex.builtin.view.disassembler.x86.16bit"_lang, this->m_modeBasicX86 == CS_MODE_16)) - this->m_modeBasicX86 = CS_MODE_16; - ImGui::SameLine(); - if (ImGui::RadioButton("hex.builtin.view.disassembler.x86.32bit"_lang, this->m_modeBasicX86 == CS_MODE_32)) - this->m_modeBasicX86 = CS_MODE_32; - ImGui::SameLine(); - if (ImGui::RadioButton("hex.builtin.view.disassembler.x86.64bit"_lang, this->m_modeBasicX86 == CS_MODE_64)) - this->m_modeBasicX86 = CS_MODE_64; - break; - case Architecture::PPC: - this->m_modeBasicARM = cs_mode(0); - this->m_modeExtraARM = cs_mode(0); - this->m_modeBasicMIPS = cs_mode(0); - this->m_modeBasicX86 = cs_mode(0); - this->m_micoMode = false; - this->m_sparcV9Mode = false; + if (ImGui::RadioButton("hex.builtin.view.disassembler.x86.16bit"_lang, this->m_modeBasicX86 == CS_MODE_16)) + this->m_modeBasicX86 = CS_MODE_16; + ImGui::SameLine(); + if (ImGui::RadioButton("hex.builtin.view.disassembler.x86.32bit"_lang, this->m_modeBasicX86 == CS_MODE_32)) + this->m_modeBasicX86 = CS_MODE_32; + ImGui::SameLine(); + if (ImGui::RadioButton("hex.builtin.view.disassembler.x86.64bit"_lang, this->m_modeBasicX86 == CS_MODE_64)) + this->m_modeBasicX86 = CS_MODE_64; + break; + case Architecture::PPC: + this->m_modeBasicARM = cs_mode(0); + this->m_modeExtraARM = cs_mode(0); + this->m_modeBasicMIPS = cs_mode(0); + this->m_modeBasicX86 = cs_mode(0); + this->m_micoMode = false; + this->m_sparcV9Mode = false; - if (m_modeBasicPPC == cs_mode(0)) - this->m_modeBasicPPC = CS_MODE_32; + if (m_modeBasicPPC == cs_mode(0)) + this->m_modeBasicPPC = CS_MODE_32; - if (ImGui::RadioButton("hex.builtin.view.disassembler.ppc.32bit"_lang, this->m_modeBasicPPC == CS_MODE_32)) - this->m_modeBasicPPC = CS_MODE_32; - ImGui::SameLine(); - if (ImGui::RadioButton("hex.builtin.view.disassembler.ppc.64bit"_lang, this->m_modeBasicPPC == CS_MODE_64)) - this->m_modeBasicPPC = CS_MODE_64; - break; - case Architecture::SPARC: - this->m_modeBasicARM = cs_mode(0); - this->m_modeExtraARM = cs_mode(0); - this->m_modeBasicMIPS = cs_mode(0); - this->m_modeBasicX86 = cs_mode(0); - this->m_modeBasicPPC = cs_mode(0); - this->m_micoMode = false; + if (ImGui::RadioButton("hex.builtin.view.disassembler.ppc.32bit"_lang, this->m_modeBasicPPC == CS_MODE_32)) + this->m_modeBasicPPC = CS_MODE_32; + ImGui::SameLine(); + if (ImGui::RadioButton("hex.builtin.view.disassembler.ppc.64bit"_lang, this->m_modeBasicPPC == CS_MODE_64)) + this->m_modeBasicPPC = CS_MODE_64; + break; + case Architecture::SPARC: + this->m_modeBasicARM = cs_mode(0); + this->m_modeExtraARM = cs_mode(0); + this->m_modeBasicMIPS = cs_mode(0); + this->m_modeBasicX86 = cs_mode(0); + this->m_modeBasicPPC = cs_mode(0); + this->m_micoMode = false; - ImGui::Checkbox("hex.builtin.view.disassembler.sparc.v9"_lang, &this->m_sparcV9Mode); - break; - case Architecture::ARM64: - case Architecture::SYSZ: - case Architecture::XCORE: - case Architecture::M68K: - case Architecture::TMS320C64X: - case Architecture::M680X: - case Architecture::EVM: - this->m_modeBasicARM = cs_mode(0); - this->m_modeExtraARM = cs_mode(0); - this->m_modeBasicMIPS = cs_mode(0); - this->m_modeBasicX86 = cs_mode(0); - this->m_modeBasicPPC = cs_mode(0); - this->m_micoMode = false; - this->m_sparcV9Mode = false; - break; + ImGui::Checkbox("hex.builtin.view.disassembler.sparc.v9"_lang, &this->m_sparcV9Mode); + break; + case Architecture::ARM64: + case Architecture::SYSZ: + case Architecture::XCORE: + case Architecture::M68K: + case Architecture::TMS320C64X: + case Architecture::M680X: + case Architecture::EVM: + this->m_modeBasicARM = cs_mode(0); + this->m_modeExtraARM = cs_mode(0); + this->m_modeBasicMIPS = cs_mode(0); + this->m_modeBasicX86 = cs_mode(0); + this->m_modeBasicPPC = cs_mode(0); + this->m_micoMode = false; + this->m_sparcV9Mode = false; + break; } - } ImGui::EndChild(); ImGui::Disabled([this] { if (ImGui::Button("hex.builtin.view.disassembler.disassemble"_lang)) this->disassemble(); - }, this->m_disassembling); + }, + this->m_disassembling); if (this->m_disassembling) { ImGui::SameLine(); diff --git a/plugins/builtin/source/content/views/view_hashes.cpp b/plugins/builtin/source/content/views/view_hashes.cpp index bdd8aa038..17042dd71 100644 --- a/plugins/builtin/source/content/views/view_hashes.cpp +++ b/plugins/builtin/source/content/views/view_hashes.cpp @@ -19,7 +19,7 @@ namespace hex::plugin::builtin { this->m_hashRegion[0] = this->m_hashRegion[1] = 0; } else { this->m_hashRegion[0] = region.address; - this->m_hashRegion[1] = region.size + 1; //WARNING: get size - 1 as region size + this->m_hashRegion[1] = region.size + 1; // WARNING: get size - 1 as region size } this->m_shouldInvalidate = true; } @@ -55,7 +55,7 @@ namespace hex::plugin::builtin { ImGui::Checkbox("hex.common.match_selection"_lang, &this->m_shouldMatchSelection); if (ImGui::IsItemEdited()) { // Force execution of Region Selection Event - EventManager::post(Region{ 0, 0 }); + EventManager::post(Region { 0, 0 }); this->m_shouldInvalidate = true; } @@ -63,15 +63,13 @@ namespace hex::plugin::builtin { ImGui::TextUnformatted("hex.builtin.view.hashes.settings"_lang); ImGui::Separator(); - if (ImGui::BeginCombo("hex.builtin.view.hashes.function"_lang, hashFunctionNames[this->m_currHashFunction].second, 0)) - { - for (int i = 0; i < hashFunctionNames.size(); i++) - { + if (ImGui::BeginCombo("hex.builtin.view.hashes.function"_lang, hashFunctionNames[this->m_currHashFunction].second, 0)) { + for (int i = 0; i < hashFunctionNames.size(); i++) { bool is_selected = (this->m_currHashFunction == i); if (ImGui::Selectable(hashFunctionNames[i].second, is_selected)) this->m_currHashFunction = i; if (is_selected) - ImGui::SetItemDefaultFocus(); // Set the initial focus when opening the combo (scrolling + for keyboard navigation support in the upcoming navigation branch) + ImGui::SetItemDefaultFocus(); // Set the initial focus when opening the combo (scrolling + for keyboard navigation support in the upcoming navigation branch) } ImGui::EndCombo(); this->m_shouldInvalidate = true; @@ -83,7 +81,7 @@ namespace hex::plugin::builtin { switch (hashFunctionNames[this->m_currHashFunction].first) { - case HashFunctions::Crc8: + case HashFunctions::Crc8: { static int polynomial = 0x07, init = 0x0000, xorout = 0x0000; static bool reflectIn = false, reflectOut = false; @@ -108,8 +106,7 @@ namespace hex::plugin::builtin { static u8 result = 0; if (this->m_shouldInvalidate) - result = crypt::crc8(provider, this->m_hashRegion[0], this->m_hashRegion[1], - polynomial, init, xorout, reflectIn, reflectOut); + result = crypt::crc8(provider, this->m_hashRegion[0], this->m_hashRegion[1], polynomial, init, xorout, reflectIn, reflectOut); char buffer[sizeof(result) * 2 + 1]; snprintf(buffer, sizeof(buffer), "%02X", result); @@ -118,8 +115,8 @@ namespace hex::plugin::builtin { ImGui::Separator(); ImGui::InputText("##nolabel", buffer, ImGuiInputTextFlags_ReadOnly); } - break; - case HashFunctions::Crc16: + break; + case HashFunctions::Crc16: { static int polynomial = 0x8005, init = 0x0000, xorout = 0x0000; static bool reflectIn = false, reflectOut = false; @@ -144,8 +141,7 @@ namespace hex::plugin::builtin { static u16 result = 0; if (this->m_shouldInvalidate) - result = crypt::crc16(provider, this->m_hashRegion[0], this->m_hashRegion[1], - polynomial, init, xorout, reflectIn, reflectOut); + result = crypt::crc16(provider, this->m_hashRegion[0], this->m_hashRegion[1], polynomial, init, xorout, reflectIn, reflectOut); char buffer[sizeof(result) * 2 + 1]; snprintf(buffer, sizeof(buffer), "%04X", result); @@ -154,14 +150,13 @@ namespace hex::plugin::builtin { ImGui::Separator(); ImGui::InputText("##nolabel", buffer, ImGuiInputTextFlags_ReadOnly); } - break; - case HashFunctions::Crc32: + break; + case HashFunctions::Crc32: { static int polynomial = 0x04C11DB7, init = 0xFFFFFFFF, xorout = 0xFFFFFFFF; static bool reflectIn = true, reflectOut = true; - ImGui::InputInt("hex.builtin.view.hashes.iv"_lang, &init, 0, 0, ImGuiInputTextFlags_CharsHexadecimal); if (ImGui::IsItemEdited()) this->m_shouldInvalidate = true; @@ -182,8 +177,7 @@ namespace hex::plugin::builtin { static u32 result = 0; if (this->m_shouldInvalidate) - result = crypt::crc32(provider, this->m_hashRegion[0], this->m_hashRegion[1], - polynomial, init, xorout, reflectIn, reflectOut); + result = crypt::crc32(provider, this->m_hashRegion[0], this->m_hashRegion[1], polynomial, init, xorout, reflectIn, reflectOut); char buffer[sizeof(result) * 2 + 1]; snprintf(buffer, sizeof(buffer), "%08X", result); @@ -192,8 +186,8 @@ namespace hex::plugin::builtin { ImGui::Separator(); ImGui::InputText("##nolabel", buffer, ImGuiInputTextFlags_ReadOnly); } - break; - case HashFunctions::Md5: + break; + case HashFunctions::Md5: { static std::array result = { 0 }; @@ -208,8 +202,8 @@ namespace hex::plugin::builtin { ImGui::Separator(); ImGui::InputText("##nolabel", buffer, ImGuiInputTextFlags_ReadOnly); } - break; - case HashFunctions::Sha1: + break; + case HashFunctions::Sha1: { static std::array result = { 0 }; @@ -224,8 +218,8 @@ namespace hex::plugin::builtin { ImGui::Separator(); ImGui::InputText("##nolabel", buffer, ImGuiInputTextFlags_ReadOnly); } - break; - case HashFunctions::Sha224: + break; + case HashFunctions::Sha224: { static std::array result = { 0 }; @@ -240,8 +234,8 @@ namespace hex::plugin::builtin { ImGui::Separator(); ImGui::InputText("##nolabel", buffer, ImGuiInputTextFlags_ReadOnly); } - break; - case HashFunctions::Sha256: + break; + case HashFunctions::Sha256: { static std::array result; @@ -256,8 +250,8 @@ namespace hex::plugin::builtin { ImGui::Separator(); ImGui::InputText("##nolabel", buffer, ImGuiInputTextFlags_ReadOnly); } - break; - case HashFunctions::Sha384: + break; + case HashFunctions::Sha384: { static std::array result; @@ -272,8 +266,8 @@ namespace hex::plugin::builtin { ImGui::Separator(); ImGui::InputText("##nolabel", buffer, ImGuiInputTextFlags_ReadOnly); } - break; - case HashFunctions::Sha512: + break; + case HashFunctions::Sha512: { static std::array result; @@ -288,9 +282,8 @@ namespace hex::plugin::builtin { ImGui::Separator(); ImGui::InputText("##nolabel", buffer, ImGuiInputTextFlags_ReadOnly); } - break; + break; } - } this->m_shouldInvalidate = false; diff --git a/plugins/builtin/source/content/views/view_help.cpp b/plugins/builtin/source/content/views/view_help.cpp index 25ef12d4e..6b7148a7d 100644 --- a/plugins/builtin/source/content/views/view_help.cpp +++ b/plugins/builtin/source/content/views/view_help.cpp @@ -22,7 +22,6 @@ namespace hex::plugin::builtin { hex::openWebpage("https://imhex.werwolv.net/docs"); } }); - } ViewHelp::~ViewHelp() { @@ -41,7 +40,7 @@ namespace hex::plugin::builtin { if (!this->m_logoTexture.valid()) { auto logo = romfs::get("logo.png"); - this->m_logoTexture = ImGui::LoadImageFromMemory(reinterpret_cast(logo.data()), logo.size()); + this->m_logoTexture = ImGui::LoadImageFromMemory(reinterpret_cast(logo.data()), logo.size()); } ImGui::Image(this->m_logoTexture.textureId, scaled(this->m_logoTexture.size())); @@ -49,15 +48,16 @@ namespace hex::plugin::builtin { ImGui::TextFormatted("ImHex Hex Editor v{} by WerWolv - " ICON_FA_CODE_BRANCH, IMHEX_VERSION); - #if defined(GIT_BRANCH) && defined(GIT_COMMIT_HASH) - ImGui::SameLine(); - if (ImGui::Hyperlink(hex::format("{0}@{1}", GIT_BRANCH, GIT_COMMIT_HASH).c_str())) - hex::openWebpage("https://github.com/WerWolv/ImHex/commit/" GIT_COMMIT_HASH); - #endif +#if defined(GIT_BRANCH) && defined(GIT_COMMIT_HASH) + ImGui::SameLine(); + if (ImGui::Hyperlink(hex::format("{0}@{1}", GIT_BRANCH, GIT_COMMIT_HASH).c_str())) + hex::openWebpage("https://github.com/WerWolv/ImHex/commit/" GIT_COMMIT_HASH); +#endif ImGui::TextUnformatted("hex.builtin.view.help.about.translator"_lang); - ImGui::TextUnformatted("hex.builtin.view.help.about.source"_lang); ImGui::SameLine(); + ImGui::TextUnformatted("hex.builtin.view.help.about.source"_lang); + ImGui::SameLine(); if (ImGui::Hyperlink("WerWolv/ImHex")) hex::openWebpage("https://github.com/WerWolv/ImHex"); @@ -69,7 +69,7 @@ namespace hex::plugin::builtin { ImGui::TextUnformatted("hex.builtin.view.help.about.donations"_lang); ImGui::Separator(); - constexpr const char* Links[] = { "https://werwolv.net/donate", "https://www.patreon.com/werwolv", "https://github.com/sponsors/WerWolv" }; + constexpr const char *Links[] = { "https://werwolv.net/donate", "https://www.patreon.com/werwolv", "https://github.com/sponsors/WerWolv" }; ImGui::TextFormattedWrapped("{}", static_cast("hex.builtin.view.help.about.thanks"_lang)); @@ -85,7 +85,6 @@ namespace hex::plugin::builtin { link("Mary for porting ImHex to MacOS", "https://github.com/Thog"); link("Roblabla for adding the MSI Windows installer", "https://github.com/roblabla"); link("jam1garner for adding support for Rust plugins", "https://github.com/jam1garner"); - } void ViewHelp::drawLibraryCreditsPage() { @@ -118,16 +117,16 @@ namespace hex::plugin::builtin { ImGui::TableSetupColumn("Type"); ImGui::TableSetupColumn("Paths"); - constexpr std::array, 8> PathTypes = {{ - { "Resources", ImHexPath::Resources }, - { "Config", ImHexPath::Config }, - { "Magic", ImHexPath::Magic }, - { "Patterns", ImHexPath::Patterns }, - { "Patterns Includes", ImHexPath::PatternsInclude }, - { "Plugins", ImHexPath::Plugins }, - { "Python Scripts", ImHexPath::Python }, - { "Yara Patterns", ImHexPath::Yara } - }}; + constexpr std::array, 8> PathTypes = { + {{ "Resources", ImHexPath::Resources }, + { "Config", ImHexPath::Config }, + { "Magic", ImHexPath::Magic }, + { "Patterns", ImHexPath::Patterns }, + { "Patterns Includes", ImHexPath::PatternsInclude }, + { "Plugins", ImHexPath::Plugins }, + { "Python Scripts", ImHexPath::Python }, + { "Yara Patterns", ImHexPath::Yara }} + }; ImGui::TableHeadersRow(); for (const auto &[name, type] : PathTypes) { diff --git a/plugins/builtin/source/content/views/view_hexeditor.cpp b/plugins/builtin/source/content/views/view_hexeditor.cpp index 9474921b3..c752fbda2 100644 --- a/plugins/builtin/source/content/views/view_hexeditor.cpp +++ b/plugins/builtin/source/content/views/view_hexeditor.cpp @@ -59,7 +59,7 @@ namespace hex::plugin::builtin { }; this->m_memoryEditor.HighlightFn = [](const ImU8 *data, size_t off, bool next) -> bool { - ViewHexEditor *_this = (ViewHexEditor *) data; + ViewHexEditor *_this = (ViewHexEditor *)data; std::optional currColor, prevColor; @@ -131,7 +131,7 @@ namespace hex::plugin::builtin { }; this->m_memoryEditor.DecodeFn = [](const ImU8 *data, size_t addr) -> MemoryEditor::DecodeData { - ViewHexEditor *_this = (ViewHexEditor *) data; + ViewHexEditor *_this = (ViewHexEditor *)data; if (_this->m_currEncodingFile.getLongestSequence() == 0) return { ".", 1, 0xFFFF8000 }; @@ -219,7 +219,6 @@ namespace hex::plugin::builtin { this->drawSearchPopup(); this->drawGotoPopup(); - } ImGui::End(); } @@ -230,7 +229,7 @@ namespace hex::plugin::builtin { } static void saveAs() { - hex::openFileBrowser("hex.builtin.view.hexeditor.save_as"_lang, DialogMode::Save, { }, [](const auto &path) { + hex::openFileBrowser("hex.builtin.view.hexeditor.save_as"_lang, DialogMode::Save, {}, [](const auto &path) { ImHexApi::Provider::get()->saveAs(path); }); } @@ -243,12 +242,8 @@ namespace hex::plugin::builtin { ImGui::TextUnformatted("hex.builtin.view.hexeditor.exit_application.desc"_lang); ImGui::NewLine(); - confirmButtons("hex.common.yes"_lang, "hex.common.no"_lang, [] { - ImHexApi::Common::closeImHex(true); - }, - [] { - ImGui::CloseCurrentPopup(); - }); + confirmButtons( + "hex.common.yes"_lang, "hex.common.no"_lang, [] { ImHexApi::Common::closeImHex(true); }, [] { ImGui::CloseCurrentPopup(); }); if (ImGui::IsKeyDown(ImGui::GetKeyIndex(ImGuiKey_Escape))) ImGui::CloseCurrentPopup(); @@ -264,14 +259,17 @@ namespace hex::plugin::builtin { ImGui::InputText("##nolabel", this->m_loaderScriptScriptPath.data(), this->m_loaderScriptScriptPath.length(), ImGuiInputTextFlags_ReadOnly); ImGui::SameLine(); if (ImGui::Button("hex.builtin.view.hexeditor.script.script"_lang)) { - hex::openFileBrowser("hex.builtin.view.hexeditor.script.script.title"_lang, DialogMode::Open, { { "Python Script", "py" } }, [this](const auto &path) { - this->m_loaderScriptScriptPath = path.string(); - }); + hex::openFileBrowser("hex.builtin.view.hexeditor.script.script.title"_lang, DialogMode::Open, { + {"Python Script", "py"} + }, + [this](const auto &path) { + this->m_loaderScriptScriptPath = path.string(); + }); } ImGui::InputText("##nolabel", this->m_loaderScriptFilePath.data(), this->m_loaderScriptFilePath.length(), ImGuiInputTextFlags_ReadOnly); ImGui::SameLine(); if (ImGui::Button("hex.builtin.view.hexeditor.script.file"_lang)) { - hex::openFileBrowser("hex.builtin.view.hexeditor.script.file.title"_lang, DialogMode::Open, { }, [this](const auto &path) { + hex::openFileBrowser("hex.builtin.view.hexeditor.script.file.title"_lang, DialogMode::Open, {}, [this](const auto &path) { this->m_loaderScriptFilePath = path.string(); }); } @@ -280,36 +278,27 @@ namespace hex::plugin::builtin { ImGui::NewLine(); - confirmButtons("hex.common.load"_lang, "hex.common.cancel"_lang, - [this, &provider] { + 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); LoaderScript::setFilePath(this->m_loaderScriptFilePath); LoaderScript::setDataProvider(provider); LoaderScript::processFile(this->m_loaderScriptScriptPath); ImGui::CloseCurrentPopup(); - } - }, - [] { - ImGui::CloseCurrentPopup(); - } - ); + } }, [] { ImGui::CloseCurrentPopup(); }); ImGui::EndPopup(); - } if (ImGui::BeginPopupModal("hex.builtin.view.hexeditor.menu.edit.set_base"_lang, nullptr, ImGuiWindowFlags_AlwaysAutoResize)) { ImGui::InputText("hex.common.address"_lang, this->m_baseAddressBuffer, 16, ImGuiInputTextFlags_CharsHexadecimal); ImGui::NewLine(); - confirmButtons("hex.common.set"_lang, "hex.common.cancel"_lang, - [this, &provider]{ + confirmButtons( + "hex.common.set"_lang, "hex.common.cancel"_lang, [this, &provider] { provider->setBaseAddress(strtoull(this->m_baseAddressBuffer, nullptr, 16)); - ImGui::CloseCurrentPopup(); - }, []{ - ImGui::CloseCurrentPopup(); - }); + ImGui::CloseCurrentPopup(); }, [] { ImGui::CloseCurrentPopup(); }); if (ImGui::IsKeyDown(ImGui::GetKeyIndex(ImGuiKey_Escape))) ImGui::CloseCurrentPopup(); @@ -323,14 +312,10 @@ namespace hex::plugin::builtin { ImGui::InputScalar("hex.common.size"_lang, ImGuiDataType_U64, &this->m_resizeSize, nullptr, nullptr, "%llx", ImGuiInputTextFlags_CharsHexadecimal); ImGui::NewLine(); - confirmButtons("hex.common.set"_lang, "hex.common.cancel"_lang, - [this, &provider]{ + confirmButtons( + "hex.common.set"_lang, "hex.common.cancel"_lang, [this, &provider] { provider->resize(this->m_resizeSize); - ImGui::CloseCurrentPopup(); - }, - [] { - ImGui::CloseCurrentPopup(); - }); + ImGui::CloseCurrentPopup(); }, [] { ImGui::CloseCurrentPopup(); }); if (ImGui::IsKeyDown(ImGui::GetKeyIndex(ImGuiKey_Escape))) ImGui::CloseCurrentPopup(); @@ -344,14 +329,10 @@ namespace hex::plugin::builtin { ImGui::InputScalar("hex.common.size"_lang, ImGuiDataType_U64, &this->m_resizeSize, nullptr, nullptr, "%llx", ImGuiInputTextFlags_CharsHexadecimal); ImGui::NewLine(); - confirmButtons("hex.common.set"_lang, "hex.common.cancel"_lang, - [this, &provider] { + confirmButtons( + "hex.common.set"_lang, "hex.common.cancel"_lang, [this, &provider] { provider->insert(std::min(this->m_memoryEditor.DataPreviewAddr, this->m_memoryEditor.DataPreviewAddrEnd), this->m_resizeSize); - ImGui::CloseCurrentPopup(); - }, - [] { - ImGui::CloseCurrentPopup(); - }); + ImGui::CloseCurrentPopup(); }, [] { ImGui::CloseCurrentPopup(); }); if (ImGui::IsKeyDown(ImGui::GetKeyIndex(ImGuiKey_Escape))) ImGui::CloseCurrentPopup(); @@ -364,7 +345,7 @@ namespace hex::plugin::builtin { hex::prv::Provider *provider = nullptr; EventManager::post("hex.builtin.provider.file", &provider); - if (auto fileProvider = dynamic_cast(provider)) { + if (auto fileProvider = dynamic_cast(provider)) { fileProvider->setPath(path); if (!fileProvider->open()) { View::showErrorPopup("hex.builtin.view.hexeditor.error.open"_lang); @@ -396,7 +377,7 @@ namespace hex::plugin::builtin { EventManager::post(); { - std::vector patterns; + std::vector patterns; EventManager::post(patterns); } } @@ -430,8 +411,8 @@ namespace hex::plugin::builtin { // Check for non-hex characters bool isValidHexString = std::find_if(clipboard.begin(), clipboard.end(), [](char c) { - return !std::isxdigit(c) && !std::isspace(c); - }) == clipboard.end(); + return !std::isxdigit(c) && !std::isspace(c); + }) == clipboard.end(); if (!isValidHexString) return; @@ -477,7 +458,7 @@ namespace hex::plugin::builtin { ImGui::SetClipboardText(buffer.c_str()); } - static std::vector> findString(hex::prv::Provider* &provider, std::string string) { + static std::vector> findString(hex::prv::Provider *&provider, std::string string) { std::vector> results; u32 foundCharacters = 0; @@ -504,7 +485,7 @@ namespace hex::plugin::builtin { return results; } - static std::vector> findHex(hex::prv::Provider* &provider, std::string string) { + static std::vector> findHex(hex::prv::Provider *&provider, std::string string) { std::vector> results; if ((string.size() % 2) == 1) @@ -544,8 +525,8 @@ namespace hex::plugin::builtin { void ViewHexEditor::drawSearchPopup() { - static auto InputCallback = [](ImGuiInputTextCallbackData* data) -> int { - auto _this = static_cast(data->UserData); + static auto InputCallback = [](ImGuiInputTextCallbackData *data) -> int { + auto _this = static_cast(data->UserData); auto provider = ImHexApi::Provider::get(); *_this->m_lastSearchBuffer = _this->m_searchFunction(provider, data->Buf); @@ -571,7 +552,7 @@ namespace hex::plugin::builtin { 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); + (*this->m_lastSearchBuffer)[this->m_lastSearchIndex].second); } }; @@ -585,7 +566,7 @@ namespace hex::plugin::builtin { 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); + (*this->m_lastSearchBuffer)[this->m_lastSearchIndex].second); } }; @@ -599,8 +580,7 @@ namespace hex::plugin::builtin { this->m_lastSearchBuffer = &this->m_lastStringSearch; currBuffer = &this->m_searchStringBuffer; - ImGui::InputText("##nolabel", currBuffer->data(), currBuffer->size(), ImGuiInputTextFlags_CallbackCompletion, - InputCallback, this); + ImGui::InputText("##nolabel", currBuffer->data(), currBuffer->size(), ImGuiInputTextFlags_CallbackCompletion, InputCallback, this); ImGui::EndTabItem(); } @@ -609,9 +589,7 @@ namespace hex::plugin::builtin { this->m_lastSearchBuffer = &this->m_lastHexSearch; currBuffer = &this->m_searchHexBuffer; - ImGui::InputText("##nolabel", currBuffer->data(), currBuffer->size(), - ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CallbackCompletion, - InputCallback, this); + ImGui::InputText("##nolabel", currBuffer->data(), currBuffer->size(), ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CallbackCompletion, InputCallback, this); ImGui::EndTabItem(); } @@ -724,7 +702,7 @@ namespace hex::plugin::builtin { ImGui::Separator(); - for (const auto&[unlocalizedName, callback] : ContentRegistry::DataFormatter::getEntries()) { + for (const auto &[unlocalizedName, callback] : ContentRegistry::DataFormatter::getEntries()) { if (ImGui::MenuItem(LangEntry(unlocalizedName))) { size_t start = std::min(this->m_memoryEditor.DataPreviewAddr, this->m_memoryEditor.DataPreviewAddrEnd); size_t end = std::max(this->m_memoryEditor.DataPreviewAddr, this->m_memoryEditor.DataPreviewAddrEnd); @@ -752,23 +730,23 @@ namespace hex::plugin::builtin { size_t start = base + std::min(this->m_memoryEditor.DataPreviewAddr, this->m_memoryEditor.DataPreviewAddrEnd); size_t end = base + std::max(this->m_memoryEditor.DataPreviewAddr, this->m_memoryEditor.DataPreviewAddrEnd); - ImHexApi::Bookmarks::add(start, end - start + 1, { }, { }); + ImHexApi::Bookmarks::add(start, end - start + 1, {}, {}); } if (ImGui::MenuItem("hex.builtin.view.hexeditor.menu.edit.set_base"_lang, nullptr, false, providerValid && provider->isReadable())) { std::memset(this->m_baseAddressBuffer, 0x00, sizeof(this->m_baseAddressBuffer)); - View::doLater([]{ ImGui::OpenPopup("hex.builtin.view.hexeditor.menu.edit.set_base"_lang); }); + View::doLater([] { ImGui::OpenPopup("hex.builtin.view.hexeditor.menu.edit.set_base"_lang); }); } if (ImGui::MenuItem("hex.builtin.view.hexeditor.menu.edit.resize"_lang, nullptr, false, providerValid && provider->isResizable())) { - View::doLater([this]{ + View::doLater([this] { this->m_resizeSize = ImHexApi::Provider::get()->getActualSize(); ImGui::OpenPopup("hex.builtin.view.hexeditor.menu.edit.resize"_lang); }); } if (ImGui::MenuItem("hex.builtin.view.hexeditor.menu.edit.insert"_lang, nullptr, false, providerValid && provider->isResizable())) { - View::doLater([this]{ + View::doLater([this] { this->m_resizeSize = 0; ImGui::OpenPopup("hex.builtin.view.hexeditor.menu.edit.insert"_lang); }); @@ -794,7 +772,7 @@ namespace hex::plugin::builtin { this->m_memoryEditor.GotoAddrAndSelect(start, start + region.size - 1); } - EventManager::post(Region { this->m_memoryEditor.DataPreviewAddr, (this->m_memoryEditor.DataPreviewAddrEnd - this->m_memoryEditor.DataPreviewAddr) + 1}); + EventManager::post(Region { this->m_memoryEditor.DataPreviewAddr, (this->m_memoryEditor.DataPreviewAddrEnd - this->m_memoryEditor.DataPreviewAddr) + 1 }); }); EventManager::subscribe(this, []() { @@ -810,7 +788,7 @@ namespace hex::plugin::builtin { EventManager::subscribe(this, [this](std::string name) { if (name == "Create File") { - hex::openFileBrowser("hex.builtin.view.hexeditor.create_file"_lang, DialogMode::Save, { }, [this](const auto &path) { + hex::openFileBrowser("hex.builtin.view.hexeditor.create_file"_lang, DialogMode::Save, {}, [this](const auto &path) { File file(path, File::Mode::Create); if (!file.isValid()) { @@ -824,15 +802,18 @@ namespace hex::plugin::builtin { this->getWindowOpenState() = true; }); } else if (name == "Open File") { - hex::openFileBrowser("hex.builtin.view.hexeditor.open_file"_lang, DialogMode::Open, { }, [this](const auto &path) { + hex::openFileBrowser("hex.builtin.view.hexeditor.open_file"_lang, DialogMode::Open, {}, [this](const auto &path) { EventManager::post(path); this->getWindowOpenState() = true; }); } else if (name == "Open Project") { - hex::openFileBrowser("hex.builtin.view.hexeditor.open_project"_lang, DialogMode::Open, { { "Project File", "hexproj" } }, [this](const auto &path) { - ProjectFile::load(path); - this->getWindowOpenState() = true; - }); + hex::openFileBrowser("hex.builtin.view.hexeditor.open_project"_lang, DialogMode::Open, { + {"Project File", "hexproj"} + }, + [this](const auto &path) { + ProjectFile::load(path); + this->getWindowOpenState() = true; + }); } }); @@ -932,7 +913,7 @@ namespace hex::plugin::builtin { }); ShortcutManager::addShortcut(this, CTRL + Keys::O, [] { - hex::openFileBrowser("hex.builtin.view.hexeditor.open_file"_lang, DialogMode::Open, { }, [](const auto &path) { + hex::openFileBrowser("hex.builtin.view.hexeditor.open_file"_lang, DialogMode::Open, {}, [](const auto &path) { EventManager::post(path); }); }); @@ -954,19 +935,18 @@ namespace hex::plugin::builtin { auto provider = ImHexApi::Provider::get(); EventManager::post(Region { provider->getBaseAddress(), provider->getActualSize() }); }); - } void ViewHexEditor::registerMenuItems() { /* Basic operations */ - ContentRegistry::Interface::addMenuItem("hex.builtin.menu.file", 1000, [&]{ + ContentRegistry::Interface::addMenuItem("hex.builtin.menu.file", 1000, [&] { auto provider = ImHexApi::Provider::get(); bool providerValid = ImHexApi::Provider::isValid(); if (ImGui::MenuItem("hex.builtin.view.hexeditor.menu.file.open_file"_lang, "CTRL + O")) { - hex::openFileBrowser("hex.builtin.view.hexeditor.open_file"_lang, DialogMode::Open, { }, [](const auto &path) { + hex::openFileBrowser("hex.builtin.view.hexeditor.open_file"_lang, DialogMode::Open, {}, [](const auto &path) { EventManager::post(path); }); } @@ -982,9 +962,9 @@ namespace hex::plugin::builtin { if (ImGui::MenuItem("hex.builtin.view.hexeditor.menu.file.clear_recent"_lang)) { SharedData::recentFilePaths.clear(); ContentRegistry::Settings::write( - "hex.builtin.setting.imhex", - "hex.builtin.setting.imhex.recent_files", - std::vector{}); + "hex.builtin.setting.imhex", + "hex.builtin.setting.imhex.recent_files", + std::vector {}); } ImGui::EndMenu(); @@ -1027,23 +1007,27 @@ namespace hex::plugin::builtin { bool providerValid = ImHexApi::Provider::isValid(); if (ImGui::MenuItem("hex.builtin.view.hexeditor.menu.file.open_project"_lang, "")) { - hex::openFileBrowser("hex.builtin.view.hexeditor.menu.file.open_project"_lang, DialogMode::Open, { { "Project File", "hexproj" } }, [](const auto &path) { - ProjectFile::load(path); - }); + hex::openFileBrowser("hex.builtin.view.hexeditor.menu.file.open_project"_lang, DialogMode::Open, { + {"Project File", "hexproj"} + }, + [](const auto &path) { + ProjectFile::load(path); + }); } if (ImGui::MenuItem("hex.builtin.view.hexeditor.menu.file.save_project"_lang, "", false, providerValid && provider->isWritable())) { if (ProjectFile::getProjectFilePath() == "") { - hex::openFileBrowser("hex.builtin.view.hexeditor.save_project"_lang, DialogMode::Save, { { "Project File", "hexproj" } }, [](const auto &path) { - if (path.extension() == ".hexproj") { - ProjectFile::store(path); - } - else { - ProjectFile::store(path.string() + ".hexproj"); - } - }); - } - else + hex::openFileBrowser("hex.builtin.view.hexeditor.save_project"_lang, DialogMode::Save, { + {"Project File", "hexproj"} + }, + [](const auto &path) { + if (path.extension() == ".hexproj") { + ProjectFile::store(path); + } else { + ProjectFile::store(path.string() + ".hexproj"); + } + }); + } else ProjectFile::store(); } @@ -1057,9 +1041,12 @@ namespace hex::plugin::builtin { } } - View::showFileChooserPopup(paths, { { "Thingy Table File", "tbl" } }, [this](const auto &path) { - this->m_currEncodingFile = EncodingFile(EncodingFile::Type::Thingy, path); - }); + View::showFileChooserPopup(paths, { + {"Thingy Table File", "tbl"} + }, + [this](const auto &path) { + this->m_currEncodingFile = EncodingFile(EncodingFile::Type::Thingy, path); + }); } }); @@ -1073,7 +1060,7 @@ namespace hex::plugin::builtin { if (ImGui::BeginMenu("hex.builtin.view.hexeditor.menu.file.import"_lang)) { if (ImGui::MenuItem("hex.builtin.view.hexeditor.menu.file.import.base64"_lang)) { - hex::openFileBrowser("hex.builtin.view.hexeditor.menu.file.import.base64"_lang, DialogMode::Open, { }, [this](const auto &path) { + hex::openFileBrowser("hex.builtin.view.hexeditor.menu.file.import.base64"_lang, DialogMode::Open, {}, [this](const auto &path) { File file(path, File::Mode::Read); if (!file.isValid()) { View::showErrorPopup("hex.builtin.view.hexeditor.error.open"_lang); @@ -1098,7 +1085,7 @@ namespace hex::plugin::builtin { if (ImGui::MenuItem("hex.builtin.view.hexeditor.menu.file.import.ips"_lang, nullptr, false, !this->m_processingImportExport)) { - hex::openFileBrowser("hex.builtin.view.hexeditor.open_file"_lang, DialogMode::Open, { }, [this](const auto &path) { + hex::openFileBrowser("hex.builtin.view.hexeditor.open_file"_lang, DialogMode::Open, {}, [this](const auto &path) { this->m_processingImportExport = true; std::thread([this, path] { auto task = ImHexApi::Tasks::createTask("hex.builtin.view.hexeditor.processing", 0); @@ -1123,12 +1110,10 @@ namespace hex::plugin::builtin { this->getWindowOpenState() = true; }); - - } if (ImGui::MenuItem("hex.builtin.view.hexeditor.menu.file.import.ips32"_lang, nullptr, false, !this->m_processingImportExport)) { - hex::openFileBrowser("hex.builtin.view.hexeditor.open_file"_lang, DialogMode::Open, { }, [this](const auto &path) { + hex::openFileBrowser("hex.builtin.view.hexeditor.open_file"_lang, DialogMode::Open, {}, [this](const auto &path) { this->m_processingImportExport = true; std::thread([this, path] { auto task = ImHexApi::Tasks::createTask("hex.builtin.view.hexeditor.processing", 0); @@ -1158,7 +1143,7 @@ namespace hex::plugin::builtin { if (ImGui::MenuItem("hex.builtin.view.hexeditor.menu.file.import.script"_lang)) { this->m_loaderScriptFilePath.clear(); this->m_loaderScriptScriptPath.clear(); - View::doLater([]{ ImGui::OpenPopup("hex.builtin.view.hexeditor.script.title"_lang); }); + View::doLater([] { ImGui::OpenPopup("hex.builtin.view.hexeditor.script.title"_lang); }); } ImGui::EndMenu(); @@ -1176,14 +1161,14 @@ namespace hex::plugin::builtin { } this->m_processingImportExport = true; - std::thread([this, patches]{ + std::thread([this, patches] { auto task = ImHexApi::Tasks::createTask("hex.builtin.view.hexeditor.processing", 0); this->m_dataToSave = generateIPSPatch(patches); this->m_processingImportExport = false; - View::doLater([this]{ - hex::openFileBrowser("hex.builtin.view.hexeditor.menu.file.export.title"_lang, DialogMode::Save, { }, [this](const auto &path) { + View::doLater([this] { + hex::openFileBrowser("hex.builtin.view.hexeditor.menu.file.export.title"_lang, DialogMode::Save, {}, [this](const auto &path) { auto file = File(path, File::Mode::Create); if (!file.isValid()) { View::showErrorPopup("hex.builtin.view.hexeditor.error.create"_lang); @@ -1205,14 +1190,14 @@ namespace hex::plugin::builtin { } this->m_processingImportExport = true; - std::thread([this, patches]{ + std::thread([this, patches] { auto task = ImHexApi::Tasks::createTask("hex.builtin.view.hexeditor.processing", 0); this->m_dataToSave = generateIPS32Patch(patches); this->m_processingImportExport = false; - View::doLater([this]{ - hex::openFileBrowser("hex.builtin.view.hexeditor.menu.file.export.title"_lang, DialogMode::Save, { }, [this](const auto &path) { + View::doLater([this] { + hex::openFileBrowser("hex.builtin.view.hexeditor.menu.file.export.title"_lang, DialogMode::Save, {}, [this](const auto &path) { auto file = File(path, File::Mode::Create); if (!file.isValid()) { View::showErrorPopup("hex.builtin.view.hexeditor.error.create"_lang); diff --git a/plugins/builtin/source/content/views/view_information.cpp b/plugins/builtin/source/content/views/view_information.cpp index 1c642123a..0ebe27b0f 100644 --- a/plugins/builtin/source/content/views/view_information.cpp +++ b/plugins/builtin/source/content/views/view_information.cpp @@ -39,7 +39,7 @@ namespace hex::plugin::builtin { this->m_entropyHandlePosition = region.address / this->m_blockSize; }); - EventManager::subscribe(this, [this]{ + EventManager::subscribe(this, [this] { this->m_dataValid = false; }); @@ -73,13 +73,13 @@ namespace hex::plugin::builtin { entropy += probability * std::log2(probability); } - return (-entropy) / 8; // log2(256) = 8 + return (-entropy) / 8; // log2(256) = 8 } void ViewInformation::analyze() { this->m_analyzing = true; - std::thread([this]{ + std::thread([this] { auto provider = ImHexApi::Provider::get(); auto task = ImHexApi::Tasks::createTask("hex.builtin.view.information.analyzing", provider->getSize()); @@ -136,7 +136,8 @@ namespace hex::plugin::builtin { ImGui::Disabled([this] { if (ImGui::Button("hex.builtin.view.information.analyze"_lang)) this->analyze(); - }, this->m_analyzing); + }, + this->m_analyzing); if (this->m_analyzing) { ImGui::TextSpinner("hex.builtin.view.information.analyzing"_lang); @@ -182,9 +183,9 @@ namespace hex::plugin::builtin { ImGui::TextUnformatted("hex.builtin.view.information.distribution"_lang); ImPlot::SetNextPlotLimits(0, 256, 0.5, float(*std::max_element(this->m_valueCounts.begin(), this->m_valueCounts.end())) * 1.1F, ImGuiCond_Always); - if (ImPlot::BeginPlot("##distribution", "Address", "Count", ImVec2(-1,0), ImPlotFlags_NoLegend | ImPlotFlags_NoMenus | ImPlotFlags_NoBoxSelect, ImPlotAxisFlags_Lock, ImPlotAxisFlags_Lock | ImPlotAxisFlags_LogScale)) { - static auto x = []{ - std::array result{ 0 }; + if (ImPlot::BeginPlot("##distribution", "Address", "Count", ImVec2(-1, 0), ImPlotFlags_NoLegend | ImPlotFlags_NoMenus | ImPlotFlags_NoBoxSelect, ImPlotAxisFlags_Lock, ImPlotAxisFlags_Lock | ImPlotAxisFlags_LogScale)) { + static auto x = [] { + std::array result { 0 }; std::iota(result.begin(), result.end(), 0); return result; }(); @@ -200,13 +201,13 @@ namespace hex::plugin::builtin { ImGui::TextUnformatted("hex.builtin.view.information.entropy"_lang); ImPlot::SetNextPlotLimits(0, this->m_blockEntropy.size(), -0.1, 1.1, ImGuiCond_Always); - if (ImPlot::BeginPlot("##entropy", "Address", "Entropy", ImVec2(-1,0), ImPlotFlags_CanvasOnly | ImPlotFlags_AntiAliased, ImPlotAxisFlags_Lock | ImPlotAxisFlags_NoTickLabels, ImPlotAxisFlags_Lock)) { + if (ImPlot::BeginPlot("##entropy", "Address", "Entropy", ImVec2(-1, 0), ImPlotFlags_CanvasOnly | ImPlotFlags_AntiAliased, ImPlotAxisFlags_Lock | ImPlotAxisFlags_NoTickLabels, ImPlotAxisFlags_Lock)) { ImPlot::PlotLine("##entropy_line", this->m_blockEntropy.data(), this->m_blockEntropy.size()); if (ImPlot::DragLineX("Position", &this->m_entropyHandlePosition, false)) { u64 address = u64(this->m_entropyHandlePosition * this->m_blockSize) + provider->getBaseAddress(); address = std::min(address, provider->getBaseAddress() + provider->getSize() - 1); - EventManager::post( Region{ address, 1 }); + EventManager::post(Region { address, 1 }); } ImPlot::EndPlot(); @@ -224,7 +225,6 @@ namespace hex::plugin::builtin { ImGui::NewLine(); ImGui::TextFormattedColored(ImVec4(0.92F, 0.25F, 0.2F, 1.0F), "{}", "hex.builtin.view.information.encrypted"_lang); } - } } } diff --git a/plugins/builtin/source/content/views/view_patches.cpp b/plugins/builtin/source/content/views/view_patches.cpp index 7a6d709ec..a025db95e 100644 --- a/plugins/builtin/source/content/views/view_patches.cpp +++ b/plugins/builtin/source/content/views/view_patches.cpp @@ -11,13 +11,13 @@ using namespace std::literals::string_literals; namespace hex::plugin::builtin { ViewPatches::ViewPatches() : View("hex.builtin.view.patches.name") { - EventManager::subscribe(this, []{ + EventManager::subscribe(this, [] { auto provider = ImHexApi::Provider::get(); if (ImHexApi::Provider::isValid()) ProjectFile::setPatches(provider->getPatches()); }); - EventManager::subscribe(this, []{ + EventManager::subscribe(this, [] { auto provider = ImHexApi::Provider::get(); if (ImHexApi::Provider::isValid()) provider->getPatches() = ProjectFile::getPatches(); @@ -35,8 +35,7 @@ namespace hex::plugin::builtin { if (ImHexApi::Provider::isValid() && provider->isReadable()) { - if (ImGui::BeginTable("##patchesTable", 3, ImGuiTableFlags_Borders | ImGuiTableFlags_Resizable | ImGuiTableFlags_Sortable | - ImGuiTableFlags_Reorderable | ImGuiTableFlags_RowBg | ImGuiTableFlags_ScrollY)) { + if (ImGui::BeginTable("##patchesTable", 3, ImGuiTableFlags_Borders | ImGuiTableFlags_Resizable | ImGuiTableFlags_Sortable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_RowBg | ImGuiTableFlags_ScrollY)) { ImGui::TableSetupScrollFreeze(0, 1); ImGui::TableSetupColumn("hex.builtin.view.patches.offset"_lang); ImGui::TableSetupColumn("hex.builtin.view.patches.orig"_lang); @@ -44,7 +43,7 @@ namespace hex::plugin::builtin { ImGui::TableHeadersRow(); - auto& patches = provider->getPatches(); + auto &patches = provider->getPatches(); u32 index = 0; ImGuiListClipper clipper(patches.size()); diff --git a/plugins/builtin/source/content/views/view_pattern_data.cpp b/plugins/builtin/source/content/views/view_pattern_data.cpp index b623742dc..0adc529b3 100644 --- a/plugins/builtin/source/content/views/view_pattern_data.cpp +++ b/plugins/builtin/source/content/views/view_pattern_data.cpp @@ -7,7 +7,7 @@ namespace hex::plugin::builtin { ViewPatternData::ViewPatternData() : View("hex.builtin.view.pattern_data.name") { - EventManager::subscribe(this, [this](auto&) { + EventManager::subscribe(this, [this](auto &) { this->m_sortedPatternData.clear(); }); } @@ -16,22 +16,22 @@ namespace hex::plugin::builtin { 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_Hideable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_RowBg | ImGuiTableFlags_ScrollY)) { ImGui::TableSetupScrollFreeze(0, 1); - ImGui::TableSetupColumn("hex.builtin.view.pattern_data.var_name"_lang, 0, 0, ImGui::GetID("name")); - ImGui::TableSetupColumn("hex.builtin.view.pattern_data.color"_lang, 0, 0, ImGui::GetID("color")); - ImGui::TableSetupColumn("hex.builtin.view.pattern_data.offset"_lang, 0, 0, ImGui::GetID("offset")); - ImGui::TableSetupColumn("hex.builtin.view.pattern_data.size"_lang, 0, 0, ImGui::GetID("size")); - ImGui::TableSetupColumn("hex.builtin.view.pattern_data.type"_lang, 0, 0, ImGui::GetID("type")); - ImGui::TableSetupColumn("hex.builtin.view.pattern_data.value"_lang, 0, 0, ImGui::GetID("value")); + ImGui::TableSetupColumn("hex.builtin.view.pattern_data.var_name"_lang, 0, 0, ImGui::GetID("name")); + ImGui::TableSetupColumn("hex.builtin.view.pattern_data.color"_lang, 0, 0, ImGui::GetID("color")); + ImGui::TableSetupColumn("hex.builtin.view.pattern_data.offset"_lang, 0, 0, ImGui::GetID("offset")); + ImGui::TableSetupColumn("hex.builtin.view.pattern_data.size"_lang, 0, 0, ImGui::GetID("size")); + ImGui::TableSetupColumn("hex.builtin.view.pattern_data.type"_lang, 0, 0, ImGui::GetID("type")); + ImGui::TableSetupColumn("hex.builtin.view.pattern_data.value"_lang, 0, 0, ImGui::GetID("value")); auto sortSpecs = ImGui::TableGetSortSpecs(); if (sortSpecs->SpecsDirty || sortedPatterns.empty()) { sortedPatterns = patterns; - std::sort(sortedPatterns.begin(), sortedPatterns.end(), [&sortSpecs, &provider](pl::PatternData* left, pl::PatternData* right) -> bool { + std::sort(sortedPatterns.begin(), sortedPatterns.end(), [&sortSpecs, &provider](pl::PatternData *left, pl::PatternData *right) -> bool { return pl::PatternData::sortPatternDataTable(sortSpecs, provider, left, right); }); @@ -58,12 +58,10 @@ namespace hex::plugin::builtin { for (auto &patternData : this->m_sortedPatternData) patternData->draw(provider); - } ImGui::EndTable(); } - } } ImGui::End(); diff --git a/plugins/builtin/source/content/views/view_pattern_editor.cpp b/plugins/builtin/source/content/views/view_pattern_editor.cpp index 5a16c0b96..7016f600d 100644 --- a/plugins/builtin/source/content/views/view_pattern_editor.cpp +++ b/plugins/builtin/source/content/views/view_pattern_editor.cpp @@ -17,26 +17,18 @@ namespace hex::plugin::builtin { using namespace hex::literals; - static const TextEditor::LanguageDefinition& PatternLanguage() { + static const TextEditor::LanguageDefinition &PatternLanguage() { static bool initialized = false; static TextEditor::LanguageDefinition langDef; if (!initialized) { - static const char* const keywords[] = { - "using", "struct", "union", "enum", "bitfield", - "be", "le", "if", "else", "false", "true", - "this", "parent", "addressof", "sizeof", - "$", - "while", "for", "fn", "return", "break", "continue", - "namespace", "in", "out" + static const char *const keywords[] = { + "using", "struct", "union", "enum", "bitfield", "be", "le", "if", "else", "false", "true", "this", "parent", "addressof", "sizeof", "$", "while", "for", "fn", "return", "break", "continue", "namespace", "in", "out" }; - for (auto& k : keywords) + for (auto &k : keywords) langDef.mKeywords.insert(k); - static const char* const builtInTypes[] = { - "u8", "u16", "u32", "u64", "u128", - "s8", "s16", "s32", "s64", "s128", - "float", "double", "char", "char16", - "bool", "padding", "str", "auto" + static const char *const builtInTypes[] = { + "u8", "u16", "u32", "u64", "u128", "s8", "s16", "s32", "s64", "s128", "float", "double", "char", "char16", "bool", "padding", "str", "auto" }; for (const auto name : builtInTypes) { @@ -45,7 +37,7 @@ namespace hex::plugin::builtin { langDef.mIdentifiers.insert(std::make_pair(std::string(name), id)); } - langDef.mTokenize = [](const char * inBegin, const char * inEnd, const char *& outBegin, const char *& outEnd, TextEditor::PaletteIndex & paletteIndex) -> bool { + langDef.mTokenize = [](const char *inBegin, const char *inEnd, const char *&outBegin, const char *&outEnd, TextEditor::PaletteIndex &paletteIndex) -> bool { paletteIndex = TextEditor::PaletteIndex::Max; while (inBegin < inEnd && isascii(*inBegin) && isblank(*inBegin)) @@ -55,11 +47,9 @@ namespace hex::plugin::builtin { outBegin = inEnd; outEnd = inEnd; paletteIndex = TextEditor::PaletteIndex::Default; - } - else if (TokenizeCStyleIdentifier(inBegin, inEnd, outBegin, outEnd)) { + } else if (TokenizeCStyleIdentifier(inBegin, inEnd, outBegin, outEnd)) { paletteIndex = TextEditor::PaletteIndex::Identifier; - } - else if (TokenizeCStyleNumber(inBegin, inEnd, outBegin, outEnd)) + } else if (TokenizeCStyleNumber(inBegin, inEnd, outBegin, outEnd)) paletteIndex = TextEditor::PaletteIndex::Number; else if (TokenizeCStyleCharacterLiteral(inBegin, inEnd, outBegin, outEnd)) paletteIndex = TextEditor::PaletteIndex::CharLiteral; @@ -105,9 +95,9 @@ namespace hex::plugin::builtin { }); EventManager::subscribe(this, [this](std::string code) { - this->m_textEditor.SelectAll(); - this->m_textEditor.Delete(); - this->m_textEditor.InsertText(code); + this->m_textEditor.SelectAll(); + this->m_textEditor.Delete(); + this->m_textEditor.InsertText(code); }); EventManager::subscribe(this, [this](const fs::path &path) { @@ -159,7 +149,7 @@ namespace hex::plugin::builtin { } }); - EventManager::subscribe(this, [this]{ + EventManager::subscribe(this, [this] { this->m_textEditor.SetText(""); this->m_evaluatorRuntime->abort(); }); @@ -169,22 +159,21 @@ namespace hex::plugin::builtin { EventManager::subscribe(this, [this](u32 theme) { switch (theme) { - default: - case 1: /* Dark theme */ - this->m_textEditor.SetPalette(TextEditor::GetDarkPalette()); - break; - case 2: /* Light theme */ - this->m_textEditor.SetPalette(TextEditor::GetLightPalette()); - break; - case 3: /* Classic theme */ - this->m_textEditor.SetPalette(TextEditor::GetRetroBluePalette()); - break; + default: + case 1: /* Dark theme */ + this->m_textEditor.SetPalette(TextEditor::GetDarkPalette()); + break; + case 2: /* Light theme */ + this->m_textEditor.SetPalette(TextEditor::GetLightPalette()); + break; + case 3: /* Classic theme */ + this->m_textEditor.SetPalette(TextEditor::GetRetroBluePalette()); + break; } }); - } - ContentRegistry::FileHandler::add({ ".hexpat", ".pat" }, [](const fs::path &path) -> bool{ + ContentRegistry::FileHandler::add({ ".hexpat", ".pat" }, [](const fs::path &path) -> bool { File file(path.string(), File::Mode::Read); if (file.isValid()) { @@ -203,24 +192,30 @@ namespace hex::plugin::builtin { for (auto &imhexPath : hex::getPath(ImHexPath::Patterns)) { if (!fs::exists(imhexPath)) continue; - for (auto &entry: fs::recursive_directory_iterator(imhexPath)) { + for (auto &entry : fs::recursive_directory_iterator(imhexPath)) { if (entry.is_regular_file() && entry.path().extension() == ".hexpat") { paths.push_back(entry.path()); } } } - View::showFileChooserPopup(paths, { { "Pattern File", "hexpat" } }, [this](const fs::path &path){ - this->loadPatternFile(path); - }); + View::showFileChooserPopup(paths, { + {"Pattern File", "hexpat"} + }, + [this](const fs::path &path) { + this->loadPatternFile(path); + }); } if (ImGui::MenuItem("hex.builtin.view.pattern_editor.menu.file.save_pattern"_lang)) { - hex::openFileBrowser("hex.builtin.view.pattern_editor.menu.file.save_pattern"_lang, DialogMode::Save, { { "Pattern", "hexpat" }}, [this](const auto &path) { - File file(path, File::Mode::Create); + hex::openFileBrowser("hex.builtin.view.pattern_editor.menu.file.save_pattern"_lang, DialogMode::Save, { + {"Pattern", "hexpat"} + }, + [this](const auto &path) { + File file(path, File::Mode::Create); - file.write(this->m_textEditor.GetText()); - }); + file.write(this->m_textEditor.GetText()); + }); } }); } @@ -243,7 +238,7 @@ namespace hex::plugin::builtin { if (ImHexApi::Provider::isValid() && provider->isAvailable()) { auto textEditorSize = ImGui::GetContentRegionAvail(); - textEditorSize.y *= 3.75/5.0; + textEditorSize.y *= 3.75 / 5.0; textEditorSize.y -= ImGui::GetTextLineHeightWithSpacing(); this->m_textEditor.Render("hex.builtin.view.pattern_editor.name"_lang, textEditorSize, true); @@ -294,10 +289,8 @@ namespace hex::plugin::builtin { ImGui::SameLine(); ImGui::TextFormatted("{} / {}", - this->m_evaluatorRuntime->getCreatedPatternCount(), - this->m_evaluatorRuntime->getMaximumPatternCount() - ); - + this->m_evaluatorRuntime->getCreatedPatternCount(), + this->m_evaluatorRuntime->getMaximumPatternCount()); } if (this->m_textEditor.IsTextChanged()) { @@ -324,15 +317,12 @@ namespace hex::plugin::builtin { ImGui::TextUnformatted("hex.builtin.view.pattern_editor.dangerous_function.desc"_lang); ImGui::NewLine(); - View::confirmButtons("hex.common.yes"_lang, "hex.common.no"_lang, - [this]{ + View::confirmButtons( + "hex.common.yes"_lang, "hex.common.no"_lang, [this] { this->m_evaluatorRuntime->allowDangerousFunctions(true); - ImGui::CloseCurrentPopup(); - }, - [this]{ + ImGui::CloseCurrentPopup(); }, [this] { this->m_evaluatorRuntime->allowDangerousFunctions(false); - ImGui::CloseCurrentPopup(); - }); + ImGui::CloseCurrentPopup(); }); ImGui::EndPopup(); } @@ -351,19 +341,20 @@ namespace hex::plugin::builtin { const auto &[level, message] = this->m_console[i]; switch (level) { - case pl::LogConsole::Level::Debug: - ImGui::PushStyleColor(ImGuiCol_Text, this->m_textEditor.GetPalette()[u32(TextEditor::PaletteIndex::Comment)]); - break; - case pl::LogConsole::Level::Info: - ImGui::PushStyleColor(ImGuiCol_Text, this->m_textEditor.GetPalette()[u32(TextEditor::PaletteIndex::Default)]); - break; - case pl::LogConsole::Level::Warning: - ImGui::PushStyleColor(ImGuiCol_Text, this->m_textEditor.GetPalette()[u32(TextEditor::PaletteIndex::Preprocessor)]); - break; - case pl::LogConsole::Level::Error: - ImGui::PushStyleColor(ImGuiCol_Text, this->m_textEditor.GetPalette()[u32(TextEditor::PaletteIndex::ErrorMarker)]); - break; - default: continue; + case pl::LogConsole::Level::Debug: + ImGui::PushStyleColor(ImGuiCol_Text, this->m_textEditor.GetPalette()[u32(TextEditor::PaletteIndex::Comment)]); + break; + case pl::LogConsole::Level::Info: + ImGui::PushStyleColor(ImGuiCol_Text, this->m_textEditor.GetPalette()[u32(TextEditor::PaletteIndex::Default)]); + break; + case pl::LogConsole::Level::Warning: + ImGui::PushStyleColor(ImGuiCol_Text, this->m_textEditor.GetPalette()[u32(TextEditor::PaletteIndex::Preprocessor)]); + break; + case pl::LogConsole::Level::Error: + ImGui::PushStyleColor(ImGuiCol_Text, this->m_textEditor.GetPalette()[u32(TextEditor::PaletteIndex::ErrorMarker)]); + break; + default: + continue; } if (ImGui::Selectable(message.c_str())) @@ -371,7 +362,6 @@ namespace hex::plugin::builtin { ImGui::PopStyleColor(); } - } ImGui::EndChild(); ImGui::PopStyleColor(1); @@ -396,7 +386,7 @@ namespace hex::plugin::builtin { ON_SCOPE_EXIT { ImGui::PopID(); }; ImGui::PushItemWidth(ImGui::GetContentRegionAvailWidth()); - constexpr const char* Types[] = { "I", "F", "S", "B" }; + constexpr const char *Types[] = { "I", "F", "S", "B" }; if (ImGui::BeginCombo("", Types[static_cast(type)])) { for (auto i = 0; i < IM_ARRAYSIZE(Types); i++) { if (ImGui::Selectable(Types[i])) @@ -410,34 +400,38 @@ namespace hex::plugin::builtin { ImGui::TableNextColumn(); ImGui::PushItemWidth(ImGui::GetContentRegionAvailWidth()); - ImGui::InputText("###name", name.data(), name.capacity(), ImGuiInputTextFlags_CallbackResize, ImGui::UpdateStringSizeCallback, &name); + ImGui::InputText("###name", name.data(), name.capacity(), ImGuiInputTextFlags_CallbackResize, ImGui::UpdateStringSizeCallback, &name); ImGui::PopItemWidth(); ImGui::TableNextColumn(); ImGui::PushItemWidth(ImGui::GetContentRegionAvailWidth()); switch (type) { - case EnvVarType::Integer: { + case EnvVarType::Integer: + { i64 displayValue = hex::get_or(value, 0); - ImGui::InputScalar("###value", ImGuiDataType_S64, &displayValue); + ImGui::InputScalar("###value", ImGuiDataType_S64, &displayValue); value = i128(displayValue); break; } - case EnvVarType::Float: { + case EnvVarType::Float: + { auto displayValue = hex::get_or(value, 0.0); ImGui::InputDouble("###value", &displayValue); value = displayValue; break; } - case EnvVarType::Bool: { + case EnvVarType::Bool: + { auto displayValue = hex::get_or(value, false); ImGui::Checkbox("###value", &displayValue); value = displayValue; break; } - case EnvVarType::String: { + case EnvVarType::String: + { auto displayValue = hex::get_or(value, ""); - ImGui::InputText("###value", displayValue.data(), displayValue.capacity(), ImGuiInputTextFlags_CallbackResize, ImGui::UpdateStringSizeCallback, &displayValue); + ImGui::InputText("###value", displayValue.data(), displayValue.capacity(), ImGuiInputTextFlags_CallbackResize, ImGui::UpdateStringSizeCallback, &displayValue); value = displayValue; break; } @@ -552,12 +546,10 @@ namespace hex::plugin::builtin { ImGui::NewLine(); ImGui::TextUnformatted("hex.builtin.view.pattern_editor.accept_pattern.question"_lang); - confirmButtons("hex.common.yes"_lang, "hex.common.no"_lang, [this]{ + confirmButtons( + "hex.common.yes"_lang, "hex.common.no"_lang, [this] { this->loadPatternFile(this->m_possiblePatternFiles[this->m_selectedPatternFile].string()); - ImGui::CloseCurrentPopup(); - }, []{ - ImGui::CloseCurrentPopup(); - }); + ImGui::CloseCurrentPopup(); }, [] { ImGui::CloseCurrentPopup(); }); if (ImGui::IsKeyDown(ImGui::GetKeyIndex(ImGuiKey_Escape))) ImGui::CloseCurrentPopup(); @@ -596,17 +588,17 @@ namespace hex::plugin::builtin { if (ast) { for (auto node : *ast) { - if (auto variableDecl = dynamic_cast(node)) { - auto type = dynamic_cast(variableDecl->getType()); + if (auto variableDecl = dynamic_cast(node)) { + auto type = dynamic_cast(variableDecl->getType()); if (type == nullptr) continue; - auto builtinType = dynamic_cast(type->getType()); + auto builtinType = dynamic_cast(type->getType()); if (builtinType == nullptr) continue; PatternVariable variable = { - .inVariable = variableDecl->isInVariable(), - .outVariable = variableDecl->isOutVariable(), - .type = builtinType->getType() + .inVariable = variableDecl->isInVariable(), + .outVariable = variableDecl->isOutVariable(), + .type = builtinType->getType() }; if (variable.inVariable || variable.outVariable) { @@ -624,12 +616,12 @@ namespace hex::plugin::builtin { void ViewPatternEditor::evaluatePattern(const std::string &code) { this->m_evaluatorRunning = true; - this->m_textEditor.SetErrorMarkers({ }); + this->m_textEditor.SetErrorMarkers({}); this->m_console.clear(); this->clearPatternData(); { - std::vector patterns; + std::vector patterns; EventManager::post(patterns); } @@ -666,7 +658,6 @@ namespace hex::plugin::builtin { this->m_evaluatorRunning = false; }).detach(); - } } diff --git a/plugins/builtin/source/content/views/view_provider_settings.cpp b/plugins/builtin/source/content/views/view_provider_settings.cpp index 0b051209e..5c644d129 100644 --- a/plugins/builtin/source/content/views/view_provider_settings.cpp +++ b/plugins/builtin/source/content/views/view_provider_settings.cpp @@ -3,7 +3,7 @@ namespace hex::plugin::builtin { ViewProviderSettings::ViewProviderSettings() : hex::View("hex.builtin.view.provider_settings.name") { - EventManager::subscribe(this, [](hex::prv::Provider *provider){ + EventManager::subscribe(this, [](hex::prv::Provider *provider) { if (provider->hasLoadInterface()) EventManager::post(View::toWindowName("hex.builtin.view.provider_settings.load_popup")); }); diff --git a/plugins/builtin/source/content/views/view_settings.cpp b/plugins/builtin/source/content/views/view_settings.cpp index 9a93b86f4..25c06fb7d 100644 --- a/plugins/builtin/source/content/views/view_settings.cpp +++ b/plugins/builtin/source/content/views/view_settings.cpp @@ -9,14 +9,14 @@ namespace hex::plugin::builtin { ViewSettings::ViewSettings() : View("hex.builtin.view.settings.name") { EventManager::subscribe(this, [this](const std::string &name) { if (name == "Settings") { - View::doLater([]{ ImGui::OpenPopup(View::toWindowName("hex.builtin.view.settings.name").c_str()); }); + View::doLater([] { ImGui::OpenPopup(View::toWindowName("hex.builtin.view.settings.name").c_str()); }); this->getWindowOpenState() = true; } }); ContentRegistry::Interface::addMenuItem("hex.builtin.menu.help", 2000, [&, this] { if (ImGui::MenuItem("hex.builtin.view.settings.name"_lang)) { - View::doLater([]{ ImGui::OpenPopup(View::toWindowName("hex.builtin.view.settings.name").c_str()); }); + View::doLater([] { ImGui::OpenPopup(View::toWindowName("hex.builtin.view.settings.name").c_str()); }); this->getWindowOpenState() = true; } }); @@ -49,7 +49,6 @@ namespace hex::plugin::builtin { ImGui::EndPopup(); } else this->getWindowOpenState() = false; - } } \ No newline at end of file diff --git a/plugins/builtin/source/content/views/view_store.cpp b/plugins/builtin/source/content/views/view_store.cpp index e298b0346..0fbf47b49 100644 --- a/plugins/builtin/source/content/views/view_store.cpp +++ b/plugins/builtin/source/content/views/view_store.cpp @@ -27,7 +27,7 @@ namespace hex::plugin::builtin { ContentRegistry::Interface::addMenuItem("hex.builtin.menu.help", 3000, [&, this] { if (ImGui::MenuItem("hex.builtin.view.store.name"_lang)) { - View::doLater([]{ ImGui::OpenPopup(View::toWindowName("hex.builtin.view.store.name").c_str()); }); + View::doLater([] { ImGui::OpenPopup(View::toWindowName("hex.builtin.view.store.name").c_str()); }); this->getWindowOpenState() = true; } }); @@ -42,7 +42,7 @@ namespace hex::plugin::builtin { this->refresh(); } - auto drawTab = [this](auto title, ImHexPath pathType, auto &content, const std::function &downloadDoneCallback) { + auto drawTab = [this](auto title, ImHexPath pathType, auto &content, const std::function &downloadDoneCallback) { if (ImGui::BeginTabItem(title)) { if (ImGui::BeginTable("##pattern_language", 3, ImGuiTableFlags_ScrollY | ImGuiTableFlags_Borders | ImGuiTableFlags_SizingStretchSame | ImGuiTableFlags_RowBg)) { ImGui::TableSetupScrollFreeze(0, 1); @@ -72,46 +72,46 @@ namespace hex::plugin::builtin { auto response = this->m_download.get(); if (response.code == 200) { - entry.installed = true; - entry.hasUpdate = false; + entry.installed = true; + entry.hasUpdate = false; - if (entry.isFolder) { - mtar_t ctx; - mtar_open(&ctx, this->m_downloadPath.string().c_str(), "r"); + if (entry.isFolder) { + mtar_t ctx; + mtar_open(&ctx, this->m_downloadPath.string().c_str(), "r"); - mtar_header_t header; - auto extractBasePath = this->m_downloadPath.parent_path() / this->m_downloadPath.stem(); - while (mtar_read_header(&ctx, &header) != MTAR_ENULLRECORD) { - auto filePath = extractBasePath / fs::path(header.name); - if (filePath.filename() == "@PaxHeader") { - mtar_next(&ctx); - continue; - } + mtar_header_t header; + auto extractBasePath = this->m_downloadPath.parent_path() / this->m_downloadPath.stem(); + while (mtar_read_header(&ctx, &header) != MTAR_ENULLRECORD) { + auto filePath = extractBasePath / fs::path(header.name); + if (filePath.filename() == "@PaxHeader") { + mtar_next(&ctx); + continue; + } - fs::create_directories(filePath.parent_path()); - File outputFile(filePath.string(), File::Mode::Create); + fs::create_directories(filePath.parent_path()); + File outputFile(filePath.string(), File::Mode::Create); - std::vector buffer(0x10000); - for (u64 offset = 0; offset < header.size; offset += buffer.size()) { - auto readSize = std::min(buffer.size(), header.size - offset); - mtar_read_data(&ctx, buffer.data(), readSize); + std::vector buffer(0x10000); + for (u64 offset = 0; offset < header.size; offset += buffer.size()) { + auto readSize = std::min(buffer.size(), header.size - offset); + mtar_read_data(&ctx, buffer.data(), readSize); - buffer.resize(readSize); - outputFile.write(buffer); - } - mtar_next(&ctx); - } + buffer.resize(readSize); + outputFile.write(buffer); + } + mtar_next(&ctx); + } - mtar_finalize(&ctx); - mtar_close(&ctx); - } + mtar_finalize(&ctx); + mtar_close(&ctx); + } - downloadDoneCallback(entry); + downloadDoneCallback(entry); } else log::error("Download failed!"); - this->m_download = { }; + this->m_download = {}; } } else if (entry.hasUpdate) { @@ -177,7 +177,7 @@ namespace hex::plugin::builtin { if (entry.contains("name") && entry.contains("desc") && entry.contains("file") && entry.contains("url") && entry.contains("hash") && entry.contains("folder")) { // Parse entry - StoreEntry storeEntry = { entry["name"], entry["desc"], entry["file"], entry["url"], entry["hash"], entry["folder"],false, false, false }; + StoreEntry storeEntry = { entry["name"], entry["desc"], entry["file"], entry["url"], entry["hash"], entry["folder"], false, false, false }; // Check if file is installed already or has an update available for (const auto &folder : hex::getPath(pathType)) { @@ -189,7 +189,7 @@ namespace hex::plugin::builtin { std::ifstream file(path, std::ios::in | std::ios::binary); std::vector data(fs::file_size(path), 0x00); - file.read(reinterpret_cast(data.data()), data.size()); + file.read(reinterpret_cast(data.data()), data.size()); auto fileHash = crypt::sha256(data); @@ -211,10 +211,8 @@ namespace hex::plugin::builtin { parseStoreEntries(json, "constants", ImHexPath::Constants, this->m_constants); parseStoreEntries(json, "yara", ImHexPath::Yara, this->m_yara); parseStoreEntries(json, "encodings", ImHexPath::Encodings, this->m_encodings); - } - this->m_apiRequest = { }; - + this->m_apiRequest = {}; } void ViewStore::drawContent() { @@ -254,7 +252,7 @@ namespace hex::plugin::builtin { return true; } - + bool ViewStore::remove(ImHexPath pathType, const std::string &fileName) { bool removed = false; for (const auto &path : hex::getPath(pathType)) { diff --git a/plugins/builtin/source/content/views/view_strings.cpp b/plugins/builtin/source/content/views/view_strings.cpp index cd431c037..a6a3daa8c 100644 --- a/plugins/builtin/source/content/views/view_strings.cpp +++ b/plugins/builtin/source/content/views/view_strings.cpp @@ -22,7 +22,7 @@ namespace hex::plugin::builtin { this->m_filter.reserve(0xFFFF); std::memset(this->m_filter.data(), 0x00, this->m_filter.capacity()); - EventManager::subscribe(this, [this]{ + EventManager::subscribe(this, [this] { this->m_foundStrings.clear(); }); } @@ -52,7 +52,7 @@ namespace hex::plugin::builtin { if (ImGui::MenuItem("hex.builtin.view.strings.demangle"_lang)) { this->m_demangledName = llvm::demangle(this->m_selectedString); if (!this->m_demangledName.empty()) - View::doLater([]{ ImGui::OpenPopup("hex.builtin.view.strings.demangle.name"_lang); }); + View::doLater([] { ImGui::OpenPopup("hex.builtin.view.strings.demangle.name"_lang); }); } ImGui::EndPopup(); } @@ -74,7 +74,7 @@ namespace hex::plugin::builtin { task.update(offset); size_t readSize = std::min(u64(buffer.size()), provider->getActualSize() - offset); - provider->read(offset + provider->getBaseAddress(), buffer.data(), readSize); + provider->read(offset + provider->getBaseAddress(), buffer.data(), readSize); for (u32 i = 0; i < readSize; i++) { if (buffer[i] >= ' ' && buffer[i] <= '~' && offset < provider->getActualSize() - 1) @@ -97,7 +97,6 @@ namespace hex::plugin::builtin { this->m_searching = false; }).detach(); - } void ViewStrings::drawContent() { @@ -105,49 +104,50 @@ namespace hex::plugin::builtin { if (ImGui::Begin(View::toWindowName("hex.builtin.view.strings.name").c_str(), &this->getWindowOpenState(), ImGuiWindowFlags_NoCollapse)) { if (ImHexApi::Provider::isValid() && provider->isReadable()) { - ImGui::Disabled([this]{ + ImGui::Disabled([this] { if (ImGui::InputInt("hex.builtin.view.strings.min_length"_lang, &this->m_minimumLength, 1, 0)) this->m_foundStrings.clear(); ImGui::Checkbox("Regex", &this->m_regex); - ImGui::InputText("hex.builtin.view.strings.filter"_lang, this->m_filter.data(), this->m_filter.capacity(), ImGuiInputTextFlags_CallbackEdit, [](ImGuiInputTextCallbackData *data) { - auto &view = *static_cast(data->UserData); - view.m_filter.resize(data->BufTextLen); - view.m_filterIndices.clear(); - std::regex pattern; - if (view.m_regex) { - try { - pattern = std::regex(data->Buf); - view.m_pattern_parsed = true; - } catch (std::regex_error &e) { - view.m_pattern_parsed = false; - } - } - for (u64 i = 0; i < view.m_foundStrings.size(); i++) { + ImGui::InputText( + "hex.builtin.view.strings.filter"_lang, this->m_filter.data(), this->m_filter.capacity(), ImGuiInputTextFlags_CallbackEdit, [](ImGuiInputTextCallbackData *data) { + auto &view = *static_cast(data->UserData); + view.m_filter.resize(data->BufTextLen); + view.m_filterIndices.clear(); + std::regex pattern; if (view.m_regex) { - if(view.m_pattern_parsed && std::regex_search(readString(view.m_foundStrings[i]), pattern)) + try { + pattern = std::regex(data->Buf); + view.m_pattern_parsed = true; + } catch (std::regex_error &e) { + view.m_pattern_parsed = false; + } + } + for (u64 i = 0; i < view.m_foundStrings.size(); i++) { + if (view.m_regex) { + if (view.m_pattern_parsed && std::regex_search(readString(view.m_foundStrings[i]), pattern)) + view.m_filterIndices.push_back(i); + } else if (readString(view.m_foundStrings[i]).find(data->Buf) != std::string::npos) { view.m_filterIndices.push_back(i); + } } - else if (readString(view.m_foundStrings[i]).find(data->Buf) != std::string::npos) { - view.m_filterIndices.push_back(i); - } - } - return 0; - }, this); + return 0; + }, + this); if (this->m_regex && !this->m_pattern_parsed) { ImGui::TextFormattedColored(ImVec4(1.0f, 0.0f, 0.0f, 1.0f), "{}", "hex.builtin.view.strings.regex_error"_lang); } if (ImGui::Button("hex.builtin.view.strings.extract"_lang)) this->searchStrings(); - }, this->m_searching); + }, + this->m_searching); if (this->m_searching) { ImGui::SameLine(); ImGui::TextSpinner("hex.builtin.view.strings.searching"_lang); - } - else if (this->m_foundStrings.size() > 0) { + } else if (this->m_foundStrings.size() > 0) { ImGui::SameLine(); ImGui::TextFormatted("hex.builtin.view.strings.results"_lang, this->m_filterIndices.size()); } @@ -156,9 +156,7 @@ namespace hex::plugin::builtin { ImGui::Separator(); ImGui::NewLine(); - if (ImGui::BeginTable("##strings", 3, - ImGuiTableFlags_Borders | ImGuiTableFlags_Resizable | ImGuiTableFlags_Sortable | - ImGuiTableFlags_Reorderable | ImGuiTableFlags_RowBg | ImGuiTableFlags_ScrollY)) { + if (ImGui::BeginTable("##strings", 3, ImGuiTableFlags_Borders | ImGuiTableFlags_Resizable | ImGuiTableFlags_Sortable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_RowBg | ImGuiTableFlags_ScrollY)) { ImGui::TableSetupScrollFreeze(0, 1); ImGui::TableSetupColumn("hex.builtin.view.strings.offset"_lang, 0, -1, ImGui::GetID("offset")); ImGui::TableSetupColumn("hex.builtin.view.strings.size"_lang, 0, -1, ImGui::GetID("size")); @@ -167,27 +165,26 @@ namespace hex::plugin::builtin { auto sortSpecs = ImGui::TableGetSortSpecs(); if (sortSpecs->SpecsDirty) { - std::sort(this->m_foundStrings.begin(), this->m_foundStrings.end(), - [&sortSpecs](FoundString &left, FoundString &right) -> bool { - if (sortSpecs->Specs->ColumnUserID == ImGui::GetID("offset")) { - if (sortSpecs->Specs->SortDirection == ImGuiSortDirection_Ascending) - return left.offset > right.offset; - else - return left.offset < right.offset; - } else if (sortSpecs->Specs->ColumnUserID == ImGui::GetID("size")) { - if (sortSpecs->Specs->SortDirection == ImGuiSortDirection_Ascending) - return left.size > right.size; - else - return left.size < right.size; - } else if (sortSpecs->Specs->ColumnUserID == ImGui::GetID("string")) { - if (sortSpecs->Specs->SortDirection == ImGuiSortDirection_Ascending) - return readString(left) > readString(right); - else - return readString(left) < readString(right); - } + std::sort(this->m_foundStrings.begin(), this->m_foundStrings.end(), [&sortSpecs](FoundString &left, FoundString &right) -> bool { + if (sortSpecs->Specs->ColumnUserID == ImGui::GetID("offset")) { + if (sortSpecs->Specs->SortDirection == ImGuiSortDirection_Ascending) + return left.offset > right.offset; + else + return left.offset < right.offset; + } else if (sortSpecs->Specs->ColumnUserID == ImGui::GetID("size")) { + if (sortSpecs->Specs->SortDirection == ImGuiSortDirection_Ascending) + return left.size > right.size; + else + return left.size < right.size; + } else if (sortSpecs->Specs->ColumnUserID == ImGui::GetID("string")) { + if (sortSpecs->Specs->SortDirection == ImGuiSortDirection_Ascending) + return readString(left) > readString(right); + else + return readString(left) < readString(right); + } - return false; - }); + return false; + }); sortSpecs->SpecsDirty = false; } @@ -235,7 +232,6 @@ namespace hex::plugin::builtin { ImGui::NewLine(); if (ImGui::Button("hex.builtin.view.strings.demangle.copy"_lang)) ImGui::SetClipboardText(this->m_demangledName.c_str()); - } ImGui::EndChild(); ImGui::EndPopup(); diff --git a/plugins/builtin/source/content/views/view_tools.cpp b/plugins/builtin/source/content/views/view_tools.cpp index 9fb4df849..003db161f 100644 --- a/plugins/builtin/source/content/views/view_tools.cpp +++ b/plugins/builtin/source/content/views/view_tools.cpp @@ -10,7 +10,7 @@ namespace hex::plugin::builtin { void ViewTools::drawContent() { if (ImGui::Begin(View::toWindowName("hex.builtin.view.tools.name").c_str(), &this->getWindowOpenState(), ImGuiWindowFlags_NoCollapse)) { - for (const auto& [name, function] : ContentRegistry::Tools::getEntries()) { + for (const auto &[name, function] : ContentRegistry::Tools::getEntries()) { if (ImGui::CollapsingHeader(LangEntry(name))) { function(); } diff --git a/plugins/builtin/source/content/views/view_yara.cpp b/plugins/builtin/source/content/views/view_yara.cpp index 93f44e569..d46a308c1 100644 --- a/plugins/builtin/source/content/views/view_yara.cpp +++ b/plugins/builtin/source/content/views/view_yara.cpp @@ -52,7 +52,7 @@ namespace hex::plugin::builtin { if (ImGui::Button("hex.builtin.view.yara.reload"_lang)) this->reloadRules(); } else { - ImGui::Disabled([this]{ + ImGui::Disabled([this] { if (ImGui::BeginCombo("hex.builtin.view.yara.header.rules"_lang, this->m_rules[this->m_selectedRule].first.c_str())) { for (u32 i = 0; i < this->m_rules.size(); i++) { const bool selected = (this->m_selectedRule == i); @@ -67,7 +67,8 @@ namespace hex::plugin::builtin { ImGui::SameLine(); if (ImGui::Button("hex.builtin.view.yara.reload"_lang)) this->reloadRules(); if (ImGui::Button("hex.builtin.view.yara.match"_lang)) this->applyRules(); - }, this->m_matching); + }, + this->m_matching); if (this->m_matching) { ImGui::SameLine(); @@ -124,7 +125,6 @@ namespace hex::plugin::builtin { ImGui::EndTable(); } - } ImGui::End(); } @@ -163,25 +163,25 @@ namespace hex::plugin::builtin { }; yr_compiler_set_include_callback( - compiler, - [](const char *includeName, const char *callingRuleFileName, const char *callingRuleNamespace, void *userData) -> const char * { - auto currFilePath = static_cast(userData); + compiler, + [](const char *includeName, const char *callingRuleFileName, const char *callingRuleNamespace, void *userData) -> const char * { + auto currFilePath = static_cast(userData); - File file((fs::path(currFilePath).parent_path() / includeName).string(), File::Mode::Read); - if (!file.isValid()) - return nullptr; + File file((fs::path(currFilePath).parent_path() / includeName).string(), File::Mode::Read); + if (!file.isValid()) + return nullptr; - auto size = file.getSize(); - char *buffer = new char[size + 1]; - file.readBuffer(reinterpret_cast(buffer), size); - buffer[size] = 0x00; + auto size = file.getSize(); + char *buffer = new char[size + 1]; + file.readBuffer(reinterpret_cast(buffer), size); + buffer[size] = 0x00; - return buffer; - }, - [](const char *ptr, void *userData) { - delete[] ptr; - }, - this->m_rules[this->m_selectedRule].second.data()); + return buffer; + }, + [](const char *ptr, void *userData) { + delete[] ptr; + }, + this->m_rules[this->m_selectedRule].second.data()); File file(this->m_rules[this->m_selectedRule].second, File::Mode::Read); @@ -210,8 +210,8 @@ namespace hex::plugin::builtin { ScanContext context; context.task = &task; context.currBlock.base = 0; - context.currBlock.fetch_data = [](auto *block) -> const u8* { - auto &context = *static_cast(block->context); + context.currBlock.fetch_data = [](auto *block) -> const u8 * { + auto &context = *static_cast(block->context); auto provider = ImHexApi::Provider::get(); @@ -230,8 +230,8 @@ namespace hex::plugin::builtin { }; iterator.context = &context; - iterator.first = [](YR_MEMORY_BLOCK_ITERATOR* iterator) -> YR_MEMORY_BLOCK* { - auto &context = *static_cast(iterator->context); + iterator.first = [](YR_MEMORY_BLOCK_ITERATOR *iterator) -> YR_MEMORY_BLOCK * { + auto &context = *static_cast(iterator->context); context.currBlock.base = 0; context.currBlock.size = 0; @@ -240,8 +240,8 @@ namespace hex::plugin::builtin { return iterator->next(iterator); }; - iterator.next = [](YR_MEMORY_BLOCK_ITERATOR* iterator) -> YR_MEMORY_BLOCK* { - auto &context = *static_cast(iterator->context); + iterator.next = [](YR_MEMORY_BLOCK_ITERATOR *iterator) -> YR_MEMORY_BLOCK * { + auto &context = *static_cast(iterator->context); u64 address = context.currBlock.base + context.currBlock.size; @@ -257,32 +257,33 @@ namespace hex::plugin::builtin { }; - yr_rules_scan_mem_blocks(rules, &iterator, 0, [](YR_SCAN_CONTEXT* context, int message, void *data, void *userData) -> int { - if (message == CALLBACK_MSG_RULE_MATCHING) { - auto &newMatches = *static_cast*>(userData); - auto rule = static_cast(data); + yr_rules_scan_mem_blocks( + rules, &iterator, 0, [](YR_SCAN_CONTEXT *context, int message, void *data, void *userData) -> int { + if (message == CALLBACK_MSG_RULE_MATCHING) { + auto &newMatches = *static_cast *>(userData); + auto rule = static_cast(data); - YR_STRING *string; - YR_MATCH *match; + YR_STRING *string; + YR_MATCH *match; - if (rule->strings != nullptr) { - yr_rule_strings_foreach(rule, string) { - yr_string_matches_foreach(context, string, match) { - newMatches.push_back({ rule->identifier, string->identifier, match->offset, match->match_length, false }); + if (rule->strings != nullptr) { + yr_rule_strings_foreach(rule, string) { + yr_string_matches_foreach(context, string, match) { + newMatches.push_back({ rule->identifier, string->identifier, match->offset, match->match_length, false }); + } } + } else { + newMatches.push_back({ rule->identifier, "", 0, 0, true }); } - } else { - newMatches.push_back({ rule->identifier, "", 0, 0, true }); } - } - - return CALLBACK_CONTINUE; - }, &newMatches, 0); + return CALLBACK_CONTINUE; + }, + &newMatches, + 0); std::copy(newMatches.begin(), newMatches.end(), std::back_inserter(this->m_matches)); }).detach(); - } } \ No newline at end of file diff --git a/plugins/builtin/source/math_evaluator.cpp b/plugins/builtin/source/math_evaluator.cpp index ef2e52e47..1c2540b85 100644 --- a/plugins/builtin/source/math_evaluator.cpp +++ b/plugins/builtin/source/math_evaluator.cpp @@ -11,7 +11,7 @@ namespace hex { - i16 comparePrecedence(const Operator& a, const Operator& b) { + i16 comparePrecedence(const Operator &a, const Operator &b) { return (static_cast(a) & 0x0F0) - (static_cast(b) & 0x0F0); } @@ -20,30 +20,30 @@ namespace hex { } std::pair toOperator(std::string input) { - if (input.starts_with("##")) return { Operator::Combine, 2 }; - if (input.starts_with("==")) return { Operator::Equals, 2 }; - if (input.starts_with("!=")) return { Operator::NotEquals, 2 }; - if (input.starts_with(">=")) return { Operator::GreaterThanOrEquals, 2 }; - if (input.starts_with("<=")) return { Operator::LessThanOrEquals, 2 }; - if (input.starts_with(">>")) return { Operator::ShiftRight, 2 }; - if (input.starts_with("<<")) return { Operator::ShiftLeft, 2 }; - if (input.starts_with("||")) return { Operator::Or, 2 }; - if (input.starts_with("^^")) return { Operator::Xor, 2 }; - if (input.starts_with("&&")) return { Operator::And, 2 }; - if (input.starts_with("**")) return { Operator::Exponentiation, 2 }; - if (input.starts_with(">")) return { Operator::GreaterThan, 1 }; - if (input.starts_with("<")) return { Operator::LessThan, 1 }; - if (input.starts_with("!")) return { Operator::Not, 1 }; - if (input.starts_with("|")) return { Operator::BitwiseOr, 1 }; - if (input.starts_with("^")) return { Operator::BitwiseXor, 1 }; - if (input.starts_with("&")) return { Operator::BitwiseAnd, 1 }; - if (input.starts_with("~")) return { Operator::BitwiseNot, 1 }; - if (input.starts_with("+")) return { Operator::Addition, 1 }; - if (input.starts_with("-")) return { Operator::Subtraction, 1 }; - if (input.starts_with("*")) return { Operator::Multiplication, 1 }; - if (input.starts_with("/")) return { Operator::Division, 1 }; - if (input.starts_with("%")) return { Operator::Modulus, 1 }; - if (input.starts_with("=")) return { Operator::Assign, 1 }; + if (input.starts_with("##")) return { Operator::Combine, 2 }; + if (input.starts_with("==")) return { Operator::Equals, 2 }; + if (input.starts_with("!=")) return { Operator::NotEquals, 2 }; + if (input.starts_with(">=")) return { Operator::GreaterThanOrEquals, 2 }; + if (input.starts_with("<=")) return { Operator::LessThanOrEquals, 2 }; + if (input.starts_with(">>")) return { Operator::ShiftRight, 2 }; + if (input.starts_with("<<")) return { Operator::ShiftLeft, 2 }; + if (input.starts_with("||")) return { Operator::Or, 2 }; + if (input.starts_with("^^")) return { Operator::Xor, 2 }; + if (input.starts_with("&&")) return { Operator::And, 2 }; + if (input.starts_with("**")) return { Operator::Exponentiation, 2 }; + if (input.starts_with(">")) return { Operator::GreaterThan, 1 }; + if (input.starts_with("<")) return { Operator::LessThan, 1 }; + if (input.starts_with("!")) return { Operator::Not, 1 }; + if (input.starts_with("|")) return { Operator::BitwiseOr, 1 }; + if (input.starts_with("^")) return { Operator::BitwiseXor, 1 }; + if (input.starts_with("&")) return { Operator::BitwiseAnd, 1 }; + if (input.starts_with("~")) return { Operator::BitwiseNot, 1 }; + if (input.starts_with("+")) return { Operator::Addition, 1 }; + if (input.starts_with("-")) return { Operator::Subtraction, 1 }; + if (input.starts_with("*")) return { Operator::Multiplication, 1 }; + if (input.starts_with("/")) return { Operator::Division, 1 }; + if (input.starts_with("%")) return { Operator::Modulus, 1 }; + if (input.starts_with("=")) return { Operator::Assign, 1 }; return { Operator::Invalid, 0 }; } @@ -51,7 +51,7 @@ namespace hex { std::queue MathEvaluator::parseInput(const char *input) { std::queue inputQueue; - char *prevPos = const_cast(input); + char *prevPos = const_cast(input); for (char *pos = prevPos; *pos != 0x00;) { if (std::isdigit(*pos) || *pos == '.') { auto number = std::strtold(pos, &pos); @@ -61,12 +61,12 @@ namespace hex { number = std::strtoull(pos, &pos, 0); } - inputQueue.push(Token{ .type = TokenType::Number, .number = number }); + inputQueue.push(Token { .type = TokenType::Number, .number = number }); } else if (*pos == '(') { - inputQueue.push(Token{ .type = TokenType::Bracket, .bracketType = BracketType::Left}); + inputQueue.push(Token { .type = TokenType::Bracket, .bracketType = BracketType::Left }); pos++; } else if (*pos == ')') { - inputQueue.push(Token{ .type = TokenType::Bracket, .bracketType = BracketType::Right}); + inputQueue.push(Token { .type = TokenType::Bracket, .bracketType = BracketType::Right }); pos++; } else if (std::isspace(*pos)) { pos++; @@ -74,7 +74,7 @@ namespace hex { auto [op, width] = toOperator(pos); if (op != Operator::Invalid) { - inputQueue.push(Token{ .type = TokenType::Operator, .op = op }); + inputQueue.push(Token { .type = TokenType::Operator, .op = op }); pos += width; } else { Token token; @@ -134,8 +134,6 @@ namespace hex { inputQueue.push(token); } } - - } if (prevPos == pos) @@ -158,9 +156,7 @@ namespace hex { if (currToken.type == TokenType::Number || currToken.type == TokenType::Variable || currToken.type == TokenType::Function) outputQueue.push(currToken); else if (currToken.type == TokenType::Operator) { - while ((!operatorStack.empty()) - && (operatorStack.top().type == TokenType::Operator && currToken.type == TokenType::Operator && (comparePrecedence(operatorStack.top().op, currToken.op) > 0) || (comparePrecedence(operatorStack.top().op, currToken.op) == 0 && isLeftAssociative(currToken.op))) - && operatorStack.top().type != TokenType::Bracket) { + while ((!operatorStack.empty()) && (operatorStack.top().type == TokenType::Operator && currToken.type == TokenType::Operator && (comparePrecedence(operatorStack.top().op, currToken.op) > 0) || (comparePrecedence(operatorStack.top().op, currToken.op) == 0 && isLeftAssociative(currToken.op))) && operatorStack.top().type != TokenType::Bracket) { outputQueue.push(operatorStack.top()); operatorStack.pop(); } @@ -211,89 +207,91 @@ namespace hex { long double rightOperand, leftOperand; if (evaluationStack.size() < 2) { if ((front.op == Operator::Addition || front.op == Operator::Subtraction || front.op == Operator::Not || front.op == Operator::BitwiseNot) && evaluationStack.size() == 1) { - rightOperand = evaluationStack.top(); evaluationStack.pop(); + rightOperand = evaluationStack.top(); + evaluationStack.pop(); leftOperand = 0; - } - else throw std::invalid_argument("Not enough operands for operator!"); + } else throw std::invalid_argument("Not enough operands for operator!"); } else { - rightOperand = evaluationStack.top(); evaluationStack.pop(); - leftOperand = evaluationStack.top(); evaluationStack.pop(); + rightOperand = evaluationStack.top(); + evaluationStack.pop(); + leftOperand = evaluationStack.top(); + evaluationStack.pop(); } long double result = std::numeric_limits::quiet_NaN(); switch (front.op) { - default: - case Operator::Invalid: - throw std::invalid_argument("Invalid operator!"); - case Operator::And: - result = static_cast(leftOperand) && static_cast(rightOperand); - break; - case Operator::Or: - result = static_cast(leftOperand) && static_cast(rightOperand); - break; - case Operator::Xor: - result = (static_cast(leftOperand) ^ static_cast(rightOperand)) > 0; - break; - case Operator::GreaterThan: - result = leftOperand > rightOperand; - break; - case Operator::LessThan: - result = leftOperand < rightOperand; - break; - case Operator::GreaterThanOrEquals: - result = leftOperand >= rightOperand; - break; - case Operator::LessThanOrEquals: - result = leftOperand <= rightOperand; - break; - case Operator::Equals: - result = leftOperand == rightOperand; - break; - case Operator::NotEquals: - result = leftOperand != rightOperand; - break; - case Operator::Not: - result = !static_cast(rightOperand); - break; - case Operator::BitwiseOr: - result = static_cast(leftOperand) | static_cast(rightOperand); - break; - case Operator::BitwiseXor: - result = static_cast(leftOperand) ^ static_cast(rightOperand); - break; - case Operator::BitwiseAnd: - result = static_cast(leftOperand) & static_cast(rightOperand); - break; - case Operator::BitwiseNot: - result = ~static_cast(rightOperand); - break; - case Operator::ShiftLeft: - result = static_cast(leftOperand) << static_cast(rightOperand); - break; - case Operator::ShiftRight: - result = static_cast(leftOperand) >> static_cast(rightOperand); - break; - case Operator::Addition: - result = leftOperand + rightOperand; - break; - case Operator::Subtraction: - result = leftOperand - rightOperand; - break; - case Operator::Multiplication: - result = leftOperand * rightOperand; - break; - case Operator::Division: - result = leftOperand / rightOperand; - break; - case Operator::Modulus: - result = std::fmod(leftOperand, rightOperand); - break; - case Operator::Exponentiation: - result = std::pow(leftOperand, rightOperand); - break; - case Operator::Combine: - result = (static_cast(leftOperand) << (64 - __builtin_clzll(static_cast(rightOperand)))) | static_cast(rightOperand); - break; + default: + case Operator::Invalid: + throw std::invalid_argument("Invalid operator!"); + case Operator::And: + result = static_cast(leftOperand) && static_cast(rightOperand); + break; + case Operator::Or: + result = static_cast(leftOperand) && static_cast(rightOperand); + break; + case Operator::Xor: + result = (static_cast(leftOperand) ^ static_cast(rightOperand)) > 0; + break; + case Operator::GreaterThan: + result = leftOperand > rightOperand; + break; + case Operator::LessThan: + result = leftOperand < rightOperand; + break; + case Operator::GreaterThanOrEquals: + result = leftOperand >= rightOperand; + break; + case Operator::LessThanOrEquals: + result = leftOperand <= rightOperand; + break; + case Operator::Equals: + result = leftOperand == rightOperand; + break; + case Operator::NotEquals: + result = leftOperand != rightOperand; + break; + case Operator::Not: + result = !static_cast(rightOperand); + break; + case Operator::BitwiseOr: + result = static_cast(leftOperand) | static_cast(rightOperand); + break; + case Operator::BitwiseXor: + result = static_cast(leftOperand) ^ static_cast(rightOperand); + break; + case Operator::BitwiseAnd: + result = static_cast(leftOperand) & static_cast(rightOperand); + break; + case Operator::BitwiseNot: + result = ~static_cast(rightOperand); + break; + case Operator::ShiftLeft: + result = static_cast(leftOperand) << static_cast(rightOperand); + break; + case Operator::ShiftRight: + result = static_cast(leftOperand) >> static_cast(rightOperand); + break; + case Operator::Addition: + result = leftOperand + rightOperand; + break; + case Operator::Subtraction: + result = leftOperand - rightOperand; + break; + case Operator::Multiplication: + result = leftOperand * rightOperand; + break; + case Operator::Division: + result = leftOperand / rightOperand; + break; + case Operator::Modulus: + result = std::fmod(leftOperand, rightOperand); + break; + case Operator::Exponentiation: + result = std::pow(leftOperand, rightOperand); + break; + case Operator::Combine: + result = (static_cast(leftOperand) << (64 - __builtin_clzll(static_cast(rightOperand)))) | static_cast(rightOperand); + break; } evaluationStack.push(result); @@ -312,11 +310,10 @@ namespace hex { evaluationStack.push(result.value()); } else throw std::invalid_argument("Parenthesis in postfix expression!"); - } if (evaluationStack.empty()) - return { }; + return {}; else if (evaluationStack.size() > 1) throw std::invalid_argument("Undigested input left!"); else @@ -373,18 +370,29 @@ namespace hex { } void MathEvaluator::registerStandardFunctions() { - this->setFunction("sin", [](auto args){ return std::sin(args[0]); }, 1, 1); - this->setFunction("cos", [](auto args){ return std::cos(args[0]); }, 1, 1); - this->setFunction("tan", [](auto args){ return std::tan(args[0]); }, 1, 1); - this->setFunction("sqrt", [](auto args){ return std::sqrt(args[0]); }, 1, 1); - this->setFunction("ceil", [](auto args){ return std::ceil(args[0]); }, 1, 1); - this->setFunction("floor", [](auto args){ return std::floor(args[0]); }, 1, 1); - this->setFunction("sign", [](auto args){ return (args[0] > 0) ? 1 : (args[0] == 0) ? 0 : -1; }, 1, 1); - this->setFunction("abs", [](auto args){ return std::abs(args[0]); }, 1, 1); - this->setFunction("ln", [](auto args){ return std::log(args[0]); }, 1, 1); - this->setFunction("lb", [](auto args){ return std::log2(args[0]); }, 1, 1); - this->setFunction("log", [](auto args){ return args.size() == 1 ? std::log10(args[0]) : std::log(args[1]) / std::log(args[0]); }, 1, 2); + this->setFunction( + "sin", [](auto args) { return std::sin(args[0]); }, 1, 1); + this->setFunction( + "cos", [](auto args) { return std::cos(args[0]); }, 1, 1); + this->setFunction( + "tan", [](auto args) { return std::tan(args[0]); }, 1, 1); + this->setFunction( + "sqrt", [](auto args) { return std::sqrt(args[0]); }, 1, 1); + this->setFunction( + "ceil", [](auto args) { return std::ceil(args[0]); }, 1, 1); + this->setFunction( + "floor", [](auto args) { return std::floor(args[0]); }, 1, 1); + this->setFunction( + "sign", [](auto args) { return (args[0] > 0) ? 1 : (args[0] == 0) ? 0 + : -1; }, 1, 1); + this->setFunction( + "abs", [](auto args) { return std::abs(args[0]); }, 1, 1); + this->setFunction( + "ln", [](auto args) { return std::log(args[0]); }, 1, 1); + this->setFunction( + "lb", [](auto args) { return std::log2(args[0]); }, 1, 1); + this->setFunction( + "log", [](auto args) { return args.size() == 1 ? std::log10(args[0]) : std::log(args[1]) / std::log(args[0]); }, 1, 2); } } - diff --git a/plugins/builtin/source/plugin_builtin.cpp b/plugins/builtin/source/plugin_builtin.cpp index b5227a9eb..ddb066b53 100644 --- a/plugins/builtin/source/plugin_builtin.cpp +++ b/plugins/builtin/source/plugin_builtin.cpp @@ -50,5 +50,3 @@ IMHEX_PLUGIN_SETUP("Built-in", "WerWolv", "Default ImHex functionality") { registerLanguageItIT(); registerLanguageZhCN(); } - - diff --git a/plugins/example_cpp/source/plugin_example.cpp b/plugins/example_cpp/source/plugin_example.cpp index c16ef916a..35392828c 100644 --- a/plugins/example_cpp/source/plugin_example.cpp +++ b/plugins/example_cpp/source/plugin_example.cpp @@ -4,8 +4,8 @@ class ViewExample : public hex::View { public: - ViewExample() : hex::View("Example") {} - ~ViewExample() override {} + ViewExample() : hex::View("Example") { } + ~ViewExample() override { } void drawContent() override { if (ImGui::Begin("Example")) { @@ -18,7 +18,4 @@ public: IMHEX_PLUGIN_SETUP("Example C++", "WerWolv", "Example C++ plugin used as template for plugin devs") { ContentRegistry::Views::add(); - } - - diff --git a/plugins/example_rust/source/plugin_example.rs b/plugins/example_rust/source/plugin_example.rs index 1e2e823e9..49bb26874 100644 --- a/plugins/example_rust/source/plugin_example.rs +++ b/plugins/example_rust/source/plugin_example.rs @@ -1,7 +1,5 @@ extern crate hex; #[hex::plugin_setup("Example Rust", "WerWolv", "Example Rust plugin used as template for plugin devs")] -fn init() { - -} +fn init() {} diff --git a/plugins/windows/include/views/view_tty_console.hpp b/plugins/windows/include/views/view_tty_console.hpp index d1edb2c0c..9fc04aa4f 100644 --- a/plugins/windows/include/views/view_tty_console.hpp +++ b/plugins/windows/include/views/view_tty_console.hpp @@ -10,7 +10,9 @@ namespace hex::plugin::windows { - namespace prv { class Provider; } + namespace prv { + class Provider; + } class ViewTTYConsole : public View { public: @@ -32,11 +34,11 @@ namespace hex::plugin::windows { std::jthread m_receiveThread; int m_selectedPort = 0; - int m_selectedBaudRate = 11; // 115200 - int m_selectedNumBits = 3; // 8 - int m_selectedStopBits = 0; // 1 - int m_selectedParityBits = 0; // None - bool m_hasCTSFlowControl = false; // No + int m_selectedBaudRate = 11; // 115200 + int m_selectedNumBits = 3; // 8 + int m_selectedStopBits = 0; // 1 + int m_selectedParityBits = 0; // None + bool m_hasCTSFlowControl = false; // No bool m_shouldAutoScroll = true; @@ -46,41 +48,41 @@ namespace hex::plugin::windows { bool m_transmitting = false; constexpr static std::array BaudRates = { - "110", - "300", - "600", - "1200", - "2400", - "4800", - "9600", - "14400", - "19200", - "38400", - "57600", - "115200", - "128000", - "256000" + "110", + "300", + "600", + "1200", + "2400", + "4800", + "9600", + "14400", + "19200", + "38400", + "57600", + "115200", + "128000", + "256000" }; constexpr static std::array NumBits = { - "5", - "6", - "7", - "8" + "5", + "6", + "7", + "8" }; constexpr static std::array StopBits = { - "1", - "1.5", - "2.0" + "1", + "1.5", + "2.0" }; constexpr static std::array ParityBits = { - "None", - "Odd", - "Even", - "Mark", - "Space" + "None", + "Odd", + "Even", + "Mark", + "Space" }; }; diff --git a/plugins/windows/source/content/settings_entries.cpp b/plugins/windows/source/content/settings_entries.cpp index 17e4cd3a4..d104d0b0a 100644 --- a/plugins/windows/source/content/settings_entries.cpp +++ b/plugins/windows/source/content/settings_entries.cpp @@ -19,7 +19,7 @@ namespace hex::plugin::windows { void addImHexContextMenuEntry() { // Create ImHex Root Key HKEY imHexRootKey; - RegCreateKeyExA(HKEY_CURRENT_USER, ImHexContextMenuKey, 0x00, nullptr, REG_OPTION_NON_VOLATILE, KEY_SET_VALUE , nullptr, &imHexRootKey, nullptr); + RegCreateKeyExA(HKEY_CURRENT_USER, ImHexContextMenuKey, 0x00, nullptr, REG_OPTION_NON_VOLATILE, KEY_SET_VALUE, nullptr, &imHexRootKey, nullptr); RegSetValueA(imHexRootKey, nullptr, REG_SZ, "Open with ImHex", 0x00); // Add Icon key to use first icon embedded in exe @@ -70,7 +70,6 @@ namespace hex::plugin::windows { return false; }); - } } \ No newline at end of file diff --git a/plugins/windows/source/content/ui_items.cpp b/plugins/windows/source/content/ui_items.cpp index aff8df28b..7829e035f 100644 --- a/plugins/windows/source/content/ui_items.cpp +++ b/plugins/windows/source/content/ui_items.cpp @@ -81,7 +81,7 @@ namespace hex::plugin::windows { if (ImGui::HasSecondPassed()) { memInfo.dwLength = sizeof(MEMORYSTATUSEX); GlobalMemoryStatusEx(&memInfo); - GetProcessMemoryInfo(GetCurrentProcess(), reinterpret_cast(&pmc), sizeof(pmc)); + GetProcessMemoryInfo(GetCurrentProcess(), reinterpret_cast(&pmc), sizeof(pmc)); } auto totalMem = memInfo.ullTotalPhys; @@ -89,7 +89,6 @@ namespace hex::plugin::windows { ImGui::TextFormatted(ICON_FA_MICROCHIP " {0} / {1}", hex::toByteString(usedMem), hex::toByteString(totalMem)); }); - } } \ No newline at end of file diff --git a/plugins/windows/source/plugin_windows.cpp b/plugins/windows/source/plugin_windows.cpp index 846e56acc..d78d9dc28 100644 --- a/plugins/windows/source/plugin_windows.cpp +++ b/plugins/windows/source/plugin_windows.cpp @@ -23,5 +23,3 @@ IMHEX_PLUGIN_SETUP("Windows", "WerWolv", "Windows-only features") { addFooterItems(); registerSettings(); } - - diff --git a/plugins/windows/source/views/view_tty_console.cpp b/plugins/windows/source/views/view_tty_console.cpp index 996748a79..514668990 100644 --- a/plugins/windows/source/views/view_tty_console.cpp +++ b/plugins/windows/source/views/view_tty_console.cpp @@ -14,7 +14,6 @@ namespace hex::plugin::windows { } ViewTTYConsole::~ViewTTYConsole() { - } void ViewTTYConsole::drawContent() { @@ -28,36 +27,51 @@ namespace hex::plugin::windows { ImGui::PushItemFlag(ImGuiItemFlags_Disabled, connected); ImGui::PushStyleVar(ImGuiStyleVar_Alpha, connected ? 0.5F : 1.0F); - ImGui::Combo("hex.windows.view.tty_console.port"_lang, &this->m_selectedPort, [](void* data, int idx, const char** out_text) -> bool { - auto &ports = *static_cast>*>(data); + ImGui::Combo( + "hex.windows.view.tty_console.port"_lang, &this->m_selectedPort, [](void *data, int idx, const char **out_text) -> bool { + auto &ports = *static_cast> *>(data); - *out_text = ports[idx].first.c_str(); - return true; - }, &this->m_comPorts, this->m_comPorts.size()); + *out_text = ports[idx].first.c_str(); + return true; + }, + &this->m_comPorts, + this->m_comPorts.size()); ImGui::SameLine(); if (ImGui::Button("hex.windows.view.tty_console.reload"_lang)) this->m_comPorts = getAvailablePorts(); - ImGui::Combo("hex.windows.view.tty_console.baud"_lang, &this->m_selectedBaudRate, [](void* data, int idx, const char** out_text) -> bool { - *out_text = ViewTTYConsole::BaudRates[idx]; - return true; - }, nullptr, ViewTTYConsole::BaudRates.size()); + ImGui::Combo( + "hex.windows.view.tty_console.baud"_lang, &this->m_selectedBaudRate, [](void *data, int idx, const char **out_text) -> bool { + *out_text = ViewTTYConsole::BaudRates[idx]; + return true; + }, + nullptr, + ViewTTYConsole::BaudRates.size()); - ImGui::Combo("hex.windows.view.tty_console.num_bits"_lang, &this->m_selectedNumBits, [](void* data, int idx, const char** out_text) -> bool { - *out_text = ViewTTYConsole::NumBits[idx]; - return true; - }, nullptr, ViewTTYConsole::NumBits.size()); + ImGui::Combo( + "hex.windows.view.tty_console.num_bits"_lang, &this->m_selectedNumBits, [](void *data, int idx, const char **out_text) -> bool { + *out_text = ViewTTYConsole::NumBits[idx]; + return true; + }, + nullptr, + ViewTTYConsole::NumBits.size()); - ImGui::Combo("hex.windows.view.tty_console.stop_bits"_lang, &this->m_selectedStopBits, [](void* data, int idx, const char** out_text) -> bool { - *out_text = ViewTTYConsole::StopBits[idx]; - return true; - }, nullptr, ViewTTYConsole::StopBits.size()); + ImGui::Combo( + "hex.windows.view.tty_console.stop_bits"_lang, &this->m_selectedStopBits, [](void *data, int idx, const char **out_text) -> bool { + *out_text = ViewTTYConsole::StopBits[idx]; + return true; + }, + nullptr, + ViewTTYConsole::StopBits.size()); - ImGui::Combo("hex.windows.view.tty_console.parity_bits"_lang, &this->m_selectedParityBits, [](void* data, int idx, const char** out_text) -> bool { - *out_text = ViewTTYConsole::ParityBits[idx]; - return true; - }, nullptr, ViewTTYConsole::ParityBits.size()); + ImGui::Combo( + "hex.windows.view.tty_console.parity_bits"_lang, &this->m_selectedParityBits, [](void *data, int idx, const char **out_text) -> bool { + *out_text = ViewTTYConsole::ParityBits[idx]; + return true; + }, + nullptr, + ViewTTYConsole::ParityBits.size()); ImGui::Checkbox("hex.windows.view.tty_console.cts"_lang, &this->m_hasCTSFlowControl); @@ -115,7 +129,6 @@ namespace hex::plugin::windows { } } ImGui::PopStyleVar(); - } ImGui::EndChild(); @@ -152,7 +165,6 @@ namespace hex::plugin::windows { ImGui::EndPopup(); } - } ImGui::End(); } @@ -173,24 +185,24 @@ namespace hex::plugin::windows { } bool ViewTTYConsole::connect() { - if(this->m_comPorts.size() == 0 || this->m_selectedPort >= this->m_comPorts.size()) { + if (this->m_comPorts.size() == 0 || this->m_selectedPort >= this->m_comPorts.size()) { View::showErrorPopup("hex.windows.view.tty_console.no_available_port"_lang); - return true; // If false, connect_error error popup will override this error popup + return true; // If false, connect_error error popup will override this error popup } this->m_portHandle = ::CreateFile(("\\\\.\\" + this->m_comPorts[this->m_selectedPort].first).c_str(), - GENERIC_READ | GENERIC_WRITE, - 0, - nullptr, - OPEN_EXISTING, - FILE_FLAG_OVERLAPPED, - nullptr); + GENERIC_READ | GENERIC_WRITE, + 0, + nullptr, + OPEN_EXISTING, + FILE_FLAG_OVERLAPPED, + nullptr); if (this->m_portHandle == INVALID_HANDLE_VALUE) return false; auto closeHandle = SCOPE_GUARD { CloseHandle(this->m_portHandle); }; - if(!::SetupComm(this->m_portHandle, 10000, 10000)) + if (!::SetupComm(this->m_portHandle, 10000, 10000)) return false; DCB serialParams; @@ -202,7 +214,7 @@ namespace hex::plugin::windows { serialParams.BaudRate = std::stoi(ViewTTYConsole::BaudRates[this->m_selectedBaudRate]); serialParams.ByteSize = std::stoi(ViewTTYConsole::NumBits[this->m_selectedNumBits]); serialParams.StopBits = this->m_selectedStopBits; - serialParams.Parity = this->m_selectedParityBits; + serialParams.Parity = this->m_selectedParityBits; serialParams.fOutxCtsFlow = this->m_hasCTSFlowControl; if (!::SetCommState(this->m_portHandle, &serialParams)) @@ -245,27 +257,28 @@ namespace hex::plugin::windows { }; while (!token.stop_requested()) { - DWORD bytesRead = 0; + DWORD bytesRead = 0; - char byte = 0; - if (!waitingOnRead) { - if (::ReadFile(this->m_portHandle, &byte, sizeof(char), &bytesRead, &overlapped)) { - addByte(byte); - } else if (::GetLastError() == ERROR_IO_PENDING) { - waitingOnRead = true; - } - } else { - byte = 0; - auto res = ::WaitForSingleObject(overlapped.hEvent, 500); - switch (res) { - case WAIT_OBJECT_0: - if (::GetOverlappedResult(this->m_portHandle, &overlapped, &bytesRead, false)) { - addByte(byte); - waitingOnRead = false; - } - default: break; - } - } + char byte = 0; + if (!waitingOnRead) { + if (::ReadFile(this->m_portHandle, &byte, sizeof(char), &bytesRead, &overlapped)) { + addByte(byte); + } else if (::GetLastError() == ERROR_IO_PENDING) { + waitingOnRead = true; + } + } else { + byte = 0; + auto res = ::WaitForSingleObject(overlapped.hEvent, 500); + switch (res) { + case WAIT_OBJECT_0: + if (::GetOverlappedResult(this->m_portHandle, &overlapped, &bytesRead, false)) { + addByte(byte); + waitingOnRead = false; + } + default: + break; + } + } } }); @@ -287,7 +300,7 @@ namespace hex::plugin::windows { if (this->m_transmitting) return; - auto transmitThread = std::thread([&, this]{ + auto transmitThread = std::thread([&, this] { OVERLAPPED overlapped = { 0 }; overlapped.hEvent = ::CreateEvent(nullptr, true, false, nullptr); diff --git a/tests/algorithms/include/test_provider.hpp b/tests/algorithms/include/test_provider.hpp index c2510e631..8f3afc454 100644 --- a/tests/algorithms/include/test_provider.hpp +++ b/tests/algorithms/include/test_provider.hpp @@ -9,7 +9,7 @@ namespace hex::test { class TestProvider : public prv::Provider { public: - TestProvider(std::vector* data) : Provider(){ + TestProvider(std::vector *data) : Provider() { this->setData(data); } ~TestProvider() override = default; @@ -20,7 +20,7 @@ namespace hex::test { [[nodiscard]] bool isResizable() const override { return false; } [[nodiscard]] bool isSavable() const override { return false; } - void setData(std::vector* data) { + void setData(std::vector *data) { this->m_data = data; } @@ -29,7 +29,7 @@ namespace hex::test { } [[nodiscard]] std::vector> getDataInformation() const override { - return { }; + return {}; } void readRaw(u64 offset, void *buffer, size_t size) override { @@ -52,7 +52,7 @@ namespace hex::test { void close() override { } private: - std::vector* m_data; + std::vector *m_data; }; } diff --git a/tests/algorithms/include/tests.hpp b/tests/algorithms/include/tests.hpp index c87ad821e..1315d77d4 100644 --- a/tests/algorithms/include/tests.hpp +++ b/tests/algorithms/include/tests.hpp @@ -10,17 +10,19 @@ #include #define TEST_SEQUENCE(...) static auto ANONYMOUS_VARIABLE(TEST_SEQUENCE) = ::hex::test::TestSequenceExecutor(__VA_ARGS__) + []() -> int -#define TEST_FAIL() return EXIT_FAILURE -#define TEST_SUCCESS() return EXIT_SUCCESS -#define FAILING true -#define TEST_ASSERT(x, ...) \ - do { \ - auto ret = (x); \ - if (!ret) { \ +#define TEST_FAIL() return EXIT_FAILURE +#define TEST_SUCCESS() return EXIT_SUCCESS +#define FAILING true +#define TEST_ASSERT(x, ...) \ + do { \ + auto ret = (x); \ + if (!ret) { \ hex::log::error("Test assert '" #x "' failed {} at {}:{}", \ - hex::format("" __VA_ARGS__), __FILE__, __LINE__); \ - return EXIT_FAILURE; \ - } \ + hex::format("" __VA_ARGS__), \ + __FILE__, \ + __LINE__); \ + return EXIT_FAILURE; \ + } \ } while (0) namespace hex::test { @@ -33,14 +35,17 @@ namespace hex::test { class Tests { public: static auto addTest(const std::string &name, const std::function &func, bool shouldFail) noexcept { - s_tests.insert({ name, { func, shouldFail } }); + s_tests.insert({ + name, {func, shouldFail} + }); return 0; } - static auto& get()noexcept { + static auto &get() noexcept { return s_tests; } + private: static inline std::map s_tests; }; @@ -48,25 +53,22 @@ namespace hex::test { template class TestSequence { public: - TestSequence(const std::string& name, F func, bool shouldFail) noexcept { + TestSequence(const std::string &name, F func, bool shouldFail) noexcept { Tests::addTest(name, func, shouldFail); } - TestSequence& operator=(TestSequence &&) = delete; + TestSequence &operator=(TestSequence &&) = delete; }; struct TestSequenceExecutor { explicit TestSequenceExecutor(std::string name, bool shouldFail = false) noexcept : m_name(std::move(name)), m_shouldFail(shouldFail) { - } - [[nodiscard]] - const auto& getName() const noexcept { + [[nodiscard]] const auto &getName() const noexcept { return this->m_name; } - [[nodiscard]] - bool shouldFail() const noexcept { + [[nodiscard]] bool shouldFail() const noexcept { return this->m_shouldFail; } @@ -76,10 +78,9 @@ namespace hex::test { }; - template - TestSequence operator+(TestSequenceExecutor executor, F&& f) noexcept { + template + TestSequence operator+(TestSequenceExecutor executor, F &&f) noexcept { return TestSequence(executor.getName(), std::forward(f), executor.shouldFail()); } } - diff --git a/tests/algorithms/source/common.cpp b/tests/algorithms/source/common.cpp index 378946c38..c799b1ae0 100644 --- a/tests/algorithms/source/common.cpp +++ b/tests/algorithms/source/common.cpp @@ -14,30 +14,30 @@ TEST_SEQUENCE("TestFailing", FAILING) { }; TEST_SEQUENCE("TestProvider_read") { - std::vector data{0xde, 0xad, 0xbe, 0xef, 0x42, 0x2a, 0x00, 0xff}; + std::vector data { 0xde, 0xad, 0xbe, 0xef, 0x42, 0x2a, 0x00, 0xff }; hex::test::TestProvider provider(&data); - hex::prv::Provider* provider2 = &provider; + hex::prv::Provider *provider2 = &provider; u8 buff[1024]; std::fill(std::begin(buff), std::end(buff), 22); provider2->read(0, buff + 1, 4); - TEST_ASSERT(buff[0] == 22); // should be unchanged + TEST_ASSERT(buff[0] == 22); // should be unchanged TEST_ASSERT(buff[1] == 0xde); TEST_ASSERT(buff[2] == 0xad); TEST_ASSERT(buff[3] == 0xbe); TEST_ASSERT(buff[4] == 0xef); - TEST_ASSERT(buff[5] == 22); // should be unchanged + TEST_ASSERT(buff[5] == 22); // should be unchanged std::fill(std::begin(buff), std::end(buff), 22); provider2->read(6, buff, 2); TEST_ASSERT(buff[0] == 0x00); TEST_ASSERT(buff[1] == 0xff); - TEST_ASSERT(buff[2] == 22); // should be unchanged + TEST_ASSERT(buff[2] == 22); // should be unchanged std::fill(std::begin(buff), std::end(buff), 22); provider2->read(7, buff, 2); - TEST_ASSERT(std::count(std::begin(buff), std::end(buff), 22) == std::size(buff)); // buff should be unchanged + TEST_ASSERT(std::count(std::begin(buff), std::end(buff), 22) == std::size(buff)); // buff should be unchanged TEST_SUCCESS(); }; @@ -45,9 +45,9 @@ TEST_SEQUENCE("TestProvider_read") { TEST_SEQUENCE("TestProvider_write") { std::vector buff(8); hex::test::TestProvider provider(&buff); - hex::prv::Provider* provider2 = &provider; + hex::prv::Provider *provider2 = &provider; - u8 data[1024] = {0xde, 0xad, 0xbe, 0xef, 0x42, 0x2a, 0x00, 0xff}; + u8 data[1024] = { 0xde, 0xad, 0xbe, 0xef, 0x42, 0x2a, 0x00, 0xff }; std::fill(std::begin(buff), std::end(buff), 22); provider2->write(1, data, 4); @@ -55,31 +55,31 @@ TEST_SEQUENCE("TestProvider_write") { hex::log::error("asd {:#x}", buff[0]); hex::log::error("asd {:#x}", buff[1]); hex::log::error("asd {:#x}", buff[2]); - TEST_ASSERT(buff[0] == 22); // should be unchanged + TEST_ASSERT(buff[0] == 22); // should be unchanged TEST_ASSERT(buff[1] == 0xde); TEST_ASSERT(buff[2] == 0xad); TEST_ASSERT(buff[3] == 0xbe); TEST_ASSERT(buff[4] == 0xef); - TEST_ASSERT(buff[5] == 22); // should be unchanged + TEST_ASSERT(buff[5] == 22); // should be unchanged std::fill(std::begin(buff), std::end(buff), 22); provider2->write(0, data + 6, 2); provider2->applyPatches(); TEST_ASSERT(buff[0] == 0x00); TEST_ASSERT(buff[1] == 0xff); - TEST_ASSERT(buff[2] == 22); // should be unchanged + TEST_ASSERT(buff[2] == 22); // should be unchanged std::fill(std::begin(buff), std::end(buff), 22); provider2->write(6, data, 2); provider2->applyPatches(); - TEST_ASSERT(buff[5] == 22); // should be unchanged + TEST_ASSERT(buff[5] == 22); // should be unchanged TEST_ASSERT(buff[6] == 0xde); TEST_ASSERT(buff[7] == 0xad); std::fill(std::begin(buff), std::end(buff), 22); provider2->write(7, data, 2); provider2->applyPatches(); - TEST_ASSERT(std::count(std::begin(buff), std::end(buff), 22) == std::size(buff)); // buff should be unchanged + TEST_ASSERT(std::count(std::begin(buff), std::end(buff), 22) == std::size(buff)); // buff should be unchanged TEST_SUCCESS(); }; diff --git a/tests/algorithms/source/crypto.cpp b/tests/algorithms/source/crypto.cpp index 23c18cae1..4b0658096 100644 --- a/tests/algorithms/source/crypto.cpp +++ b/tests/algorithms/source/crypto.cpp @@ -17,15 +17,15 @@ struct EncodeChek { TEST_SEQUENCE("EncodeDecode16") { std::array golden_samples = { - // source: created by hand - EncodeChek{ { }, "" }, - EncodeChek{ { 0x2a }, "2A" }, - EncodeChek{ { 0x00, 0x2a }, "002A" }, - EncodeChek{ { 0x2a, 0x00 }, "2A00" }, - EncodeChek{ { 0xde, 0xad, 0xbe, 0xef, 0x42, 0x2a, 0x00, 0xff}, "DEADBEEF422A00FF" }, + // source: created by hand + EncodeChek {{}, "" }, + EncodeChek { { 0x2a }, "2A" }, + EncodeChek { { 0x00, 0x2a }, "002A" }, + EncodeChek { { 0x2a, 0x00 }, "2A00" }, + EncodeChek { { 0xde, 0xad, 0xbe, 0xef, 0x42, 0x2a, 0x00, 0xff }, "DEADBEEF422A00FF"}, }; - for(auto& i: golden_samples) { + for (auto &i : golden_samples) { std::string string; TEST_ASSERT((string = hex::crypt::encode16(i.vec)) == i.string, "string: '{}' i.string: '{}' from: {}", string, i.string, i.vec); @@ -38,9 +38,9 @@ TEST_SEQUENCE("EncodeDecode16") { std::uniform_int_distribution<> dataLen(0, 1024); std::uniform_int_distribution data; - for(int i = 0; i < 1000; i++) { + for (int i = 0; i < 1000; i++) { std::vector original(dataLen(gen)); - std::generate(std::begin(original), std::end(original), [&](){ return data(gen); }); + std::generate(std::begin(original), std::end(original), [&]() { return data(gen); }); auto encoded = hex::crypt::encode16(original); auto decoded = hex::crypt::decode16(encoded); @@ -56,7 +56,7 @@ TEST_SEQUENCE("EncodeDecode16") { }; std::string vectorToString(std::vector in) { - return std::string(reinterpret_cast(in.data()), in.size()); + return std::string(reinterpret_cast(in.data()), in.size()); } std::vector stringToVector(std::string in) { @@ -66,16 +66,16 @@ std::vector stringToVector(std::string in) { TEST_SEQUENCE("EncodeDecode64") { std::array golden_samples = { - // source: linux command base64 (from GNU coreutils) - EncodeChek{ { }, "" }, - EncodeChek{ { 0x2a }, "Kg==" }, - EncodeChek{ { 0x00, 0x2a }, "ACo=" }, - EncodeChek{ { 0x2a, 0x00 }, "KgA=" }, - EncodeChek{ { 0x42, 0xff, 0x55 }, "Qv9V" }, - EncodeChek{ { 0xde, 0xad, 0xbe, 0xef, 0x42, 0x2a, 0x00, 0xff}, "3q2+70IqAP8=" }, + // source: linux command base64 (from GNU coreutils) + EncodeChek {{}, "" }, + EncodeChek { { 0x2a }, "Kg==" }, + EncodeChek { { 0x00, 0x2a }, "ACo=" }, + EncodeChek { { 0x2a, 0x00 }, "KgA=" }, + EncodeChek { { 0x42, 0xff, 0x55 }, "Qv9V" }, + EncodeChek { { 0xde, 0xad, 0xbe, 0xef, 0x42, 0x2a, 0x00, 0xff }, "3q2+70IqAP8="}, }; - for(auto& i: golden_samples) { + for (auto &i : golden_samples) { std::string string; TEST_ASSERT((string = vectorToString(hex::crypt::encode64(i.vec))) == i.string, "string: '{}' i.string: '{}' from: {}", string, i.string, i.vec); @@ -88,9 +88,9 @@ TEST_SEQUENCE("EncodeDecode64") { std::uniform_int_distribution<> dataLen(0, 1024); std::uniform_int_distribution data; - for(int i = 0; i < 1000; i++) { + for (int i = 0; i < 1000; i++) { std::vector original(dataLen(gen)); - std::generate(std::begin(original), std::end(original), [&](){ return data(gen); }); + std::generate(std::begin(original), std::end(original), [&]() { return data(gen); }); auto encoded = vectorToString(hex::crypt::encode64(original)); auto decoded = hex::crypt::decode64(stringToVector(encoded)); @@ -114,34 +114,34 @@ struct CrcCheck { std::vector data; }; -template Func, typename Range> +template Func, typename Range> int checkCrcAgainstGondenSamples(Func func, Range golden_samples) { - for(auto& i: golden_samples) { + for (auto &i : golden_samples) { hex::test::TestProvider provider(&i.data); - hex::prv::Provider* provider2 = &provider; + hex::prv::Provider *provider2 = &provider; auto crc = func(provider2, 0, i.data.size(), i.poly, i.init, i.xorOut, i.refIn, i.refOut); TEST_ASSERT(crc == i.result, "name: {} got: {:#x} expected: {:#x}", i.name, crc, i.result); } TEST_SUCCESS(); } -template Func> +template Func> int checkCrcAgainstRandomData(Func func, int width) { // crc( message + crc(message) ) should be 0 std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> distribLen(0, 1024); - std::uniform_int_distribution distribPoly(0, (0b10ull << (width-1)) - 1); + std::uniform_int_distribution distribPoly(0, (0b10ull << (width - 1)) - 1); std::uniform_int_distribution distribData; - for(int i = 0; i < 500; i++) { - CrcCheck c{"", width, distribPoly(gen), distribPoly(gen), 0, false, false, 0, {}}; + for (int i = 0; i < 500; i++) { + CrcCheck c { "", width, distribPoly(gen), distribPoly(gen), 0, false, false, 0, {} }; c.data.resize(distribLen(gen)); - std::generate(std::begin(c.data), std::end(c.data), [&](){ return distribData(gen); }); + std::generate(std::begin(c.data), std::end(c.data), [&]() { return distribData(gen); }); hex::test::TestProvider testprovider(&c.data); - hex::prv::Provider* provider = &testprovider; + hex::prv::Provider *provider = &testprovider; u32 crc1 = func(provider, 0, c.data.size(), c.poly, c.init, c.xorOut, c.refIn, c.refOut); std::vector data2 = c.data; @@ -150,16 +150,24 @@ int checkCrcAgainstRandomData(Func func, int width) { data2.push_back((crc1 >> 16) & 0xff); } if (width >= 16) - data2.push_back((crc1 >> 8) & 0xff); - data2.push_back((crc1 >> 0) & 0xff); + data2.push_back((crc1 >> 8) & 0xff); + data2.push_back((crc1 >> 0) & 0xff); hex::test::TestProvider testprovider2(&data2); - hex::prv::Provider* provider2 = &testprovider2; + hex::prv::Provider *provider2 = &testprovider2; u32 crc2 = func(provider2, 0, data2.size(), c.poly, c.init, c.xorOut, c.refIn, c.refOut); TEST_ASSERT(crc2 == 0, "got wrong crc2: {:#x}, crc1: {:#x}, " "width: {:2d}, poly: {:#018x}, init: {:#018x}, xorout: {:#018x}, refin: {:5}, refout: {:5}, data: {}", - crc2, crc1, c.width, c.poly, c.init, c.xorOut, c.refIn, c.refOut, data2); + crc2, + crc1, + c.width, + c.poly, + c.init, + c.xorOut, + c.refIn, + c.refOut, + data2); } TEST_SUCCESS(); @@ -167,27 +175,27 @@ int checkCrcAgainstRandomData(Func func, int width) { TEST_SEQUENCE("CRC32") { std::array golden_samples = { - // source: A Painless Guide to CRC Error Detection Algorithms [https://zlib.net/crc_v3.txt] - CrcCheck {"CRC-32-CRC32-check", 32, 0x4C11DB7, 0xFFFFFFFF, 0xFFFFFFFF, true, true , 0xCBF43926, {0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39}}, + // source: A Painless Guide to CRC Error Detection Algorithms [https://zlib.net/crc_v3.txt] + CrcCheck {"CRC-32-CRC32-check", 32, 0x4C11DB7, 0xFFFFFFFF, 0xFFFFFFFF, true, true, 0xCBF43926, { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39 } }, - // source: Sunshine's Homepage - Online CRC Calculator Javascript [http://www.sunshine2k.de/coding/javascript/crc/crc_js.html] - CrcCheck {"CRC-32-1-check", 32, 0x4C11DB7, 0xFFFFFFFF, 0xFFFFFFFF, true, false, 0x649C2FD3, {0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39}}, - CrcCheck {"CRC-32-2-check", 32, 0x4C11DB7, 0xFFFFFFFF, 0xFFFFFFFF, false, true, 0x1898913F, {0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39}}, - CrcCheck {"CRC-32-3-check", 32, 0x4C11DB7, 0xFFFFFFFF, 0xFFFFFFFF, false, false, 0xFC891918, {0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39}}, - CrcCheck {"CRC-32-4-check", 32, 0x4C11DB7, 0x55422a00, 0xaa004422, false, false, 0x41A1D8EE, {0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39}}, - CrcCheck {"CRC-32-5-check", 32, 0x4C11DB7, 0x55422a00, 0xaa004422, false, false, 0xFF426E22, { }}, + // source: Sunshine's Homepage - Online CRC Calculator Javascript [http://www.sunshine2k.de/coding/javascript/crc/crc_js.html] + CrcCheck { "CRC-32-1-check", 32, 0x4C11DB7, 0xFFFFFFFF, 0xFFFFFFFF, true, false, 0x649C2FD3, { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39 } }, + CrcCheck { "CRC-32-2-check", 32, 0x4C11DB7, 0xFFFFFFFF, 0xFFFFFFFF, false, true, 0x1898913F, { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39 } }, + CrcCheck { "CRC-32-3-check", 32, 0x4C11DB7, 0xFFFFFFFF, 0xFFFFFFFF, false, false, 0xFC891918, { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39 } }, + CrcCheck { "CRC-32-4-check", 32, 0x4C11DB7, 0x55422a00, 0xaa004422, false, false, 0x41A1D8EE, { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39 } }, + CrcCheck { "CRC-32-5-check", 32, 0x4C11DB7, 0x55422a00, 0xaa004422, false, false, 0xFF426E22, {} }, - // source: generated by Boost CRC from random data and random parameters - CrcCheck {"CRC-32-RANDOM-170" , 32, 0x000000005c0dd7fd, 0x000000001c8be2e1, 0x00000000efdedd60, false, true , 0x000000004e9b67a8, {181, 235, 196, 140, 43, 8, 101, 39, 17, 128, 187, 117, 118, 75, 41, 240, 228, 60, 93, 101, 228, 235, 36, 117, 208, 54, 218, 57, 24, 84, 54, 173, 13, 66, 42, 232, 206, 49, 210, 165, 146, 145, 234, 88, 76, 130, 154, 231, 247, 66, 73, 150, 163, 104, 42, 77, 214, 16, 53, 120, 210, 74, 215, 54, 88, 171, 137, 133, 26, 29, 134, 0, 103, 240, 146, 220, 169, 64, 155, 162, 23, 73, 73, 87, 224, 106, 121, 58, 66, 146, 158, 101, 196, 62, 153, 143, 86, 87, 147, 4, 36, 248, 41, 6, 213, 233, 27, 24, 42, 207, 24, 167, 72, 216, 24, 27, 59, 205, 184, 0, 101, 102, 34, 32, 248, 213, 53, 244, 83, 60, 8, 249, 115, 214, 144, 109, 245, 119, 137, 225, 156, 247, 250, 230, 147, 201, 1, 14, 111, 148, 214, 90, 80, 156, 31, 85, 186, 165, 218, 127, 66, 9, 191, 215, 17, 253, 32, 162, 28, 223, 61, 7, 115, 177, 58}}, - CrcCheck {"CRC-32-RANDOM-171" , 32, 0x00000000380bb4f5, 0x00000000c6c652b3, 0x000000003a5ee7d1, false, false, 0x000000002f5a76b0, {59, 215, 138, 110, 177, 211, 25, 172, 77, 145, 155, 166, 99, 202, 132, 92, 179, 249, 223, 254, 103, 9, 16, 218, 42}}, - CrcCheck {"CRC-32-RANDOM-172" , 32, 0x000000000dc7ba53, 0x00000000acfa5319, 0x00000000ee250595, true , true , 0x00000000b3e56ef4, {218, 89, 16, 112, 197, 97, 69, 29, 33, 173, 8, 121, 78, 23, 131, 152, 82, 174, 94, 206, 33, 228, 35, 205, 83, 71, 219, 99, 13, 48, 105, 180, 187, 246, 101, 249, 91, 67, 207, 177, 61, 108, 144, 73, 209, 201, 166, 115, 2, 110, 70, 67, 25, 31, 0, 20, 83, 9, 152, 169, 125, 74, 246, 183, 186, 70, 199, 106, 38, 127, 230, 44, 43, 64, 119, 14, 97, 127, 127, 166, 98, 157, 71, 109, 3, 15, 197, 223}}, - CrcCheck {"CRC-32-RANDOM-173" , 32, 0x00000000fd5a3b2e, 0x00000000580018a2, 0x000000002dbfb987, true , true , 0x0000000040c086a9, {0, 90, 253, 254, 61, 67, 185, 88, 110, 58, 243, 86, 43, 183, 21, 161, 192, 81, 10, 83, 147, 21, 235, 250, 195, 201, 199, 36, 254, 107, 191, 212, 27, 30, 173, 247, 174, 219, 240, 39, 0, 72, 146, 155, 72, 250, 252, 51, 250, 195, 161, 241, 75, 244, 13, 85, 233, 204, 70, 89, 110, 193, 25, 199, 179, 92, 169, 179, 75, 124, 142, 31, 36, 167, 16, 166, 119, 148, 68, 74, 8, 5, 60, 164, 217, 168, 231, 99, 214, 171, 239, 23, 36, 219, 176, 111, 210, 96, 111, 57, 231, 160, 5, 119, 76, 19, 197, 197, 3, 11, 121, 140, 182, 150, 30, 90, 160, 30, 114, 114, 214, 57, 118, 70, 219, 201, 223, 143, 0, 126, 14, 223, 175, 212, 208, 135, 104, 173, 169, 189, 5, 228, 232, 170, 191, 137, 45, 98, 43, 153, 180, 186, 46, 53, 167, 166, 99, 154, 188, 234, 37, 137, 37, 132, 251, 122, 143, 230, 151, 227, 41, 111, 6, 168, 135, 0, 239, 141, 125, 5, 199, 48, 161, 53, 186, 91, 56, 41, 227, 49, 28, 132, 88, 2, 22, 33, 21, 155, 209, 82, 116, 17, 142, 55, 87, 156, 134, 165, 153, 38, 125, 40, 80, 229, 233, 28, 23, 197}}, - CrcCheck {"CRC-32-RANDOM-174" , 32, 0x000000006eae3222, 0x0000000097093735, 0x000000000460e363, false, false, 0x0000000096bf93cd, {98, 234, 52, 152, 123}}, - CrcCheck {"CRC-32-RANDOM-175" , 32, 0x000000002ac3bed5, 0x00000000c2a0964a, 0x0000000019ee4b3b, true , true , 0x00000000b7f1e6b7, {108, 151, 223, 46, 204, 105, 253, 2, 101, 184, 48, 186, 204, 86, 230, 246, 222, 137, 136, 207, 197, 195, 33, 165, 239, 55, 92, 9, 54, 29, 189, 126, 123, 106, 19, 1, 176, 52, 87, 178, 246, 110, 75, 220, 204, 8, 11, 22}}, - CrcCheck {"CRC-32-RANDOM-176" , 32, 0x000000006dc26b9c, 0x00000000096e9400, 0x000000005e4839bf, false, true , 0x0000000063d4b648, {88, 185, 144, 84, 86, 77, 217, 85, 61, 80, 21, 84, 81, 120, 14, 247, 106, 56, 193, 3, 185, 118, 131, 196, 51, 249, 79, 252, 145, 43, 243, 120, 56, 184, 242, 226, 80, 73, 102, 179, 20, 7, 208, 70, 242, 20, 208, 180, 21, 128, 175, 195, 248, 174, 45, 187, 142, 76, 2, 6, 58, 56, 155, 28, 37, 35, 134, 50, 34, 174, 204, 170, 163, 94, 68, 161, 124, 23, 224, 38, 137, 255, 92, 228, 77, 53, 42, 145, 147, 12, 246, 23, 205, 143, 241, 201, 227, 79, 215, 65, 55, 247, 219, 209, 30, 19, 11, 211, 145, 150, 45, 200, 90, 69, 55, 234, 7, 11, 6, 113, 158, 229, 56, 131, 220, 14, 236, 127, 249, 191, 182, 108, 23, 197, 148, 247, 115, 85, 0, 86, 63, 210, 153, 112, 235, 146, 53, 249, 216, 42, 169, 18, 54, 245, 60, 232, 224, 9, 187, 125, 27, 180, 171, 138, 138, 13, 45, 125, 220, 158, 164, 21, 109, 23, 8, 2, 41, 178, 245, 226, 211, 202, 134, 4, 133, 192, 125}}, - CrcCheck {"CRC-32-RANDOM-177" , 32, 0x00000000de2c5518, 0x000000003e12e6ec, 0x00000000474d1134, true , false, 0x00000000623e70f4, {239, 114, 198, 23, 88, 133, 118, 9, 184, 162, 78, 142, 128, 165, 196, 6, 148, 0, 56, 249, 4, 126, 152, 67, 17, 48, 153, 151, 46, 183, 92, 242, 155, 233, 216, 166, 22, 107, 139, 93, 3, 239, 154, 20, 15, 69, 41, 126, 65, 76, 229, 133, 161, 181, 201, 134, 213, 158, 174, 17, 32, 45, 223, 74, 56, 194, 228, 37, 71, 128, 160, 202, 219, 173, 55, 223, 104, 90, 176, 152, 113, 160, 224, 36, 111, 170, 64, 28, 29, 239, 23, 135, 254, 240, 117, 147, 125, 138, 86, 206, 28, 48, 169, 107, 193, 186, 197, 219, 180, 83, 108, 250, 172, 21, 18, 121, 154, 77, 36, 48, 88, 167, 42, 3, 91, 172, 235, 166, 85, 93, 42, 254, 47, 37, 193, 104, 32, 171, 172, 225, 194, 80, 120, 61, 198, 108, 105, 21, 188, 51, 101, 49, 88, 97, 51, 168, 251, 4, 226, 114, 202, 53, 7, 171, 41, 72, 138, 161, 227, 182, 223, 92, 96, 196, 203, 255, 72, 190, 6, 106, 69, 172, 41, 131, 241, 34, 147, 155, 27, 67, 109, 39, 202, 82, 184, 160, 167, 163, 66, 222, 172, 65, 24, 46, 181, 217, 1, 249, 206, 171, 27, 87, 88, 40, 191, 153, 121, 206, 89, 48, 7, 86, 82, 68, 129, 224, 181, 108, 144, 1, 14, 204, 79, 183, 129, 116, 124, 175, 158, 98, 197}}, - CrcCheck {"CRC-32-RANDOM-178" , 32, 0x00000000983395ff, 0x00000000b8a8a4fe, 0x00000000c0996c7c, true , true , 0x0000000003def4ee, {81, 82, 118, 44, 112, 193, 97, 94, 233, 4, 105, 223, 158, 176, 91, 215, 162, 197, 79, 59, 191, 152, 87, 68, 79, 122, 35, 78, 180, 40, 151, 82, 199, 227}}, - CrcCheck {"CRC-32-RANDOM-179" , 32, 0x0000000096345585, 0x0000000098436ef2, 0x000000000373eba2, true , false, 0x000000001a7ca97a, {22, 29, 92, 40, 254, 225, 67, 92, 243, 28, 191, 168, 25, 228, 67, 240, 230, 20, 1, 165, 223, 154, 244, 100, 127, 254, 103, 233, 105, 139, 3, 232, 31, 57, 84, 99, 144, 1, 105, 240, 103, 118, 146, 128, 216, 43, 115, 59, 233, 56, 3, 9, 139, 64, 229, 52, 116, 210, 173, 55, 190, 126, 168, 10, 4, 72, 62, 134, 152, 151, 143, 153, 217, 50, 134, 15, 251, 158, 241, 253, 161, 36, 44, 60, 75, 74, 253, 170, 39, 43, 255, 183, 194, 176, 95, 255, 21, 122, 83, 200, 201, 249, 175, 245, 166, 128, 54, 253, 234, 106, 122, 177, 169, 162, 71, 99, 135, 204, 72, 24, 22, 170, 97, 11, 5, 165, 88, 173, 43, 138, 143, 5, 68, 12, 178, 125, 66, 132, 28, 215, 49, 47, 146, 193, 0, 193, 65, 103, 53, 81, 58, 99, 38, 224, 34, 124, 44, 165, 95, 129, 192, 160, 110, 76, 131, 157, 49, 76, 100, 83, 220, 101, 253, 108, 11, 21, 88, 178, 114, 163, 58, 200, 57, 232, 252, 216, 217, 154, 122, 251, 200, 216, 238, 165, 94, 97, 76, 112, 39, 243, 77, 81, 189, 10, 48, 10, 65, 180, 252, 15, 132, 86, 68, 199, 185, 4, 19, 19, 61, 249, 133, 80, 45, 206, 49, 16, 107, 176}}, + // source: generated by Boost CRC from random data and random parameters + CrcCheck { "CRC-32-RANDOM-170", 32, 0x000000005c0dd7fd, 0x000000001c8be2e1, 0x00000000efdedd60, false, true, 0x000000004e9b67a8, { 181, 235, 196, 140, 43, 8, 101, 39, 17, 128, 187, 117, 118, 75, 41, 240, 228, 60, 93, 101, 228, 235, 36, 117, 208, 54, 218, 57, 24, 84, 54, 173, 13, 66, 42, 232, 206, 49, 210, 165, 146, 145, 234, 88, 76, 130, 154, 231, 247, 66, 73, 150, 163, 104, 42, 77, 214, 16, 53, 120, 210, 74, 215, 54, 88, 171, 137, 133, 26, 29, 134, 0, 103, 240, 146, 220, 169, 64, 155, 162, 23, 73, 73, 87, 224, 106, 121, 58, 66, 146, 158, 101, 196, 62, 153, 143, 86, 87, 147, 4, 36, 248, 41, 6, 213, 233, 27, 24, 42, 207, 24, 167, 72, 216, 24, 27, 59, 205, 184, 0, 101, 102, 34, 32, 248, 213, 53, 244, 83, 60, 8, 249, 115, 214, 144, 109, 245, 119, 137, 225, 156, 247, 250, 230, 147, 201, 1, 14, 111, 148, 214, 90, 80, 156, 31, 85, 186, 165, 218, 127, 66, 9, 191, 215, 17, 253, 32, 162, 28, 223, 61, 7, 115, 177, 58 } }, + CrcCheck { "CRC-32-RANDOM-171", 32, 0x00000000380bb4f5, 0x00000000c6c652b3, 0x000000003a5ee7d1, false, false, 0x000000002f5a76b0, { 59, 215, 138, 110, 177, 211, 25, 172, 77, 145, 155, 166, 99, 202, 132, 92, 179, 249, 223, 254, 103, 9, 16, 218, 42 } }, + CrcCheck { "CRC-32-RANDOM-172", 32, 0x000000000dc7ba53, 0x00000000acfa5319, 0x00000000ee250595, true, true, 0x00000000b3e56ef4, { 218, 89, 16, 112, 197, 97, 69, 29, 33, 173, 8, 121, 78, 23, 131, 152, 82, 174, 94, 206, 33, 228, 35, 205, 83, 71, 219, 99, 13, 48, 105, 180, 187, 246, 101, 249, 91, 67, 207, 177, 61, 108, 144, 73, 209, 201, 166, 115, 2, 110, 70, 67, 25, 31, 0, 20, 83, 9, 152, 169, 125, 74, 246, 183, 186, 70, 199, 106, 38, 127, 230, 44, 43, 64, 119, 14, 97, 127, 127, 166, 98, 157, 71, 109, 3, 15, 197, 223 } }, + CrcCheck { "CRC-32-RANDOM-173", 32, 0x00000000fd5a3b2e, 0x00000000580018a2, 0x000000002dbfb987, true, true, 0x0000000040c086a9, { 0, 90, 253, 254, 61, 67, 185, 88, 110, 58, 243, 86, 43, 183, 21, 161, 192, 81, 10, 83, 147, 21, 235, 250, 195, 201, 199, 36, 254, 107, 191, 212, 27, 30, 173, 247, 174, 219, 240, 39, 0, 72, 146, 155, 72, 250, 252, 51, 250, 195, 161, 241, 75, 244, 13, 85, 233, 204, 70, 89, 110, 193, 25, 199, 179, 92, 169, 179, 75, 124, 142, 31, 36, 167, 16, 166, 119, 148, 68, 74, 8, 5, 60, 164, 217, 168, 231, 99, 214, 171, 239, 23, 36, 219, 176, 111, 210, 96, 111, 57, 231, 160, 5, 119, 76, 19, 197, 197, 3, 11, 121, 140, 182, 150, 30, 90, 160, 30, 114, 114, 214, 57, 118, 70, 219, 201, 223, 143, 0, 126, 14, 223, 175, 212, 208, 135, 104, 173, 169, 189, 5, 228, 232, 170, 191, 137, 45, 98, 43, 153, 180, 186, 46, 53, 167, 166, 99, 154, 188, 234, 37, 137, 37, 132, 251, 122, 143, 230, 151, 227, 41, 111, 6, 168, 135, 0, 239, 141, 125, 5, 199, 48, 161, 53, 186, 91, 56, 41, 227, 49, 28, 132, 88, 2, 22, 33, 21, 155, 209, 82, 116, 17, 142, 55, 87, 156, 134, 165, 153, 38, 125, 40, 80, 229, 233, 28, 23, 197 } }, + CrcCheck { "CRC-32-RANDOM-174", 32, 0x000000006eae3222, 0x0000000097093735, 0x000000000460e363, false, false, 0x0000000096bf93cd, { 98, 234, 52, 152, 123 } }, + CrcCheck { "CRC-32-RANDOM-175", 32, 0x000000002ac3bed5, 0x00000000c2a0964a, 0x0000000019ee4b3b, true, true, 0x00000000b7f1e6b7, { 108, 151, 223, 46, 204, 105, 253, 2, 101, 184, 48, 186, 204, 86, 230, 246, 222, 137, 136, 207, 197, 195, 33, 165, 239, 55, 92, 9, 54, 29, 189, 126, 123, 106, 19, 1, 176, 52, 87, 178, 246, 110, 75, 220, 204, 8, 11, 22 } }, + CrcCheck { "CRC-32-RANDOM-176", 32, 0x000000006dc26b9c, 0x00000000096e9400, 0x000000005e4839bf, false, true, 0x0000000063d4b648, { 88, 185, 144, 84, 86, 77, 217, 85, 61, 80, 21, 84, 81, 120, 14, 247, 106, 56, 193, 3, 185, 118, 131, 196, 51, 249, 79, 252, 145, 43, 243, 120, 56, 184, 242, 226, 80, 73, 102, 179, 20, 7, 208, 70, 242, 20, 208, 180, 21, 128, 175, 195, 248, 174, 45, 187, 142, 76, 2, 6, 58, 56, 155, 28, 37, 35, 134, 50, 34, 174, 204, 170, 163, 94, 68, 161, 124, 23, 224, 38, 137, 255, 92, 228, 77, 53, 42, 145, 147, 12, 246, 23, 205, 143, 241, 201, 227, 79, 215, 65, 55, 247, 219, 209, 30, 19, 11, 211, 145, 150, 45, 200, 90, 69, 55, 234, 7, 11, 6, 113, 158, 229, 56, 131, 220, 14, 236, 127, 249, 191, 182, 108, 23, 197, 148, 247, 115, 85, 0, 86, 63, 210, 153, 112, 235, 146, 53, 249, 216, 42, 169, 18, 54, 245, 60, 232, 224, 9, 187, 125, 27, 180, 171, 138, 138, 13, 45, 125, 220, 158, 164, 21, 109, 23, 8, 2, 41, 178, 245, 226, 211, 202, 134, 4, 133, 192, 125 } }, + CrcCheck { "CRC-32-RANDOM-177", 32, 0x00000000de2c5518, 0x000000003e12e6ec, 0x00000000474d1134, true, false, 0x00000000623e70f4, { 239, 114, 198, 23, 88, 133, 118, 9, 184, 162, 78, 142, 128, 165, 196, 6, 148, 0, 56, 249, 4, 126, 152, 67, 17, 48, 153, 151, 46, 183, 92, 242, 155, 233, 216, 166, 22, 107, 139, 93, 3, 239, 154, 20, 15, 69, 41, 126, 65, 76, 229, 133, 161, 181, 201, 134, 213, 158, 174, 17, 32, 45, 223, 74, 56, 194, 228, 37, 71, 128, 160, 202, 219, 173, 55, 223, 104, 90, 176, 152, 113, 160, 224, 36, 111, 170, 64, 28, 29, 239, 23, 135, 254, 240, 117, 147, 125, 138, 86, 206, 28, 48, 169, 107, 193, 186, 197, 219, 180, 83, 108, 250, 172, 21, 18, 121, 154, 77, 36, 48, 88, 167, 42, 3, 91, 172, 235, 166, 85, 93, 42, 254, 47, 37, 193, 104, 32, 171, 172, 225, 194, 80, 120, 61, 198, 108, 105, 21, 188, 51, 101, 49, 88, 97, 51, 168, 251, 4, 226, 114, 202, 53, 7, 171, 41, 72, 138, 161, 227, 182, 223, 92, 96, 196, 203, 255, 72, 190, 6, 106, 69, 172, 41, 131, 241, 34, 147, 155, 27, 67, 109, 39, 202, 82, 184, 160, 167, 163, 66, 222, 172, 65, 24, 46, 181, 217, 1, 249, 206, 171, 27, 87, 88, 40, 191, 153, 121, 206, 89, 48, 7, 86, 82, 68, 129, 224, 181, 108, 144, 1, 14, 204, 79, 183, 129, 116, 124, 175, 158, 98, 197 }}, + CrcCheck { "CRC-32-RANDOM-178", 32, 0x00000000983395ff, 0x00000000b8a8a4fe, 0x00000000c0996c7c, true, true, 0x0000000003def4ee, { 81, 82, 118, 44, 112, 193, 97, 94, 233, 4, 105, 223, 158, 176, 91, 215, 162, 197, 79, 59, 191, 152, 87, 68, 79, 122, 35, 78, 180, 40, 151, 82, 199, 227 } }, + CrcCheck { "CRC-32-RANDOM-179", 32, 0x0000000096345585, 0x0000000098436ef2, 0x000000000373eba2, true, false, 0x000000001a7ca97a, { 22, 29, 92, 40, 254, 225, 67, 92, 243, 28, 191, 168, 25, 228, 67, 240, 230, 20, 1, 165, 223, 154, 244, 100, 127, 254, 103, 233, 105, 139, 3, 232, 31, 57, 84, 99, 144, 1, 105, 240, 103, 118, 146, 128, 216, 43, 115, 59, 233, 56, 3, 9, 139, 64, 229, 52, 116, 210, 173, 55, 190, 126, 168, 10, 4, 72, 62, 134, 152, 151, 143, 153, 217, 50, 134, 15, 251, 158, 241, 253, 161, 36, 44, 60, 75, 74, 253, 170, 39, 43, 255, 183, 194, 176, 95, 255, 21, 122, 83, 200, 201, 249, 175, 245, 166, 128, 54, 253, 234, 106, 122, 177, 169, 162, 71, 99, 135, 204, 72, 24, 22, 170, 97, 11, 5, 165, 88, 173, 43, 138, 143, 5, 68, 12, 178, 125, 66, 132, 28, 215, 49, 47, 146, 193, 0, 193, 65, 103, 53, 81, 58, 99, 38, 224, 34, 124, 44, 165, 95, 129, 192, 160, 110, 76, 131, 157, 49, 76, 100, 83, 220, 101, 253, 108, 11, 21, 88, 178, 114, 163, 58, 200, 57, 232, 252, 216, 217, 154, 122, 251, 200, 216, 238, 165, 94, 97, 76, 112, 39, 243, 77, 81, 189, 10, 48, 10, 65, 180, 252, 15, 132, 86, 68, 199, 185, 4, 19, 19, 61, 249, 133, 80, 45, 206, 49, 16, 107, 176 } }, }; TEST_ASSERT(!checkCrcAgainstGondenSamples(hex::crypt::crc32, golden_samples)); @@ -203,25 +211,25 @@ TEST_SEQUENCE("CRC32Random") { TEST_SEQUENCE("CRC16") { std::array golden_samples = { - // source: A Painless Guide to CRC Error Detection Algorithms [https://zlib.net/crc_v3.txt] - CrcCheck {"CRC-16-CRC16-check", 16, 0x8005, 0x0000, 0x0000, true , true , 0xBB3D, {0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39}}, + // source: A Painless Guide to CRC Error Detection Algorithms [https://zlib.net/crc_v3.txt] + CrcCheck {"CRC-16-CRC16-check", 16, 0x8005, 0x0000, 0x0000, true, true, 0xBB3D, { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39 } }, - // source: Sunshine's Homepage - Online CRC Calculator Javascript [http://www.sunshine2k.de/coding/javascript/crc/crc_js.html] - CrcCheck {"CRC-16-1-check", 16, 0x8005, 0x0000, 0x0000, true , false, 0xBCDD, {0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39}}, - CrcCheck {"CRC-16-2-check", 16, 0x8005, 0x0000, 0x0000, false, true , 0x177F, {0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39}}, - CrcCheck {"CRC-16-3-check", 16, 0x8005, 0x0000, 0x0000, false, false, 0xFEE8, {0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39}}, - CrcCheck {"CRC-16-3-check", 16, 0x8005, 0x5042, 0xfc2a, false, false, 0xDD50, {0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39}}, + // source: Sunshine's Homepage - Online CRC Calculator Javascript [http://www.sunshine2k.de/coding/javascript/crc/crc_js.html] + CrcCheck { "CRC-16-1-check", 16, 0x8005, 0x0000, 0x0000, true, false, 0xBCDD, { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39 } }, + CrcCheck { "CRC-16-2-check", 16, 0x8005, 0x0000, 0x0000, false, true, 0x177F, { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39 } }, + CrcCheck { "CRC-16-3-check", 16, 0x8005, 0x0000, 0x0000, false, false, 0xFEE8, { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39 } }, + CrcCheck { "CRC-16-3-check", 16, 0x8005, 0x5042, 0xfc2a, false, false, 0xDD50, { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39 } }, - // source: generated by Boost CRC from random data and random parameters - CrcCheck {"CRC-16-RANDOM-10" , 16, 0x000000000000afbb, 0x00000000000091ea, 0x0000000000000ea8, true , true , 0x0000000000000670, {239, 127, 45, 34, 24, 9, 68, 49, 206, 206, 71, 116, 233, 144, 237, 184, 241, 86, 244, 237, 163, 167, 42, 194, 69, 147, 236, 136, 245, 183, 254, 2, 67, 220, 111, 241, 168, 255, 36, 248, 147, 137, 75, 137, 201, 100, 215, 161, 36, 13, 54, 235, 34, 187, 75, 82, 227, 97, 240, 137, 173, 165, 246, 129, 30, 174, 42, 21, 185, 94, 43, 218, 126, 90, 197, 205, 15, 21, 115, 50, 103, 38, 178, 124, 27, 24, 208, 157, 41, 53, 204, 158, 198, 238, 133, 61, 164, 203, 159, 6, 94, 213, 225, 145, 61, 245, 86, 157, 126, 41, 130, 195, 130, 11, 48, 29, 193, 187, 127, 135, 83, 44, 232, 66, 169, 147, 106, 11, 118, 124, 189, 114, 131, 148, 106, 45, 250, 134, 11, 189, 179, 74, 92, 43, 8, 116, 18, 241, 53, 218, 160, 169, 65, 112, 161, 63, 208, 61, 223, 18, 254, 51, 87, 101, 180, 244, 149, 78, 135, 54, 222, 122, 244, 184, 44}}, - CrcCheck {"CRC-16-RANDOM-11" , 16, 0x0000000000001b6c, 0x0000000000005bce, 0x000000000000e29c, true , true , 0x000000000000dfa2, {92, 73, 175, 57, 17, 7, 61, 3, 7, 81, 172, 188, 91, 214, 51, 201, 52, 249, 51, 206, 210, 79, 156, 42, 36, 28, 235, 71, 83, 127, 30, 123, 200, 55, 127, 217, 218, 71, 203, 29, 223, 222, 198, 56, 138, 207, 196, 46, 195, 105, 28, 45, 5, 138, 168, 54, 239, 203, 1, 0, 105, 110, 21, 193, 207}}, - CrcCheck {"CRC-16-RANDOM-12" , 16, 0x000000000000477b, 0x000000000000afa4, 0x0000000000003d01, false, false, 0x0000000000000b96, {63, 84, 254, 94, 21, 194, 88, 199, 189, 117, 111, 234, 231, 51, 119, 117, 203, 239, 210, 109, 162, 58, 158, 239, 163, 18, 68, 233, 37, 120, 48, 205, 17, 188, 141, 44, 143, 147, 173, 105}}, - CrcCheck {"CRC-16-RANDOM-13" , 16, 0x0000000000004438, 0x0000000000008e25, 0x0000000000006c55, false, false, 0x0000000000004a6d, {179, 169, 67, 230, 228, 213, 173, 155, 152, 64, 85, 170, 20, 177, 38, 127, 169, 186, 44, 163, 153, 153, 11, 112, 63, 24, 127, 25, 135, 40, 214, 33, 88, 132, 14, 84, 82, 66, 216, 75, 55, 231, 101, 114, 68, 244, 56, 140, 100, 196, 226, 60, 0, 177, 187, 164, 237, 1, 199, 119, 249, 148, 102, 175, 32, 62, 232, 179, 30, 102, 85, 8, 188, 61, 28, 156, 74, 71, 11, 102, 51, 243, 120, 60, 146, 207, 116, 156, 219, 237, 157, 25, 0, 149, 7, 137, 248, 102, 157, 171, 60, 76, 117, 29, 34, 117, 148, 241, 142, 18, 251, 240, 37, 213, 171, 120, 85, 145, 50, 209, 130, 225, 28, 27, 170, 195, 148, 102}}, - CrcCheck {"CRC-16-RANDOM-14" , 16, 0x000000000000f461, 0x0000000000004d96, 0x0000000000003e1d, true , true , 0x0000000000009eef, {38, 252, 182, 80, 159, 97, 166, 150, 29, 9, 45, 216, 186, 165, 148, 128, 60, 170, 243, 69, 177, 203, 17, 191, 5, 60, 209, 41, 20, 42, 23, 147, 126, 209, 125, 157, 30, 45, 94, 157, 146, 7, 20, 234, 70, 23, 141, 87, 88, 93, 184, 169, 69, 88, 108, 253, 58, 157, 175, 88, 177, 154, 181, 127, 216, 82, 202, 16, 164, 227, 188, 243, 140, 84, 24, 213, 31, 130, 185, 234, 215, 248, 169, 233, 4, 208, 67, 102, 248, 13, 114, 162, 175, 187, 120, 228, 213, 93}}, - CrcCheck {"CRC-16-RANDOM-15" , 16, 0x000000000000bbf3, 0x000000000000e279, 0x000000000000a01c, false, false, 0x000000000000f294, {251, 1, 172, 207, 75, 242, 148, 19, 255, 106, 41, 114, 213, 142, 229, 239, 156, 23, 225, 4, 181, 190, 130, 111, 160, 59, 145, 253, 181, 114, 17, 118, 65, 201, 206, 61, 137, 118, 87, 156, 205, 110, 6, 63, 153, 254, 163, 225, 66, 88, 232, 189, 126, 92, 228, 204, 0, 243, 78, 239, 62, 193, 27, 197, 106, 96, 215, 1, 143, 116, 114, 112, 6, 150, 209, 152, 254, 66, 54, 94, 123, 109, 220, 31, 156, 118, 201, 119, 232, 181, 49, 140, 82, 192, 65, 167, 94, 196, 10, 162, 138, 163, 9, 240, 203, 230, 23, 117, 118, 217, 35, 59, 80, 150, 105, 253, 127, 105, 53, 54, 134, 90, 78, 161, 95, 123, 164, 235, 209, 143, 12, 199, 20, 167, 53, 246, 87, 5, 76, 164, 90, 230, 19, 34, 24, 30, 133, 190, 136, 129, 68, 208, 98, 110, 170, 174, 135, 152, 155, 76, 215, 26, 189, 63, 72, 14, 57, 186, 173, 44, 212, 212, 66, 120, 155, 51, 62, 116, 210, 218, 49, 125, 23, 134}}, - CrcCheck {"CRC-16-RANDOM-16" , 16, 0x000000000000e5dd, 0x0000000000009239, 0x00000000000006f7, false, false, 0x0000000000005351, {185, 105, 153, 99, 108, 57, 120, 51, 20, 3, 200, 10, 175, 75, 171, 152, 175, 99, 174, 14, 48, 148, 220, 47, 84, 168, 249, 218, 35, 74, 212, 106, 182, 241, 40, 210, 59, 193, 243, 1, 225, 152, 167, 139, 119, 252, 61, 192, 71, 32, 236, 161, 110, 30, 151, 179, 147, 225, 190, 238, 30, 131, 165, 128, 141, 6, 84, 62, 13, 147, 135, 190, 42, 97, 140, 154, 231, 162, 125, 98, 239, 156, 248, 149, 43, 112, 164, 127, 103, 1, 59, 30, 210, 140, 174, 72, 121, 187, 29, 204, 32, 120, 108, 243, 54, 124, 30, 88, 116, 179, 188, 230, 16, 139, 153, 151, 128, 109, 155, 131, 56, 83, 125, 11, 178, 79, 68, 209, 198, 216, 81, 133, 171, 184, 222, 68, 99, 153, 34, 93, 135, 148, 128, 21, 110, 248, 141, 92, 92, 117, 154, 56, 250, 210, 126, 109, 113, 233, 143, 253, 8, 184, 61, 223, 170, 131, 215, 150, 57, 91, 95, 200, 151, 185, 234, 166, 113, 73, 34, 83, 204, 6}}, - CrcCheck {"CRC-16-RANDOM-17" , 16, 0x000000000000b4a3, 0x000000000000b94e, 0x000000000000744e, true , true , 0x000000000000cd8b, {55, 240, 81, 130, 195, 14, 15, 70, 94, 190, 211, 82, 239, 29, 140, 56, 29, 155, 47, 100, 41, 110, 50, 185, 94, 203, 192, 11, 78, 245, 44, 158, 244, 176, 132, 85, 193, 94, 32, 74, 6, 224, 248, 2, 61, 8, 227, 112, 10, 58, 81, 76, 56, 252, 147, 99, 226, 82, 203, 87, 9, 216, 201, 189, 195, 142, 216, 248, 73, 157, 62}}, - CrcCheck {"CRC-16-RANDOM-18" , 16, 0x0000000000009c67, 0x0000000000006327, 0x0000000000008e39, false, false, 0x000000000000d9e0, {37, 181, 10, 26, 177, 9, 181, 162, 61, 13, 117, 143, 203, 86, 77, 104, 107, 0, 187, 12, 243, 73, 117, 131, 36, 34, 68, 180, 221, 2, 10, 104, 42, 247, 230, 199, 208, 83, 55, 235, 33, 104, 10, 91, 250, 88, 16, 24, 191, 252, 94, 152, 208, 179, 216, 41, 101, 64, 217, 76, 33, 231}}, + // source: generated by Boost CRC from random data and random parameters + CrcCheck { "CRC-16-RANDOM-10", 16, 0x000000000000afbb, 0x00000000000091ea, 0x0000000000000ea8, true, true, 0x0000000000000670, { 239, 127, 45, 34, 24, 9, 68, 49, 206, 206, 71, 116, 233, 144, 237, 184, 241, 86, 244, 237, 163, 167, 42, 194, 69, 147, 236, 136, 245, 183, 254, 2, 67, 220, 111, 241, 168, 255, 36, 248, 147, 137, 75, 137, 201, 100, 215, 161, 36, 13, 54, 235, 34, 187, 75, 82, 227, 97, 240, 137, 173, 165, 246, 129, 30, 174, 42, 21, 185, 94, 43, 218, 126, 90, 197, 205, 15, 21, 115, 50, 103, 38, 178, 124, 27, 24, 208, 157, 41, 53, 204, 158, 198, 238, 133, 61, 164, 203, 159, 6, 94, 213, 225, 145, 61, 245, 86, 157, 126, 41, 130, 195, 130, 11, 48, 29, 193, 187, 127, 135, 83, 44, 232, 66, 169, 147, 106, 11, 118, 124, 189, 114, 131, 148, 106, 45, 250, 134, 11, 189, 179, 74, 92, 43, 8, 116, 18, 241, 53, 218, 160, 169, 65, 112, 161, 63, 208, 61, 223, 18, 254, 51, 87, 101, 180, 244, 149, 78, 135, 54, 222, 122, 244, 184, 44 } }, + CrcCheck { "CRC-16-RANDOM-11", 16, 0x0000000000001b6c, 0x0000000000005bce, 0x000000000000e29c, true, true, 0x000000000000dfa2, { 92, 73, 175, 57, 17, 7, 61, 3, 7, 81, 172, 188, 91, 214, 51, 201, 52, 249, 51, 206, 210, 79, 156, 42, 36, 28, 235, 71, 83, 127, 30, 123, 200, 55, 127, 217, 218, 71, 203, 29, 223, 222, 198, 56, 138, 207, 196, 46, 195, 105, 28, 45, 5, 138, 168, 54, 239, 203, 1, 0, 105, 110, 21, 193, 207 } }, + CrcCheck { "CRC-16-RANDOM-12", 16, 0x000000000000477b, 0x000000000000afa4, 0x0000000000003d01, false, false, 0x0000000000000b96, { 63, 84, 254, 94, 21, 194, 88, 199, 189, 117, 111, 234, 231, 51, 119, 117, 203, 239, 210, 109, 162, 58, 158, 239, 163, 18, 68, 233, 37, 120, 48, 205, 17, 188, 141, 44, 143, 147, 173, 105 } }, + CrcCheck { "CRC-16-RANDOM-13", 16, 0x0000000000004438, 0x0000000000008e25, 0x0000000000006c55, false, false, 0x0000000000004a6d, { 179, 169, 67, 230, 228, 213, 173, 155, 152, 64, 85, 170, 20, 177, 38, 127, 169, 186, 44, 163, 153, 153, 11, 112, 63, 24, 127, 25, 135, 40, 214, 33, 88, 132, 14, 84, 82, 66, 216, 75, 55, 231, 101, 114, 68, 244, 56, 140, 100, 196, 226, 60, 0, 177, 187, 164, 237, 1, 199, 119, 249, 148, 102, 175, 32, 62, 232, 179, 30, 102, 85, 8, 188, 61, 28, 156, 74, 71, 11, 102, 51, 243, 120, 60, 146, 207, 116, 156, 219, 237, 157, 25, 0, 149, 7, 137, 248, 102, 157, 171, 60, 76, 117, 29, 34, 117, 148, 241, 142, 18, 251, 240, 37, 213, 171, 120, 85, 145, 50, 209, 130, 225, 28, 27, 170, 195, 148, 102 } }, + CrcCheck { "CRC-16-RANDOM-14", 16, 0x000000000000f461, 0x0000000000004d96, 0x0000000000003e1d, true, true, 0x0000000000009eef, { 38, 252, 182, 80, 159, 97, 166, 150, 29, 9, 45, 216, 186, 165, 148, 128, 60, 170, 243, 69, 177, 203, 17, 191, 5, 60, 209, 41, 20, 42, 23, 147, 126, 209, 125, 157, 30, 45, 94, 157, 146, 7, 20, 234, 70, 23, 141, 87, 88, 93, 184, 169, 69, 88, 108, 253, 58, 157, 175, 88, 177, 154, 181, 127, 216, 82, 202, 16, 164, 227, 188, 243, 140, 84, 24, 213, 31, 130, 185, 234, 215, 248, 169, 233, 4, 208, 67, 102, 248, 13, 114, 162, 175, 187, 120, 228, 213, 93 } }, + CrcCheck { "CRC-16-RANDOM-15", 16, 0x000000000000bbf3, 0x000000000000e279, 0x000000000000a01c, false, false, 0x000000000000f294, { 251, 1, 172, 207, 75, 242, 148, 19, 255, 106, 41, 114, 213, 142, 229, 239, 156, 23, 225, 4, 181, 190, 130, 111, 160, 59, 145, 253, 181, 114, 17, 118, 65, 201, 206, 61, 137, 118, 87, 156, 205, 110, 6, 63, 153, 254, 163, 225, 66, 88, 232, 189, 126, 92, 228, 204, 0, 243, 78, 239, 62, 193, 27, 197, 106, 96, 215, 1, 143, 116, 114, 112, 6, 150, 209, 152, 254, 66, 54, 94, 123, 109, 220, 31, 156, 118, 201, 119, 232, 181, 49, 140, 82, 192, 65, 167, 94, 196, 10, 162, 138, 163, 9, 240, 203, 230, 23, 117, 118, 217, 35, 59, 80, 150, 105, 253, 127, 105, 53, 54, 134, 90, 78, 161, 95, 123, 164, 235, 209, 143, 12, 199, 20, 167, 53, 246, 87, 5, 76, 164, 90, 230, 19, 34, 24, 30, 133, 190, 136, 129, 68, 208, 98, 110, 170, 174, 135, 152, 155, 76, 215, 26, 189, 63, 72, 14, 57, 186, 173, 44, 212, 212, 66, 120, 155, 51, 62, 116, 210, 218, 49, 125, 23, 134 }}, + CrcCheck { "CRC-16-RANDOM-16", 16, 0x000000000000e5dd, 0x0000000000009239, 0x00000000000006f7, false, false, 0x0000000000005351, { 185, 105, 153, 99, 108, 57, 120, 51, 20, 3, 200, 10, 175, 75, 171, 152, 175, 99, 174, 14, 48, 148, 220, 47, 84, 168, 249, 218, 35, 74, 212, 106, 182, 241, 40, 210, 59, 193, 243, 1, 225, 152, 167, 139, 119, 252, 61, 192, 71, 32, 236, 161, 110, 30, 151, 179, 147, 225, 190, 238, 30, 131, 165, 128, 141, 6, 84, 62, 13, 147, 135, 190, 42, 97, 140, 154, 231, 162, 125, 98, 239, 156, 248, 149, 43, 112, 164, 127, 103, 1, 59, 30, 210, 140, 174, 72, 121, 187, 29, 204, 32, 120, 108, 243, 54, 124, 30, 88, 116, 179, 188, 230, 16, 139, 153, 151, 128, 109, 155, 131, 56, 83, 125, 11, 178, 79, 68, 209, 198, 216, 81, 133, 171, 184, 222, 68, 99, 153, 34, 93, 135, 148, 128, 21, 110, 248, 141, 92, 92, 117, 154, 56, 250, 210, 126, 109, 113, 233, 143, 253, 8, 184, 61, 223, 170, 131, 215, 150, 57, 91, 95, 200, 151, 185, 234, 166, 113, 73, 34, 83, 204, 6 } }, + CrcCheck { "CRC-16-RANDOM-17", 16, 0x000000000000b4a3, 0x000000000000b94e, 0x000000000000744e, true, true, 0x000000000000cd8b, { 55, 240, 81, 130, 195, 14, 15, 70, 94, 190, 211, 82, 239, 29, 140, 56, 29, 155, 47, 100, 41, 110, 50, 185, 94, 203, 192, 11, 78, 245, 44, 158, 244, 176, 132, 85, 193, 94, 32, 74, 6, 224, 248, 2, 61, 8, 227, 112, 10, 58, 81, 76, 56, 252, 147, 99, 226, 82, 203, 87, 9, 216, 201, 189, 195, 142, 216, 248, 73, 157, 62 } }, + CrcCheck { "CRC-16-RANDOM-18", 16, 0x0000000000009c67, 0x0000000000006327, 0x0000000000008e39, false, false, 0x000000000000d9e0, { 37, 181, 10, 26, 177, 9, 181, 162, 61, 13, 117, 143, 203, 86, 77, 104, 107, 0, 187, 12, 243, 73, 117, 131, 36, 34, 68, 180, 221, 2, 10, 104, 42, 247, 230, 199, 208, 83, 55, 235, 33, 104, 10, 91, 250, 88, 16, 24, 191, 252, 94, 152, 208, 179, 216, 41, 101, 64, 217, 76, 33, 231 } }, }; TEST_ASSERT(!checkCrcAgainstGondenSamples(hex::crypt::crc16, golden_samples)); @@ -238,24 +246,24 @@ TEST_SEQUENCE("CRC16Random") { TEST_SEQUENCE("CRC8") { std::array golden_samples = { - // source: Sunshine's Homepage - Online CRC Calculator Javascript [http://www.sunshine2k.de/coding/javascript/crc/crc_js.html] - CrcCheck {"CRC-8-0-check", 8, 0xD5, 0xff, 0x00, true , true , 0x7f, {0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39}}, - CrcCheck {"CRC-8-1-check", 8, 0xD5, 0xff, 0x00, true , false, 0xfe, {0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39}}, - CrcCheck {"CRC-8-2-check", 8, 0xD5, 0xff, 0x00, false, true , 0x3e, {0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39}}, - CrcCheck {"CRC-8-3-check", 8, 0xD5, 0xff, 0x00, false, false, 0x7c, {0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39}}, - CrcCheck {"CRC-8-3-check", 8, 0xD5, 0x42, 0x5a, false, false, 0x4a, {0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39}}, + // source: Sunshine's Homepage - Online CRC Calculator Javascript [http://www.sunshine2k.de/coding/javascript/crc/crc_js.html] + CrcCheck {"CRC-8-0-check", 8, 0xD5, 0xff, 0x00, true, true, 0x7f, { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39 } }, + CrcCheck { "CRC-8-1-check", 8, 0xD5, 0xff, 0x00, true, false, 0xfe, { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39 } }, + CrcCheck { "CRC-8-2-check", 8, 0xD5, 0xff, 0x00, false, true, 0x3e, { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39 } }, + CrcCheck { "CRC-8-3-check", 8, 0xD5, 0xff, 0x00, false, false, 0x7c, { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39 } }, + CrcCheck { "CRC-8-3-check", 8, 0xD5, 0x42, 0x5a, false, false, 0x4a, { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39 } }, - // source: generated by Boost CRC from random data and random parameters - CrcCheck {"CRC-8-RANDOM-0" , 8, 0x000000000000008b, 0x00000000000000d4, 0x00000000000000c7, true , false, 0x0000000000000093, {195, 137, 209, 107, 84, 196, 218, 41, 155, 11, 48, 19, 105, 74, 207, 198, 134, 17, 172, 76, 89, 18, 81, 236, 101, 109, 222, 62, 254, 170, 66, 240, 56, 184, 199, 187, 253, 115, 251, 59, 115, 2, 105, 234, 91, 110, 86, 36, 31, 129, 146, 217, 16, 90, 115, 35, 27, 17, 81, 247, 215, 8, 67, 77, 103, 141, 9, 101, 90, 36, 155, 193, 106, 186, 134, 46, 182, 124, 220, 46, 4, 203, 171, 215, 56, 132, 110, 146, 77, 231, 214, 233, 17, 49, 77, 119, 80, 77, 158, 253, 255, 74, 94, 232, 77, 94, 81, 48, 164, 29, 51, 81, 122, 71, 23, 57, 126, 176, 129, 250, 163, 6, 1, 191, 5, 93, 172, 176, 128, 202, 52, 89, 104, 36, 50, 30, 64, 216, 19, 140, 229, 7, 214, 168, 155}}, - CrcCheck {"CRC-8-RANDOM-1" , 8, 0x000000000000005d, 0x0000000000000077, 0x0000000000000005, false, false, 0x000000000000009a, {40, 210, 96, 74, 179, 97, 240, 65, 23, 50, 222, 233, 252, 131, 110, 135, 141, 161, 239, 91, 108, 132, 166, 169, 82, 187, 251, 92, 125, 57, 64, 207, 238, 108, 243, 72, 50, 229, 127, 224, 235, 179, 59, 107, 36, 48, 15, 165, 24, 196, 221, 5, 116, 57, 5, 124, 1, 64, 141, 134, 82, 159, 200, 171, 19, 10, 196, 70, 80, 39, 2, 188, 230, 165, 138, 178, 38, 44, 26, 225, 212, 32, 44, 139, 39, 125, 231, 94, 224, 89, 47, 125, 6, 46, 254, 49, 101, 225, 23, 44, 89, 16, 76, 50, 23, 115, 188, 185, 76, 100, 122, 1, 57, 239, 100, 180, 63, 158, 205, 6}}, - CrcCheck {"CRC-8-RANDOM-2" , 8, 0x00000000000000ea, 0x00000000000000d9, 0x0000000000000000, false, false, 0x0000000000000092, {215, 10, 66, 226, 48, 21, 189, 238, 141, 93, 174, 19, 109, 196, 154, 78, 215}}, - CrcCheck {"CRC-8-RANDOM-3" , 8, 0x00000000000000f3, 0x000000000000007b, 0x000000000000007f, true , true , 0x00000000000000de, {120, 75, 112, 57, 59, 218, 44, 68, 242, 0, 155, 24, 95, 210, 134, 36, 136, 139, 106, 190, 215, 23, 15, 45, 185, 217, 72, 219, 214, 170, 89, 93, 179, 61, 71, 162, 221, 10, 37, 163, 205, 10, 136, 200, 77, 102, 51, 188, 170, 232, 196, 184, 200, 98, 79, 150, 249, 253, 188, 27, 53, 169, 239, 246, 167, 28, 100, 86, 224, 197, 201, 8, 176, 114, 195, 40, 181, 52, 77, 27, 151, 45, 44, 205, 245, 240, 182, 223, 205, 182, 57, 102, 44, 72, 201, 233, 168, 241, 30, 253, 104, 7, 72, 227, 135, 49, 63, 209, 187, 174, 29, 255, 237, 107, 77, 22, 187, 148, 64, 207, 175, 218, 201, 104, 45, 54, 204, 65, 80, 6, 185, 187, 10, 246, 222, 62, 115, 88, 250, 65, 148, 127, 28, 93, 121, 161, 65, 87, 150, 151, 117, 199, 229, 98, 31, 145, 34, 242, 145, 146, 9, 24, 176, 248, 104, 180, 208, 181, 64, 223, 171, 144, 156, 80, 234, 169, 218, 107, 68, 62, 147, 7, 61, 102, 75, 112, 168, 33, 13, 132, 56, 46, 181, 219, 84, 137, 64, 84, 228, 172, 143}}, - CrcCheck {"CRC-8-RANDOM-4" , 8, 0x00000000000000a1, 0x0000000000000035, 0x0000000000000013, true , true , 0x00000000000000e8, {132, 238, 232, 49, 230, 205, 207, 227, 227, 111, 23, 5, 192, 33, 32, 227, 219, 48, 97, 228, 184, 213, 25, 66, 188, 16, 190, 115, 253, 113, 144, 222, 9, 120, 159, 187, 23, 146, 37, 212, 214, 3, 54, 190, 246, 3, 55, 19, 254, 150, 31, 36, 112, 89, 32, 78, 42, 171, 124, 3, 229, 191, 144, 10, 60, 209, 46, 54, 11, 205, 109, 52, 142, 67, 189, 186, 147, 219, 91, 21, 1, 61, 143, 77, 38, 15, 150, 126, 140, 139, 233, 83, 103, 162, 1, 79, 30, 223, 51, 93, 43, 131, 8, 123, 228, 37}}, - CrcCheck {"CRC-8-RANDOM-5" , 8, 0x0000000000000095, 0x00000000000000d8, 0x0000000000000043, false, false, 0x0000000000000008, {25, 135, 154, 213, 104, 181, 83, 188, 128, 84, 4, 175, 2, 108, 206, 235, 11, 252, 150, 39, 125, 195, 172, 130, 109, 181, 73, 171, 211, 35, 162, 82, 207, 1, 73, 78, 24, 102, 151, 170, 234, 242, 127, 77, 161, 43, 80, 176, 5, 89, 11, 51, 24, 60, 144, 187, 182, 70, 177, 218, 126, 230, 188, 108, 205, 181, 17, 55, 154, 207, 228, 209, 77, 99, 122, 146, 209, 199, 47, 177, 200, 178, 139, 239, 27, 56, 183, 228, 153, 127, 47, 34, 111, 78, 161, 54, 86, 110, 244, 126, 108, 95, 7, 100, 160, 26, 133, 76, 101, 59, 25, 54, 23, 83, 148, 90, 26, 252, 213, 37, 9, 97, 10, 56, 53, 213, 152, 111, 126, 254, 101, 232, 71, 1, 166, 14, 159, 196, 71, 113, 20, 232, 138, 115, 126, 64, 140, 11, 52, 78, 240, 45, 160, 103, 212, 19, 188, 238, 141, 92, 126, 36, 160, 44, 72, 121, 60, 8, 211, 112, 192, 198, 50, 83, 177, 80, 166, 107, 96, 205, 183, 126, 229, 254, 128, 154, 191, 242, 251, 248, 122, 174, 162, 89, 136, 83, 217, 220, 224, 106, 23, 22, 33, 63, 142, 226, 83, 247, 60, 102, 193, 36, 63, 235, 97, 182, 86, 229, 85, 98, 90, 17, 253, 134, 201, 253, 64, 39, 33, 223, 8, 110, 55, 10, 223, 136, 14, 229, 66, 179, 79, 203, 110, 41, 151, 194, 85, 190, 122, 114, 109, 209, 59, 8}}, - CrcCheck {"CRC-8-RANDOM-6" , 8, 0x0000000000000081, 0x0000000000000083, 0x00000000000000d7, true , true , 0x000000000000006d, {7, 210, 211, 232, 246, 26, 147, 95, 236, 136, 206, 194, 251, 106, 140, 115, 125, 183, 176, 39, 84, 236, 236, 111, 120, 165, 211, 12, 217, 60, 139, 2, 182, 81, 158, 49, 38, 96, 93, 49, 197, 88, 114, 50, 235, 119, 196, 122, 165, 157, 234, 65, 166, 237, 217, 3, 247, 96, 50, 108, 153, 156, 123, 252, 224, 187, 215, 151, 52, 160, 149, 74, 50, 125, 233, 96, 242, 124, 176, 78, 178, 23, 232, 133, 191, 213, 121, 225, 34, 220, 87, 25, 187, 26, 22, 92, 92, 249, 175, 216, 162, 190, 191, 198, 166, 49, 225, 161, 117, 215, 227, 218, 80, 32, 253, 0, 19, 26, 235, 9, 23, 198, 23, 181, 161, 152, 121, 166, 57, 189, 66, 197, 72, 229, 18, 34, 146, 179, 93, 148, 184, 51, 143, 140, 138, 94, 45, 100, 194, 200, 80, 224, 15, 154, 31, 142, 55, 72, 252, 47, 76, 235, 189, 249, 27, 126, 101, 245, 232, 46, 46, 152, 208, 23, 9, 206, 76, 174, 133, 229, 221, 146, 243, 126, 73, 8, 98, 83}}, - CrcCheck {"CRC-8-RANDOM-7" , 8, 0x00000000000000e5, 0x000000000000001e, 0x00000000000000ca, false, true , 0x00000000000000ac, {207, 120, 96, 152, 93, 112, 171, 102, 62, 189, 137, 61, 204, 42, 249, 226, 131, 164, 162, 33, 222, 75, 84, 174, 63, 71, 125, 255, 254, 135, 241, 176, 17, 184, 193, 248, 167, 247, 117, 192, 182}}, - CrcCheck {"CRC-8-RANDOM-8" , 8, 0x0000000000000003, 0x0000000000000035, 0x0000000000000033, true , false, 0x00000000000000d9, {96, 249, 185, 15, 247, 136, 115, 115, 87, 117, 90, 120, 18, 197, 112, 61, 70, 87, 22, 98, 103, 241, 49, 87, 120, 119, 201, 92, 192, 109, 175, 86, 135, 157, 183, 66, 43, 21, 76, 201}}, - CrcCheck {"CRC-8-RANDOM-9" , 8, 0x000000000000002c, 0x0000000000000094, 0x0000000000000001, false, false, 0x0000000000000095, {52, 156, 20, 14, 1, 178, 132, 57, 220, 251, 1, 215, 195, 236, 197, 102, 193, 157, 140, 196, 132, 204, 155, 140, 185, 73, 13, 252, 175, 141, 171, 139, 221, 14, 156, 253, 107, 24, 153, 166, 217, 181, 203, 39, 172, 114, 160, 88, 197, 221, 51, 241, 70, 152, 181, 31, 88, 165, 30, 123, 231, 163, 75, 107, 55, 95, 2, 13, 70, 128, 165, 27, 224, 105, 51, 97, 76, 160, 100, 245, 174, 32, 109, 251, 43, 55, 139, 88, 89, 122, 194, 92, 245, 188, 236, 38, 211, 19, 252, 17, 209, 60, 133, 227, 36, 69, 213, 161, 162, 187, 161, 202, 3, 71, 32, 29, 131, 167, 43, 99, 175, 141, 70, 62, 3, 56, 100, 107, 165, 123, 239, 252, 219, 111, 11, 31, 216, 22, 111, 27, 7, 44, 168, 68, 216, 58, 207, 231, 94, 58, 178, 210, 149}}, + // source: generated by Boost CRC from random data and random parameters + CrcCheck { "CRC-8-RANDOM-0", 8, 0x000000000000008b, 0x00000000000000d4, 0x00000000000000c7, true, false, 0x0000000000000093, { 195, 137, 209, 107, 84, 196, 218, 41, 155, 11, 48, 19, 105, 74, 207, 198, 134, 17, 172, 76, 89, 18, 81, 236, 101, 109, 222, 62, 254, 170, 66, 240, 56, 184, 199, 187, 253, 115, 251, 59, 115, 2, 105, 234, 91, 110, 86, 36, 31, 129, 146, 217, 16, 90, 115, 35, 27, 17, 81, 247, 215, 8, 67, 77, 103, 141, 9, 101, 90, 36, 155, 193, 106, 186, 134, 46, 182, 124, 220, 46, 4, 203, 171, 215, 56, 132, 110, 146, 77, 231, 214, 233, 17, 49, 77, 119, 80, 77, 158, 253, 255, 74, 94, 232, 77, 94, 81, 48, 164, 29, 51, 81, 122, 71, 23, 57, 126, 176, 129, 250, 163, 6, 1, 191, 5, 93, 172, 176, 128, 202, 52, 89, 104, 36, 50, 30, 64, 216, 19, 140, 229, 7, 214, 168, 155 } }, + CrcCheck { "CRC-8-RANDOM-1", 8, 0x000000000000005d, 0x0000000000000077, 0x0000000000000005, false, false, 0x000000000000009a, { 40, 210, 96, 74, 179, 97, 240, 65, 23, 50, 222, 233, 252, 131, 110, 135, 141, 161, 239, 91, 108, 132, 166, 169, 82, 187, 251, 92, 125, 57, 64, 207, 238, 108, 243, 72, 50, 229, 127, 224, 235, 179, 59, 107, 36, 48, 15, 165, 24, 196, 221, 5, 116, 57, 5, 124, 1, 64, 141, 134, 82, 159, 200, 171, 19, 10, 196, 70, 80, 39, 2, 188, 230, 165, 138, 178, 38, 44, 26, 225, 212, 32, 44, 139, 39, 125, 231, 94, 224, 89, 47, 125, 6, 46, 254, 49, 101, 225, 23, 44, 89, 16, 76, 50, 23, 115, 188, 185, 76, 100, 122, 1, 57, 239, 100, 180, 63, 158, 205, 6 } }, + CrcCheck { "CRC-8-RANDOM-2", 8, 0x00000000000000ea, 0x00000000000000d9, 0x0000000000000000, false, false, 0x0000000000000092, { 215, 10, 66, 226, 48, 21, 189, 238, 141, 93, 174, 19, 109, 196, 154, 78, 215 } }, + CrcCheck { "CRC-8-RANDOM-3", 8, 0x00000000000000f3, 0x000000000000007b, 0x000000000000007f, true, true, 0x00000000000000de, { 120, 75, 112, 57, 59, 218, 44, 68, 242, 0, 155, 24, 95, 210, 134, 36, 136, 139, 106, 190, 215, 23, 15, 45, 185, 217, 72, 219, 214, 170, 89, 93, 179, 61, 71, 162, 221, 10, 37, 163, 205, 10, 136, 200, 77, 102, 51, 188, 170, 232, 196, 184, 200, 98, 79, 150, 249, 253, 188, 27, 53, 169, 239, 246, 167, 28, 100, 86, 224, 197, 201, 8, 176, 114, 195, 40, 181, 52, 77, 27, 151, 45, 44, 205, 245, 240, 182, 223, 205, 182, 57, 102, 44, 72, 201, 233, 168, 241, 30, 253, 104, 7, 72, 227, 135, 49, 63, 209, 187, 174, 29, 255, 237, 107, 77, 22, 187, 148, 64, 207, 175, 218, 201, 104, 45, 54, 204, 65, 80, 6, 185, 187, 10, 246, 222, 62, 115, 88, 250, 65, 148, 127, 28, 93, 121, 161, 65, 87, 150, 151, 117, 199, 229, 98, 31, 145, 34, 242, 145, 146, 9, 24, 176, 248, 104, 180, 208, 181, 64, 223, 171, 144, 156, 80, 234, 169, 218, 107, 68, 62, 147, 7, 61, 102, 75, 112, 168, 33, 13, 132, 56, 46, 181, 219, 84, 137, 64, 84, 228, 172, 143 } }, + CrcCheck { "CRC-8-RANDOM-4", 8, 0x00000000000000a1, 0x0000000000000035, 0x0000000000000013, true, true, 0x00000000000000e8, { 132, 238, 232, 49, 230, 205, 207, 227, 227, 111, 23, 5, 192, 33, 32, 227, 219, 48, 97, 228, 184, 213, 25, 66, 188, 16, 190, 115, 253, 113, 144, 222, 9, 120, 159, 187, 23, 146, 37, 212, 214, 3, 54, 190, 246, 3, 55, 19, 254, 150, 31, 36, 112, 89, 32, 78, 42, 171, 124, 3, 229, 191, 144, 10, 60, 209, 46, 54, 11, 205, 109, 52, 142, 67, 189, 186, 147, 219, 91, 21, 1, 61, 143, 77, 38, 15, 150, 126, 140, 139, 233, 83, 103, 162, 1, 79, 30, 223, 51, 93, 43, 131, 8, 123, 228, 37 } }, + CrcCheck { "CRC-8-RANDOM-5", 8, 0x0000000000000095, 0x00000000000000d8, 0x0000000000000043, false, false, 0x0000000000000008, { 25, 135, 154, 213, 104, 181, 83, 188, 128, 84, 4, 175, 2, 108, 206, 235, 11, 252, 150, 39, 125, 195, 172, 130, 109, 181, 73, 171, 211, 35, 162, 82, 207, 1, 73, 78, 24, 102, 151, 170, 234, 242, 127, 77, 161, 43, 80, 176, 5, 89, 11, 51, 24, 60, 144, 187, 182, 70, 177, 218, 126, 230, 188, 108, 205, 181, 17, 55, 154, 207, 228, 209, 77, 99, 122, 146, 209, 199, 47, 177, 200, 178, 139, 239, 27, 56, 183, 228, 153, 127, 47, 34, 111, 78, 161, 54, 86, 110, 244, 126, 108, 95, 7, 100, 160, 26, 133, 76, 101, 59, 25, 54, 23, 83, 148, 90, 26, 252, 213, 37, 9, 97, 10, 56, 53, 213, 152, 111, 126, 254, 101, 232, 71, 1, 166, 14, 159, 196, 71, 113, 20, 232, 138, 115, 126, 64, 140, 11, 52, 78, 240, 45, 160, 103, 212, 19, 188, 238, 141, 92, 126, 36, 160, 44, 72, 121, 60, 8, 211, 112, 192, 198, 50, 83, 177, 80, 166, 107, 96, 205, 183, 126, 229, 254, 128, 154, 191, 242, 251, 248, 122, 174, 162, 89, 136, 83, 217, 220, 224, 106, 23, 22, 33, 63, 142, 226, 83, 247, 60, 102, 193, 36, 63, 235, 97, 182, 86, 229, 85, 98, 90, 17, 253, 134, 201, 253, 64, 39, 33, 223, 8, 110, 55, 10, 223, 136, 14, 229, 66, 179, 79, 203, 110, 41, 151, 194, 85, 190, 122, 114, 109, 209, 59, 8 }}, + CrcCheck { "CRC-8-RANDOM-6", 8, 0x0000000000000081, 0x0000000000000083, 0x00000000000000d7, true, true, 0x000000000000006d, { 7, 210, 211, 232, 246, 26, 147, 95, 236, 136, 206, 194, 251, 106, 140, 115, 125, 183, 176, 39, 84, 236, 236, 111, 120, 165, 211, 12, 217, 60, 139, 2, 182, 81, 158, 49, 38, 96, 93, 49, 197, 88, 114, 50, 235, 119, 196, 122, 165, 157, 234, 65, 166, 237, 217, 3, 247, 96, 50, 108, 153, 156, 123, 252, 224, 187, 215, 151, 52, 160, 149, 74, 50, 125, 233, 96, 242, 124, 176, 78, 178, 23, 232, 133, 191, 213, 121, 225, 34, 220, 87, 25, 187, 26, 22, 92, 92, 249, 175, 216, 162, 190, 191, 198, 166, 49, 225, 161, 117, 215, 227, 218, 80, 32, 253, 0, 19, 26, 235, 9, 23, 198, 23, 181, 161, 152, 121, 166, 57, 189, 66, 197, 72, 229, 18, 34, 146, 179, 93, 148, 184, 51, 143, 140, 138, 94, 45, 100, 194, 200, 80, 224, 15, 154, 31, 142, 55, 72, 252, 47, 76, 235, 189, 249, 27, 126, 101, 245, 232, 46, 46, 152, 208, 23, 9, 206, 76, 174, 133, 229, 221, 146, 243, 126, 73, 8, 98, 83 } }, + CrcCheck { "CRC-8-RANDOM-7", 8, 0x00000000000000e5, 0x000000000000001e, 0x00000000000000ca, false, true, 0x00000000000000ac, { 207, 120, 96, 152, 93, 112, 171, 102, 62, 189, 137, 61, 204, 42, 249, 226, 131, 164, 162, 33, 222, 75, 84, 174, 63, 71, 125, 255, 254, 135, 241, 176, 17, 184, 193, 248, 167, 247, 117, 192, 182 } }, + CrcCheck { "CRC-8-RANDOM-8", 8, 0x0000000000000003, 0x0000000000000035, 0x0000000000000033, true, false, 0x00000000000000d9, { 96, 249, 185, 15, 247, 136, 115, 115, 87, 117, 90, 120, 18, 197, 112, 61, 70, 87, 22, 98, 103, 241, 49, 87, 120, 119, 201, 92, 192, 109, 175, 86, 135, 157, 183, 66, 43, 21, 76, 201 } }, + CrcCheck { "CRC-8-RANDOM-9", 8, 0x000000000000002c, 0x0000000000000094, 0x0000000000000001, false, false, 0x0000000000000095, { 52, 156, 20, 14, 1, 178, 132, 57, 220, 251, 1, 215, 195, 236, 197, 102, 193, 157, 140, 196, 132, 204, 155, 140, 185, 73, 13, 252, 175, 141, 171, 139, 221, 14, 156, 253, 107, 24, 153, 166, 217, 181, 203, 39, 172, 114, 160, 88, 197, 221, 51, 241, 70, 152, 181, 31, 88, 165, 30, 123, 231, 163, 75, 107, 55, 95, 2, 13, 70, 128, 165, 27, 224, 105, 51, 97, 76, 160, 100, 245, 174, 32, 109, 251, 43, 55, 139, 88, 89, 122, 194, 92, 245, 188, 236, 38, 211, 19, 252, 17, 209, 60, 133, 227, 36, 69, 213, 161, 162, 187, 161, 202, 3, 71, 32, 29, 131, 167, 43, 99, 175, 141, 70, 62, 3, 56, 100, 107, 165, 123, 239, 252, 219, 111, 11, 31, 216, 22, 111, 27, 7, 44, 168, 68, 216, 58, 207, 231, 94, 58, 178, 210, 149 } }, }; TEST_ASSERT(!checkCrcAgainstGondenSamples(hex::crypt::crc8, golden_samples)); @@ -275,48 +283,52 @@ struct HashCheck { }; template -int checkHashProviderAgainstGondenSamples(Ret (*func)(hex::prv::Provider* &, u64, size_t), Range golden_samples) -{ - for(auto& i: golden_samples) { +int checkHashProviderAgainstGondenSamples(Ret (*func)(hex::prv::Provider *&, u64, size_t), Range golden_samples) { + for (auto &i : golden_samples) { std::vector data(i.data.data(), i.data.data() + i.data.size()); hex::test::TestProvider provider(&data); - hex::prv::Provider* provider2 = &provider; + hex::prv::Provider *provider2 = &provider; auto res = func(provider2, 0, i.data.size()); TEST_ASSERT(std::equal(std::begin(res), std::end(res), hex::crypt::decode16(i.result).begin()), - "data: '{}' got: {} expected: {}", i.data, hex::crypt::encode16(std::vector(res.begin(), res.end())), i.result); + "data: '{}' got: {} expected: {}", + i.data, + hex::crypt::encode16(std::vector(res.begin(), res.end())), + i.result); } TEST_SUCCESS(); } template -int checkHashVectorAgainstGondenSamples(Ret (*func)(const std::vector &), Range golden_samples) -{ - for(auto& i: golden_samples) { +int checkHashVectorAgainstGondenSamples(Ret (*func)(const std::vector &), Range golden_samples) { + for (auto &i : golden_samples) { std::vector data(i.data.data(), i.data.data() + i.data.size()); auto res = func(data); TEST_ASSERT(std::equal(std::begin(res), std::end(res), hex::crypt::decode16(i.result).begin()), - "data: '{}' got: {} expected: {}", i.data, hex::crypt::encode16(std::vector(res.begin(), res.end())), i.result); + "data: '{}' got: {} expected: {}", + i.data, + hex::crypt::encode16(std::vector(res.begin(), res.end())), + i.result); } TEST_SUCCESS(); } TEST_SEQUENCE("md5") { std::array golden_samples = { - // source: RFC 1321: The MD5 Message-Digest Algorithm [https://datatracker.ietf.org/doc/html/rfc1321#appendix-A.5] - HashCheck{"", - "d41d8cd98f00b204e9800998ecf8427e"}, - HashCheck{"a", - "0cc175b9c0f1b6a831c399e269772661"}, - HashCheck{"abc", - "900150983cd24fb0d6963f7d28e17f72"}, - HashCheck{"message digest", - "f96b697d7cb7938d525a2f31aaf161d0"}, - HashCheck{"abcdefghijklmnopqrstuvwxyz", - "c3fcd3d76192e4007dfb496cca67e13b"}, - HashCheck{"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", - "d174ab98d277d9f5a5611c2c9f419d9f"}, - HashCheck{"12345678901234567890123456789012345678901234567890123456789012345678901234567890", - "57edf4a22be3c955ac49da2e2107b67a"}, + // source: RFC 1321: The MD5 Message-Digest Algorithm [https://datatracker.ietf.org/doc/html/rfc1321#appendix-A.5] + HashCheck {"", + "d41d8cd98f00b204e9800998ecf8427e"}, + HashCheck { "a", + "0cc175b9c0f1b6a831c399e269772661"}, + HashCheck { "abc", + "900150983cd24fb0d6963f7d28e17f72"}, + HashCheck { "message digest", + "f96b697d7cb7938d525a2f31aaf161d0"}, + HashCheck { "abcdefghijklmnopqrstuvwxyz", + "c3fcd3d76192e4007dfb496cca67e13b"}, + HashCheck { "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", + "d174ab98d277d9f5a5611c2c9f419d9f"}, + HashCheck { "12345678901234567890123456789012345678901234567890123456789012345678901234567890", + "57edf4a22be3c955ac49da2e2107b67a"}, }; TEST_ASSERT(!checkHashProviderAgainstGondenSamples(hex::crypt::md5, golden_samples)); @@ -328,11 +340,11 @@ TEST_SEQUENCE("md5") { TEST_SEQUENCE("sha1") { std::array golden_samples = { - // source: RFC 3174: US Secure Hash Algorithm 1 (SHA1) [https://datatracker.ietf.org/doc/html/rfc3174#section-7.3] - HashCheck{"abc", - "A9993E364706816ABA3E25717850C26C9CD0D89D"}, - HashCheck{"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", - "84983E441C3BD26EBAAE4AA1F95129E5E54670F1"}, + // source: RFC 3174: US Secure Hash Algorithm 1 (SHA1) [https://datatracker.ietf.org/doc/html/rfc3174#section-7.3] + HashCheck {"abc", + "A9993E364706816ABA3E25717850C26C9CD0D89D"}, + HashCheck { "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", + "84983E441C3BD26EBAAE4AA1F95129E5E54670F1"}, }; TEST_ASSERT(!checkHashProviderAgainstGondenSamples(hex::crypt::sha1, golden_samples)); @@ -343,11 +355,11 @@ TEST_SEQUENCE("sha1") { TEST_SEQUENCE("sha224") { std::array golden_samples = { - // source: RFC 3874: A 224-bit One-way Hash Function: SHA-224 [https://datatracker.ietf.org/doc/html/rfc3874#section-3] - HashCheck{"abc", - "23097D223405D8228642A477BDA255B32AADBCE4BDA0B3F7E36C9DA7"}, - HashCheck{"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", - "75388B16512776CC5DBA5DA1FD890150B0C6455CB4F58B1952522525"}, + // source: RFC 3874: A 224-bit One-way Hash Function: SHA-224 [https://datatracker.ietf.org/doc/html/rfc3874#section-3] + HashCheck {"abc", + "23097D223405D8228642A477BDA255B32AADBCE4BDA0B3F7E36C9DA7"}, + HashCheck { "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", + "75388B16512776CC5DBA5DA1FD890150B0C6455CB4F58B1952522525"}, }; TEST_ASSERT(!checkHashProviderAgainstGondenSamples(hex::crypt::sha224, golden_samples)); @@ -358,11 +370,11 @@ TEST_SEQUENCE("sha224") { TEST_SEQUENCE("sha256") { std::array golden_samples = { - // source: RFC 4634: US Secure Hash Algorithms (SHA and HMAC-SHA) [https://datatracker.ietf.org/doc/html/rfc4634#section-8.4] - HashCheck{"abc", - "BA7816BF8F01CFEA414140DE5DAE2223B00361A396177A9CB410FF61F20015AD"}, - HashCheck{"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", - "248D6A61D20638B8E5C026930C3E6039A33CE45964FF2167F6ECEDD419DB06C1"}, + // source: RFC 4634: US Secure Hash Algorithms (SHA and HMAC-SHA) [https://datatracker.ietf.org/doc/html/rfc4634#section-8.4] + HashCheck {"abc", + "BA7816BF8F01CFEA414140DE5DAE2223B00361A396177A9CB410FF61F20015AD"}, + HashCheck { "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", + "248D6A61D20638B8E5C026930C3E6039A33CE45964FF2167F6ECEDD419DB06C1"}, }; TEST_ASSERT(!checkHashProviderAgainstGondenSamples(hex::crypt::sha256, golden_samples)); @@ -373,11 +385,11 @@ TEST_SEQUENCE("sha256") { TEST_SEQUENCE("sha384") { std::array golden_samples = { - // source: RFC 4634: US Secure Hash Algorithms (SHA and HMAC-SHA) [https://datatracker.ietf.org/doc/html/rfc4634#section-8.4] - HashCheck{"abc", - "CB00753F45A35E8BB5A03D699AC65007272C32AB0EDED1631A8B605A43FF5BED8086072BA1E7CC2358BAECA134C825A7"}, - HashCheck{"abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu", - "09330C33F71147E83D192FC782CD1B4753111B173B3B05D22FA08086E3B0F712FCC7C71A557E2DB966C3E9FA91746039"}, + // source: RFC 4634: US Secure Hash Algorithms (SHA and HMAC-SHA) [https://datatracker.ietf.org/doc/html/rfc4634#section-8.4] + HashCheck {"abc", + "CB00753F45A35E8BB5A03D699AC65007272C32AB0EDED1631A8B605A43FF5BED8086072BA1E7CC2358BAECA134C825A7"}, + HashCheck { "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu", + "09330C33F71147E83D192FC782CD1B4753111B173B3B05D22FA08086E3B0F712FCC7C71A557E2DB966C3E9FA91746039"}, }; TEST_ASSERT(!checkHashProviderAgainstGondenSamples(hex::crypt::sha384, golden_samples)); @@ -388,11 +400,11 @@ TEST_SEQUENCE("sha384") { TEST_SEQUENCE("sha512") { std::array golden_samples = { - // source: RFC 4634: US Secure Hash Algorithms (SHA and HMAC-SHA) [https://datatracker.ietf.org/doc/html/rfc4634#section-8.4] - HashCheck{"abc", - "DDAF35A193617ABACC417349AE20413112E6FA4E89A97EA20A9EEEE64B55D39A2192992A274FC1A836BA3C23A3FEEBBD454D4423643CE80E2A9AC94FA54CA49F"}, - HashCheck{"abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu", - "8E959B75DAE313DA8CF4F72814FC143F8F7779C6EB9F7FA17299AEADB6889018501D289E4900F7E4331B99DEC4B5433AC7D329EEB6DD26545E96E55B874BE909"}, + // source: RFC 4634: US Secure Hash Algorithms (SHA and HMAC-SHA) [https://datatracker.ietf.org/doc/html/rfc4634#section-8.4] + HashCheck {"abc", + "DDAF35A193617ABACC417349AE20413112E6FA4E89A97EA20A9EEEE64B55D39A2192992A274FC1A836BA3C23A3FEEBBD454D4423643CE80E2A9AC94FA54CA49F"}, + HashCheck { "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu", + "8E959B75DAE313DA8CF4F72814FC143F8F7779C6EB9F7FA17299AEADB6889018501D289E4900F7E4331B99DEC4B5433AC7D329EEB6DD26545E96E55B874BE909"}, }; TEST_ASSERT(!checkHashProviderAgainstGondenSamples(hex::crypt::sha512, golden_samples)); diff --git a/tests/algorithms/source/endian.cpp b/tests/algorithms/source/endian.cpp index 642a5ed15..e025b06c3 100644 --- a/tests/algorithms/source/endian.cpp +++ b/tests/algorithms/source/endian.cpp @@ -10,7 +10,7 @@ TEST_SEQUENCE("32BitIntegerEndianSwap") { TEST_SEQUENCE("64BitFloatEndianSwap") { double floatValue = 1234.5; - u64 integerValue = reinterpret_cast(floatValue); + u64 integerValue = reinterpret_cast(floatValue); double swappedFloatValue = hex::changeEndianess(floatValue, std::endian::big); u64 swappedIntegerValue = hex::changeEndianess(integerValue, std::endian::big); diff --git a/tests/algorithms/source/main.cpp b/tests/algorithms/source/main.cpp index ba0b7982c..8c2b75bdd 100644 --- a/tests/algorithms/source/main.cpp +++ b/tests/algorithms/source/main.cpp @@ -25,9 +25,12 @@ int test(int argc, char **argv) { if (test.shouldFail) { switch (result) { - case EXIT_SUCCESS: return EXIT_FAILURE; - case EXIT_FAILURE: return EXIT_SUCCESS; - default: return result; + case EXIT_SUCCESS: + return EXIT_FAILURE; + case EXIT_FAILURE: + return EXIT_SUCCESS; + default: + return result; } } else { return result; diff --git a/tests/pattern_language/include/test_patterns/test_pattern.hpp b/tests/pattern_language/include/test_patterns/test_pattern.hpp index 84e803431..f6e40654a 100644 --- a/tests/pattern_language/include/test_patterns/test_pattern.hpp +++ b/tests/pattern_language/include/test_patterns/test_pattern.hpp @@ -5,7 +5,7 @@ #include -#define TEST(name) (hex::test::TestPattern*) new hex::test::TestPattern ## name () +#define TEST(name) (hex::test::TestPattern *)new hex::test::TestPattern##name() namespace hex::test { @@ -28,7 +28,7 @@ namespace hex::test { } template - static T* create(const std::string &typeName, const std::string &varName, auto ... args) { + static T *create(const std::string &typeName, const std::string &varName, auto... args) { auto pattern = new T(args...); pattern->setTypeName(typeName); pattern->setVariableName(varName); @@ -36,37 +36,32 @@ namespace hex::test { return pattern; } - [[nodiscard]] - virtual std::string getSourceCode() const = 0; + [[nodiscard]] virtual std::string getSourceCode() const = 0; - [[nodiscard]] - virtual const std::vector& getPatterns() const final { return this->m_patterns; } + [[nodiscard]] virtual const std::vector &getPatterns() const final { return this->m_patterns; } virtual void addPattern(PatternData *pattern) final { this->m_patterns.push_back(pattern); } - [[nodiscard]] - auto failing() { + [[nodiscard]] auto failing() { this->m_mode = Mode::Failing; return this; } - [[nodiscard]] - Mode getMode() { + [[nodiscard]] Mode getMode() { return this->m_mode; } - [[nodiscard]] - static auto& getTests() { + [[nodiscard]] static auto &getTests() { return TestPattern::s_tests; } private: - std::vector m_patterns; + std::vector m_patterns; Mode m_mode; - static inline std::map s_tests; + static inline std::map s_tests; }; } \ No newline at end of file diff --git a/tests/pattern_language/include/test_patterns/test_pattern_bitfields.hpp b/tests/pattern_language/include/test_patterns/test_pattern_bitfields.hpp index 302ce070c..317fdfa5a 100644 --- a/tests/pattern_language/include/test_patterns/test_pattern_bitfields.hpp +++ b/tests/pattern_language/include/test_patterns/test_pattern_bitfields.hpp @@ -6,22 +6,19 @@ namespace hex::test { class TestPatternBitfields : public TestPattern { public: - TestPatternBitfields() : TestPattern("Bitfields") { + TestPatternBitfields() : TestPattern("Bitfields") { auto testBitfield = create("TestBitfield", "testBitfield", 0x12, (4 * 4) / 8, nullptr); testBitfield->setEndian(std::endian::big); - testBitfield->setFields({ - create("", "a", 0x12, 0, 4, testBitfield, nullptr), - create("", "b", 0x12, 4, 4, testBitfield, nullptr), - create("", "c", 0x12, 8, 4, testBitfield, nullptr), - create("", "d", 0x12, 12, 4, testBitfield, nullptr) - }); + testBitfield->setFields({ create("", "a", 0x12, 0, 4, testBitfield, nullptr), + create("", "b", 0x12, 4, 4, testBitfield, nullptr), + create("", "c", 0x12, 8, 4, testBitfield, nullptr), + create("", "d", 0x12, 12, 4, testBitfield, nullptr) }); addPattern(testBitfield); } ~TestPatternBitfields() override = default; - [[nodiscard]] - std::string getSourceCode() const override { + [[nodiscard]] std::string getSourceCode() const override { return R"( bitfield TestBitfield { a : 4; @@ -38,7 +35,6 @@ namespace hex::test { std::assert(testBitfield.d == 0x03, "Field D invalid"); )"; } - }; } \ No newline at end of file diff --git a/tests/pattern_language/include/test_patterns/test_pattern_enums.hpp b/tests/pattern_language/include/test_patterns/test_pattern_enums.hpp index d8be52c44..49eb49f94 100644 --- a/tests/pattern_language/include/test_patterns/test_pattern_enums.hpp +++ b/tests/pattern_language/include/test_patterns/test_pattern_enums.hpp @@ -6,13 +6,13 @@ namespace hex::test { class TestPatternEnums : public TestPattern { public: - TestPatternEnums() : TestPattern("Enums"){ + TestPatternEnums() : TestPattern("Enums") { auto testEnum = create("TestEnum", "testEnum", 0x08, sizeof(u32), nullptr); testEnum->setEnumValues({ - { u128(0x0000), "A" }, - { i128(0x0C), "B" }, - { u128(0x0D), "C" }, - { u128(0x0E), "D" }, + {u128(0x0000), "A"}, + { i128(0x0C), "B"}, + { u128(0x0D), "C"}, + { u128(0x0E), "D"}, }); testEnum->setEndian(std::endian::big); @@ -20,8 +20,7 @@ namespace hex::test { } ~TestPatternEnums() override = default; - [[nodiscard]] - std::string getSourceCode() const override { + [[nodiscard]] std::string getSourceCode() const override { return R"( enum TestEnum : u32 { A, @@ -35,7 +34,6 @@ namespace hex::test { std::assert(testEnum == TestEnum::C, "Invalid enum value"); )"; } - }; } \ No newline at end of file diff --git a/tests/pattern_language/include/test_patterns/test_pattern_example.hpp b/tests/pattern_language/include/test_patterns/test_pattern_example.hpp index 5adf8dae9..1aa019d57 100644 --- a/tests/pattern_language/include/test_patterns/test_pattern_example.hpp +++ b/tests/pattern_language/include/test_patterns/test_pattern_example.hpp @@ -6,18 +6,15 @@ namespace hex::test { class TestPatternExample : public TestPattern { public: - TestPatternExample() : TestPattern("") { - + TestPatternExample() : TestPattern("") { } ~TestPatternExample() override = default; - [[nodiscard]] - std::string getSourceCode() const override { + [[nodiscard]] std::string getSourceCode() const override { return R"( )"; } - }; } \ No newline at end of file diff --git a/tests/pattern_language/include/test_patterns/test_pattern_extra_semicolon.hpp b/tests/pattern_language/include/test_patterns/test_pattern_extra_semicolon.hpp index e58a8c605..c0149e2d0 100644 --- a/tests/pattern_language/include/test_patterns/test_pattern_extra_semicolon.hpp +++ b/tests/pattern_language/include/test_patterns/test_pattern_extra_semicolon.hpp @@ -6,13 +6,11 @@ namespace hex::test { class TestPatternExtraSemicolon : public TestPattern { public: - TestPatternExtraSemicolon() : TestPattern("ExtraSemicolon") { - + TestPatternExtraSemicolon() : TestPattern("ExtraSemicolon") { } ~TestPatternExtraSemicolon() override = default; - [[nodiscard]] - std::string getSourceCode() const override { + [[nodiscard]] std::string getSourceCode() const override { return R"( struct Test { u32 x;;; @@ -29,7 +27,6 @@ namespace hex::test { Test test2 @ 0x10; )"; } - }; } \ No newline at end of file diff --git a/tests/pattern_language/include/test_patterns/test_pattern_failing_assert.hpp b/tests/pattern_language/include/test_patterns/test_pattern_failing_assert.hpp index 1088ecdac..44b8c797c 100644 --- a/tests/pattern_language/include/test_patterns/test_pattern_failing_assert.hpp +++ b/tests/pattern_language/include/test_patterns/test_pattern_failing_assert.hpp @@ -6,13 +6,11 @@ namespace hex::test { class TestPatternFailingAssert : public TestPattern { public: - TestPatternFailingAssert() : TestPattern("FailingAssert", Mode::Failing) { - + TestPatternFailingAssert() : TestPattern("FailingAssert", Mode::Failing) { } ~TestPatternFailingAssert() override = default; - [[nodiscard]] - std::string getSourceCode() const override { + [[nodiscard]] std::string getSourceCode() const override { return R"( #define MSG "Error" @@ -20,7 +18,6 @@ namespace hex::test { )"; } - }; } \ No newline at end of file diff --git a/tests/pattern_language/include/test_patterns/test_pattern_literals.hpp b/tests/pattern_language/include/test_patterns/test_pattern_literals.hpp index 3a51fc47b..0d5bb34cd 100644 --- a/tests/pattern_language/include/test_patterns/test_pattern_literals.hpp +++ b/tests/pattern_language/include/test_patterns/test_pattern_literals.hpp @@ -6,13 +6,11 @@ namespace hex::test { class TestPatternLiterals : public TestPattern { public: - TestPatternLiterals() : TestPattern("Literals") { - + TestPatternLiterals() : TestPattern("Literals") { } ~TestPatternLiterals() override = default; - [[nodiscard]] - std::string getSourceCode() const override { + [[nodiscard]] std::string getSourceCode() const override { return R"( #define MSG "Invalid literal" @@ -26,7 +24,6 @@ namespace hex::test { )"; } - }; } \ No newline at end of file diff --git a/tests/pattern_language/include/test_patterns/test_pattern_math.hpp b/tests/pattern_language/include/test_patterns/test_pattern_math.hpp index 0d277822a..8cb0b54be 100644 --- a/tests/pattern_language/include/test_patterns/test_pattern_math.hpp +++ b/tests/pattern_language/include/test_patterns/test_pattern_math.hpp @@ -6,13 +6,11 @@ namespace hex::test { class TestPatternMath : public TestPattern { public: - TestPatternMath() : TestPattern("Math") { - + TestPatternMath() : TestPattern("Math") { } ~TestPatternMath() override = default; - [[nodiscard]] - std::string getSourceCode() const override { + [[nodiscard]] std::string getSourceCode() const override { return R"( // Compare operations std::assert(123 == 123, "== operation error"); @@ -70,7 +68,6 @@ namespace hex::test { std::assert(10F / (20F + 30F) != 10F / 20F + 10F / 30F, "/ operator distributivity error"); )"; } - }; } \ No newline at end of file diff --git a/tests/pattern_language/include/test_patterns/test_pattern_namespaces.hpp b/tests/pattern_language/include/test_patterns/test_pattern_namespaces.hpp index d6e15bdac..003d6193e 100644 --- a/tests/pattern_language/include/test_patterns/test_pattern_namespaces.hpp +++ b/tests/pattern_language/include/test_patterns/test_pattern_namespaces.hpp @@ -6,13 +6,11 @@ namespace hex::test { class TestPatternNamespaces : public TestPattern { public: - TestPatternNamespaces() : TestPattern("Namespaces") { - + TestPatternNamespaces() : TestPattern("Namespaces") { } ~TestPatternNamespaces() override = default; - [[nodiscard]] - std::string getSourceCode() const override { + [[nodiscard]] std::string getSourceCode() const override { return R"( namespace A { struct Test { @@ -36,7 +34,6 @@ namespace hex::test { std::assert(sizeof(test2) != sizeof(test3), "error differentiating two namespace types with same name"); )"; } - }; } \ No newline at end of file diff --git a/tests/pattern_language/include/test_patterns/test_pattern_padding.hpp b/tests/pattern_language/include/test_patterns/test_pattern_padding.hpp index 869a71596..41fc0e565 100644 --- a/tests/pattern_language/include/test_patterns/test_pattern_padding.hpp +++ b/tests/pattern_language/include/test_patterns/test_pattern_padding.hpp @@ -6,7 +6,7 @@ namespace hex::test { class TestPatternPadding : public TestPattern { public: - TestPatternPadding() : TestPattern("Padding") { + TestPatternPadding() : TestPattern("Padding") { auto testStruct = create("TestStruct", "testStruct", 0x100, sizeof(i32) + 20 + sizeof(u8[0x10]), nullptr); auto variable = create("s32", "variable", 0x100, sizeof(i32), nullptr); @@ -20,8 +20,7 @@ namespace hex::test { } ~TestPatternPadding() override = default; - [[nodiscard]] - std::string getSourceCode() const override { + [[nodiscard]] std::string getSourceCode() const override { return R"( struct TestStruct { s32 variable; @@ -32,7 +31,6 @@ namespace hex::test { TestStruct testStruct @ 0x100; )"; } - }; } \ No newline at end of file diff --git a/tests/pattern_language/include/test_patterns/test_pattern_placement.hpp b/tests/pattern_language/include/test_patterns/test_pattern_placement.hpp index c5b557ca6..79ff52afc 100644 --- a/tests/pattern_language/include/test_patterns/test_pattern_placement.hpp +++ b/tests/pattern_language/include/test_patterns/test_pattern_placement.hpp @@ -6,7 +6,7 @@ namespace hex::test { class TestPatternPlacement : public TestPattern { public: - TestPatternPlacement() : TestPattern("Placement") { + TestPatternPlacement() : TestPattern("Placement") { // placementVar { addPattern(create("u32", "placementVar", 0x00, sizeof(u32), nullptr)); @@ -18,18 +18,15 @@ namespace hex::test { placementArray->setEntries(create("u8", "", 0x10, sizeof(u8), nullptr), 10); addPattern(placementArray); } - } ~TestPatternPlacement() override = default; - [[nodiscard]] - std::string getSourceCode() const override { + [[nodiscard]] std::string getSourceCode() const override { return R"( u32 placementVar @ 0x00; u8 placementArray[10] @ 0x10; )"; } - }; } \ No newline at end of file diff --git a/tests/pattern_language/include/test_patterns/test_pattern_pointers.hpp b/tests/pattern_language/include/test_patterns/test_pattern_pointers.hpp index 3ebc802eb..b8259ae8a 100644 --- a/tests/pattern_language/include/test_patterns/test_pattern_pointers.hpp +++ b/tests/pattern_language/include/test_patterns/test_pattern_pointers.hpp @@ -6,7 +6,7 @@ namespace hex::test { class TestPatternPointers : public TestPattern { public: - TestPatternPointers() : TestPattern("Pointers") { + TestPatternPointers() : TestPattern("Pointers") { // placementPointer { auto placementPointer = create("", "placementPointer", 0x0C, sizeof(u8), nullptr); @@ -16,17 +16,14 @@ namespace hex::test { placementPointer->setPointedAtPattern(pointedTo); addPattern(placementPointer); } - } ~TestPatternPointers() override = default; - [[nodiscard]] - std::string getSourceCode() const override { + [[nodiscard]] std::string getSourceCode() const override { return R"( u32 *placementPointer : u8 @ 0x0C; )"; } - }; } \ No newline at end of file diff --git a/tests/pattern_language/include/test_patterns/test_pattern_rvalues.hpp b/tests/pattern_language/include/test_patterns/test_pattern_rvalues.hpp index b7c55bb24..197ebadeb 100644 --- a/tests/pattern_language/include/test_patterns/test_pattern_rvalues.hpp +++ b/tests/pattern_language/include/test_patterns/test_pattern_rvalues.hpp @@ -6,13 +6,11 @@ namespace hex::test { class TestPatternRValues : public TestPattern { public: - TestPatternRValues() : TestPattern("RValues") { - + TestPatternRValues() : TestPattern("RValues") { } ~TestPatternRValues() override = default; - [[nodiscard]] - std::string getSourceCode() const override { + [[nodiscard]] std::string getSourceCode() const override { return R"( union C { u8 y; @@ -34,7 +32,6 @@ namespace hex::test { std::assert(a.b.c.y == a.b.c.array[0], "RValue array access test failed!"); )"; } - }; } \ No newline at end of file diff --git a/tests/pattern_language/include/test_patterns/test_pattern_structs.hpp b/tests/pattern_language/include/test_patterns/test_pattern_structs.hpp index a38d82510..438afd6ea 100644 --- a/tests/pattern_language/include/test_patterns/test_pattern_structs.hpp +++ b/tests/pattern_language/include/test_patterns/test_pattern_structs.hpp @@ -6,7 +6,7 @@ namespace hex::test { class TestPatternStructs : public TestPattern { public: - TestPatternStructs() : TestPattern("Structs") { + TestPatternStructs() : TestPattern("Structs") { auto testStruct = create("TestStruct", "testStruct", 0x100, sizeof(i32) + sizeof(u8[0x10]), nullptr); auto variable = create("s32", "variable", 0x100, sizeof(i32), nullptr); @@ -19,8 +19,7 @@ namespace hex::test { } ~TestPatternStructs() override = default; - [[nodiscard]] - std::string getSourceCode() const override { + [[nodiscard]] std::string getSourceCode() const override { return R"( struct TestStruct { s32 variable; @@ -30,7 +29,6 @@ namespace hex::test { TestStruct testStruct @ 0x100; )"; } - }; } \ No newline at end of file diff --git a/tests/pattern_language/include/test_patterns/test_pattern_succeeding_assert.hpp b/tests/pattern_language/include/test_patterns/test_pattern_succeeding_assert.hpp index dc6d524f7..df79fdd10 100644 --- a/tests/pattern_language/include/test_patterns/test_pattern_succeeding_assert.hpp +++ b/tests/pattern_language/include/test_patterns/test_pattern_succeeding_assert.hpp @@ -6,13 +6,11 @@ namespace hex::test { class TestPatternSucceedingAssert : public TestPattern { public: - TestPatternSucceedingAssert() : TestPattern("SucceedingAssert") { - + TestPatternSucceedingAssert() : TestPattern("SucceedingAssert") { } ~TestPatternSucceedingAssert() override = default; - [[nodiscard]] - std::string getSourceCode() const override { + [[nodiscard]] std::string getSourceCode() const override { return R"( #define MSG "Error" @@ -23,7 +21,6 @@ namespace hex::test { )"; } - }; } \ No newline at end of file diff --git a/tests/pattern_language/include/test_patterns/test_pattern_unions.hpp b/tests/pattern_language/include/test_patterns/test_pattern_unions.hpp index 63fae43e9..afb185c43 100644 --- a/tests/pattern_language/include/test_patterns/test_pattern_unions.hpp +++ b/tests/pattern_language/include/test_patterns/test_pattern_unions.hpp @@ -6,7 +6,7 @@ namespace hex::test { class TestPatternUnions : public TestPattern { public: - TestPatternUnions() : TestPattern("Unions") { + TestPatternUnions() : TestPattern("Unions") { auto testUnion = create("TestUnion", "testUnion", 0x200, sizeof(u128), nullptr); auto array = create("s32", "array", 0x200, sizeof(i32[2]), nullptr); @@ -19,8 +19,7 @@ namespace hex::test { } ~TestPatternUnions() override = default; - [[nodiscard]] - std::string getSourceCode() const override { + [[nodiscard]] std::string getSourceCode() const override { return R"( union TestUnion { s32 array[2]; @@ -30,7 +29,6 @@ namespace hex::test { TestUnion testUnion @ 0x200; )"; } - }; } \ No newline at end of file diff --git a/tests/pattern_language/include/test_provider.hpp b/tests/pattern_language/include/test_provider.hpp index 9e8ed2b6b..9d972bd7a 100644 --- a/tests/pattern_language/include/test_provider.hpp +++ b/tests/pattern_language/include/test_provider.hpp @@ -28,17 +28,17 @@ namespace hex::test { } [[nodiscard]] std::vector> getDataInformation() const override { - return { }; + return {}; } void readRaw(u64 offset, void *buffer, size_t size) override { this->m_testFile.seek(offset); - this->m_testFile.readBuffer(static_cast(buffer), size); + this->m_testFile.readBuffer(static_cast(buffer), size); } void writeRaw(u64 offset, const void *buffer, size_t size) override { this->m_testFile.seek(offset); - this->m_testFile.write(static_cast(buffer), size); + this->m_testFile.write(static_cast(buffer), size); } size_t getActualSize() const override { diff --git a/tests/pattern_language/source/main.cpp b/tests/pattern_language/source/main.cpp index 01e8fde76..88b79439c 100644 --- a/tests/pattern_language/source/main.cpp +++ b/tests/pattern_language/source/main.cpp @@ -24,7 +24,7 @@ void addFunctions() { if (!condition) LogConsole::abortEvaluation(hex::format("assertion failed \"{0}\"", message)); - return { }; + return {}; }); } diff --git a/tests/pattern_language/source/tests.cpp b/tests/pattern_language/source/tests.cpp index e5e5a824b..a3dc1d58b 100644 --- a/tests/pattern_language/source/tests.cpp +++ b/tests/pattern_language/source/tests.cpp @@ -16,18 +16,18 @@ #include "test_patterns/test_pattern_pointers.hpp" std::array Tests = { - TEST(Placement), - TEST(Structs), - TEST(Unions), - TEST(Enums), - TEST(Literals), - TEST(Padding), - TEST(SucceedingAssert), - TEST(FailingAssert), - TEST(Bitfields), - TEST(Math), - TEST(RValues), - TEST(Namespaces), - TEST(ExtraSemicolon), - TEST(Pointers) + TEST(Placement), + TEST(Structs), + TEST(Unions), + TEST(Enums), + TEST(Literals), + TEST(Padding), + TEST(SucceedingAssert), + TEST(FailingAssert), + TEST(Bitfields), + TEST(Math), + TEST(RValues), + TEST(Namespaces), + TEST(ExtraSemicolon), + TEST(Pointers) }; \ No newline at end of file