1
0
mirror of synced 2024-11-24 15:50:16 +01:00

sys: Added clang-format file, formatted entire project

This commit is contained in:
WerWolv 2022-01-24 20:53:17 +01:00
parent a66fec489c
commit 0e08b0226b
168 changed files with 5178 additions and 4866 deletions

178
.clang-format Normal file
View File

@ -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
...

View File

@ -26,4 +26,3 @@ namespace hex {
};
}

View File

@ -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<bool(const std::string&, nlohmann::json&)>;
using Callback = std::function<bool(const std::string &, nlohmann::json &)>;
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<std::string>& value);
void write(const std::string &unlocalizedCategory, const std::string &unlocalizedName, const std::vector<std::string> &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<std::string> read(const std::string &unlocalizedCategory, const std::string &unlocalizedName, const std::vector<std::string>& defaultValue = { });
std::vector<std::string> read(const std::string &unlocalizedCategory, const std::string &unlocalizedName, const std::vector<std::string> &defaultValue = {});
std::map<std::string, std::vector<Entry>>& getEntries();
std::map<std::string, std::vector<Entry>> &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,8 +84,9 @@ 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<Entry>& getEntries();
void add(
Type type, const std::string &command, const std::string &unlocalizedDescription, const DisplayCallback &displayCallback, const ExecuteCallback &executeCallback = [](auto) {});
std::vector<Entry> &getEntries();
}
/* Pattern Language Function Registry. Allows adding of new functions that may be used inside the pattern language */
@ -91,7 +98,7 @@ namespace hex {
constexpr static u32 NoParameters = 0x0000'0000;
using Namespace = std::vector<std::string>;
using Callback = std::function<std::optional<hex::pl::Token::Literal>(hex::pl::Evaluator*, const std::vector<hex::pl::Token::Literal>&)>;
using Callback = std::function<std::optional<hex::pl::Token::Literal>(hex::pl::Evaluator *, const std::vector<hex::pl::Token::Literal> &)>;
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<std::string, ContentRegistry::PatternLanguage::Function>& getFunctions();
std::map<std::string, ContentRegistry::PatternLanguage::Function> &getFunctions();
}
/* View Registry. Allows adding of new windows */
@ -113,14 +120,14 @@ namespace hex {
}
template<hex::derived_from<View> T, typename ... Args>
void add(Args&& ... args) {
template<hex::derived_from<View> T, typename... Args>
void add(Args &&...args) {
return impl::add(new T(std::forward<Args>(args)...));
}
std::map<std::string, View*>& getEntries();
std::map<std::string, View *> &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<impl::Entry>& getEntries();
std::vector<impl::Entry> &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<std::string()>;
using GeneratorFunction = std::function<DisplayFunction(const std::vector<u8>&, std::endian, NumberDisplayStyle)>;
using GeneratorFunction = std::function<DisplayFunction(const std::vector<u8> &, 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<impl::Entry>& getEntries();
std::vector<impl::Entry> &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<dp::Node*()>;
using CreatorFunction = std::function<dp::Node *()>;
struct Entry {
std::string category;
@ -188,20 +195,18 @@ namespace hex {
}
template<hex::derived_from<dp::Node> T, typename ... Args>
void add(const std::string &unlocalizedCategory, const std::string &unlocalizedName, Args&& ... args) {
add(impl::Entry{ unlocalizedCategory.c_str(), unlocalizedName.c_str(),
[=]{
template<hex::derived_from<dp::Node> 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>(args)...);
node->setUnlocalizedName(unlocalizedName);
return node;
}
});
} });
}
void addSeparator();
std::vector<impl::Entry>& getEntries();
std::vector<impl::Entry> &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<std::string, std::string>& getLanguages();
std::map<std::string, std::vector<LanguageDefinition>>& getLanguageDefinitions();
std::map<std::string, std::string> &getLanguages();
std::map<std::string, std::vector<LanguageDefinition>> &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<u32, impl::MainMenuItem>& getMainMenuItems();
std::multimap<u32, impl::MenuItem>& getMenuItems();
std::multimap<u32, impl::MainMenuItem> &getMainMenuItems();
std::multimap<u32, impl::MenuItem> &getMenuItems();
std::vector<impl::DrawCallback>& getWelcomeScreenEntries();
std::vector<impl::DrawCallback>& getFooterItems();
std::vector<impl::DrawCallback>& getToolbarItems();
std::vector<impl::SidebarItem>& getSidebarItems();
std::vector<impl::DrawCallback> &getWelcomeScreenEntries();
std::vector<impl::DrawCallback> &getFooterItems();
std::vector<impl::DrawCallback> &getToolbarItems();
std::vector<impl::SidebarItem> &getSidebarItems();
std::vector<impl::Layout>& getLayouts();
std::vector<impl::Layout> &getLayouts();
}
/* Provider Registry. Allows adding new data providers to be created from the UI */
@ -277,7 +282,7 @@ namespace hex {
template<hex::derived_from<hex::prv::Provider> T>
void add(const std::string &unlocalizedName, bool addToList = true) {
(void) EventManager::subscribe<RequestCreateProvider>([expectedName = unlocalizedName](const std::string &name, hex::prv::Provider **provider){
(void)EventManager::subscribe<RequestCreateProvider>([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<std::string>& getEntries();
const std::vector<std::string> &getEntries();
}
@ -310,7 +315,7 @@ namespace hex {
void add(const std::string &unlocalizedName, const impl::Callback &callback);
std::vector<impl::Entry>& getEntries();
std::vector<impl::Entry> &getEntries();
}
@ -328,7 +333,7 @@ namespace hex {
void add(const std::vector<std::string> &extensions, const impl::Callback &callback);
std::vector<impl::Entry>& getEntries();
std::vector<impl::Entry> &getEntries();
}
};

View File

@ -30,7 +30,7 @@ namespace hex {
}
}
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<typename ... Params>
template<typename... Params>
struct Event : public EventBase {
using Callback = std::function<void(Params...)>;
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<std::pair<EventId, EventBase*>>;
using EventList = std::list<std::pair<EventId, EventBase *>>;
template<typename E>
[[nodiscard]] static EventList::iterator subscribe(typename E::Callback function) {
@ -74,7 +74,7 @@ namespace hex {
template<typename E>
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,7 +84,7 @@ namespace hex {
}
template<typename E>
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<E *>(event))(std::forward<decltype(args)>(args)...);
@ -92,25 +92,27 @@ namespace hex {
}
private:
static std::map<void*, EventList::iterator> s_tokenStore;
static std::map<void *, EventList::iterator> 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<pl::PatternData*>&);
EVENT_DEF(EventWindowClosing, GLFWwindow*);
EVENT_DEF(EventPatternChanged, std::vector<pl::PatternData *> &);
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 &);
}

View File

@ -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<Entry>& getEntries();
std::list<Entry> &getEntries();
};
namespace Provider {
prv::Provider* get();
const std::vector<prv::Provider*>& getProviders();
prv::Provider *get();
const std::vector<prv::Provider *> &getProviders();
bool isValid();
void add(prv::Provider *provider);
template<hex::derived_from<prv::Provider> T>
void add(auto&& ... args) {
void add(auto &&...args) {
add(new T(std::forward<decltype(args)>(args)...));
}

View File

@ -131,9 +131,9 @@ namespace hex {
class Key {
public:
constexpr Key(Keys key) :m_key(static_cast<u32>(key)) { }
constexpr Key(Keys key) : m_key(static_cast<u32>(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);

View File

@ -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;

View File

@ -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<u32, Attribute*>& getConnectedAttributes() { return this->m_connectedAttributes; }
[[nodiscard]] std::map<u32, Attribute *> &getConnectedAttributes() { return this->m_connectedAttributes; }
[[nodiscard]] Node* getParentNode() { return this->m_parentNode; }
[[nodiscard]] Node *getParentNode() { return this->m_parentNode; }
[[nodiscard]] std::optional<std::vector<u8>> &getOutputData() { return this->m_outputData; }
[[nodiscard]] std::optional<std::vector<u8>>& getOutputData() { return this->m_outputData; }
private:
u32 m_id;
IOType m_ioType;
Type m_type;
std::string m_unlocalizedName;
std::map<u32, Attribute*> m_connectedAttributes;
std::map<u32, Attribute *> m_connectedAttributes;
Node *m_parentNode = nullptr;
std::optional<std::vector<u8>> m_outputData;

View File

@ -9,7 +9,10 @@
#include <nlohmann/json_fwd.hpp>
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<Attribute>& getAttributes() { return this->m_attributes; }
[[nodiscard]] const std::string &getUnlocalizedTitle() const { return this->m_unlocalizedTitle; }
[[nodiscard]] std::vector<Attribute> &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<Node*, std::string>;
using NodeError = std::pair<Node *, std::string>;
void resetOutputData() {
for (auto &attribute : this->m_attributes)
@ -56,7 +59,7 @@ namespace hex::dp {
std::set<u32> 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<u8> &data);
};
}

View File

@ -113,21 +113,21 @@ namespace hex {
}
#if defined(_LIBCPP_VERSION) && _LIBCPP_VERSION <= 12000
#if __has_include(<concepts>)
// Make sure we break when derived_from is implemented in libc++. Then we can fix a compatibility version above
#include <concepts>
#endif
#if __has_include(<concepts>)
// Make sure we break when derived_from is implemented in libc++. Then we can fix a compatibility version above
#include <concepts>
#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<class _Dp, class _Bp>
concept derived_from =
__is_base_of(_Bp, _Dp) && __is_convertible_to(const volatile _Dp*, const volatile _Bp*);
template<class _Dp, class _Bp>
concept derived_from =
__is_base_of(_Bp, _Dp) && __is_convertible_to(const volatile _Dp *, const volatile _Bp *);
}
#else
// Assume supported
#include <concepts>
// Assume supported
#include <concepts>
namespace hex {
using std::derived_from;
}
@ -153,10 +153,9 @@ namespace hex {
namespace hex {
template<typename T>
struct always_false : std::false_type {};
struct always_false : std::false_type { };
template<typename T, size_t Size>
concept has_size = sizeof(T) == Size;
}

View File

@ -7,23 +7,25 @@
#include <string>
#include <vector>
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<u8, 16> md5(prv::Provider* &data, u64 offset, size_t size);
std::array<u8, 20> sha1(prv::Provider* &data, u64 offset, size_t size);
std::array<u8, 28> sha224(prv::Provider* &data, u64 offset, size_t size);
std::array<u8, 32> sha256(prv::Provider* &data, u64 offset, size_t size);
std::array<u8, 48> sha384(prv::Provider* &data, u64 offset, size_t size);
std::array<u8, 64> sha512(prv::Provider* &data, u64 offset, size_t size);
std::array<u8, 16> md5(prv::Provider *&data, u64 offset, size_t size);
std::array<u8, 20> sha1(prv::Provider *&data, u64 offset, size_t size);
std::array<u8, 28> sha224(prv::Provider *&data, u64 offset, size_t size);
std::array<u8, 32> sha256(prv::Provider *&data, u64 offset, size_t size);
std::array<u8, 48> sha384(prv::Provider *&data, u64 offset, size_t size);
std::array<u8, 64> sha512(prv::Provider *&data, u64 offset, size_t size);
std::array<u8, 16> md5(const std::vector<u8> &data);
std::array<u8, 20> sha1(const std::vector<u8> &data);

View File

@ -1,9 +1,9 @@
#pragma once
#if __has_include(<capstone/capstone.h>)
#include <capstone/capstone.h>
#include <capstone/capstone.h>
#else
#include <capstone.h>
#include <capstone.h>
#endif
#include <hex.hpp>
@ -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;

View File

@ -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;

View File

@ -6,13 +6,13 @@
namespace hex {
template<typename ... Args>
inline std::string format(std::string_view format, Args ... args) {
template<typename... Args>
inline std::string format(std::string_view format, Args... args) {
return fmt::format(fmt::runtime(format), args...);
}
template<typename ... Args>
inline void print(std::string_view format, Args ... args) {
template<typename... Args>
inline void print(std::string_view format, Args... args) {
fmt::print(fmt::runtime(format), args...);
}

View File

@ -11,7 +11,7 @@ namespace hex {
public:
LanguageDefinition(std::initializer_list<std::pair<std::string, std::string>> entries);
const std::map<std::string, std::string>& getEntries() const;
const std::map<std::string, std::string> &getEntries() const;
private:
std::map<std::string, std::string> 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<std::string, std::string>& getSupportedLanguages();
static const std::map<std::string, std::string> &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 {
}
}

View File

@ -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);
}
}

View File

@ -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);
};
}

View File

@ -8,46 +8,46 @@ namespace hex::log {
FILE *getDestination();
bool isRedirected();
template <typename... T>
void print(fmt::format_string<T...> fmt, T&&... args) {
template<typename... T>
void print(fmt::format_string<T...> fmt, T &&...args) {
fmt::print(getDestination(), fmt, args...);
}
template <typename S, typename... Args>
void print(const fmt::text_style& ts, const S& fmt, const Args&... args) {
template<typename S, typename... Args>
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)
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
#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");

View File

@ -7,7 +7,9 @@
#include <string>
#include <vector>
namespace hex::prv { class Provider; }
namespace hex::prv {
class Provider;
}
namespace hex::magic {

View File

@ -41,19 +41,18 @@ namespace hex {
std::future<Response<std::string>> uploadFile(const std::string &url, const fs::path &filePath, u32 timeout = 2000);
std::future<Response<void>> 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<std::string, std::string> &extraHeaders = { }, const std::string &body = { });
void setCommonSettings(std::string &response, const std::string &url, u32 timeout = 2000, const std::map<std::string, std::string> &extraHeaders = {}, const std::string &body = {});
std::optional<i32> 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;

View File

@ -3,8 +3,8 @@
#if defined(OS_MACOS)
#include <hex/helpers/paths.hpp>
namespace hex {
namespace hex {
std::string getMacExecutableDirectoryPath();
std::string getMacApplicationSupportDirectoryPath();
}
}
#endif

View File

@ -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<RequestChangeWindowTitle>(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<ImHexApi::Bookmarks::Entry>& getBookmarks() {
[[nodiscard]] static const std::list<ImHexApi::Bookmarks::Entry> &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;
}

View File

@ -17,7 +17,9 @@
#include <nlohmann/json_fwd.hpp>
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<typename T>
static T& getVariable(std::string variableName) {
return std::any_cast<T&>(SharedData::sharedVariables[variableName]);
static T &getVariable(std::string variableName) {
return std::any_cast<T &>(SharedData::sharedVariables[variableName]);
}
template<typename T>
@ -56,20 +65,20 @@ namespace hex {
public:
static std::vector<std::function<void()>> deferredCalls;
static std::vector<prv::Provider*> providers;
static std::vector<prv::Provider *> providers;
static u32 currentProvider;
static std::map<std::string, std::vector<ContentRegistry::Settings::Entry>> settingsEntries;
static nlohmann::json settingsJson;
static std::vector<ContentRegistry::CommandPaletteCommands::Entry> commandPaletteCommands;
static std::map<std::string, ContentRegistry::PatternLanguage::Function> patternLanguageFunctions;
static std::map<std::string, View*> views;
static std::map<std::string, View *> views;
static std::vector<ContentRegistry::Tools::impl::Entry> toolsEntries;
static std::vector<ContentRegistry::DataInspector::impl::Entry> dataInspectorEntries;
static u32 patternPaletteOffset;
static std::string popupMessage;
static std::list<ImHexApi::Bookmarks::Entry> bookmarkEntries;
static std::vector<pl::PatternData*> patternData;
static std::vector<pl::PatternData *> patternData;
static u32 selectableFileIndex;
static std::vector<fs::path> selectableFiles;
@ -93,7 +102,7 @@ namespace hex {
static std::map<Shortcut, std::function<void()>> globalShortcuts;
static std::mutex tasksMutex;
static std::list<Task*> runningTasks;
static std::list<Task *> runningTasks;
static std::vector<std::string> providerNames;

View File

@ -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<u8> readBytes(size_t size = 0x1000) const;
@ -45,11 +44,11 @@ namespace hex {
private:
bool m_connected = false;
#if defined(OS_WINDOWS)
#if defined(OS_WINDOWS)
SOCKET m_socket = SOCKET_NONE;
#else
#else
int m_socket = SOCKET_NONE;
#endif
#endif
};
}

View File

@ -20,7 +20,7 @@
#include <nfd.hpp>
#define TOKEN_CONCAT_IMPL(x, y) 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__)
@ -50,7 +50,7 @@ namespace hex {
[[nodiscard]] inline u64 extract(u32 from, u32 to, const std::vector<u8> &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<class... Ts> struct overloaded : Ts... { using Ts::operator()...; };
template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>;
template<class... Ts>
struct overloaded : Ts... { using Ts::operator()...; };
template<class... Ts>
overloaded(Ts...) -> overloaded<Ts...>;
template<size_t Size>
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<size_t Size>
using SizeType = typename SizeTypeImpl<Size>::Type;
@ -102,12 +109,23 @@ namespace hex {
static_assert(always_false<T>::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<class T>
constexpr T bit_width(T x) noexcept {
return std::numeric_limits<T>::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<u8> 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));
}
@ -208,7 +236,8 @@ namespace hex {
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());
}).base(),
s.end());
}
inline void trim(std::string &s) {
@ -240,7 +269,7 @@ namespace hex {
return iter != a.end();
}
template<typename T, typename ... VariantTypes>
template<typename T, typename... VariantTypes>
T get_or(const std::variant<VariantTypes...> &variant, T alt) {
const T *value = std::get_if<T>(&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 F>
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 <typename F>
constexpr ScopeGuard<F> operator+(ScopeGuardOnExit, F&& f) {
template<typename F>
constexpr ScopeGuard<F> operator+(ScopeGuardOnExit, F &&f) {
return ScopeGuard<F>(std::forward<F>(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 F>
class FirstTimeExecute {
public:
constexpr FirstTimeExecute(F func) { func(); }
FirstTimeExecute& operator=(FirstTimeExecute &&) = delete;
FirstTimeExecute &operator=(FirstTimeExecute &&) = delete;
};
enum class FirstTimeExecutor { };
template <typename F>
constexpr FirstTimeExecute<F> operator+(FirstTimeExecutor, F&& f) {
template<typename F>
constexpr FirstTimeExecute<F> operator+(FirstTimeExecutor, F &&f) {
return FirstTimeExecute<F>(std::forward<F>(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 F>
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 <typename F>
constexpr FinalCleanupExecute<F> operator+(FinalCleanupExecutor, F&& f) {
template<typename F>
constexpr FinalCleanupExecute<F> operator+(FinalCleanupExecutor, F &&f) {
return FinalCleanupExecute<F>(std::forward<F>(f));
}

File diff suppressed because it is too large Load Diff

View File

@ -13,7 +13,9 @@
#include <hex/helpers/fmt.hpp>
#include <hex/helpers/concepts.hpp>
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<std::vector<PatternData*>> evaluate(const std::vector<ASTNode*> &ast);
std::optional<std::vector<PatternData *>> evaluate(const std::vector<ASTNode *> &ast);
[[nodiscard]]
LogConsole& getConsole() {
[[nodiscard]] LogConsole &getConsole() {
return this->m_console;
}
struct Scope { PatternData *parent; std::vector<PatternData*>* scope; };
void pushScope(PatternData *parent, std::vector<PatternData*> &scope) {
struct Scope {
PatternData *parent;
std::vector<PatternData *> *scope;
};
void pushScope(PatternData *parent, std::vector<PatternData *> &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<std::string, Token::Literal> getOutVariables() const {
[[nodiscard]] std::map<std::string, Token::Literal> getOutVariables() const {
std::map<std::string, Token::Literal> 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<std::string, ContentRegistry::PatternLanguage::Function>& getCustomFunctions() const {
[[nodiscard]] const std::map<std::string, ContentRegistry::PatternLanguage::Function> &getCustomFunctions() const {
return this->m_customFunctions;
}
[[nodiscard]]
std::vector<Token::Literal>& getStack() {
[[nodiscard]] std::vector<Token::Literal> &getStack() {
return this->m_stack;
}
[[nodiscard]]
const std::vector<Token::Literal>& getStack() const {
[[nodiscard]] const std::vector<Token::Literal> &getStack() const {
return this->m_stack;
}
void createVariable(const std::string &name, ASTNode *type, const std::optional<Token::Literal> &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<Token::Literal> getEnvVariable(const std::string &name) const {
[[nodiscard]] std::optional<Token::Literal> 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<Scope> m_scopes;
std::map<std::string, ContentRegistry::PatternLanguage::Function> m_customFunctions;
std::vector<ASTNode*> m_customFunctionDefinitions;
std::vector<ASTNode *> m_customFunctionDefinitions;
std::vector<Token::Literal> m_stack;
std::map<std::string, Token::Literal> m_envVariables;

View File

@ -16,8 +16,8 @@ namespace hex::pl {
Lexer() = default;
std::optional<std::vector<Token>> lex(const std::string& code);
const std::optional<LexerError>& getError() { return this->m_error; }
std::optional<std::vector<Token>> lex(const std::string &code);
const std::optional<LexerError> &getError() { return this->m_error; }
private:
std::optional<LexerError> m_error;

View File

@ -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<u32, std::string>;
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<EvaluateError>& getLastHardError() { return this->m_lastHardError; };
[[nodiscard]] const std::optional<EvaluateError> &getLastHardError() { return this->m_lastHardError; };
private:
std::vector<std::pair<Level, std::string>> m_consoleLog;

View File

@ -21,15 +21,15 @@ namespace hex::pl {
Parser() = default;
~Parser() = default;
std::optional<std::vector<ASTNode*>> parse(const std::vector<Token> &tokens);
const std::optional<ParseError>& getError() { return this->m_error; }
std::optional<std::vector<ASTNode *>> parse(const std::vector<Token> &tokens);
const std::optional<ParseError> &getError() { return this->m_error; }
private:
std::optional<ParseError> m_error;
TokenIter m_curr;
TokenIter m_originalPosition;
std::unordered_map<std::string, ASTNode*> m_types;
std::unordered_map<std::string, ASTNode *> m_types;
std::vector<TokenIter> m_matchedOptionals;
std::vector<std::vector<std::string>> 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<typename T>
const T& getValue(i32 index) const {
const T &getValue(i32 index) const {
auto value = std::get_if<T>(&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<ASTNode*> parseStatementBody();
ASTNode* parseFunctionConditional();
ASTNode* parseFunctionWhileLoop();
ASTNode* parseFunctionForLoop();
ASTNode *parseFunctionDefinition();
ASTNode *parseFunctionVariableDecl();
ASTNode *parseFunctionStatement();
ASTNode *parseFunctionVariableAssignment();
ASTNode *parseFunctionControlFlowStatement();
std::vector<ASTNode *> 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<ASTNode*> parseNamespace();
std::vector<ASTNode*> 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<ASTNode *> parseNamespace();
std::vector<ASTNode *> parseStatements();
ASTNodeTypeDecl* addType(const std::string &name, ASTNode *node, std::optional<std::endian> endian = std::nullopt);
ASTNodeTypeDecl *addType(const std::string &name, ASTNode *node, std::optional<std::endian> endian = std::nullopt);
std::vector<ASTNode*> parseTillToken(Token::Type endTokenType, const auto value) {
std::vector<ASTNode*> program;
std::vector<ASTNode *> parseTillToken(Token::Type endTokenType, const auto value) {
std::vector<ASTNode *> 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<Setting>(0);
constexpr static auto Not = static_cast<Setting>(1);
@ -173,7 +173,7 @@ namespace hex::pl {
}
template<Setting S = Normal>
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<Setting S = Normal>
bool oneOf(Token::Type type, auto value, auto ... args) {
bool oneOf(Token::Type type, auto value, auto... args) {
if constexpr (S == Normal)
return sequence<Normal>(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;
}
};
}

View File

@ -30,7 +30,7 @@ namespace hex::pl {
template<hex::has_size<1> 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;
};
@ -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,17 +107,20 @@ 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<std::string>& getComment() const { return this->m_comment; }
[[nodiscard]] const std::optional<std::string> &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; }
@ -125,18 +129,17 @@ namespace hex::pl {
[[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<u8> 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,8 +237,7 @@ namespace hex::pl {
template<typename T>
[[nodiscard]] bool areCommonPropertiesEqual(const PatternData &other) const {
return
typeid(other) == typeid(std::remove_cvref_t<T>) &&
return typeid(other) == typeid(std::remove_cvref_t<T>) &&
this->m_offset == other.m_offset &&
this->m_size == other.m_size &&
this->m_hidden == other.m_hidden &&
@ -252,8 +248,7 @@ namespace hex::pl {
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 {
@ -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<decltype(*this)>(other) &&
*static_cast<const PatternDataPointer*>(&other)->m_pointedAt == *this->m_pointedAt;
*static_cast<const PatternDataPointer *>(&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<float*>(&data), data, this->getSize() * 2), *reinterpret_cast<float*>(&data));
this->createDefaultEntry(hex::format("{:e} (0x{:0{}X})", *reinterpret_cast<float *>(&data), data, this->getSize() * 2), *reinterpret_cast<float *>(&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<double*>(&data), data, this->getSize() * 2), *reinterpret_cast<double*>(&data));
this->createDefaultEntry(hex::format("{:e} (0x{:0{}X})", *reinterpret_cast<double *>(&data), data, this->getSize() * 2), *reinterpret_cast<double *>(&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";
}
}
@ -563,11 +582,11 @@ namespace hex::pl {
explicit PatternDataBoolean(u64 offset, Evaluator *evaluator, u32 color = 0)
: 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);
@ -614,17 +633,17 @@ namespace hex::pl {
explicit PatternDataCharacter16(u64 offset, Evaluator *evaluator, u32 color = 0)
: 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<std::codecvt_utf8_utf16<char16_t>, char16_t>{}.to_bytes(character)), literal);
this->createDefaultEntry(hex::format("'{0}'", std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, 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<std::codecvt_utf8_utf16<char16_t>, char16_t>{}.to_bytes(character);
return std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> {}.to_bytes(character);
}
[[nodiscard]] bool operator==(const PatternData &other) const override { return areCommonPropertiesEqual<decltype(*this)>(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<size_t>(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;
});
@ -676,7 +695,7 @@ namespace hex::pl {
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;
});
@ -691,27 +710,27 @@ namespace hex::pl {
PatternDataString16(u64 offset, size_t size, Evaluator *evaluator, u32 color = 0)
: 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<size_t>(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<std::codecvt_utf8_utf16<char16_t>, char16_t>{}.to_bytes(buffer);
auto utf8String = std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, 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<std::codecvt_utf8_utf16<char16_t>, char16_t>{}.to_bytes(buffer);
return std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> {}.to_bytes(buffer);
}
[[nodiscard]] bool operator==(const PatternData &other) const override { return areCommonPropertiesEqual<decltype(*this)>(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<PatternData*> entries;
std::vector<PatternData *> 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<PatternData*>& getEntries() {
[[nodiscard]] const std::vector<PatternData *> &getEntries() {
return this->m_entries;
}
void setEntries(const std::vector<PatternData*> &entries) {
void setEntries(const std::vector<PatternData *> &entries) {
this->m_entries = entries;
if (this->hasOverriddenColor()) {
@ -854,7 +874,7 @@ namespace hex::pl {
if (!areCommonPropertiesEqual<decltype(*this)>(other))
return false;
auto &otherArray = *static_cast<const PatternDataDynamicArray*>(&other);
auto &otherArray = *static_cast<const PatternDataDynamicArray *>(&other);
if (this->m_entries.size() != otherArray.m_entries.size())
return false;
@ -866,11 +886,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_entries.begin(), this->m_entries.end(), [this, offset](PatternData *pattern){
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());
});
@ -881,11 +900,12 @@ namespace hex::pl {
}
private:
std::vector<PatternData*> m_entries;
std::vector<PatternData *> 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) {
@ -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<decltype(*this)>(other))
return false;
auto &otherArray = *static_cast<const PatternDataStaticArray*>(&other);
auto &otherArray = *static_cast<const PatternDataStaticArray *>(&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<u64, u32> &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<PatternData*> & members) {
void setMembers(const std::vector<PatternData *> &members) {
this->m_members.clear();
for (auto &member : members) {
@ -1140,7 +1161,7 @@ namespace hex::pl {
if (!areCommonPropertiesEqual<decltype(*this)>(other))
return false;
auto &otherStruct = *static_cast<const PatternDataStruct*>(&other);
auto &otherStruct = *static_cast<const PatternDataStruct *>(&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<PatternData*> m_members;
std::vector<PatternData*> m_sortedMembers;
std::vector<PatternData *> m_members;
std::vector<PatternData *> 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));
@ -1220,7 +1242,6 @@ namespace hex::pl {
if (!this->isInlined())
ImGui::TreePop();
}
}
void getHighlightedAddresses(std::map<u64, u32> &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<PatternData*> & members) {
void setMembers(const std::vector<PatternData *> &members) {
this->m_members.clear();
for (auto &member : members) {
if (member == nullptr) continue;
@ -1276,7 +1298,7 @@ namespace hex::pl {
if (!areCommonPropertiesEqual<decltype(*this)>(other))
return false;
auto &otherUnion = *static_cast<const PatternDataUnion*>(&other);
auto &otherUnion = *static_cast<const PatternDataUnion *>(&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<PatternData*> m_members;
std::vector<PatternData*> m_sortedMembers;
std::vector<PatternData *> m_members;
std::vector<PatternData *> 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());
@ -1338,8 +1359,8 @@ namespace hex::pl {
return false;
},
[](std::string) { return false; },
[](PatternData*) { return false; }
}, entryValueLiteral);
[](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<decltype(*this)>(other))
return false;
auto &otherEnum = *static_cast<const PatternDataEnum*>(&other);
auto &otherEnum = *static_cast<const PatternDataEnum *>(&other);
if (this->m_enumValues.size() != otherEnum.m_enumValues.size())
return false;
@ -1405,14 +1428,13 @@ namespace hex::pl {
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) {
}
PatternData* clone() override {
PatternData *clone() override {
return new PatternDataBitfieldField(*this);
}
void createEntry(prv::Provider* &provider) override {
void createEntry(prv::Provider *&provider) override {
std::vector<u8> 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<decltype(*this)>(other))
return false;
auto &otherBitfieldField = *static_cast<const PatternDataBitfieldField*>(&other);
auto &otherBitfieldField = *static_cast<const PatternDataBitfieldField *>(&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<u8> 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<PatternData*> &fields) {
void setFields(const std::vector<PatternData *> &fields) {
this->m_fields = fields;
for (auto &field : this->m_fields) {
@ -1567,7 +1589,7 @@ namespace hex::pl {
if (!areCommonPropertiesEqual<decltype(*this)>(other))
return false;
auto &otherBitfield = *static_cast<const PatternDataBitfield*>(&other);
auto &otherBitfield = *static_cast<const PatternDataBitfield *>(&other);
if (this->m_fields.size() != otherBitfield.m_fields.size())
return false;
@ -1580,7 +1602,7 @@ namespace hex::pl {
}
private:
std::vector<PatternData*> m_fields;
std::vector<PatternData *> m_fields;
};
}

View File

@ -12,7 +12,9 @@
#include <hex/pattern_language/log_console.hpp>
#include <hex/pattern_language/token.hpp>
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<std::vector<ASTNode*>> parseString(const std::string &code);
[[nodiscard]]
std::optional<std::vector<PatternData*>> executeString(prv::Provider *provider, const std::string &string, const std::map<std::string, Token::Literal> &envVars = { }, const std::map<std::string, Token::Literal> &inVariables = { });
[[nodiscard]]
std::optional<std::vector<PatternData*>> executeFile(prv::Provider *provider, const fs::path &path, const std::map<std::string, Token::Literal> &envVars = { }, const std::map<std::string, Token::Literal> &inVariables = { });
[[nodiscard]]
const std::vector<ASTNode*>& getCurrentAST() const;
[[nodiscard]] std::optional<std::vector<ASTNode *>> parseString(const std::string &code);
[[nodiscard]] std::optional<std::vector<PatternData *>> executeString(prv::Provider *provider, const std::string &string, const std::map<std::string, Token::Literal> &envVars = {}, const std::map<std::string, Token::Literal> &inVariables = {});
[[nodiscard]] std::optional<std::vector<PatternData *>> executeFile(prv::Provider *provider, const fs::path &path, const std::map<std::string, Token::Literal> &envVars = {}, const std::map<std::string, Token::Literal> &inVariables = {});
[[nodiscard]] const std::vector<ASTNode *> &getCurrentAST() const;
void abort();
[[nodiscard]]
const std::vector<std::pair<LogConsole::Level, std::string>>& getConsoleLog();
[[nodiscard]]
const std::optional<std::pair<u32, std::string>>& getError();
[[nodiscard]]
std::map<std::string, Token::Literal> getOutVariables() const;
[[nodiscard]] const std::vector<std::pair<LogConsole::Level, std::string>> &getConsoleLog();
[[nodiscard]] const std::optional<std::pair<u32, std::string>> &getError();
[[nodiscard]] std::map<std::string, Token::Literal> 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<ASTNode*> m_currAST;
std::vector<ASTNode *> m_currAST;
std::optional<std::pair<u32, std::string>> m_currError;
};

View File

@ -15,12 +15,12 @@ namespace hex::pl {
public:
Preprocessor();
std::optional<std::string> preprocess(const std::string& code, bool initialRun = true);
std::optional<std::string> preprocess(const std::string &code, bool initialRun = true);
void addPragmaHandler(const std::string &pragmaType, const std::function<bool(const std::string&)> &function);
void addPragmaHandler(const std::string &pragmaType, const std::function<bool(const std::string &)> &function);
void addDefaultPragmaHandlers();
const std::pair<u32, std::string>& getError() { return this->m_error; }
const std::pair<u32, std::string> &getError() { return this->m_error; }
private:
using PreprocessorError = std::pair<u32, std::string>;

View File

@ -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<char, bool, u128, i128, double, std::string, PatternData*>;
using Literal = std::variant<char, bool, u128, i128, double, std::string, PatternData *>;
using ValueTypes = std::variant<Keyword, Identifier, Operator, Literal, ValueType, Separator>;
Token(Type type, auto value, u32 lineNumber) : type(type), value(value), lineNumber(lineNumber) {
}
[[nodiscard]] constexpr static inline bool isUnsigned(const ValueType type) {
@ -159,36 +157,32 @@ 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; }
},
[](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; }
},
[](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; }
},
[](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; }
},
[](PatternData *) -> bool { throw std::string("expected integral type, got custom type"); },
[](auto &&value) -> bool { return value != 0; } },
literal);
}
@ -202,31 +196,47 @@ namespace hex::pl {
[](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); }
},
[](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 "< ??? >";
}
}
@ -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,7 +275,6 @@ namespace hex::pl {
Type type;
ValueTypes value;
u32 lineNumber;
};
}

View File

@ -13,9 +13,9 @@ namespace hex::pl {
public:
Validator();
bool validate(const std::vector<ASTNode*>& ast);
bool validate(const std::vector<ASTNode *> &ast);
const std::pair<u32, std::string>& getError() { return this->m_error; }
const std::pair<u32, std::string> &getError() { return this->m_error; }
private:
std::pair<u32, std::string> m_error;
@ -25,7 +25,6 @@ namespace hex::pl {
[[noreturn]] void throwValidateError(std::string_view error, u32 lineNumber) const {
throw ValidatorError(lineNumber, error);
}
};
}

View File

@ -9,9 +9,12 @@
#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; } \
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()

View File

@ -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<u8>& getData() { return this->m_data; }
[[nodiscard]] std::vector<u8> &getData() { return this->m_data; }
private:
u64 m_address = 0;

View File

@ -40,13 +40,13 @@ namespace hex::prv {
void applyOverlays(u64 offset, void *buffer, size_t size);
[[nodiscard]] std::map<u64, u8>& getPatches();
[[nodiscard]] const std::map<u64, u8>& getPatches() const;
[[nodiscard]] std::map<u64, u8> &getPatches();
[[nodiscard]] const std::map<u64, u8> &getPatches() const;
void applyPatches();
[[nodiscard]] Overlay* newOverlay();
[[nodiscard]] Overlay *newOverlay();
void deleteOverlay(Overlay *overlay);
[[nodiscard]] const std::list<Overlay*>& getOverlays();
[[nodiscard]] const std::list<Overlay *> &getOverlays();
[[nodiscard]] u32 getPageCount() const;
[[nodiscard]] u32 getCurrentPage() const;
@ -84,7 +84,7 @@ namespace hex::prv {
u32 m_patchTreeOffset = 0;
std::list<std::map<u64, u8>> m_patches;
std::list<Overlay*> m_overlays;
std::list<Overlay *> m_overlays;
};
}

View File

@ -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<void()> &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<ImU32>(ImGui::GetTime() * 100) % 100 <= static_cast<ImU32>(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<decltype(args)>(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<decltype(args)>(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<decltype(args)>(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<decltype(args)>(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);

View File

@ -36,7 +36,7 @@ namespace hex {
virtual bool shouldProcess() const { return this->isAvailable() && this->getWindowOpenState(); }
static void doLater(std::function<void()> &&function);
static std::vector<std::function<void()>>& getDeferedCalls();
static std::vector<std::function<void()>> &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<void()> &leftButtonFn, const std::function<void()> &rightButtonFn);

View File

@ -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<std::string>& value) {
void ContentRegistry::Settings::write(const std::string &unlocalizedCategory, const std::string &unlocalizedName, const std::vector<std::string> &value) {
auto &json = getSettingsData();
if (!json.contains(unlocalizedCategory))
@ -122,7 +122,7 @@ namespace hex {
return json[unlocalizedCategory][unlocalizedName].get<std::string>();
}
std::vector<std::string> ContentRegistry::Settings::read(const std::string &unlocalizedCategory, const std::string &unlocalizedName, const std::vector<std::string>& defaultValue) {
std::vector<std::string> ContentRegistry::Settings::read(const std::string &unlocalizedCategory, const std::string &unlocalizedName, const std::vector<std::string> &defaultValue) {
auto &json = getSettingsData();
if (!json.contains(unlocalizedCategory))
@ -140,20 +140,20 @@ namespace hex {
}
std::map<std::string, std::vector<ContentRegistry::Settings::Entry>>& ContentRegistry::Settings::getEntries() {
std::map<std::string, std::vector<ContentRegistry::Settings::Entry>> &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<std::string(std::string)> &displayCallback, const std::function<void(std::string)> &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::Entry>& ContentRegistry::CommandPaletteCommands::getEntries() {
std::vector<ContentRegistry::CommandPaletteCommands::Entry> &ContentRegistry::CommandPaletteCommands::getEntries() {
return SharedData::commandPaletteCommands;
}
@ -196,7 +196,7 @@ namespace hex {
getFunctions()[getFunctionName(ns, name)] = Function { parameterCount, func, true };
}
std::map<std::string, ContentRegistry::PatternLanguage::Function>& ContentRegistry::PatternLanguage::getFunctions() {
std::map<std::string, ContentRegistry::PatternLanguage::Function> &ContentRegistry::PatternLanguage::getFunctions() {
return SharedData::patternLanguageFunctions;
}
@ -209,7 +209,7 @@ namespace hex {
getEntries().insert({ view->getUnlocalizedName(), view });
}
std::map<std::string, View*>& ContentRegistry::Views::getEntries() {
std::map<std::string, View *> &ContentRegistry::Views::getEntries() {
return SharedData::views;
}
@ -225,13 +225,13 @@ namespace hex {
/* Tools */
void ContentRegistry::Tools:: add(const std::string &unlocalizedName, const std::function<void()> &function) {
void ContentRegistry::Tools::add(const std::string &unlocalizedName, const std::function<void()> &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::impl::Entry>& ContentRegistry::Tools::getEntries() {
std::vector<ContentRegistry::Tools::impl::Entry> &ContentRegistry::Tools::getEntries() {
return SharedData::toolsEntries;
}
@ -244,7 +244,7 @@ namespace hex {
getEntries().push_back({ unlocalizedName, requiredSize, std::move(function) });
}
std::vector<ContentRegistry::DataInspector::impl::Entry>& ContentRegistry::DataInspector::getEntries() {
std::vector<ContentRegistry::DataInspector::impl::Entry> &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::impl::Entry>& ContentRegistry::DataProcessorNode::getEntries() {
std::vector<ContentRegistry::DataProcessorNode::impl::Entry> &ContentRegistry::DataProcessorNode::getEntries() {
return SharedData::dataProcessorNodes;
}
@ -278,16 +278,15 @@ namespace hex {
getLanguageDefinitions()[languageCode].push_back(definition);
}
std::map<std::string, std::string>& ContentRegistry::Language::getLanguages() {
std::map<std::string, std::string> &ContentRegistry::Language::getLanguages() {
return SharedData::languageNames;
}
std::map<std::string, std::vector<LanguageDefinition>>& ContentRegistry::Language::getLanguageDefinitions() {
std::map<std::string, std::vector<LanguageDefinition>> &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<u32, ContentRegistry::Interface::impl::MainMenuItem>& ContentRegistry::Interface::getMainMenuItems() {
std::multimap<u32, ContentRegistry::Interface::impl::MainMenuItem> &ContentRegistry::Interface::getMainMenuItems() {
return SharedData::mainMenuItems;
}
std::multimap<u32, ContentRegistry::Interface::impl::MenuItem>& ContentRegistry::Interface::getMenuItems() {
std::multimap<u32, ContentRegistry::Interface::impl::MenuItem> &ContentRegistry::Interface::getMenuItems() {
return SharedData::menuItems;
}
std::vector<ContentRegistry::Interface::impl::DrawCallback>& ContentRegistry::Interface::getWelcomeScreenEntries() {
std::vector<ContentRegistry::Interface::impl::DrawCallback> &ContentRegistry::Interface::getWelcomeScreenEntries() {
return SharedData::welcomeScreenEntries;
}
std::vector<ContentRegistry::Interface::impl::DrawCallback>& ContentRegistry::Interface::getFooterItems() {
std::vector<ContentRegistry::Interface::impl::DrawCallback> &ContentRegistry::Interface::getFooterItems() {
return SharedData::footerItems;
}
std::vector<ContentRegistry::Interface::impl::DrawCallback>& ContentRegistry::Interface::getToolbarItems() {
std::vector<ContentRegistry::Interface::impl::DrawCallback> &ContentRegistry::Interface::getToolbarItems() {
return SharedData::toolbarItems;
}
std::vector<ContentRegistry::Interface::impl::SidebarItem>& ContentRegistry::Interface::getSidebarItems() {
std::vector<ContentRegistry::Interface::impl::SidebarItem> &ContentRegistry::Interface::getSidebarItems() {
return SharedData::sidebarItems;
}
std::vector<ContentRegistry::Interface::impl::Layout>& ContentRegistry::Interface::getLayouts() {
std::vector<ContentRegistry::Interface::impl::Layout> &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,7 +381,6 @@ namespace hex {
}
/* File Handlers */
void ContentRegistry::FileHandler::add(const std::vector<std::string> &extensions, const impl::Callback &callback) {

View File

@ -3,6 +3,6 @@
namespace hex {
EventManager::EventList EventManager::s_events;
std::map<void*, EventManager::EventList::iterator> EventManager::s_tokenStore;
std::map<void *, EventManager::EventList::iterator> EventManager::s_tokenStore;
}

View File

@ -15,7 +15,7 @@ namespace hex {
void ImHexApi::Common::restartImHex() {
EventManager::post<RequestCloseImHex>(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::Entry>& ImHexApi::Bookmarks::getEntries() {
std::list<ImHexApi::Bookmarks::Entry> &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<prv::Provider*>& ImHexApi::Provider::getProviders() {
const std::vector<prv::Provider *> &ImHexApi::Provider::getProviders() {
return SharedData::providers;
}

View File

@ -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;
}

View File

@ -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() {

View File

@ -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<u64*>(outputData->data());
return *reinterpret_cast<u64 *>(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<float*>(outputData->data());
return *reinterpret_cast<float *>(outputData->data());
}
void Node::setBufferOnOutput(u32 index, std::vector<u8> data) {

View File

@ -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<std::invocable<unsigned char*, size_t> Func>
void processDataByChunks(prv::Provider* data, u64 offset, size_t size, Func func)
{
template<std::invocable<unsigned char *, size_t> Func>
void processDataByChunks(prv::Provider *data, u64 offset, size_t size, Func func) {
std::array<u8, 512> 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<typename T>
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<typename T>
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,15 +89,14 @@ 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)),
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<uint64_t, 256> table = {0};
table([polynomial, bits]() {
auto reflectedpoly = reflect(polynomial & ((0b10ull << (bits - 1)) - 1), bits);
std::array<uint64_t, 256> table = { 0 };
for (uint32_t i = 0; i < 256; i++) {
uint64_t c = i;
@ -157,7 +149,7 @@ namespace hex::crypt {
};
template<int bits>
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<u8, 16> md5(prv::Provider* &data, u64 offset, size_t size) {
std::array<u8, 16> md5(prv::Provider *&data, u64 offset, size_t size) {
std::array<u8, 16> result = { 0 };
mbedtls_md5_context ctx;
@ -210,7 +202,7 @@ namespace hex::crypt {
return result;
}
std::array<u8, 20> sha1(prv::Provider* &data, u64 offset, size_t size) {
std::array<u8, 20> sha1(prv::Provider *&data, u64 offset, size_t size) {
std::array<u8, 20> result = { 0 };
mbedtls_sha1_context ctx;
@ -242,7 +234,7 @@ namespace hex::crypt {
return result;
}
std::array<u8, 28> sha224(prv::Provider* &data, u64 offset, size_t size) {
std::array<u8, 28> sha224(prv::Provider *&data, u64 offset, size_t size) {
std::array<u8, 28> result = { 0 };
mbedtls_sha256_context ctx;
@ -274,7 +266,7 @@ namespace hex::crypt {
return result;
}
std::array<u8, 32> sha256(prv::Provider* &data, u64 offset, size_t size) {
std::array<u8, 32> sha256(prv::Provider *&data, u64 offset, size_t size) {
std::array<u8, 32> result = { 0 };
mbedtls_sha256_context ctx;
@ -306,7 +298,7 @@ namespace hex::crypt {
return result;
}
std::array<u8, 48> sha384(prv::Provider* &data, u64 offset, size_t size) {
std::array<u8, 48> sha384(prv::Provider *&data, u64 offset, size_t size) {
std::array<u8, 48> result = { 0 };
mbedtls_sha512_context ctx;
@ -338,7 +330,7 @@ namespace hex::crypt {
return result;
}
std::array<u8, 64> sha512(prv::Provider* &data, u64 offset, size_t size) {
std::array<u8, 64> sha512(prv::Provider *&data, u64 offset, size_t size) {
std::array<u8, 64> result = { 0 };
mbedtls_sha512_context ctx;
@ -377,7 +369,7 @@ namespace hex::crypt {
mbedtls_base64_decode(nullptr, 0, &written, reinterpret_cast<const unsigned char *>(input.data()), input.size());
std::vector<u8> output(written, 0x00);
if (mbedtls_base64_decode(output.data(), output.size(), &written, reinterpret_cast<const unsigned char *>(input.data()), input.size()))
return { };
return {};
output.resize(written);
@ -391,7 +383,7 @@ namespace hex::crypt {
std::vector<u8> output(written, 0x00);
if (mbedtls_base64_encode(output.data(), output.size(), &written, reinterpret_cast<const unsigned char *>(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<u8> &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<u8> 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<u8> aesDecrypt(AESMode mode, KeyLength keyLength, const std::vector<u8> &key, std::array<u8, 8> nonce, std::array<u8, 8> iv, const std::vector<u8> &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));

View File

@ -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());

View File

@ -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,7 +54,7 @@ namespace hex {
}
std::vector<u8> File::readBytes(size_t numBytes) {
if (!isValid()) return { };
if (!isValid()) return {};
std::vector<u8> bytes(numBytes ?: getSize());
auto bytesRead = fread(bytes.data(), 1, bytes.size(), this->m_file);
@ -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<char*>(bytes.data()), bytes.size() };
return { reinterpret_cast<char *>(bytes.data()), bytes.size() };
}
void File::write(const u8 *buffer, size_t size) {

View File

@ -11,7 +11,7 @@ namespace hex {
this->m_entries.insert(pair);
}
const std::map<std::string, std::string>& LanguageDefinition::getEntries() const {
const std::map<std::string, std::string> &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<std::string>(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<std::string, std::string>& LangEntry::getSupportedLanguages() {
const std::map<std::string, std::string> &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;
}

View File

@ -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,10 +188,9 @@ 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." },
{"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" },

View File

@ -9,7 +9,7 @@ namespace hex::log {
static File g_loggerFile;
FILE* getDestination() {
FILE *getDestination() {
if (g_loggerFile.isValid())
return g_loggerFile.getHandle();
else

View File

@ -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<u8> &data){
std::string getMIMEType(const std::vector<u8> &data) {
auto magicFiles = getMagicFiles();
if (magicFiles.has_value()) {

View File

@ -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<std::string*>(userdata)->append((char*)contents, size * nmemb);
static size_t writeToString(void *contents, size_t size, size_t nmemb, void *userdata) {
static_cast<std::string *>(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<FILE*>(userdata);
FILE *file = static_cast<FILE *>(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<FILE*>(userdata);
FILE *file = static_cast<FILE *>(userdata);
return fwrite(contents, size, nmemb, file);
}
static CURLcode sslCtxFunction(CURL *ctx, void *sslctx, void *userdata) {
auto* cfg = static_cast<mbedtls_ssl_config*>(sslctx);
auto *cfg = static_cast<mbedtls_ssl_config *>(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<const u8*>(cacert.data()), cacert.size());
mbedtls_x509_crt_parse(&crt, reinterpret_cast<const u8 *>(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<Net*>(contents);
auto &net = *static_cast<Net *>(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<Response<std::string>> 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<Response<nlohmann::json>> 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<std::string> { 400, { } };
return Response<std::string> { 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<FILE*>(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<FILE*>(arg);
fseek(file, offset, origin);
return CURL_SEEKFUNC_OK;
},
[](void *arg) {
return CURL_SEEKFUNC_OK; }, [](void *arg) {
auto file = static_cast<FILE*>(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<Response<void>> 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 {};
}
}

View File

@ -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<u8*>(&address);
auto addressBytes = reinterpret_cast<u8 *>(&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<u16>(result, changeEndianess<u16>(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<u8*>(&address);
auto addressBytes = reinterpret_cast<u8 *>(&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<u16>(result, changeEndianess<u16>(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<u8> &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<u8> &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 {};
}
}

View File

@ -19,27 +19,27 @@
namespace hex {
std::string getExecutablePath() {
#if defined(OS_WINDOWS)
#if defined(OS_WINDOWS)
std::string exePath(MAX_PATH, '\0');
GetModuleFileName(nullptr, exePath.data(), exePath.length());
return exePath;
#elif defined(OS_LINUX)
#elif defined(OS_LINUX)
std::string exePath(PATH_MAX, '\0');
readlink("/proc/self/exe", exePath.data(), PATH_MAX);
return exePath;
#elif defined(OS_MACOS)
#elif defined(OS_MACOS)
return getMacExecutableDirectoryPath();
#else
#else
return "";
#endif
#endif
}
std::vector<fs::path> getPath(ImHexPath path, bool listNonExisting) {
std::vector<fs::path> result;
#if defined(OS_WINDOWS)
#if defined(OS_WINDOWS)
const auto exePath = getExecutablePath();
const auto parentDir = fs::path(exePath).parent_path();
@ -57,60 +57,61 @@ namespace hex {
switch (path) {
case ImHexPath::Patterns:
std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path){
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){
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){
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){
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){
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){
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){
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){
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){
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){
std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path) {
return (path / "logs").string();
});
break;
default: __builtin_unreachable();
default:
__builtin_unreachable();
}
#elif defined(OS_MACOS)
#elif defined(OS_MACOS)
// Get path to special directories
const auto exePath = getExecutablePath();
const fs::path applicationSupportDir(getMacApplicationSupportDirectoryPath());
@ -131,7 +132,7 @@ namespace hex {
result.push_back((applicationSupportDir / "python").string());
break;
case ImHexPath::Plugins:
std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path){
std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path) {
return (path / "plugins").string();
});
break;
@ -153,9 +154,10 @@ namespace hex {
case ImHexPath::Logs:
result.push_back((applicationSupportDir / "logs").string());
break;
default: __builtin_unreachable();
default:
__builtin_unreachable();
}
#else
#else
std::vector<fs::path> configDirs = xdg::ConfigDirs();
std::vector<fs::path> dataDirs = xdg::DataDirs();
@ -172,57 +174,48 @@ namespace hex {
switch (path) {
case ImHexPath::Patterns:
std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result),
[](auto p) { return (p / "patterns").string(); });
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(); });
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(); });
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(); });
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(); });
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(); });
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(); });
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(); });
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(); });
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(); });
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(); });
std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result), [](auto p) { return (p / "logs").string(); });
break;
default: __builtin_unreachable();
default:
__builtin_unreachable();
}
#endif
#endif
if (!listNonExisting) {
result.erase(std::remove_if(result.begin(), result.end(), [](const auto& path){
result.erase(std::remove_if(result.begin(), result.end(), [](const auto &path) {
return !fs::is_directory(path);
}), result.end());
}),
result.end());
}
return result;

View File

@ -18,11 +18,18 @@ namespace hex {
std::list<ImHexApi::Bookmarks::Entry> 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);

View File

@ -6,20 +6,20 @@ namespace hex {
std::vector<std::function<void()>> SharedData::deferredCalls;
std::vector<prv::Provider*> SharedData::providers;
std::vector<prv::Provider *> SharedData::providers;
u32 SharedData::currentProvider;
std::map<std::string, std::vector<ContentRegistry::Settings::Entry>> SharedData::settingsEntries;
nlohmann::json SharedData::settingsJson;
std::vector<ContentRegistry::CommandPaletteCommands::Entry> SharedData::commandPaletteCommands;
std::map<std::string, ContentRegistry::PatternLanguage::Function> SharedData::patternLanguageFunctions;
std::map<std::string, View*> SharedData::views;
std::map<std::string, View *> SharedData::views;
std::vector<ContentRegistry::Tools::impl::Entry> SharedData::toolsEntries;
std::vector<ContentRegistry::DataInspector::impl::Entry> SharedData::dataInspectorEntries;
u32 SharedData::patternPaletteOffset;
std::string SharedData::popupMessage;
std::list<ImHexApi::Bookmarks::Entry> SharedData::bookmarkEntries;
std::vector<pl::PatternData*> SharedData::patternData;
std::vector<pl::PatternData *> SharedData::patternData;
u32 SharedData::selectableFileIndex;
std::vector<fs::path> SharedData::selectableFiles;
@ -44,7 +44,7 @@ namespace hex {
std::map<Shortcut, std::function<void()>> SharedData::globalShortcuts;
std::mutex SharedData::tasksMutex;
std::list<Task*> SharedData::runningTasks;
std::list<Task *> SharedData::runningTasks;
std::vector<std::string> SharedData::providerNames;

View File

@ -6,7 +6,7 @@
namespace hex {
Socket::Socket(const std::string &address, u16 port) {
#if defined(OS_WINDOWS)
#if defined(OS_WINDOWS)
FIRST_TIME {
WSAData wsa;
WSAStartup(MAKEWORD(2, 2), &wsa);
@ -15,7 +15,7 @@ namespace hex {
FINAL_CLEANUP {
WSACleanup();
};
#endif
#endif
this->connect(address, port);
}
@ -34,7 +34,7 @@ namespace hex {
void Socket::writeBytes(const std::vector<u8> &bytes) const {
if (!this->isConnected()) return;
::send(this->m_socket, reinterpret_cast<const char*>(bytes.data()), bytes.size(), 0);
::send(this->m_socket, reinterpret_cast<const char *>(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<char *>(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)
#if defined(OS_WINDOWS)
client.sin_addr.S_un.S_addr = ::inet_addr(address.c_str());
#else
#else
client.sin_addr.s_addr = ::inet_addr(address.c_str());
#endif
#endif
this->m_connected = ::connect(this->m_socket, reinterpret_cast<sockaddr*>(&client), sizeof(client)) == 0;
this->m_connected = ::connect(this->m_socket, reinterpret_cast<sockaddr *>(&client), sizeof(client)) == 0;
}
void Socket::disconnect() {
if (this->m_socket != SOCKET_NONE) {
#if defined(OS_WINDOWS)
#if defined(OS_WINDOWS)
closesocket(this->m_socket);
#else
#else
close(this->m_socket);
#endif
#endif
}
this->m_connected = false;

View File

@ -8,11 +8,11 @@
#include <hex/helpers/fmt.hpp>
#include <hex/helpers/shared_data.hpp>
#if defined (OS_WINDOWS)
#if defined(OS_WINDOWS)
#include <windows.h>
#elif defined (OS_LINUX)
#elif defined(OS_LINUX)
#include <unistd.h>
#elif defined (OS_MACOS)
#elif defined(OS_MACOS)
#include <CoreFoundation/CFBundle.h>
#include <ApplicationServices/ApplicationServices.h>
#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<char>(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<char>(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
#else
#warning "Unknown OS, can't open webpages"
#endif
#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)
#if defined(OS_WINDOWS)
ShellExecute(nullptr, "open", url.c_str(), nullptr, nullptr, SW_SHOWNORMAL);
#elif defined(OS_MACOS)
CFURLRef urlRef = CFURLCreateWithBytes(nullptr, reinterpret_cast<u8*>(url.data()), url.length(), kCFStringEncodingASCII, nullptr);
#elif defined(OS_MACOS)
CFURLRef urlRef = CFURLCreateWithBytes(nullptr, reinterpret_cast<u8 *>(url.data()), url.length(), kCFStringEncodingASCII, nullptr);
LSOpenCFURLRef(urlRef, nullptr);
CFRelease(urlRef);
#elif defined(OS_LINUX)
#elif defined(OS_LINUX)
system(hex::format("xdg-open {0}", url).c_str());
#else
#else
#warning "Unknown OS, can't open webpages"
#endif
#endif
}
void openFileBrowser(const std::string &title, DialogMode mode, const std::vector<nfdfilteritem_t> &validExtensions, const std::function<void(fs::path)> &callback, const std::string &defaultPath) {
@ -223,7 +272,8 @@ namespace hex {
case DialogMode::Folder:
result = NFD::PickFolder(outPath, defaultPath.c_str());
break;
default: __builtin_unreachable();
default:
__builtin_unreachable();
}
if (result == NFD_OKAY) {
@ -265,11 +315,11 @@ namespace hex {
result = (sign << 31) | ((exponent + (0x7F - 15)) << 23) | (mantissa << 13);
}
return reinterpret_cast<float&>(result);
return reinterpret_cast<float &>(result);
}
bool isProcessElevated() {
#if defined (OS_WINDOWS)
#if defined(OS_WINDOWS)
bool elevated = false;
HANDLE token = INVALID_HANDLE_VALUE;
@ -286,9 +336,9 @@ namespace hex {
return elevated;
#elif defined(OS_LINUX) || defined (OS_MACOS)
#elif defined(OS_LINUX) || defined(OS_MACOS)
return getuid() < 0 || getuid() != geteuid();
#endif
#endif
}
}

View File

@ -30,8 +30,8 @@ namespace hex::pl {
pattern = new PatternDataBoolean(0, this);
else if (std::get_if<char>(&value.value()) != nullptr)
pattern = new PatternDataCharacter(0, this);
else if (std::get_if<PatternData*>(&value.value()) != nullptr)
pattern = std::get<PatternData*>(value.value())->clone();
else if (std::get_if<PatternData *>(&value.value()) != nullptr)
pattern = std::get<PatternData *>(value.value())->clone();
else if (std::get_if<std::string>(&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;
{
@ -80,48 +80,47 @@ namespace hex::pl {
Token::Literal castedLiteral = std::visit(overloaded {
[&](double &value) -> Token::Literal {
if (dynamic_cast<PatternDataUnsigned*>(pattern))
if (dynamic_cast<PatternDataUnsigned *>(pattern))
return u128(value) & bitmask(pattern->getSize() * 8);
else if (dynamic_cast<PatternDataSigned*>(pattern))
else if (dynamic_cast<PatternDataSigned *>(pattern))
return i128(value) & bitmask(pattern->getSize() * 8);
else if (dynamic_cast<PatternDataFloat*>(pattern))
else if (dynamic_cast<PatternDataFloat *>(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<PatternDataString*>(pattern))
if (dynamic_cast<PatternDataString *>(pattern))
return value;
else
LogConsole::abortEvaluation(hex::format("cannot cast type 'string' to type '{}'", pattern->getTypeName()));
},
[&](PatternData * const &value) -> Token::Literal {
[&](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<PatternDataUnsigned*>(pattern) || dynamic_cast<PatternDataEnum*>(pattern))
if (dynamic_cast<PatternDataUnsigned *>(pattern) || dynamic_cast<PatternDataEnum *>(pattern))
return u128(value) & bitmask(pattern->getSize() * 8);
else if (dynamic_cast<PatternDataSigned*>(pattern))
else if (dynamic_cast<PatternDataSigned *>(pattern))
return i128(value) & bitmask(pattern->getSize() * 8);
else if (dynamic_cast<PatternDataCharacter*>(pattern))
else if (dynamic_cast<PatternDataCharacter *>(pattern))
return char(value);
else if (dynamic_cast<PatternDataBoolean*>(pattern))
else if (dynamic_cast<PatternDataBoolean *>(pattern))
return bool(value);
else if (dynamic_cast<PatternDataFloat*>(pattern))
else if (dynamic_cast<PatternDataFloat *>(pattern))
return pattern->getSize() == sizeof(float) ? double(float(value)) : value;
else
LogConsole::abortEvaluation(hex::format("cannot cast integer literal to type '{}'", pattern->getTypeName()));
}
}, value);
} },
value);
this->getStack()[pattern->getOffset()] = castedLiteral;
}
std::optional<std::vector<PatternData*>> Evaluator::evaluate(const std::vector<ASTNode*> &ast) {
std::optional<std::vector<PatternData *>> Evaluator::evaluate(const std::vector<ASTNode *> &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<PatternData*> patterns;
std::vector<PatternData *> patterns;
try {
this->setCurrentControlFlowStatement(ControlFlowStatement::None);
pushScope(nullptr, patterns);
for (auto node : ast) {
if (dynamic_cast<ASTNodeTypeDecl*>(node)) {
;// Don't create patterns from type declarations
} else if (dynamic_cast<ASTNodeFunctionCall*>(node)) {
if (dynamic_cast<ASTNodeTypeDecl *>(node)) {
; // Don't create patterns from type declarations
} else if (dynamic_cast<ASTNodeFunctionCall *>(node)) {
delete node->evaluate(this);
} else if (dynamic_cast<ASTNodeFunctionDefinition*>(node)) {
} else if (dynamic_cast<ASTNodeFunctionDefinition *>(node)) {
this->m_customFunctionDefinitions.push_back(node->evaluate(this));
} else if (auto varDeclNode = dynamic_cast<ASTNodeVariableDecl*>(node)) {
} else if (auto varDeclNode = dynamic_cast<ASTNodeVariableDecl *>(node)) {
auto pattern = node->createPatterns(this).front();
if (varDeclNode->getPlacementOffset() == nullptr) {
@ -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);

View File

@ -10,7 +10,7 @@ namespace hex::pl {
#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<bool(char)> predicate) {
std::string matchTillInvalid(const char *characters, std::function<bool(char)> 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<std::pair<char, size_t>> 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<std::pair<std::string, size_t>> 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<std::pair<char, size_t>> 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<std::vector<Token>> Lexer::lex(const std::string& code) {
std::optional<std::vector<Token>> Lexer::lex(const std::string &code) {
std::vector<Token> 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())
@ -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 {};
}

View File

@ -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<const ASTNode*>(node)->getLineNumber(), message);
[[noreturn]] void LogConsole::abortEvaluation(const std::string &message, const ASTNode *node) {
throw EvaluateError(static_cast<const ASTNode *>(node)->getLineNumber(), message);
}
void LogConsole::clear() {
this->m_consoleLog.clear();
this->m_lastHardError = { };
this->m_lastHardError = {};
}
}

View File

@ -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<ASTNode*> params;
std::vector<ASTNode *> params;
auto paramCleanup = SCOPE_GUARD {
for (auto &param : 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<Token::Literal>(-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) {
@ -82,8 +80,7 @@ namespace hex::pl {
return create(new ASTNodeScopeResolution(this->m_types[typeName]->clone(), getValue<Token::Identifier>(-1).get()));
}
}
else
} else
break;
}
@ -91,7 +88,7 @@ namespace hex::pl {
}
// <Identifier[.]...>
ASTNode* Parser::parseRValue(ASTNodeRValue::Path &path) {
ASTNode *Parser::parseRValue(ASTNodeRValue::Path &path) {
if (peek(IDENTIFIER, -1))
path.push_back(getValue<Token::Identifier>(-1).get());
else if (peek(KEYWORD_PARENT, -1))
@ -115,7 +112,7 @@ namespace hex::pl {
}
// <Integer|((parseMathematicalExpression))>
ASTNode* Parser::parseFactor() {
ASTNode *Parser::parseFactor() {
if (MATCHES(sequence(INTEGER)))
return new ASTNodeLiteral(getValue<Token::Literal>(-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<ASTNodeBuiltinType*>(type->getType());
auto builtinType = dynamic_cast<ASTNodeBuiltinType *>(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<Token::Operator>(-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<Token::Operator>(-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<Token::Identifier>(-2).get();
std::vector<std::pair<std::string, ASTNode*>> params;
std::vector<std::pair<std::string, ASTNode *>> params;
// Parse parameter list
bool hasParams = !peek(SEPARATOR_ROUNDBRACKETCLOSE);
@ -456,7 +452,7 @@ namespace hex::pl {
// Parse function body
std::vector<ASTNode*> body;
std::vector<ASTNode *> 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<Token::Identifier>(-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<ASTNode*> Parser::parseStatementBody() {
std::vector<ASTNode*> body;
std::vector<ASTNode *> Parser::parseStatementBody() {
std::vector<ASTNode *> 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<ASTNode*> trueBody, falseBody;
std::vector<ASTNode *> 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<ASTNode*> body;
std::vector<ASTNode *> 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<ASTNode*> body;
std::vector<ASTNode *> 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<ASTNode*> trueBody, falseBody;
std::vector<ASTNode *> 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] <Identifier|u8|u16|u32|u64|u128|s8|s16|s32|s64|s128|float|double|str>
ASTNodeTypeDecl* Parser::parseType(bool allowFunctionTypes) {
ASTNodeTypeDecl *Parser::parseType(bool allowFunctionTypes) {
std::optional<std::endian> endian;
if (MATCHES(sequence(KEYWORD_LE)))
@ -736,13 +729,12 @@ namespace hex::pl {
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<Token::ValueType>(-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<ASTNode*> variables;
auto variableCleanup = SCOPE_GUARD { for (auto var : variables) delete var; };
std::vector<ASTNode *> variables;
auto variableCleanup = SCOPE_GUARD {
for (auto var : variables) delete var;
};
do {
variables.push_back(create(new ASTNodeVariableDecl(getValue<Token::Identifier>(-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<Token::Identifier>(-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<Token::Identifier>(-2).get();
auto sizeType = parseType();
{
auto builtinType = dynamic_cast<ASTNodeBuiltinType*>(sizeType->getType());
auto builtinType = dynamic_cast<ASTNodeBuiltinType *>(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<Token::Identifier>(-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<Token::Identifier>(-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) { <<Identifier|Identifier = (parseMathematicalExpression)[,]>...> }
ASTNode* Parser::parseEnum() {
ASTNode *Parser::parseEnum() {
auto typeName = getValue<Token::Identifier>(-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<Token::Identifier>(-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,13 +1004,16 @@ namespace hex::pl {
}
// bitfield Identifier { <Identifier : (parseMathematicalExpression)[;]...> }
ASTNode* Parser::parseBitfield() {
ASTNode *Parser::parseBitfield() {
std::string typeName = getValue<Token::Identifier>(-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))) {
@ -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<Token::Identifier>(-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<Token::Identifier>(-2).get();
auto sizeType = parseType();
auto sizeCleanup = SCOPE_GUARD { delete sizeType; };
{
auto builtinType = dynamic_cast<ASTNodeBuiltinType*>(sizeType->getType());
auto builtinType = dynamic_cast<ASTNodeBuiltinType *>(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<ASTNode*> Parser::parseNamespace() {
std::vector<ASTNode*> statements;
std::vector<ASTNode *> Parser::parseNamespace() {
std::vector<ASTNode *> 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<ASTNode*> Parser::parseStatements() {
std::vector<ASTNode *> 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,14 +1198,15 @@ 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<std::endian> endian) {
ASTNodeTypeDecl *Parser::addType(const std::string &name, ASTNode *node, std::optional<std::endian> endian) {
auto typeName = getNamespacePrefixedName(name);
if (this->m_types.contains(typeName))
@ -1216,7 +1219,7 @@ namespace hex::pl {
}
// <(parseNamespace)...> EndOfProgram
std::optional<std::vector<ASTNode*>> Parser::parse(const std::vector<Token> &tokens) {
std::optional<std::vector<ASTNode *>> Parser::parse(const std::vector<Token> &tokens) {
this->m_curr = tokens.begin();
this->m_types.clear();
@ -1235,7 +1238,7 @@ namespace hex::pl {
this->m_error = e;
}
return { };
return {};
}
}

View File

@ -94,29 +94,29 @@ namespace hex::pl {
delete this->m_validator;
}
std::optional<std::vector<ASTNode*>> PatternLanguage::parseString(const std::string &code) {
std::optional<std::vector<ASTNode *>> 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<std::vector<PatternData*>> PatternLanguage::executeString(prv::Provider *provider, const std::string &code, const std::map<std::string, Token::Literal> &envVars, const std::map<std::string, Token::Literal> &inVariables) {
std::optional<std::vector<PatternData *>> PatternLanguage::executeString(prv::Provider *provider, const std::string &code, const std::map<std::string, Token::Literal> &envVars, const std::map<std::string, Token::Literal> &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<std::vector<PatternData*>> PatternLanguage::executeFile(prv::Provider *provider, const fs::path &path, const std::map<std::string, Token::Literal> &envVars, const std::map<std::string, Token::Literal> &inVariables) {
std::optional<std::vector<PatternData *>> PatternLanguage::executeFile(prv::Provider *provider, const fs::path &path, const std::map<std::string, Token::Literal> &envVars, const std::map<std::string, Token::Literal> &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<ASTNode*> &PatternLanguage::getCurrentAST() const {
const std::vector<ASTNode *> &PatternLanguage::getCurrentAST() const {
return this->m_currAST;
}
[[nodiscard]]
std::map<std::string, Token::Literal> PatternLanguage::getOutVariables() const {
[[nodiscard]] std::map<std::string, Token::Literal> PatternLanguage::getOutVariables() const {
return this->m_evaluator->getOutVariables();
}
const std::vector<std::pair<LogConsole::Level, std::string>>& PatternLanguage::getConsoleLog() {
const std::vector<std::pair<LogConsole::Level, std::string>> &PatternLanguage::getConsoleLog() {
return this->m_evaluator->getConsole().getLog();
}
const std::optional<std::pair<u32, std::string>>& PatternLanguage::getError() {
const std::optional<std::pair<u32, std::string>> &PatternLanguage::getError() {
return this->m_currError;
}

View File

@ -9,10 +9,9 @@
namespace hex::pl {
Preprocessor::Preprocessor() {
}
std::optional<std::string> Preprocessor::preprocess(const std::string& code, bool initialRun) {
std::optional<std::string> Preprocessor::preprocess(const std::string &code, bool initialRun) {
u32 offset = 0;
u32 lineNumber = 1;
bool isInString = false;
@ -196,7 +195,7 @@ namespace hex::pl {
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<bool(const std::string&)> &function) {
void Preprocessor::addPragmaHandler(const std::string &pragmaType, const std::function<bool(const std::string &)> &function) {
if (!this->m_pragmaHandlers.contains(pragmaType))
this->m_pragmaHandlers.emplace(pragmaType, function);
}

View File

@ -10,10 +10,9 @@
namespace hex::pl {
Validator::Validator() {
}
bool Validator::validate(const std::vector<ASTNode*>& ast) {
bool Validator::validate(const std::vector<ASTNode *> &ast) {
std::unordered_set<std::string> 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<ASTNodeVariableDecl*>(node); variableDeclNode != nullptr) {
if (auto variableDeclNode = dynamic_cast<ASTNodeVariableDecl *>(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<ASTNodeTypeDecl*>(node); typeDeclNode != nullptr) {
} else if (auto typeDeclNode = dynamic_cast<ASTNodeTypeDecl *>(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<ASTNodeStruct*>(node); structNode != nullptr) {
} else if (auto structNode = dynamic_cast<ASTNodeStruct *>(node); structNode != nullptr) {
this->validate(structNode->getMembers());
} else if (auto unionNode = dynamic_cast<ASTNodeUnion*>(node); unionNode != nullptr) {
} else if (auto unionNode = dynamic_cast<ASTNodeUnion *>(node); unionNode != nullptr) {
this->validate(unionNode->getMembers());
} else if (auto enumNode = dynamic_cast<ASTNodeEnum*>(node); enumNode != nullptr) {
} else if (auto enumNode = dynamic_cast<ASTNodeEnum *>(node); enumNode != nullptr) {
std::unordered_set<std::string> enumIdentifiers;
for (auto &[name, value] : enumNode->getEntries()) {
if (!enumIdentifiers.insert(name).second)

View File

@ -60,12 +60,12 @@ namespace hex::prv {
i128 overlapMin = std::max(offset, overlayOffset);
i128 overlapMax = std::min(offset + size, overlayOffset + overlaySize);
if (overlapMax > overlapMin)
std::memcpy(static_cast<u8*>(buffer) + std::max<i128>(0, overlapMin - offset), overlay->getData().data() + std::max<i128>(0, overlapMin - overlayOffset), overlapMax - overlapMin);
std::memcpy(static_cast<u8 *>(buffer) + std::max<i128>(0, overlapMin - offset), overlay->getData().data() + std::max<i128>(0, overlapMin - overlayOffset), overlapMax - overlapMin);
}
}
std::map<u64, u8>& Provider::getPatches() {
std::map<u64, u8> &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<u64, u8>& Provider::getPatches() const {
const std::map<u64, u8> &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<Overlay*>& Provider::getOverlays() {
const std::list<Overlay *> &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<const u8*>(buffer)[i];
getPatches()[offset + i] = reinterpret_cast<const u8 *>(buffer)[i];
}
void Provider::createUndoPoint() {
@ -190,11 +190,9 @@ namespace hex::prv {
}
void Provider::drawLoadInterface() {
}
void Provider::drawInterface() {
}
}

View File

@ -16,19 +16,19 @@
namespace ImGui {
int UpdateStringSizeCallback(ImGuiInputTextCallbackData *data) {
auto &mathInput = *static_cast<std::string*>(data->UserData);
auto &mathInput = *static_cast<std::string *>(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);
@ -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,13 +125,13 @@ 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);
@ -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);
@ -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,21 +237,21 @@ namespace ImGui {
}
ImU32 GetCustomColorU32(ImGuiCustomCol idx, float alpha_mul) {
auto& customData = *static_cast<ImHexCustomData*>(GImGui->IO.UserData);
auto &customData = *static_cast<ImHexCustomData *>(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<ImHexCustomData*>(GImGui->IO.UserData);
auto &customData = *static_cast<ImHexCustomData *>(GImGui->IO.UserData);
ImVec4 c = customData.Colors[idx];
c.w *= GImGui->Style.Alpha * alpha_mul;
return c;
}
void StyleCustomColorsDark() {
auto &colors = static_cast<ImHexCustomData*>(GImGui->IO.UserData)->Colors;
auto &colors = static_cast<ImHexCustomData *>(GImGui->IO.UserData)->Colors;
colors[ImGuiCustomCol_DescButton] = ImColor(20, 20, 20);
colors[ImGuiCustomCol_DescButtonHovered] = ImColor(40, 40, 40);
@ -269,7 +269,7 @@ namespace ImGui {
}
void StyleCustomColorsLight() {
auto &colors = static_cast<ImHexCustomData*>(GImGui->IO.UserData)->Colors;
auto &colors = static_cast<ImHexCustomData *>(GImGui->IO.UserData)->Colors;
colors[ImGuiCustomCol_DescButton] = ImColor(230, 230, 230);
colors[ImGuiCustomCol_DescButtonHovered] = ImColor(210, 210, 210);
@ -287,7 +287,7 @@ namespace ImGui {
}
void StyleCustomColorsClassic() {
auto &colors = static_cast<ImHexCustomData*>(GImGui->IO.UserData)->Colors;
auto &colors = static_cast<ImHexCustomData *>(GImGui->IO.UserData)->Colors;
colors[ImGuiCustomCol_DescButton] = ImColor(40, 40, 80);
colors[ImGuiCustomCol_DescButtonHovered] = ImColor(60, 60, 100);
@ -308,7 +308,7 @@ namespace ImGui {
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)
#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);
@ -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);

View File

@ -16,7 +16,7 @@ namespace hex {
return ImHexApi::Provider::isValid() && ImHexApi::Provider::get()->isAvailable();
}
std::vector<std::function<void()>>& View::getDeferedCalls() {
std::vector<std::function<void()>> &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;
}

View File

@ -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,16 +25,17 @@ 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;
@ -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;
}

View File

@ -18,5 +18,5 @@ namespace hex::init {
std::vector<Task> getInitTasks();
std::vector<Task> getExitTasks();
std::vector<Argument>& getInitArguments();
std::vector<Argument> &getInitArguments();
}

View File

@ -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;

View File

@ -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());
}

View File

@ -69,7 +69,7 @@ namespace hex::init {
bool WindowSplash::loop() {
auto splash = romfs::get("splash.png");
ImGui::Texture splashTexture = ImGui::LoadImageFromMemory(reinterpret_cast<const ImU8*>(splash.data()), splash.size());
ImGui::Texture splashTexture = ImGui::LoadImageFromMemory(reinterpret_cast<const ImU8 *>(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)
#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
#else
drawList->AddText(ImVec2(15, 140) * scale, ImColor(0xFF, 0xFF, 0xFF, 0xFF), hex::format("{0}", IMHEX_VERSION).c_str());
#endif
#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)
// 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
#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;

View File

@ -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
};
@ -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;
}
@ -284,8 +281,8 @@ namespace hex::init {
std::vector<Task> getInitTasks() {
return {
{ "Checking for updates...", checkForUpdates },
{ "Downloading information...", downloadInformation },
{"Checking for updates...", checkForUpdates },
{ "Downloading information...", downloadInformation},
{ "Creating directories...", createDirectories },
{ "Loading settings...", loadSettings },
{ "Loading plugins...", loadPlugins },
@ -295,13 +292,13 @@ namespace hex::init {
std::vector<Task> getExitTasks() {
return {
{ "Saving settings...", storeSettings },
{ "Cleaning up shared data...", deleteSharedData },
{"Saving settings...", storeSettings },
{ "Cleaning up shared data...", deleteSharedData},
{ "Unloading plugins...", unloadPlugins },
};
}
std::vector<Argument>& getInitArguments() {
std::vector<Argument> &getInitArguments() {
static std::vector<Argument> initArguments;
return initArguments;

View File

@ -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

View File

@ -9,7 +9,7 @@
#include <sys/wait.h>
#include <unistd.h>
namespace hex {
namespace hex {
void Window::initNative() {
if (!isatty(STDOUT_FILENO)) {
@ -19,14 +19,14 @@
void Window::setupNativeWindow() {
bool themeFollowSystem = ContentRegistry::Settings::getSetting("hex.builtin.setting.interface", "hex.builtin.setting.interface.color") == 0;
EventManager::subscribe<EventOSThemeChanged>(this, [themeFollowSystem]{
EventManager::subscribe<EventOSThemeChanged>(this, [themeFollowSystem] {
if (!themeFollowSystem) return;
std::array<char, 128> 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");
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)
@ -43,17 +43,14 @@
}
void Window::beginNativeWindowFrame() {
}
void Window::endNativeWindowFrame() {
}
void Window::drawTitleBar() {
}
}
}
#endif

View File

@ -7,7 +7,7 @@
#include <nlohmann/json.hpp>
#include <unistd.h>
namespace hex {
namespace hex {
void Window::initNative() {
if (!isatty(STDOUT_FILENO)) {
@ -17,7 +17,7 @@
void Window::setupNativeWindow() {
bool themeFollowSystem = ContentRegistry::Settings::getSetting("hex.builtin.setting.interface", "hex.builtin.setting.interface.color") == 0;
EventManager::subscribe<EventOSThemeChanged>(this, [themeFollowSystem]{
EventManager::subscribe<EventOSThemeChanged>(this, [themeFollowSystem] {
if (!themeFollowSystem) return;
// TODO: Implement this when MacOS build is working again
@ -29,17 +29,14 @@
}
void Window::beginNativeWindowFrame() {
}
void Window::endNativeWindowFrame() {
}
void Window::drawTitleBar() {
}
}
}
#endif

View File

@ -21,7 +21,7 @@
#include <dwmapi.h>
#include <windowsx.h>
namespace hex {
namespace hex {
static LONG_PTR g_oldWndProc;
static float g_titleBarHeight;
@ -33,8 +33,9 @@
case WM_NCACTIVATE:
case WM_NCPAINT:
return DefWindowProcW(hwnd, uMsg, wParam, lParam);
case WM_NCCALCSIZE: {
RECT &rect = *reinterpret_cast<RECT*>(lParam);
case WM_NCCALCSIZE:
{
RECT &rect = *reinterpret_cast<RECT *>(lParam);
RECT client = rect;
CallWindowProc((WNDPROC)g_oldWndProc, hwnd, uMsg, wParam, lParam);
@ -54,7 +55,8 @@
return 0;
}
case WM_SETCURSOR: {
case WM_SETCURSOR:
{
auto cursorPos = LOWORD(lParam);
switch (cursorPos) {
@ -82,10 +84,11 @@
return TRUE;
}
case WM_NCHITTEST: {
case WM_NCHITTEST:
{
POINT cursor = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };
const POINT border{
const POINT border {
static_cast<LONG>((::GetSystemMetrics(SM_CXFRAME) + ::GetSystemMetrics(SM_CXPADDEDBORDER)) * SharedData::globalScale / 1.5F),
static_cast<LONG>((::GetSystemMetrics(SM_CYFRAME) + ::GetSystemMetrics(SM_CXPADDEDBORDER)) * SharedData::globalScale / 1.5F)
};
@ -147,10 +150,10 @@
}
case WM_COPYDATA:
{
auto message = reinterpret_cast<COPYDATASTRUCT*>(lParam);
auto message = reinterpret_cast<COPYDATASTRUCT *>(lParam);
if (message == nullptr) break;
auto path = reinterpret_cast<const char*>(message->lpData);
auto path = reinterpret_cast<const char *>(message->lpData);
if (path == nullptr) break;
log::info("Opening file in existing instance: {}", path);
@ -158,7 +161,8 @@
break;
}
default: break;
default:
break;
}
return CallWindowProc((WNDPROC)g_oldWndProc, hwnd, uMsg, wParam, lParam);
@ -222,7 +226,8 @@
}
return TRUE;
}, 0);
},
0);
std::exit(0);
}
@ -246,7 +251,7 @@
// Setup system theme change detector
bool themeFollowSystem = ContentRegistry::Settings::getSetting("hex.builtin.setting.interface", "hex.builtin.setting.interface.color") == 0;
EventManager::subscribe<EventOSThemeChanged>(this, [themeFollowSystem]{
EventManager::subscribe<EventOSThemeChanged>(this, [themeFollowSystem] {
if (!themeFollowSystem) return;
HKEY hkey;
@ -323,7 +328,7 @@
if (ImGui::GetIO().KeyCtrl) {
// Explicitly trigger a segfault by writing to an invalid memory location
// Used for debugging crashes
*reinterpret_cast<u8*>(0x10) = 0x10;
*reinterpret_cast<u8 *>(0x10) = 0x10;
} else if (ImGui::GetIO().KeyShift) {
// Explicitly trigger an abort by throwing an uncaught exception
// Used for debugging exception errors
@ -364,6 +369,6 @@
ImGui::TextUnformatted(this->m_windowTitle.c_str());
}
}
}
#endif

View File

@ -49,14 +49,14 @@ namespace hex {
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) {
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); });
}
}
}
@ -136,7 +136,7 @@ namespace hex {
ImPlot::StyleColorsDark();
auto banner = romfs::get("banner_dark.png");
this->m_bannerTexture = ImGui::LoadImageFromMemory(reinterpret_cast<const ImU8*>(banner.data()), banner.size());
this->m_bannerTexture = ImGui::LoadImageFromMemory(reinterpret_cast<const ImU8 *>(banner.data()), banner.size());
break;
}
@ -147,7 +147,7 @@ namespace hex {
ImPlot::StyleColorsLight();
auto banner = romfs::get("banner_light.png");
this->m_bannerTexture = ImGui::LoadImageFromMemory(reinterpret_cast<const ImU8*>(banner.data()), banner.size());
this->m_bannerTexture = ImGui::LoadImageFromMemory(reinterpret_cast<const ImU8 *>(banner.data()), banner.size());
break;
}
@ -158,7 +158,7 @@ namespace hex {
ImPlot::StyleColorsClassic();
auto banner = romfs::get("banner_dark.png");
this->m_bannerTexture = ImGui::LoadImageFromMemory(reinterpret_cast<const ImU8*>(banner.data()), banner.size());
this->m_bannerTexture = ImGui::LoadImageFromMemory(reinterpret_cast<const ImU8 *>(banner.data()), banner.size());
break;
}
@ -175,7 +175,7 @@ namespace hex {
}
});
EventManager::subscribe<EventFileLoaded>(this, [](const auto &path){
EventManager::subscribe<EventFileLoaded>(this, [](const auto &path) {
SharedData::recentFilePaths.push_front(path);
{
@ -206,7 +206,7 @@ namespace hex {
}
});
EventManager::subscribe<EventFileUnloaded>(this, []{
EventManager::subscribe<EventFileUnloaded>(this, [] {
EventManager::post<RequestChangeWindowTitle>("");
});
@ -244,14 +244,14 @@ namespace hex {
}
});
EventManager::subscribe<RequestOpenPopup>(this, [this](auto name){
EventManager::subscribe<RequestOpenPopup>(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,12 +269,11 @@ namespace hex {
// Let's not loop on this...
std::signal(signalNumber, nullptr);
#if defined(DEBUG)
#if defined(DEBUG)
assert(false);
#else
#else
std::raise(signalNumber);
#endif
#endif
};
std::signal(SIGTERM, signalHandler);
@ -285,7 +284,7 @@ namespace hex {
std::signal(SIGFPE, signalHandler);
auto imhexLogo = romfs::get("logo.png");
this->m_logoTexture = ImGui::LoadImageFromMemory(reinterpret_cast<const ImU8*>(imhexLogo.data()), imhexLogo.size());
this->m_logoTexture = ImGui::LoadImageFromMemory(reinterpret_cast<const ImU8 *>(imhexLogo.data()), imhexLogo.size());
ContentRegistry::Settings::store();
EventManager::post<EventSettingsChanged>();
@ -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)
#if defined(OS_WINDOWS)
glfwWindowHint(GLFW_DECORATED, GLFW_FALSE);
#elif defined(OS_MACOS)
#elif defined(OS_MACOS)
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
#endif
#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<Window*>(glfwGetWindowUserPointer(window));
auto win = static_cast<Window *>(glfwGetWindowUserPointer(window));
win->frameBegin();
win->frame();
win->frameEnd();
@ -877,19 +871,18 @@ namespace hex {
if (auto g = ImGui::GetCurrentContext(); g == nullptr || g->WithinFrameScope) return;
auto win = static_cast<Window*>(glfwGetWindowUserPointer(window));
auto win = static_cast<Window *>(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<Window*>(glfwGetWindowUserPointer(window));
auto win = static_cast<Window *>(glfwGetWindowUserPointer(window));
if (action == GLFW_PRESS) {
auto &io = ImGui::GetIO();
@ -899,8 +892,7 @@ namespace hex {
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) {
} else if (action == GLFW_RELEASE) {
auto &io = ImGui::GetIO();
io.KeysDown[key] = false;
io.KeyCtrl = (mods & GLFW_MOD_CONTROL) != 0;
@ -950,16 +942,16 @@ 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);
@ -1052,7 +1044,7 @@ namespace hex {
}
void Window::exitImGui() {
delete static_cast<ImGui::ImHexCustomData*>(ImGui::GetIO().UserData);
delete static_cast<ImGui::ImHexCustomData *>(ImGui::GetIO().UserData);
ImNodes::PopAttributeFlag();
ImNodes::PopAttributeFlag();

View File

@ -44,12 +44,12 @@ namespace hex::plugin::builtin::prv {
std::set<std::string> m_availableDrives;
fs::path m_path;
#if defined(OS_WINDOWS)
#if defined(OS_WINDOWS)
HANDLE m_diskHandle = INVALID_HANDLE_VALUE;
#else
#else
std::string m_pathBuffer;
int m_diskHandle = -1;
#endif
#endif
size_t m_diskSize;
size_t m_sectorSize;

View File

@ -7,11 +7,11 @@
#include <sys/stat.h>
#if defined(OS_WINDOWS)
#include <windows.h>
#include <windows.h>
#else
#include <sys/mman.h>
#include <unistd.h>
#include <sys/fcntl.h>
#include <sys/mman.h>
#include <unistd.h>
#include <sys/fcntl.h>
#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;

View File

@ -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;

View File

@ -7,7 +7,9 @@
namespace hex::plugin::builtin {
namespace prv { class Provider; }
namespace prv {
class Provider;
}
class ViewBookmarks : public View {
public:

View File

@ -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;

View File

@ -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<dp::Node*> m_endNodes;
std::list<dp::Node*> m_nodes;
std::list<dp::Node *> m_endNodes;
std::list<dp::Node *> m_nodes;
std::list<dp::Link> m_links;
std::vector<hex::prv::Overlay*> m_dataOverlays;
std::vector<hex::prv::Overlay *> m_dataOverlays;
int m_rightClickedId = -1;
ImVec2 m_rightClickedCoords;

View File

@ -11,7 +11,9 @@
namespace hex::plugin::builtin {
namespace prv { class Provider; }
namespace prv {
class Provider;
}
class ViewDiff : public View {
public:

View File

@ -10,7 +10,9 @@
namespace hex::plugin::builtin {
namespace prv { class Provider; }
namespace prv {
class Provider;
}
struct Disassembly {
u64 address;

View File

@ -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"},
};
};

View File

@ -11,7 +11,9 @@
namespace hex::plugin::builtin {
namespace prv { class Provider; }
namespace prv {
class Provider;
}
class ViewHelp : public View {
public:

View File

@ -10,13 +10,15 @@
#include <random>
#include <vector>
namespace hex::prv { class Provider; }
namespace hex::prv {
class Provider;
}
namespace hex::plugin::builtin {
using SearchFunction = std::vector<std::pair<u64, u64>> (*)(prv::Provider* &provider, std::string string);
using SearchFunction = std::vector<std::pair<u64, u64>> (*)(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<u8> m_dataToSave;
std::set<pl::PatternData*> m_highlightedPatterns;
std::set<pl::PatternData *> m_highlightedPatterns;
std::string m_loaderScriptScriptPath;
std::string m_loaderScriptFilePath;

View File

@ -10,7 +10,9 @@
namespace hex::plugin::builtin {
namespace prv { class Provider; }
namespace prv {
class Provider;
}
class ViewInformation : public View {
public:

View File

@ -9,7 +9,9 @@
namespace hex::plugin::builtin {
namespace prv { class Provider; }
namespace prv {
class Provider;
}
class ViewPatches : public View {
public:

View File

@ -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<pl::PatternData*> m_sortedPatternData;
std::vector<pl::PatternData *> m_sortedPatternData;
};
}

View File

@ -7,7 +7,9 @@
namespace hex::plugin::builtin {
namespace prv { class Provider; }
namespace prv {
class Provider;
}
struct FoundString {
u64 offset;

View File

@ -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;
};
}

View File

@ -74,7 +74,7 @@ namespace hex {
void setVariable(std::string name, long double value);
void setFunction(std::string name, std::function<std::optional<long double>(std::vector<long double>)> function, size_t minNumArgs, size_t maxNumArgs);
std::unordered_map<std::string, long double>& getVariables() { return this->m_variables; }
std::unordered_map<std::string, long double> &getVariables() { return this->m_variables; }
private:
std::queue<Token> parseInput(const char *input);

View File

@ -14,7 +14,8 @@ namespace hex::plugin::builtin {
ContentRegistry::CommandPaletteCommands::add(
ContentRegistry::CommandPaletteCommands::Type::SymbolCommand,
"#", "hex.builtin.command.calc.desc",
"#",
"hex.builtin.command.calc.desc",
[](auto input) {
hex::MathEvaluator evaluator;
evaluator.registerStandardVariables();
@ -24,7 +25,7 @@ namespace hex::plugin::builtin {
try {
result = evaluator.evaluate(input);
} catch (std::exception &e) {}
} catch (std::exception &e) { }
if (result.has_value())
@ -35,7 +36,8 @@ namespace hex::plugin::builtin {
ContentRegistry::CommandPaletteCommands::add(
ContentRegistry::CommandPaletteCommands::Type::KeywordCommand,
"/web", "hex.builtin.command.web.desc",
"/web",
"hex.builtin.command.web.desc",
[](auto input) {
return hex::format("hex.builtin.command.web.result"_lang, input.data());
},
@ -45,14 +47,14 @@ namespace hex::plugin::builtin {
ContentRegistry::CommandPaletteCommands::add(
ContentRegistry::CommandPaletteCommands::Type::SymbolCommand,
"$", "hex.builtin.command.cmd.desc",
"$",
"hex.builtin.command.cmd.desc",
[](auto input) {
return hex::format("hex.builtin.command.cmd.result"_lang, input.data());
},
[](auto input) {
hex::runCommand(input);
});
}
}

View File

@ -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<uint8_t, {0}> data = {{", size),
"0x{0:02X}, ",
"};");
return formatLanguageArray(provider, offset, size, hex::format("constexpr std::array<uint8_t, {0}> 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,7 +101,6 @@ namespace hex::plugin::builtin {
result += "\n";
}
}
return result;
});
@ -148,7 +127,7 @@ namespace hex::plugin::builtin {
for (u32 col = offset >> 4; col <= (end >> 4); col++) {
result += hex::format(" <span class=\"offsetcolumn\">{0:08X}</span>&nbsp&nbsp<span class=\"hexcolumn\">", 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 += "&nbsp&nbsp ";
@ -161,7 +140,7 @@ namespace hex::plugin::builtin {
result += "</span>&nbsp&nbsp<span class=\"textcolumn\">";
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 += "&nbsp";
@ -174,7 +153,6 @@ namespace hex::plugin::builtin {
result += "</span><br>\n";
}
}
result +=
@ -183,7 +161,6 @@ namespace hex::plugin::builtin {
return result;
});
}
}

Some files were not shown because too many files have changed in this diff Show More