1
0
mirror of synced 2024-11-24 07:40:17 +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

@ -6,17 +6,17 @@
constexpr static const auto ImHexApiURL = "https://api.werwolv.net/imhex";
constexpr static const auto GitHubApiURL = "https://api.github.com/repos/WerWolv/ImHex";
using u8 = std::uint8_t;
using u16 = std::uint16_t;
using u32 = std::uint32_t;
using u64 = std::uint64_t;
using u128 = __uint128_t;
using u8 = std::uint8_t;
using u16 = std::uint16_t;
using u32 = std::uint32_t;
using u64 = std::uint64_t;
using u128 = __uint128_t;
using i8 = std::int8_t;
using i16 = std::int16_t;
using i32 = std::int32_t;
using i64 = std::int64_t;
using i128 = __int128_t;
using i8 = std::int8_t;
using i16 = std::int16_t;
using i32 = std::int32_t;
using i64 = std::int64_t;
using i128 = __int128_t;
namespace hex {
@ -26,4 +26,3 @@ namespace hex {
};
}

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,20 +84,21 @@ namespace hex {
ExecuteCallback executeCallback;
};
void add(Type type, const std::string &command, const std::string &unlocalizedDescription, const DisplayCallback &displayCallback, const ExecuteCallback &executeCallback = [](auto){});
std::vector<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 */
namespace PatternLanguage {
constexpr static u32 UnlimitedParameters = 0xFFFF'FFFF;
constexpr static u32 MoreParametersThan = 0x8000'0000;
constexpr static u32 LessParametersThan = 0x4000'0000;
constexpr static u32 NoParameters = 0x0000'0000;
constexpr static u32 UnlimitedParameters = 0xFFFF'FFFF;
constexpr static u32 MoreParametersThan = 0x8000'0000;
constexpr static u32 LessParametersThan = 0x4000'0000;
constexpr static u32 NoParameters = 0x0000'0000;
using Namespace = std::vector<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(),
[=]{
auto node = new T(std::forward<Args>(args)...);
node->setUnlocalizedName(unlocalizedName);
return node;
}
});
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

@ -10,10 +10,10 @@
#include <hex/api/imhex_api.hpp>
#include <hex/helpers/paths.hpp>
#define EVENT_DEF(event_name, ...) \
struct event_name final : public hex::Event<__VA_ARGS__> { \
constexpr static auto id = [] { return hex::EventId(); }(); \
explicit event_name(Callback func) noexcept : Event(std::move(func)) { } \
#define EVENT_DEF(event_name, ...) \
struct event_name final : public hex::Event<__VA_ARGS__> { \
constexpr static auto id = [] { return hex::EventId(); }(); \
explicit event_name(Callback func) noexcept : Event(std::move(func)) { } \
}
class GLFWwindow;
@ -25,12 +25,12 @@ namespace hex {
explicit constexpr EventId(const char *func = __builtin_FUNCTION(), u32 line = __builtin_LINE()) {
this->m_hash = line ^ 123456789;
for (auto c : std::string_view(func)) {
this->m_hash = (this->m_hash >> 5) | (this->m_hash << 27);
this->m_hash = (this->m_hash >> 5) | (this->m_hash << 27);
this->m_hash ^= c;
}
}
constexpr bool operator ==(const EventId &rhs) const = default;
constexpr bool operator==(const EventId &rhs) const = default;
private:
u32 m_hash;
@ -40,11 +40,11 @@ namespace hex {
EventBase() noexcept = default;
};
template<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,33 +84,35 @@ 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)...);
}
}
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

@ -14,126 +14,126 @@ namespace hex {
struct View;
enum class Keys {
Space = GLFW_KEY_SPACE,
Apostrophe = GLFW_KEY_APOSTROPHE,
Comma = GLFW_KEY_COMMA,
Minus = GLFW_KEY_MINUS,
Period = GLFW_KEY_PERIOD,
Slash = GLFW_KEY_SLASH,
Num0 = GLFW_KEY_0,
Num1 = GLFW_KEY_1,
Num2 = GLFW_KEY_2,
Num3 = GLFW_KEY_3,
Num4 = GLFW_KEY_4,
Num5 = GLFW_KEY_5,
Num6 = GLFW_KEY_6,
Num7 = GLFW_KEY_7,
Num8 = GLFW_KEY_8,
Num9 = GLFW_KEY_9,
Semicolon = GLFW_KEY_SEMICOLON,
Equals = GLFW_KEY_EQUAL,
A = GLFW_KEY_A,
B = GLFW_KEY_B,
C = GLFW_KEY_C,
D = GLFW_KEY_D,
E = GLFW_KEY_E,
F = GLFW_KEY_F,
G = GLFW_KEY_G,
H = GLFW_KEY_H,
I = GLFW_KEY_I,
J = GLFW_KEY_J,
K = GLFW_KEY_K,
L = GLFW_KEY_L,
M = GLFW_KEY_M,
N = GLFW_KEY_N,
O = GLFW_KEY_O,
P = GLFW_KEY_P,
Q = GLFW_KEY_Q,
R = GLFW_KEY_R,
S = GLFW_KEY_S,
T = GLFW_KEY_T,
U = GLFW_KEY_U,
V = GLFW_KEY_V,
W = GLFW_KEY_W,
X = GLFW_KEY_X,
Y = GLFW_KEY_Y,
Z = GLFW_KEY_Z,
LeftBracket = GLFW_KEY_LEFT_BRACKET,
Backslash = GLFW_KEY_BACKSLASH,
RightBracket = GLFW_KEY_RIGHT_BRACKET,
GraveAccent = GLFW_KEY_GRAVE_ACCENT,
World1 = GLFW_KEY_WORLD_1,
World2 = GLFW_KEY_WORLD_2,
Escape = GLFW_KEY_ESCAPE,
Enter = GLFW_KEY_ENTER,
Tab = GLFW_KEY_TAB,
Backspace = GLFW_KEY_BACKSPACE,
Insert = GLFW_KEY_INSERT,
Delete = GLFW_KEY_DELETE,
Right = GLFW_KEY_RIGHT,
Left = GLFW_KEY_LEFT,
Down = GLFW_KEY_DOWN,
Up = GLFW_KEY_UP,
PageUp = GLFW_KEY_PAGE_UP,
PageDown = GLFW_KEY_PAGE_DOWN,
Home = GLFW_KEY_HOME,
End = GLFW_KEY_END,
CapsLock = GLFW_KEY_CAPS_LOCK,
ScrollLock = GLFW_KEY_SCROLL_LOCK,
NumLock = GLFW_KEY_NUM_LOCK,
PrintScreen = GLFW_KEY_PRINT_SCREEN,
Pause = GLFW_KEY_PAUSE,
F1 = GLFW_KEY_F1,
F2 = GLFW_KEY_F2,
F3 = GLFW_KEY_F3,
F4 = GLFW_KEY_F4,
F5 = GLFW_KEY_F5,
F6 = GLFW_KEY_F6,
F7 = GLFW_KEY_F7,
F8 = GLFW_KEY_F8,
F9 = GLFW_KEY_F9,
F10 = GLFW_KEY_F10,
F11 = GLFW_KEY_F11,
F12 = GLFW_KEY_F12,
F13 = GLFW_KEY_F13,
F14 = GLFW_KEY_F14,
F15 = GLFW_KEY_F15,
F16 = GLFW_KEY_F16,
F17 = GLFW_KEY_F17,
F18 = GLFW_KEY_F18,
F19 = GLFW_KEY_F19,
F20 = GLFW_KEY_F20,
F21 = GLFW_KEY_F21,
F22 = GLFW_KEY_F22,
F23 = GLFW_KEY_F23,
F24 = GLFW_KEY_F24,
F25 = GLFW_KEY_F25,
KeyPad0 = GLFW_KEY_KP_0,
KeyPad1 = GLFW_KEY_KP_1,
KeyPad2 = GLFW_KEY_KP_2,
KeyPad3 = GLFW_KEY_KP_3,
KeyPad4 = GLFW_KEY_KP_4,
KeyPad5 = GLFW_KEY_KP_5,
KeyPad6 = GLFW_KEY_KP_6,
KeyPad7 = GLFW_KEY_KP_7,
KeyPad8 = GLFW_KEY_KP_8,
KeyPad9 = GLFW_KEY_KP_9,
KeyPadDecimal = GLFW_KEY_KP_DECIMAL,
KeyPadDivide = GLFW_KEY_KP_DIVIDE,
KeyPadMultiply = GLFW_KEY_KP_MULTIPLY,
KeyPadSubtract = GLFW_KEY_KP_SUBTRACT,
KeyPadAdd = GLFW_KEY_KP_ADD,
KeyPadEnter = GLFW_KEY_KP_ENTER,
KeyPadEqual = GLFW_KEY_KP_EQUAL,
Menu = GLFW_KEY_MENU,
Space = GLFW_KEY_SPACE,
Apostrophe = GLFW_KEY_APOSTROPHE,
Comma = GLFW_KEY_COMMA,
Minus = GLFW_KEY_MINUS,
Period = GLFW_KEY_PERIOD,
Slash = GLFW_KEY_SLASH,
Num0 = GLFW_KEY_0,
Num1 = GLFW_KEY_1,
Num2 = GLFW_KEY_2,
Num3 = GLFW_KEY_3,
Num4 = GLFW_KEY_4,
Num5 = GLFW_KEY_5,
Num6 = GLFW_KEY_6,
Num7 = GLFW_KEY_7,
Num8 = GLFW_KEY_8,
Num9 = GLFW_KEY_9,
Semicolon = GLFW_KEY_SEMICOLON,
Equals = GLFW_KEY_EQUAL,
A = GLFW_KEY_A,
B = GLFW_KEY_B,
C = GLFW_KEY_C,
D = GLFW_KEY_D,
E = GLFW_KEY_E,
F = GLFW_KEY_F,
G = GLFW_KEY_G,
H = GLFW_KEY_H,
I = GLFW_KEY_I,
J = GLFW_KEY_J,
K = GLFW_KEY_K,
L = GLFW_KEY_L,
M = GLFW_KEY_M,
N = GLFW_KEY_N,
O = GLFW_KEY_O,
P = GLFW_KEY_P,
Q = GLFW_KEY_Q,
R = GLFW_KEY_R,
S = GLFW_KEY_S,
T = GLFW_KEY_T,
U = GLFW_KEY_U,
V = GLFW_KEY_V,
W = GLFW_KEY_W,
X = GLFW_KEY_X,
Y = GLFW_KEY_Y,
Z = GLFW_KEY_Z,
LeftBracket = GLFW_KEY_LEFT_BRACKET,
Backslash = GLFW_KEY_BACKSLASH,
RightBracket = GLFW_KEY_RIGHT_BRACKET,
GraveAccent = GLFW_KEY_GRAVE_ACCENT,
World1 = GLFW_KEY_WORLD_1,
World2 = GLFW_KEY_WORLD_2,
Escape = GLFW_KEY_ESCAPE,
Enter = GLFW_KEY_ENTER,
Tab = GLFW_KEY_TAB,
Backspace = GLFW_KEY_BACKSPACE,
Insert = GLFW_KEY_INSERT,
Delete = GLFW_KEY_DELETE,
Right = GLFW_KEY_RIGHT,
Left = GLFW_KEY_LEFT,
Down = GLFW_KEY_DOWN,
Up = GLFW_KEY_UP,
PageUp = GLFW_KEY_PAGE_UP,
PageDown = GLFW_KEY_PAGE_DOWN,
Home = GLFW_KEY_HOME,
End = GLFW_KEY_END,
CapsLock = GLFW_KEY_CAPS_LOCK,
ScrollLock = GLFW_KEY_SCROLL_LOCK,
NumLock = GLFW_KEY_NUM_LOCK,
PrintScreen = GLFW_KEY_PRINT_SCREEN,
Pause = GLFW_KEY_PAUSE,
F1 = GLFW_KEY_F1,
F2 = GLFW_KEY_F2,
F3 = GLFW_KEY_F3,
F4 = GLFW_KEY_F4,
F5 = GLFW_KEY_F5,
F6 = GLFW_KEY_F6,
F7 = GLFW_KEY_F7,
F8 = GLFW_KEY_F8,
F9 = GLFW_KEY_F9,
F10 = GLFW_KEY_F10,
F11 = GLFW_KEY_F11,
F12 = GLFW_KEY_F12,
F13 = GLFW_KEY_F13,
F14 = GLFW_KEY_F14,
F15 = GLFW_KEY_F15,
F16 = GLFW_KEY_F16,
F17 = GLFW_KEY_F17,
F18 = GLFW_KEY_F18,
F19 = GLFW_KEY_F19,
F20 = GLFW_KEY_F20,
F21 = GLFW_KEY_F21,
F22 = GLFW_KEY_F22,
F23 = GLFW_KEY_F23,
F24 = GLFW_KEY_F24,
F25 = GLFW_KEY_F25,
KeyPad0 = GLFW_KEY_KP_0,
KeyPad1 = GLFW_KEY_KP_1,
KeyPad2 = GLFW_KEY_KP_2,
KeyPad3 = GLFW_KEY_KP_3,
KeyPad4 = GLFW_KEY_KP_4,
KeyPad5 = GLFW_KEY_KP_5,
KeyPad6 = GLFW_KEY_KP_6,
KeyPad7 = GLFW_KEY_KP_7,
KeyPad8 = GLFW_KEY_KP_8,
KeyPad9 = GLFW_KEY_KP_9,
KeyPadDecimal = GLFW_KEY_KP_DECIMAL,
KeyPadDivide = GLFW_KEY_KP_DIVIDE,
KeyPadMultiply = GLFW_KEY_KP_MULTIPLY,
KeyPadSubtract = GLFW_KEY_KP_SUBTRACT,
KeyPadAdd = GLFW_KEY_KP_ADD,
KeyPadEnter = GLFW_KEY_KP_ENTER,
KeyPadEqual = GLFW_KEY_KP_EQUAL,
Menu = GLFW_KEY_MENU,
};
class Key {
public:
constexpr Key(Keys key) :m_key(static_cast<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);
@ -175,8 +175,8 @@ namespace hex {
return result;
}
static constexpr auto CTRL = Key(static_cast<Keys>(0x1000'0000));
static constexpr auto ALT = Key(static_cast<Keys>(0x2000'0000));
static constexpr auto CTRL = Key(static_cast<Keys>(0x1000'0000));
static constexpr auto ALT = Key(static_cast<Keys>(0x2000'0000));
static constexpr auto SHIFT = Key(static_cast<Keys>(0x3000'0000));
static constexpr auto SUPER = Key(static_cast<Keys>(0x4000'0000));

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

@ -8,11 +8,11 @@ namespace hex::dp {
public:
Link(u32 from, u32 to);
[[nodiscard]] u32 getID() const { return this->m_id; }
[[nodiscard]] u32 getID() const { return this->m_id; }
void setID(u32 id) { this->m_id = id; }
[[nodiscard]] u32 getFromID() const { return this->m_from; }
[[nodiscard]] u32 getToID() const { return this->m_to; }
[[nodiscard]] u32 getToID() const { return this->m_to; }
private:
u32 m_id;

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);
@ -38,14 +40,14 @@ namespace hex::crypt {
std::string encode16(const std::vector<u8> &input);
enum class AESMode : u8 {
ECB = 0,
CBC = 1,
CFB128 = 2,
CTR = 3,
GCM = 4,
CCM = 5,
OFB = 6,
XTS = 7
ECB = 0,
CBC = 1,
CFB128 = 2,
CTR = 3,
GCM = 4,
CCM = 5,
OFB = 6,
XTS = 7
};
enum class KeyLength : u8 {

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

@ -9,10 +9,10 @@
#include <hex/helpers/paths.hpp>
#if defined(OS_MACOS)
#define off64_t off_t
#define fopen64 fopen
#define fseeko64 fseek
#define ftello64 ftell
#define off64_t off_t
#define fopen64 fopen
#define fseeko64 fseek
#define ftello64 ftell
#define ftruncate64 ftruncate
#endif
@ -28,12 +28,12 @@ namespace hex {
explicit File(const fs::path &path, Mode mode) noexcept;
File() noexcept;
File(const File&) = delete;
File(const File &) = delete;
File(File &&other) noexcept;
~File();
File& operator=(File &&other) noexcept;
File &operator=(File &&other) noexcept;
[[nodiscard]] bool isValid() const { return this->m_file != nullptr; }
@ -56,7 +56,7 @@ namespace hex {
void remove();
auto getHandle() { return this->m_file; }
const fs::path& getPath() { return this->m_path; }
const fs::path &getPath() { return this->m_path; }
private:
FILE *m_file;

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)
log::print(fg(fmt::color::green_yellow) | fmt::emphasis::bold, "[DEBUG] ");
log::print(fmt::runtime(fmt), args...);
log::print("\n");
#endif
void debug(const std::string &fmt, auto... args) {
#if defined(DEBUG)
log::print(fg(fmt::color::green_yellow) | fmt::emphasis::bold, "[DEBUG] ");
log::print(fmt::runtime(fmt), args...);
log::print("\n");
#endif
}
void info(const std::string &fmt, auto ... args) {
void info(const std::string &fmt, auto... args) {
log::print(fg(fmt::color::cadet_blue) | fmt::emphasis::bold, "[INFO] ");
log::print(fmt::runtime(fmt), args...);
log::print("\n");
}
void warn(const std::string &fmt, auto ... args) {
void warn(const std::string &fmt, auto... args) {
log::print(fg(fmt::color::orange) | fmt::emphasis::bold, "[WARN] ");
log::print(fmt::runtime(fmt), args...);
log::print("\n");
}
void error(const std::string &fmt, auto ... args) {
void error(const std::string &fmt, auto... args) {
log::print(fg(fmt::color::red) | fmt::emphasis::bold, "[ERROR] ");
log::print(fmt::runtime(fmt), args...);
log::print("\n");
}
void fatal(const std::string &fmt, auto ... args) {
void fatal(const std::string &fmt, auto... args) {
log::print(fg(fmt::color::purple) | fmt::emphasis::bold, "[FATAL] ");
log::print(fmt::runtime(fmt), args...);
log::print("\n");

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 {
std::string getMacExecutableDirectoryPath();
std::string getMacApplicationSupportDirectoryPath();
}
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)
SOCKET m_socket = SOCKET_NONE;
#else
int m_socket = SOCKET_NONE;
#endif
#if defined(OS_WINDOWS)
SOCKET m_socket = SOCKET_NONE;
#else
int m_socket = SOCKET_NONE;
#endif
};
}

View File

@ -20,8 +20,8 @@
#include <nfd.hpp>
#define TOKEN_CONCAT_IMPL(x, y) x ## y
#define TOKEN_CONCAT(x, y) TOKEN_CONCAT_IMPL(x, y)
#define TOKEN_CONCAT_IMPL(x, y) x##y
#define TOKEN_CONCAT(x, y) TOKEN_CONCAT_IMPL(x, y)
#define ANONYMOUS_VARIABLE(prefix) TOKEN_CONCAT(prefix, __COUNTER__)
struct ImVec2;
@ -50,7 +50,7 @@ namespace hex {
[[nodiscard]] inline u64 extract(u32 from, u32 to, const std::vector<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;
@ -99,15 +106,26 @@ namespace hex {
SizeType<Size> swapped;
if constexpr (!std::has_single_bit(Size) || Size > 16)
static_assert(always_false<T>::value, "Invalid type provided!");
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));
}
@ -201,14 +229,15 @@ namespace hex {
inline void trimLeft(std::string &s) {
s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](unsigned char ch) {
return !std::isspace(ch) && ch >= 0x20;
}));
return !std::isspace(ch) && ch >= 0x20;
}));
}
inline void trimRight(std::string &s) {
inline void trimRight(std::string &s) {
s.erase(std::find_if(s.rbegin(), s.rend(), [](unsigned char ch) {
return !std::isspace(ch) && ch >= 0x20;
}).base(), s.end());
return !std::isspace(ch) && ch >= 0x20;
}).base(),
s.end());
}
inline void trim(std::string &s) {
@ -233,14 +262,14 @@ namespace hex {
}
inline bool containsIgnoreCase(const std::string &a, const std::string &b) {
auto iter = std::search(a.begin(), a.end(), b.begin(), b.end(), [](char ch1, char ch2) {
auto iter = std::search(a.begin(), a.end(), b.begin(), b.end(), [](char ch1, char ch2) {
return std::toupper(ch1) == std::toupper(ch2);
});
return iter != a.end();
}
template<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;
}
};
}

File diff suppressed because it is too large Load Diff

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

@ -80,31 +80,31 @@ namespace hex::pl {
};
enum class ValueType {
Unsigned8Bit = 0x10,
Signed8Bit = 0x11,
Unsigned16Bit = 0x20,
Signed16Bit = 0x21,
Unsigned32Bit = 0x40,
Signed32Bit = 0x41,
Unsigned64Bit = 0x80,
Signed64Bit = 0x81,
Unsigned128Bit = 0x100,
Signed128Bit = 0x101,
Character = 0x13,
Character16 = 0x23,
Boolean = 0x14,
Float = 0x42,
Double = 0x82,
String = 0x15,
Auto = 0x16,
CustomType = 0x00,
Padding = 0x1F,
Unsigned8Bit = 0x10,
Signed8Bit = 0x11,
Unsigned16Bit = 0x20,
Signed16Bit = 0x21,
Unsigned32Bit = 0x40,
Signed32Bit = 0x41,
Unsigned64Bit = 0x80,
Signed64Bit = 0x81,
Unsigned128Bit = 0x100,
Signed128Bit = 0x101,
Character = 0x13,
Character16 = 0x23,
Boolean = 0x14,
Float = 0x42,
Double = 0x82,
String = 0x15,
Auto = 0x16,
CustomType = 0x00,
Padding = 0x1F,
Unsigned = 0xFF00,
Signed = 0xFF01,
FloatingPoint = 0xFF02,
Integer = 0xFF03,
Any = 0xFFFF
Unsigned = 0xFF00,
Signed = 0xFF01,
FloatingPoint = 0xFF02,
Integer = 0xFF03,
Any = 0xFFFF
};
enum class Separator {
@ -123,21 +123,19 @@ namespace hex::pl {
struct Identifier {
explicit Identifier(std::string identifier) : m_identifier(std::move(identifier)) { }
[[nodiscard]]
const std::string &get() const { return this->m_identifier; }
[[nodiscard]] const std::string &get() const { return this->m_identifier; }
auto operator<=>(const Identifier&) const = default;
bool operator==(const Identifier&) const = default;
auto operator<=>(const Identifier &) const = default;
bool operator==(const Identifier &) const = default;
private:
std::string m_identifier;
};
using Literal = std::variant<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) {
@ -158,37 +156,33 @@ namespace hex::pl {
static u128 literalToUnsigned(const pl::Token::Literal &literal) {
return std::visit(overloaded {
[](std::string) -> u128 { throw std::string("expected integral type, got string"); },
[](PatternData*) -> u128 { throw std::string("expected integral type, got custom type"); },
[](auto &&value) -> u128 { return value; }
},
[](std::string) -> u128 { throw std::string("expected integral type, got string"); },
[](PatternData *) -> u128 { throw std::string("expected integral type, got custom type"); },
[](auto &&value) -> u128 { return value; } },
literal);
}
static i128 literalToSigned(const pl::Token::Literal &literal) {
return std::visit(overloaded {
[](std::string) -> i128 { throw std::string("expected integral type, got string"); },
[](PatternData*) -> i128 { throw std::string("expected integral type, got custom type"); },
[](auto &&value) -> i128 { return value; }
},
[](std::string) -> i128 { throw std::string("expected integral type, got string"); },
[](PatternData *) -> i128 { throw std::string("expected integral type, got custom type"); },
[](auto &&value) -> i128 { return value; } },
literal);
}
static double literalToFloatingPoint(const pl::Token::Literal &literal) {
return std::visit(overloaded {
[](std::string) -> double { throw std::string("expected integral type, got string"); },
[](PatternData*) -> double { throw std::string("expected integral type, got custom type"); },
[](auto &&value) -> double { return value; }
},
[](std::string) -> double { throw std::string("expected integral type, got string"); },
[](PatternData *) -> double { throw std::string("expected integral type, got custom type"); },
[](auto &&value) -> double { return value; } },
literal);
}
static bool literalToBoolean(const pl::Token::Literal &literal) {
return std::visit(overloaded {
[](std::string) -> bool { throw std::string("expected integral type, got string"); },
[](PatternData*) -> bool { throw std::string("expected integral type, got custom type"); },
[](auto &&value) -> bool { return value != 0; }
},
[](std::string) -> bool { throw std::string("expected integral type, got string"); },
[](PatternData *) -> bool { throw std::string("expected integral type, got custom type"); },
[](auto &&value) -> bool { return value != 0; } },
literal);
}
@ -197,36 +191,52 @@ namespace hex::pl {
throw std::string("expected string type, got integral");
return std::visit(overloaded {
[](std::string value) -> std::string { return value; },
[](u128 value) -> std::string { return std::to_string(u64(value)); },
[](i128 value) -> std::string { return std::to_string(i64(value)); },
[](bool value) -> std::string { return value ? "true" : "false"; },
[](char value) -> std::string { return std::string() + value; },
[](PatternData*) -> std::string { throw std::string("expected integral type, got custom type"); },
[](auto &&value) -> std::string { return std::to_string(value); }
},
[](std::string value) -> std::string { return value; },
[](u128 value) -> std::string { return std::to_string(u64(value)); },
[](i128 value) -> std::string { return std::to_string(i64(value)); },
[](bool value) -> std::string { return value ? "true" : "false"; },
[](char value) -> std::string { return std::string() + value; },
[](PatternData *) -> std::string { throw std::string("expected integral type, got custom type"); },
[](auto &&value) -> std::string { return std::to_string(value); } },
literal);
}
[[nodiscard]] constexpr static auto getTypeName(const pl::Token::ValueType type) {
switch (type) {
case ValueType::Signed8Bit: return "s8";
case ValueType::Signed16Bit: return "s16";
case ValueType::Signed32Bit: return "s32";
case ValueType::Signed64Bit: return "s64";
case ValueType::Signed128Bit: return "s128";
case ValueType::Unsigned8Bit: return "u8";
case ValueType::Unsigned16Bit: return "u16";
case ValueType::Unsigned32Bit: return "u32";
case ValueType::Unsigned64Bit: return "u64";
case ValueType::Unsigned128Bit: return "u128";
case ValueType::Float: return "float";
case ValueType::Double: return "double";
case ValueType::Character: return "char";
case ValueType::Character16: return "char16";
case ValueType::Padding: return "padding";
case ValueType::String: return "str";
default: return "< ??? >";
case ValueType::Signed8Bit:
return "s8";
case ValueType::Signed16Bit:
return "s16";
case ValueType::Signed32Bit:
return "s32";
case ValueType::Signed64Bit:
return "s64";
case ValueType::Signed128Bit:
return "s128";
case ValueType::Unsigned8Bit:
return "u8";
case ValueType::Unsigned16Bit:
return "u16";
case ValueType::Unsigned32Bit:
return "u32";
case ValueType::Unsigned64Bit:
return "u64";
case ValueType::Unsigned128Bit:
return "u128";
case ValueType::Float:
return "float";
case ValueType::Double:
return "double";
case ValueType::Character:
return "char";
case ValueType::Character16:
return "char16";
case ValueType::Padding:
return "padding";
case ValueType::String:
return "str";
default:
return "< ??? >";
}
}
@ -234,8 +244,8 @@ namespace hex::pl {
if (this->type == Type::Integer || this->type == Type::Identifier || this->type == Type::String)
return true;
else if (this->type == Type::ValueType) {
auto otherValueType = std::get_if<ValueType>(&other);
auto valueType = std::get_if<ValueType>(&this->value);
auto otherValueType = std::get_if<ValueType>(&other);
auto valueType = std::get_if<ValueType>(&this->value);
if (otherValueType == nullptr) return false;
if (valueType == nullptr) return false;
@ -252,8 +262,7 @@ namespace hex::pl {
return isFloatingPoint(*valueType);
else if (*otherValueType == ValueType::Integer)
return isUnsigned(*valueType) || isSigned(*valueType);
}
else
} else
return other == this->value;
return false;
@ -266,83 +275,82 @@ namespace hex::pl {
Type type;
ValueTypes value;
u32 lineNumber;
};
}
#define COMPONENT(type, value) hex::pl::Token::Type::type, hex::pl::Token::type::value
#define KEYWORD_STRUCT COMPONENT(Keyword, Struct)
#define KEYWORD_UNION COMPONENT(Keyword, Union)
#define KEYWORD_USING COMPONENT(Keyword, Using)
#define KEYWORD_ENUM COMPONENT(Keyword, Enum)
#define KEYWORD_BITFIELD COMPONENT(Keyword, Bitfield)
#define KEYWORD_LE COMPONENT(Keyword, LittleEndian)
#define KEYWORD_BE COMPONENT(Keyword, BigEndian)
#define KEYWORD_IF COMPONENT(Keyword, If)
#define KEYWORD_ELSE COMPONENT(Keyword, Else)
#define KEYWORD_PARENT COMPONENT(Keyword, Parent)
#define KEYWORD_THIS COMPONENT(Keyword, This)
#define KEYWORD_WHILE COMPONENT(Keyword, While)
#define KEYWORD_FOR COMPONENT(Keyword, For)
#define KEYWORD_FUNCTION COMPONENT(Keyword, Function)
#define KEYWORD_RETURN COMPONENT(Keyword, Return)
#define KEYWORD_NAMESPACE COMPONENT(Keyword, Namespace)
#define KEYWORD_IN COMPONENT(Keyword, In)
#define KEYWORD_OUT COMPONENT(Keyword, Out)
#define KEYWORD_BREAK COMPONENT(Keyword, Break)
#define KEYWORD_CONTINUE COMPONENT(Keyword, Continue)
#define KEYWORD_STRUCT COMPONENT(Keyword, Struct)
#define KEYWORD_UNION COMPONENT(Keyword, Union)
#define KEYWORD_USING COMPONENT(Keyword, Using)
#define KEYWORD_ENUM COMPONENT(Keyword, Enum)
#define KEYWORD_BITFIELD COMPONENT(Keyword, Bitfield)
#define KEYWORD_LE COMPONENT(Keyword, LittleEndian)
#define KEYWORD_BE COMPONENT(Keyword, BigEndian)
#define KEYWORD_IF COMPONENT(Keyword, If)
#define KEYWORD_ELSE COMPONENT(Keyword, Else)
#define KEYWORD_PARENT COMPONENT(Keyword, Parent)
#define KEYWORD_THIS COMPONENT(Keyword, This)
#define KEYWORD_WHILE COMPONENT(Keyword, While)
#define KEYWORD_FOR COMPONENT(Keyword, For)
#define KEYWORD_FUNCTION COMPONENT(Keyword, Function)
#define KEYWORD_RETURN COMPONENT(Keyword, Return)
#define KEYWORD_NAMESPACE COMPONENT(Keyword, Namespace)
#define KEYWORD_IN COMPONENT(Keyword, In)
#define KEYWORD_OUT COMPONENT(Keyword, Out)
#define KEYWORD_BREAK COMPONENT(Keyword, Break)
#define KEYWORD_CONTINUE COMPONENT(Keyword, Continue)
#define INTEGER hex::pl::Token::Type::Integer, hex::pl::Token::Literal(u128(0))
#define IDENTIFIER hex::pl::Token::Type::Identifier, ""
#define STRING hex::pl::Token::Type::String, hex::pl::Token::Literal("")
#define INTEGER hex::pl::Token::Type::Integer, hex::pl::Token::Literal(u128(0))
#define IDENTIFIER hex::pl::Token::Type::Identifier, ""
#define STRING hex::pl::Token::Type::String, hex::pl::Token::Literal("")
#define OPERATOR_AT COMPONENT(Operator, AtDeclaration)
#define OPERATOR_ASSIGNMENT COMPONENT(Operator, Assignment)
#define OPERATOR_INHERIT COMPONENT(Operator, Inherit)
#define OPERATOR_PLUS COMPONENT(Operator, Plus)
#define OPERATOR_MINUS COMPONENT(Operator, Minus)
#define OPERATOR_STAR COMPONENT(Operator, Star)
#define OPERATOR_SLASH COMPONENT(Operator, Slash)
#define OPERATOR_PERCENT COMPONENT(Operator, Percent)
#define OPERATOR_SHIFTLEFT COMPONENT(Operator, ShiftLeft)
#define OPERATOR_SHIFTRIGHT COMPONENT(Operator, ShiftRight)
#define OPERATOR_BITOR COMPONENT(Operator, BitOr)
#define OPERATOR_BITAND COMPONENT(Operator, BitAnd)
#define OPERATOR_BITXOR COMPONENT(Operator, BitXor)
#define OPERATOR_BITNOT COMPONENT(Operator, BitNot)
#define OPERATOR_BOOLEQUALS COMPONENT(Operator, BoolEquals)
#define OPERATOR_BOOLNOTEQUALS COMPONENT(Operator, BoolNotEquals)
#define OPERATOR_BOOLGREATERTHAN COMPONENT(Operator, BoolGreaterThan)
#define OPERATOR_BOOLLESSTHAN COMPONENT(Operator, BoolLessThan)
#define OPERATOR_BOOLGREATERTHANOREQUALS COMPONENT(Operator, BoolGreaterThanOrEquals)
#define OPERATOR_BOOLLESSTHANOREQUALS COMPONENT(Operator, BoolLessThanOrEquals)
#define OPERATOR_BOOLAND COMPONENT(Operator, BoolAnd)
#define OPERATOR_BOOLOR COMPONENT(Operator, BoolOr)
#define OPERATOR_BOOLXOR COMPONENT(Operator, BoolXor)
#define OPERATOR_BOOLNOT COMPONENT(Operator, BoolNot)
#define OPERATOR_TERNARYCONDITIONAL COMPONENT(Operator, TernaryConditional)
#define OPERATOR_DOLLAR COMPONENT(Operator, Dollar)
#define OPERATOR_ADDRESSOF COMPONENT(Operator, AddressOf)
#define OPERATOR_SIZEOF COMPONENT(Operator, SizeOf)
#define OPERATOR_SCOPERESOLUTION COMPONENT(Operator, ScopeResolution)
#define OPERATOR_AT COMPONENT(Operator, AtDeclaration)
#define OPERATOR_ASSIGNMENT COMPONENT(Operator, Assignment)
#define OPERATOR_INHERIT COMPONENT(Operator, Inherit)
#define OPERATOR_PLUS COMPONENT(Operator, Plus)
#define OPERATOR_MINUS COMPONENT(Operator, Minus)
#define OPERATOR_STAR COMPONENT(Operator, Star)
#define OPERATOR_SLASH COMPONENT(Operator, Slash)
#define OPERATOR_PERCENT COMPONENT(Operator, Percent)
#define OPERATOR_SHIFTLEFT COMPONENT(Operator, ShiftLeft)
#define OPERATOR_SHIFTRIGHT COMPONENT(Operator, ShiftRight)
#define OPERATOR_BITOR COMPONENT(Operator, BitOr)
#define OPERATOR_BITAND COMPONENT(Operator, BitAnd)
#define OPERATOR_BITXOR COMPONENT(Operator, BitXor)
#define OPERATOR_BITNOT COMPONENT(Operator, BitNot)
#define OPERATOR_BOOLEQUALS COMPONENT(Operator, BoolEquals)
#define OPERATOR_BOOLNOTEQUALS COMPONENT(Operator, BoolNotEquals)
#define OPERATOR_BOOLGREATERTHAN COMPONENT(Operator, BoolGreaterThan)
#define OPERATOR_BOOLLESSTHAN COMPONENT(Operator, BoolLessThan)
#define OPERATOR_BOOLGREATERTHANOREQUALS COMPONENT(Operator, BoolGreaterThanOrEquals)
#define OPERATOR_BOOLLESSTHANOREQUALS COMPONENT(Operator, BoolLessThanOrEquals)
#define OPERATOR_BOOLAND COMPONENT(Operator, BoolAnd)
#define OPERATOR_BOOLOR COMPONENT(Operator, BoolOr)
#define OPERATOR_BOOLXOR COMPONENT(Operator, BoolXor)
#define OPERATOR_BOOLNOT COMPONENT(Operator, BoolNot)
#define OPERATOR_TERNARYCONDITIONAL COMPONENT(Operator, TernaryConditional)
#define OPERATOR_DOLLAR COMPONENT(Operator, Dollar)
#define OPERATOR_ADDRESSOF COMPONENT(Operator, AddressOf)
#define OPERATOR_SIZEOF COMPONENT(Operator, SizeOf)
#define OPERATOR_SCOPERESOLUTION COMPONENT(Operator, ScopeResolution)
#define VALUETYPE_CUSTOMTYPE COMPONENT(ValueType, CustomType)
#define VALUETYPE_PADDING COMPONENT(ValueType, Padding)
#define VALUETYPE_UNSIGNED COMPONENT(ValueType, Unsigned)
#define VALUETYPE_SIGNED COMPONENT(ValueType, Signed)
#define VALUETYPE_FLOATINGPOINT COMPONENT(ValueType, FloatingPoint)
#define VALUETYPE_INTEGER COMPONENT(ValueType, Integer)
#define VALUETYPE_ANY COMPONENT(ValueType, Any)
#define VALUETYPE_CUSTOMTYPE COMPONENT(ValueType, CustomType)
#define VALUETYPE_PADDING COMPONENT(ValueType, Padding)
#define VALUETYPE_UNSIGNED COMPONENT(ValueType, Unsigned)
#define VALUETYPE_SIGNED COMPONENT(ValueType, Signed)
#define VALUETYPE_FLOATINGPOINT COMPONENT(ValueType, FloatingPoint)
#define VALUETYPE_INTEGER COMPONENT(ValueType, Integer)
#define VALUETYPE_ANY COMPONENT(ValueType, Any)
#define SEPARATOR_ROUNDBRACKETOPEN COMPONENT(Separator, RoundBracketOpen)
#define SEPARATOR_ROUNDBRACKETCLOSE COMPONENT(Separator, RoundBracketClose)
#define SEPARATOR_CURLYBRACKETOPEN COMPONENT(Separator, CurlyBracketOpen)
#define SEPARATOR_CURLYBRACKETCLOSE COMPONENT(Separator, CurlyBracketClose)
#define SEPARATOR_SQUAREBRACKETOPEN COMPONENT(Separator, SquareBracketOpen)
#define SEPARATOR_SQUAREBRACKETCLOSE COMPONENT(Separator, SquareBracketClose)
#define SEPARATOR_COMMA COMPONENT(Separator, Comma)
#define SEPARATOR_DOT COMPONENT(Separator, Dot)
#define SEPARATOR_ENDOFEXPRESSION COMPONENT(Separator, EndOfExpression)
#define SEPARATOR_ENDOFPROGRAM COMPONENT(Separator, EndOfProgram)
#define SEPARATOR_ROUNDBRACKETOPEN COMPONENT(Separator, RoundBracketOpen)
#define SEPARATOR_ROUNDBRACKETCLOSE COMPONENT(Separator, RoundBracketClose)
#define SEPARATOR_CURLYBRACKETOPEN COMPONENT(Separator, CurlyBracketOpen)
#define SEPARATOR_CURLYBRACKETCLOSE COMPONENT(Separator, CurlyBracketClose)
#define SEPARATOR_SQUAREBRACKETOPEN COMPONENT(Separator, SquareBracketOpen)
#define SEPARATOR_SQUAREBRACKETCLOSE COMPONENT(Separator, SquareBracketClose)
#define SEPARATOR_COMMA COMPONENT(Separator, Comma)
#define SEPARATOR_DOT COMPONENT(Separator, Dot)
#define SEPARATOR_ENDOFEXPRESSION COMPONENT(Separator, EndOfExpression)
#define SEPARATOR_ENDOFPROGRAM COMPONENT(Separator, EndOfProgram)

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

@ -8,10 +8,13 @@
#define IMHEX_PLUGIN_SETUP(name, author, description) IMHEX_PLUGIN_SETUP_IMPL(IMHEX_PLUGIN_NAME, name, author, description)
#define IMHEX_PLUGIN_SETUP_IMPL(namespaceName, name, author, description) \
extern "C" [[gnu::visibility("default")]] const char* getPluginName() { return name; } \
extern "C" [[gnu::visibility("default")]] const char* getPluginAuthor() { return author; } \
extern "C" [[gnu::visibility("default")]] const char* getPluginDescription() { return description; } \
extern "C" [[gnu::visibility("default")]] const char* getCompatibleVersion() { return IMHEX_VERSION; } \
extern "C" [[gnu::visibility("default")]] void setImGuiContext(ImGuiContext *ctx) { ImGui::SetCurrentContext(ctx); GImGui = ctx; } \
#define IMHEX_PLUGIN_SETUP_IMPL(namespaceName, name, author, description) \
extern "C" [[gnu::visibility("default")]] const char *getPluginName() { return name; } \
extern "C" [[gnu::visibility("default")]] const char *getPluginAuthor() { return author; } \
extern "C" [[gnu::visibility("default")]] const char *getPluginDescription() { return description; } \
extern "C" [[gnu::visibility("default")]] const char *getCompatibleVersion() { return IMHEX_VERSION; } \
extern "C" [[gnu::visibility("default")]] void setImGuiContext(ImGuiContext *ctx) { \
ImGui::SetCurrentContext(ctx); \
GImGui = ctx; \
} \
extern "C" [[gnu::visibility("default")]] void initializePlugin()

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

@ -36,17 +36,17 @@ namespace hex::prv {
virtual void readRaw(u64 offset, void *buffer, size_t size) = 0;
virtual void writeRaw(u64 offset, const void *buffer, size_t size) = 0;
[[nodiscard]] virtual size_t getActualSize() const = 0;
[[nodiscard]] virtual size_t getActualSize() const = 0;
void applyOverlays(u64 offset, void *buffer, size_t size);
[[nodiscard]] std::map<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,14 +381,13 @@ namespace hex {
}
/* File Handlers */
void ContentRegistry::FileHandler::add(const std::vector<std::string> &extensions, const impl::Callback &callback) {
for (const auto &extension : extensions)
log::info("Registered new data handler for extensions: {}", extension);
ContentRegistry::FileHandler::getEntries().push_back({ extensions, callback });
ContentRegistry::FileHandler::getEntries().push_back({ extensions, callback });
}
std::vector<ContentRegistry::FileHandler::impl::Entry> &ContentRegistry::FileHandler::getEntries() {

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

@ -11,7 +11,7 @@ namespace hex {
}
void ShortcutManager::addShortcut(View *view, const Shortcut &shortcut, const std::function<void()> &callback) {
view->m_shortcuts.insert({ shortcut, callback });
view->m_shortcuts.insert({ shortcut, callback });
}
void ShortcutManager::process(View *currentView, bool ctrl, bool alt, bool shift, bool super, bool focused, u32 keyCode) {

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,29 +89,28 @@ namespace hex::crypt {
public:
using calc_type = uint64_t;
Crc(int bits, calc_type polynomial, calc_type init, calc_type xorout, bool refin, bool refout) :
m_bits(bits),
m_init(init & ((0b10ull << (bits-1)) - 1)),
m_xorout(xorout & ((0b10ull << (bits-1)) - 1)),
m_refin(refin),
m_refout(refout),
table([polynomial, bits](){
auto reflectedpoly= reflect(polynomial & ((0b10ull << (bits-1)) - 1), bits);
std::array<uint64_t, 256> table = {0};
Crc(int bits, calc_type polynomial, calc_type init, calc_type xorout, bool refin, bool refout) : m_bits(bits),
m_init(init & ((0b10ull << (bits - 1)) - 1)),
m_xorout(xorout & ((0b10ull << (bits - 1)) - 1)),
m_refin(refin),
m_refout(refout),
table([polynomial, bits]() {
auto reflectedpoly = reflect(polynomial & ((0b10ull << (bits - 1)) - 1), bits);
std::array<uint64_t, 256> table = { 0 };
for (uint32_t i = 0; i < 256; i++) {
uint64_t c = i;
for (std::size_t j = 0; j < 8; j++) {
if (c & 0b1)
c = reflectedpoly ^ (c >> 1);
else
c >>= 1;
}
table[i] = c;
}
for (uint32_t i = 0; i < 256; i++) {
uint64_t c = i;
for (std::size_t j = 0; j < 8; j++) {
if (c & 0b1)
c = reflectedpoly ^ (c >> 1);
else
c >>= 1;
}
table[i] = c;
}
return table;
}()) {
return table;
}()) {
reset();
};
@ -157,7 +149,7 @@ namespace hex::crypt {
};
template<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,10 +54,10 @@ 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);
auto bytesRead = fread(bytes.data(), 1, bytes.size(), this->m_file);
bytes.resize(bytesRead);
@ -65,13 +65,13 @@ namespace hex {
}
std::string File::readString(size_t numBytes) {
if (!isValid()) return { };
if (!isValid()) return {};
if (getSize() == 0) return { };
if (getSize() == 0) return {};
auto bytes = readBytes(numBytes);
return { reinterpret_cast<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,22 +188,21 @@ namespace hex {
}
}
PyImport_AppendInittab("_imhex", []() -> PyObject* {
PyImport_AppendInittab("_imhex", []() -> PyObject * {
static PyMethodDef ImHexMethods[] = {
{ "get_file_path", &LoaderScript::Py_getFilePath, METH_NOARGS, "Returns the path of the file being loaded." },
{ "patch", &LoaderScript::Py_addPatch, METH_VARARGS, "Patches a region of memory" },
{ "add_bookmark", &LoaderScript::Py_addBookmark, METH_VARARGS, "Adds a bookmark" },
{ "add_struct", &LoaderScript::Py_addStruct, METH_VARARGS, "Adds a struct" },
{ "add_union", &LoaderScript::Py_addUnion, METH_VARARGS, "Adds a union" },
{ nullptr, nullptr, 0, nullptr }
{"get_file_path", &LoaderScript::Py_getFilePath, METH_NOARGS, "Returns the path of the file being loaded."},
{ "patch", &LoaderScript::Py_addPatch, METH_VARARGS, "Patches a region of memory" },
{ "add_bookmark", &LoaderScript::Py_addBookmark, METH_VARARGS, "Adds a bookmark" },
{ "add_struct", &LoaderScript::Py_addStruct, METH_VARARGS, "Adds a struct" },
{ "add_union", &LoaderScript::Py_addUnion, METH_VARARGS, "Adds a union" },
{ nullptr, nullptr, 0, nullptr }
};
static PyModuleDef ImHexModule = {
PyModuleDef_HEAD_INIT, "imhex", nullptr, -1, ImHexMethods, nullptr, nullptr, nullptr, nullptr
};
auto module = PyModule_Create(&ImHexModule);
auto module = PyModule_Create(&ImHexModule);
if (module == nullptr)
return nullptr;

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

@ -17,7 +17,7 @@ namespace hex {
buffer.resize(buffer.size() + sizeof(T));
std::memcpy((&buffer.back() - sizeof(T)) + 1, &bytes, sizeof(T));
}
std::vector<u8> generateIPSPatch(const Patches &patches) {
std::vector<u8> result;
@ -43,19 +43,21 @@ namespace hex {
bytes.push_back(values[i]);
if (bytes.size() > 0xFFFF || startAddress > 0xFF'FFFF)
return { };
return {};
u32 address = startAddress.value();
auto addressBytes = reinterpret_cast<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,210 +19,203 @@
namespace hex {
std::string getExecutablePath() {
#if defined(OS_WINDOWS)
std::string exePath(MAX_PATH, '\0');
GetModuleFileName(nullptr, exePath.data(), exePath.length());
#if defined(OS_WINDOWS)
std::string exePath(MAX_PATH, '\0');
GetModuleFileName(nullptr, exePath.data(), exePath.length());
return exePath;
#elif defined(OS_LINUX)
std::string exePath(PATH_MAX, '\0');
readlink("/proc/self/exe", exePath.data(), PATH_MAX);
return exePath;
#elif defined(OS_LINUX)
std::string exePath(PATH_MAX, '\0');
readlink("/proc/self/exe", exePath.data(), PATH_MAX);
return exePath;
#elif defined(OS_MACOS)
return getMacExecutableDirectoryPath();
#else
return "";
#endif
return exePath;
#elif defined(OS_MACOS)
return getMacExecutableDirectoryPath();
#else
return "";
#endif
}
std::vector<fs::path> getPath(ImHexPath path, bool listNonExisting) {
std::vector<fs::path> result;
#if defined(OS_WINDOWS)
const auto exePath = getExecutablePath();
const auto parentDir = fs::path(exePath).parent_path();
#if defined(OS_WINDOWS)
const auto exePath = getExecutablePath();
const auto parentDir = fs::path(exePath).parent_path();
fs::path appDataDir;
{
LPWSTR wAppDataPath = nullptr;
if (!SUCCEEDED(SHGetKnownFolderPath(FOLDERID_LocalAppData, KF_FLAG_CREATE, nullptr, &wAppDataPath)))
throw std::runtime_error("Failed to get APPDATA folder path");
fs::path appDataDir;
{
LPWSTR wAppDataPath = nullptr;
if (!SUCCEEDED(SHGetKnownFolderPath(FOLDERID_LocalAppData, KF_FLAG_CREATE, nullptr, &wAppDataPath)))
throw std::runtime_error("Failed to get APPDATA folder path");
appDataDir = wAppDataPath;
CoTaskMemFree(wAppDataPath);
}
appDataDir = wAppDataPath;
CoTaskMemFree(wAppDataPath);
}
std::vector<fs::path> paths = { parentDir, appDataDir / "imhex" };
std::vector<fs::path> paths = { parentDir, appDataDir / "imhex" };
switch (path) {
case ImHexPath::Patterns:
std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path){
return (path / "patterns").string();
});
break;
case ImHexPath::PatternsInclude:
std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path){
return (path / "includes").string();
});
break;
case ImHexPath::Magic:
std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path){
return (path / "magic").string();
});
break;
case ImHexPath::Python:
std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path){
return (path / "python").string();
});
break;
case ImHexPath::Plugins:
std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path){
return (path / "plugins").string();
});
break;
case ImHexPath::Yara:
std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path){
return (path / "yara").string();
});
break;
case ImHexPath::Config:
return { (appDataDir / "imhex" / "config").string() };
case ImHexPath::Resources:
std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path){
return (path / "resources").string();
});
break;
case ImHexPath::Constants:
std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path){
return (path / "constants").string();
});
break;
case ImHexPath::Encodings:
std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path){
return (path / "encodings").string();
});
break;
case ImHexPath::Logs:
std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path){
return (path / "logs").string();
});
break;
default: __builtin_unreachable();
}
#elif defined(OS_MACOS)
// Get path to special directories
const auto exePath = getExecutablePath();
const fs::path applicationSupportDir(getMacApplicationSupportDirectoryPath());
switch (path) {
case ImHexPath::Patterns:
std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path) {
return (path / "patterns").string();
});
break;
case ImHexPath::PatternsInclude:
std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path) {
return (path / "includes").string();
});
break;
case ImHexPath::Magic:
std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path) {
return (path / "magic").string();
});
break;
case ImHexPath::Python:
std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path) {
return (path / "python").string();
});
break;
case ImHexPath::Plugins:
std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path) {
return (path / "plugins").string();
});
break;
case ImHexPath::Yara:
std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path) {
return (path / "yara").string();
});
break;
case ImHexPath::Config:
return { (appDataDir / "imhex" / "config").string() };
case ImHexPath::Resources:
std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path) {
return (path / "resources").string();
});
break;
case ImHexPath::Constants:
std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path) {
return (path / "constants").string();
});
break;
case ImHexPath::Encodings:
std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path) {
return (path / "encodings").string();
});
break;
case ImHexPath::Logs:
std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path) {
return (path / "logs").string();
});
break;
default:
__builtin_unreachable();
}
#elif defined(OS_MACOS)
// Get path to special directories
const auto exePath = getExecutablePath();
const fs::path applicationSupportDir(getMacApplicationSupportDirectoryPath());
std::vector<fs::path> paths = { exePath, applicationSupportDir };
std::vector<fs::path> paths = { exePath, applicationSupportDir };
switch (path) {
case ImHexPath::Patterns:
result.push_back((applicationSupportDir / "patterns").string());
break;
case ImHexPath::PatternsInclude:
result.push_back((applicationSupportDir / "includes").string());
break;
case ImHexPath::Magic:
result.push_back((applicationSupportDir / "magic").string());
break;
case ImHexPath::Python:
result.push_back((applicationSupportDir / "python").string());
break;
case ImHexPath::Plugins:
std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path){
return (path / "plugins").string();
});
break;
case ImHexPath::Yara:
result.push_back((applicationSupportDir / "yara").string());
break;
case ImHexPath::Config:
result.push_back((applicationSupportDir / "config").string());
break;
case ImHexPath::Resources:
result.push_back((applicationSupportDir / "resources").string());
break;
case ImHexPath::Constants:
result.push_back((applicationSupportDir / "constants").string());
break;
case ImHexPath::Encodings:
result.push_back((applicationSupportDir / "encodings").string());
break;
case ImHexPath::Logs:
result.push_back((applicationSupportDir / "logs").string());
break;
default: __builtin_unreachable();
}
#else
std::vector<fs::path> configDirs = xdg::ConfigDirs();
std::vector<fs::path> dataDirs = xdg::DataDirs();
switch (path) {
case ImHexPath::Patterns:
result.push_back((applicationSupportDir / "patterns").string());
break;
case ImHexPath::PatternsInclude:
result.push_back((applicationSupportDir / "includes").string());
break;
case ImHexPath::Magic:
result.push_back((applicationSupportDir / "magic").string());
break;
case ImHexPath::Python:
result.push_back((applicationSupportDir / "python").string());
break;
case ImHexPath::Plugins:
std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path) {
return (path / "plugins").string();
});
break;
case ImHexPath::Yara:
result.push_back((applicationSupportDir / "yara").string());
break;
case ImHexPath::Config:
result.push_back((applicationSupportDir / "config").string());
break;
case ImHexPath::Resources:
result.push_back((applicationSupportDir / "resources").string());
break;
case ImHexPath::Constants:
result.push_back((applicationSupportDir / "constants").string());
break;
case ImHexPath::Encodings:
result.push_back((applicationSupportDir / "encodings").string());
break;
case ImHexPath::Logs:
result.push_back((applicationSupportDir / "logs").string());
break;
default:
__builtin_unreachable();
}
#else
std::vector<fs::path> configDirs = xdg::ConfigDirs();
std::vector<fs::path> dataDirs = xdg::DataDirs();
configDirs.insert(configDirs.begin(), xdg::ConfigHomeDir());
dataDirs.insert(dataDirs.begin(), xdg::DataHomeDir());
configDirs.insert(configDirs.begin(), xdg::ConfigHomeDir());
dataDirs.insert(dataDirs.begin(), xdg::DataHomeDir());
for (auto &dir : dataDirs)
dir = dir / "imhex";
for (auto &dir : dataDirs)
dir = dir / "imhex";
const auto exePath = getExecutablePath();
const auto exePath = getExecutablePath();
if (!exePath.empty())
dataDirs.emplace(dataDirs.begin(), fs::path(exePath.data()).parent_path());
if (!exePath.empty())
dataDirs.emplace(dataDirs.begin(), fs::path(exePath.data()).parent_path());
switch (path) {
case ImHexPath::Patterns:
std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result),
[](auto p) { return (p / "patterns").string(); });
break;
case ImHexPath::PatternsInclude:
std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result),
[](auto p) { return (p / "includes").string(); });
break;
case ImHexPath::Magic:
std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result),
[](auto p) { return (p / "magic").string(); });
break;
case ImHexPath::Python:
std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result),
[](auto p) { return (p).string(); });
break;
case ImHexPath::Plugins:
std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result),
[](auto p) { return (p / "plugins").string(); });
break;
case ImHexPath::Yara:
std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result),
[](auto p) { return (p / "yara").string(); });
break;
case ImHexPath::Config:
std::transform(configDirs.begin(), configDirs.end(), std::back_inserter(result),
[](auto p) { return (p / "imhex").string(); });
break;
case ImHexPath::Resources:
std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result),
[](auto p) { return (p / "resources").string(); });
break;
case ImHexPath::Constants:
std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result),
[](auto p) { return (p / "constants").string(); });
break;
case ImHexPath::Encodings:
std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result),
[](auto p) { return (p / "encodings").string(); });
break;
case ImHexPath::Logs:
std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result),
[](auto p) { return (p / "logs").string(); });
break;
default: __builtin_unreachable();
}
#endif
switch (path) {
case ImHexPath::Patterns:
std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result), [](auto p) { return (p / "patterns").string(); });
break;
case ImHexPath::PatternsInclude:
std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result), [](auto p) { return (p / "includes").string(); });
break;
case ImHexPath::Magic:
std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result), [](auto p) { return (p / "magic").string(); });
break;
case ImHexPath::Python:
std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result), [](auto p) { return (p).string(); });
break;
case ImHexPath::Plugins:
std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result), [](auto p) { return (p / "plugins").string(); });
break;
case ImHexPath::Yara:
std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result), [](auto p) { return (p / "yara").string(); });
break;
case ImHexPath::Config:
std::transform(configDirs.begin(), configDirs.end(), std::back_inserter(result), [](auto p) { return (p / "imhex").string(); });
break;
case ImHexPath::Resources:
std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result), [](auto p) { return (p / "resources").string(); });
break;
case ImHexPath::Constants:
std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result), [](auto p) { return (p / "constants").string(); });
break;
case ImHexPath::Encodings:
std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result), [](auto p) { return (p / "encodings").string(); });
break;
case ImHexPath::Logs:
std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result), [](auto p) { return (p / "logs").string(); });
break;
default:
__builtin_unreachable();
}
#endif
if (!listNonExisting) {
result.erase(std::remove_if(result.begin(), result.end(), [](const auto& path){
return !fs::is_directory(path);
}), result.end());
result.erase(std::remove_if(result.begin(), result.end(), [](const auto &path) {
return !fs::is_directory(path);
}),
result.end());
}
return result;

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);
@ -48,9 +55,9 @@ namespace hex {
std::ifstream projectFile(filePath.c_str());
projectFile >> projectFileData;
ProjectFile::s_filePath = fs::path(projectFileData["filePath"].get<std::string>());
ProjectFile::s_pattern = projectFileData["pattern"];
ProjectFile::s_patches = projectFileData["patches"].get<Patches>();
ProjectFile::s_filePath = fs::path(projectFileData["filePath"].get<std::string>());
ProjectFile::s_pattern = projectFileData["pattern"];
ProjectFile::s_patches = projectFileData["patches"].get<Patches>();
ProjectFile::s_dataProcessorContent = projectFileData["dataProcessor"];
ProjectFile::s_bookmarks.clear();
@ -82,10 +89,10 @@ namespace hex {
filePath = ProjectFile::s_currProjectFilePath;
try {
projectFileData["filePath"] = ProjectFile::s_filePath;
projectFileData["pattern"] = ProjectFile::s_pattern;
projectFileData["patches"] = ProjectFile::s_patches;
projectFileData["dataProcessor"] = ProjectFile::s_dataProcessorContent;
projectFileData["filePath"] = ProjectFile::s_filePath;
projectFileData["pattern"] = ProjectFile::s_pattern;
projectFileData["patches"] = ProjectFile::s_patches;
projectFileData["dataProcessor"] = ProjectFile::s_dataProcessorContent;
for (auto &bookmark : ProjectFile::s_bookmarks) {
to_json(projectFileData["bookmarks"].emplace_back(), bookmark);

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;
@ -37,14 +37,14 @@ namespace hex {
std::vector<ContentRegistry::Interface::impl::DrawCallback> SharedData::welcomeScreenEntries;
std::vector<ContentRegistry::Interface::impl::DrawCallback> SharedData::footerItems;
std::vector<ContentRegistry::Interface::impl::SidebarItem> SharedData::sidebarItems;
std::vector<ContentRegistry::Interface::impl::SidebarItem> SharedData::sidebarItems;
std::vector<ContentRegistry::Interface::impl::DrawCallback> SharedData::toolbarItems;
std::vector<ContentRegistry::Interface::impl::Layout> SharedData::layouts;
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,16 +6,16 @@
namespace hex {
Socket::Socket(const std::string &address, u16 port) {
#if defined(OS_WINDOWS)
FIRST_TIME {
WSAData wsa;
WSAStartup(MAKEWORD(2, 2), &wsa);
};
#if defined(OS_WINDOWS)
FIRST_TIME {
WSAData wsa;
WSAStartup(MAKEWORD(2, 2), &wsa);
};
FINAL_CLEANUP {
WSACleanup();
};
#endif
FINAL_CLEANUP {
WSACleanup();
};
#endif
this->connect(address, port);
}
@ -34,7 +34,7 @@ namespace hex {
void Socket::writeBytes(const std::vector<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)
client.sin_addr.S_un.S_addr = ::inet_addr(address.c_str());
#else
client.sin_addr.s_addr = ::inet_addr(address.c_str());
#endif
#if defined(OS_WINDOWS)
client.sin_addr.S_un.S_addr = ::inet_addr(address.c_str());
#else
client.sin_addr.s_addr = ::inet_addr(address.c_str());
#endif
this->m_connected = ::connect(this->m_socket, reinterpret_cast<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)
closesocket(this->m_socket);
#else
close(this->m_socket);
#endif
#if defined(OS_WINDOWS)
closesocket(this->m_socket);
#else
close(this->m_socket);
#endif
}
this->m_connected = false;

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
#warning "Unknown OS, can't open webpages"
#endif
#else
#warning "Unknown OS, can't open webpages"
#endif
}
void openWebpage(std::string url) {
@ -194,18 +244,17 @@ namespace hex {
if (url.find("://") == std::string::npos)
url = "https://" + url;
#if defined(OS_WINDOWS)
ShellExecute(nullptr, "open", url.c_str(), nullptr, nullptr, SW_SHOWNORMAL);
#elif defined(OS_MACOS)
CFURLRef urlRef = CFURLCreateWithBytes(nullptr, reinterpret_cast<u8*>(url.data()), url.length(), kCFStringEncodingASCII, nullptr);
LSOpenCFURLRef(urlRef, nullptr);
CFRelease(urlRef);
#elif defined(OS_LINUX)
system(hex::format("xdg-open {0}", url).c_str());
#else
#warning "Unknown OS, can't open webpages"
#endif
#if defined(OS_WINDOWS)
ShellExecute(nullptr, "open", url.c_str(), nullptr, nullptr, SW_SHOWNORMAL);
#elif defined(OS_MACOS)
CFURLRef urlRef = CFURLCreateWithBytes(nullptr, reinterpret_cast<u8 *>(url.data()), url.length(), kCFStringEncodingASCII, nullptr);
LSOpenCFURLRef(urlRef, nullptr);
CFRelease(urlRef);
#elif defined(OS_LINUX)
system(hex::format("xdg-open {0}", url).c_str());
#else
#warning "Unknown OS, can't open webpages"
#endif
}
void openFileBrowser(const std::string &title, DialogMode mode, const std::vector<nfdfilteritem_t> &validExtensions, const std::function<void(fs::path)> &callback, const std::string &defaultPath) {
@ -214,16 +263,17 @@ namespace hex {
nfdchar_t *outPath;
nfdresult_t result;
switch (mode) {
case DialogMode::Open:
result = NFD::OpenDialog(outPath, validExtensions.data(), validExtensions.size(), defaultPath.c_str());
break;
case DialogMode::Save:
result = NFD::SaveDialog(outPath, validExtensions.data(), validExtensions.size(), defaultPath.c_str());
break;
case DialogMode::Folder:
result = NFD::PickFolder(outPath, defaultPath.c_str());
break;
default: __builtin_unreachable();
case DialogMode::Open:
result = NFD::OpenDialog(outPath, validExtensions.data(), validExtensions.size(), defaultPath.c_str());
break;
case DialogMode::Save:
result = NFD::SaveDialog(outPath, validExtensions.data(), validExtensions.size(), defaultPath.c_str());
break;
case DialogMode::Folder:
result = NFD::PickFolder(outPath, defaultPath.c_str());
break;
default:
__builtin_unreachable();
}
if (result == NFD_OKAY) {
@ -265,30 +315,30 @@ namespace hex {
result = (sign << 31) | ((exponent + (0x7F - 15)) << 23) | (mantissa << 13);
}
return reinterpret_cast<float&>(result);
return reinterpret_cast<float &>(result);
}
bool isProcessElevated() {
#if defined (OS_WINDOWS)
bool elevated = false;
HANDLE token = INVALID_HANDLE_VALUE;
#if defined(OS_WINDOWS)
bool elevated = false;
HANDLE token = INVALID_HANDLE_VALUE;
if (::OpenProcessToken(::GetCurrentProcess(), TOKEN_QUERY, &token)) {
TOKEN_ELEVATION elevation;
DWORD elevationSize = sizeof(TOKEN_ELEVATION);
if (::OpenProcessToken(::GetCurrentProcess(), TOKEN_QUERY, &token)) {
TOKEN_ELEVATION elevation;
DWORD elevationSize = sizeof(TOKEN_ELEVATION);
if (::GetTokenInformation(token, TokenElevation, &elevation, sizeof(elevation), &elevationSize))
elevated = elevation.TokenIsElevated;
}
if (::GetTokenInformation(token, TokenElevation, &elevation, sizeof(elevation), &elevationSize))
elevated = elevation.TokenIsElevated;
}
if (token != INVALID_HANDLE_VALUE)
::CloseHandle(token);
if (token != INVALID_HANDLE_VALUE)
::CloseHandle(token);
return elevated;
return elevated;
#elif defined(OS_LINUX) || defined (OS_MACOS)
return getuid() < 0 || getuid() != geteuid();
#endif
#elif defined(OS_LINUX) || defined(OS_MACOS)
return getuid() < 0 || getuid() != geteuid();
#endif
}
}

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;
{
@ -79,49 +79,48 @@ namespace hex::pl {
LogConsole::abortEvaluation(hex::format("no variable with name '{}' found", name));
Token::Literal castedLiteral = std::visit(overloaded {
[&](double &value) -> Token::Literal {
if (dynamic_cast<PatternDataUnsigned*>(pattern))
return u128(value) & bitmask(pattern->getSize() * 8);
else if (dynamic_cast<PatternDataSigned*>(pattern))
return i128(value) & bitmask(pattern->getSize() * 8);
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))
return value;
else
LogConsole::abortEvaluation(hex::format("cannot cast type 'string' to type '{}'", pattern->getTypeName()));
},
[&](PatternData * const &value) -> Token::Literal {
if (value->getTypeName() == pattern->getTypeName())
return value;
else
LogConsole::abortEvaluation(hex::format("cannot cast type '{}' to type '{}'", value->getTypeName(), pattern->getTypeName()));
},
[&](auto &&value) -> Token::Literal {
if (dynamic_cast<PatternDataUnsigned*>(pattern) || dynamic_cast<PatternDataEnum*>(pattern))
return u128(value) & bitmask(pattern->getSize() * 8);
else if (dynamic_cast<PatternDataSigned*>(pattern))
return i128(value) & bitmask(pattern->getSize() * 8);
else if (dynamic_cast<PatternDataCharacter*>(pattern))
return char(value);
else if (dynamic_cast<PatternDataBoolean*>(pattern))
return bool(value);
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);
[&](double &value) -> Token::Literal {
if (dynamic_cast<PatternDataUnsigned *>(pattern))
return u128(value) & bitmask(pattern->getSize() * 8);
else if (dynamic_cast<PatternDataSigned *>(pattern))
return i128(value) & bitmask(pattern->getSize() * 8);
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))
return value;
else
LogConsole::abortEvaluation(hex::format("cannot cast type 'string' to type '{}'", pattern->getTypeName()));
},
[&](PatternData *const &value) -> Token::Literal {
if (value->getTypeName() == pattern->getTypeName())
return value;
else
LogConsole::abortEvaluation(hex::format("cannot cast type '{}' to type '{}'", value->getTypeName(), pattern->getTypeName()));
},
[&](auto &&value) -> Token::Literal {
if (dynamic_cast<PatternDataUnsigned *>(pattern) || dynamic_cast<PatternDataEnum *>(pattern))
return u128(value) & bitmask(pattern->getSize() * 8);
else if (dynamic_cast<PatternDataSigned *>(pattern))
return i128(value) & bitmask(pattern->getSize() * 8);
else if (dynamic_cast<PatternDataCharacter *>(pattern))
return char(value);
else if (dynamic_cast<PatternDataBoolean *>(pattern))
return bool(value);
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);
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) {
@ -170,9 +169,9 @@ namespace hex::pl {
this->setVariable(name, this->m_inVariables[name]);
delete pattern;
} else {
patterns.push_back(pattern);
}
} else {
patterns.push_back(pattern);
}
} else {
auto newPatterns = node->createPatterns(this);
std::copy(newPatterns.begin(), newPatterns.end(), std::back_inserter(patterns));
@ -185,7 +184,7 @@ namespace hex::pl {
if (mainFunction.parameterCount > 0)
LogConsole::abortEvaluation("main function may not accept any arguments");
auto result = mainFunction.func(this, { });
auto result = mainFunction.func(this, {});
if (result) {
auto returnCode = Token::literalToSigned(*result);

View File

@ -7,10 +7,10 @@
namespace hex::pl {
#define TOKEN(type, value) Token::Type::type, Token::type::value, lineNumber
#define TOKEN(type, value) Token::Type::type, Token::type::value, lineNumber
#define VALUE_TOKEN(type, value) Token::Type::type, value, lineNumber
std::string matchTillInvalid(const char* characters, std::function<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())
@ -425,7 +469,7 @@ namespace hex::pl {
else if (identifier == "continue")
tokens.emplace_back(TOKEN(Keyword, Continue));
// Check for built-in types
// Check for built-in types
else if (identifier == "u8")
tokens.emplace_back(TOKEN(ValueType, Unsigned8Bit));
else if (identifier == "s8")
@ -480,13 +524,12 @@ namespace hex::pl {
offset += getIntegerLiteralLength(&code[offset]);
} else
throwLexerError("unknown token", lineNumber);
}
tokens.emplace_back(TOKEN(Separator, EndOfProgram));
} catch (LexerError &e) {
this->m_error = e;
return { };
return {};
}

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) {
@ -75,15 +73,14 @@ namespace hex::pl {
if (MATCHES(sequence(OPERATOR_SCOPERESOLUTION, IDENTIFIER))) {
if (peek(OPERATOR_SCOPERESOLUTION, 0) && peek(IDENTIFIER, 1)) {
typeName += "::";
continue;
continue;
} else {
if (!this->m_types.contains(typeName))
throwParseError(hex::format("cannot access scope of invalid type '{}'", typeName), -1);
return create(new ASTNodeScopeResolution(this->m_types[typeName]->clone(), getValue<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)))
@ -732,17 +725,16 @@ namespace hex::pl {
else if (MATCHES(sequence(KEYWORD_BE)))
endian = std::endian::big;
if (MATCHES(sequence(IDENTIFIER))) { // Custom type
if (MATCHES(sequence(IDENTIFIER))) { // Custom type
std::string typeName = parseNamespaceResolution();
if (this->m_types.contains(typeName))
return create(new ASTNodeTypeDecl({ }, this->m_types[typeName]->clone(), endian));
return create(new ASTNodeTypeDecl({}, this->m_types[typeName]->clone(), endian));
else if (this->m_types.contains(getNamespacePrefixedName(typeName)))
return create(new ASTNodeTypeDecl({ }, this->m_types[getNamespacePrefixedName(typeName)]->clone(), endian));
return create(new ASTNodeTypeDecl({}, this->m_types[getNamespacePrefixedName(typeName)]->clone(), endian));
else
throwParseError(hex::format("unknown type '{}'", typeName));
}
else if (MATCHES(sequence(VALUETYPE_ANY))) { // Builtin type
} else if (MATCHES(sequence(VALUETYPE_ANY))) { // Builtin type
auto type = getValue<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,20 +1004,23 @@ 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))) {
auto name = getValue<Token::Identifier>(-2).get();
bitfieldNode->addEntry(name, parseMathematicalExpression());
} else if (MATCHES(sequence(VALUETYPE_PADDING, OPERATOR_INHERIT))) {
bitfieldNode->addEntry("padding", parseMathematicalExpression());
bitfieldNode->addEntry("padding", parseMathematicalExpression());
} else if (MATCHES(sequence(SEPARATOR_ENDOFPROGRAM)))
throwParseError("unexpected end of program", -2);
else
@ -1026,7 +1030,8 @@ namespace hex::pl {
throwParseError("missing ';' at end of expression", -1);
// Consume superfluous semicolons
while (MATCHES(sequence(SEPARATOR_ENDOFEXPRESSION)));
while (MATCHES(sequence(SEPARATOR_ENDOFEXPRESSION)))
;
}
enumGuard.release();
@ -1035,7 +1040,7 @@ namespace hex::pl {
}
// (parseType) Identifier @ Integer
ASTNode* Parser::parseVariablePlacement(ASTNodeTypeDecl *type) {
ASTNode *Parser::parseVariablePlacement(ASTNodeTypeDecl *type) {
bool inVariable = false;
bool outVariable = false;
@ -1046,8 +1051,7 @@ namespace hex::pl {
placementOffset = parseMathematicalExpression();
} else if (MATCHES(sequence(KEYWORD_IN))) {
inVariable = true;
}
else if (MATCHES(sequence(KEYWORD_OUT))) {
} else if (MATCHES(sequence(KEYWORD_OUT))) {
outVariable = true;
}
@ -1055,7 +1059,7 @@ namespace hex::pl {
}
// (parseType) Identifier[[(parseMathematicalExpression)]] @ Integer
ASTNode* Parser::parseArrayVariablePlacement(ASTNodeTypeDecl *type) {
ASTNode *Parser::parseArrayVariablePlacement(ASTNodeTypeDecl *type) {
auto name = getValue<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,27 +1198,28 @@ namespace hex::pl {
throwParseError("missing ';' at end of expression", -1);
// Consume superfluous semicolons
while (MATCHES(sequence(SEPARATOR_ENDOFEXPRESSION)));
while (MATCHES(sequence(SEPARATOR_ENDOFEXPRESSION)))
;
statementGuard.release();
return { statement };
}
ASTNodeTypeDecl* Parser::addType(const std::string &name, ASTNode *node, std::optional<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))
throwParseError(hex::format("redefinition of type '{}'", typeName));
auto typeDecl = create(new ASTNodeTypeDecl(typeName, node, endian));
this->m_types.insert({ typeName, typeDecl });
this->m_types.insert({ typeName, typeDecl });
return typeDecl;
}
// <(parseNamespace)...> EndOfProgram
std::optional<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;
@ -67,7 +66,7 @@ namespace hex::pl {
if (includeFile[0] != '/') {
for (const auto &dir : hex::getPath(ImHexPath::PatternsInclude)) {
std::string tempPath = hex::format("{0}/{1}", dir.string().c_str(), includeFile.c_str());
std::string tempPath = hex::format("{0}/{1}", dir.string().c_str(), includeFile.c_str());
if (fs::exists(tempPath)) {
includePath = tempPath;
break;
@ -191,12 +190,12 @@ namespace hex::pl {
std::vector<std::tuple<std::string, std::string, u32>> sortedDefines;
std::copy(this->m_defines.begin(), this->m_defines.end(), std::back_inserter(sortedDefines));
std::sort(sortedDefines.begin(), sortedDefines.end(), [](const auto &left, const auto &right) {
return std::get<0>(left).size() > std::get<0>(right).size();
return std::get<0>(left).size() > std::get<0>(right).size();
});
for (const auto &[define, value, defineLine] : sortedDefines) {
i32 index = 0;
while((index = output.find(define, index)) != std::string::npos) {
while ((index = output.find(define, index)) != std::string::npos) {
output.replace(index, define.length(), value);
index += value.length();
}
@ -213,13 +212,13 @@ namespace hex::pl {
}
} catch (PreprocessorError &e) {
this->m_error = e;
return { };
return {};
}
return output;
}
void Preprocessor::addPragmaHandler(const std::string &pragmaType, const std::function<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

@ -59,13 +59,13 @@ namespace hex::prv {
i128 overlapMin = std::max(offset, overlayOffset);
i128 overlapMax = std::min(offset + size, overlayOffset + overlaySize);
if (overlapMax > overlapMin)
std::memcpy(static_cast<u8*>(buffer) + std::max<i128>(0, overlapMin - offset), overlay->getData().data() + std::max<i128>(0, overlapMin - overlayOffset), overlapMax - overlapMin);
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::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);
@ -82,7 +82,7 @@ namespace ImGui {
// Render
const ImU32 col = hovered ? GetColorU32(ImGuiCol_ButtonHovered) : GetColorU32(ImGuiCol_ButtonActive);
PushStyleColor(ImGuiCol_Text, ImU32(col));
TextEx(label, NULL, ImGuiTextFlags_NoWidthForLargeClippedText); // Skip formatting
TextEx(label, NULL, ImGuiTextFlags_NoWidthForLargeClippedText); // Skip formatting
GetWindowDrawList()->AddLine(ImVec2(pos.x, pos.y + size.y), pos + size, ImU32(col));
PopStyleColor();
@ -90,13 +90,13 @@ namespace ImGui {
return pressed;
}
bool BulletHyperlink(const char* label, const ImVec2& size_arg, ImGuiButtonFlags flags) {
ImGuiWindow* window = GetCurrentWindow();
bool BulletHyperlink(const char *label, const ImVec2 &size_arg, ImGuiButtonFlags flags) {
ImGuiWindow *window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
ImGuiContext &g = *GImGui;
const ImGuiStyle &style = g.Style;
const ImGuiID id = window->GetID(label);
const ImVec2 label_size = CalcTextSize(label, NULL, true);
@ -125,19 +125,19 @@ namespace ImGui {
return pressed;
}
bool DescriptionButton(const char* label, const char* description, const ImVec2& size_arg, ImGuiButtonFlags flags) {
ImGuiWindow* window = GetCurrentWindow();
bool DescriptionButton(const char *label, const char *description, const ImVec2 &size_arg, ImGuiButtonFlags flags) {
ImGuiWindow *window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
ImGuiContext &g = *GImGui;
const ImGuiStyle &style = g.Style;
const ImGuiID id = window->GetID(label);
const ImVec2 text_size = CalcTextSize((std::string(label) + "\n " + std::string(description)).c_str(), NULL, true);
const ImVec2 label_size = CalcTextSize(label, NULL, true);
ImVec2 pos = window->DC.CursorPos;
if ((flags & ImGuiButtonFlags_AlignTextBaseLine) && style.FramePadding.y < window->DC.CurrLineTextBaseOffset) // Try to vertically align buttons that are smaller/have no padding so that text baseline matches (bit hacky, since it shouldn't be a flag)
if ((flags & ImGuiButtonFlags_AlignTextBaseLine) && style.FramePadding.y < window->DC.CurrLineTextBaseOffset) // Try to vertically align buttons that are smaller/have no padding so that text baseline matches (bit hacky, since it shouldn't be a flag)
pos.y += window->DC.CurrLineTextBaseOffset - style.FramePadding.y;
ImVec2 size = CalcItemSize(size_arg, text_size.x + style.FramePadding.x * 4.0f, text_size.y + style.FramePadding.y * 4.0f);
@ -154,7 +154,8 @@ namespace ImGui {
ImGui::PushStyleVar(ImGuiStyleVar_ButtonTextAlign, ImVec2(0.0, 0.5));
// Render
const ImU32 col = GetCustomColorU32((held && hovered) ? ImGuiCustomCol_DescButtonActive : hovered ? ImGuiCustomCol_DescButtonHovered : ImGuiCustomCol_DescButton);
const ImU32 col = GetCustomColorU32((held && hovered) ? ImGuiCustomCol_DescButtonActive : hovered ? ImGuiCustomCol_DescButtonHovered
: ImGuiCustomCol_DescButton);
RenderNavHighlight(bb, id);
RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding);
PushStyleColor(ImGuiCol_Text, GetColorU32(ImGuiCol_ButtonActive));
@ -167,15 +168,15 @@ namespace ImGui {
ImGui::PopStyleVar();
// Automatically close popups
//if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup))
// if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup))
// CloseCurrentPopup();
IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags);
return pressed;
}
void UnderlinedText(const char* label, ImColor color, const ImVec2& size_arg) {
ImGuiWindow* window = GetCurrentWindow();
void UnderlinedText(const char *label, ImColor color, const ImVec2 &size_arg) {
ImGuiWindow *window = GetCurrentWindow();
const ImVec2 label_size = CalcTextSize(label, NULL, true);
@ -183,7 +184,7 @@ namespace ImGui {
ImVec2 size = CalcItemSize(size_arg, label_size.x, label_size.y);
PushStyleColor(ImGuiCol_Text, ImU32(color));
TextEx(label, NULL, ImGuiTextFlags_NoWidthForLargeClippedText); // Skip formatting
TextEx(label, NULL, ImGuiTextFlags_NoWidthForLargeClippedText); // Skip formatting
GetWindowDrawList()->AddLine(ImVec2(pos.x, pos.y + size.y), pos + size, ImU32(color));
PopStyleColor();
}
@ -196,10 +197,9 @@ namespace ImGui {
} else {
widgets();
}
}
void TextSpinner(const char* label) {
void TextSpinner(const char *label) {
ImGui::Text("[%c] %s", "|/-\\"[ImU32(ImGui::GetTime() * 20) % 4], label);
}
@ -237,78 +237,78 @@ namespace ImGui {
}
ImU32 GetCustomColorU32(ImGuiCustomCol idx, float alpha_mul) {
auto& customData = *static_cast<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);
colors[ImGuiCustomCol_DescButtonActive] = ImColor(60, 60, 60);
colors[ImGuiCustomCol_DescButton] = ImColor(20, 20, 20);
colors[ImGuiCustomCol_DescButtonHovered] = ImColor(40, 40, 40);
colors[ImGuiCustomCol_DescButtonActive] = ImColor(60, 60, 60);
colors[ImGuiCustomCol_ToolbarGray] = ImColor(230, 230, 230);
colors[ImGuiCustomCol_ToolbarRed] = ImColor(231, 76, 60);
colors[ImGuiCustomCol_ToolbarYellow] = ImColor(241, 196, 15);
colors[ImGuiCustomCol_ToolbarGreen] = ImColor(56, 139, 66);
colors[ImGuiCustomCol_ToolbarBlue] = ImColor(6, 83, 155);
colors[ImGuiCustomCol_ToolbarPurple] = ImColor(103, 42, 120);
colors[ImGuiCustomCol_ToolbarBrown] = ImColor(219, 179, 119);
colors[ImGuiCustomCol_ToolbarGray] = ImColor(230, 230, 230);
colors[ImGuiCustomCol_ToolbarRed] = ImColor(231, 76, 60);
colors[ImGuiCustomCol_ToolbarYellow] = ImColor(241, 196, 15);
colors[ImGuiCustomCol_ToolbarGreen] = ImColor(56, 139, 66);
colors[ImGuiCustomCol_ToolbarBlue] = ImColor(6, 83, 155);
colors[ImGuiCustomCol_ToolbarPurple] = ImColor(103, 42, 120);
colors[ImGuiCustomCol_ToolbarBrown] = ImColor(219, 179, 119);
colors[ImGuiCustomCol_Highlight] = ImColor(77, 198, 155);
colors[ImGuiCustomCol_Highlight] = ImColor(77, 198, 155);
}
void StyleCustomColorsLight() {
auto &colors = static_cast<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);
colors[ImGuiCustomCol_DescButtonActive] = ImColor(190, 190, 190);
colors[ImGuiCustomCol_DescButton] = ImColor(230, 230, 230);
colors[ImGuiCustomCol_DescButtonHovered] = ImColor(210, 210, 210);
colors[ImGuiCustomCol_DescButtonActive] = ImColor(190, 190, 190);
colors[ImGuiCustomCol_ToolbarGray] = ImColor(25, 25, 25);
colors[ImGuiCustomCol_ToolbarRed] = ImColor(231, 76, 60);
colors[ImGuiCustomCol_ToolbarYellow] = ImColor(241, 196, 15);
colors[ImGuiCustomCol_ToolbarGreen] = ImColor(56, 139, 66);
colors[ImGuiCustomCol_ToolbarBlue] = ImColor(6, 83, 155);
colors[ImGuiCustomCol_ToolbarPurple] = ImColor(103, 42, 120);
colors[ImGuiCustomCol_ToolbarBrown] = ImColor(219, 179, 119);
colors[ImGuiCustomCol_ToolbarGray] = ImColor(25, 25, 25);
colors[ImGuiCustomCol_ToolbarRed] = ImColor(231, 76, 60);
colors[ImGuiCustomCol_ToolbarYellow] = ImColor(241, 196, 15);
colors[ImGuiCustomCol_ToolbarGreen] = ImColor(56, 139, 66);
colors[ImGuiCustomCol_ToolbarBlue] = ImColor(6, 83, 155);
colors[ImGuiCustomCol_ToolbarPurple] = ImColor(103, 42, 120);
colors[ImGuiCustomCol_ToolbarBrown] = ImColor(219, 179, 119);
colors[ImGuiCustomCol_Highlight] = ImColor(41, 151, 112);
colors[ImGuiCustomCol_Highlight] = ImColor(41, 151, 112);
}
void StyleCustomColorsClassic() {
auto &colors = static_cast<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);
colors[ImGuiCustomCol_DescButtonActive] = ImColor(80, 80, 120);
colors[ImGuiCustomCol_DescButton] = ImColor(40, 40, 80);
colors[ImGuiCustomCol_DescButtonHovered] = ImColor(60, 60, 100);
colors[ImGuiCustomCol_DescButtonActive] = ImColor(80, 80, 120);
colors[ImGuiCustomCol_ToolbarGray] = ImColor(230, 230, 230);
colors[ImGuiCustomCol_ToolbarRed] = ImColor(231, 76, 60);
colors[ImGuiCustomCol_ToolbarYellow] = ImColor(241, 196, 15);
colors[ImGuiCustomCol_ToolbarGreen] = ImColor(56, 139, 66);
colors[ImGuiCustomCol_ToolbarBlue] = ImColor(6, 83, 155);
colors[ImGuiCustomCol_ToolbarPurple] = ImColor(103, 42, 120);
colors[ImGuiCustomCol_ToolbarBrown] = ImColor(219, 179, 119);
colors[ImGuiCustomCol_ToolbarGray] = ImColor(230, 230, 230);
colors[ImGuiCustomCol_ToolbarRed] = ImColor(231, 76, 60);
colors[ImGuiCustomCol_ToolbarYellow] = ImColor(241, 196, 15);
colors[ImGuiCustomCol_ToolbarGreen] = ImColor(56, 139, 66);
colors[ImGuiCustomCol_ToolbarBlue] = ImColor(6, 83, 155);
colors[ImGuiCustomCol_ToolbarPurple] = ImColor(103, 42, 120);
colors[ImGuiCustomCol_ToolbarBrown] = ImColor(219, 179, 119);
colors[ImGuiCustomCol_Highlight] = ImColor(77, 198, 155);
colors[ImGuiCustomCol_Highlight] = ImColor(77, 198, 155);
}
Texture LoadImageFromPath(const char *path) {
int imageWidth = 0;
int imageHeight = 0;
unsigned char* imageData = stbi_load(path, &imageWidth, &imageHeight, nullptr, 4);
unsigned char *imageData = stbi_load(path, &imageWidth, &imageHeight, nullptr, 4);
if (imageData == nullptr)
return { nullptr, -1, -1 };
@ -320,9 +320,9 @@ namespace ImGui {
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
#if defined(GL_UNPACK_ROW_LENGTH)
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
#endif
#if defined(GL_UNPACK_ROW_LENGTH)
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
#endif
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, imageWidth, imageHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, imageData);
stbi_image_free(imageData);
@ -334,7 +334,7 @@ namespace ImGui {
int imageHeight = 0;
unsigned char* imageData = stbi_load_from_memory(buffer, size, &imageWidth, &imageHeight, nullptr, 4);
unsigned char *imageData = stbi_load_from_memory(buffer, size, &imageWidth, &imageHeight, nullptr, 4);
if (imageData == nullptr)
return { nullptr, -1, -1 };
@ -345,9 +345,9 @@ namespace ImGui {
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
#if defined(GL_UNPACK_ROW_LENGTH)
#if defined(GL_UNPACK_ROW_LENGTH)
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
#endif
#endif
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, imageWidth, imageHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, imageData);
stbi_image_free(imageData);
@ -372,13 +372,13 @@ namespace ImGui {
}
bool TitleBarButton(const char* label, ImVec2 size_arg) {
ImGuiWindow* window = GetCurrentWindow();
bool TitleBarButton(const char *label, ImVec2 size_arg) {
ImGuiWindow *window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
ImGuiContext &g = *GImGui;
const ImGuiStyle &style = g.Style;
const ImGuiID id = window->GetID(label);
const ImVec2 label_size = CalcTextSize(label, NULL, true);
@ -395,28 +395,29 @@ namespace ImGui {
bool pressed = ButtonBehavior(bb, id, &hovered, &held);
// Render
const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered
: ImGuiCol_Button);
RenderNavHighlight(bb, id);
RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding);
RenderTextClipped(bb.Min + style.FramePadding * ImVec2(1, 2), bb.Max - style.FramePadding, label, NULL, &label_size, style.ButtonTextAlign, &bb);
// Automatically close popups
//if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup))
// if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup))
// CloseCurrentPopup();
IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags);
return pressed;
}
bool ToolBarButton(const char* symbol, ImVec4 color) {
ImGuiWindow* window = GetCurrentWindow();
bool ToolBarButton(const char *symbol, ImVec4 color) {
ImGuiWindow *window = GetCurrentWindow();
if (window->SkipItems)
return false;
color.w = 1.0F;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
ImGuiContext &g = *GImGui;
const ImGuiStyle &style = g.Style;
const ImGuiID id = window->GetID(symbol);
const ImVec2 label_size = CalcTextSize(symbol, NULL, true);
@ -435,7 +436,8 @@ namespace ImGui {
PushStyleColor(ImGuiCol_Text, color);
// Render
const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ScrollbarGrabActive : hovered ? ImGuiCol_ScrollbarGrabHovered : ImGuiCol_MenuBarBg);
const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ScrollbarGrabActive : hovered ? ImGuiCol_ScrollbarGrabHovered
: ImGuiCol_MenuBarBg);
RenderNavHighlight(bb, id);
RenderFrame(bb.Min, bb.Max, col, false, style.FrameRounding);
RenderTextClipped(bb.Min + style.FramePadding * ImVec2(1, 2), bb.Max - style.FramePadding, symbol, NULL, &label_size, style.ButtonTextAlign, &bb);
@ -443,22 +445,22 @@ namespace ImGui {
PopStyleColor();
// Automatically close popups
//if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup))
// if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup))
// CloseCurrentPopup();
IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags);
return pressed;
}
bool IconButton(const char* symbol, ImVec4 color, ImVec2 size_arg) {
ImGuiWindow* window = GetCurrentWindow();
bool IconButton(const char *symbol, ImVec4 color, ImVec2 size_arg) {
ImGuiWindow *window = GetCurrentWindow();
if (window->SkipItems)
return false;
color.w = 1.0F;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
ImGuiContext &g = *GImGui;
const ImGuiStyle &style = g.Style;
const ImGuiID id = window->GetID(symbol);
const ImVec2 label_size = CalcTextSize(symbol, NULL, true);
@ -477,7 +479,8 @@ namespace ImGui {
PushStyleColor(ImGuiCol_Text, color);
// Render
const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered
: ImGuiCol_Button);
RenderNavHighlight(bb, id);
RenderFrame(bb.Min, bb.Max, col, false, style.FrameRounding);
RenderTextClipped(bb.Min + style.FramePadding * ImVec2(1, 2), bb.Max - style.FramePadding, symbol, NULL, &label_size, style.ButtonTextAlign, &bb);
@ -485,7 +488,7 @@ namespace ImGui {
PopStyleColor();
// Automatically close popups
//if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup))
// if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup))
// CloseCurrentPopup();
IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags);
@ -493,12 +496,12 @@ namespace ImGui {
}
void SmallProgressBar(float fraction, float yOffset) {
ImGuiWindow* window = GetCurrentWindow();
ImGuiWindow *window = GetCurrentWindow();
if (window->SkipItems)
return;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
ImGuiContext &g = *GImGui;
const ImGuiStyle &style = g.Style;
ImVec2 pos = window->DC.CursorPos + ImVec2(0, yOffset);
ImVec2 size = CalcItemSize(ImVec2(100, 5), 100, g.FontSize + style.FramePadding.y * 2.0f);

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,28 +25,29 @@ namespace hex {
[[nodiscard]] std::string getCompatibleVersion() const;
void setImGuiContext(ImGuiContext *ctx) const;
[[nodiscard]] const fs::path& getPath() const;
[[nodiscard]] const fs::path &getPath() const;
[[nodiscard]] bool isLoaded() const;
private:
using InitializePluginFunc = void(*)();
using GetPluginNameFunc = const char*(*)();
using GetPluginAuthorFunc = const char*(*)();
using GetPluginDescriptionFunc = const char*(*)();
using GetCompatibleVersionFunc = const char*(*)();
using SetImGuiContextFunc = void(*)(ImGuiContext*);
using InitializePluginFunc = void (*)();
using GetPluginNameFunc = const char *(*)();
using GetPluginAuthorFunc = const char *(*)();
using GetPluginDescriptionFunc = const char *(*)();
using GetCompatibleVersionFunc = const char *(*)();
using SetImGuiContextFunc = void (*)(ImGuiContext *);
void *m_handle = nullptr;
fs::path m_path;
mutable bool m_initialized = false;
InitializePluginFunc m_initializePluginFunction = nullptr;
GetPluginNameFunc m_getPluginNameFunction = nullptr;
GetPluginAuthorFunc m_getPluginAuthorFunction = nullptr;
GetPluginDescriptionFunc m_getPluginDescriptionFunction = nullptr;
GetCompatibleVersionFunc m_getCompatibleVersionFunction = nullptr;
SetImGuiContextFunc m_setImGuiContextFunction = nullptr;
InitializePluginFunc m_initializePluginFunction = nullptr;
GetPluginNameFunc m_getPluginNameFunction = nullptr;
GetPluginAuthorFunc m_getPluginAuthorFunction = nullptr;
GetPluginDescriptionFunc m_getPluginDescriptionFunction = nullptr;
GetCompatibleVersionFunc m_getCompatibleVersionFunction = nullptr;
SetImGuiContextFunc m_setImGuiContextFunction = nullptr;
template<typename T>
[[nodiscard]] auto getPluginFunction(const std::string &symbol) {
@ -54,7 +55,7 @@ namespace hex {
}
private:
[[nodiscard]] void* getPluginFunction(const std::string &symbol);
[[nodiscard]] void *getPluginFunction(const std::string &symbol);
};
class PluginManager {
@ -65,7 +66,7 @@ namespace hex {
static void unload();
static void reload();
static const auto& getPlugins() {
static const auto &getPlugins() {
return PluginManager::s_plugins;
}

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

@ -17,32 +17,32 @@ namespace hex {
auto pluginName = fs::path(path).stem().string();
this->m_initializePluginFunction = getPluginFunction<InitializePluginFunc>("initializePlugin");
this->m_getPluginNameFunction = getPluginFunction<GetPluginNameFunc>("getPluginName");
this->m_getPluginAuthorFunction = getPluginFunction<GetPluginAuthorFunc>("getPluginAuthor");
this->m_getPluginDescriptionFunction = getPluginFunction<GetPluginDescriptionFunc>("getPluginDescription");
this->m_getCompatibleVersionFunction = getPluginFunction<GetCompatibleVersionFunc>("getCompatibleVersion");
this->m_setImGuiContextFunction = getPluginFunction<SetImGuiContextFunc>("setImGuiContext");
this->m_initializePluginFunction = getPluginFunction<InitializePluginFunc>("initializePlugin");
this->m_getPluginNameFunction = getPluginFunction<GetPluginNameFunc>("getPluginName");
this->m_getPluginAuthorFunction = getPluginFunction<GetPluginAuthorFunc>("getPluginAuthor");
this->m_getPluginDescriptionFunction = getPluginFunction<GetPluginDescriptionFunc>("getPluginDescription");
this->m_getCompatibleVersionFunction = getPluginFunction<GetCompatibleVersionFunc>("getCompatibleVersion");
this->m_setImGuiContextFunction = getPluginFunction<SetImGuiContextFunc>("setImGuiContext");
}
Plugin::Plugin(Plugin &&other) noexcept {
this->m_handle = other.m_handle;
this->m_path = std::move(other.m_path);
this->m_initializePluginFunction = other.m_initializePluginFunction;
this->m_getPluginNameFunction = other.m_getPluginNameFunction;
this->m_getPluginAuthorFunction = other.m_getPluginAuthorFunction;
this->m_getPluginDescriptionFunction = other.m_getPluginDescriptionFunction;
this->m_getCompatibleVersionFunction = other.m_getCompatibleVersionFunction;
this->m_setImGuiContextFunction = other.m_setImGuiContextFunction;
this->m_initializePluginFunction = other.m_initializePluginFunction;
this->m_getPluginNameFunction = other.m_getPluginNameFunction;
this->m_getPluginAuthorFunction = other.m_getPluginAuthorFunction;
this->m_getPluginDescriptionFunction = other.m_getPluginDescriptionFunction;
this->m_getCompatibleVersionFunction = other.m_getCompatibleVersionFunction;
this->m_setImGuiContextFunction = other.m_setImGuiContextFunction;
other.m_handle = nullptr;
other.m_initializePluginFunction = nullptr;
other.m_getPluginNameFunction = nullptr;
other.m_getPluginAuthorFunction = nullptr;
other.m_getPluginDescriptionFunction = nullptr;
other.m_getCompatibleVersionFunction = nullptr;
other.m_setImGuiContextFunction = nullptr;
other.m_initializePluginFunction = nullptr;
other.m_getPluginNameFunction = nullptr;
other.m_getPluginAuthorFunction = nullptr;
other.m_getPluginDescriptionFunction = nullptr;
other.m_getCompatibleVersionFunction = nullptr;
other.m_setImGuiContextFunction = nullptr;
}
Plugin::~Plugin() {
@ -100,7 +100,7 @@ namespace hex {
this->m_setImGuiContextFunction(ctx);
}
const fs::path& Plugin::getPath() const {
const fs::path &Plugin::getPath() const {
return this->m_path;
}
@ -109,7 +109,7 @@ namespace hex {
}
void* Plugin::getPluginFunction(const std::string &symbol) {
void *Plugin::getPluginFunction(const std::string &symbol) {
return dlsym(this->m_handle, symbol.c_str());
}
@ -120,7 +120,7 @@ namespace hex {
PluginManager::s_pluginFolder = pluginFolder;
for (auto& pluginPath : fs::directory_iterator(pluginFolder)) {
for (auto &pluginPath : fs::directory_iterator(pluginFolder)) {
if (pluginPath.is_regular_file() && pluginPath.path().extension() == ".hexplug")
PluginManager::s_plugins.emplace_back(pluginPath.path().string());
}

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)
drawList->AddText(ImVec2(15, 140) * scale, ImColor(0xFF, 0xFF, 0xFF, 0xFF), hex::format("{0} : {1} {2}@{3}", IMHEX_VERSION, ICON_FA_CODE_BRANCH, GIT_BRANCH, GIT_COMMIT_HASH).c_str());
#else
drawList->AddText(ImVec2(15, 140) * scale, ImColor(0xFF, 0xFF, 0xFF, 0xFF), hex::format("{0}", IMHEX_VERSION).c_str());
#endif
#if defined(DEBUG)
drawList->AddText(ImVec2(15, 140) * scale, ImColor(0xFF, 0xFF, 0xFF, 0xFF), hex::format("{0} : {1} {2}@{3}", IMHEX_VERSION, ICON_FA_CODE_BRANCH, GIT_BRANCH, GIT_COMMIT_HASH).c_str());
#else
drawList->AddText(ImVec2(15, 140) * scale, ImColor(0xFF, 0xFF, 0xFF, 0xFF), hex::format("{0}", IMHEX_VERSION).c_str());
#endif
drawList->AddRectFilled(ImVec2(0, splashTexture.size().y - 5) * scale, ImVec2(splashTexture.size().x * this->m_progress, splashTexture.size().y) * scale, 0xFFFFFFFF);
drawList->AddText(ImVec2(15, splashTexture.size().y - 25) * scale, ImColor(0xFF, 0xFF, 0xFF, 0xFF),
hex::format("[{}] {}", "|/-\\"[ImU32(ImGui::GetTime() * 15) % 4], this->m_currTaskName).c_str());
drawList->AddText(ImVec2(15, splashTexture.size().y - 25) * scale, ImColor(0xFF, 0xFF, 0xFF, 0xFF), hex::format("[{}] {}", "|/-\\"[ImU32(ImGui::GetTime() * 15) % 4], this->m_currTaskName).c_str());
}
ImGui::Render();
@ -171,12 +170,12 @@ namespace hex::init {
SharedData::globalScale = SharedData::fontScale = std::midpoint(xScale, yScale);
// On Macs with a retina display (basically all modern ones we care about), the OS reports twice
// the actual monitor scale for some obscure reason. Get rid of this here so ImHex doesn't look
// extremely huge with native scaling on MacOS.
#if defined(OS_MACOS)
SharedData::globalScale /= 2;
#endif
// On Macs with a retina display (basically all modern ones we care about), the OS reports twice
// the actual monitor scale for some obscure reason. Get rid of this here so ImHex doesn't look
// extremely huge with native scaling on MacOS.
#if defined(OS_MACOS)
SharedData::globalScale /= 2;
#endif
if (SharedData::globalScale <= 0) {
SharedData::globalScale = 1.0;
@ -217,8 +216,7 @@ namespace hex::init {
cfg.MergeMode = true;
ImWchar fontAwesomeRange[] = {
ICON_MIN_FA, ICON_MAX_FA,
0
ICON_MIN_FA, ICON_MAX_FA, 0
};
std::uint8_t *px;
int w, h;

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
};
@ -151,7 +148,7 @@ namespace hex::init {
cfg.OversampleH = cfg.OversampleV = 1, cfg.PixelSnapH = true;
cfg.SizePixels = fontSize * SharedData::fontScale;
fonts->AddFontFromFileTTF(fontFile.string().c_str(), std::floor(fontSize * SharedData::fontScale), &cfg, ranges.Data); // Needs conversion to char for Windows
fonts->AddFontFromFileTTF(fontFile.string().c_str(), std::floor(fontSize * SharedData::fontScale), &cfg, ranges.Data); // Needs conversion to char for Windows
}
cfg.MergeMode = true;
@ -224,7 +221,7 @@ namespace hex::init {
if (PluginManager::getPlugins().empty()) {
log::error("No plugins found!");
getInitArguments().push_back({ "no-plugins", { } });
getInitArguments().push_back({ "no-plugins", {} });
return false;
}
@ -251,22 +248,22 @@ namespace hex::init {
}
switch (ContentRegistry::Settings::read("hex.builtin.setting.interface", "hex.builtin.setting.interface.scaling", 0)) {
default:
case 0:
// Native scaling
break;
case 1:
SharedData::globalScale = SharedData::fontScale = 0.5F;
break;
case 2:
SharedData::globalScale = SharedData::fontScale = 1.0F;
break;
case 3:
SharedData::globalScale = SharedData::fontScale = 1.5F;
break;
case 4:
SharedData::globalScale = SharedData::fontScale = 2.0F;
break;
default:
case 0:
// Native scaling
break;
case 1:
SharedData::globalScale = SharedData::fontScale = 0.5F;
break;
case 2:
SharedData::globalScale = SharedData::fontScale = 1.0F;
break;
case 3:
SharedData::globalScale = SharedData::fontScale = 1.5F;
break;
case 4:
SharedData::globalScale = SharedData::fontScale = 2.0F;
break;
}
return true;
@ -284,24 +281,24 @@ namespace hex::init {
std::vector<Task> getInitTasks() {
return {
{ "Checking for updates...", checkForUpdates },
{ "Downloading information...", downloadInformation },
{ "Creating directories...", createDirectories },
{ "Loading settings...", loadSettings },
{ "Loading plugins...", loadPlugins },
{ "Loading fonts...", loadFonts },
{"Checking for updates...", checkForUpdates },
{ "Downloading information...", downloadInformation},
{ "Creating directories...", createDirectories },
{ "Loading settings...", loadSettings },
{ "Loading plugins...", loadPlugins },
{ "Loading fonts...", loadFonts },
};
}
std::vector<Task> getExitTasks() {
return {
{ "Saving settings...", storeSettings },
{ "Cleaning up shared data...", deleteSharedData },
{ "Unloading plugins...", unloadPlugins },
{"Saving settings...", storeSettings },
{ "Cleaning up shared data...", deleteSharedData},
{ "Unloading plugins...", unloadPlugins },
};
}
std::vector<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
@ -44,7 +44,7 @@ int main(int argc, char **argv, char **envp) {
Window window;
if (argc == 1)
; // No arguments provided
; // No arguments provided
else if (argc == 2)
EventManager::post<RequestOpenFile>(argv[1]);
else {

View File

@ -9,51 +9,48 @@
#include <sys/wait.h>
#include <unistd.h>
namespace hex {
namespace hex {
void Window::initNative() {
if (!isatty(STDOUT_FILENO)) {
log::redirectToFile();
}
void Window::initNative() {
if (!isatty(STDOUT_FILENO)) {
log::redirectToFile();
}
void Window::setupNativeWindow() {
bool themeFollowSystem = ContentRegistry::Settings::getSetting("hex.builtin.setting.interface", "hex.builtin.setting.interface.color") == 0;
EventManager::subscribe<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");
if (pipe == nullptr) return;
while (fgets(buffer.data(), buffer.size(), pipe) != nullptr)
result += buffer.data();
auto exitCode = WEXITSTATUS(pclose(pipe));
if (exitCode != 0) return;
EventManager::post<RequestChangeTheme>(hex::containsIgnoreCase(result, "dark") ? 1 : 2);
});
if (themeFollowSystem)
EventManager::post<EventOSThemeChanged>();
}
void Window::beginNativeWindowFrame() {
}
void Window::endNativeWindowFrame() {
}
void Window::drawTitleBar() {
}
}
void Window::setupNativeWindow() {
bool themeFollowSystem = ContentRegistry::Settings::getSetting("hex.builtin.setting.interface", "hex.builtin.setting.interface.color") == 0;
EventManager::subscribe<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");
if (pipe == nullptr) return;
while (fgets(buffer.data(), buffer.size(), pipe) != nullptr)
result += buffer.data();
auto exitCode = WEXITSTATUS(pclose(pipe));
if (exitCode != 0) return;
EventManager::post<RequestChangeTheme>(hex::containsIgnoreCase(result, "dark") ? 1 : 2);
});
if (themeFollowSystem)
EventManager::post<EventOSThemeChanged>();
}
void Window::beginNativeWindowFrame() {
}
void Window::endNativeWindowFrame() {
}
void Window::drawTitleBar() {
}
}
#endif

View File

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

View File

@ -21,349 +21,354 @@
#include <dwmapi.h>
#include <windowsx.h>
namespace hex {
namespace hex {
static LONG_PTR g_oldWndProc;
static float g_titleBarHeight;
static ImGuiMouseCursor g_mouseCursorIcon;
static BOOL g_compositionEnabled = false;
static LONG_PTR g_oldWndProc;
static float g_titleBarHeight;
static ImGuiMouseCursor g_mouseCursorIcon;
static BOOL g_compositionEnabled = false;
static LRESULT windowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
switch (uMsg) {
case WM_NCACTIVATE:
case WM_NCPAINT:
return DefWindowProcW(hwnd, uMsg, wParam, lParam);
case WM_NCCALCSIZE: {
RECT &rect = *reinterpret_cast<RECT*>(lParam);
RECT client = rect;
static LRESULT windowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
switch (uMsg) {
case WM_NCACTIVATE:
case WM_NCPAINT:
return DefWindowProcW(hwnd, uMsg, wParam, lParam);
case WM_NCCALCSIZE:
{
RECT &rect = *reinterpret_cast<RECT *>(lParam);
RECT client = rect;
CallWindowProc((WNDPROC)g_oldWndProc, hwnd, uMsg, wParam, lParam);
CallWindowProc((WNDPROC)g_oldWndProc, hwnd, uMsg, wParam, lParam);
if (IsMaximized(hwnd)) {
WINDOWINFO windowInfo = { .cbSize = sizeof(WINDOWINFO) };
GetWindowInfo(hwnd, &windowInfo);
rect = RECT {
.left = static_cast<LONG>(client.left + windowInfo.cyWindowBorders),
.top = static_cast<LONG>(client.top + windowInfo.cyWindowBorders),
.right = static_cast<LONG>(client.right - windowInfo.cyWindowBorders),
.bottom = static_cast<LONG>(client.bottom - windowInfo.cyWindowBorders) + 1
};
} else {
rect = client;
}
return 0;
if (IsMaximized(hwnd)) {
WINDOWINFO windowInfo = { .cbSize = sizeof(WINDOWINFO) };
GetWindowInfo(hwnd, &windowInfo);
rect = RECT {
.left = static_cast<LONG>(client.left + windowInfo.cyWindowBorders),
.top = static_cast<LONG>(client.top + windowInfo.cyWindowBorders),
.right = static_cast<LONG>(client.right - windowInfo.cyWindowBorders),
.bottom = static_cast<LONG>(client.bottom - windowInfo.cyWindowBorders) + 1
};
} else {
rect = client;
}
case WM_SETCURSOR: {
auto cursorPos = LOWORD(lParam);
switch (cursorPos) {
case HTRIGHT:
case HTLEFT:
g_mouseCursorIcon = ImGuiMouseCursor_ResizeEW;
break;
case HTTOP:
case HTBOTTOM:
g_mouseCursorIcon = ImGuiMouseCursor_ResizeNS;
break;
case HTTOPLEFT:
case HTBOTTOMRIGHT:
g_mouseCursorIcon = ImGuiMouseCursor_ResizeNWSE;
break;
case HTTOPRIGHT:
case HTBOTTOMLEFT:
g_mouseCursorIcon = ImGuiMouseCursor_ResizeNESW;
break;
case HTCAPTION:
case HTCLIENT:
g_mouseCursorIcon = ImGuiMouseCursor_None;
break;
return 0;
}
case WM_SETCURSOR:
{
auto cursorPos = LOWORD(lParam);
switch (cursorPos) {
case HTRIGHT:
case HTLEFT:
g_mouseCursorIcon = ImGuiMouseCursor_ResizeEW;
break;
case HTTOP:
case HTBOTTOM:
g_mouseCursorIcon = ImGuiMouseCursor_ResizeNS;
break;
case HTTOPLEFT:
case HTBOTTOMRIGHT:
g_mouseCursorIcon = ImGuiMouseCursor_ResizeNWSE;
break;
case HTTOPRIGHT:
case HTBOTTOMLEFT:
g_mouseCursorIcon = ImGuiMouseCursor_ResizeNESW;
break;
case HTCAPTION:
case HTCLIENT:
g_mouseCursorIcon = ImGuiMouseCursor_None;
break;
}
return TRUE;
}
case WM_NCHITTEST:
{
POINT cursor = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };
const POINT border {
static_cast<LONG>((::GetSystemMetrics(SM_CXFRAME) + ::GetSystemMetrics(SM_CXPADDEDBORDER)) * SharedData::globalScale / 1.5F),
static_cast<LONG>((::GetSystemMetrics(SM_CYFRAME) + ::GetSystemMetrics(SM_CXPADDEDBORDER)) * SharedData::globalScale / 1.5F)
};
RECT window;
if (!::GetWindowRect(hwnd, &window)) {
return HTNOWHERE;
}
constexpr auto RegionClient = 0b0000;
constexpr auto RegionLeft = 0b0001;
constexpr auto RegionRight = 0b0010;
constexpr auto RegionTop = 0b0100;
constexpr auto RegionBottom = 0b1000;
const auto result =
RegionLeft * (cursor.x < (window.left + border.x)) |
RegionRight * (cursor.x >= (window.right - border.x)) |
RegionTop * (cursor.y < (window.top + border.y)) |
RegionBottom * (cursor.y >= (window.bottom - border.y));
if (result != 0 && (ImGui::IsItemHovered() || ImGui::IsPopupOpen(nullptr, ImGuiPopupFlags_AnyPopupId)))
break;
switch (result) {
case RegionLeft:
return HTLEFT;
case RegionRight:
return HTRIGHT;
case RegionTop:
return HTTOP;
case RegionBottom:
return HTBOTTOM;
case RegionTop | RegionLeft:
return HTTOPLEFT;
case RegionTop | RegionRight:
return HTTOPRIGHT;
case RegionBottom | RegionLeft:
return HTBOTTOMLEFT;
case RegionBottom | RegionRight:
return HTBOTTOMRIGHT;
case RegionClient:
default:
if ((cursor.y < (window.top + g_titleBarHeight * 2)) && !(ImGui::IsAnyItemHovered() || ImGui::IsPopupOpen(nullptr, ImGuiPopupFlags_AnyPopupId)))
return HTCAPTION;
else break;
}
break;
}
case WM_SETTINGCHANGE:
{
if (lParam == 0) break;
if (LPCTSTR(lParam) == std::string_view("ImmersiveColorSet")) {
EventManager::post<EventOSThemeChanged>();
}
break;
}
case WM_COPYDATA:
{
auto message = reinterpret_cast<COPYDATASTRUCT *>(lParam);
if (message == nullptr) break;
auto path = reinterpret_cast<const char *>(message->lpData);
if (path == nullptr) break;
log::info("Opening file in existing instance: {}", path);
EventManager::post<RequestOpenFile>(path);
break;
}
default:
break;
}
return CallWindowProc((WNDPROC)g_oldWndProc, hwnd, uMsg, wParam, lParam);
}
void Window::initNative() {
// Attach to parent console if one exists
if (AttachConsole(ATTACH_PARENT_PROCESS)) {
// Redirect cin, cout and cerr to that console
freopen("CONIN$", "r", stdin);
freopen("CONOUT$", "w", stdout);
freopen("CONOUT$", "w", stderr);
setvbuf(stdin, nullptr, _IONBF, 0);
setvbuf(stdout, nullptr, _IONBF, 0);
setvbuf(stderr, nullptr, _IONBF, 0);
fmt::print("\n");
// Enable color format specifiers in console
{
auto hConsole = ::GetStdHandle(STD_OUTPUT_HANDLE);
if (hConsole != INVALID_HANDLE_VALUE) {
DWORD mode = 0;
if (::GetConsoleMode(hConsole, &mode)) {
mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING | ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT;
::SetConsoleMode(hConsole, mode);
}
}
}
} else {
log::redirectToFile();
}
// Open new files in already existing ImHex instance
constexpr static auto UniqueMutexId = "ImHex/a477ea68-e334-4d07-a439-4f159c683763";
HANDLE globalMutex = OpenMutex(MUTEX_ALL_ACCESS, FALSE, UniqueMutexId);
if (!globalMutex) {
globalMutex = CreateMutex(nullptr, FALSE, UniqueMutexId);
} else {
if (SharedData::mainArgc > 1) {
::EnumWindows([](HWND hWnd, LPARAM lparam) -> BOOL {
auto length = ::GetWindowTextLength(hWnd);
std::string windowName(length + 1, '\x00');
::GetWindowText(hWnd, windowName.data(), windowName.size());
if (::IsWindowVisible(hWnd) && length != 0) {
if (windowName.starts_with("ImHex")) {
COPYDATASTRUCT message = {
.dwData = 0,
.cbData = static_cast<DWORD>(std::strlen(SharedData::mainArgv[1])) + 1,
.lpData = SharedData::mainArgv[1]
};
SendMessage(hWnd, WM_COPYDATA, reinterpret_cast<WPARAM>(hWnd), reinterpret_cast<LPARAM>(&message));
return FALSE;
}
}
return TRUE;
}
case WM_NCHITTEST: {
POINT cursor = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };
},
0);
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)
};
RECT window;
if (!::GetWindowRect(hwnd, &window)) {
return HTNOWHERE;
}
constexpr auto RegionClient = 0b0000;
constexpr auto RegionLeft = 0b0001;
constexpr auto RegionRight = 0b0010;
constexpr auto RegionTop = 0b0100;
constexpr auto RegionBottom = 0b1000;
const auto result =
RegionLeft * (cursor.x < (window.left + border.x)) |
RegionRight * (cursor.x >= (window.right - border.x)) |
RegionTop * (cursor.y < (window.top + border.y)) |
RegionBottom * (cursor.y >= (window.bottom - border.y));
if (result != 0 && (ImGui::IsItemHovered() || ImGui::IsPopupOpen(nullptr, ImGuiPopupFlags_AnyPopupId)))
break;
switch (result) {
case RegionLeft:
return HTLEFT;
case RegionRight:
return HTRIGHT;
case RegionTop:
return HTTOP;
case RegionBottom:
return HTBOTTOM;
case RegionTop | RegionLeft:
return HTTOPLEFT;
case RegionTop | RegionRight:
return HTTOPRIGHT;
case RegionBottom | RegionLeft:
return HTBOTTOMLEFT;
case RegionBottom | RegionRight:
return HTBOTTOMRIGHT;
case RegionClient:
default:
if ((cursor.y < (window.top + g_titleBarHeight * 2)) && !(ImGui::IsAnyItemHovered() || ImGui::IsPopupOpen(nullptr, ImGuiPopupFlags_AnyPopupId)))
return HTCAPTION;
else break;
}
break;
}
case WM_SETTINGCHANGE:
{
if (lParam == 0) break;
if (LPCTSTR(lParam) == std::string_view("ImmersiveColorSet")) {
EventManager::post<EventOSThemeChanged>();
}
break;
}
case WM_COPYDATA:
{
auto message = reinterpret_cast<COPYDATASTRUCT*>(lParam);
if (message == nullptr) break;
auto path = reinterpret_cast<const char*>(message->lpData);
if (path == nullptr) break;
log::info("Opening file in existing instance: {}", path);
EventManager::post<RequestOpenFile>(path);
break;
}
default: break;
}
return CallWindowProc((WNDPROC)g_oldWndProc, hwnd, uMsg, wParam, lParam);
}
void Window::initNative() {
// Attach to parent console if one exists
if (AttachConsole(ATTACH_PARENT_PROCESS)) {
// Redirect cin, cout and cerr to that console
freopen("CONIN$", "r", stdin);
freopen("CONOUT$", "w", stdout);
freopen("CONOUT$", "w", stderr);
setvbuf(stdin, nullptr, _IONBF, 0);
setvbuf(stdout, nullptr, _IONBF, 0);
setvbuf(stderr, nullptr, _IONBF, 0);
fmt::print("\n");
// Enable color format specifiers in console
{
auto hConsole = ::GetStdHandle(STD_OUTPUT_HANDLE);
if (hConsole != INVALID_HANDLE_VALUE) {
DWORD mode = 0;
if (::GetConsoleMode(hConsole, &mode)) {
mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING | ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT;
::SetConsoleMode(hConsole, mode);
}
}
}
} else {
log::redirectToFile();
}
// Open new files in already existing ImHex instance
constexpr static auto UniqueMutexId = "ImHex/a477ea68-e334-4d07-a439-4f159c683763";
HANDLE globalMutex = OpenMutex(MUTEX_ALL_ACCESS, FALSE, UniqueMutexId);
if (!globalMutex) {
globalMutex = CreateMutex(nullptr, FALSE, UniqueMutexId);
} else {
if (SharedData::mainArgc > 1) {
::EnumWindows([](HWND hWnd, LPARAM lparam) -> BOOL {
auto length = ::GetWindowTextLength(hWnd);
std::string windowName(length + 1, '\x00');
::GetWindowText(hWnd, windowName.data(), windowName.size());
if (::IsWindowVisible(hWnd) && length != 0) {
if (windowName.starts_with("ImHex")) {
COPYDATASTRUCT message = {
.dwData = 0,
.cbData = static_cast<DWORD>(std::strlen(SharedData::mainArgv[1])) + 1,
.lpData = SharedData::mainArgv[1]
};
SendMessage(hWnd, WM_COPYDATA, reinterpret_cast<WPARAM>(hWnd), reinterpret_cast<LPARAM>(&message));
return FALSE;
}
}
return TRUE;
}, 0);
std::exit(0);
}
std::exit(0);
}
}
void Window::setupNativeWindow() {
// Setup borderless window
auto hwnd = glfwGetWin32Window(this->m_window);
g_oldWndProc = ::SetWindowLongPtr(hwnd, GWLP_WNDPROC, (LONG_PTR)windowProc);
MARGINS borderless = { 1, 1, 1, 1 };
::DwmExtendFrameIntoClientArea(hwnd, &borderless);
DWORD attribute = DWMNCRP_ENABLED;
::DwmSetWindowAttribute(hwnd, DWMWA_NCRENDERING_POLICY, &attribute, sizeof(attribute));
::SetWindowPos(hwnd, nullptr, 0, 0, 0, 0, SWP_NOZORDER | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSIZE | SWP_NOMOVE);
::SetWindowLong(hwnd, GWL_STYLE, GetWindowLong(hwnd, GWL_STYLE) | WS_OVERLAPPEDWINDOW);
// Setup system theme change detector
bool themeFollowSystem = ContentRegistry::Settings::getSetting("hex.builtin.setting.interface", "hex.builtin.setting.interface.color") == 0;
EventManager::subscribe<EventOSThemeChanged>(this, [themeFollowSystem]{
if (!themeFollowSystem) return;
HKEY hkey;
if (RegOpenKey(HKEY_CURRENT_USER, R"(Software\Microsoft\Windows\CurrentVersion\Themes\Personalize)", &hkey) == ERROR_SUCCESS) {
DWORD value = 0;
DWORD size = sizeof(DWORD);
auto error = RegQueryValueEx(hkey, "AppsUseLightTheme", nullptr, nullptr, reinterpret_cast<LPBYTE>(&value), &size);
if (error == ERROR_SUCCESS) {
EventManager::post<RequestChangeTheme>(value == 0 ? 1 : 2);
}
}
});
if (themeFollowSystem)
EventManager::post<EventOSThemeChanged>();
}
void Window::beginNativeWindowFrame() {
g_titleBarHeight = ImGui::GetCurrentWindow()->MenuBarHeight();
}
void Window::endNativeWindowFrame() {
if (g_mouseCursorIcon != ImGuiMouseCursor_None) {
ImGui::SetMouseCursor(g_mouseCursorIcon);
}
switch (ImGui::GetMouseCursor()) {
case ImGuiMouseCursor_Arrow:
SetCursor(LoadCursor(nullptr, IDC_ARROW));
break;
case ImGuiMouseCursor_Hand:
SetCursor(LoadCursor(nullptr, IDC_HAND));
break;
case ImGuiMouseCursor_ResizeEW:
SetCursor(LoadCursor(nullptr, IDC_SIZEWE));
break;
case ImGuiMouseCursor_ResizeNS:
SetCursor(LoadCursor(nullptr, IDC_SIZENS));
break;
case ImGuiMouseCursor_ResizeNWSE:
SetCursor(LoadCursor(nullptr, IDC_SIZENWSE));
break;
case ImGuiMouseCursor_ResizeNESW:
SetCursor(LoadCursor(nullptr, IDC_SIZENESW));
break;
case ImGuiMouseCursor_ResizeAll:
SetCursor(LoadCursor(nullptr, IDC_SIZEALL));
break;
case ImGuiMouseCursor_NotAllowed:
SetCursor(LoadCursor(nullptr, IDC_NO));
break;
case ImGuiMouseCursor_TextInput:
SetCursor(LoadCursor(nullptr, IDC_IBEAM));
break;
default:
case ImGuiMouseCursor_None:
SetCursor(LoadCursor(nullptr, IDC_ARROW));
break;
}
}
void Window::drawTitleBar() {
auto buttonSize = ImVec2(g_titleBarHeight * 1.5F, g_titleBarHeight - 1);
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0));
ImGui::PushStyleColor(ImGuiCol_Button, ImGui::GetColorU32(ImGuiCol_MenuBarBg));
ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImGui::GetColorU32(ImGuiCol_ScrollbarGrabActive));
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImGui::GetColorU32(ImGuiCol_ScrollbarGrabHovered));
ImGui::SetCursorPosX(ImGui::GetWindowWidth() - buttonSize.x * 6);
#if defined(DEBUG)
if (ImGui::TitleBarButton(ICON_VS_DEBUG, buttonSize)) {
if (ImGui::GetIO().KeyCtrl) {
// Explicitly trigger a segfault by writing to an invalid memory location
// Used for debugging crashes
*reinterpret_cast<u8*>(0x10) = 0x10;
} else if (ImGui::GetIO().KeyShift) {
// Explicitly trigger an abort by throwing an uncaught exception
// Used for debugging exception errors
throw std::runtime_error("Debug Error");
} else {
hex::openWebpage("https://imhex.werwolv.net/debug");
}
}
ImGui::InfoTooltip("hex.menu.debug_build"_lang);
#endif
if (ImGui::TitleBarButton(ICON_VS_SMILEY, buttonSize))
hex::openWebpage("mailto://hey@werwolv.net");
ImGui::InfoTooltip("hex.menu.feedback"_lang);
ImGui::SetCursorPosX(ImGui::GetWindowWidth() - buttonSize.x * 3);
if (ImGui::TitleBarButton(ICON_VS_CHROME_MINIMIZE, buttonSize))
glfwIconifyWindow(this->m_window);
if (glfwGetWindowAttrib(this->m_window, GLFW_MAXIMIZED)) {
if (ImGui::TitleBarButton(ICON_VS_CHROME_RESTORE, buttonSize))
glfwRestoreWindow(this->m_window);
} else {
if (ImGui::TitleBarButton(ICON_VS_CHROME_MAXIMIZE, buttonSize))
glfwMaximizeWindow(this->m_window);
}
ImGui::PushStyleColor(ImGuiCol_ButtonActive, 0xFF7A70F1);
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, 0xFF2311E8);
if (ImGui::TitleBarButton(ICON_VS_CHROME_CLOSE, buttonSize)) {
ImHexApi::Common::closeImHex();
}
ImGui::PopStyleColor(5);
ImGui::PopStyleVar();
ImGui::SetCursorPosX((ImGui::GetWindowWidth() - ImGui::CalcTextSize(this->m_windowTitle.c_str()).x) / 2);
ImGui::TextUnformatted(this->m_windowTitle.c_str());
}
}
void Window::setupNativeWindow() {
// Setup borderless window
auto hwnd = glfwGetWin32Window(this->m_window);
g_oldWndProc = ::SetWindowLongPtr(hwnd, GWLP_WNDPROC, (LONG_PTR)windowProc);
MARGINS borderless = { 1, 1, 1, 1 };
::DwmExtendFrameIntoClientArea(hwnd, &borderless);
DWORD attribute = DWMNCRP_ENABLED;
::DwmSetWindowAttribute(hwnd, DWMWA_NCRENDERING_POLICY, &attribute, sizeof(attribute));
::SetWindowPos(hwnd, nullptr, 0, 0, 0, 0, SWP_NOZORDER | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSIZE | SWP_NOMOVE);
::SetWindowLong(hwnd, GWL_STYLE, GetWindowLong(hwnd, GWL_STYLE) | WS_OVERLAPPEDWINDOW);
// Setup system theme change detector
bool themeFollowSystem = ContentRegistry::Settings::getSetting("hex.builtin.setting.interface", "hex.builtin.setting.interface.color") == 0;
EventManager::subscribe<EventOSThemeChanged>(this, [themeFollowSystem] {
if (!themeFollowSystem) return;
HKEY hkey;
if (RegOpenKey(HKEY_CURRENT_USER, R"(Software\Microsoft\Windows\CurrentVersion\Themes\Personalize)", &hkey) == ERROR_SUCCESS) {
DWORD value = 0;
DWORD size = sizeof(DWORD);
auto error = RegQueryValueEx(hkey, "AppsUseLightTheme", nullptr, nullptr, reinterpret_cast<LPBYTE>(&value), &size);
if (error == ERROR_SUCCESS) {
EventManager::post<RequestChangeTheme>(value == 0 ? 1 : 2);
}
}
});
if (themeFollowSystem)
EventManager::post<EventOSThemeChanged>();
}
void Window::beginNativeWindowFrame() {
g_titleBarHeight = ImGui::GetCurrentWindow()->MenuBarHeight();
}
void Window::endNativeWindowFrame() {
if (g_mouseCursorIcon != ImGuiMouseCursor_None) {
ImGui::SetMouseCursor(g_mouseCursorIcon);
}
switch (ImGui::GetMouseCursor()) {
case ImGuiMouseCursor_Arrow:
SetCursor(LoadCursor(nullptr, IDC_ARROW));
break;
case ImGuiMouseCursor_Hand:
SetCursor(LoadCursor(nullptr, IDC_HAND));
break;
case ImGuiMouseCursor_ResizeEW:
SetCursor(LoadCursor(nullptr, IDC_SIZEWE));
break;
case ImGuiMouseCursor_ResizeNS:
SetCursor(LoadCursor(nullptr, IDC_SIZENS));
break;
case ImGuiMouseCursor_ResizeNWSE:
SetCursor(LoadCursor(nullptr, IDC_SIZENWSE));
break;
case ImGuiMouseCursor_ResizeNESW:
SetCursor(LoadCursor(nullptr, IDC_SIZENESW));
break;
case ImGuiMouseCursor_ResizeAll:
SetCursor(LoadCursor(nullptr, IDC_SIZEALL));
break;
case ImGuiMouseCursor_NotAllowed:
SetCursor(LoadCursor(nullptr, IDC_NO));
break;
case ImGuiMouseCursor_TextInput:
SetCursor(LoadCursor(nullptr, IDC_IBEAM));
break;
default:
case ImGuiMouseCursor_None:
SetCursor(LoadCursor(nullptr, IDC_ARROW));
break;
}
}
void Window::drawTitleBar() {
auto buttonSize = ImVec2(g_titleBarHeight * 1.5F, g_titleBarHeight - 1);
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0));
ImGui::PushStyleColor(ImGuiCol_Button, ImGui::GetColorU32(ImGuiCol_MenuBarBg));
ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImGui::GetColorU32(ImGuiCol_ScrollbarGrabActive));
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImGui::GetColorU32(ImGuiCol_ScrollbarGrabHovered));
ImGui::SetCursorPosX(ImGui::GetWindowWidth() - buttonSize.x * 6);
#if defined(DEBUG)
if (ImGui::TitleBarButton(ICON_VS_DEBUG, buttonSize)) {
if (ImGui::GetIO().KeyCtrl) {
// Explicitly trigger a segfault by writing to an invalid memory location
// Used for debugging crashes
*reinterpret_cast<u8 *>(0x10) = 0x10;
} else if (ImGui::GetIO().KeyShift) {
// Explicitly trigger an abort by throwing an uncaught exception
// Used for debugging exception errors
throw std::runtime_error("Debug Error");
} else {
hex::openWebpage("https://imhex.werwolv.net/debug");
}
}
ImGui::InfoTooltip("hex.menu.debug_build"_lang);
#endif
if (ImGui::TitleBarButton(ICON_VS_SMILEY, buttonSize))
hex::openWebpage("mailto://hey@werwolv.net");
ImGui::InfoTooltip("hex.menu.feedback"_lang);
ImGui::SetCursorPosX(ImGui::GetWindowWidth() - buttonSize.x * 3);
if (ImGui::TitleBarButton(ICON_VS_CHROME_MINIMIZE, buttonSize))
glfwIconifyWindow(this->m_window);
if (glfwGetWindowAttrib(this->m_window, GLFW_MAXIMIZED)) {
if (ImGui::TitleBarButton(ICON_VS_CHROME_RESTORE, buttonSize))
glfwRestoreWindow(this->m_window);
} else {
if (ImGui::TitleBarButton(ICON_VS_CHROME_MAXIMIZE, buttonSize))
glfwMaximizeWindow(this->m_window);
}
ImGui::PushStyleColor(ImGuiCol_ButtonActive, 0xFF7A70F1);
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, 0xFF2311E8);
if (ImGui::TitleBarButton(ICON_VS_CHROME_CLOSE, buttonSize)) {
ImHexApi::Common::closeImHex();
}
ImGui::PopStyleColor(5);
ImGui::PopStyleVar();
ImGui::SetCursorPosX((ImGui::GetWindowWidth() - ImGui::CalcTextSize(this->m_windowTitle.c_str()).x) / 2);
ImGui::TextUnformatted(this->m_windowTitle.c_str());
}
}
#endif

View File

@ -46,18 +46,18 @@ namespace hex {
using namespace std::literals::chrono_literals;
void *ImHexSettingsHandler_ReadOpenFn(ImGuiContext *ctx, ImGuiSettingsHandler *, const char *) {
return ctx; // Unused, but the return value has to be non-null
return ctx; // Unused, but the return value has to be non-null
}
void ImHexSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler *handler, void *, const char* line) {
void ImHexSettingsHandler_ReadLine(ImGuiContext *, ImGuiSettingsHandler *handler, void *, const char *line) {
for (auto &[name, view] : ContentRegistry::Views::getEntries()) {
std::string format = std::string(view->getUnlocalizedName()) + "=%d";
sscanf(line, format.c_str(), &view->getWindowOpenState());
}
}
void ImHexSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler *handler, ImGuiTextBuffer *buf) {
buf->reserve(buf->size() + 0x20); // Ballpark reserve
void ImHexSettingsHandler_WriteAll(ImGuiContext *ctx, ImGuiSettingsHandler *handler, ImGuiTextBuffer *buf) {
buf->reserve(buf->size() + 0x20); // Ballpark reserve
buf->appendf("[%s][General]\n", handler->TypeName);
@ -74,13 +74,13 @@ namespace hex {
if (argument == "update-available") {
this->m_availableUpdate = value;
} else if (argument == "no-plugins") {
View::doLater([]{ ImGui::OpenPopup("No Plugins"); });
View::doLater([] { ImGui::OpenPopup("No Plugins"); });
} else if (argument == "tip-of-the-day") {
this->m_tipOfTheDay = value;
this->m_showTipOfTheDay = ContentRegistry::Settings::read("hex.builtin.setting.general", "hex.builtin.setting.general.show_tips", 1);
if (this->m_showTipOfTheDay)
View::doLater([]{ ImGui::OpenPopup("hex.welcome.tip_of_the_day"_lang); });
View::doLater([] { ImGui::OpenPopup("hex.welcome.tip_of_the_day"_lang); });
}
}
}
@ -128,37 +128,37 @@ namespace hex {
ImGui::UnloadImage(this->m_bannerTexture);
switch (theme) {
default:
case 1: /* Dark theme */
default:
case 1: /* Dark theme */
{
ImGui::StyleColorsDark();
ImGui::StyleCustomColorsDark();
ImPlot::StyleColorsDark();
auto banner = romfs::get("banner_dark.png");
this->m_bannerTexture = ImGui::LoadImageFromMemory(reinterpret_cast<const ImU8*>(banner.data()), banner.size());
this->m_bannerTexture = ImGui::LoadImageFromMemory(reinterpret_cast<const ImU8 *>(banner.data()), banner.size());
break;
}
case 2: /* Light theme */
case 2: /* Light theme */
{
ImGui::StyleColorsLight();
ImGui::StyleCustomColorsLight();
ImPlot::StyleColorsLight();
auto banner = romfs::get("banner_light.png");
this->m_bannerTexture = ImGui::LoadImageFromMemory(reinterpret_cast<const ImU8*>(banner.data()), banner.size());
this->m_bannerTexture = ImGui::LoadImageFromMemory(reinterpret_cast<const ImU8 *>(banner.data()), banner.size());
break;
}
case 3: /* Classic theme */
case 3: /* Classic theme */
{
ImGui::StyleColorsClassic();
ImGui::StyleCustomColorsClassic();
ImPlot::StyleColorsClassic();
auto banner = romfs::get("banner_dark.png");
this->m_bannerTexture = ImGui::LoadImageFromMemory(reinterpret_cast<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,23 +269,22 @@ namespace hex {
// Let's not loop on this...
std::signal(signalNumber, nullptr);
#if defined(DEBUG)
assert(false);
#else
std::raise(signalNumber);
#endif
#if defined(DEBUG)
assert(false);
#else
std::raise(signalNumber);
#endif
};
std::signal(SIGTERM, signalHandler);
std::signal(SIGSEGV, signalHandler);
std::signal(SIGINT, signalHandler);
std::signal(SIGILL, signalHandler);
std::signal(SIGINT, signalHandler);
std::signal(SIGILL, signalHandler);
std::signal(SIGABRT, signalHandler);
std::signal(SIGFPE, signalHandler);
std::signal(SIGFPE, signalHandler);
auto imhexLogo = romfs::get("logo.png");
this->m_logoTexture = ImGui::LoadImageFromMemory(reinterpret_cast<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)
glfwWindowHint(GLFW_DECORATED, GLFW_FALSE);
#elif defined(OS_MACOS)
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
#endif
#if defined(OS_WINDOWS)
glfwWindowHint(GLFW_DECORATED, GLFW_FALSE);
#elif defined(OS_MACOS)
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
#endif
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
@ -866,7 +860,7 @@ namespace hex {
if (auto g = ImGui::GetCurrentContext(); g == nullptr || g->WithinFrameScope) return;
auto win = static_cast<Window*>(glfwGetWindowUserPointer(window));
auto win = static_cast<Window *>(glfwGetWindowUserPointer(window));
win->frameBegin();
win->frame();
win->frameEnd();
@ -877,35 +871,33 @@ namespace hex {
if (auto g = ImGui::GetCurrentContext(); g == nullptr || g->WithinFrameScope) return;
auto win = static_cast<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();
win->m_pressedKeys.push_back(key);
io.KeysDown[key] = true;
io.KeyCtrl = (mods & GLFW_MOD_CONTROL) != 0;
io.KeyCtrl = (mods & GLFW_MOD_CONTROL) != 0;
io.KeyShift = (mods & GLFW_MOD_SHIFT) != 0;
io.KeyAlt = (mods & GLFW_MOD_ALT) != 0;
}
else if (action == GLFW_RELEASE) {
io.KeyAlt = (mods & GLFW_MOD_ALT) != 0;
} else if (action == GLFW_RELEASE) {
auto &io = ImGui::GetIO();
io.KeysDown[key] = false;
io.KeyCtrl = (mods & GLFW_MOD_CONTROL) != 0;
io.KeyCtrl = (mods & GLFW_MOD_CONTROL) != 0;
io.KeyShift = (mods & GLFW_MOD_SHIFT) != 0;
io.KeyAlt = (mods & GLFW_MOD_ALT) != 0;
io.KeyAlt = (mods & GLFW_MOD_ALT) != 0;
}
});
@ -950,43 +942,43 @@ namespace hex {
GImPlot = ImPlot::CreateContext();
GImNodes = ImNodes::CreateContext();
ImGuiIO& io = ImGui::GetIO();
ImGuiStyle& style = ImGui::GetStyle();
ImGuiIO &io = ImGui::GetIO();
ImGuiStyle &style = ImGui::GetStyle();
style.Alpha = 1.0F;
style.WindowRounding = 0.0F;
io.ConfigFlags |= ImGuiConfigFlags_DockingEnable | ImGuiConfigFlags_NavEnableKeyboard;
#if !defined(OS_LINUX)
#if !defined(OS_LINUX)
io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable;
#endif
#endif
for (auto &entry : SharedData::fontAtlas->ConfigData)
io.Fonts->ConfigData.push_back(entry);
io.ConfigViewportsNoTaskBarIcon = false;
io.KeyMap[ImGuiKey_Tab] = GLFW_KEY_TAB;
io.KeyMap[ImGuiKey_LeftArrow] = GLFW_KEY_LEFT;
io.KeyMap[ImGuiKey_RightArrow] = GLFW_KEY_RIGHT;
io.KeyMap[ImGuiKey_UpArrow] = GLFW_KEY_UP;
io.KeyMap[ImGuiKey_DownArrow] = GLFW_KEY_DOWN;
io.KeyMap[ImGuiKey_PageUp] = GLFW_KEY_PAGE_UP;
io.KeyMap[ImGuiKey_PageDown] = GLFW_KEY_PAGE_DOWN;
io.KeyMap[ImGuiKey_Home] = GLFW_KEY_HOME;
io.KeyMap[ImGuiKey_End] = GLFW_KEY_END;
io.KeyMap[ImGuiKey_Insert] = GLFW_KEY_INSERT;
io.KeyMap[ImGuiKey_Delete] = GLFW_KEY_DELETE;
io.KeyMap[ImGuiKey_Backspace] = GLFW_KEY_BACKSPACE;
io.KeyMap[ImGuiKey_Space] = GLFW_KEY_SPACE;
io.KeyMap[ImGuiKey_Enter] = GLFW_KEY_ENTER;
io.KeyMap[ImGuiKey_Escape] = GLFW_KEY_ESCAPE;
io.KeyMap[ImGuiKey_Tab] = GLFW_KEY_TAB;
io.KeyMap[ImGuiKey_LeftArrow] = GLFW_KEY_LEFT;
io.KeyMap[ImGuiKey_RightArrow] = GLFW_KEY_RIGHT;
io.KeyMap[ImGuiKey_UpArrow] = GLFW_KEY_UP;
io.KeyMap[ImGuiKey_DownArrow] = GLFW_KEY_DOWN;
io.KeyMap[ImGuiKey_PageUp] = GLFW_KEY_PAGE_UP;
io.KeyMap[ImGuiKey_PageDown] = GLFW_KEY_PAGE_DOWN;
io.KeyMap[ImGuiKey_Home] = GLFW_KEY_HOME;
io.KeyMap[ImGuiKey_End] = GLFW_KEY_END;
io.KeyMap[ImGuiKey_Insert] = GLFW_KEY_INSERT;
io.KeyMap[ImGuiKey_Delete] = GLFW_KEY_DELETE;
io.KeyMap[ImGuiKey_Backspace] = GLFW_KEY_BACKSPACE;
io.KeyMap[ImGuiKey_Space] = GLFW_KEY_SPACE;
io.KeyMap[ImGuiKey_Enter] = GLFW_KEY_ENTER;
io.KeyMap[ImGuiKey_Escape] = GLFW_KEY_ESCAPE;
io.KeyMap[ImGuiKey_KeyPadEnter] = GLFW_KEY_KP_ENTER;
io.KeyMap[ImGuiKey_A] = GLFW_KEY_A;
io.KeyMap[ImGuiKey_C] = GLFW_KEY_C;
io.KeyMap[ImGuiKey_V] = GLFW_KEY_V;
io.KeyMap[ImGuiKey_X] = GLFW_KEY_X;
io.KeyMap[ImGuiKey_Y] = GLFW_KEY_Y;
io.KeyMap[ImGuiKey_Z] = GLFW_KEY_Z;
io.KeyMap[ImGuiKey_A] = GLFW_KEY_A;
io.KeyMap[ImGuiKey_C] = GLFW_KEY_C;
io.KeyMap[ImGuiKey_V] = GLFW_KEY_V;
io.KeyMap[ImGuiKey_X] = GLFW_KEY_X;
io.KeyMap[ImGuiKey_Y] = GLFW_KEY_Y;
io.KeyMap[ImGuiKey_Z] = GLFW_KEY_Z;
ImNodes::PushAttributeFlag(ImNodesAttributeFlags_EnableLinkDetachWithDragClick);
ImNodes::PushAttributeFlag(ImNodesAttributeFlags_EnableLinkCreationOnSnap);
@ -1026,7 +1018,7 @@ namespace hex {
handler.ReadOpenFn = ImHexSettingsHandler_ReadOpenFn;
handler.ReadLineFn = ImHexSettingsHandler_ReadLine;
handler.WriteAllFn = ImHexSettingsHandler_WriteAll;
handler.UserData = this;
handler.UserData = this;
ImGui::GetCurrentContext()->SettingsHandlers.push_back(handler);
static std::string iniFileName;
@ -1052,7 +1044,7 @@ namespace hex {
}
void Window::exitImGui() {
delete static_cast<ImGui::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)
HANDLE m_diskHandle = INVALID_HANDLE_VALUE;
#else
std::string m_pathBuffer;
int m_diskHandle = -1;
#endif
#if defined(OS_WINDOWS)
HANDLE m_diskHandle = INVALID_HANDLE_VALUE;
#else
std::string m_pathBuffer;
int m_diskHandle = -1;
#endif
size_t m_diskSize;
size_t m_sectorSize;

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::Link> m_links;
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

@ -20,31 +20,31 @@ namespace hex {
};
enum class Operator : u16 {
Invalid = 0x000,
Assign = 0x010,
Or = 0x020,
Xor = 0x030,
And = 0x040,
BitwiseOr = 0x050,
BitwiseXor = 0x060,
BitwiseAnd = 0x070,
Equals = 0x080,
NotEquals = 0x081,
GreaterThan = 0x090,
LessThan = 0x091,
GreaterThanOrEquals = 0x092,
LessThanOrEquals = 0x093,
ShiftLeft = 0x0A0,
ShiftRight = 0x0A1,
Addition = 0x0B0,
Subtraction = 0x0B1,
Multiplication = 0x0C0,
Division = 0x0C1,
Modulus = 0x0C2,
Exponentiation = 0x1D0,
Combine = 0x0E0,
BitwiseNot = 0x0F0,
Not = 0x0F1
Invalid = 0x000,
Assign = 0x010,
Or = 0x020,
Xor = 0x030,
And = 0x040,
BitwiseOr = 0x050,
BitwiseXor = 0x060,
BitwiseAnd = 0x070,
Equals = 0x080,
NotEquals = 0x081,
GreaterThan = 0x090,
LessThan = 0x091,
GreaterThanOrEquals = 0x092,
LessThanOrEquals = 0x093,
ShiftLeft = 0x0A0,
ShiftRight = 0x0A1,
Addition = 0x0B0,
Subtraction = 0x0B1,
Multiplication = 0x0C0,
Division = 0x0C1,
Modulus = 0x0C2,
Exponentiation = 0x1D0,
Combine = 0x0E0,
BitwiseNot = 0x0F0,
Not = 0x0F1
};
enum class BracketType : std::uint8_t {
@ -74,7 +74,7 @@ namespace hex {
void setVariable(std::string name, long double value);
void setFunction(std::string name, std::function<std::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);

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