1
0
mirror of synced 2024-09-24 03:28:24 +02:00

sys: Reformat all

This commit is contained in:
WerWolv 2022-02-01 22:09:44 +01:00
parent 1991afb87b
commit ce59226909
99 changed files with 2304 additions and 2314 deletions

View File

@ -2,10 +2,10 @@
Language: Cpp
# BasedOnStyle: LLVM
AccessModifierOffset: -4
AlignAfterOpenBracket: Align
AlignAfterOpenBracket: false
AlignArrayOfStructures: Left
AlignConsecutiveMacros: Consecutive
AlignConsecutiveAssignments: None
AlignConsecutiveAssignments: Consecutive
AlignConsecutiveBitFields: AcrossEmptyLinesAndComments
AlignConsecutiveDeclarations: None
AlignEscapedNewlines: Left
@ -13,7 +13,7 @@ AlignOperands: Align
AlignTrailingComments: true
AllowAllArgumentsOnNextLine: true
AllowAllConstructorInitializersOnNextLine: true
AllowAllParametersOfDeclarationOnNextLine: true
AllowAllParametersOfDeclarationOnNextLine: false
AllowShortEnumsOnASingleLine: false
AllowShortBlocksOnASingleLine: Always
AllowShortCaseLabelsOnASingleLine: false
@ -95,7 +95,7 @@ IncludeCategories:
IncludeIsMainRegex: '(Test)?$'
IncludeIsMainSourceRegex: ''
IndentAccessModifiers: false
IndentCaseLabels: false
IndentCaseLabels: true
IndentCaseBlocks: true
IndentGotoLabels: true
IndentPPDirectives: BeforeHash

View File

@ -3,19 +3,19 @@
#include <cstdint>
#include <cstddef>
constexpr static const auto ImHexApiURL = "https://api.werwolv.net/imhex";
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 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 i8 = std::int8_t;
using i16 = std::int16_t;
using i32 = std::int32_t;
using i64 = std::int64_t;
using i128 = __int128_t;
using color_t = u32;

View File

@ -85,7 +85,11 @@ namespace hex {
};
void add(
Type type, const std::string &command, const std::string &unlocalizedDescription, const DisplayCallback &displayCallback, const ExecuteCallback &executeCallback = [](auto) {});
Type type,
const std::string &command,
const std::string &unlocalizedDescription,
const DisplayCallback &displayCallback,
const ExecuteCallback &executeCallback = [](auto) {});
std::vector<Entry> &getEntries();
}
@ -101,14 +105,14 @@ namespace hex {
}
constexpr static u32 UnlimitedParameters = 0xFFFF'FFFF;
constexpr static u32 MoreParametersThan = 0x8000'0000;
constexpr static u32 LessParametersThan = 0x4000'0000;
constexpr static u32 ExactlyOrMoreParametersThan = 0x2000'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 ExactlyOrMoreParametersThan = 0x2000'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;
@ -120,7 +124,7 @@ namespace hex {
void addDangerousFunction(const Namespace &ns, const std::string &name, u32 parameterCount, const Callback &func);
std::map<std::string, ContentRegistry::PatternLanguage::Function> &getFunctions();
std::vector<impl::ColorPalette>& getPalettes();
std::vector<impl::ColorPalette> &getPalettes();
void addColorPalette(const std::string &unlocalizedName, const std::vector<u32> &colors);
void setSelectedPalette(u32 index);
u32 getNextColor();
@ -177,7 +181,7 @@ namespace hex {
namespace impl {
using DisplayFunction = std::function<std::string()>;
using DisplayFunction = std::function<std::string()>;
using GeneratorFunction = std::function<DisplayFunction(const std::vector<u8> &, std::endian, NumberDisplayStyle)>;
struct Entry {
@ -240,7 +244,7 @@ namespace hex {
namespace impl {
using DrawCallback = std::function<void()>;
using DrawCallback = std::function<void()>;
using LayoutFunction = std::function<void(u32)>;
struct Layout {

View File

@ -93,7 +93,7 @@ namespace hex {
Task createTask(const std::string &unlocalizedName, u64 maxValue);
void doLater(const std::function<void()> &function);
std::vector<std::function<void()>>& getDeferredCalls();
std::vector<std::function<void()>> &getDeferredCalls();
}
@ -116,7 +116,7 @@ namespace hex {
char **envp;
};
const ProgramArguments& getProgramArguments();
const ProgramArguments &getProgramArguments();
float getTargetFPS();
void setTargetFPS(float fps);
@ -127,7 +127,7 @@ namespace hex {
ImVec2 getMainWindowSize();
ImGuiID getMainDockSpaceId();
std::map<std::string, std::string>& getInitArguments();
std::map<std::string, std::string> &getInitArguments();
}

View File

@ -14,118 +14,118 @@ 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,
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,
KeyPadAdd = GLFW_KEY_KP_ADD,
KeyPadEnter = GLFW_KEY_KP_ENTER,
KeyPadEqual = GLFW_KEY_KP_EQUAL,
Menu = GLFW_KEY_MENU,
};
@ -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));
@ -187,6 +187,7 @@ namespace hex {
static void process(View *currentView, bool ctrl, bool alt, bool shift, bool super, bool focused, u32 keyCode);
static void clearShortcuts();
private:
static std::map<Shortcut, std::function<void()>> s_globalShortcuts;
};

View File

@ -31,26 +31,26 @@ namespace hex {
[[nodiscard]] bool isLoaded() const;
private:
using InitializePluginFunc = void (*)();
using GetPluginNameFunc = const char *(*)();
using GetPluginAuthorFunc = const char *(*)();
using InitializePluginFunc = void (*)();
using GetPluginNameFunc = const char *(*)();
using GetPluginAuthorFunc = const char *(*)();
using GetPluginDescriptionFunc = const char *(*)();
using GetCompatibleVersionFunc = const char *(*)();
using SetImGuiContextFunc = void (*)(ImGuiContext *);
using IsBuiltinPluginFunc = bool(*)();
using SetImGuiContextFunc = void (*)(ImGuiContext *);
using IsBuiltinPluginFunc = bool (*)();
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;
InitializePluginFunc m_initializePluginFunction = nullptr;
GetPluginNameFunc m_getPluginNameFunction = nullptr;
GetPluginAuthorFunc m_getPluginAuthorFunction = nullptr;
GetPluginDescriptionFunc m_getPluginDescriptionFunction = nullptr;
GetCompatibleVersionFunc m_getCompatibleVersionFunction = nullptr;
SetImGuiContextFunc m_setImGuiContextFunction = nullptr;
IsBuiltinPluginFunc m_isBuiltinPluginFunction = nullptr;
SetImGuiContextFunc m_setImGuiContextFunction = nullptr;
IsBuiltinPluginFunc m_isBuiltinPluginFunction = nullptr;
template<typename T>
[[nodiscard]] auto getPluginFunction(const std::string &symbol) {

View File

@ -24,8 +24,8 @@ namespace hex {
[[nodiscard]] bool isPending() const;
static size_t getRunningTaskCount();
static std::list<Task *>& getRunningTasks() { return Task::s_runningTasks; }
static std::mutex& getTaskMutex() { return Task::s_taskMutex; }
static std::list<Task *> &getRunningTasks() { return Task::s_runningTasks; }
static std::mutex &getTaskMutex() { return Task::s_taskMutex; }
private:
std::string m_name;

View File

@ -166,7 +166,7 @@ namespace hex {
template<typename T>
class Cloneable {
public:
[[nodiscard]] virtual T* clone() const = 0;
[[nodiscard]] virtual T *clone() const = 0;
};
}

View File

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

View File

@ -58,7 +58,7 @@ namespace hex {
curl_slist *m_headers = nullptr;
std::mutex m_transmissionActive;
float m_progress = 0.0F;
float m_progress = 0.0F;
bool m_shouldCancel = false;
};

View File

@ -24,7 +24,7 @@ namespace hex {
class Socket {
public:
Socket() = default;
Socket() = default;
Socket(const Socket &) = delete;
Socket(Socket &&other);

View File

@ -45,7 +45,7 @@ namespace hex {
if (from < to) std::swap(from, to);
using ValueType = std::remove_cvref_t<decltype(value)>;
ValueType mask = (std::numeric_limits<ValueType>::max() >> (((sizeof(value) * 8) - 1) - (from - to))) << to;
ValueType mask = (std::numeric_limits<ValueType>::max() >> (((sizeof(value) * 8) - 1) - (from - to))) << to;
return (value & mask) >> to;
}
@ -111,23 +111,23 @@ namespace hex {
static_assert(always_false<T>::value, "Invalid type provided!");
switch (Size) {
case 1:
swapped = unswapped;
break;
case 2:
swapped = __builtin_bswap16(unswapped);
break;
case 4:
swapped = __builtin_bswap32(unswapped);
break;
case 8:
swapped = __builtin_bswap64(unswapped);
break;
case 16:
swapped = (u128(__builtin_bswap64(unswapped & 0xFFFF'FFFF'FFFF'FFFF)) << 64) | __builtin_bswap64(u128(unswapped) >> 64);
break;
default:
__builtin_unreachable();
case 1:
swapped = unswapped;
break;
case 2:
swapped = __builtin_bswap16(unswapped);
break;
case 4:
swapped = __builtin_bswap32(unswapped);
break;
case 8:
swapped = __builtin_bswap64(unswapped);
break;
case 16:
swapped = (u128(__builtin_bswap64(unswapped & 0xFFFF'FFFF'FFFF'FFFF)) << 64) | __builtin_bswap64(u128(unswapped) >> 64);
break;
default:
__builtin_unreachable();
}
T result;
@ -151,23 +151,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;
@ -231,15 +231,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) {
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) {

View File

@ -51,7 +51,7 @@ namespace hex::pl {
ASTNodeAttribute(const ASTNodeAttribute &other) : ASTNode(other) {
this->m_attribute = other.m_attribute;
this->m_value = other.m_value;
this->m_value = other.m_value;
}
[[nodiscard]] ASTNode *clone() const override {
@ -81,7 +81,7 @@ namespace hex::pl {
Attributable(const Attributable &other) {
for (auto &attribute : other.m_attributes) {
if (auto node = dynamic_cast<ASTNodeAttribute*>(attribute->clone()))
if (auto node = dynamic_cast<ASTNodeAttribute *>(attribute->clone()))
this->m_attributes.push_back(node);
else
delete node;
@ -175,8 +175,8 @@ namespace hex::pl {
ASTNodeMathematicalExpression(const ASTNodeMathematicalExpression &other) : ASTNode(other) {
this->m_operator = other.m_operator;
this->m_left = other.m_left->clone();
this->m_right = other.m_right->clone();
this->m_left = other.m_left->clone();
this->m_right = other.m_right->clone();
}
[[nodiscard]] ASTNode *clone() const override {
@ -187,7 +187,7 @@ namespace hex::pl {
if (this->getLeftOperand() == nullptr || this->getRightOperand() == nullptr)
LogConsole::abortEvaluation("attempted to use void expression in mathematical expression", this);
auto *left = dynamic_cast<ASTNodeLiteral *>(this->getLeftOperand()->evaluate(evaluator));
auto *left = dynamic_cast<ASTNodeLiteral *>(this->getLeftOperand()->evaluate(evaluator));
auto *right = dynamic_cast<ASTNodeLiteral *>(this->getRightOperand()->evaluate(evaluator));
ON_SCOPE_EXIT {
delete left;
@ -213,105 +213,105 @@ namespace hex::pl {
[this](auto &&left, const std::string &right) -> ASTNode * { LogConsole::abortEvaluation("invalid operand used in mathematical expression", this); },
[this](const std::string &left, auto &&right) -> ASTNode * {
switch (this->getOperator()) {
case Token::Operator::Star:
{
std::string result;
for (auto i = 0; i < right; i++)
result += left;
return new ASTNodeLiteral(result);
}
default:
LogConsole::abortEvaluation("invalid operand used in mathematical expression", this);
case Token::Operator::Star:
{
std::string result;
for (auto i = 0; i < right; i++)
result += left;
return new ASTNodeLiteral(result);
}
default:
LogConsole::abortEvaluation("invalid operand used in mathematical expression", this);
}
},
[this](const std::string &left, const std::string &right) -> ASTNode * {
switch (this->getOperator()) {
case Token::Operator::Plus:
return new ASTNodeLiteral(left + right);
case Token::Operator::BoolEquals:
return new ASTNodeLiteral(left == right);
case Token::Operator::BoolNotEquals:
return new ASTNodeLiteral(left != right);
case Token::Operator::BoolGreaterThan:
return new ASTNodeLiteral(left > right);
case Token::Operator::BoolLessThan:
return new ASTNodeLiteral(left < right);
case Token::Operator::BoolGreaterThanOrEquals:
return new ASTNodeLiteral(left >= right);
case Token::Operator::BoolLessThanOrEquals:
return new ASTNodeLiteral(left <= right);
default:
LogConsole::abortEvaluation("invalid operand used in mathematical expression", this);
case Token::Operator::Plus:
return new ASTNodeLiteral(left + right);
case Token::Operator::BoolEquals:
return new ASTNodeLiteral(left == right);
case Token::Operator::BoolNotEquals:
return new ASTNodeLiteral(left != right);
case Token::Operator::BoolGreaterThan:
return new ASTNodeLiteral(left > right);
case Token::Operator::BoolLessThan:
return new ASTNodeLiteral(left < right);
case Token::Operator::BoolGreaterThanOrEquals:
return new ASTNodeLiteral(left >= right);
case Token::Operator::BoolLessThanOrEquals:
return new ASTNodeLiteral(left <= right);
default:
LogConsole::abortEvaluation("invalid operand used in mathematical expression", this);
}
},
[this](const std::string &left, char right) -> ASTNode * {
switch (this->getOperator()) {
case Token::Operator::Plus:
return new ASTNodeLiteral(left + right);
default:
LogConsole::abortEvaluation("invalid operand used in mathematical expression", this);
case Token::Operator::Plus:
return new ASTNodeLiteral(left + right);
default:
LogConsole::abortEvaluation("invalid operand used in mathematical expression", this);
}
},
[this](char left, const std::string &right) -> ASTNode * {
switch (this->getOperator()) {
case Token::Operator::Plus:
return new ASTNodeLiteral(left + right);
default:
LogConsole::abortEvaluation("invalid operand used in mathematical expression", this);
case Token::Operator::Plus:
return new ASTNodeLiteral(left + right);
default:
LogConsole::abortEvaluation("invalid operand used in mathematical expression", this);
}
},
[this](auto &&left, auto &&right) -> ASTNode * {
switch (this->getOperator()) {
case Token::Operator::Plus:
return new ASTNodeLiteral(left + right);
case Token::Operator::Minus:
return new ASTNodeLiteral(left - right);
case Token::Operator::Star:
return new ASTNodeLiteral(left * right);
case Token::Operator::Slash:
if (right == 0) LogConsole::abortEvaluation("division by zero!", this);
return new ASTNodeLiteral(left / right);
case Token::Operator::Percent:
if (right == 0) LogConsole::abortEvaluation("division by zero!", this);
return new ASTNodeLiteral(modulus(left, right));
case Token::Operator::ShiftLeft:
return new ASTNodeLiteral(shiftLeft(left, right));
case Token::Operator::ShiftRight:
return new ASTNodeLiteral(shiftRight(left, right));
case Token::Operator::BitAnd:
return new ASTNodeLiteral(bitAnd(left, right));
case Token::Operator::BitXor:
return new ASTNodeLiteral(bitXor(left, right));
case Token::Operator::BitOr:
return new ASTNodeLiteral(bitOr(left, right));
case Token::Operator::BitNot:
return new ASTNodeLiteral(bitNot(left, right));
case Token::Operator::BoolEquals:
return new ASTNodeLiteral(bool(left == right));
case Token::Operator::BoolNotEquals:
return new ASTNodeLiteral(bool(left != right));
case Token::Operator::BoolGreaterThan:
return new ASTNodeLiteral(bool(left > right));
case Token::Operator::BoolLessThan:
return new ASTNodeLiteral(bool(left < right));
case Token::Operator::BoolGreaterThanOrEquals:
return new ASTNodeLiteral(bool(left >= right));
case Token::Operator::BoolLessThanOrEquals:
return new ASTNodeLiteral(bool(left <= right));
case Token::Operator::BoolAnd:
return new ASTNodeLiteral(bool(left && right));
case Token::Operator::BoolXor:
return new ASTNodeLiteral(bool(left && !right || !left && right));
case Token::Operator::BoolOr:
return new ASTNodeLiteral(bool(left || right));
case Token::Operator::BoolNot:
return new ASTNodeLiteral(bool(!right));
default:
LogConsole::abortEvaluation("invalid operand used in mathematical expression", this);
case Token::Operator::Plus:
return new ASTNodeLiteral(left + right);
case Token::Operator::Minus:
return new ASTNodeLiteral(left - right);
case Token::Operator::Star:
return new ASTNodeLiteral(left * right);
case Token::Operator::Slash:
if (right == 0) LogConsole::abortEvaluation("division by zero!", this);
return new ASTNodeLiteral(left / right);
case Token::Operator::Percent:
if (right == 0) LogConsole::abortEvaluation("division by zero!", this);
return new ASTNodeLiteral(modulus(left, right));
case Token::Operator::ShiftLeft:
return new ASTNodeLiteral(shiftLeft(left, right));
case Token::Operator::ShiftRight:
return new ASTNodeLiteral(shiftRight(left, right));
case Token::Operator::BitAnd:
return new ASTNodeLiteral(bitAnd(left, right));
case Token::Operator::BitXor:
return new ASTNodeLiteral(bitXor(left, right));
case Token::Operator::BitOr:
return new ASTNodeLiteral(bitOr(left, right));
case Token::Operator::BitNot:
return new ASTNodeLiteral(bitNot(left, right));
case Token::Operator::BoolEquals:
return new ASTNodeLiteral(bool(left == right));
case Token::Operator::BoolNotEquals:
return new ASTNodeLiteral(bool(left != right));
case Token::Operator::BoolGreaterThan:
return new ASTNodeLiteral(bool(left > right));
case Token::Operator::BoolLessThan:
return new ASTNodeLiteral(bool(left < right));
case Token::Operator::BoolGreaterThanOrEquals:
return new ASTNodeLiteral(bool(left >= right));
case Token::Operator::BoolLessThanOrEquals:
return new ASTNodeLiteral(bool(left <= right));
case Token::Operator::BoolAnd:
return new ASTNodeLiteral(bool(left && right));
case Token::Operator::BoolXor:
return new ASTNodeLiteral(bool(left && !right || !left && right));
case Token::Operator::BoolOr:
return new ASTNodeLiteral(bool(left || right));
case Token::Operator::BoolNot:
return new ASTNodeLiteral(bool(!right));
default:
LogConsole::abortEvaluation("invalid operand used in mathematical expression", this);
}
} },
left->getValue(),
right->getValue());
left->getValue(),
right->getValue());
}
[[nodiscard]] ASTNode *getLeftOperand() const { return this->m_left; }
@ -336,9 +336,9 @@ namespace hex::pl {
ASTNodeTernaryExpression(const ASTNodeTernaryExpression &other) : ASTNode(other) {
this->m_operator = other.m_operator;
this->m_first = other.m_first->clone();
this->m_second = other.m_second->clone();
this->m_third = other.m_third->clone();
this->m_first = other.m_first->clone();
this->m_second = other.m_second->clone();
this->m_third = other.m_third->clone();
}
[[nodiscard]] ASTNode *clone() const override {
@ -349,9 +349,9 @@ namespace hex::pl {
if (this->getFirstOperand() == nullptr || this->getSecondOperand() == nullptr || this->getThirdOperand() == nullptr)
LogConsole::abortEvaluation("attempted to use void expression in mathematical expression", this);
auto *first = dynamic_cast<ASTNodeLiteral *>(this->getFirstOperand()->evaluate(evaluator));
auto *first = dynamic_cast<ASTNodeLiteral *>(this->getFirstOperand()->evaluate(evaluator));
auto *second = dynamic_cast<ASTNodeLiteral *>(this->getSecondOperand()->evaluate(evaluator));
auto *third = dynamic_cast<ASTNodeLiteral *>(this->getThirdOperand()->evaluate(evaluator));
auto *third = dynamic_cast<ASTNodeLiteral *>(this->getThirdOperand()->evaluate(evaluator));
ON_SCOPE_EXIT {
delete first;
delete second;
@ -362,13 +362,13 @@ namespace hex::pl {
[](const std::string &value) -> bool { return !value.empty(); },
[this](PatternData *const &) -> bool { LogConsole::abortEvaluation("cannot cast custom type to bool", this); },
[](auto &&value) -> bool { return bool(value); } },
first->getValue());
first->getValue());
return std::visit(overloaded {
[condition]<typename T>(const T &second, const T &third) -> ASTNode * { return new ASTNodeLiteral(condition ? second : third); },
[this](auto &&second, auto &&third) -> ASTNode * { LogConsole::abortEvaluation("operands to ternary expression have different types", this); } },
second->getValue(),
third->getValue());
second->getValue(),
third->getValue());
}
[[nodiscard]] ASTNode *getFirstOperand() const { return this->m_first; }
@ -394,7 +394,7 @@ namespace hex::pl {
[[nodiscard]] std::vector<PatternData *> createPatterns(Evaluator *evaluator) const override {
auto offset = evaluator->dataOffset();
auto size = Token::getTypeSize(this->m_type);
auto size = Token::getTypeSize(this->m_type);
evaluator->dataOffset() += size;
@ -436,8 +436,8 @@ namespace hex::pl {
: ASTNode(), m_name(std::move(name)), m_type(type), m_endian(endian) { }
ASTNodeTypeDecl(const ASTNodeTypeDecl &other) : ASTNode(other), Attributable(other) {
this->m_name = other.m_name;
this->m_type = other.m_type;
this->m_name = other.m_name;
this->m_type = other.m_type;
this->m_endian = other.m_endian;
}
@ -455,7 +455,7 @@ namespace hex::pl {
if (auto attributable = dynamic_cast<Attributable *>(type)) {
for (auto &attribute : this->getAttributes()) {
if (auto node = dynamic_cast<ASTNodeAttribute*>(attribute->clone()))
if (auto node = dynamic_cast<ASTNodeAttribute *>(attribute->clone()))
attributable->addAttribute(node);
else
delete node;
@ -493,7 +493,7 @@ namespace hex::pl {
ASTNodeCast(ASTNode *value, ASTNode *type) : m_value(value), m_type(type) { }
ASTNodeCast(const ASTNodeCast &other) : ASTNode(other) {
this->m_value = other.m_value->clone();
this->m_type = other.m_type->clone();
this->m_type = other.m_type->clone();
}
~ASTNodeCast() override {
@ -507,7 +507,7 @@ namespace hex::pl {
[[nodiscard]] ASTNode *evaluate(Evaluator *evaluator) const override {
auto literal = dynamic_cast<ASTNodeLiteral *>(this->m_value->evaluate(evaluator));
auto type = dynamic_cast<ASTNodeBuiltinType *>(this->m_type->evaluate(evaluator))->getType();
auto type = dynamic_cast<ASTNodeBuiltinType *>(this->m_type->evaluate(evaluator))->getType();
auto startOffset = evaluator->dataOffset();
@ -523,53 +523,53 @@ namespace hex::pl {
[&, this](auto &&value) -> ASTNode * {
auto endianAdjustedValue = hex::changeEndianess(value, typePattern->getSize(), typePattern->getEndian());
switch (type) {
case Token::ValueType::Unsigned8Bit:
return new ASTNodeLiteral(u128(u8(endianAdjustedValue)));
case Token::ValueType::Unsigned16Bit:
return new ASTNodeLiteral(u128(u16(endianAdjustedValue)));
case Token::ValueType::Unsigned32Bit:
return new ASTNodeLiteral(u128(u32(endianAdjustedValue)));
case Token::ValueType::Unsigned64Bit:
return new ASTNodeLiteral(u128(u64(endianAdjustedValue)));
case Token::ValueType::Unsigned128Bit:
return new ASTNodeLiteral(u128(endianAdjustedValue));
case Token::ValueType::Signed8Bit:
return new ASTNodeLiteral(i128(i8(endianAdjustedValue)));
case Token::ValueType::Signed16Bit:
return new ASTNodeLiteral(i128(i16(endianAdjustedValue)));
case Token::ValueType::Signed32Bit:
return new ASTNodeLiteral(i128(i32(endianAdjustedValue)));
case Token::ValueType::Signed64Bit:
return new ASTNodeLiteral(i128(i64(endianAdjustedValue)));
case Token::ValueType::Signed128Bit:
return new ASTNodeLiteral(i128(endianAdjustedValue));
case Token::ValueType::Float:
return new ASTNodeLiteral(double(float(endianAdjustedValue)));
case Token::ValueType::Double:
return new ASTNodeLiteral(double(endianAdjustedValue));
case Token::ValueType::Character:
return new ASTNodeLiteral(char(endianAdjustedValue));
case Token::ValueType::Character16:
return new ASTNodeLiteral(u128(char16_t(endianAdjustedValue)));
case Token::ValueType::Boolean:
return new ASTNodeLiteral(bool(endianAdjustedValue));
case Token::ValueType::String:
{
std::string string(sizeof(value), '\x00');
std::memcpy(string.data(), &value, string.size());
hex::trim(string);
case Token::ValueType::Unsigned8Bit:
return new ASTNodeLiteral(u128(u8(endianAdjustedValue)));
case Token::ValueType::Unsigned16Bit:
return new ASTNodeLiteral(u128(u16(endianAdjustedValue)));
case Token::ValueType::Unsigned32Bit:
return new ASTNodeLiteral(u128(u32(endianAdjustedValue)));
case Token::ValueType::Unsigned64Bit:
return new ASTNodeLiteral(u128(u64(endianAdjustedValue)));
case Token::ValueType::Unsigned128Bit:
return new ASTNodeLiteral(u128(endianAdjustedValue));
case Token::ValueType::Signed8Bit:
return new ASTNodeLiteral(i128(i8(endianAdjustedValue)));
case Token::ValueType::Signed16Bit:
return new ASTNodeLiteral(i128(i16(endianAdjustedValue)));
case Token::ValueType::Signed32Bit:
return new ASTNodeLiteral(i128(i32(endianAdjustedValue)));
case Token::ValueType::Signed64Bit:
return new ASTNodeLiteral(i128(i64(endianAdjustedValue)));
case Token::ValueType::Signed128Bit:
return new ASTNodeLiteral(i128(endianAdjustedValue));
case Token::ValueType::Float:
return new ASTNodeLiteral(double(float(endianAdjustedValue)));
case Token::ValueType::Double:
return new ASTNodeLiteral(double(endianAdjustedValue));
case Token::ValueType::Character:
return new ASTNodeLiteral(char(endianAdjustedValue));
case Token::ValueType::Character16:
return new ASTNodeLiteral(u128(char16_t(endianAdjustedValue)));
case Token::ValueType::Boolean:
return new ASTNodeLiteral(bool(endianAdjustedValue));
case Token::ValueType::String:
{
std::string string(sizeof(value), '\x00');
std::memcpy(string.data(), &value, string.size());
hex::trim(string);
if (typePattern->getEndian() != std::endian::native)
std::reverse(string.begin(), string.end());
if (typePattern->getEndian() != std::endian::native)
std::reverse(string.begin(), string.end());
return new ASTNodeLiteral(string);
}
default:
LogConsole::abortEvaluation(hex::format("cannot cast value to '{}'", Token::getTypeName(type)), this);
return new ASTNodeLiteral(string);
}
default:
LogConsole::abortEvaluation(hex::format("cannot cast value to '{}'", Token::getTypeName(type)), this);
}
},
},
literal->getValue());
literal->getValue());
}
private:
@ -621,8 +621,8 @@ namespace hex::pl {
while (evaluateCondition(evaluator)) {
evaluator->handleAbort();
auto variables = *evaluator->getScope(0).scope;
auto parameterPack = evaluator->getScope(0).parameterPack;
auto variables = *evaluator->getScope(0).scope;
auto parameterPack = evaluator->getScope(0).parameterPack;
u32 startVariableCount = variables.size();
ON_SCOPE_EXIT {
ssize_t stackSize = evaluator->getStack().size();
@ -676,7 +676,7 @@ namespace hex::pl {
[](const std::string &value) -> bool { return !value.empty(); },
[this](PatternData *const &) -> bool { LogConsole::abortEvaluation("cannot cast custom type to bool", this); },
[](auto &&value) -> bool { return value != 0; } },
literal->getValue());
literal->getValue());
}
private:
@ -686,7 +686,7 @@ namespace hex::pl {
};
inline void applyVariableAttributes(Evaluator *evaluator, const Attributable *attributable, PatternData *pattern) {
auto endOffset = evaluator->dataOffset();
auto endOffset = evaluator->dataOffset();
evaluator->dataOffset() = pattern->getOffset();
ON_SCOPE_EXIT { evaluator->dataOffset() = endOffset; };
@ -787,7 +787,7 @@ namespace hex::pl {
else
this->m_placementOffset = nullptr;
this->m_inVariable = other.m_inVariable;
this->m_inVariable = other.m_inVariable;
this->m_outVariable = other.m_outVariable;
}
@ -816,7 +816,7 @@ namespace hex::pl {
[this](const std::string &) -> u64 { LogConsole::abortEvaluation("placement offset cannot be a string", this); },
[this](PatternData *const &) -> u64 { LogConsole::abortEvaluation("placement offset cannot be a custom type", this); },
[](auto &&offset) -> u64 { return offset; } },
offset->getValue());
offset->getValue());
}
auto pattern = this->m_type->createPatterns(evaluator).front();
@ -880,7 +880,7 @@ namespace hex::pl {
[this](const std::string &) -> u64 { LogConsole::abortEvaluation("placement offset cannot be a string", this); },
[this](PatternData *const &) -> u64 { LogConsole::abortEvaluation("placement offset cannot be a custom type", this); },
[](auto &&offset) -> u64 { return offset; } },
offset->getValue());
offset->getValue());
}
auto type = this->m_type->evaluate(evaluator);
@ -938,7 +938,7 @@ namespace hex::pl {
[this](const std::string &) -> u128 { LogConsole::abortEvaluation("cannot use string to index array", this); },
[this](PatternData *) -> u128 { LogConsole::abortEvaluation("cannot use custom type to index array", this); },
[](auto &&size) -> u128 { return size; } },
literal->getValue());
literal->getValue());
} else if (auto whileStatement = dynamic_cast<ASTNodeWhileStatement *>(sizeNode)) {
while (whileStatement->evaluateCondition(evaluator)) {
entryCount++;
@ -1004,7 +1004,7 @@ namespace hex::pl {
delete entry;
};
size_t size = 0;
size_t size = 0;
u64 entryIndex = 0;
auto addEntries = [&](const std::vector<PatternData *> &patterns) {
@ -1037,7 +1037,7 @@ namespace hex::pl {
[this](const std::string &) -> u128 { LogConsole::abortEvaluation("cannot use string to index array", this); },
[this](PatternData *) -> u128 { LogConsole::abortEvaluation("cannot use custom type to index array", this); },
[](auto &&size) -> u128 { return size; } },
literal->getValue());
literal->getValue());
auto limit = evaluator->getArrayLimit();
if (entryCount > limit)
@ -1085,7 +1085,7 @@ namespace hex::pl {
} else {
while (true) {
bool reachedEnd = true;
auto limit = evaluator->getArrayLimit();
auto limit = evaluator->getArrayLimit();
if (entryIndex > limit)
LogConsole::abortEvaluation(hex::format("array grew past set limit of {}", limit), this);
@ -1150,8 +1150,8 @@ namespace hex::pl {
: ASTNode(), m_name(std::move(name)), m_type(type), m_sizeType(sizeType), m_placementOffset(placementOffset) { }
ASTNodePointerVariableDecl(const ASTNodePointerVariableDecl &other) : ASTNode(other), Attributable(other) {
this->m_name = other.m_name;
this->m_type = other.m_type->clone();
this->m_name = other.m_name;
this->m_type = other.m_type->clone();
this->m_sizeType = other.m_sizeType->clone();
if (other.m_placementOffset != nullptr)
@ -1184,7 +1184,7 @@ namespace hex::pl {
[this](const std::string &) -> u64 { LogConsole::abortEvaluation("placement offset cannot be a string", this); },
[this](PatternData *) -> u64 { LogConsole::abortEvaluation("placement offset cannot be a custom type", this); },
[](auto &&offset) -> u64 { return u64(offset); } },
offset->getValue());
offset->getValue());
}
auto startOffset = evaluator->dataOffset();
@ -1430,7 +1430,7 @@ namespace hex::pl {
}
[[nodiscard]] std::vector<PatternData *> createPatterns(Evaluator *evaluator) const override {
auto pattern = new PatternDataEnum(evaluator, evaluator->dataOffset(), 0);
auto pattern = new PatternDataEnum(evaluator, evaluator->dataOffset(), 0);
auto enumCleanup = SCOPE_GUARD { delete pattern; };
@ -1507,7 +1507,7 @@ namespace hex::pl {
[this](const std::string &) -> u8 { LogConsole::abortEvaluation("bitfield field size cannot be a string", this); },
[this](PatternData *) -> u8 { LogConsole::abortEvaluation("bitfield field size cannot be a custom type", this); },
[](auto &&offset) -> u8 { return static_cast<u8>(offset); } },
dynamic_cast<ASTNodeLiteral *>(literal)->getValue());
dynamic_cast<ASTNodeLiteral *>(literal)->getValue());
// If a field is named padding, it was created through a padding expression and only advances the bit position
if (name != "padding") {
@ -1536,7 +1536,7 @@ namespace hex::pl {
class ASTNodeParameterPack : public ASTNode {
public:
explicit ASTNodeParameterPack(std::vector<Token::Literal> values) : m_values(std::move(values)) {}
explicit ASTNodeParameterPack(std::vector<Token::Literal> values) : m_values(std::move(values)) { }
[[nodiscard]] ASTNode *clone() const override {
return new ASTNodeParameterPack(*this);
@ -1595,7 +1595,7 @@ namespace hex::pl {
} else if (dynamic_cast<PatternDataSigned *>(pattern)) {
i128 value = 0;
readVariable(evaluator, value, pattern);
value = hex::signExtend(pattern->getSize() * 8, value);
value = hex::signExtend(pattern->getSize() * 8, value);
literal = value;
} else if (dynamic_cast<PatternDataFloat *>(pattern)) {
if (pattern->getSize() == sizeof(u16)) {
@ -1635,7 +1635,7 @@ namespace hex::pl {
readVariable(evaluator, value, assignmentValue);
},
[&, this](auto &&assignmentValue) { LogConsole::abortEvaluation(hex::format("cannot assign '{}' to string", pattern->getTypeName()), this); } },
literal);
literal);
} else {
value.resize(pattern->getSize());
evaluator->getProvider()->read(pattern->getOffset(), value.data(), value.size());
@ -1665,7 +1665,7 @@ namespace hex::pl {
[[nodiscard]] std::vector<PatternData *> createPatterns(Evaluator *evaluator) const override {
std::vector<PatternData *> searchScope;
PatternData *currPattern = nullptr;
i32 scopeIndex = 0;
i32 scopeIndex = 0;
if (!evaluator->isGlobalScope()) {
@ -1690,7 +1690,7 @@ namespace hex::pl {
if (-scopeIndex >= evaluator->getScopeCount())
LogConsole::abortEvaluation("cannot access parent of global scope", this);
searchScope = *evaluator->getScope(scopeIndex).scope;
searchScope = *evaluator->getScope(scopeIndex).scope;
auto currParent = evaluator->getScope(scopeIndex).parent;
if (currParent == nullptr) {
@ -1717,7 +1717,7 @@ namespace hex::pl {
auto newPattern = (*iter)->clone();
delete currPattern;
currPattern = newPattern;
found = true;
found = true;
break;
}
}
@ -1755,7 +1755,7 @@ namespace hex::pl {
currPattern = newPattern;
}
} },
index->getValue());
index->getValue());
}
if (currPattern == nullptr)
@ -1810,7 +1810,7 @@ namespace hex::pl {
},
[&](PatternData *assignmentValue) { readVariable(evaluator, value, assignmentValue); },
[&](auto &&assignmentValue) { value = assignmentValue; } },
literal);
literal);
} else {
if constexpr (isString) {
value.resize(variablePattern->getSize());
@ -1893,7 +1893,7 @@ namespace hex::pl {
[[nodiscard]] std::vector<PatternData *> createPatterns(Evaluator *evaluator) const override {
auto &scope = *evaluator->getScope(0).scope;
auto &body = evaluateCondition(evaluator) ? this->m_trueBody : this->m_falseBody;
auto &body = evaluateCondition(evaluator) ? this->m_trueBody : this->m_falseBody;
for (auto &node : body) {
auto newPatterns = node->createPatterns(evaluator);
@ -1912,7 +1912,7 @@ namespace hex::pl {
FunctionResult execute(Evaluator *evaluator) const override {
auto &body = evaluateCondition(evaluator) ? this->m_trueBody : this->m_falseBody;
auto variables = *evaluator->getScope(0).scope;
auto variables = *evaluator->getScope(0).scope;
auto parameterPack = evaluator->getScope(0).parameterPack;
u32 startVariableCount = variables.size();
@ -1948,7 +1948,7 @@ namespace hex::pl {
[](const std::string &value) -> bool { return !value.empty(); },
[this](PatternData *const &) -> bool { LogConsole::abortEvaluation("cannot cast custom type to bool", this); },
[](auto &&value) -> bool { return value != 0; } },
literal->getValue());
literal->getValue());
}
ASTNode *m_condition;
@ -2010,7 +2010,7 @@ namespace hex::pl {
}
auto &customFunctions = evaluator->getCustomFunctions();
auto functions = ContentRegistry::PatternLanguage::getFunctions();
auto functions = ContentRegistry::PatternLanguage::getFunctions();
for (auto &func : customFunctions)
functions.insert(func);
@ -2081,7 +2081,7 @@ namespace hex::pl {
}
ASTNodeTypeOperator(const ASTNodeTypeOperator &other) : ASTNode(other) {
this->m_op = other.m_op;
this->m_op = other.m_op;
this->m_expression = other.m_expression->clone();
}
@ -2106,12 +2106,12 @@ namespace hex::pl {
ON_SCOPE_EXIT { delete pattern; };
switch (this->getOperator()) {
case Token::Operator::AddressOf:
return new ASTNodeLiteral(u128(pattern->getOffset()));
case Token::Operator::SizeOf:
return new ASTNodeLiteral(u128(pattern->getSize()));
default:
LogConsole::abortEvaluation("invalid type operator", this);
case Token::Operator::AddressOf:
return new ASTNodeLiteral(u128(pattern->getOffset()));
case Token::Operator::SizeOf:
return new ASTNodeLiteral(u128(pattern->getSize()));
default:
LogConsole::abortEvaluation("invalid type operator", this);
}
}
@ -2129,7 +2129,7 @@ namespace hex::pl {
ASTNodeAssignment(const ASTNodeAssignment &other) : ASTNode(other) {
this->m_lvalueName = other.m_lvalueName;
this->m_rvalue = other.m_rvalue->clone();
this->m_rvalue = other.m_rvalue->clone();
}
[[nodiscard]] ASTNode *clone() const override {
@ -2231,7 +2231,7 @@ namespace hex::pl {
}
ASTNodeFunctionDefinition(const ASTNodeFunctionDefinition &other) : ASTNode(other) {
this->m_name = other.m_name;
this->m_name = other.m_name;
this->m_params = other.m_params;
for (const auto &[name, type] : other.m_params) {
@ -2304,12 +2304,12 @@ namespace hex::pl {
if (ctx->getCurrentControlFlowStatement() != ControlFlowStatement::None) {
switch (ctx->getCurrentControlFlowStatement()) {
case ControlFlowStatement::Break:
LogConsole::abortEvaluation("break statement not within a loop", statement);
case ControlFlowStatement::Continue:
LogConsole::abortEvaluation("continue statement not within a loop", statement);
default:
break;
case ControlFlowStatement::Break:
LogConsole::abortEvaluation("break statement not within a loop", statement);
case ControlFlowStatement::Continue:
LogConsole::abortEvaluation("continue statement not within a loop", statement);
default:
break;
}
ctx->setCurrentControlFlowStatement(ControlFlowStatement::None);
@ -2379,7 +2379,7 @@ namespace hex::pl {
FunctionResult execute(Evaluator *evaluator) const override {
FunctionResult result;
auto variables = *evaluator->getScope(0).scope;
auto variables = *evaluator->getScope(0).scope;
u32 startVariableCount = variables.size();
if (this->m_newScope) {

View File

@ -12,7 +12,7 @@ namespace hex::pl {
PatternLanguageError(u32 lineNumber, std::string message) : m_lineNumber(lineNumber), m_message(std::move(message)) { }
[[nodiscard]] const char *what() const noexcept override {
return this->m_message.c_str();
return this->m_message.c_str();
}
[[nodiscard]] u32 getLineNumber() const {

View File

@ -258,7 +258,7 @@ namespace hex::pl {
std::map<std::string, Token::Literal> m_inVariables;
std::map<std::string, size_t> m_outVariables;
std::atomic<bool> m_dangerousFunctionCalled = false;
std::atomic<bool> m_dangerousFunctionCalled = false;
std::atomic<DangerousFunctionPermission> m_allowDangerousFunctions = DangerousFunctionPermission::Ask;
ControlFlowStatement m_currControlFlowStatement;

View File

@ -18,7 +18,7 @@ namespace hex::pl {
public:
using TokenIter = std::vector<Token>::const_iterator;
Parser() = default;
Parser() = default;
~Parser() = default;
std::optional<std::vector<ASTNode *>> parse(const std::vector<Token> &tokens);
@ -151,7 +151,7 @@ namespace hex::pl {
enum class Setting { };
constexpr static auto Normal = static_cast<Setting>(0);
constexpr static auto Not = static_cast<Setting>(1);
constexpr static auto Not = static_cast<Setting>(1);
bool begin() {
this->m_originalPosition = this->m_curr;

View File

@ -69,15 +69,16 @@ namespace hex::pl {
getEvaluator()->patternDestroyed();
}
[[nodiscard]]
Evaluator* getEvaluator() const {
[[nodiscard]] Evaluator *getEvaluator() const {
return this->m_evaluator;
}
private:
Evaluator *m_evaluator = nullptr;
};
class PatternData : public PatternCreationLimiter, public Cloneable<PatternData> {
class PatternData : public PatternCreationLimiter,
public Cloneable<PatternData> {
public:
PatternData(Evaluator *evaluator, u64 offset, size_t size, u32 color = 0)
: PatternCreationLimiter(evaluator), m_offset(offset), m_size(size), m_color(color) {
@ -86,7 +87,7 @@ namespace hex::pl {
if (color != 0)
return;
this->m_color = ContentRegistry::PatternLanguage::getNextColor();
this->m_color = ContentRegistry::PatternLanguage::getNextColor();
this->m_manualColor = false;
}
@ -111,7 +112,7 @@ namespace hex::pl {
[[nodiscard]] u32 getColor() const { return this->m_color; }
virtual void setColor(u32 color) {
this->m_color = color;
this->m_color = color;
this->m_manualColor = true;
}
[[nodiscard]] bool hasOverriddenColor() const { return this->m_manualColor; }
@ -131,7 +132,7 @@ namespace hex::pl {
[[nodiscard]] const auto &getFormatterFunction() const { return this->m_formatterFunction; }
void setFormatterFunction(const ContentRegistry::PatternLanguage::Function &function) { this->m_formatterFunction = function; }
virtual void createEntry(prv::Provider *&provider) = 0;
virtual void createEntry(prv::Provider *&provider) = 0;
[[nodiscard]] virtual std::string getFormattedName() const = 0;
[[nodiscard]] virtual const PatternData *getPattern(u64 offset) const {
@ -298,7 +299,7 @@ namespace hex::pl {
bool m_hidden = false;
private:
u64 m_offset = 0x00;
u64 m_offset = 0x00;
size_t m_size = 0x00;
u32 m_color = 0x00;
@ -310,7 +311,7 @@ namespace hex::pl {
std::optional<ContentRegistry::PatternLanguage::Function> m_formatterFunction;
std::optional<ContentRegistry::PatternLanguage::Function> m_transformFunction;
bool m_local = false;
bool m_local = false;
bool m_manualColor = false;
};
@ -318,8 +319,7 @@ namespace hex::pl {
public:
PatternDataPadding(Evaluator *evaluator, u64 offset, size_t size) : PatternData(evaluator, offset, size, 0xFF000000) { }
[[nodiscard]]
PatternData *clone() const override {
[[nodiscard]] PatternData *clone() const override {
return new PatternDataPadding(*this);
}
@ -347,8 +347,7 @@ namespace hex::pl {
delete this->m_pointedAt;
}
[[nodiscard]]
PatternData *clone() const override {
[[nodiscard]] PatternData *clone() const override {
return new PatternDataPointer(*this);
}
@ -387,21 +386,21 @@ namespace hex::pl {
[[nodiscard]] std::string getFormattedName() const override {
std::string result = this->m_pointedAt->getFormattedName() + "* : ";
switch (this->getSize()) {
case 1:
result += "u8";
break;
case 2:
result += "u16";
break;
case 4:
result += "u32";
break;
case 8:
result += "u64";
break;
case 16:
result += "u128";
break;
case 1:
result += "u8";
break;
case 2:
result += "u16";
break;
case 4:
result += "u32";
break;
case 8:
result += "u64";
break;
case 16:
result += "u128";
break;
}
return result;
@ -459,7 +458,7 @@ namespace hex::pl {
private:
PatternData *m_pointedAt = nullptr;
u64 m_pointedAtAddress = 0;
u64 m_pointedAtAddress = 0;
u64 m_pointerBase = 0;
};
@ -469,8 +468,7 @@ namespace hex::pl {
PatternDataUnsigned(Evaluator *evaluator, u64 offset, size_t size, u32 color = 0)
: PatternData(evaluator, offset, size, color) { }
[[nodiscard]]
PatternData *clone() const override {
[[nodiscard]] PatternData *clone() const override {
return new PatternDataUnsigned(*this);
}
@ -484,18 +482,18 @@ namespace hex::pl {
[[nodiscard]] std::string getFormattedName() const override {
switch (this->getSize()) {
case 1:
return "u8";
case 2:
return "u16";
case 4:
return "u32";
case 8:
return "u64";
case 16:
return "u128";
default:
return "Unsigned data";
case 1:
return "u8";
case 2:
return "u16";
case 4:
return "u32";
case 8:
return "u64";
case 16:
return "u128";
default:
return "Unsigned data";
}
}
@ -507,8 +505,7 @@ namespace hex::pl {
PatternDataSigned(Evaluator *evaluator, u64 offset, size_t size, u32 color = 0)
: PatternData(evaluator, offset, size, color) { }
[[nodiscard]]
PatternData *clone() const override {
[[nodiscard]] PatternData *clone() const override {
return new PatternDataSigned(*this);
}
@ -523,18 +520,18 @@ namespace hex::pl {
[[nodiscard]] std::string getFormattedName() const override {
switch (this->getSize()) {
case 1:
return "s8";
case 2:
return "s16";
case 4:
return "s32";
case 8:
return "s64";
case 16:
return "s128";
default:
return "Signed data";
case 1:
return "s8";
case 2:
return "s16";
case 4:
return "s32";
case 8:
return "s64";
case 16:
return "s128";
default:
return "Signed data";
}
}
@ -546,8 +543,7 @@ namespace hex::pl {
PatternDataFloat(Evaluator *evaluator, u64 offset, size_t size, u32 color = 0)
: PatternData(evaluator, offset, size, color) { }
[[nodiscard]]
PatternData *clone() const override {
[[nodiscard]] PatternData *clone() const override {
return new PatternDataFloat(*this);
}
@ -569,12 +565,12 @@ namespace hex::pl {
[[nodiscard]] std::string getFormattedName() const override {
switch (this->getSize()) {
case 4:
return "float";
case 8:
return "double";
default:
return "Floating point data";
case 4:
return "float";
case 8:
return "double";
default:
return "Floating point data";
}
}
@ -586,8 +582,7 @@ namespace hex::pl {
explicit PatternDataBoolean(Evaluator *evaluator, u64 offset, u32 color = 0)
: PatternData(evaluator, offset, 1, color) { }
[[nodiscard]]
PatternData *clone() const override {
[[nodiscard]] PatternData *clone() const override {
return new PatternDataBoolean(*this);
}
@ -615,8 +610,7 @@ namespace hex::pl {
explicit PatternDataCharacter(Evaluator *evaluator, u64 offset, u32 color = 0)
: PatternData(evaluator, offset, 1, color) { }
[[nodiscard]]
PatternData *clone() const override {
[[nodiscard]] PatternData *clone() const override {
return new PatternDataCharacter(*this);
}
@ -639,8 +633,7 @@ namespace hex::pl {
explicit PatternDataCharacter16(Evaluator *evaluator, u64 offset, u32 color = 0)
: PatternData(evaluator, offset, 2, color) { }
[[nodiscard]]
PatternData *clone() const override {
[[nodiscard]] PatternData *clone() const override {
return new PatternDataCharacter16(*this);
}
@ -673,8 +666,7 @@ namespace hex::pl {
PatternDataString(Evaluator *evaluator, u64 offset, size_t size, u32 color = 0)
: PatternData(evaluator, offset, size, color) { }
[[nodiscard]]
PatternData *clone() const override {
[[nodiscard]] PatternData *clone() const override {
return new PatternDataString(*this);
}
@ -714,8 +706,7 @@ namespace hex::pl {
PatternDataString16(Evaluator *evaluator, u64 offset, size_t size, u32 color = 0)
: PatternData(evaluator, offset, size, color) { }
[[nodiscard]]
PatternData *clone() const override {
[[nodiscard]] PatternData *clone() const override {
return new PatternDataString16(*this);
}
@ -731,9 +722,10 @@ namespace hex::pl {
for (auto &c : buffer)
c = hex::changeEndianess(c, 2, this->getEndian());
buffer.erase(std::remove_if(buffer.begin(), buffer.end(), [](auto c){
buffer.erase(std::remove_if(buffer.begin(), buffer.end(), [](auto c) {
return c == 0x00;
}), buffer.end());
}),
buffer.end());
auto utf8String = std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> {}.to_bytes(buffer);
@ -781,8 +773,7 @@ namespace hex::pl {
delete entry;
}
[[nodiscard]]
PatternData *clone() const override {
[[nodiscard]] PatternData *clone() const override {
return new PatternDataDynamicArray(*this);
}
@ -934,8 +925,7 @@ namespace hex::pl {
delete this->m_highlightTemplate;
}
[[nodiscard]]
PatternData *clone() const override {
[[nodiscard]] PatternData *clone() const override {
return new PatternDataStaticArray(*this);
}
@ -1036,9 +1026,9 @@ namespace hex::pl {
}
void setEntries(PatternData *templ, size_t count) {
this->m_template = templ;
this->m_template = templ;
this->m_highlightTemplate = this->m_template->clone();
this->m_entryCount = count;
this->m_entryCount = count;
if (this->hasOverriddenColor()) this->setColor(this->m_template->getColor());
this->m_template->setEndian(templ->getEndian());
@ -1070,10 +1060,10 @@ namespace hex::pl {
}
private:
PatternData *m_template = nullptr;
PatternData *m_template = nullptr;
mutable PatternData *m_highlightTemplate = nullptr;
size_t m_entryCount = 0;
u64 m_displayEnd = 50;
size_t m_entryCount = 0;
u64 m_displayEnd = 50;
};
class PatternDataStruct : public PatternData,
@ -1094,8 +1084,7 @@ namespace hex::pl {
delete member;
}
[[nodiscard]]
PatternData *clone() const override {
[[nodiscard]] PatternData *clone() const override {
return new PatternDataStruct(*this);
}
@ -1242,8 +1231,7 @@ namespace hex::pl {
delete member;
}
[[nodiscard]]
PatternData *clone() const override {
[[nodiscard]] PatternData *clone() const override {
return new PatternDataUnion(*this);
}
@ -1380,8 +1368,7 @@ namespace hex::pl {
: PatternData(evaluator, offset, size, color) {
}
[[nodiscard]]
PatternData *clone() const override {
[[nodiscard]] PatternData *clone() const override {
return new PatternDataEnum(*this);
}
@ -1404,9 +1391,9 @@ namespace hex::pl {
return false;
},
[](std::string&) { return false; },
[](std::string &) { return false; },
[](PatternData *) { return false; } },
entryValueLiteral);
entryValueLiteral);
if (matches)
break;
}
@ -1476,8 +1463,7 @@ namespace hex::pl {
: PatternData(evaluator, offset, 0, color), m_bitOffset(bitOffset), m_bitSize(bitSize), m_bitField(bitField) {
}
[[nodiscard]]
PatternData *clone() const override {
[[nodiscard]] PatternData *clone() const override {
return new PatternDataBitfieldField(*this);
}
@ -1556,8 +1542,7 @@ namespace hex::pl {
delete field;
}
[[nodiscard]]
PatternData *clone() const override {
[[nodiscard]] PatternData *clone() const override {
return new PatternDataBitfield(*this);
}

View File

@ -49,7 +49,7 @@ namespace hex::pl {
[[nodiscard]] bool hasDangerousFunctionBeenCalled() const;
void allowDangerousFunctions(bool allow);
[[nodiscard]] std::vector<PatternData*> &getPatterns() {
[[nodiscard]] std::vector<PatternData *> &getPatterns() {
return this->m_patterns;
}
@ -67,7 +67,7 @@ namespace hex::pl {
std::optional<PatternLanguageError> m_currError;
std::vector<PatternData*> m_patterns;
std::vector<PatternData *> m_patterns;
bool m_running = false;
};

View File

@ -81,31 +81,31 @@ namespace hex::pl {
};
enum class ValueType {
Unsigned8Bit = 0x10,
Signed8Bit = 0x11,
Unsigned16Bit = 0x20,
Signed16Bit = 0x21,
Unsigned32Bit = 0x40,
Signed32Bit = 0x41,
Unsigned64Bit = 0x80,
Signed64Bit = 0x81,
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,
Signed128Bit = 0x101,
Character = 0x13,
Character16 = 0x23,
Boolean = 0x14,
Float = 0x42,
Double = 0x82,
String = 0x15,
Auto = 0x16,
CustomType = 0x00,
Padding = 0x1F,
Unsigned = 0xFF00,
Signed = 0xFF01,
Unsigned = 0xFF00,
Signed = 0xFF01,
FloatingPoint = 0xFF02,
Integer = 0xFF03,
Any = 0xFFFF
Integer = 0xFF03,
Any = 0xFFFF
};
enum class Separator {
@ -127,13 +127,13 @@ namespace hex::pl {
[[nodiscard]] const std::string &get() const { return this->m_identifier; }
auto operator<=>(const Identifier &) const = default;
bool 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) {
@ -160,7 +160,7 @@ namespace hex::pl {
[](const std::string &) -> u128 { LogConsole::abortEvaluation("expected integral type, got string"); },
[](PatternData *) -> u128 { LogConsole::abortEvaluation("expected integral type, got custom type"); },
[](auto &&result) -> u128 { return result; } },
literal);
literal);
}
static i128 literalToSigned(const pl::Token::Literal &literal) {
@ -168,7 +168,7 @@ namespace hex::pl {
[](const std::string &) -> i128 { LogConsole::abortEvaluation("expected integral type, got string"); },
[](PatternData *) -> i128 { LogConsole::abortEvaluation("expected integral type, got custom type"); },
[](auto &&result) -> i128 { return result; } },
literal);
literal);
}
static double literalToFloatingPoint(const pl::Token::Literal &literal) {
@ -176,7 +176,7 @@ namespace hex::pl {
[](const std::string &) -> double { LogConsole::abortEvaluation("expected integral type, got string"); },
[](PatternData *) -> double { LogConsole::abortEvaluation("expected integral type, got custom type"); },
[](auto &&result) -> double { return result; } },
literal);
literal);
}
static bool literalToBoolean(const pl::Token::Literal &literal) {
@ -184,7 +184,7 @@ namespace hex::pl {
[](const std::string &) -> bool { LogConsole::abortEvaluation("expected integral type, got string"); },
[](PatternData *) -> bool { LogConsole::abortEvaluation("expected integral type, got custom type"); },
[](auto &&result) -> bool { return result != 0; } },
literal);
literal);
}
static std::string literalToString(const pl::Token::Literal &literal, bool cast) {
@ -199,45 +199,45 @@ namespace hex::pl {
[](char result) -> std::string { return { 1, result }; },
[](PatternData *) -> std::string { LogConsole::abortEvaluation("expected integral type, got custom type"); },
[](auto &&result) -> std::string { return std::to_string(result); } },
literal);
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 "< ??? >";
}
}
@ -246,7 +246,7 @@ namespace hex::pl {
return true;
else if (this->type == Type::ValueType) {
auto otherValueType = std::get_if<ValueType>(&other);
auto valueType = std::get_if<ValueType>(&this->value);
auto valueType = std::get_if<ValueType>(&this->value);
if (otherValueType == nullptr) return false;
if (valueType == nullptr) return false;

View File

@ -21,10 +21,10 @@ namespace hex::prv {
virtual ~Provider();
[[nodiscard]] virtual bool isAvailable() const = 0;
[[nodiscard]] virtual bool isReadable() const = 0;
[[nodiscard]] virtual bool isWritable() const = 0;
[[nodiscard]] virtual bool isReadable() const = 0;
[[nodiscard]] virtual bool isWritable() const = 0;
[[nodiscard]] virtual bool isResizable() const = 0;
[[nodiscard]] virtual bool isSavable() const = 0;
[[nodiscard]] virtual bool isSavable() const = 0;
virtual void read(u64 offset, void *buffer, size_t size, bool overlays = true);
virtual void write(u64 offset, const void *buffer, size_t size);
@ -35,9 +35,9 @@ namespace hex::prv {
virtual void save();
virtual void saveAs(const fs::path &path);
virtual void readRaw(u64 offset, void *buffer, size_t size) = 0;
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);
@ -59,11 +59,11 @@ namespace hex::prv {
[[nodiscard]] virtual size_t getSize() const;
[[nodiscard]] virtual std::optional<u32> getPageOfAddress(u64 address) const;
[[nodiscard]] virtual std::string getName() const = 0;
[[nodiscard]] virtual std::string getName() const = 0;
[[nodiscard]] virtual std::vector<std::pair<std::string, std::string>> getDataInformation() const = 0;
[[nodiscard]] virtual bool open() = 0;
virtual void close() = 0;
virtual void close() = 0;
void addPatch(u64 offset, const void *buffer, size_t size, bool createUndo = false);
void createUndoPoint();
@ -79,11 +79,11 @@ namespace hex::prv {
virtual void drawLoadInterface();
virtual void drawInterface();
pl::PatternLanguage& getPatternLanguageRuntime() { return this->m_patternLanguageRuntime; }
std::string& getPatternLanguageSourceCode() { return this->m_patternLanguageSourceCode; }
pl::PatternLanguage &getPatternLanguageRuntime() { return this->m_patternLanguageRuntime; }
std::string &getPatternLanguageSourceCode() { return this->m_patternLanguageSourceCode; }
protected:
u32 m_currPage = 0;
u32 m_currPage = 0;
u64 m_baseAddress = 0;
u32 m_patchTreeOffset = 0;

View File

@ -219,10 +219,8 @@ namespace hex {
}
void ContentRegistry::PatternLanguage::addColorPalette(const std::string &unlocalizedName, const std::vector<u32> &colors) {
s_colorPalettes.push_back({
unlocalizedName,
colors
});
s_colorPalettes.push_back({ unlocalizedName,
colors });
}
void ContentRegistry::PatternLanguage::setSelectedPalette(u32 index) {

View File

@ -29,13 +29,15 @@ namespace hex {
static std::map<u32, ImHexApi::HexEditor::Highlighting> s_highlights;
Highlighting::Highlighting(Region region, color_t color, const std::string &tooltip)
: m_region(region), m_color(color), m_tooltip(tooltip) {
: m_region(region), m_color(color), m_tooltip(tooltip) {
}
u32 addHighlight(const Region &region, color_t color, std::string tooltip) {
auto id = s_highlights.size();
s_highlights.insert({ id, Highlighting{ region, color, tooltip } });
s_highlights.insert({
id, Highlighting {region, color, tooltip}
});
return id;
}
@ -67,7 +69,7 @@ namespace hex {
namespace ImHexApi::Provider {
static u32 s_currentProvider;
static std::vector<prv::Provider*> s_providers;
static std::vector<prv::Provider *> s_providers;
prv::Provider *get() {
if (!ImHexApi::Provider::isValid())
@ -82,7 +84,7 @@ namespace hex {
void setCurrentProvider(u32 index) {
if (index < s_providers.size()) {
auto oldProvider = get();
auto oldProvider = get();
s_currentProvider = index;
EventManager::post<EventProviderChanged>(oldProvider, get());
}
@ -126,7 +128,7 @@ namespace hex {
getDeferredCalls().push_back(function);
}
std::vector<std::function<void()>>& getDeferredCalls() {
std::vector<std::function<void()>> &getDeferredCalls() {
return s_deferredCalls;
}
@ -169,8 +171,7 @@ namespace hex {
}
const ProgramArguments& getProgramArguments() {
const ProgramArguments &getProgramArguments() {
return impl::s_programArguments;
}
@ -203,7 +204,7 @@ namespace hex {
return impl::s_mainDockSpaceId;
}
std::map<std::string, std::string>& getInitArguments() {
std::map<std::string, std::string> &getInitArguments() {
static std::map<std::string, std::string> initArgs;
return initArgs;

View File

@ -17,35 +17,35 @@ 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_isBuiltinPluginFunction = getPluginFunction<IsBuiltinPluginFunc>("isBuiltinPlugin");
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_isBuiltinPluginFunction = getPluginFunction<IsBuiltinPluginFunc>("isBuiltinPlugin");
}
Plugin::Plugin(Plugin &&other) noexcept {
this->m_handle = other.m_handle;
this->m_path = std::move(other.m_path);
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_isBuiltinPluginFunction = other.m_isBuiltinPluginFunction;
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_isBuiltinPluginFunction = other.m_isBuiltinPluginFunction;
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_isBuiltinPluginFunction = nullptr;
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_isBuiltinPluginFunction = nullptr;
}
Plugin::~Plugin() {

View File

@ -95,7 +95,7 @@ namespace hex::crypt {
m_refin(refin),
m_refout(refout),
table([polynomial, bits]() {
auto reflectedpoly = reflect(polynomial & ((0b10ull << (bits - 1)) - 1), 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++) {
@ -452,47 +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,11 +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;
@ -45,7 +45,7 @@ namespace hex {
continue;
from = line.substr(0, delimiterPos);
to = line.substr(delimiterPos + 1);
to = line.substr(delimiterPos + 1);
hex::trim(from);
hex::trim(to);

View File

@ -50,7 +50,7 @@ namespace hex {
u64 address;
size_t size;
char *name = nullptr;
char *name = nullptr;
char *comment = nullptr;
if (!PyArg_ParseTuple(args, "K|n|s|s", &address, &size, &name, &comment)) {
@ -213,7 +213,7 @@ namespace hex {
{
auto sysPath = PySys_GetObject("path");
auto path = PyUnicode_FromString("lib");
auto path = PyUnicode_FromString("lib");
PyList_Insert(sysPath, 0, path);
}

View File

@ -110,12 +110,12 @@ namespace hex {
curl_easy_setopt(this->m_ctx, CURLOPT_NOSIGNAL, 1L);
curl_easy_setopt(this->m_ctx, CURLOPT_NOPROGRESS, 0L);
#if defined(OS_WINDOWS)
curl_easy_setopt(this->m_ctx, CURLOPT_CAINFO, nullptr);
curl_easy_setopt(this->m_ctx, CURLOPT_CAPATH, nullptr);
curl_easy_setopt(this->m_ctx, CURLOPT_SSLCERTTYPE, "PEM");
curl_easy_setopt(this->m_ctx, CURLOPT_SSL_CTX_FUNCTION, sslCtxFunction);
#endif
#if defined(OS_WINDOWS)
curl_easy_setopt(this->m_ctx, CURLOPT_CAINFO, nullptr);
curl_easy_setopt(this->m_ctx, CURLOPT_CAPATH, nullptr);
curl_easy_setopt(this->m_ctx, CURLOPT_SSLCERTTYPE, "PEM");
curl_easy_setopt(this->m_ctx, CURLOPT_SSL_CTX_FUNCTION, sslCtxFunction);
#endif
}
std::optional<i32> Net::execute() {
@ -127,8 +127,8 @@ namespace hex {
curl_easy_getinfo(this->m_ctx, CURLINFO_RESPONSE_CODE, &responseCode);
curl_slist_free_all(this->m_headers);
this->m_headers = nullptr;
this->m_progress = 0.0F;
this->m_headers = nullptr;
this->m_progress = 0.0F;
this->m_shouldCancel = false;
if (result != CURLE_OK)
@ -183,7 +183,7 @@ namespace hex {
if (!file.isValid())
return Response<std::string> { 400, {} };
curl_mime *mime = curl_mime_init(this->m_ctx);
curl_mime *mime = curl_mime_init(this->m_ctx);
curl_mimepart *part = curl_mime_addpart(mime);
auto fileName = filePath.filename().string();

View File

@ -45,7 +45,7 @@ namespace hex {
if (bytes.size() > 0xFFFF || startAddress > 0xFF'FFFF)
return {};
u32 address = startAddress.value();
u32 address = startAddress.value();
auto addressBytes = reinterpret_cast<u8 *>(&address);
result.push_back(addressBytes[2]);
@ -93,7 +93,7 @@ namespace hex {
if (bytes.size() > 0xFFFF || startAddress > 0xFFFF'FFFF)
return {};
u32 address = startAddress.value();
u32 address = startAddress.value();
auto addressBytes = reinterpret_cast<u8 *>(&address);
result.push_back(addressBytes[3]);
@ -128,7 +128,7 @@ namespace hex {
u32 ipsOffset = 5;
while (ipsOffset < ipsPatch.size() - (5 + 3)) {
u32 offset = ipsPatch[ipsOffset + 2] | (ipsPatch[ipsOffset + 1] << 8) | (ipsPatch[ipsOffset + 0] << 16);
u16 size = ipsPatch[ipsOffset + 4] | (ipsPatch[ipsOffset + 3] << 8);
u16 size = ipsPatch[ipsOffset + 4] | (ipsPatch[ipsOffset + 3] << 8);
ipsOffset += 5;
@ -179,7 +179,7 @@ namespace hex {
u32 ipsOffset = 5;
while (ipsOffset < ipsPatch.size() - (5 + 4)) {
u32 offset = ipsPatch[ipsOffset + 3] | (ipsPatch[ipsOffset + 2] << 8) | (ipsPatch[ipsOffset + 1] << 16) | (ipsPatch[ipsOffset + 0] << 24);
u16 size = ipsPatch[ipsOffset + 5] | (ipsPatch[ipsOffset + 4] << 8);
u16 size = ipsPatch[ipsOffset + 5] | (ipsPatch[ipsOffset + 4] << 8);
ipsOffset += 6;

View File

@ -40,7 +40,7 @@ namespace hex {
std::vector<fs::path> result;
#if defined(OS_WINDOWS)
const auto exePath = getExecutablePath();
const auto exePath = getExecutablePath();
const auto parentDir = fs::path(exePath).parent_path();
fs::path appDataDir;
@ -56,60 +56,60 @@ namespace hex {
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();
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
@ -119,47 +119,47 @@ namespace hex {
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();
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();
std::vector<fs::path> dataDirs = xdg::DataDirs();
configDirs.insert(configDirs.begin(), xdg::ConfigHomeDir());
dataDirs.insert(dataDirs.begin(), xdg::DataHomeDir());
@ -173,49 +173,49 @@ namespace hex {
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();
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());
return !fs::is_directory(path);
}),
result.end());
}
return result;

View File

@ -55,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();
@ -89,9 +89,9 @@ namespace hex {
filePath = ProjectFile::s_currProjectFilePath;
try {
projectFileData["filePath"] = ProjectFile::s_filePath;
projectFileData["pattern"] = ProjectFile::s_pattern;
projectFileData["patches"] = ProjectFile::s_patches;
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) {
@ -106,7 +106,7 @@ namespace hex {
return false;
}
ProjectFile::s_hasUnsavedChanged = false;
ProjectFile::s_hasUnsavedChanged = false;
ProjectFile::s_currProjectFilePath = filePath;
return true;

View File

@ -21,7 +21,7 @@ namespace hex {
}
Socket::Socket(Socket &&other) {
this->m_socket = other.m_socket;
this->m_socket = other.m_socket;
this->m_connected = other.m_connected;
other.m_socket = SOCKET_NONE;
@ -78,7 +78,7 @@ namespace hex {
sockaddr_in client = { 0 };
client.sin_family = AF_INET;
client.sin_port = htons(port);
client.sin_port = htons(port);
#if defined(OS_WINDOWS)
client.sin_addr.S_un.S_addr = ::inet_addr(address.c_str());

View File

@ -83,29 +83,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;
@ -113,78 +113,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);
}
}
@ -268,17 +268,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) {
@ -290,7 +290,7 @@ namespace hex {
}
float float16ToFloat32(u16 float16) {
u32 sign = float16 >> 15;
u32 sign = float16 >> 15;
u32 exponent = (float16 >> 10) & 0x1F;
u32 mantissa = float16 & 0x3FF;
@ -326,7 +326,7 @@ namespace hex {
bool isProcessElevated() {
#if defined(OS_WINDOWS)
bool elevated = false;
HANDLE token = INVALID_HANDLE_VALUE;
HANDLE token = INVALID_HANDLE_VALUE;
if (::OpenProcessToken(::GetCurrentProcess(), TOKEN_QUERY, &token)) {
TOKEN_ELEVATION elevation;

View File

@ -19,8 +19,8 @@ namespace hex::pl {
}
}
auto startOffset = this->dataOffset();
auto pattern = type == nullptr ? nullptr : type->createPatterns(this).front();
auto startOffset = this->dataOffset();
auto pattern = type == nullptr ? nullptr : type->createPatterns(this).front();
this->dataOffset() = startOffset;
if (pattern == nullptr) {
@ -123,7 +123,7 @@ namespace hex::pl {
else
LogConsole::abortEvaluation(hex::format("cannot cast integer literal to type '{}'", pattern->getTypeName()));
} },
value);
value);
this->getStack()[pattern->getOffset()] = castedLiteral;
}
@ -143,7 +143,7 @@ namespace hex::pl {
this->m_envVariables.clear();
};
this->dataOffset() = 0x00;
this->dataOffset() = 0x00;
this->m_currPatternCount = 0;
for (auto &func : this->m_customFunctionDefinitions)

View File

@ -38,7 +38,7 @@ namespace hex::pl {
u8 base;
auto endPos = getIntegerLiteralLength(string);
auto endPos = getIntegerLiteralLength(string);
auto numberData = std::string_view(string).substr(0, endPos);
if (numberData.ends_with('U')) {
@ -56,7 +56,7 @@ namespace hex::pl {
if (numberData.starts_with("0x")) {
numberData = numberData.substr(2);
base = 16;
base = 16;
if (Token::isFloatingPoint(type))
return std::nullopt;
@ -65,7 +65,7 @@ namespace hex::pl {
return std::nullopt;
} else if (numberData.starts_with("0b")) {
numberData = numberData.substr(2);
base = 2;
base = 2;
if (Token::isFloatingPoint(type))
return std::nullopt;
@ -111,23 +111,23 @@ namespace hex::pl {
}
switch (type) {
case Token::ValueType::Unsigned128Bit:
return { u128(integer) };
case Token::ValueType::Signed128Bit:
return { i128(integer) };
default:
return std::nullopt;
case Token::ValueType::Unsigned128Bit:
return { u128(integer) };
case Token::ValueType::Signed128Bit:
return { i128(integer) };
default:
return std::nullopt;
}
} 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 std::nullopt;
case Token::ValueType::Float:
return { float(floatingPoint) };
case Token::ValueType::Double:
return { double(floatingPoint) };
default:
return std::nullopt;
}
}
@ -147,46 +147,46 @@ namespace hex::pl {
// 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

View File

@ -133,7 +133,7 @@ namespace hex::pl {
auto originalPos = this->m_curr;
parseNamespaceResolution();
bool isFunction = peek(SEPARATOR_ROUNDBRACKETOPEN);
this->m_curr = originalPos;
this->m_curr = originalPos;
if (isFunction) {
@ -174,7 +174,7 @@ namespace hex::pl {
ASTNode *Parser::parseCastExpression() {
if (peek(KEYWORD_BE) || peek(KEYWORD_LE) || peek(VALUETYPE_ANY)) {
auto type = parseType(true);
auto type = parseType(true);
auto builtinType = dynamic_cast<ASTNodeBuiltinType *>(type->getType());
if (builtinType == nullptr)
@ -210,7 +210,7 @@ namespace hex::pl {
while (MATCHES(oneOf(OPERATOR_STAR, OPERATOR_SLASH, OPERATOR_PERCENT))) {
auto op = getValue<Token::Operator>(-1);
node = create(new ASTNodeMathematicalExpression(node, this->parseUnaryExpression(), op));
node = create(new ASTNodeMathematicalExpression(node, this->parseUnaryExpression(), op));
}
nodeCleanup.release();
@ -226,7 +226,7 @@ namespace hex::pl {
while (MATCHES(variant(OPERATOR_PLUS, OPERATOR_MINUS))) {
auto op = getValue<Token::Operator>(-1);
node = create(new ASTNodeMathematicalExpression(node, this->parseMultiplicativeExpression(), op));
node = create(new ASTNodeMathematicalExpression(node, this->parseMultiplicativeExpression(), op));
}
nodeCleanup.release();
@ -242,7 +242,7 @@ namespace hex::pl {
while (MATCHES(variant(OPERATOR_SHIFTLEFT, OPERATOR_SHIFTRIGHT))) {
auto op = getValue<Token::Operator>(-1);
node = create(new ASTNodeMathematicalExpression(node, this->parseAdditiveExpression(), op));
node = create(new ASTNodeMathematicalExpression(node, this->parseAdditiveExpression(), op));
}
nodeCleanup.release();
@ -258,7 +258,7 @@ namespace hex::pl {
while (MATCHES(sequence(OPERATOR_BOOLGREATERTHAN) || sequence(OPERATOR_BOOLLESSTHAN) || sequence(OPERATOR_BOOLGREATERTHANOREQUALS) || sequence(OPERATOR_BOOLLESSTHANOREQUALS))) {
auto op = getValue<Token::Operator>(-1);
node = create(new ASTNodeMathematicalExpression(node, this->parseShiftExpression(), op));
node = create(new ASTNodeMathematicalExpression(node, this->parseShiftExpression(), op));
}
nodeCleanup.release();
@ -274,7 +274,7 @@ namespace hex::pl {
while (MATCHES(sequence(OPERATOR_BOOLEQUALS) || sequence(OPERATOR_BOOLNOTEQUALS))) {
auto op = getValue<Token::Operator>(-1);
node = create(new ASTNodeMathematicalExpression(node, this->parseRelationExpression(), op));
node = create(new ASTNodeMathematicalExpression(node, this->parseRelationExpression(), op));
}
nodeCleanup.release();
@ -385,7 +385,7 @@ namespace hex::pl {
throwParserError("expected ':' in ternary expression");
auto third = this->parseBooleanOr();
node = create(new ASTNodeTernaryExpression(node, second, third, Token::Operator::TernaryConditional));
node = create(new ASTNodeTernaryExpression(node, second, third, Token::Operator::TernaryConditional));
}
nodeCleanup.release();
@ -410,7 +410,7 @@ namespace hex::pl {
auto attribute = getValue<Token::Identifier>(-1).get();
if (MATCHES(sequence(SEPARATOR_ROUNDBRACKETOPEN, STRING, SEPARATOR_ROUNDBRACKETCLOSE))) {
auto value = getValue<Token::Literal>(-2);
auto value = getValue<Token::Literal>(-2);
auto string = std::get_if<std::string>(&value);
if (string == nullptr)
@ -434,7 +434,7 @@ namespace hex::pl {
std::optional<std::string> parameterPack;
// Parse parameter list
bool hasParams = !peek(SEPARATOR_ROUNDBRACKETCLOSE);
bool hasParams = !peek(SEPARATOR_ROUNDBRACKETCLOSE);
u32 unnamedParamCount = 0;
while (hasParams) {
if (MATCHES(sequence(VALUETYPE_AUTO, SEPARATOR_DOT, SEPARATOR_DOT, SEPARATOR_DOT, IDENTIFIER))) {
@ -488,7 +488,7 @@ namespace hex::pl {
if (MATCHES(sequence(IDENTIFIER))) {
auto identifier = getValue<Token::Identifier>(-1).get();
statement = parseMemberVariable(type);
statement = parseMemberVariable(type);
if (MATCHES(sequence(OPERATOR_ASSIGNMENT))) {
auto expression = parseMathematicalExpression();
@ -516,13 +516,13 @@ namespace hex::pl {
else if (MATCHES(oneOf(KEYWORD_RETURN, KEYWORD_BREAK, KEYWORD_CONTINUE)))
statement = parseFunctionControlFlowStatement();
else if (MATCHES(sequence(KEYWORD_IF, SEPARATOR_ROUNDBRACKETOPEN))) {
statement = parseFunctionConditional();
statement = parseFunctionConditional();
needsSemicolon = false;
} else if (MATCHES(sequence(KEYWORD_WHILE, SEPARATOR_ROUNDBRACKETOPEN))) {
statement = parseFunctionWhileLoop();
statement = parseFunctionWhileLoop();
needsSemicolon = false;
} else if (MATCHES(sequence(KEYWORD_FOR, SEPARATOR_ROUNDBRACKETOPEN))) {
statement = parseFunctionForLoop();
statement = parseFunctionForLoop();
needsSemicolon = false;
} else if (MATCHES(sequence(IDENTIFIER))) {
auto originalPos = this->m_curr;
@ -531,10 +531,10 @@ namespace hex::pl {
if (isFunction) {
this->m_curr = originalPos;
statement = parseFunctionCall();
statement = parseFunctionCall();
} else {
this->m_curr = originalPos - 1;
statement = parseFunctionVariableDecl();
statement = parseFunctionVariableDecl();
}
} else if (peek(KEYWORD_BE) || peek(KEYWORD_LE) || peek(VALUETYPE_ANY)) {
statement = parseFunctionVariableDecl();
@ -651,13 +651,13 @@ namespace hex::pl {
}
ASTNode *Parser::parseFunctionForLoop() {
auto variable = parseFunctionVariableDecl();
auto variable = parseFunctionVariableDecl();
auto variableCleanup = SCOPE_GUARD { delete variable; };
if (!MATCHES(sequence(SEPARATOR_COMMA)))
throwParserError("expected ',' after for loop variable declaration");
auto condition = parseMathematicalExpression();
auto condition = parseMathematicalExpression();
auto conditionCleanup = SCOPE_GUARD { delete condition; };
if (!MATCHES(sequence(SEPARATOR_COMMA)))
@ -833,7 +833,7 @@ namespace hex::pl {
ASTNode *Parser::parseMemberArrayVariable(ASTNodeTypeDecl *type) {
auto name = getValue<Token::Identifier>(-2).get();
ASTNode *size = nullptr;
ASTNode *size = nullptr;
auto sizeCleanup = SCOPE_GUARD { delete size; };
if (!MATCHES(sequence(SEPARATOR_SQUAREBRACKETCLOSE))) {
@ -881,7 +881,7 @@ namespace hex::pl {
auto originalPos = this->m_curr;
this->m_curr++;
parseNamespaceResolution();
isFunction = peek(SEPARATOR_ROUNDBRACKETOPEN);
isFunction = peek(SEPARATOR_ROUNDBRACKETOPEN);
this->m_curr = originalPos;
if (isFunction) {
@ -938,8 +938,8 @@ namespace hex::pl {
const auto &typeName = getValue<Token::Identifier>(-1).get();
const auto structNode = create(new ASTNodeStruct());
const auto typeDecl = addType(typeName, structNode);
auto structGuard = SCOPE_GUARD {
const auto typeDecl = addType(typeName, structNode);
auto structGuard = SCOPE_GUARD {
delete structNode;
delete typeDecl;
};
@ -976,8 +976,8 @@ namespace hex::pl {
const auto &typeName = getValue<Token::Identifier>(-2).get();
const auto unionNode = create(new ASTNodeUnion());
const auto typeDecl = addType(typeName, unionNode);
auto unionGuard = SCOPE_GUARD {
const auto typeDecl = addType(typeName, unionNode);
auto unionGuard = SCOPE_GUARD {
delete unionNode;
delete typeDecl;
};
@ -1000,7 +1000,7 @@ namespace hex::pl {
const auto enumNode = create(new ASTNodeEnum(underlyingType));
const auto typeDecl = addType(typeName, enumNode);
auto enumGuard = SCOPE_GUARD {
auto enumGuard = SCOPE_GUARD {
delete enumNode;
delete typeDecl;
};
@ -1011,7 +1011,7 @@ namespace hex::pl {
ASTNode *lastEntry = nullptr;
while (!MATCHES(sequence(SEPARATOR_CURLYBRACKETCLOSE))) {
if (MATCHES(sequence(IDENTIFIER, OPERATOR_ASSIGNMENT))) {
auto name = getValue<Token::Identifier>(-2).get();
auto name = getValue<Token::Identifier>(-2).get();
auto value = parseMathematicalExpression();
enumNode->addEntry(name, value);
@ -1048,7 +1048,7 @@ namespace hex::pl {
std::string typeName = getValue<Token::Identifier>(-2).get();
const auto bitfieldNode = create(new ASTNodeBitfield());
const auto typeDecl = addType(typeName, bitfieldNode);
const auto typeDecl = addType(typeName, bitfieldNode);
auto enumGuard = SCOPE_GUARD {
delete bitfieldNode;
@ -1081,7 +1081,7 @@ namespace hex::pl {
// (parseType) Identifier @ Integer
ASTNode *Parser::parseVariablePlacement(ASTNodeTypeDecl *type) {
bool inVariable = false;
bool inVariable = false;
bool outVariable = false;
auto name = getValue<Token::Identifier>(-1).get();
@ -1102,7 +1102,7 @@ namespace hex::pl {
ASTNode *Parser::parseArrayVariablePlacement(ASTNodeTypeDecl *type) {
auto name = getValue<Token::Identifier>(-2).get();
ASTNode *size = nullptr;
ASTNode *size = nullptr;
auto sizeCleanup = SCOPE_GUARD { delete size; };
if (!MATCHES(sequence(SEPARATOR_SQUAREBRACKETCLOSE))) {
@ -1129,7 +1129,7 @@ namespace hex::pl {
ASTNode *Parser::parsePointerVariablePlacement(ASTNodeTypeDecl *type) {
auto name = getValue<Token::Identifier>(-2).get();
auto sizeType = parseType();
auto sizeType = parseType();
auto sizeCleanup = SCOPE_GUARD { delete sizeType; };
{
@ -1196,7 +1196,7 @@ namespace hex::pl {
// <(parseUsingDeclaration)|(parseVariablePlacement)|(parseStruct)>
std::vector<ASTNode *> Parser::parseStatements() {
ASTNode *statement = nullptr;
ASTNode *statement = nullptr;
auto statementGuard = SCOPE_GUARD {
delete statement;
};
@ -1208,7 +1208,7 @@ namespace hex::pl {
this->m_curr++;
parseNamespaceResolution();
bool isFunction = peek(SEPARATOR_ROUNDBRACKETOPEN);
this->m_curr = originalPos;
this->m_curr = originalPos;
if (isFunction) {
this->m_curr++;

View File

@ -16,10 +16,10 @@ namespace hex::pl {
PatternLanguage::PatternLanguage() {
this->m_preprocessor = new Preprocessor();
this->m_lexer = new Lexer();
this->m_parser = new Parser();
this->m_validator = new Validator();
this->m_evaluator = new Evaluator();
this->m_lexer = new Lexer();
this->m_parser = new Parser();
this->m_validator = new Validator();
this->m_evaluator = new Evaluator();
this->m_preprocessor->addDefaultPragmaHandlers();

View File

@ -9,8 +9,8 @@
namespace hex::pl {
std::optional<std::string> Preprocessor::preprocess(const std::string &code, bool initialRun) {
u32 offset = 0;
u32 lineNumber = 1;
u32 offset = 0;
u32 lineNumber = 1;
bool isInString = false;
if (initialRun) {

View File

@ -56,7 +56,7 @@ namespace hex::prv {
void Provider::applyOverlays(u64 offset, void *buffer, size_t size) {
for (auto &overlay : this->m_overlays) {
auto overlayOffset = overlay->getAddress();
auto overlaySize = overlay->getSize();
auto overlaySize = overlay->getSize();
i128 overlapMin = std::max(offset, overlayOffset);
i128 overlapMax = std::min(offset + size, overlayOffset + overlaySize);
@ -156,7 +156,7 @@ namespace hex::prv {
createUndoPoint();
for (u64 i = 0; i < size; i++) {
u8 patch = reinterpret_cast<const u8 *>(buffer)[i];
u8 patch = reinterpret_cast<const u8 *>(buffer)[i];
u8 originalValue = 0x00;
this->readRaw(offset + i, &originalValue, sizeof(u8));

View File

@ -27,13 +27,13 @@ namespace ImGui {
if (window->SkipItems)
return false;
ImGuiContext &g = *GImGui;
ImGuiContext &g = *GImGui;
const ImGuiStyle &style = g.Style;
const ImGuiID id = window->GetID(label);
ImVec2 label_size = CalcTextSize(icon, NULL, false);
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;
ImVec2 pos = window->DC.CursorPos;
ImVec2 pos = window->DC.CursorPos;
ImVec2 size = CalcItemSize(size_arg, label_size.x, label_size.y);
const ImRect bb(pos, pos + size);
@ -62,12 +62,12 @@ namespace ImGui {
if (window->SkipItems)
return false;
ImGuiContext &g = *GImGui;
ImGuiContext &g = *GImGui;
const ImGuiStyle &style = g.Style;
const ImGuiID id = window->GetID(label);
const ImGuiID id = window->GetID(label);
const ImVec2 label_size = CalcTextSize(label, NULL, true);
ImVec2 pos = window->DC.CursorPos;
ImVec2 pos = window->DC.CursorPos;
ImVec2 size = CalcItemSize(size_arg, label_size.x, label_size.y);
const ImRect bb(pos, pos + size);
@ -95,12 +95,12 @@ namespace ImGui {
if (window->SkipItems)
return false;
ImGuiContext &g = *GImGui;
ImGuiContext &g = *GImGui;
const ImGuiStyle &style = g.Style;
const ImGuiID id = window->GetID(label);
const ImGuiID id = window->GetID(label);
const ImVec2 label_size = CalcTextSize(label, NULL, true);
ImVec2 pos = window->DC.CursorPos;
ImVec2 pos = window->DC.CursorPos;
ImVec2 size = CalcItemSize(size_arg, label_size.x, label_size.y) + ImVec2(g.FontSize + style.FramePadding.x * 2, 0.0f);
const ImRect bb(pos, pos + size);
@ -130,10 +130,10 @@ namespace ImGui {
if (window->SkipItems)
return false;
ImGuiContext &g = *GImGui;
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 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;
@ -180,7 +180,7 @@ namespace ImGui {
const ImVec2 label_size = CalcTextSize(label, NULL, true);
ImVec2 pos = window->DC.CursorPos;
ImVec2 pos = window->DC.CursorPos;
ImVec2 size = CalcItemSize(size_arg, label_size.x, label_size.y);
PushStyleColor(ImGuiCol_Text, ImU32(color));
@ -221,7 +221,7 @@ namespace ImGui {
static double lastMoveTime;
static ImGuiID lastHoveredID;
double currTime = ImGui::GetTime();
double currTime = ImGui::GetTime();
ImGuiID hoveredID = ImGui::GetHoveredID();
if (IsItemHovered() && (currTime - lastMoveTime) >= 0.5 && hoveredID == lastHoveredID) {
@ -238,14 +238,14 @@ namespace ImGui {
ImU32 GetCustomColorU32(ImGuiCustomCol idx, float alpha_mul) {
auto &customData = *static_cast<ImHexCustomData *>(GImGui->IO.UserData);
ImVec4 c = customData.Colors[idx];
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);
ImVec4 c = customData.Colors[idx];
ImVec4 c = customData.Colors[idx];
c.w *= GImGui->Style.Alpha * alpha_mul;
return c;
}
@ -253,17 +253,17 @@ namespace ImGui {
void StyleCustomColorsDark() {
auto &colors = static_cast<ImHexCustomData *>(GImGui->IO.UserData)->Colors;
colors[ImGuiCustomCol_DescButton] = ImColor(20, 20, 20);
colors[ImGuiCustomCol_DescButton] = ImColor(20, 20, 20);
colors[ImGuiCustomCol_DescButtonHovered] = ImColor(40, 40, 40);
colors[ImGuiCustomCol_DescButtonActive] = ImColor(60, 60, 60);
colors[ImGuiCustomCol_DescButtonActive] = ImColor(60, 60, 60);
colors[ImGuiCustomCol_ToolbarGray] = ImColor(230, 230, 230);
colors[ImGuiCustomCol_ToolbarRed] = ImColor(231, 76, 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_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_ToolbarBrown] = ImColor(219, 179, 119);
colors[ImGuiCustomCol_Highlight] = ImColor(77, 198, 155);
}
@ -271,17 +271,17 @@ namespace ImGui {
void StyleCustomColorsLight() {
auto &colors = static_cast<ImHexCustomData *>(GImGui->IO.UserData)->Colors;
colors[ImGuiCustomCol_DescButton] = ImColor(230, 230, 230);
colors[ImGuiCustomCol_DescButton] = ImColor(230, 230, 230);
colors[ImGuiCustomCol_DescButtonHovered] = ImColor(210, 210, 210);
colors[ImGuiCustomCol_DescButtonActive] = ImColor(190, 190, 190);
colors[ImGuiCustomCol_DescButtonActive] = ImColor(190, 190, 190);
colors[ImGuiCustomCol_ToolbarGray] = ImColor(25, 25, 25);
colors[ImGuiCustomCol_ToolbarRed] = ImColor(231, 76, 60);
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_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_ToolbarBrown] = ImColor(219, 179, 119);
colors[ImGuiCustomCol_Highlight] = ImColor(41, 151, 112);
}
@ -289,23 +289,23 @@ namespace ImGui {
void StyleCustomColorsClassic() {
auto &colors = static_cast<ImHexCustomData *>(GImGui->IO.UserData)->Colors;
colors[ImGuiCustomCol_DescButton] = ImColor(40, 40, 80);
colors[ImGuiCustomCol_DescButton] = ImColor(40, 40, 80);
colors[ImGuiCustomCol_DescButtonHovered] = ImColor(60, 60, 100);
colors[ImGuiCustomCol_DescButtonActive] = ImColor(80, 80, 120);
colors[ImGuiCustomCol_DescButtonActive] = ImColor(80, 80, 120);
colors[ImGuiCustomCol_ToolbarGray] = ImColor(230, 230, 230);
colors[ImGuiCustomCol_ToolbarRed] = ImColor(231, 76, 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_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_ToolbarBrown] = ImColor(219, 179, 119);
colors[ImGuiCustomCol_Highlight] = ImColor(77, 198, 155);
}
Texture LoadImageFromPath(const char *path) {
int imageWidth = 0;
int imageWidth = 0;
int imageHeight = 0;
unsigned char *imageData = stbi_load(path, &imageWidth, &imageHeight, nullptr, 4);
@ -330,7 +330,7 @@ namespace ImGui {
}
Texture LoadImageFromMemory(const ImU8 *buffer, int size) {
int imageWidth = 0;
int imageWidth = 0;
int imageHeight = 0;
@ -377,9 +377,9 @@ namespace ImGui {
if (window->SkipItems)
return false;
ImGuiContext &g = *GImGui;
ImGuiContext &g = *GImGui;
const ImGuiStyle &style = g.Style;
const ImGuiID id = window->GetID(label);
const ImGuiID id = window->GetID(label);
const ImVec2 label_size = CalcTextSize(label, NULL, true);
ImVec2 pos = window->DC.CursorPos;
@ -416,9 +416,9 @@ namespace ImGui {
color.w = 1.0F;
ImGuiContext &g = *GImGui;
ImGuiContext &g = *GImGui;
const ImGuiStyle &style = g.Style;
const ImGuiID id = window->GetID(symbol);
const ImGuiID id = window->GetID(symbol);
const ImVec2 label_size = CalcTextSize(symbol, NULL, true);
ImVec2 pos = window->DC.CursorPos;
@ -459,9 +459,9 @@ namespace ImGui {
color.w = 1.0F;
ImGuiContext &g = *GImGui;
ImGuiContext &g = *GImGui;
const ImGuiStyle &style = g.Style;
const ImGuiID id = window->GetID(symbol);
const ImGuiID id = window->GetID(symbol);
const ImVec2 label_size = CalcTextSize(symbol, NULL, true);
ImVec2 pos = window->DC.CursorPos;
@ -500,10 +500,10 @@ namespace ImGui {
if (window->SkipItems)
return;
ImGuiContext &g = *GImGui;
ImGuiContext &g = *GImGui;
const ImGuiStyle &style = g.Style;
ImVec2 pos = window->DC.CursorPos + ImVec2(0, yOffset);
ImVec2 pos = window->DC.CursorPos + ImVec2(0, yOffset);
ImVec2 size = CalcItemSize(ImVec2(100, 5), 100, g.FontSize + style.FramePadding.y * 2.0f);
ImRect bb(pos, pos + size);
ItemSize(size, 0);

View File

@ -118,10 +118,10 @@ namespace hex {
}
void View::showFileChooserPopup(const std::vector<fs::path> &paths, const std::vector<nfdfilteritem_t> &validExtensions, const std::function<void(fs::path)> &callback) {
View::s_selectableFileIndex = 0;
View::s_selectableFiles = paths;
View::s_selectableFileIndex = 0;
View::s_selectableFiles = paths;
View::s_selectableFilesValidExtensions = validExtensions;
View::s_selectableFileOpenCallback = callback;
View::s_selectableFileOpenCallback = callback;
ImHexApi::Tasks::doLater([] { ImGui::OpenPopup("hex.common.choose_file"_lang); });
}

View File

@ -59,7 +59,7 @@ namespace hex {
std::string m_tipOfTheDay;
ImGui::Texture m_bannerTexture = { 0 };
ImGui::Texture m_logoTexture = { 0 };
ImGui::Texture m_logoTexture = { 0 };
fs::path m_safetyBackupPath;

View File

@ -68,7 +68,7 @@ namespace hex::init {
}
bool WindowSplash::loop() {
auto splash = romfs::get("splash.png");
auto splash = romfs::get("splash.png");
ImGui::Texture splashTexture = ImGui::LoadImageFromMemory(reinterpret_cast<const ImU8 *>(splash.data()), splash.size());
if (splashTexture == nullptr) {
@ -170,12 +170,12 @@ namespace hex::init {
auto meanScale = 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)
meanScale /= 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)
meanScale /= 2;
#endif
if (meanScale <= 0) {
meanScale = 1.0;

View File

@ -33,7 +33,7 @@ namespace hex::init {
return false;
auto versionString = std::string(IMHEX_VERSION);
auto currVersion = "v" + versionString.substr(0, versionString.find_first_of('-'));
auto currVersion = "v" + versionString.substr(0, versionString.find_first_of('-'));
auto latestVersion = releases.body["tag_name"].get<std::string_view>();
if (latestVersion != currVersion)
@ -89,7 +89,7 @@ namespace hex::init {
}
bool loadFonts() {
auto fonts = IM_NEW(ImFontAtlas)();
auto fonts = IM_NEW(ImFontAtlas)();
ImFontConfig cfg = {};
fs::path fontFile;
@ -220,7 +220,7 @@ namespace hex::init {
}
u32 builtinPlugins = 0;
u32 loadErrors = 0;
u32 loadErrors = 0;
for (const auto &plugin : plugins) {
if (!plugin.initializePlugin()) {
log::error("Failed to initialize plugin {}", plugin.getPath().filename().string());
@ -266,22 +266,22 @@ namespace hex::init {
float interfaceScaling = 1.0F;
switch (ContentRegistry::Settings::read("hex.builtin.setting.interface", "hex.builtin.setting.interface.scaling", 0)) {
default:
case 0:
// Native scaling
break;
case 1:
interfaceScaling = 0.5F;
break;
case 2:
interfaceScaling = 1.0F;
break;
case 3:
interfaceScaling = 1.5F;
break;
case 4:
interfaceScaling = 2.0F;
break;
default:
case 0:
// Native scaling
break;
case 1:
interfaceScaling = 0.5F;
break;
case 2:
interfaceScaling = 1.0F;
break;
case 3:
interfaceScaling = 1.5F;
break;
case 4:
interfaceScaling = 2.0F;
break;
}
ImHexApi::System::impl::setGlobalScale(interfaceScaling);
@ -301,7 +301,7 @@ namespace hex::init {
std::vector<Task> getInitTasks() {
return {
{ "Checking for updates...", checkForUpdates },
{"Checking for updates...", checkForUpdates },
{ "Downloading information...", downloadInformation},
{ "Creating directories...", createDirectories },
{ "Loading settings...", loadSettings },
@ -312,9 +312,9 @@ namespace hex::init {
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 },
};
}

View File

@ -31,139 +31,139 @@ namespace hex {
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;
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
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;
}
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)) * ImHexApi::System::getGlobalScale() / 1.5F),
static_cast<LONG>((::GetSystemMetrics(SM_CYFRAME) + ::GetSystemMetrics(SM_CXPADDEDBORDER)) * ImHexApi::System::getGlobalScale() / 1.5F)
};
} else {
rect = client;
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;
return 0;
}
case WM_SETCURSOR:
{
auto cursorPos = LOWORD(lParam);
if (LPCTSTR(lParam) == std::string_view("ImmersiveColorSet")) {
EventManager::post<EventOSThemeChanged>();
}
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;
}
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;
}
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)) * ImHexApi::System::getGlobalScale() / 1.5F),
static_cast<LONG>((::GetSystemMetrics(SM_CYFRAME) + ::GetSystemMetrics(SM_CXPADDEDBORDER)) * ImHexApi::System::getGlobalScale() / 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;
}
default:
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);
@ -230,7 +230,7 @@ namespace hex {
return TRUE;
},
0);
0);
std::exit(0);
}
@ -260,7 +260,7 @@ namespace hex {
HKEY hkey;
if (RegOpenKey(HKEY_CURRENT_USER, R"(Software\Microsoft\Windows\CurrentVersion\Themes\Personalize)", &hkey) == ERROR_SUCCESS) {
DWORD value = 0;
DWORD size = sizeof(DWORD);
DWORD size = sizeof(DWORD);
auto error = RegQueryValueEx(hkey, "AppsUseLightTheme", nullptr, nullptr, reinterpret_cast<LPBYTE>(&value), &size);
if (error == ERROR_SUCCESS) {
@ -283,37 +283,37 @@ namespace hex {
}
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;
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;
}
}

View File

@ -136,11 +136,11 @@ 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);
@ -150,7 +150,7 @@ namespace hex {
std::signal(SIGABRT, signalHandler);
std::signal(SIGFPE, signalHandler);
auto imhexLogo = romfs::get("logo.png");
auto imhexLogo = romfs::get("logo.png");
this->m_logoTexture = ImGui::LoadImageFromMemory(reinterpret_cast<const ImU8 *>(imhexLogo.data()), imhexLogo.size());
ContentRegistry::Settings::store();
@ -176,7 +176,7 @@ namespace hex {
} else {
double timeout = (1.0 / 5.0) - (glfwGetTime() - this->m_lastFrameTime);
timeout = timeout > 0 ? timeout : 0;
timeout = timeout > 0 ? timeout : 0;
glfwWaitEventsTimeout(ImGui::IsPopupOpen(ImGuiID(0), ImGuiPopupFlags_AnyPopupId) || Task::getRunningTaskCount() > 0 ? 0 : timeout);
}
@ -208,12 +208,12 @@ namespace hex {
if (ImGui::Begin("DockSpace", nullptr, windowFlags)) {
auto drawList = ImGui::GetWindowDrawList();
ImGui::PopStyleVar();
auto sidebarPos = ImGui::GetCursorPos();
auto sidebarPos = ImGui::GetCursorPos();
auto sidebarWidth = ContentRegistry::Interface::getSidebarItems().empty() ? 0 : 30_scaled;
ImGui::SetCursorPosX(sidebarWidth);
auto footerHeight = ImGui::GetTextLineHeightWithSpacing() + ImGui::GetStyle().FramePadding.y * 2 + 1_scaled;
auto footerHeight = ImGui::GetTextLineHeightWithSpacing() + ImGui::GetStyle().FramePadding.y * 2 + 1_scaled;
auto dockSpaceSize = ImVec2(ImHexApi::System::getMainWindowSize().x - sidebarWidth, ImGui::GetContentRegionAvail().y - footerHeight);
auto dockId = ImGui::DockSpace(ImGui::GetID("MainDock"), dockSpaceSize);
@ -240,7 +240,7 @@ namespace hex {
ImGui::SetCursorPos(sidebarPos);
static i32 openWindow = -1;
u32 index = 0;
u32 index = 0;
ImGui::PushID("SideBarWindows");
for (const auto &[icon, callback] : ContentRegistry::Interface::getSidebarItems()) {
ImGui::SetCursorPosY(sidebarPos.y + sidebarWidth * index);
@ -375,9 +375,9 @@ namespace hex {
}
if (view->getWindowOpenState()) {
auto window = ImGui::FindWindowByName(view->getName().c_str());
auto window = ImGui::FindWindowByName(view->getName().c_str());
bool hasWindow = window != nullptr;
bool focused = false;
bool focused = false;
if (hasWindow && !(window->Flags & ImGuiWindowFlags_Popup)) {
@ -425,7 +425,6 @@ namespace hex {
}
void Window::drawWelcomeScreen() {
}
void Window::resetLayout() const {
@ -460,7 +459,7 @@ namespace hex {
glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);
this->m_windowTitle = "ImHex";
this->m_window = glfwCreateWindow(1280_scaled, 720_scaled, this->m_windowTitle.c_str(), nullptr, nullptr);
this->m_window = glfwCreateWindow(1280_scaled, 720_scaled, this->m_windowTitle.c_str(), nullptr, nullptr);
glfwSetWindowUserPointer(this->m_window, this);
@ -534,15 +533,15 @@ namespace hex {
win->m_pressedKeys.push_back(key);
io.KeysDown[key] = true;
io.KeyCtrl = (mods & GLFW_MOD_CONTROL) != 0;
io.KeyShift = (mods & GLFW_MOD_SHIFT) != 0;
io.KeyAlt = (mods & GLFW_MOD_ALT) != 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) {
auto &io = ImGui::GetIO();
auto &io = ImGui::GetIO();
io.KeysDown[key] = false;
io.KeyCtrl = (mods & GLFW_MOD_CONTROL) != 0;
io.KeyShift = (mods & GLFW_MOD_SHIFT) != 0;
io.KeyAlt = (mods & GLFW_MOD_ALT) != 0;
io.KeyCtrl = (mods & GLFW_MOD_CONTROL) != 0;
io.KeyShift = (mods & GLFW_MOD_SHIFT) != 0;
io.KeyAlt = (mods & GLFW_MOD_ALT) != 0;
}
});
@ -585,14 +584,14 @@ namespace hex {
auto fonts = View::getFontAtlas();
GImGui = ImGui::CreateContext(fonts);
GImPlot = ImPlot::CreateContext();
GImGui = ImGui::CreateContext(fonts);
GImPlot = ImPlot::CreateContext();
GImNodes = ImNodes::CreateContext();
ImGuiIO &io = ImGui::GetIO();
ImGuiIO &io = ImGui::GetIO();
ImGuiStyle &style = ImGui::GetStyle();
style.Alpha = 1.0F;
style.Alpha = 1.0F;
style.WindowRounding = 0.0F;
io.ConfigFlags |= ImGuiConfigFlags_DockingEnable | ImGuiConfigFlags_NavEnableKeyboard;
@ -604,34 +603,34 @@ namespace hex {
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);
{
static bool always = true;
static bool always = true;
ImNodes::GetIO().LinkDetachWithModifierClick.Modifier = &always;
}
@ -656,16 +655,16 @@ namespace hex {
}
style.WindowMenuButtonPosition = ImGuiDir_None;
style.IndentSpacing = 10.0F;
style.IndentSpacing = 10.0F;
// Install custom settings handler
ImGuiSettingsHandler handler;
handler.TypeName = "ImHex";
handler.TypeHash = ImHashStr("ImHex");
handler.TypeName = "ImHex";
handler.TypeHash = ImHashStr("ImHex");
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;

View File

@ -50,7 +50,7 @@ namespace hex::plugin::builtin::prv {
protected:
#if defined(OS_WINDOWS)
HANDLE m_file = INVALID_HANDLE_VALUE;
HANDLE m_file = INVALID_HANDLE_VALUE;
HANDLE m_mapping = INVALID_HANDLE_VALUE;
#else
int m_file = -1;
@ -58,10 +58,10 @@ namespace hex::plugin::builtin::prv {
fs::path m_path;
void *m_mappedFile = nullptr;
size_t m_fileSize = 0;
size_t m_fileSize = 0;
bool m_fileStatsValid = false;
bool m_emptyFile = false;
bool m_fileStatsValid = false;
bool m_emptyFile = false;
struct stat m_fileStats = { 0 };
bool m_readable = false, m_writable = false;

View File

@ -40,8 +40,8 @@ namespace hex::plugin::builtin {
};
bool m_commandPaletteOpen = false;
bool m_justOpened = false;
bool m_focusInputTextBox = false;
bool m_justOpened = false;
bool m_focusInputTextBox = false;
std::vector<char> m_commandBuffer;
std::vector<CommandResult> m_lastResults;

View File

@ -29,10 +29,10 @@ namespace hex::plugin::builtin {
bool m_shouldInvalidate = true;
std::endian m_endian = std::endian::native;
std::endian m_endian = std::endian::native;
ContentRegistry::DataInspector::NumberDisplayStyle m_numberDisplayStyle = ContentRegistry::DataInspector::NumberDisplayStyle::Decimal;
u64 m_startAddress = 0;
u64 m_startAddress = 0;
size_t m_validBytes = 0;
std::vector<InspectorCacheEntry> m_cachedData;
};

View File

@ -28,8 +28,8 @@ namespace hex::plugin::builtin {
int m_providerA = -1, m_providerB = -1;
bool m_greyedOutZeros = true;
bool m_upperCaseHex = true;
int m_columnCount = 16;
bool m_upperCaseHex = true;
int m_columnCount = 16;
};
}

View File

@ -33,12 +33,12 @@ namespace hex::plugin::builtin {
private:
bool m_disassembling = false;
u64 m_baseAddress = 0;
u64 m_codeRegion[2] = { 0 };
u64 m_baseAddress = 0;
u64 m_codeRegion[2] = { 0 };
bool m_shouldMatchSelection = false;
Architecture m_architecture = Architecture::ARM;
cs_mode m_mode = cs_mode(0);
cs_mode m_mode = cs_mode(0);
std::vector<Disassembly> m_disassembly;

View File

@ -32,9 +32,9 @@ namespace hex::plugin::builtin {
Sha512
};
bool m_shouldInvalidate = true;
int m_currHashFunction = 0;
u64 m_hashRegion[2] = { 0 };
bool m_shouldInvalidate = true;
int m_currHashFunction = 0;
u64 m_hashRegion[2] = { 0 };
bool m_shouldMatchSelection = false;
static constexpr std::array hashFunctionNames {

View File

@ -43,7 +43,7 @@ namespace hex::plugin::builtin {
i64 m_gotoAddress = 0;
char m_baseAddressBuffer[0x20] = { 0 };
u64 m_resizeSize = 0;
u64 m_resizeSize = 0;
std::vector<u8> m_dataToSave;
std::set<pl::PatternData *> m_highlightedPatterns;
@ -54,7 +54,7 @@ namespace hex::plugin::builtin {
hex::EncodingFile m_currEncodingFile;
u8 m_highlightAlpha = 0x80;
bool m_processingImportExport = false;
bool m_processingImportExport = false;
bool m_advancedDecodingEnabled = false;
void drawSearchPopup();

View File

@ -22,16 +22,16 @@ namespace hex::plugin::builtin {
void drawContent() override;
private:
bool m_dataValid = false;
u32 m_blockSize = 0;
float m_averageEntropy = 0;
bool m_dataValid = false;
u32 m_blockSize = 0;
float m_averageEntropy = 0;
float m_highestBlockEntropy = 0;
std::vector<float> m_blockEntropy;
double m_entropyHandlePosition;
std::array<ImU64, 256> m_valueCounts = { 0 };
bool m_analyzing = false;
bool m_analyzing = false;
std::pair<u64, u64> m_analyzedRegion = { 0, 0 };

View File

@ -19,7 +19,7 @@ namespace hex::plugin::builtin {
void drawContent() override;
private:
std::map<prv::Provider*, std::vector<pl::PatternData*>> m_sortedPatterns;
std::map<prv::Provider *, std::vector<pl::PatternData *>> m_sortedPatterns;
};
}

View File

@ -28,10 +28,10 @@ namespace hex::plugin::builtin {
std::vector<fs::path> m_possiblePatternFiles;
u32 m_selectedPatternFile = 0;
bool m_runAutomatically = false;
bool m_runAutomatically = false;
std::atomic<u32> m_runningEvaluators = 0;
std::atomic<u32> m_runningParsers = 0;
std::atomic<u32> m_runningParsers = 0;
bool m_hasUnevaluatedChanges = false;

View File

@ -24,8 +24,8 @@ namespace hex::plugin::builtin {
void drawContent() override;
private:
bool m_searching = false;
bool m_regex = false;
bool m_searching = false;
bool m_regex = false;
bool m_pattern_parsed = false;
std::vector<FoundString> m_foundStrings;

View File

@ -26,7 +26,7 @@ namespace hex::plugin::builtin {
std::vector<std::pair<std::string, std::string>> m_rules;
std::vector<YaraMatch> m_matches;
u32 m_selectedRule = 0;
bool m_matching = false;
bool m_matching = false;
std::vector<char> m_errorMessage;
void reloadRules();

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,
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
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 {

View File

@ -93,7 +93,7 @@ namespace hex::plugin::builtin {
if (col == (offset >> 4) && i < (offset & 0xF) || col == (end >> 4) && i > (end & 0xF))
result += " ";
else {
u8 c = buffer[((col << 4) - offset) + i];
u8 c = buffer[((col << 4) - offset) + i];
char displayChar = (c < 32 || c >= 128) ? '.' : c;
result += hex::format("{0}", displayChar);
}
@ -145,7 +145,7 @@ namespace hex::plugin::builtin {
if (col == (offset >> 4) && i < (offset & 0xF) || col == (end >> 4) && i > (end & 0xF))
result += "&nbsp";
else {
u8 c = buffer[((col << 4) - offset) + i];
u8 c = buffer[((col << 4) - offset) + i];
char displayChar = (c < 32 || c >= 128) ? '.' : c;
result += hex::format("{0}", displayChar);
}

View File

@ -49,9 +49,9 @@ namespace hex::plugin::builtin {
ContentRegistry::DataInspector::add("hex.builtin.inspector.i8", sizeof(i8), [](auto buffer, auto endian, auto style) {
auto format = (style == Style::Decimal) ? "{0}{1:d}" : ((style == Style::Hexadecimal) ? "{0}0x{1:02X}" : "{0}0o{1:03o}");
auto number = hex::changeEndianess(*reinterpret_cast<i8 *>(buffer.data()), endian);
auto number = hex::changeEndianess(*reinterpret_cast<i8 *>(buffer.data()), endian);
bool negative = number < 0;
auto value = hex::format(format, negative ? "-" : "", std::abs(number));
auto value = hex::format(format, negative ? "-" : "", std::abs(number));
return [value] { ImGui::TextUnformatted(value.c_str()); return value; };
});
@ -67,9 +67,9 @@ namespace hex::plugin::builtin {
ContentRegistry::DataInspector::add("hex.builtin.inspector.i16", sizeof(i16), [](auto buffer, auto endian, auto style) {
auto format = (style == Style::Decimal) ? "{0}{1:d}" : ((style == Style::Hexadecimal) ? "{0}0x{1:04X}" : "{0}0o{1:06o}");
auto number = hex::changeEndianess(*reinterpret_cast<i16 *>(buffer.data()), endian);
auto number = hex::changeEndianess(*reinterpret_cast<i16 *>(buffer.data()), endian);
bool negative = number < 0;
auto value = hex::format(format, negative ? "-" : "", std::abs(number));
auto value = hex::format(format, negative ? "-" : "", std::abs(number));
return [value] { ImGui::TextUnformatted(value.c_str()); return value; };
});
@ -85,9 +85,9 @@ namespace hex::plugin::builtin {
ContentRegistry::DataInspector::add("hex.builtin.inspector.i32", sizeof(i32), [](auto buffer, auto endian, auto style) {
auto format = (style == Style::Decimal) ? "{0}{1:d}" : ((style == Style::Hexadecimal) ? "{0}0x{1:08X}" : "{0}0o{1:011o}");
auto number = hex::changeEndianess(*reinterpret_cast<i32 *>(buffer.data()), endian);
auto number = hex::changeEndianess(*reinterpret_cast<i32 *>(buffer.data()), endian);
bool negative = number < 0;
auto value = hex::format(format, negative ? "-" : "", std::abs(number));
auto value = hex::format(format, negative ? "-" : "", std::abs(number));
return [value] { ImGui::TextUnformatted(value.c_str()); return value; };
});
@ -103,9 +103,9 @@ namespace hex::plugin::builtin {
ContentRegistry::DataInspector::add("hex.builtin.inspector.i64", sizeof(i64), [](auto buffer, auto endian, auto style) {
auto format = (style == Style::Decimal) ? "{0}{1:d}" : ((style == Style::Hexadecimal) ? "{0}0x{1:016X}" : "{0}0o{1:022o}");
auto number = hex::changeEndianess(*reinterpret_cast<i64 *>(buffer.data()), endian);
auto number = hex::changeEndianess(*reinterpret_cast<i64 *>(buffer.data()), endian);
bool negative = number < 0;
auto value = hex::format(format, negative ? "-" : "", std::abs(number));
auto value = hex::format(format, negative ? "-" : "", std::abs(number));
return [value] { ImGui::TextUnformatted(value.c_str()); return value; };
});
@ -143,17 +143,17 @@ namespace hex::plugin::builtin {
});
ContentRegistry::DataInspector::add("hex.builtin.inspector.utf8", sizeof(char8_t) * 4, [](auto buffer, auto endian, auto style) {
char utf8Buffer[5] = { 0 };
char utf8Buffer[5] = { 0 };
char codepointString[5] = { 0 };
u32 codepoint = 0;
u32 codepoint = 0;
std::memcpy(utf8Buffer, reinterpret_cast<char8_t *>(buffer.data()), 4);
u8 codepointSize = ImTextCharFromUtf8(&codepoint, utf8Buffer, utf8Buffer + 4);
std::memcpy(codepointString, utf8Buffer, std::min(codepointSize, u8(4)));
auto value = hex::format("'{0}' (U+0x{1:04X})",
codepoint == 0xFFFD ? "Invalid" : (codepointSize == 1 ? makePrintable(codepointString[0]) : codepointString),
codepoint);
codepoint == 0xFFFD ? "Invalid" : (codepointSize == 1 ? makePrintable(codepointString[0]) : codepointString),
codepoint);
return [value] { ImGui::TextUnformatted(value.c_str()); return value; };
});
@ -228,18 +228,18 @@ namespace hex::plugin::builtin {
GUID guid;
std::memcpy(&guid, buffer.data(), sizeof(GUID));
auto value = hex::format("{}{{{:08X}-{:04X}-{:04X}-{:02X}{:02X}-{:02X}{:02X}{:02X}{:02X}{:02X}{:02X}}}",
(hex::changeEndianess(guid.data3, endian) >> 12) <= 5 && ((guid.data4[0] >> 4) >= 8 || (guid.data4[0] >> 4) == 0) ? "" : "Invalid ",
hex::changeEndianess(guid.data1, endian),
hex::changeEndianess(guid.data2, endian),
hex::changeEndianess(guid.data3, endian),
guid.data4[0],
guid.data4[1],
guid.data4[2],
guid.data4[3],
guid.data4[4],
guid.data4[5],
guid.data4[6],
guid.data4[7]);
(hex::changeEndianess(guid.data3, endian) >> 12) <= 5 && ((guid.data4[0] >> 4) >= 8 || (guid.data4[0] >> 4) == 0) ? "" : "Invalid ",
hex::changeEndianess(guid.data1, endian),
hex::changeEndianess(guid.data2, endian),
hex::changeEndianess(guid.data3, endian),
guid.data4[0],
guid.data4[1],
guid.data4[2],
guid.data4[3],
guid.data4[4],
guid.data4[5],
guid.data4[6],
guid.data4[7]);
return [value] { ImGui::TextUnformatted(value.c_str()); return value; };
});

View File

@ -52,7 +52,7 @@ namespace hex::plugin::builtin {
}
void load(nlohmann::json &j) override {
this->m_size = j["size"];
this->m_size = j["size"];
this->m_buffer = j["data"].get<std::vector<u8>>();
}
@ -162,10 +162,10 @@ namespace hex::plugin::builtin {
class NodeRGBA8 : public dp::Node {
public:
NodeRGBA8() : Node("hex.builtin.nodes.constants.rgba8.header",
{ dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.constants.rgba8.output.r"),
dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.constants.rgba8.output.g"),
dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.constants.rgba8.output.b"),
dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.constants.rgba8.output.a") }) { }
{ dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.constants.rgba8.output.r"),
dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.constants.rgba8.output.g"),
dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.constants.rgba8.output.b"),
dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.constants.rgba8.output.a") }) { }
void drawNode() override {
ImGui::PushItemWidth(200);
@ -183,7 +183,7 @@ namespace hex::plugin::builtin {
void store(nlohmann::json &j) override {
j = nlohmann::json::object();
j["data"] = nlohmann::json::object();
j["data"] = nlohmann::json::object();
j["data"]["r"] = this->m_color.Value.x;
j["data"]["g"] = this->m_color.Value.y;
j["data"]["b"] = this->m_color.Value.z;
@ -347,7 +347,7 @@ namespace hex::plugin::builtin {
void process() override {
auto address = this->getIntegerOnInput(0);
auto size = this->getIntegerOnInput(1);
auto size = this->getIntegerOnInput(1);
std::vector<u8> data;
data.resize(size);
@ -364,7 +364,7 @@ namespace hex::plugin::builtin {
void process() override {
auto address = this->getIntegerOnInput(0);
auto data = this->getBufferOnInput(1);
auto data = this->getBufferOnInput(1);
this->setOverlayData(address, data);
}
@ -506,8 +506,8 @@ namespace hex::plugin::builtin {
void process() override {
auto input = this->getBufferOnInput(0);
auto from = this->getIntegerOnInput(1);
auto to = this->getIntegerOnInput(2);
auto from = this->getIntegerOnInput(1);
auto to = this->getIntegerOnInput(2);
if (from < 0 || from >= input.size())
throwNodeError("'from' input out of range");
@ -526,7 +526,7 @@ namespace hex::plugin::builtin {
void process() override {
auto buffer = this->getBufferOnInput(0);
auto count = this->getIntegerOnInput(1);
auto count = this->getIntegerOnInput(1);
std::vector<u8> output;
output.resize(buffer.size() * count);
@ -541,14 +541,14 @@ namespace hex::plugin::builtin {
class NodeIf : public dp::Node {
public:
NodeIf() : Node("ex.builtin.nodes.control_flow.if.header",
{ dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.if.condition"),
dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.control_flow.if.true"),
dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.control_flow.if.false"),
dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "hex.builtin.nodes.control_flow.if.output") }) { }
{ dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.if.condition"),
dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.control_flow.if.true"),
dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.control_flow.if.false"),
dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "hex.builtin.nodes.control_flow.if.output") }) { }
void process() override {
auto cond = this->getIntegerOnInput(0);
auto trueData = this->getBufferOnInput(1);
auto cond = this->getIntegerOnInput(0);
auto trueData = this->getBufferOnInput(1);
auto falseData = this->getBufferOnInput(2);
if (cond != 0)
@ -561,9 +561,9 @@ namespace hex::plugin::builtin {
class NodeEquals : public dp::Node {
public:
NodeEquals() : Node("hex.builtin.nodes.control_flow.equals.header",
{ dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.equals.input.a"),
dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.equals.input.b"),
dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.equals.output") }) { }
{ dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.equals.input.a"),
dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.equals.input.b"),
dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.equals.output") }) { }
void process() override {
auto inputA = this->getIntegerOnInput(0);
@ -576,8 +576,8 @@ namespace hex::plugin::builtin {
class NodeNot : public dp::Node {
public:
NodeNot() : Node("hex.builtin.nodes.control_flow.not.header",
{ dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.not.input"),
dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.not.output") }) { }
{ dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.not.input"),
dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.not.output") }) { }
void process() override {
auto input = this->getIntegerOnInput(0);
@ -589,9 +589,9 @@ namespace hex::plugin::builtin {
class NodeGreaterThan : public dp::Node {
public:
NodeGreaterThan() : Node("hex.builtin.nodes.control_flow.gt.header",
{ dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.gt.input.a"),
dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.gt.input.b"),
dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.gt.output") }) { }
{ dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.gt.input.a"),
dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.gt.input.b"),
dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.gt.output") }) { }
void process() override {
auto inputA = this->getIntegerOnInput(0);
@ -604,9 +604,9 @@ namespace hex::plugin::builtin {
class NodeLessThan : public dp::Node {
public:
NodeLessThan() : Node("hex.builtin.nodes.control_flow.lt.header",
{ dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.lt.input.a"),
dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.lt.input.b"),
dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.lt.output") }) { }
{ dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.lt.input.a"),
dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.lt.input.b"),
dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.lt.output") }) { }
void process() override {
auto inputA = this->getIntegerOnInput(0);
@ -619,9 +619,9 @@ namespace hex::plugin::builtin {
class NodeBoolAND : public dp::Node {
public:
NodeBoolAND() : Node("hex.builtin.nodes.control_flow.and.header",
{ dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.and.input.a"),
dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.and.input.b"),
dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.and.output") }) { }
{ dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.and.input.a"),
dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.and.input.b"),
dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.and.output") }) { }
void process() override {
auto inputA = this->getIntegerOnInput(0);
@ -634,9 +634,9 @@ namespace hex::plugin::builtin {
class NodeBoolOR : public dp::Node {
public:
NodeBoolOR() : Node("hex.builtin.nodes.control_flow.or.header",
{ dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.or.input.a"),
dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.or.input.b"),
dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.or.output") }) { }
{ dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.or.input.a"),
dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.or.input.b"),
dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.or.output") }) { }
void process() override {
auto inputA = this->getIntegerOnInput(0);
@ -649,11 +649,11 @@ namespace hex::plugin::builtin {
class NodeCryptoAESDecrypt : public dp::Node {
public:
NodeCryptoAESDecrypt() : Node("hex.builtin.nodes.crypto.aes.header",
{ dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.crypto.aes.key"),
dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.crypto.aes.iv"),
dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.crypto.aes.nonce"),
dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.crypto.aes.input"),
dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "hex.builtin.nodes.crypto.aes.output") }) { }
{ dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.crypto.aes.key"),
dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.crypto.aes.iv"),
dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.crypto.aes.nonce"),
dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.crypto.aes.input"),
dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "hex.builtin.nodes.crypto.aes.output") }) { }
void drawNode() override {
ImGui::PushItemWidth(100);
@ -663,8 +663,8 @@ namespace hex::plugin::builtin {
}
void process() override {
auto key = this->getBufferOnInput(0);
auto iv = this->getBufferOnInput(1);
auto key = this->getBufferOnInput(0);
auto iv = this->getBufferOnInput(1);
auto nonce = this->getBufferOnInput(2);
auto input = this->getBufferOnInput(3);
@ -687,18 +687,18 @@ namespace hex::plugin::builtin {
void store(nlohmann::json &j) override {
j = nlohmann::json::object();
j["data"] = nlohmann::json::object();
j["data"]["mode"] = this->m_mode;
j["data"] = nlohmann::json::object();
j["data"]["mode"] = this->m_mode;
j["data"]["key_length"] = this->m_keyLength;
}
void load(nlohmann::json &j) override {
this->m_mode = j["data"]["mode"];
this->m_mode = j["data"]["mode"];
this->m_keyLength = j["data"]["key_length"];
}
private:
int m_mode = 0;
int m_mode = 0;
int m_keyLength = 0;
};

View File

@ -16,10 +16,10 @@ namespace hex::plugin::builtin {
void registerLayouts() {
ContentRegistry::Interface::addLayout("hex.builtin.layouts.default", [](ImGuiID dockMain) {
ImGuiID hexEditor = ImGui::DockBuilderSplitNode(dockMain, ImGuiDir_Left, 0.7F, nullptr, &dockMain);
ImGuiID utils = ImGui::DockBuilderSplitNode(dockMain, ImGuiDir_Right, 0.8F, nullptr, &dockMain);
ImGuiID hexEditor = ImGui::DockBuilderSplitNode(dockMain, ImGuiDir_Left, 0.7F, nullptr, &dockMain);
ImGuiID utils = ImGui::DockBuilderSplitNode(dockMain, ImGuiDir_Right, 0.8F, nullptr, &dockMain);
ImGuiID patternData = ImGui::DockBuilderSplitNode(hexEditor, ImGuiDir_Down, 0.3F, nullptr, &hexEditor);
ImGuiID inspector = ImGui::DockBuilderSplitNode(hexEditor, ImGuiDir_Right, 0.3F, nullptr, &hexEditor);
ImGuiID inspector = ImGui::DockBuilderSplitNode(hexEditor, ImGuiDir_Right, 0.3F, nullptr, &hexEditor);
openViewAndDockTo("hex.builtin.view.hexeditor.name", hexEditor);
openViewAndDockTo("hex.builtin.view.data_inspector.name", inspector);

View File

@ -31,7 +31,7 @@ namespace hex::plugin::builtin {
[&](auto &&value) {
formatArgs.push_back(value);
} },
param);
param);
}
try {
@ -80,14 +80,14 @@ namespace hex::plugin::builtin {
/* error(message) */
ContentRegistry::PatternLanguage::addFunction(nsStd, "error", 1, [](Evaluator *ctx, auto params) -> std::optional<Token::Literal> {
LogConsole::abortEvaluation(Token::literalToString(params[0], true));
LogConsole::abortEvaluation(Token::literalToString(params[0], true));
return std::nullopt;
});
/* warning(message) */
ContentRegistry::PatternLanguage::addFunction(nsStd, "warning", 1, [](Evaluator *ctx, auto params) -> std::optional<Token::Literal> {
ctx->getConsole().log(LogConsole::Level::Warning, Token::literalToString(params[0], true));
ctx->getConsole().log(LogConsole::Level::Warning, Token::literalToString(params[0], true));
return std::nullopt;
});
@ -141,7 +141,7 @@ namespace hex::plugin::builtin {
/* read_unsigned(address, size) */
ContentRegistry::PatternLanguage::addFunction(nsStdMem, "read_unsigned", 2, [](Evaluator *ctx, auto params) -> std::optional<Token::Literal> {
auto address = Token::literalToUnsigned(params[0]);
auto size = Token::literalToUnsigned(params[1]);
auto size = Token::literalToUnsigned(params[1]);
if (size > 16)
LogConsole::abortEvaluation("read size out of range");
@ -155,7 +155,7 @@ namespace hex::plugin::builtin {
/* read_signed(address, size) */
ContentRegistry::PatternLanguage::addFunction(nsStdMem, "read_signed", 2, [](Evaluator *ctx, auto params) -> std::optional<Token::Literal> {
auto address = Token::literalToUnsigned(params[0]);
auto size = Token::literalToUnsigned(params[1]);
auto size = Token::literalToUnsigned(params[1]);
if (size > 16)
LogConsole::abortEvaluation("read size out of range");
@ -168,7 +168,7 @@ namespace hex::plugin::builtin {
/* read_string(address, size) */
ContentRegistry::PatternLanguage::addFunction(nsStdMem, "read_string", 2, [](Evaluator *ctx, auto params) -> std::optional<Token::Literal> {
auto address = Token::literalToUnsigned(params[0]);
auto size = Token::literalToUnsigned(params[1]);
auto size = Token::literalToUnsigned(params[1]);
std::string result(size, '\x00');
ctx->getProvider()->read(address, result.data(), size);
@ -189,11 +189,11 @@ namespace hex::plugin::builtin {
/* at(string, index) */
ContentRegistry::PatternLanguage::addFunction(nsStdString, "at", 2, [](Evaluator *ctx, auto params) -> std::optional<Token::Literal> {
auto string = Token::literalToString(params[0], false);
auto index = Token::literalToSigned(params[1]);
auto index = Token::literalToSigned(params[1]);
#if defined(OS_MACOS)
const auto signIndex = index >> (sizeof(index) * 8 - 1);
const auto absIndex = (index ^ signIndex) - signIndex;
const auto absIndex = (index ^ signIndex) - signIndex;
#else
const auto absIndex = std::abs(index);
#endif
@ -210,8 +210,8 @@ namespace hex::plugin::builtin {
/* substr(string, pos, count) */
ContentRegistry::PatternLanguage::addFunction(nsStdString, "substr", 3, [](Evaluator *ctx, auto params) -> std::optional<Token::Literal> {
auto string = Token::literalToString(params[0], false);
auto pos = Token::literalToUnsigned(params[1]);
auto size = Token::literalToUnsigned(params[2]);
auto pos = Token::literalToUnsigned(params[1]);
auto size = Token::literalToUnsigned(params[2]);
if (pos > string.length())
LogConsole::abortEvaluation("character index out of range");
@ -222,7 +222,7 @@ namespace hex::plugin::builtin {
/* parse_int(string, base) */
ContentRegistry::PatternLanguage::addFunction(nsStdString, "parse_int", 2, [](Evaluator *ctx, auto params) -> std::optional<Token::Literal> {
auto string = Token::literalToString(params[0], false);
auto base = Token::literalToUnsigned(params[1]);
auto base = Token::literalToUnsigned(params[1]);
return i128(std::strtoll(string.c_str(), nullptr, base));
});
@ -255,22 +255,22 @@ namespace hex::plugin::builtin {
/* open(path, mode) */
ContentRegistry::PatternLanguage::addDangerousFunction(nsStdFile, "open", 2, [](Evaluator *ctx, auto params) -> std::optional<Token::Literal> {
const auto path = Token::literalToString(params[0], false);
const auto path = Token::literalToString(params[0], false);
const auto modeEnum = Token::literalToUnsigned(params[1]);
File::Mode mode;
switch (modeEnum) {
case 1:
mode = File::Mode::Read;
break;
case 2:
mode = File::Mode::Write;
break;
case 3:
mode = File::Mode::Create;
break;
default:
LogConsole::abortEvaluation("invalid file open mode");
case 1:
mode = File::Mode::Read;
break;
case 2:
mode = File::Mode::Write;
break;
case 3:
mode = File::Mode::Create;
break;
default:
LogConsole::abortEvaluation("invalid file open mode");
}
auto file = File(path, mode);
@ -322,7 +322,7 @@ namespace hex::plugin::builtin {
/* seek(file, offset) */
ContentRegistry::PatternLanguage::addDangerousFunction(nsStdFile, "seek", 2, [](Evaluator *ctx, auto params) -> std::optional<Token::Literal> {
const auto file = Token::literalToUnsigned(params[0]);
const auto file = Token::literalToUnsigned(params[0]);
const auto offset = Token::literalToUnsigned(params[1]);
if (!openFiles.contains(file))
@ -507,7 +507,6 @@ namespace hex::plugin::builtin {
ContentRegistry::PatternLanguage::addFunction(nsStdMath, "atanh", 1, [](Evaluator *ctx, auto params) -> std::optional<Token::Literal> {
return std::atanh(Token::literalToFloatingPoint(params[0]));
});
}
}

View File

@ -73,7 +73,7 @@ namespace hex::plugin::builtin::prv {
this->m_diskHandle = reinterpret_cast<HANDLE>(CreateFileW(path.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr));
if (this->m_diskHandle == INVALID_HANDLE_VALUE) {
this->m_diskHandle = reinterpret_cast<HANDLE>(CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr));
this->m_writable = false;
this->m_writable = false;
if (this->m_diskHandle == INVALID_HANDLE_VALUE)
return false;
@ -81,7 +81,7 @@ namespace hex::plugin::builtin::prv {
{
DISK_GEOMETRY_EX diskGeometry = { 0 };
DWORD bytesRead = 0;
DWORD bytesRead = 0;
if (DeviceIoControl(
this->m_diskHandle,
IOCTL_DISK_GET_DRIVE_GEOMETRY_EX,
@ -91,14 +91,14 @@ namespace hex::plugin::builtin::prv {
sizeof(DISK_GEOMETRY_EX),
&bytesRead,
nullptr)) {
this->m_diskSize = diskGeometry.DiskSize.QuadPart;
this->m_diskSize = diskGeometry.DiskSize.QuadPart;
this->m_sectorSize = diskGeometry.Geometry.BytesPerSector;
this->m_sectorBuffer.resize(this->m_sectorSize);
}
}
if (this->m_diskHandle == nullptr || this->m_diskHandle == INVALID_HANDLE_VALUE) {
this->m_readable = false;
this->m_readable = false;
this->m_diskHandle = nullptr;
CloseHandle(this->m_diskHandle);
@ -112,13 +112,13 @@ namespace hex::plugin::builtin::prv {
struct stat driveStat;
::stat(path.c_str(), &driveStat) == 0;
this->m_diskSize = driveStat.st_size;
this->m_diskSize = driveStat.st_size;
this->m_sectorSize = 0;
this->m_diskHandle = ::open(path.c_str(), O_RDWR);
if (this->m_diskHandle == -1) {
this->m_diskHandle = ::open(path.c_str(), O_RDONLY);
this->m_writable = false;
this->m_writable = false;
}
if (this->m_diskHandle == -1) {
@ -153,7 +153,7 @@ namespace hex::plugin::builtin::prv {
while (size > 0) {
LARGE_INTEGER seekPosition;
seekPosition.LowPart = (offset & 0xFFFF'FFFF) - (offset % this->m_sectorSize);
seekPosition.LowPart = (offset & 0xFFFF'FFFF) - (offset % this->m_sectorSize);
seekPosition.HighPart = offset >> 32;
if (this->m_sectorBufferAddress != seekPosition.QuadPart) {
@ -168,7 +168,7 @@ namespace hex::plugin::builtin::prv {
offset += this->m_sectorSize;
}
#else
u64 startOffset = offset;
u64 startOffset = offset;
while (size > 0) {
u64 seekPosition = offset - (offset % this->m_sectorSize);
@ -197,14 +197,14 @@ namespace hex::plugin::builtin::prv {
modifiedSectorBuffer.resize(this->m_sectorSize);
while (size > 0) {
u64 sectorBase = offset - (offset % this->m_sectorSize);
u64 sectorBase = offset - (offset % this->m_sectorSize);
size_t currSize = std::min(size, this->m_sectorSize);
this->readRaw(sectorBase, modifiedSectorBuffer.data(), modifiedSectorBuffer.size());
std::memcpy(modifiedSectorBuffer.data() + ((offset - sectorBase) % this->m_sectorSize), reinterpret_cast<const u8 *>(buffer) + (startOffset - offset), currSize);
LARGE_INTEGER seekPosition;
seekPosition.LowPart = (offset & 0xFFFF'FFFF) - (offset % this->m_sectorSize);
seekPosition.LowPart = (offset & 0xFFFF'FFFF) - (offset % this->m_sectorSize);
seekPosition.HighPart = offset >> 32;
::SetFilePointer(this->m_diskHandle, seekPosition.LowPart, &seekPosition.HighPart, FILE_BEGIN);
@ -222,7 +222,7 @@ namespace hex::plugin::builtin::prv {
modifiedSectorBuffer.resize(this->m_sectorSize);
while (size > 0) {
u64 sectorBase = offset - (offset % this->m_sectorSize);
u64 sectorBase = offset - (offset % this->m_sectorSize);
size_t currSize = std::min(size, this->m_sectorSize);
this->readRaw(sectorBase, modifiedSectorBuffer.data(), modifiedSectorBuffer.size());
@ -271,8 +271,8 @@ namespace hex::plugin::builtin::prv {
if (handle == INVALID_HANDLE_VALUE) continue;
VOLUME_DISK_EXTENTS diskExtents = { 0 };
DWORD bytesRead = 0;
auto result = ::DeviceIoControl(
DWORD bytesRead = 0;
auto result = ::DeviceIoControl(
handle,
IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS,
nullptr,

View File

@ -173,7 +173,7 @@ namespace hex::plugin::builtin::prv {
const auto &path = this->m_path.native();
LARGE_INTEGER fileSize = { 0 };
this->m_file = reinterpret_cast<HANDLE>(CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr));
this->m_file = reinterpret_cast<HANDLE>(CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr));
GetFileSizeEx(this->m_file, &fileSize);
this->m_fileSize = fileSize.QuadPart;
@ -181,7 +181,7 @@ namespace hex::plugin::builtin::prv {
this->m_file = reinterpret_cast<HANDLE>(CreateFileW(path.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr));
if (this->m_file == nullptr || this->m_file == INVALID_HANDLE_VALUE) {
this->m_file = reinterpret_cast<HANDLE>(CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr));
this->m_file = reinterpret_cast<HANDLE>(CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr));
this->m_writable = false;
}
@ -189,7 +189,7 @@ namespace hex::plugin::builtin::prv {
CloseHandle(this->m_file);
this->m_readable = false;
this->m_file = nullptr;
this->m_file = nullptr;
};
if (this->m_file == nullptr || this->m_file == INVALID_HANDLE_VALUE) {
@ -209,7 +209,7 @@ namespace hex::plugin::builtin::prv {
auto mappingCleanup = SCOPE_GUARD {
CloseHandle(this->m_mapping);
this->m_mapping = nullptr;
this->m_mapping = nullptr;
this->m_readable = false;
};
@ -241,7 +241,7 @@ namespace hex::plugin::builtin::prv {
this->m_file = ::open(path.c_str(), O_RDWR);
if (this->m_file == -1) {
this->m_file = ::open(path.c_str(), O_RDONLY);
this->m_file = ::open(path.c_str(), O_RDONLY);
this->m_writable = false;
}

View File

@ -42,7 +42,7 @@ namespace hex::plugin::builtin::prv {
if (packet[packet.length() - 3] != '#')
return std::nullopt;
std::string data = packet.substr(1, packet.length() - 4);
std::string data = packet.substr(1, packet.length() - 4);
std::string checksum = packet.substr(packet.length() - 2, 2);
if (checksum.length() != 2 || crypt::decode16(checksum)[0] != calculateChecksum(data))
@ -229,10 +229,10 @@ namespace hex::plugin::builtin::prv {
if (!this->isConnected()) {
address = "-";
port = "-";
port = "-";
} else {
address = this->m_ipAddress;
port = std::to_string(this->m_port);
port = std::to_string(this->m_port);
}
return hex::format("hex.builtin.provider.gdb.name"_lang, address, port);

View File

@ -101,10 +101,10 @@ namespace hex::plugin::builtin {
}
void drawRegexReplacer() {
static auto regexInput = [] { std::string s; s.reserve(0xFFF); return s; }();
static auto regexPattern = [] { std::string s; s.reserve(0xFFF); return s; }();
static auto regexInput = [] { std::string s; s.reserve(0xFFF); return s; }();
static auto regexPattern = [] { std::string s; s.reserve(0xFFF); return s; }();
static auto replacePattern = [] { std::string s; s.reserve(0xFFF); return s; }();
static auto regexOutput = [] { std::string s; s.reserve(0xFFF); return s; }();
static auto regexOutput = [] { std::string s; s.reserve(0xFFF); return s; }();
bool changed1 = ImGui::InputText("hex.builtin.tools.regex_replacer.pattern"_lang, regexPattern.data(), regexPattern.capacity(), ImGuiInputTextFlags_CallbackEdit, ImGui::UpdateStringSizeCallback, &regexPattern);
bool changed2 = ImGui::InputText("hex.builtin.tools.regex_replacer.replace"_lang, replacePattern.data(), replacePattern.capacity(), ImGuiInputTextFlags_CallbackEdit, ImGui::UpdateStringSizeCallback, &replacePattern);
@ -243,32 +243,32 @@ namespace hex::plugin::builtin {
ImGui::SameLine();
ImGui::NewLine();
switch (mathDisplayType) {
case MathDisplayType::Standard:
case MathDisplayType::Scientific:
case MathDisplayType::Engineering:
if (ImGui::Button("", buttonSize)) mathInput += "** 2";
ImGui::SameLine();
if (ImGui::Button("1/x", buttonSize)) mathInput += "1/";
ImGui::SameLine();
if (ImGui::Button("|x|", buttonSize)) mathInput += "abs";
ImGui::SameLine();
if (ImGui::Button("exp", buttonSize)) mathInput += "e ** ";
ImGui::SameLine();
if (ImGui::Button("%", buttonSize)) mathInput += "%";
ImGui::SameLine();
break;
case MathDisplayType::Programmer:
if (ImGui::Button("<<", buttonSize)) mathInput += "<<";
ImGui::SameLine();
if (ImGui::Button(">>", buttonSize)) mathInput += ">>";
ImGui::SameLine();
if (ImGui::Button("&", buttonSize)) mathInput += "&";
ImGui::SameLine();
if (ImGui::Button("|", buttonSize)) mathInput += "|";
ImGui::SameLine();
if (ImGui::Button("^", buttonSize)) mathInput += "^";
ImGui::SameLine();
break;
case MathDisplayType::Standard:
case MathDisplayType::Scientific:
case MathDisplayType::Engineering:
if (ImGui::Button("", buttonSize)) mathInput += "** 2";
ImGui::SameLine();
if (ImGui::Button("1/x", buttonSize)) mathInput += "1/";
ImGui::SameLine();
if (ImGui::Button("|x|", buttonSize)) mathInput += "abs";
ImGui::SameLine();
if (ImGui::Button("exp", buttonSize)) mathInput += "e ** ";
ImGui::SameLine();
if (ImGui::Button("%", buttonSize)) mathInput += "%";
ImGui::SameLine();
break;
case MathDisplayType::Programmer:
if (ImGui::Button("<<", buttonSize)) mathInput += "<<";
ImGui::SameLine();
if (ImGui::Button(">>", buttonSize)) mathInput += ">>";
ImGui::SameLine();
if (ImGui::Button("&", buttonSize)) mathInput += "&";
ImGui::SameLine();
if (ImGui::Button("|", buttonSize)) mathInput += "|";
ImGui::SameLine();
if (ImGui::Button("^", buttonSize)) mathInput += "^";
ImGui::SameLine();
break;
}
ImGui::NewLine();
if (ImGui::Button("sqrt", buttonSize)) mathInput += "sqrt";
@ -352,20 +352,20 @@ namespace hex::plugin::builtin {
ImGui::TableNextColumn();
switch (mathDisplayType) {
case MathDisplayType::Standard:
ImGui::TextFormatted("{0:.3Lf}", mathHistory[(mathHistory.size() - 1) - i]);
break;
case MathDisplayType::Scientific:
ImGui::TextFormatted("{0:.6Le}", mathHistory[(mathHistory.size() - 1) - i]);
break;
case MathDisplayType::Engineering:
ImGui::TextFormatted("{0}", hex::toEngineeringString(mathHistory[(mathHistory.size() - 1) - i]).c_str());
break;
case MathDisplayType::Programmer:
ImGui::TextFormatted("0x{0:X} ({1})",
u64(mathHistory[(mathHistory.size() - 1) - i]),
u64(mathHistory[(mathHistory.size() - 1) - i]));
break;
case MathDisplayType::Standard:
ImGui::TextFormatted("{0:.3Lf}", mathHistory[(mathHistory.size() - 1) - i]);
break;
case MathDisplayType::Scientific:
ImGui::TextFormatted("{0:.6Le}", mathHistory[(mathHistory.size() - 1) - i]);
break;
case MathDisplayType::Engineering:
ImGui::TextFormatted("{0}", hex::toEngineeringString(mathHistory[(mathHistory.size() - 1) - i]).c_str());
break;
case MathDisplayType::Programmer:
ImGui::TextFormatted("0x{0:X} ({1})",
u64(mathHistory[(mathHistory.size() - 1) - i]),
u64(mathHistory[(mathHistory.size() - 1) - i]));
break;
}
if (i == 0)
@ -392,18 +392,18 @@ namespace hex::plugin::builtin {
ImGui::TableNextColumn();
switch (mathDisplayType) {
case MathDisplayType::Standard:
ImGui::TextFormatted("{0:.3Lf}", value);
break;
case MathDisplayType::Scientific:
ImGui::TextFormatted("{0:.6Le}", value);
break;
case MathDisplayType::Engineering:
ImGui::TextFormatted("{}", hex::toEngineeringString(value));
break;
case MathDisplayType::Programmer:
ImGui::TextFormatted("0x{0:X} ({1})", u64(value), u64(value));
break;
case MathDisplayType::Standard:
ImGui::TextFormatted("{0:.3Lf}", value);
break;
case MathDisplayType::Scientific:
ImGui::TextFormatted("{0:.6Le}", value);
break;
case MathDisplayType::Engineering:
ImGui::TextFormatted("{}", hex::toEngineeringString(value));
break;
case MathDisplayType::Programmer:
ImGui::TextFormatted("0x{0:X} ({1})", u64(value), u64(value));
break;
}
}
@ -447,16 +447,16 @@ namespace hex::plugin::builtin {
static auto CharFilter = [](ImGuiInputTextCallbackData *data) -> int {
switch (*static_cast<u32 *>(data->UserData)) {
case 16:
return std::isxdigit(data->EventChar);
case 10:
return std::isdigit(data->EventChar);
case 8:
return std::isdigit(data->EventChar) && data->EventChar < '8';
case 2:
return data->EventChar == '0' || data->EventChar == '1';
default:
return false;
case 16:
return std::isxdigit(data->EventChar);
case 10:
return std::isdigit(data->EventChar);
case 8:
return std::isdigit(data->EventChar) && data->EventChar < '8';
case 2:
return data->EventChar == '0' || data->EventChar == '1';
default:
return false;
}
};
@ -465,26 +465,26 @@ namespace hex::plugin::builtin {
errno = 0;
switch (base) {
case 16:
number = std::strtoull(buffer[1], nullptr, base);
break;
case 10:
number = std::strtoull(buffer[0], nullptr, base);
break;
case 8:
number = std::strtoull(buffer[2], nullptr, base);
break;
case 2:
number = std::strtoull(buffer[3], nullptr, base);
break;
default:
return;
case 16:
number = std::strtoull(buffer[1], nullptr, base);
break;
case 10:
number = std::strtoull(buffer[0], nullptr, base);
break;
case 8:
number = std::strtoull(buffer[2], nullptr, base);
break;
case 2:
number = std::strtoull(buffer[3], nullptr, base);
break;
default:
return;
}
auto base10String = std::to_string(number);
auto base16String = hex::format("0x{0:X}", number);
auto base8String = hex::format("{0:#o}", number);
auto base2String = hex::toBinaryString(number);
auto base8String = hex::format("{0:#o}", number);
auto base2String = hex::toBinaryString(number);
std::strncpy(buffer[0], base10String.c_str(), sizeof(buffer[0]));
std::strncpy(buffer[1], base16String.c_str(), sizeof(buffer[1]));
@ -552,10 +552,10 @@ namespace hex::plugin::builtin {
ImGui::Separator();
auto result = hex::format("{}{}{}{}",
(setuid << 2) | (setgid << 1) | (sticky << 0),
(r[0] << 2) | (w[0] << 1) | (x[0] << 0),
(r[1] << 2) | (w[1] << 1) | (x[1] << 0),
(r[2] << 2) | (w[2] << 1) | (x[2] << 0));
(setuid << 2) | (setgid << 1) | (sticky << 0),
(r[0] << 2) | (w[0] << 1) | (x[0] << 0),
(r[1] << 2) | (w[1] << 1) | (x[1] << 0),
(r[2] << 2) | (w[2] << 1) | (x[2] << 0));
ImGui::InputText("##permissions_absolute", result.data(), result.size(), ImGuiInputTextFlags_ReadOnly);
ImGui::NewLine();
@ -586,7 +586,7 @@ namespace hex::plugin::builtin {
if (ImGui::Button("hex.builtin.tools.file_uploader.upload"_lang)) {
hex::openFileBrowser("hex.builtin.tools.file_uploader.done"_lang, DialogMode::Open, {}, [&](auto path) {
uploadProcess = net.uploadFile("https://api.anonfiles.com/upload", path);
currFile = path;
currFile = path;
});
}
} else {
@ -645,8 +645,8 @@ namespace hex::plugin::builtin {
try {
auto json = nlohmann::json::parse(response.body);
links.push_back({ currFile.filename().string(),
json["data"]["file"]["url"]["short"],
json["data"]["file"]["metadata"]["size"]["readable"] });
json["data"]["file"]["url"]["short"],
json["data"]["file"]["metadata"]["size"]["readable"] });
} catch (...) {
View::showErrorPopup("hex.builtin.tools.file_uploader.invalid_response"_lang);
}
@ -708,12 +708,12 @@ namespace hex::plugin::builtin {
auto json = nlohmann::json::parse(response.body);
resultTitle = json["query"]["pages"][0]["title"];
resultTitle = json["query"]["pages"][0]["title"];
resultExtract = json["query"]["pages"][0]["extract"];
if (!extendedSearch && resultExtract.ends_with(':')) {
extendedSearch = true;
searchProcess = net.getString(WikipediaApiUrl + "&titles="s + net.encode(searchString));
searchProcess = net.getString(WikipediaApiUrl + "&titles="s + net.encode(searchString));
resultTitle.clear();
resultExtract.clear();
} else {
@ -724,9 +724,9 @@ namespace hex::plugin::builtin {
resultTitle.clear();
resultExtract.clear();
extendedSearch = false;
searchProcess = {};
searchProcess = {};
resultTitle = "???";
resultTitle = "???";
resultExtract = "hex.builtin.tools.wiki_explain.invalid_response"_lang.get();
}
}
@ -734,9 +734,9 @@ namespace hex::plugin::builtin {
void drawFileToolShredder() {
static bool shredding = false;
static bool shredding = false;
static auto selectedFile = [] { std::string s; s.reserve(0x1000); return s; }();
static bool fastMode = false;
static bool fastMode = false;
ImGui::TextUnformatted("hex.builtin.tools.file_tools.shredder.warning"_lang);
ImGui::NewLine();
@ -879,11 +879,11 @@ namespace hex::plugin::builtin {
1
};
static bool splitting = false;
static auto selectedFile = [] { std::string s; s.reserve(0x1000); return s; }();
static bool splitting = false;
static auto selectedFile = [] { std::string s; s.reserve(0x1000); return s; }();
static auto baseOutputPath = [] { std::string s; s.reserve(0x1000); return s; }();
static u64 splitSize = sizes[0];
static int selectedItem = 0;
static u64 splitSize = sizes[0];
static int selectedItem = 0;
if (ImGui::BeginChild("split_settings", { 0, ImGui::GetTextLineHeightWithSpacing() * 7 }, true, ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse)) {
ImGui::BeginDisabled(splitting);
@ -1095,7 +1095,7 @@ namespace hex::plugin::builtin {
}
constexpr auto BufferSize = 0xFF'FFFF;
auto inputSize = input.getSize();
auto inputSize = input.getSize();
for (u64 inputOffset = 0; inputOffset < inputSize; inputOffset += BufferSize) {
output.write(input.readBytes(std::min<u64>(BufferSize, inputSize - inputOffset)));
output.flush();

View File

@ -33,7 +33,7 @@ namespace hex::plugin::builtin {
});
ContentRegistry::Interface::addFooterItem([] {
size_t taskCount = 0;
size_t taskCount = 0;
double taskProgress = 0.0;
std::string taskName;
@ -43,8 +43,8 @@ namespace hex::plugin::builtin {
taskCount = Task::getRunningTasks().size();
if (taskCount > 0) {
auto frontTask = Task::getRunningTasks().front();
taskProgress = frontTask->getProgress();
taskName = frontTask->getName();
taskProgress = frontTask->getProgress();
taskName = frontTask->getName();
}
}
@ -71,14 +71,14 @@ namespace hex::plugin::builtin {
if (ImGui::ToolBarButton(ICON_VS_DISCARD, ImGui::GetCustomColorVec4(ImGuiCustomCol_ToolbarBlue)))
provider->undo();
},
!ImHexApi::Provider::isValid() || !provider->canUndo());
!ImHexApi::Provider::isValid() || !provider->canUndo());
// Redo
ImGui::Disabled([&provider] {
if (ImGui::ToolBarButton(ICON_VS_REDO, ImGui::GetCustomColorVec4(ImGuiCustomCol_ToolbarBlue)))
provider->redo();
},
!ImHexApi::Provider::isValid() || !provider->canRedo());
!ImHexApi::Provider::isValid() || !provider->canRedo());
ImGui::SeparatorEx(ImGuiSeparatorFlags_Vertical);
@ -99,7 +99,7 @@ namespace hex::plugin::builtin {
if (ImGui::ToolBarButton(ICON_VS_SAVE, ImGui::GetCustomColorVec4(ImGuiCustomCol_ToolbarBlue)))
provider->save();
},
!ImHexApi::Provider::isValid() || !provider->isWritable() || !provider->isSavable());
!ImHexApi::Provider::isValid() || !provider->isWritable() || !provider->isSavable());
// Save file as
ImGui::Disabled([&provider] {
@ -108,7 +108,7 @@ namespace hex::plugin::builtin {
provider->saveAs(path);
});
},
!ImHexApi::Provider::isValid() || !provider->isSavable());
!ImHexApi::Provider::isValid() || !provider->isSavable());
ImGui::SeparatorEx(ImGuiSeparatorFlags_Vertical);
@ -123,7 +123,7 @@ namespace hex::plugin::builtin {
ImHexApi::Bookmarks::add(region.address, region.size, {}, {});
}
},
!ImHexApi::Provider::isValid() || !provider->isReadable());
!ImHexApi::Provider::isValid() || !provider->isReadable());
ImGui::SeparatorEx(ImGuiSeparatorFlags_Vertical);
@ -149,7 +149,7 @@ namespace hex::plugin::builtin {
ImGui::EndCombo();
}
},
!ImHexApi::Provider::isValid());
!ImHexApi::Provider::isValid());
});
}

View File

@ -19,15 +19,13 @@ namespace hex::plugin::builtin {
color = ImGui::GetColorU32(ImGuiCol_Header);
this->m_bookmarks.push_back({
region,
this->m_bookmarks.push_back({ region,
name,
std::move(comment),
color,
false,
ImHexApi::HexEditor::addHighlight(region, color, name)
});
ImHexApi::HexEditor::addHighlight(region, color, name) });
ProjectFile::markDirty();
});
@ -62,13 +60,13 @@ namespace hex::plugin::builtin {
ImGui::TextFormattedCentered("hex.builtin.view.bookmarks.no_bookmarks"_lang);
}
u32 id = 1;
u32 id = 1;
auto bookmarkToRemove = this->m_bookmarks.end();
for (auto iter = this->m_bookmarks.begin(); iter != this->m_bookmarks.end(); iter++) {
auto &[region, name, comment, color, locked, highlight] = *iter;
auto headerColor = ImColor(color);
auto hoverColor = ImColor(color);
auto hoverColor = ImColor(color);
hoverColor.Value.w *= 1.3F;
ImGui::PushID(id);
@ -95,7 +93,7 @@ namespace hex::plugin::builtin {
// First line
{
std::array<u8, 0x10> bytes = { 0 };
size_t byteCount = std::min<size_t>(0x10 - offset, region.size);
size_t byteCount = std::min<size_t>(0x10 - offset, region.size);
ImHexApi::Provider::get()->read(region.address, bytes.data() + offset, byteCount);
for (size_t byte = 0; byte < 0x10; byte++) {

View File

@ -12,7 +12,7 @@ namespace hex::plugin::builtin {
ShortcutManager::addGlobalShortcut(CTRL + SHIFT + Keys::P, [this] {
EventManager::post<RequestOpenPopup>("hex.builtin.view.command_palette.name"_lang);
this->m_commandPaletteOpen = true;
this->m_justOpened = true;
this->m_justOpened = true;
});
}
@ -23,7 +23,7 @@ namespace hex::plugin::builtin {
if (!this->m_commandPaletteOpen) return;
auto windowPos = ImHexApi::System::getMainWindowPosition();
auto windowPos = ImHexApi::System::getMainWindowPosition();
auto windowSize = ImHexApi::System::getMainWindowSize();
ImGui::SetNextWindowPos(ImVec2(windowPos.x + windowSize.x * 0.5F, windowPos.y), ImGuiCond_Always, ImVec2(0.5F, 0.0F));
@ -34,7 +34,7 @@ namespace hex::plugin::builtin {
ImGui::PushItemWidth(-1);
if (ImGui::InputText(
"##command_input", this->m_commandBuffer.data(), this->m_commandBuffer.size(), ImGuiInputTextFlags_CallbackEdit | ImGuiInputTextFlags_EnterReturnsTrue, [](ImGuiInputTextCallbackData *callbackData) -> int {
auto _this = static_cast<ViewCommandPalette *>(callbackData->UserData);
auto _this = static_cast<ViewCommandPalette *>(callbackData->UserData);
_this->m_lastResults = _this->getCommandResults(callbackData->Buf);
return 0;

View File

@ -37,7 +37,7 @@ namespace hex::plugin::builtin {
for (auto value : content["values"]) {
Constant constant;
constant.category = content["name"];
constant.name = value["name"];
constant.name = value["name"];
if (value.contains("desc"))
constant.description = value["desc"];
constant.value = value["value"];

View File

@ -17,7 +17,7 @@ namespace hex::plugin::builtin {
if (!ImHexApi::Provider::isValid() || region.address == (size_t)-1) {
this->m_validBytes = 0;
} else {
this->m_validBytes = u64(provider->getSize() - region.address);
this->m_validBytes = u64(provider->getSize() - region.address);
this->m_startAddress = region.address;
}
@ -83,32 +83,32 @@ namespace hex::plugin::builtin {
ImGui::NewLine();
if (ImGui::RadioButton("hex.common.little_endian"_lang, this->m_endian == std::endian::little)) {
this->m_endian = std::endian::little;
this->m_endian = std::endian::little;
this->m_shouldInvalidate = true;
}
ImGui::SameLine();
if (ImGui::RadioButton("hex.common.big_endian"_lang, this->m_endian == std::endian::big)) {
this->m_endian = std::endian::big;
this->m_endian = std::endian::big;
this->m_shouldInvalidate = true;
}
if (ImGui::RadioButton("hex.common.decimal"_lang, this->m_numberDisplayStyle == NumberDisplayStyle::Decimal)) {
this->m_numberDisplayStyle = NumberDisplayStyle::Decimal;
this->m_shouldInvalidate = true;
this->m_shouldInvalidate = true;
}
ImGui::SameLine();
if (ImGui::RadioButton("hex.common.hexadecimal"_lang, this->m_numberDisplayStyle == NumberDisplayStyle::Hexadecimal)) {
this->m_numberDisplayStyle = NumberDisplayStyle::Hexadecimal;
this->m_shouldInvalidate = true;
this->m_shouldInvalidate = true;
}
ImGui::SameLine();
if (ImGui::RadioButton("hex.common.octal"_lang, this->m_numberDisplayStyle == NumberDisplayStyle::Octal)) {
this->m_numberDisplayStyle = NumberDisplayStyle::Octal;
this->m_shouldInvalidate = true;
this->m_shouldInvalidate = true;
}
} else {
std::string text = "hex.builtin.view.data_inspector.no_data"_lang;
auto textSize = ImGui::CalcTextSize(text.c_str());
std::string text = "hex.builtin.view.data_inspector.no_data"_lang;
auto textSize = ImGui::CalcTextSize(text.c_str());
auto availableSpace = ImGui::GetContentRegionAvail();
ImGui::SetCursorPos((availableSpace - textSize) / 2.0F);

View File

@ -15,16 +15,16 @@ namespace hex::plugin::builtin {
ViewDataProcessor::ViewDataProcessor() : View("hex.builtin.view.data_processor.name") {
EventManager::subscribe<RequestChangeTheme>(this, [](u32 theme) {
switch (theme) {
default:
case 1: /* Dark theme */
ImNodes::StyleColorsDark();
break;
case 2: /* Light theme */
ImNodes::StyleColorsLight();
break;
case 3: /* Classic theme */
ImNodes::StyleColorsClassic();
break;
default:
case 1: /* Dark theme */
ImNodes::StyleColorsDark();
break;
case 2: /* Light theme */
ImNodes::StyleColorsLight();
break;
case 3: /* Classic theme */
ImNodes::StyleColorsClassic();
break;
}
ImNodes::GetStyle().Flags = ImNodesStyleFlags_NodeOutline | ImNodesStyleFlags_GridLines;
@ -53,22 +53,22 @@ namespace hex::plugin::builtin {
hex::openFileBrowser("hex.builtin.view.data_processor.menu.file.load_processor"_lang, DialogMode::Open, {
{"hex.builtin.view.data_processor.name"_lang, "hexnode"}
},
[this](const fs::path &path) {
File file(path, File::Mode::Read);
if (file.isValid())
this->loadNodes(file.readString());
});
[this](const fs::path &path) {
File file(path, File::Mode::Read);
if (file.isValid())
this->loadNodes(file.readString());
});
}
if (ImGui::MenuItem("hex.builtin.view.data_processor.menu.file.save_processor"_lang, nullptr, false, !this->m_nodes.empty())) {
hex::openFileBrowser("hex.builtin.view.data_processor.menu.file.save_processor"_lang, DialogMode::Save, {
{"hex.builtin.view.data_processor.name"_lang, "hexnode"}
},
[this](const fs::path &path) {
File file(path, File::Mode::Create);
if (file.isValid())
file.write(this->saveNodes());
});
[this](const fs::path &path) {
File file(path, File::Mode::Create);
if (file.isValid())
file.write(this->saveNodes());
});
}
});
}
@ -228,7 +228,7 @@ namespace hex::plugin::builtin {
this->m_nodes.push_back(node);
bool hasOutput = false;
bool hasInput = false;
bool hasInput = false;
for (auto &attr : node->getAttributes()) {
if (attr.getIOType() == dp::Attribute::IOType::Out)
hasOutput = true;
@ -291,15 +291,15 @@ namespace hex::plugin::builtin {
ImNodesPinShape pinShape;
switch (attribute.getType()) {
case dp::Attribute::Type::Integer:
pinShape = ImNodesPinShape_Circle;
break;
case dp::Attribute::Type::Float:
pinShape = ImNodesPinShape_Triangle;
break;
case dp::Attribute::Type::Buffer:
pinShape = ImNodesPinShape_Quad;
break;
case dp::Attribute::Type::Integer:
pinShape = ImNodesPinShape_Circle;
break;
case dp::Attribute::Type::Float:
pinShape = ImNodesPinShape_Triangle;
break;
case dp::Attribute::Type::Buffer:
pinShape = ImNodesPinShape_Quad;
break;
}
if (attribute.getIOType() == dp::Attribute::IOType::In) {
@ -403,17 +403,17 @@ namespace hex::plugin::builtin {
output["nodes"] = json::object();
for (auto &node : this->m_nodes) {
auto id = node->getId();
auto id = node->getId();
auto &currNodeOutput = output["nodes"][std::to_string(id)];
auto pos = ImNodes::GetNodeGridSpacePos(id);
auto pos = ImNodes::GetNodeGridSpacePos(id);
currNodeOutput["type"] = node->getUnlocalizedName();
currNodeOutput["pos"] = {
currNodeOutput["pos"] = {
{"x", pos.x},
{ "y", pos.y}
};
currNodeOutput["attrs"] = json::array();
currNodeOutput["id"] = id;
currNodeOutput["id"] = id;
json nodeData;
node->store(nodeData);
@ -428,12 +428,12 @@ namespace hex::plugin::builtin {
output["links"] = json::object();
for (auto &link : this->m_links) {
auto id = link.getId();
auto id = link.getId();
auto &currOutput = output["links"][std::to_string(id)];
currOutput["id"] = id;
currOutput["id"] = id;
currOutput["from"] = link.getFromId();
currOutput["to"] = link.getToId();
currOutput["to"] = link.getToId();
}
return output.dump();
@ -467,13 +467,13 @@ namespace hex::plugin::builtin {
continue;
u32 nodeId = node["id"];
maxNodeId = std::max(nodeId, maxNodeId);
maxNodeId = std::max(nodeId, maxNodeId);
newNode->setId(nodeId);
bool hasOutput = false;
bool hasInput = false;
u32 attrIndex = 0;
bool hasInput = false;
u32 attrIndex = 0;
for (auto &attr : newNode->getAttributes()) {
if (attr.getIOType() == dp::Attribute::IOType::Out)
hasOutput = true;
@ -482,7 +482,7 @@ namespace hex::plugin::builtin {
hasInput = true;
u32 attrId = node["attrs"][attrIndex];
maxAttrId = std::max(attrId, maxAttrId);
maxAttrId = std::max(attrId, maxAttrId);
attr.setId(attrId);
attrIndex++;
@ -502,7 +502,7 @@ namespace hex::plugin::builtin {
dp::Link newLink(link["from"], link["to"]);
u32 linkId = link["id"];
maxLinkId = std::max(linkId, maxLinkId);
maxLinkId = std::max(linkId, maxLinkId);
newLink.setID(linkId);
this->m_links.push_back(newLink);

View File

@ -113,7 +113,7 @@ namespace hex::plugin::builtin {
ImDrawList *drawList = ImGui::GetWindowDrawList();
auto glyphWidth = ImGui::CalcTextSize("0").x + 1;
auto glyphWidth = ImGui::CalcTextSize("0").x + 1;
static auto highlightSize = ImGui::CalcTextSize("00");
auto startY = ImGui::GetCursorPosY();
@ -122,7 +122,7 @@ namespace hex::plugin::builtin {
ImGui::SetCursorPosY(startY);
ImGui::TableNextColumn();
const ImColor colorText = ImGui::GetColorU32(ImGuiCol_Text);
const ImColor colorText = ImGui::GetColorU32(ImGuiCol_Text);
const ImColor colorDisabled = this->m_greyedOutZeros ? ImGui::GetColorU32(ImGuiCol_TextDisabled) : static_cast<u32>(colorText);
@ -137,19 +137,19 @@ namespace hex::plugin::builtin {
// Diff bytes
std::optional<u32> highlightColor;
switch (diffBytes(col, lineInfo[curr], lineInfo[other])) {
default:
case DiffResult::Same:
/* No highlight */
break;
case DiffResult::Changed:
highlightColor = getDiffColor(ImGui::GetCustomColorU32(ImGuiCustomCol_ToolbarYellow));
break;
case DiffResult::Added:
highlightColor = getDiffColor(ImGui::GetCustomColorU32(ImGuiCustomCol_ToolbarGreen));
break;
case DiffResult::Removed:
highlightColor = getDiffColor(ImGui::GetCustomColorU32(ImGuiCustomCol_ToolbarRed));
break;
default:
case DiffResult::Same:
/* No highlight */
break;
case DiffResult::Changed:
highlightColor = getDiffColor(ImGui::GetCustomColorU32(ImGuiCustomCol_ToolbarYellow));
break;
case DiffResult::Added:
highlightColor = getDiffColor(ImGui::GetCustomColorU32(ImGuiCustomCol_ToolbarGreen));
break;
case DiffResult::Removed:
highlightColor = getDiffColor(ImGui::GetCustomColorU32(ImGuiCustomCol_ToolbarRed));
break;
}
// Draw byte

View File

@ -70,13 +70,13 @@ namespace hex::plugin::builtin {
u64 usedBytes = 0;
for (u32 i = 0; i < instructionCount; i++) {
const auto &instr = instructions[i];
const auto &instr = instructions[i];
Disassembly disassembly = { 0 };
disassembly.address = instr.address;
disassembly.offset = this->m_codeRegion[0] + address + usedBytes;
disassembly.size = instr.size;
disassembly.mnemonic = instr.mnemonic;
disassembly.operators = instr.op_str;
disassembly.address = instr.address;
disassembly.offset = this->m_codeRegion[0] + address + usedBytes;
disassembly.size = instr.size;
disassembly.mnemonic = instr.mnemonic;
disassembly.operators = instr.op_str;
for (u16 j = 0; j < instr.size; j++)
disassembly.bytes += hex::format("{0:02X} ", instr.bytes[j]);
@ -136,178 +136,188 @@ namespace hex::plugin::builtin {
ImGui::NewLine();
switch (this->m_architecture) {
case Architecture::ARM: {
static int mode = CS_MODE_ARM;
ImGui::RadioButton("hex.builtin.view.disassembler.arm.arm"_lang, &mode, CS_MODE_ARM);
ImGui::SameLine();
ImGui::RadioButton("hex.builtin.view.disassembler.arm.thumb"_lang, &mode, CS_MODE_THUMB);
case Architecture::ARM:
{
static int mode = CS_MODE_ARM;
ImGui::RadioButton("hex.builtin.view.disassembler.arm.arm"_lang, &mode, CS_MODE_ARM);
ImGui::SameLine();
ImGui::RadioButton("hex.builtin.view.disassembler.arm.thumb"_lang, &mode, CS_MODE_THUMB);
static int extraMode = 0;
ImGui::RadioButton("hex.builtin.view.disassembler.arm.default"_lang, &extraMode, 0);
ImGui::SameLine();
ImGui::RadioButton("hex.builtin.view.disassembler.arm.cortex_m"_lang, &extraMode, CS_MODE_MCLASS);
ImGui::SameLine();
ImGui::RadioButton("hex.builtin.view.disassembler.arm.armv8"_lang, &extraMode, CS_MODE_V8);
static int extraMode = 0;
ImGui::RadioButton("hex.builtin.view.disassembler.arm.default"_lang, &extraMode, 0);
ImGui::SameLine();
ImGui::RadioButton("hex.builtin.view.disassembler.arm.cortex_m"_lang, &extraMode, CS_MODE_MCLASS);
ImGui::SameLine();
ImGui::RadioButton("hex.builtin.view.disassembler.arm.armv8"_lang, &extraMode, CS_MODE_V8);
this->m_mode = cs_mode(mode | extraMode);
}
break;
case Architecture::MIPS: {
static int mode = CS_MODE_MIPS32;
ImGui::RadioButton("hex.builtin.view.disassembler.mips.mips32"_lang, &mode, CS_MODE_MIPS32);
ImGui::SameLine();
ImGui::RadioButton("hex.builtin.view.disassembler.mips.mips64"_lang, &mode, CS_MODE_MIPS64);
ImGui::SameLine();
ImGui::RadioButton("hex.builtin.view.disassembler.mips.mips32R6"_lang, &mode, CS_MODE_MIPS32R6);
ImGui::RadioButton("hex.builtin.view.disassembler.mips.mips2"_lang, &mode, CS_MODE_MIPS2);
ImGui::SameLine();
ImGui::RadioButton("hex.builtin.view.disassembler.mips.mips3"_lang, &mode, CS_MODE_MIPS3);
static bool microMode;
ImGui::Checkbox("hex.builtin.view.disassembler.mips.micro"_lang, &microMode);
this->m_mode = cs_mode(mode | (microMode ? CS_MODE_MICRO : 0));
}
break;
case Architecture::X86: {
static int mode = CS_MODE_32;
ImGui::RadioButton("hex.builtin.view.disassembler.16bit"_lang, &mode, CS_MODE_16);
ImGui::SameLine();
ImGui::RadioButton("hex.builtin.view.disassembler.32bit"_lang, &mode, CS_MODE_32);
ImGui::SameLine();
ImGui::RadioButton("hex.builtin.view.disassembler.64bit"_lang, &mode, CS_MODE_64);
this->m_mode = cs_mode(mode);
}
break;
case Architecture::PPC: {
static int mode = CS_MODE_32;
ImGui::RadioButton("hex.builtin.view.disassembler.32bit"_lang, &mode, CS_MODE_32);
ImGui::SameLine();
ImGui::RadioButton("hex.builtin.view.disassembler.64bit"_lang, &mode, CS_MODE_64);
static bool qpx = false;
ImGui::Checkbox("hex.builtin.view.disassembler.ppc.qpx"_lang, &qpx);
static bool spe = false;
ImGui::Checkbox("hex.builtin.view.disassembler.ppc.spe"_lang, &spe);
static bool booke = false;
ImGui::Checkbox("hex.builtin.view.disassembler.ppc.booke"_lang, &booke);
this->m_mode = cs_mode(mode | (qpx ? CS_MODE_QPX : 0) | (spe ? CS_MODE_SPE : 0) | (booke ? CS_MODE_BOOKE : 0));
}
break;
case Architecture::SPARC: {
static bool v9Mode = false;
ImGui::Checkbox("hex.builtin.view.disassembler.sparc.v9"_lang, &v9Mode);
this->m_mode = cs_mode(v9Mode ? CS_MODE_V9 : 0);
}
break;
case Architecture::RISCV: {
static int mode = CS_MODE_RISCV32;
ImGui::RadioButton("hex.builtin.view.disassembler.32bit"_lang, &mode, CS_MODE_RISCV32);
ImGui::SameLine();
ImGui::RadioButton("hex.builtin.view.disassembler.64bit"_lang, &mode, CS_MODE_RISCV64);
static bool compressed = false;
ImGui::Checkbox("hex.builtin.view.disassembler.riscv.compressed"_lang, &compressed);
this->m_mode = cs_mode(mode | (compressed ? CS_MODE_RISCVC : 0));
}
break;
case Architecture::M68K: {
static int selectedMode = 0;
std::pair<const char*, cs_mode> modes[] = {
{ "hex.builtin.view.disassembler.m68k.000"_lang, CS_MODE_M68K_000 },
{ "hex.builtin.view.disassembler.m68k.010"_lang, CS_MODE_M68K_010 },
{ "hex.builtin.view.disassembler.m68k.020"_lang, CS_MODE_M68K_020 },
{ "hex.builtin.view.disassembler.m68k.030"_lang, CS_MODE_M68K_030 },
{ "hex.builtin.view.disassembler.m68k.040"_lang, CS_MODE_M68K_040 },
{ "hex.builtin.view.disassembler.m68k.060"_lang, CS_MODE_M68K_060 },
};
if (ImGui::BeginCombo("hex.builtin.view.disassembler.settings.mode"_lang, modes[selectedMode].first)) {
for (u32 i = 0; i < IM_ARRAYSIZE(modes); i++) {
if (ImGui::Selectable(modes[i].first))
selectedMode = i;
}
ImGui::EndCombo();
this->m_mode = cs_mode(mode | extraMode);
}
break;
case Architecture::MIPS:
{
static int mode = CS_MODE_MIPS32;
ImGui::RadioButton("hex.builtin.view.disassembler.mips.mips32"_lang, &mode, CS_MODE_MIPS32);
ImGui::SameLine();
ImGui::RadioButton("hex.builtin.view.disassembler.mips.mips64"_lang, &mode, CS_MODE_MIPS64);
ImGui::SameLine();
ImGui::RadioButton("hex.builtin.view.disassembler.mips.mips32R6"_lang, &mode, CS_MODE_MIPS32R6);
this->m_mode = cs_mode(modes[selectedMode].second);
}
break;
case Architecture::M680X: {
static int selectedMode = 0;
ImGui::RadioButton("hex.builtin.view.disassembler.mips.mips2"_lang, &mode, CS_MODE_MIPS2);
ImGui::SameLine();
ImGui::RadioButton("hex.builtin.view.disassembler.mips.mips3"_lang, &mode, CS_MODE_MIPS3);
std::pair<const char*, cs_mode> modes[] = {
{ "hex.builtin.view.disassembler.m680x.6301"_lang, CS_MODE_M680X_6301 },
{ "hex.builtin.view.disassembler.m680x.6309"_lang, CS_MODE_M680X_6309 },
{ "hex.builtin.view.disassembler.m680x.6800"_lang, CS_MODE_M680X_6800 },
{ "hex.builtin.view.disassembler.m680x.6801"_lang, CS_MODE_M680X_6801 },
{ "hex.builtin.view.disassembler.m680x.6805"_lang, CS_MODE_M680X_6805 },
{ "hex.builtin.view.disassembler.m680x.6808"_lang, CS_MODE_M680X_6808 },
{ "hex.builtin.view.disassembler.m680x.6809"_lang, CS_MODE_M680X_6809 },
{ "hex.builtin.view.disassembler.m680x.6811"_lang, CS_MODE_M680X_6811 },
{ "hex.builtin.view.disassembler.m680x.cpu12"_lang, CS_MODE_M680X_CPU12 },
{ "hex.builtin.view.disassembler.m680x.hcs08"_lang, CS_MODE_M680X_HCS08 },
};
static bool microMode;
ImGui::Checkbox("hex.builtin.view.disassembler.mips.micro"_lang, &microMode);
if (ImGui::BeginCombo("hex.builtin.view.disassembler.settings.mode"_lang, modes[selectedMode].first)) {
for (u32 i = 0; i < IM_ARRAYSIZE(modes); i++) {
if (ImGui::Selectable(modes[i].first))
selectedMode = i;
}
ImGui::EndCombo();
this->m_mode = cs_mode(mode | (microMode ? CS_MODE_MICRO : 0));
}
break;
case Architecture::X86:
{
static int mode = CS_MODE_32;
ImGui::RadioButton("hex.builtin.view.disassembler.16bit"_lang, &mode, CS_MODE_16);
ImGui::SameLine();
ImGui::RadioButton("hex.builtin.view.disassembler.32bit"_lang, &mode, CS_MODE_32);
ImGui::SameLine();
ImGui::RadioButton("hex.builtin.view.disassembler.64bit"_lang, &mode, CS_MODE_64);
this->m_mode = cs_mode(modes[selectedMode].second);
}
break;
case Architecture::MOS65XX: {
static int selectedMode = 0;
std::pair<const char*, cs_mode> modes[] = {
{ "hex.builtin.view.disassembler.mos65xx.6502"_lang, CS_MODE_MOS65XX_6502 },
{ "hex.builtin.view.disassembler.mos65xx.65c02"_lang, CS_MODE_MOS65XX_65C02 },
{ "hex.builtin.view.disassembler.mos65xx.w65c02"_lang, CS_MODE_MOS65XX_W65C02 },
{ "hex.builtin.view.disassembler.mos65xx.65816"_lang, CS_MODE_MOS65XX_65816 },
{ "hex.builtin.view.disassembler.mos65xx.65816_long_m"_lang, CS_MODE_MOS65XX_65816_LONG_M },
{ "hex.builtin.view.disassembler.mos65xx.65816_long_x"_lang, CS_MODE_MOS65XX_65816_LONG_X },
{ "hex.builtin.view.disassembler.mos65xx.65816_long_mx"_lang, CS_MODE_MOS65XX_65816_LONG_MX },
};
if (ImGui::BeginCombo("hex.builtin.view.disassembler.settings.mode"_lang, modes[selectedMode].first)) {
for (u32 i = 0; i < IM_ARRAYSIZE(modes); i++) {
if (ImGui::Selectable(modes[i].first))
selectedMode = i;
}
ImGui::EndCombo();
this->m_mode = cs_mode(mode);
}
break;
case Architecture::PPC:
{
static int mode = CS_MODE_32;
ImGui::RadioButton("hex.builtin.view.disassembler.32bit"_lang, &mode, CS_MODE_32);
ImGui::SameLine();
ImGui::RadioButton("hex.builtin.view.disassembler.64bit"_lang, &mode, CS_MODE_64);
this->m_mode = cs_mode(modes[selectedMode].second);
}
break;
case Architecture::BPF: {
static int mode = CS_MODE_BPF_CLASSIC;
ImGui::RadioButton("hex.builtin.view.disassembler.bpf.classic"_lang, &mode, CS_MODE_BPF_CLASSIC);
ImGui::SameLine();
ImGui::RadioButton("hex.builtin.view.disassembler.bpf.extended"_lang, &mode, CS_MODE_BPF_EXTENDED);
static bool qpx = false;
ImGui::Checkbox("hex.builtin.view.disassembler.ppc.qpx"_lang, &qpx);
static bool spe = false;
ImGui::Checkbox("hex.builtin.view.disassembler.ppc.spe"_lang, &spe);
static bool booke = false;
ImGui::Checkbox("hex.builtin.view.disassembler.ppc.booke"_lang, &booke);
this->m_mode = cs_mode(mode);
}
break;
case Architecture::EVM:
case Architecture::TMS320C64X:
case Architecture::ARM64:
case Architecture::SYSZ:
case Architecture::XCORE:
case Architecture::WASM:
case Architecture::MAX:
this->m_mode = cs_mode(0);
break;
this->m_mode = cs_mode(mode | (qpx ? CS_MODE_QPX : 0) | (spe ? CS_MODE_SPE : 0) | (booke ? CS_MODE_BOOKE : 0));
}
break;
case Architecture::SPARC:
{
static bool v9Mode = false;
ImGui::Checkbox("hex.builtin.view.disassembler.sparc.v9"_lang, &v9Mode);
this->m_mode = cs_mode(v9Mode ? CS_MODE_V9 : 0);
}
break;
case Architecture::RISCV:
{
static int mode = CS_MODE_RISCV32;
ImGui::RadioButton("hex.builtin.view.disassembler.32bit"_lang, &mode, CS_MODE_RISCV32);
ImGui::SameLine();
ImGui::RadioButton("hex.builtin.view.disassembler.64bit"_lang, &mode, CS_MODE_RISCV64);
static bool compressed = false;
ImGui::Checkbox("hex.builtin.view.disassembler.riscv.compressed"_lang, &compressed);
this->m_mode = cs_mode(mode | (compressed ? CS_MODE_RISCVC : 0));
}
break;
case Architecture::M68K:
{
static int selectedMode = 0;
std::pair<const char *, cs_mode> modes[] = {
{"hex.builtin.view.disassembler.m68k.000"_lang, CS_MODE_M68K_000},
{ "hex.builtin.view.disassembler.m68k.010"_lang, CS_MODE_M68K_010},
{ "hex.builtin.view.disassembler.m68k.020"_lang, CS_MODE_M68K_020},
{ "hex.builtin.view.disassembler.m68k.030"_lang, CS_MODE_M68K_030},
{ "hex.builtin.view.disassembler.m68k.040"_lang, CS_MODE_M68K_040},
{ "hex.builtin.view.disassembler.m68k.060"_lang, CS_MODE_M68K_060},
};
if (ImGui::BeginCombo("hex.builtin.view.disassembler.settings.mode"_lang, modes[selectedMode].first)) {
for (u32 i = 0; i < IM_ARRAYSIZE(modes); i++) {
if (ImGui::Selectable(modes[i].first))
selectedMode = i;
}
ImGui::EndCombo();
}
this->m_mode = cs_mode(modes[selectedMode].second);
}
break;
case Architecture::M680X:
{
static int selectedMode = 0;
std::pair<const char *, cs_mode> modes[] = {
{"hex.builtin.view.disassembler.m680x.6301"_lang, CS_MODE_M680X_6301 },
{ "hex.builtin.view.disassembler.m680x.6309"_lang, CS_MODE_M680X_6309 },
{ "hex.builtin.view.disassembler.m680x.6800"_lang, CS_MODE_M680X_6800 },
{ "hex.builtin.view.disassembler.m680x.6801"_lang, CS_MODE_M680X_6801 },
{ "hex.builtin.view.disassembler.m680x.6805"_lang, CS_MODE_M680X_6805 },
{ "hex.builtin.view.disassembler.m680x.6808"_lang, CS_MODE_M680X_6808 },
{ "hex.builtin.view.disassembler.m680x.6809"_lang, CS_MODE_M680X_6809 },
{ "hex.builtin.view.disassembler.m680x.6811"_lang, CS_MODE_M680X_6811 },
{ "hex.builtin.view.disassembler.m680x.cpu12"_lang, CS_MODE_M680X_CPU12},
{ "hex.builtin.view.disassembler.m680x.hcs08"_lang, CS_MODE_M680X_HCS08},
};
if (ImGui::BeginCombo("hex.builtin.view.disassembler.settings.mode"_lang, modes[selectedMode].first)) {
for (u32 i = 0; i < IM_ARRAYSIZE(modes); i++) {
if (ImGui::Selectable(modes[i].first))
selectedMode = i;
}
ImGui::EndCombo();
}
this->m_mode = cs_mode(modes[selectedMode].second);
}
break;
case Architecture::MOS65XX:
{
static int selectedMode = 0;
std::pair<const char *, cs_mode> modes[] = {
{"hex.builtin.view.disassembler.mos65xx.6502"_lang, CS_MODE_MOS65XX_6502 },
{ "hex.builtin.view.disassembler.mos65xx.65c02"_lang, CS_MODE_MOS65XX_65C02 },
{ "hex.builtin.view.disassembler.mos65xx.w65c02"_lang, CS_MODE_MOS65XX_W65C02 },
{ "hex.builtin.view.disassembler.mos65xx.65816"_lang, CS_MODE_MOS65XX_65816 },
{ "hex.builtin.view.disassembler.mos65xx.65816_long_m"_lang, CS_MODE_MOS65XX_65816_LONG_M },
{ "hex.builtin.view.disassembler.mos65xx.65816_long_x"_lang, CS_MODE_MOS65XX_65816_LONG_X },
{ "hex.builtin.view.disassembler.mos65xx.65816_long_mx"_lang, CS_MODE_MOS65XX_65816_LONG_MX},
};
if (ImGui::BeginCombo("hex.builtin.view.disassembler.settings.mode"_lang, modes[selectedMode].first)) {
for (u32 i = 0; i < IM_ARRAYSIZE(modes); i++) {
if (ImGui::Selectable(modes[i].first))
selectedMode = i;
}
ImGui::EndCombo();
}
this->m_mode = cs_mode(modes[selectedMode].second);
}
break;
case Architecture::BPF:
{
static int mode = CS_MODE_BPF_CLASSIC;
ImGui::RadioButton("hex.builtin.view.disassembler.bpf.classic"_lang, &mode, CS_MODE_BPF_CLASSIC);
ImGui::SameLine();
ImGui::RadioButton("hex.builtin.view.disassembler.bpf.extended"_lang, &mode, CS_MODE_BPF_EXTENDED);
this->m_mode = cs_mode(mode);
}
break;
case Architecture::EVM:
case Architecture::TMS320C64X:
case Architecture::ARM64:
case Architecture::SYSZ:
case Architecture::XCORE:
case Architecture::WASM:
case Architecture::MAX:
this->m_mode = cs_mode(0);
break;
}
}
ImGui::EndChild();
@ -316,7 +326,7 @@ namespace hex::plugin::builtin {
if (ImGui::Button("hex.builtin.view.disassembler.disassemble"_lang))
this->disassemble();
},
this->m_disassembling);
this->m_disassembling);
if (this->m_disassembling) {
ImGui::SameLine();

View File

@ -81,208 +81,208 @@ namespace hex::plugin::builtin {
switch (hashFunctionNames[this->m_currHashFunction].first) {
case HashFunctions::Crc8:
{
static int polynomial = 0x07, init = 0x0000, xorout = 0x0000;
static bool reflectIn = false, reflectOut = false;
case HashFunctions::Crc8:
{
static int polynomial = 0x07, init = 0x0000, xorout = 0x0000;
static bool reflectIn = false, reflectOut = false;
ImGui::InputInt("hex.builtin.view.hashes.iv"_lang, &init, 0, 0, ImGuiInputTextFlags_CharsHexadecimal);
if (ImGui::IsItemEdited()) this->m_shouldInvalidate = true;
ImGui::InputInt("hex.builtin.view.hashes.iv"_lang, &init, 0, 0, ImGuiInputTextFlags_CharsHexadecimal);
if (ImGui::IsItemEdited()) this->m_shouldInvalidate = true;
ImGui::InputInt("hex.builtin.view.hashes.xorout"_lang, &xorout, 0, 0, ImGuiInputTextFlags_CharsHexadecimal);
if (ImGui::IsItemEdited()) this->m_shouldInvalidate = true;
ImGui::InputInt("hex.builtin.view.hashes.xorout"_lang, &xorout, 0, 0, ImGuiInputTextFlags_CharsHexadecimal);
if (ImGui::IsItemEdited()) this->m_shouldInvalidate = true;
ImGui::Checkbox("hex.common.reflectIn"_lang, &reflectIn);
if (ImGui::IsItemEdited()) this->m_shouldInvalidate = true;
ImGui::Checkbox("hex.common.reflectIn"_lang, &reflectIn);
if (ImGui::IsItemEdited()) this->m_shouldInvalidate = true;
ImGui::Checkbox("hex.common.reflectOut"_lang, &reflectOut);
if (ImGui::IsItemEdited()) this->m_shouldInvalidate = true;
ImGui::Checkbox("hex.common.reflectOut"_lang, &reflectOut);
if (ImGui::IsItemEdited()) this->m_shouldInvalidate = true;
ImGui::InputInt("hex.builtin.view.hashes.poly"_lang, &polynomial, 0, 0, ImGuiInputTextFlags_CharsHexadecimal);
if (ImGui::IsItemEdited()) this->m_shouldInvalidate = true;
ImGui::InputInt("hex.builtin.view.hashes.poly"_lang, &polynomial, 0, 0, ImGuiInputTextFlags_CharsHexadecimal);
if (ImGui::IsItemEdited()) this->m_shouldInvalidate = true;
ImGui::NewLine();
ImGui::NewLine();
static u8 result = 0;
static u8 result = 0;
if (this->m_shouldInvalidate)
result = crypt::crc8(provider, this->m_hashRegion[0], this->m_hashRegion[1], polynomial, init, xorout, reflectIn, reflectOut);
if (this->m_shouldInvalidate)
result = crypt::crc8(provider, this->m_hashRegion[0], this->m_hashRegion[1], polynomial, init, xorout, reflectIn, reflectOut);
char buffer[sizeof(result) * 2 + 1];
snprintf(buffer, sizeof(buffer), "%02X", result);
char buffer[sizeof(result) * 2 + 1];
snprintf(buffer, sizeof(buffer), "%02X", result);
ImGui::TextUnformatted("hex.builtin.view.hashes.result"_lang);
ImGui::Separator();
ImGui::InputText("##nolabel", buffer, ImGuiInputTextFlags_ReadOnly);
}
break;
case HashFunctions::Crc16:
{
static int polynomial = 0x8005, init = 0x0000, xorout = 0x0000;
static bool reflectIn = false, reflectOut = false;
ImGui::TextUnformatted("hex.builtin.view.hashes.result"_lang);
ImGui::Separator();
ImGui::InputText("##nolabel", buffer, ImGuiInputTextFlags_ReadOnly);
}
break;
case HashFunctions::Crc16:
{
static int polynomial = 0x8005, init = 0x0000, xorout = 0x0000;
static bool reflectIn = false, reflectOut = false;
ImGui::InputInt("hex.builtin.view.hashes.iv"_lang, &init, 0, 0, ImGuiInputTextFlags_CharsHexadecimal);
if (ImGui::IsItemEdited()) this->m_shouldInvalidate = true;
ImGui::InputInt("hex.builtin.view.hashes.iv"_lang, &init, 0, 0, ImGuiInputTextFlags_CharsHexadecimal);
if (ImGui::IsItemEdited()) this->m_shouldInvalidate = true;
ImGui::InputInt("hex.builtin.view.hashes.xorout"_lang, &xorout, 0, 0, ImGuiInputTextFlags_CharsHexadecimal);
if (ImGui::IsItemEdited()) this->m_shouldInvalidate = true;
ImGui::InputInt("hex.builtin.view.hashes.xorout"_lang, &xorout, 0, 0, ImGuiInputTextFlags_CharsHexadecimal);
if (ImGui::IsItemEdited()) this->m_shouldInvalidate = true;
ImGui::Checkbox("hex.common.reflectIn"_lang, &reflectIn);
if (ImGui::IsItemEdited()) this->m_shouldInvalidate = true;
ImGui::Checkbox("hex.common.reflectIn"_lang, &reflectIn);
if (ImGui::IsItemEdited()) this->m_shouldInvalidate = true;
ImGui::Checkbox("hex.common.reflectOut"_lang, &reflectOut);
if (ImGui::IsItemEdited()) this->m_shouldInvalidate = true;
ImGui::Checkbox("hex.common.reflectOut"_lang, &reflectOut);
if (ImGui::IsItemEdited()) this->m_shouldInvalidate = true;
ImGui::InputInt("hex.builtin.view.hashes.poly"_lang, &polynomial, 0, 0, ImGuiInputTextFlags_CharsHexadecimal);
if (ImGui::IsItemEdited()) this->m_shouldInvalidate = true;
ImGui::InputInt("hex.builtin.view.hashes.poly"_lang, &polynomial, 0, 0, ImGuiInputTextFlags_CharsHexadecimal);
if (ImGui::IsItemEdited()) this->m_shouldInvalidate = true;
ImGui::NewLine();
ImGui::NewLine();
static u16 result = 0;
static u16 result = 0;
if (this->m_shouldInvalidate)
result = crypt::crc16(provider, this->m_hashRegion[0], this->m_hashRegion[1], polynomial, init, xorout, reflectIn, reflectOut);
if (this->m_shouldInvalidate)
result = crypt::crc16(provider, this->m_hashRegion[0], this->m_hashRegion[1], polynomial, init, xorout, reflectIn, reflectOut);
char buffer[sizeof(result) * 2 + 1];
snprintf(buffer, sizeof(buffer), "%04X", result);
char buffer[sizeof(result) * 2 + 1];
snprintf(buffer, sizeof(buffer), "%04X", result);
ImGui::TextUnformatted("hex.builtin.view.hashes.result"_lang);
ImGui::Separator();
ImGui::InputText("##nolabel", buffer, ImGuiInputTextFlags_ReadOnly);
}
break;
case HashFunctions::Crc32:
{
static int polynomial = 0x04C11DB7, init = 0xFFFFFFFF, xorout = 0xFFFFFFFF;
static bool reflectIn = true, reflectOut = true;
ImGui::TextUnformatted("hex.builtin.view.hashes.result"_lang);
ImGui::Separator();
ImGui::InputText("##nolabel", buffer, ImGuiInputTextFlags_ReadOnly);
}
break;
case HashFunctions::Crc32:
{
static int polynomial = 0x04C11DB7, init = 0xFFFFFFFF, xorout = 0xFFFFFFFF;
static bool reflectIn = true, reflectOut = true;
ImGui::InputInt("hex.builtin.view.hashes.iv"_lang, &init, 0, 0, ImGuiInputTextFlags_CharsHexadecimal);
if (ImGui::IsItemEdited()) this->m_shouldInvalidate = true;
ImGui::InputInt("hex.builtin.view.hashes.iv"_lang, &init, 0, 0, ImGuiInputTextFlags_CharsHexadecimal);
if (ImGui::IsItemEdited()) this->m_shouldInvalidate = true;
ImGui::InputInt("hex.builtin.view.hashes.xorout"_lang, &xorout, 0, 0, ImGuiInputTextFlags_CharsHexadecimal);
if (ImGui::IsItemEdited()) this->m_shouldInvalidate = true;
ImGui::InputInt("hex.builtin.view.hashes.xorout"_lang, &xorout, 0, 0, ImGuiInputTextFlags_CharsHexadecimal);
if (ImGui::IsItemEdited()) this->m_shouldInvalidate = true;
ImGui::Checkbox("hex.common.reflectIn"_lang, &reflectIn);
if (ImGui::IsItemEdited()) this->m_shouldInvalidate = true;
ImGui::Checkbox("hex.common.reflectIn"_lang, &reflectIn);
if (ImGui::IsItemEdited()) this->m_shouldInvalidate = true;
ImGui::Checkbox("hex.common.reflectOut"_lang, &reflectOut);
if (ImGui::IsItemEdited()) this->m_shouldInvalidate = true;
ImGui::Checkbox("hex.common.reflectOut"_lang, &reflectOut);
if (ImGui::IsItemEdited()) this->m_shouldInvalidate = true;
ImGui::InputInt("hex.builtin.view.hashes.poly"_lang, &polynomial, 0, 0, ImGuiInputTextFlags_CharsHexadecimal);
if (ImGui::IsItemEdited()) this->m_shouldInvalidate = true;
ImGui::InputInt("hex.builtin.view.hashes.poly"_lang, &polynomial, 0, 0, ImGuiInputTextFlags_CharsHexadecimal);
if (ImGui::IsItemEdited()) this->m_shouldInvalidate = true;
ImGui::NewLine();
ImGui::NewLine();
static u32 result = 0;
static u32 result = 0;
if (this->m_shouldInvalidate)
result = crypt::crc32(provider, this->m_hashRegion[0], this->m_hashRegion[1], polynomial, init, xorout, reflectIn, reflectOut);
if (this->m_shouldInvalidate)
result = crypt::crc32(provider, this->m_hashRegion[0], this->m_hashRegion[1], polynomial, init, xorout, reflectIn, reflectOut);
char buffer[sizeof(result) * 2 + 1];
snprintf(buffer, sizeof(buffer), "%08X", result);
char buffer[sizeof(result) * 2 + 1];
snprintf(buffer, sizeof(buffer), "%08X", result);
ImGui::TextUnformatted("hex.builtin.view.hashes.result"_lang);
ImGui::Separator();
ImGui::InputText("##nolabel", buffer, ImGuiInputTextFlags_ReadOnly);
}
break;
case HashFunctions::Md5:
{
static std::array<u8, 16> result = { 0 };
ImGui::TextUnformatted("hex.builtin.view.hashes.result"_lang);
ImGui::Separator();
ImGui::InputText("##nolabel", buffer, ImGuiInputTextFlags_ReadOnly);
}
break;
case HashFunctions::Md5:
{
static std::array<u8, 16> result = { 0 };
if (this->m_shouldInvalidate)
result = crypt::md5(provider, this->m_hashRegion[0], this->m_hashRegion[1]);
if (this->m_shouldInvalidate)
result = crypt::md5(provider, this->m_hashRegion[0], this->m_hashRegion[1]);
char buffer[sizeof(result) * 2 + 1];
formatBigHexInt(result, buffer, sizeof(buffer));
char buffer[sizeof(result) * 2 + 1];
formatBigHexInt(result, buffer, sizeof(buffer));
ImGui::NewLine();
ImGui::TextUnformatted("hex.builtin.view.hashes.result"_lang);
ImGui::Separator();
ImGui::InputText("##nolabel", buffer, ImGuiInputTextFlags_ReadOnly);
}
break;
case HashFunctions::Sha1:
{
static std::array<u8, 20> result = { 0 };
ImGui::NewLine();
ImGui::TextUnformatted("hex.builtin.view.hashes.result"_lang);
ImGui::Separator();
ImGui::InputText("##nolabel", buffer, ImGuiInputTextFlags_ReadOnly);
}
break;
case HashFunctions::Sha1:
{
static std::array<u8, 20> result = { 0 };
if (this->m_shouldInvalidate)
result = crypt::sha1(provider, this->m_hashRegion[0], this->m_hashRegion[1]);
if (this->m_shouldInvalidate)
result = crypt::sha1(provider, this->m_hashRegion[0], this->m_hashRegion[1]);
char buffer[sizeof(result) * 2 + 1];
formatBigHexInt(result, buffer, sizeof(buffer));
char buffer[sizeof(result) * 2 + 1];
formatBigHexInt(result, buffer, sizeof(buffer));
ImGui::NewLine();
ImGui::TextUnformatted("hex.builtin.view.hashes.result"_lang);
ImGui::Separator();
ImGui::InputText("##nolabel", buffer, ImGuiInputTextFlags_ReadOnly);
}
break;
case HashFunctions::Sha224:
{
static std::array<u8, 28> result = { 0 };
ImGui::NewLine();
ImGui::TextUnformatted("hex.builtin.view.hashes.result"_lang);
ImGui::Separator();
ImGui::InputText("##nolabel", buffer, ImGuiInputTextFlags_ReadOnly);
}
break;
case HashFunctions::Sha224:
{
static std::array<u8, 28> result = { 0 };
if (this->m_shouldInvalidate)
result = crypt::sha224(provider, this->m_hashRegion[0], this->m_hashRegion[1]);
if (this->m_shouldInvalidate)
result = crypt::sha224(provider, this->m_hashRegion[0], this->m_hashRegion[1]);
char buffer[sizeof(result) * 2 + 1];
formatBigHexInt(result, buffer, sizeof(buffer));
char buffer[sizeof(result) * 2 + 1];
formatBigHexInt(result, buffer, sizeof(buffer));
ImGui::NewLine();
ImGui::TextUnformatted("hex.builtin.view.hashes.result"_lang);
ImGui::Separator();
ImGui::InputText("##nolabel", buffer, ImGuiInputTextFlags_ReadOnly);
}
break;
case HashFunctions::Sha256:
{
static std::array<u8, 32> result;
ImGui::NewLine();
ImGui::TextUnformatted("hex.builtin.view.hashes.result"_lang);
ImGui::Separator();
ImGui::InputText("##nolabel", buffer, ImGuiInputTextFlags_ReadOnly);
}
break;
case HashFunctions::Sha256:
{
static std::array<u8, 32> result;
if (this->m_shouldInvalidate)
result = crypt::sha256(provider, this->m_hashRegion[0], this->m_hashRegion[1]);
if (this->m_shouldInvalidate)
result = crypt::sha256(provider, this->m_hashRegion[0], this->m_hashRegion[1]);
char buffer[sizeof(result) * 2 + 1];
formatBigHexInt(result, buffer, sizeof(buffer));
char buffer[sizeof(result) * 2 + 1];
formatBigHexInt(result, buffer, sizeof(buffer));
ImGui::NewLine();
ImGui::TextUnformatted("hex.builtin.view.hashes.result"_lang);
ImGui::Separator();
ImGui::InputText("##nolabel", buffer, ImGuiInputTextFlags_ReadOnly);
}
break;
case HashFunctions::Sha384:
{
static std::array<u8, 48> result;
ImGui::NewLine();
ImGui::TextUnformatted("hex.builtin.view.hashes.result"_lang);
ImGui::Separator();
ImGui::InputText("##nolabel", buffer, ImGuiInputTextFlags_ReadOnly);
}
break;
case HashFunctions::Sha384:
{
static std::array<u8, 48> result;
if (this->m_shouldInvalidate)
result = crypt::sha384(provider, this->m_hashRegion[0], this->m_hashRegion[1]);
if (this->m_shouldInvalidate)
result = crypt::sha384(provider, this->m_hashRegion[0], this->m_hashRegion[1]);
char buffer[sizeof(result) * 2 + 1];
formatBigHexInt(result, buffer, sizeof(buffer));
char buffer[sizeof(result) * 2 + 1];
formatBigHexInt(result, buffer, sizeof(buffer));
ImGui::NewLine();
ImGui::TextUnformatted("hex.builtin.view.hashes.result"_lang);
ImGui::Separator();
ImGui::InputText("##nolabel", buffer, ImGuiInputTextFlags_ReadOnly);
}
break;
case HashFunctions::Sha512:
{
static std::array<u8, 64> result;
ImGui::NewLine();
ImGui::TextUnformatted("hex.builtin.view.hashes.result"_lang);
ImGui::Separator();
ImGui::InputText("##nolabel", buffer, ImGuiInputTextFlags_ReadOnly);
}
break;
case HashFunctions::Sha512:
{
static std::array<u8, 64> result;
if (this->m_shouldInvalidate)
result = crypt::sha512(provider, this->m_hashRegion[0], this->m_hashRegion[1]);
if (this->m_shouldInvalidate)
result = crypt::sha512(provider, this->m_hashRegion[0], this->m_hashRegion[1]);
char buffer[sizeof(result) * 2 + 1];
formatBigHexInt(result, buffer, sizeof(buffer));
char buffer[sizeof(result) * 2 + 1];
formatBigHexInt(result, buffer, sizeof(buffer));
ImGui::NewLine();
ImGui::TextUnformatted("hex.builtin.view.hashes.result"_lang);
ImGui::Separator();
ImGui::InputText("##nolabel", buffer, ImGuiInputTextFlags_ReadOnly);
}
break;
ImGui::NewLine();
ImGui::TextUnformatted("hex.builtin.view.hashes.result"_lang);
ImGui::Separator();
ImGui::InputText("##nolabel", buffer, ImGuiInputTextFlags_ReadOnly);
}
break;
}
}

View File

@ -16,7 +16,7 @@ namespace hex::plugin::builtin {
ContentRegistry::Interface::addMenuItem("hex.builtin.menu.help", 1000, [&, this] {
if (ImGui::MenuItem("hex.builtin.view.help.about.name"_lang, "")) {
ImHexApi::Tasks::doLater([] { ImGui::OpenPopup(View::toWindowName("hex.builtin.view.help.about.name").c_str()); });
this->m_aboutWindowOpen = true;
this->m_aboutWindowOpen = true;
this->getWindowOpenState() = true;
}
@ -41,7 +41,7 @@ namespace hex::plugin::builtin {
ImGui::TableNextColumn();
if (!this->m_logoTexture.valid()) {
auto logo = romfs::get("logo.png");
auto logo = romfs::get("logo.png");
this->m_logoTexture = ImGui::LoadImageFromMemory(reinterpret_cast<const ImU8 *>(logo.data()), logo.size());
}

View File

@ -59,7 +59,7 @@ namespace hex::plugin::builtin {
};
this->m_memoryEditor.HighlightFn = [](const ImU8 *data, size_t off, bool next) -> bool {
auto _this = (ViewHexEditor*)(data);
auto _this = (ViewHexEditor *)(data);
std::optional<u32> currColor, prevColor;
@ -71,7 +71,7 @@ namespace hex::plugin::builtin {
for (const auto &[id, highlight] : ImHexApi::HexEditor::getHighlights()) {
auto &region = highlight.getRegion();
auto &color = highlight.getColor();
auto &color = highlight.getColor();
if (off >= region.address && off < (region.address + region.size))
currColor = (color & 0x00FFFFFF) | alpha;
@ -85,7 +85,7 @@ namespace hex::plugin::builtin {
auto child = pattern->getPattern(off);
if (child != nullptr) {
auto color = (child->getColor() & 0x00FFFFFF) | alpha;
currColor = currColor.has_value() ? ImAlphaBlendColors(color, currColor.value()) : color;
currColor = currColor.has_value() ? ImAlphaBlendColors(color, currColor.value()) : color;
break;
}
}
@ -94,7 +94,7 @@ namespace hex::plugin::builtin {
auto child = pattern->getPattern(off - 1);
if (child != nullptr) {
auto color = (child->getColor() & 0x00FFFFFF) | alpha;
prevColor = prevColor.has_value() ? ImAlphaBlendColors(color, currColor.value()) : color;
prevColor = prevColor.has_value() ? ImAlphaBlendColors(color, currColor.value()) : color;
break;
}
}
@ -119,8 +119,8 @@ namespace hex::plugin::builtin {
off += ImHexApi::Provider::get()->getBaseAddress();
for (const auto &[id, highlight] : ImHexApi::HexEditor::getHighlights()) {
auto &region = highlight.getRegion();
auto &color = highlight.getColor();
auto &region = highlight.getRegion();
auto &color = highlight.getColor();
auto &tooltip = highlight.getTooltip();
if (off >= region.address && off < (region.address + region.size)) {
@ -145,7 +145,7 @@ namespace hex::plugin::builtin {
return { ".", 1, 0xFFFF8000 };
auto provider = ImHexApi::Provider::get();
size_t size = std::min<size_t>(_this->m_currEncodingFile.getLongestSequence(), provider->getActualSize() - addr);
size_t size = std::min<size_t>(_this->m_currEncodingFile.getLongestSequence(), provider->getActualSize() - addr);
std::vector<u8> buffer(size);
provider->read(addr + provider->getBaseAddress() + provider->getCurrentPageAddress(), buffer.data(), size);
@ -270,9 +270,9 @@ namespace hex::plugin::builtin {
hex::openFileBrowser("hex.builtin.view.hexeditor.script.script.title"_lang, DialogMode::Open, {
{"Python Script", "py"}
},
[this](const auto &path) {
this->m_loaderScriptScriptPath = path.string();
});
[this](const auto &path) {
this->m_loaderScriptScriptPath = path.string();
});
}
ImGui::InputText("##nolabel", this->m_loaderScriptFilePath.data(), this->m_loaderScriptFilePath.length(), ImGuiInputTextFlags_ReadOnly);
ImGui::SameLine();
@ -394,7 +394,7 @@ namespace hex::plugin::builtin {
auto provider = ImHexApi::Provider::get();
size_t start = std::min(this->m_memoryEditor.DataPreviewAddr, this->m_memoryEditor.DataPreviewAddrEnd);
size_t end = std::max(this->m_memoryEditor.DataPreviewAddr, this->m_memoryEditor.DataPreviewAddrEnd);
size_t end = std::max(this->m_memoryEditor.DataPreviewAddr, this->m_memoryEditor.DataPreviewAddrEnd);
size_t copySize = (end - start) + 1;
@ -413,14 +413,14 @@ namespace hex::plugin::builtin {
auto provider = ImHexApi::Provider::get();
size_t start = std::min(this->m_memoryEditor.DataPreviewAddr, this->m_memoryEditor.DataPreviewAddrEnd);
size_t end = std::max(this->m_memoryEditor.DataPreviewAddr, this->m_memoryEditor.DataPreviewAddrEnd);
size_t end = std::max(this->m_memoryEditor.DataPreviewAddr, this->m_memoryEditor.DataPreviewAddrEnd);
std::string clipboard = ImGui::GetClipboardText();
// Check for non-hex characters
bool isValidHexString = std::find_if(clipboard.begin(), clipboard.end(), [](char c) {
return !std::isxdigit(c) && !std::isspace(c);
}) == clipboard.end();
return !std::isxdigit(c) && !std::isspace(c);
}) == clipboard.end();
if (!isValidHexString) return;
@ -455,7 +455,7 @@ namespace hex::plugin::builtin {
auto provider = ImHexApi::Provider::get();
size_t start = std::min(this->m_memoryEditor.DataPreviewAddr, this->m_memoryEditor.DataPreviewAddrEnd);
size_t end = std::max(this->m_memoryEditor.DataPreviewAddr, this->m_memoryEditor.DataPreviewAddrEnd);
size_t end = std::max(this->m_memoryEditor.DataPreviewAddr, this->m_memoryEditor.DataPreviewAddrEnd);
size_t copySize = (end - start) + 1;
@ -534,11 +534,11 @@ namespace hex::plugin::builtin {
void ViewHexEditor::drawSearchPopup() {
static auto InputCallback = [](ImGuiInputTextCallbackData *data) -> int {
auto _this = static_cast<ViewHexEditor *>(data->UserData);
auto _this = static_cast<ViewHexEditor *>(data->UserData);
auto provider = ImHexApi::Provider::get();
*_this->m_lastSearchBuffer = _this->m_searchFunction(provider, data->Buf);
_this->m_lastSearchIndex = 0;
_this->m_lastSearchIndex = 0;
if (!_this->m_lastSearchBuffer->empty())
_this->m_memoryEditor.GotoAddrAndSelect((*_this->m_lastSearchBuffer)[0].first, (*_this->m_lastSearchBuffer)[0].second);
@ -550,7 +550,7 @@ namespace hex::plugin::builtin {
auto provider = ImHexApi::Provider::get();
*this->m_lastSearchBuffer = this->m_searchFunction(provider, buffer);
this->m_lastSearchIndex = 0;
this->m_lastSearchIndex = 0;
if (!this->m_lastSearchBuffer->empty())
this->m_memoryEditor.GotoAddrAndSelect((*this->m_lastSearchBuffer)[0].first, (*this->m_lastSearchBuffer)[0].second);
@ -560,7 +560,7 @@ namespace hex::plugin::builtin {
if (!this->m_lastSearchBuffer->empty()) {
++this->m_lastSearchIndex %= this->m_lastSearchBuffer->size();
this->m_memoryEditor.GotoAddrAndSelect((*this->m_lastSearchBuffer)[this->m_lastSearchIndex].first,
(*this->m_lastSearchBuffer)[this->m_lastSearchIndex].second);
(*this->m_lastSearchBuffer)[this->m_lastSearchIndex].second);
}
};
@ -574,7 +574,7 @@ namespace hex::plugin::builtin {
this->m_lastSearchIndex %= this->m_lastSearchBuffer->size();
this->m_memoryEditor.GotoAddrAndSelect((*this->m_lastSearchBuffer)[this->m_lastSearchIndex].first,
(*this->m_lastSearchBuffer)[this->m_lastSearchIndex].second);
(*this->m_lastSearchBuffer)[this->m_lastSearchIndex].second);
}
};
@ -584,9 +584,9 @@ namespace hex::plugin::builtin {
if (ImGui::BeginTabBar("searchTabs")) {
std::vector<char> *currBuffer = nullptr;
if (ImGui::BeginTabItem("hex.builtin.view.hexeditor.search.string"_lang)) {
this->m_searchFunction = findString;
this->m_searchFunction = findString;
this->m_lastSearchBuffer = &this->m_lastStringSearch;
currBuffer = &this->m_searchStringBuffer;
currBuffer = &this->m_searchStringBuffer;
ImGui::SetKeyboardFocusHere();
if (ImGui::InputText("##nolabel", currBuffer->data(), currBuffer->size(), ImGuiInputTextFlags_CallbackCompletion | ImGuiInputTextFlags_EnterReturnsTrue, InputCallback, this)) {
@ -599,9 +599,9 @@ namespace hex::plugin::builtin {
}
if (ImGui::BeginTabItem("hex.builtin.view.hexeditor.search.hex"_lang)) {
this->m_searchFunction = findHex;
this->m_searchFunction = findHex;
this->m_lastSearchBuffer = &this->m_lastHexSearch;
currBuffer = &this->m_searchHexBuffer;
currBuffer = &this->m_searchHexBuffer;
ImGui::SetKeyboardFocusHere();
if (ImGui::InputText("##nolabel", currBuffer->data(), currBuffer->size(), ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CallbackCompletion | ImGuiInputTextFlags_EnterReturnsTrue, InputCallback, this)) {
@ -636,9 +636,9 @@ namespace hex::plugin::builtin {
}
void ViewHexEditor::drawGotoPopup() {
auto provider = ImHexApi::Provider::get();
auto provider = ImHexApi::Provider::get();
auto baseAddress = provider->getBaseAddress();
auto dataSize = provider->getActualSize();
auto dataSize = provider->getActualSize();
ImGui::SetNextWindowPos(ImGui::GetWindowPos() + ImGui::GetWindowContentRegionMin() - ImGui::GetStyle().WindowPadding);
if (ImGui::BeginPopup("hex.builtin.view.hexeditor.menu.file.goto"_lang)) {
@ -708,7 +708,7 @@ namespace hex::plugin::builtin {
}
void ViewHexEditor::drawEditPopup() {
auto provider = ImHexApi::Provider::get();
auto provider = ImHexApi::Provider::get();
bool providerValid = ImHexApi::Provider::isValid();
if (ImGui::MenuItem("hex.builtin.view.hexeditor.menu.edit.undo"_lang, "CTRL + Z", false, providerValid))
provider->undo();
@ -731,7 +731,7 @@ namespace hex::plugin::builtin {
for (const auto &[unlocalizedName, callback] : ContentRegistry::DataFormatter::getEntries()) {
if (ImGui::MenuItem(LangEntry(unlocalizedName))) {
size_t start = std::min(this->m_memoryEditor.DataPreviewAddr, this->m_memoryEditor.DataPreviewAddrEnd);
size_t end = std::max(this->m_memoryEditor.DataPreviewAddr, this->m_memoryEditor.DataPreviewAddrEnd);
size_t end = std::max(this->m_memoryEditor.DataPreviewAddr, this->m_memoryEditor.DataPreviewAddrEnd);
size_t copySize = (end - start) + 1;
@ -754,7 +754,7 @@ namespace hex::plugin::builtin {
auto base = ImHexApi::Provider::get()->getBaseAddress();
size_t start = base + std::min(this->m_memoryEditor.DataPreviewAddr, this->m_memoryEditor.DataPreviewAddrEnd);
size_t end = base + std::max(this->m_memoryEditor.DataPreviewAddr, this->m_memoryEditor.DataPreviewAddrEnd);
size_t end = base + std::max(this->m_memoryEditor.DataPreviewAddr, this->m_memoryEditor.DataPreviewAddrEnd);
ImHexApi::Bookmarks::add(start, end - start + 1, {}, {});
}
@ -787,7 +787,7 @@ namespace hex::plugin::builtin {
EventManager::subscribe<RequestSelectionChange>(this, [this](Region region) {
auto provider = ImHexApi::Provider::get();
auto page = provider->getPageOfAddress(region.address);
auto page = provider->getPageOfAddress(region.address);
if (!page.has_value())
return;
@ -836,10 +836,10 @@ namespace hex::plugin::builtin {
hex::openFileBrowser("hex.builtin.view.hexeditor.open_project"_lang, DialogMode::Open, {
{"Project File", "hexproj"}
},
[this](const auto &path) {
ProjectFile::load(path);
this->getWindowOpenState() = true;
});
[this](const auto &path) {
ProjectFile::load(path);
this->getWindowOpenState() = true;
});
}
});
@ -968,11 +968,10 @@ namespace hex::plugin::builtin {
/* Basic operations */
ContentRegistry::Interface::addMenuItem("hex.builtin.menu.file", 1100, [&] {
auto provider = ImHexApi::Provider::get();
auto provider = ImHexApi::Provider::get();
bool providerValid = ImHexApi::Provider::isValid();
if (ImGui::MenuItem("hex.builtin.view.hexeditor.menu.file.save"_lang, "CTRL + S", false, providerValid && provider->isWritable())) {
save();
}
@ -995,16 +994,16 @@ namespace hex::plugin::builtin {
/* Metadata save/load */
ContentRegistry::Interface::addMenuItem("hex.builtin.menu.file", 1200, [&, this] {
auto provider = ImHexApi::Provider::get();
auto provider = ImHexApi::Provider::get();
bool providerValid = ImHexApi::Provider::isValid();
if (ImGui::MenuItem("hex.builtin.view.hexeditor.menu.file.open_project"_lang, "")) {
hex::openFileBrowser("hex.builtin.view.hexeditor.menu.file.open_project"_lang, DialogMode::Open, {
{"Project File", "hexproj"}
},
[](const auto &path) {
ProjectFile::load(path);
});
[](const auto &path) {
ProjectFile::load(path);
});
}
if (ImGui::MenuItem("hex.builtin.view.hexeditor.menu.file.save_project"_lang, "", false, providerValid && provider->isWritable())) {
@ -1012,13 +1011,13 @@ namespace hex::plugin::builtin {
hex::openFileBrowser("hex.builtin.view.hexeditor.save_project"_lang, DialogMode::Save, {
{"Project File", "hexproj"}
},
[](const auto &path) {
if (path.extension() == ".hexproj") {
ProjectFile::store(path);
} else {
ProjectFile::store(path.string() + ".hexproj");
}
});
[](const auto &path) {
if (path.extension() == ".hexproj") {
ProjectFile::store(path);
} else {
ProjectFile::store(path.string() + ".hexproj");
}
});
} else
ProjectFile::store();
}
@ -1036,16 +1035,16 @@ namespace hex::plugin::builtin {
View::showFileChooserPopup(paths, {
{"Thingy Table File", "tbl"}
},
[this](const auto &path) {
this->m_currEncodingFile = EncodingFile(EncodingFile::Type::Thingy, path);
});
[this](const auto &path) {
this->m_currEncodingFile = EncodingFile(EncodingFile::Type::Thingy, path);
});
}
});
/* Import / Export */
ContentRegistry::Interface::addMenuItem("hex.builtin.menu.file", 1300, [&, this] {
auto provider = ImHexApi::Provider::get();
auto provider = ImHexApi::Provider::get();
bool providerValid = ImHexApi::Provider::isValid();
/* Import */
@ -1083,7 +1082,7 @@ namespace hex::plugin::builtin {
auto task = ImHexApi::Tasks::createTask("hex.builtin.view.hexeditor.processing", 0);
auto patchData = File(path, File::Mode::Read).readBytes();
auto patch = hex::loadIPSPatch(patchData);
auto patch = hex::loadIPSPatch(patchData);
task.setMaxValue(patch.size());
@ -1111,7 +1110,7 @@ namespace hex::plugin::builtin {
auto task = ImHexApi::Tasks::createTask("hex.builtin.view.hexeditor.processing", 0);
auto patchData = File(path, File::Mode::Read).readBytes();
auto patch = hex::loadIPS32Patch(patchData);
auto patch = hex::loadIPS32Patch(patchData);
task.setMaxValue(patch.size());
@ -1156,7 +1155,7 @@ namespace hex::plugin::builtin {
std::thread([this, patches] {
auto task = ImHexApi::Tasks::createTask("hex.builtin.view.hexeditor.processing", 0);
this->m_dataToSave = generateIPSPatch(patches);
this->m_dataToSave = generateIPSPatch(patches);
this->m_processingImportExport = false;
ImHexApi::Tasks::doLater([this] {
@ -1185,7 +1184,7 @@ namespace hex::plugin::builtin {
std::thread([this, patches] {
auto task = ImHexApi::Tasks::createTask("hex.builtin.view.hexeditor.processing", 0);
this->m_dataToSave = generateIPS32Patch(patches);
this->m_dataToSave = generateIPS32Patch(patches);
this->m_processingImportExport = false;
ImHexApi::Tasks::doLater([this] {

View File

@ -25,15 +25,15 @@ namespace hex::plugin::builtin {
ViewInformation::ViewInformation() : View("hex.builtin.view.information.name") {
EventManager::subscribe<EventDataChanged>(this, [this]() {
this->m_dataValid = false;
this->m_dataValid = false;
this->m_highestBlockEntropy = 0;
this->m_blockEntropy.clear();
this->m_averageEntropy = 0;
this->m_blockSize = 0;
this->m_blockSize = 0;
this->m_valueCounts.fill(0x00);
this->m_mimeType = "";
this->m_mimeType = "";
this->m_fileDescription = "";
this->m_analyzedRegion = { 0, 0 };
this->m_analyzedRegion = { 0, 0 };
});
EventManager::subscribe<EventRegionSelected>(this, [this](Region region) {
@ -92,7 +92,7 @@ namespace hex::plugin::builtin {
magic::compile();
this->m_fileDescription = magic::getDescription(provider);
this->m_mimeType = magic::getMIMEType(provider);
this->m_mimeType = magic::getMIMEType(provider);
}
this->m_dataValid = true;
@ -117,7 +117,7 @@ namespace hex::plugin::builtin {
task.update(i);
}
this->m_averageEntropy = calculateEntropy(this->m_valueCounts, provider->getSize());
this->m_averageEntropy = calculateEntropy(this->m_valueCounts, provider->getSize());
this->m_highestBlockEntropy = *std::max_element(this->m_blockEntropy.begin(), this->m_blockEntropy.end());
}
@ -139,7 +139,7 @@ namespace hex::plugin::builtin {
if (ImGui::Button("hex.builtin.view.information.analyze"_lang))
this->analyze();
},
this->m_analyzing);
this->m_analyzing);
if (this->m_analyzing) {
ImGui::TextSpinner("hex.builtin.view.information.analyzing"_lang);
@ -208,7 +208,7 @@ namespace hex::plugin::builtin {
if (ImPlot::DragLineX("Position", &this->m_entropyHandlePosition, false)) {
u64 address = u64(this->m_entropyHandlePosition * this->m_blockSize) + provider->getBaseAddress();
address = std::min(address, provider->getBaseAddress() + provider->getSize() - 1);
address = std::min(address, provider->getBaseAddress() + provider->getSize() - 1);
EventManager::post<RequestSelectionChange>(Region { address, 1 });
}

View File

@ -44,7 +44,7 @@ namespace hex::plugin::builtin {
ImGui::TableHeadersRow();
auto &patches = provider->getPatches();
u32 index = 0;
u32 index = 0;
ImGuiListClipper clipper(patches.size());

View File

@ -41,8 +41,8 @@ namespace hex::plugin::builtin {
inBegin++;
if (inBegin == inEnd) {
outBegin = inEnd;
outEnd = inEnd;
outBegin = inEnd;
outEnd = inEnd;
paletteIndex = TextEditor::PaletteIndex::Default;
} else if (TokenizeCStyleIdentifier(inBegin, inEnd, outBegin, outEnd)) {
paletteIndex = TextEditor::PaletteIndex::Identifier;
@ -56,13 +56,13 @@ namespace hex::plugin::builtin {
return paletteIndex != TextEditor::PaletteIndex::Max;
};
langDef.mCommentStart = "/*";
langDef.mCommentEnd = "*/";
langDef.mCommentStart = "/*";
langDef.mCommentEnd = "*/";
langDef.mSingleLineComment = "//";
langDef.mCaseSensitive = true;
langDef.mCaseSensitive = true;
langDef.mAutoIndentation = true;
langDef.mPreprocChar = '#';
langDef.mPreprocChar = '#';
langDef.mName = "Pattern Language";
@ -164,16 +164,16 @@ namespace hex::plugin::builtin {
EventManager::subscribe<RequestChangeTheme>(this, [this](u32 theme) {
switch (theme) {
default:
case 1: /* Dark theme */
this->m_textEditor.SetPalette(TextEditor::GetDarkPalette());
break;
case 2: /* Light theme */
this->m_textEditor.SetPalette(TextEditor::GetLightPalette());
break;
case 3: /* Classic theme */
this->m_textEditor.SetPalette(TextEditor::GetRetroBluePalette());
break;
default:
case 1: /* Dark theme */
this->m_textEditor.SetPalette(TextEditor::GetDarkPalette());
break;
case 2: /* Light theme */
this->m_textEditor.SetPalette(TextEditor::GetLightPalette());
break;
case 3: /* Classic theme */
this->m_textEditor.SetPalette(TextEditor::GetRetroBluePalette());
break;
}
});
}
@ -207,20 +207,20 @@ namespace hex::plugin::builtin {
View::showFileChooserPopup(paths, {
{"Pattern File", "hexpat"}
},
[this](const fs::path &path) {
this->loadPatternFile(path);
});
[this](const fs::path &path) {
this->loadPatternFile(path);
});
}
if (ImGui::MenuItem("hex.builtin.view.pattern_editor.menu.file.save_pattern"_lang)) {
hex::openFileBrowser("hex.builtin.view.pattern_editor.menu.file.save_pattern"_lang, DialogMode::Save, {
{"Pattern", "hexpat"}
},
[this](const auto &path) {
File file(path, File::Mode::Create);
[this](const auto &path) {
File file(path, File::Mode::Create);
file.write(this->m_textEditor.GetText());
});
file.write(this->m_textEditor.GetText());
});
}
});
}
@ -294,8 +294,8 @@ namespace hex::plugin::builtin {
ImGui::SameLine();
ImGui::TextFormatted("{} / {}",
provider->getPatternLanguageRuntime().getCreatedPatternCount(),
provider->getPatternLanguageRuntime().getMaximumPatternCount());
provider->getPatternLanguageRuntime().getCreatedPatternCount(),
provider->getPatternLanguageRuntime().getMaximumPatternCount());
}
if (this->m_textEditor.IsTextChanged()) {
@ -323,15 +323,11 @@ namespace hex::plugin::builtin {
ImGui::NewLine();
View::confirmButtons(
"hex.common.yes"_lang, "hex.common.no"_lang,
[] {
"hex.common.yes"_lang, "hex.common.no"_lang, [] {
ImHexApi::Provider::get()->getPatternLanguageRuntime().allowDangerousFunctions(true);
ImGui::CloseCurrentPopup();
},
[] {
ImGui::CloseCurrentPopup(); }, [] {
ImHexApi::Provider::get()->getPatternLanguageRuntime().allowDangerousFunctions(false);
ImGui::CloseCurrentPopup();
});
ImGui::CloseCurrentPopup(); });
ImGui::EndPopup();
}
@ -350,20 +346,20 @@ namespace hex::plugin::builtin {
const auto &[level, message] = this->m_console[i];
switch (level) {
case pl::LogConsole::Level::Debug:
ImGui::PushStyleColor(ImGuiCol_Text, this->m_textEditor.GetPalette()[u32(TextEditor::PaletteIndex::Comment)]);
break;
case pl::LogConsole::Level::Info:
ImGui::PushStyleColor(ImGuiCol_Text, this->m_textEditor.GetPalette()[u32(TextEditor::PaletteIndex::Default)]);
break;
case pl::LogConsole::Level::Warning:
ImGui::PushStyleColor(ImGuiCol_Text, this->m_textEditor.GetPalette()[u32(TextEditor::PaletteIndex::Preprocessor)]);
break;
case pl::LogConsole::Level::Error:
ImGui::PushStyleColor(ImGuiCol_Text, this->m_textEditor.GetPalette()[u32(TextEditor::PaletteIndex::ErrorMarker)]);
break;
default:
continue;
case pl::LogConsole::Level::Debug:
ImGui::PushStyleColor(ImGuiCol_Text, this->m_textEditor.GetPalette()[u32(TextEditor::PaletteIndex::Comment)]);
break;
case pl::LogConsole::Level::Info:
ImGui::PushStyleColor(ImGuiCol_Text, this->m_textEditor.GetPalette()[u32(TextEditor::PaletteIndex::Default)]);
break;
case pl::LogConsole::Level::Warning:
ImGui::PushStyleColor(ImGuiCol_Text, this->m_textEditor.GetPalette()[u32(TextEditor::PaletteIndex::Preprocessor)]);
break;
case pl::LogConsole::Level::Error:
ImGui::PushStyleColor(ImGuiCol_Text, this->m_textEditor.GetPalette()[u32(TextEditor::PaletteIndex::ErrorMarker)]);
break;
default:
continue;
}
if (ImGui::Selectable(message.c_str()))
@ -416,34 +412,34 @@ namespace hex::plugin::builtin {
ImGui::PushItemWidth(ImGui::GetContentRegionAvailWidth());
switch (type) {
case EnvVarType::Integer:
{
i64 displayValue = hex::get_or<i128>(value, 0);
ImGui::InputScalar("###value", ImGuiDataType_S64, &displayValue);
value = i128(displayValue);
break;
}
case EnvVarType::Float:
{
auto displayValue = hex::get_or<double>(value, 0.0);
ImGui::InputDouble("###value", &displayValue);
value = displayValue;
break;
}
case EnvVarType::Bool:
{
auto displayValue = hex::get_or<bool>(value, false);
ImGui::Checkbox("###value", &displayValue);
value = displayValue;
break;
}
case EnvVarType::String:
{
auto displayValue = hex::get_or<std::string>(value, "");
ImGui::InputText("###value", displayValue.data(), displayValue.capacity(), ImGuiInputTextFlags_CallbackResize, ImGui::UpdateStringSizeCallback, &displayValue);
value = displayValue;
break;
}
case EnvVarType::Integer:
{
i64 displayValue = hex::get_or<i128>(value, 0);
ImGui::InputScalar("###value", ImGuiDataType_S64, &displayValue);
value = i128(displayValue);
break;
}
case EnvVarType::Float:
{
auto displayValue = hex::get_or<double>(value, 0.0);
ImGui::InputDouble("###value", &displayValue);
value = displayValue;
break;
}
case EnvVarType::Bool:
{
auto displayValue = hex::get_or<bool>(value, false);
ImGui::Checkbox("###value", &displayValue);
value = displayValue;
break;
}
case EnvVarType::String:
{
auto displayValue = hex::get_or<std::string>(value, "");
ImGui::InputText("###value", displayValue.data(), displayValue.capacity(), ImGuiInputTextFlags_CallbackResize, ImGui::UpdateStringSizeCallback, &displayValue);
value = displayValue;
break;
}
}
ImGui::PopItemWidth();
@ -604,9 +600,9 @@ namespace hex::plugin::builtin {
if (builtinType == nullptr) continue;
PatternVariable variable = {
.inVariable = variableDecl->isInVariable(),
.inVariable = variableDecl->isInVariable(),
.outVariable = variableDecl->isOutVariable(),
.type = builtinType->getType()
.type = builtinType->getType()
};
if (variable.inVariable || variable.outVariable) {
@ -651,7 +647,9 @@ namespace hex::plugin::builtin {
if (!result) {
auto error = runtime.getError();
if (error) {
TextEditor::ErrorMarkers errorMarkers = { { error->getLineNumber(), error->what() } };
TextEditor::ErrorMarkers errorMarkers = {
{error->getLineNumber(), error->what()}
};
this->m_textEditor.SetErrorMarkers(errorMarkers);
}
}

View File

@ -240,9 +240,9 @@ namespace hex::plugin::builtin {
for (const auto &path : hex::getPath(pathType)) {
auto fullPath = path / fs::path(fileName);
if (!update || fs::exists(fullPath)) {
downloading = true;
downloading = true;
this->m_downloadPath = fullPath;
this->m_download = this->m_net.downloadFile(url, fullPath);
this->m_download = this->m_net.downloadFile(url, fullPath);
break;
}
}
@ -258,7 +258,7 @@ namespace hex::plugin::builtin {
bool ViewStore::remove(ImHexPath pathType, const std::string &fileName) {
bool removed = false;
for (const auto &path : hex::getPath(pathType)) {
bool removedFile = fs::remove(path / fs::path(fileName));
bool removedFile = fs::remove(path / fs::path(fileName));
bool removedFolder = fs::remove(path / fs::path(fileName).stem());
removed = removedFile || removedFolder;

View File

@ -65,7 +65,7 @@ namespace hex::plugin::builtin {
std::thread([this] {
auto provider = ImHexApi::Provider::get();
auto task = ImHexApi::Tasks::createTask("hex.builtin.view.strings.searching", provider->getActualSize());
auto task = ImHexApi::Tasks::createTask("hex.builtin.view.strings.searching", provider->getActualSize());
std::vector<u8> buffer(1024, 0x00);
u32 foundCharacters = 0;
@ -118,7 +118,7 @@ namespace hex::plugin::builtin {
std::regex pattern;
if (view.m_regex) {
try {
pattern = std::regex(data->Buf);
pattern = std::regex(data->Buf);
view.m_pattern_parsed = true;
} catch (std::regex_error &e) {
view.m_pattern_parsed = false;
@ -142,7 +142,7 @@ namespace hex::plugin::builtin {
if (ImGui::Button("hex.builtin.view.strings.extract"_lang))
this->searchStrings();
},
this->m_searching);
this->m_searching);
if (this->m_searching) {
ImGui::SameLine();
@ -197,7 +197,7 @@ namespace hex::plugin::builtin {
while (clipper.Step()) {
for (u64 i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) {
auto &foundString = this->m_foundStrings[this->m_filterIndices[i]];
auto string = readString(foundString);
auto string = readString(foundString);
ImGui::TableNextRow();
ImGui::TableNextColumn();

View File

@ -70,7 +70,7 @@ namespace hex::plugin::builtin {
if (ImGui::Button("hex.builtin.view.yara.reload"_lang)) this->reloadRules();
if (ImGui::Button("hex.builtin.view.yara.match"_lang)) this->applyRules();
},
this->m_matching);
this->m_matching);
if (this->m_matching) {
ImGui::SameLine();
@ -155,7 +155,7 @@ namespace hex::plugin::builtin {
if (!ImHexApi::Provider::isValid()) return;
auto provider = ImHexApi::Provider::get();
auto task = ImHexApi::Tasks::createTask("hex.builtin.view.yara.matching", provider->getActualSize());
auto task = ImHexApi::Tasks::createTask("hex.builtin.view.yara.matching", provider->getActualSize());
YR_COMPILER *compiler = nullptr;
yr_compiler_create(&compiler);
@ -173,7 +173,7 @@ namespace hex::plugin::builtin {
if (!file.isValid())
return nullptr;
auto size = file.getSize();
auto size = file.getSize();
char *buffer = new char[size + 1];
file.readBuffer(reinterpret_cast<u8 *>(buffer), size);
buffer[size] = 0x00;
@ -210,8 +210,8 @@ namespace hex::plugin::builtin {
};
ScanContext context;
context.task = &task;
context.currBlock.base = 0;
context.task = &task;
context.currBlock.base = 0;
context.currBlock.fetch_data = [](auto *block) -> const u8 * {
auto &context = *static_cast<ScanContext *>(block->context);
@ -232,7 +232,7 @@ namespace hex::plugin::builtin {
};
iterator.context = &context;
iterator.first = [](YR_MEMORY_BLOCK_ITERATOR *iterator) -> YR_MEMORY_BLOCK * {
iterator.first = [](YR_MEMORY_BLOCK_ITERATOR *iterator) -> YR_MEMORY_BLOCK *{
auto &context = *static_cast<ScanContext *>(iterator->context);
context.currBlock.base = 0;
@ -247,9 +247,9 @@ namespace hex::plugin::builtin {
u64 address = context.currBlock.base + context.currBlock.size;
iterator->last_error = ERROR_SUCCESS;
context.currBlock.base = address;
context.currBlock.size = ImHexApi::Provider::get()->getActualSize() - address;
iterator->last_error = ERROR_SUCCESS;
context.currBlock.base = address;
context.currBlock.size = ImHexApi::Provider::get()->getActualSize() - address;
context.currBlock.context = &context;
context.task->update(address);
@ -263,7 +263,7 @@ namespace hex::plugin::builtin {
rules, &iterator, 0, [](YR_SCAN_CONTEXT *context, int message, void *data, void *userData) -> int {
if (message == CALLBACK_MSG_RULE_MATCHING) {
auto &newMatches = *static_cast<std::vector<YaraMatch> *>(userData);
auto rule = static_cast<YR_RULE *>(data);
auto rule = static_cast<YR_RULE *>(data);
YR_STRING *string;
YR_MATCH *match;

View File

@ -309,43 +309,43 @@ namespace hex::plugin::builtin {
switch (theme) {
default:
case 1: /* Dark theme */
{
ImGui::StyleColorsDark();
ImGui::StyleCustomColorsDark();
ImPlot::StyleColorsDark();
{
ImGui::StyleColorsDark();
ImGui::StyleCustomColorsDark();
ImPlot::StyleColorsDark();
auto banner = romfs::get("banner_dark.png");
s_bannerTexture = ImGui::LoadImageFromMemory(reinterpret_cast<const ImU8 *>(banner.data()), banner.size());
auto banner = romfs::get("banner_dark.png");
s_bannerTexture = ImGui::LoadImageFromMemory(reinterpret_cast<const ImU8 *>(banner.data()), banner.size());
break;
}
break;
}
case 2: /* Light theme */
{
ImGui::StyleColorsLight();
ImGui::StyleCustomColorsLight();
ImPlot::StyleColorsLight();
{
ImGui::StyleColorsLight();
ImGui::StyleCustomColorsLight();
ImPlot::StyleColorsLight();
auto banner = romfs::get("banner_light.png");
s_bannerTexture = ImGui::LoadImageFromMemory(reinterpret_cast<const ImU8 *>(banner.data()), banner.size());
auto banner = romfs::get("banner_light.png");
s_bannerTexture = ImGui::LoadImageFromMemory(reinterpret_cast<const ImU8 *>(banner.data()), banner.size());
break;
}
break;
}
case 3: /* Classic theme */
{
ImGui::StyleColorsClassic();
ImGui::StyleCustomColorsClassic();
ImPlot::StyleColorsClassic();
{
ImGui::StyleColorsClassic();
ImGui::StyleCustomColorsClassic();
ImPlot::StyleColorsClassic();
auto banner = romfs::get("banner_dark.png");
s_bannerTexture = ImGui::LoadImageFromMemory(reinterpret_cast<const ImU8 *>(banner.data()), banner.size());
auto banner = romfs::get("banner_dark.png");
s_bannerTexture = ImGui::LoadImageFromMemory(reinterpret_cast<const ImU8 *>(banner.data()), banner.size());
break;
}
break;
}
}
ImGui::GetStyle().Colors[ImGuiCol_DockingEmptyBg] = ImGui::GetStyle().Colors[ImGuiCol_WindowBg];
ImGui::GetStyle().Colors[ImGuiCol_TitleBg] = ImGui::GetStyle().Colors[ImGuiCol_MenuBarBg];
ImGui::GetStyle().Colors[ImGuiCol_TitleBgActive] = ImGui::GetStyle().Colors[ImGuiCol_MenuBarBg];
ImGui::GetStyle().Colors[ImGuiCol_DockingEmptyBg] = ImGui::GetStyle().Colors[ImGuiCol_WindowBg];
ImGui::GetStyle().Colors[ImGuiCol_TitleBg] = ImGui::GetStyle().Colors[ImGuiCol_MenuBarBg];
ImGui::GetStyle().Colors[ImGuiCol_TitleBgActive] = ImGui::GetStyle().Colors[ImGuiCol_MenuBarBg];
ImGui::GetStyle().Colors[ImGuiCol_TitleBgCollapsed] = ImGui::GetStyle().Colors[ImGuiCol_MenuBarBg];
if (!s_bannerTexture.valid()) {
@ -387,10 +387,9 @@ namespace hex::plugin::builtin {
ContentRegistry::Interface::addMenuItem("hex.builtin.menu.file", 1050, [&] {
if (ImGui::MenuItem("hex.builtin.view.hexeditor.menu.file.open_file"_lang, "CTRL + O")) {
hex::openFileBrowser("hex.builtin.view.hexeditor.open_file"_lang, DialogMode::Open, {},
[](const auto &path) {
EventManager::post<RequestOpenFile>(path);
});
hex::openFileBrowser("hex.builtin.view.hexeditor.open_file"_lang, DialogMode::Open, {}, [](const auto &path) {
EventManager::post<RequestOpenFile>(path);
});
}
if (ImGui::BeginMenu("hex.builtin.view.hexeditor.menu.file.open_recent"_lang, !s_recentFilePaths.empty())) {
@ -404,9 +403,9 @@ namespace hex::plugin::builtin {
if (ImGui::MenuItem("hex.builtin.view.hexeditor.menu.file.clear_recent"_lang)) {
s_recentFilePaths.clear();
ContentRegistry::Settings::write(
"hex.builtin.setting.imhex",
"hex.builtin.setting.imhex.recent_files",
std::vector<std::string>{});
"hex.builtin.setting.imhex",
"hex.builtin.setting.imhex.recent_files",
std::vector<std::string> {});
}
ImGui::EndMenu();
@ -422,7 +421,6 @@ namespace hex::plugin::builtin {
ImGui::EndMenu();
}
});

View File

@ -116,9 +116,9 @@ namespace hex {
else if (expression == "")
break;
auto inputQueue = parseInput(expression.c_str());
auto inputQueue = parseInput(expression.c_str());
auto postfixTokens = toPostfix(inputQueue);
auto result = evaluate(postfixTokens);
auto result = evaluate(postfixTokens);
if (!result.has_value())
throw std::invalid_argument("Invalid argument for function!");
@ -220,78 +220,78 @@ namespace hex {
long double result = std::numeric_limits<long double>::quiet_NaN();
switch (front.op) {
default:
case Operator::Invalid:
throw std::invalid_argument("Invalid operator!");
case Operator::And:
result = static_cast<i64>(leftOperand) && static_cast<i64>(rightOperand);
break;
case Operator::Or:
result = static_cast<i64>(leftOperand) && static_cast<i64>(rightOperand);
break;
case Operator::Xor:
result = (static_cast<i64>(leftOperand) ^ static_cast<i64>(rightOperand)) > 0;
break;
case Operator::GreaterThan:
result = leftOperand > rightOperand;
break;
case Operator::LessThan:
result = leftOperand < rightOperand;
break;
case Operator::GreaterThanOrEquals:
result = leftOperand >= rightOperand;
break;
case Operator::LessThanOrEquals:
result = leftOperand <= rightOperand;
break;
case Operator::Equals:
result = leftOperand == rightOperand;
break;
case Operator::NotEquals:
result = leftOperand != rightOperand;
break;
case Operator::Not:
result = !static_cast<i64>(rightOperand);
break;
case Operator::BitwiseOr:
result = static_cast<i64>(leftOperand) | static_cast<i64>(rightOperand);
break;
case Operator::BitwiseXor:
result = static_cast<i64>(leftOperand) ^ static_cast<i64>(rightOperand);
break;
case Operator::BitwiseAnd:
result = static_cast<i64>(leftOperand) & static_cast<i64>(rightOperand);
break;
case Operator::BitwiseNot:
result = ~static_cast<i64>(rightOperand);
break;
case Operator::ShiftLeft:
result = static_cast<i64>(leftOperand) << static_cast<i64>(rightOperand);
break;
case Operator::ShiftRight:
result = static_cast<i64>(leftOperand) >> static_cast<i64>(rightOperand);
break;
case Operator::Addition:
result = leftOperand + rightOperand;
break;
case Operator::Subtraction:
result = leftOperand - rightOperand;
break;
case Operator::Multiplication:
result = leftOperand * rightOperand;
break;
case Operator::Division:
result = leftOperand / rightOperand;
break;
case Operator::Modulus:
result = std::fmod(leftOperand, rightOperand);
break;
case Operator::Exponentiation:
result = std::pow(leftOperand, rightOperand);
break;
case Operator::Combine:
result = (static_cast<u64>(leftOperand) << (64 - __builtin_clzll(static_cast<u64>(rightOperand)))) | static_cast<u64>(rightOperand);
break;
default:
case Operator::Invalid:
throw std::invalid_argument("Invalid operator!");
case Operator::And:
result = static_cast<i64>(leftOperand) && static_cast<i64>(rightOperand);
break;
case Operator::Or:
result = static_cast<i64>(leftOperand) && static_cast<i64>(rightOperand);
break;
case Operator::Xor:
result = (static_cast<i64>(leftOperand) ^ static_cast<i64>(rightOperand)) > 0;
break;
case Operator::GreaterThan:
result = leftOperand > rightOperand;
break;
case Operator::LessThan:
result = leftOperand < rightOperand;
break;
case Operator::GreaterThanOrEquals:
result = leftOperand >= rightOperand;
break;
case Operator::LessThanOrEquals:
result = leftOperand <= rightOperand;
break;
case Operator::Equals:
result = leftOperand == rightOperand;
break;
case Operator::NotEquals:
result = leftOperand != rightOperand;
break;
case Operator::Not:
result = !static_cast<i64>(rightOperand);
break;
case Operator::BitwiseOr:
result = static_cast<i64>(leftOperand) | static_cast<i64>(rightOperand);
break;
case Operator::BitwiseXor:
result = static_cast<i64>(leftOperand) ^ static_cast<i64>(rightOperand);
break;
case Operator::BitwiseAnd:
result = static_cast<i64>(leftOperand) & static_cast<i64>(rightOperand);
break;
case Operator::BitwiseNot:
result = ~static_cast<i64>(rightOperand);
break;
case Operator::ShiftLeft:
result = static_cast<i64>(leftOperand) << static_cast<i64>(rightOperand);
break;
case Operator::ShiftRight:
result = static_cast<i64>(leftOperand) >> static_cast<i64>(rightOperand);
break;
case Operator::Addition:
result = leftOperand + rightOperand;
break;
case Operator::Subtraction:
result = leftOperand - rightOperand;
break;
case Operator::Multiplication:
result = leftOperand * rightOperand;
break;
case Operator::Division:
result = leftOperand / rightOperand;
break;
case Operator::Modulus:
result = std::fmod(leftOperand, rightOperand);
break;
case Operator::Exponentiation:
result = std::pow(leftOperand, rightOperand);
break;
case Operator::Combine:
result = (static_cast<u64>(leftOperand) << (64 - __builtin_clzll(static_cast<u64>(rightOperand)))) | static_cast<u64>(rightOperand);
break;
}
evaluationStack.push(result);

View File

@ -33,10 +33,10 @@ namespace hex::plugin::windows {
HANDLE m_portHandle = INVALID_HANDLE_VALUE;
std::jthread m_receiveThread;
int m_selectedPort = 0;
int m_selectedBaudRate = 11; // 115200
int m_selectedNumBits = 3; // 8
int m_selectedStopBits = 0; // 1
int m_selectedPort = 0;
int m_selectedBaudRate = 11; // 115200
int m_selectedNumBits = 3; // 8
int m_selectedStopBits = 0; // 1
int m_selectedParityBits = 0; // None
bool m_hasCTSFlowControl = false; // No

View File

@ -15,10 +15,10 @@ namespace hex::plugin::windows {
static ULONGLONG subtractTimes(const FILETIME &left, const FILETIME &right) {
LARGE_INTEGER a, b;
a.LowPart = left.dwLowDateTime;
a.LowPart = left.dwLowDateTime;
a.HighPart = left.dwHighDateTime;
b.LowPart = right.dwLowDateTime;
b.LowPart = right.dwLowDateTime;
b.HighPart = right.dwHighDateTime;
return a.QuadPart - b.QuadPart;
@ -63,9 +63,9 @@ namespace hex::plugin::windows {
(user.QuadPart - lastUserCPU.QuadPart);
cpuUsage /= (now.QuadPart - lastCPU.QuadPart);
cpuUsage /= numProcessors;
lastCPU = now;
lastCPU = now;
lastUserCPU = user;
lastSysCPU = sys;
lastSysCPU = sys;
}
cpuUsage *= 100;
@ -85,7 +85,7 @@ namespace hex::plugin::windows {
}
auto totalMem = memInfo.ullTotalPhys;
auto usedMem = pmc.PrivateUsage;
auto usedMem = pmc.PrivateUsage;
ImGui::TextFormatted(ICON_FA_MICROCHIP " {0} / {1}", hex::toByteString(usedMem), hex::toByteString(totalMem));
});

View File

@ -190,12 +190,12 @@ namespace hex::plugin::windows {
return true; // If false, connect_error error popup will override this error popup
}
this->m_portHandle = ::CreateFile(("\\\\.\\" + this->m_comPorts[this->m_selectedPort].first).c_str(),
GENERIC_READ | GENERIC_WRITE,
0,
nullptr,
OPEN_EXISTING,
FILE_FLAG_OVERLAPPED,
nullptr);
GENERIC_READ | GENERIC_WRITE,
0,
nullptr,
OPEN_EXISTING,
FILE_FLAG_OVERLAPPED,
nullptr);
if (this->m_portHandle == INVALID_HANDLE_VALUE)
return false;
@ -211,20 +211,20 @@ namespace hex::plugin::windows {
if (!::GetCommState(this->m_portHandle, &serialParams))
return false;
serialParams.BaudRate = std::stoi(ViewTTYConsole::BaudRates[this->m_selectedBaudRate]);
serialParams.ByteSize = std::stoi(ViewTTYConsole::NumBits[this->m_selectedNumBits]);
serialParams.StopBits = this->m_selectedStopBits;
serialParams.Parity = this->m_selectedParityBits;
serialParams.BaudRate = std::stoi(ViewTTYConsole::BaudRates[this->m_selectedBaudRate]);
serialParams.ByteSize = std::stoi(ViewTTYConsole::NumBits[this->m_selectedNumBits]);
serialParams.StopBits = this->m_selectedStopBits;
serialParams.Parity = this->m_selectedParityBits;
serialParams.fOutxCtsFlow = this->m_hasCTSFlowControl;
if (!::SetCommState(this->m_portHandle, &serialParams))
return false;
COMMTIMEOUTS timeouts;
timeouts.ReadIntervalTimeout = 500;
timeouts.ReadTotalTimeoutConstant = 500;
timeouts.ReadTotalTimeoutMultiplier = 100;
timeouts.WriteTotalTimeoutConstant = 500;
timeouts.ReadIntervalTimeout = 500;
timeouts.ReadTotalTimeoutConstant = 500;
timeouts.ReadTotalTimeoutMultiplier = 100;
timeouts.WriteTotalTimeoutConstant = 500;
timeouts.WriteTotalTimeoutMultiplier = 100;
if (!::SetCommTimeouts(this->m_portHandle, &timeouts))
@ -233,7 +233,7 @@ namespace hex::plugin::windows {
closeHandle.release();
this->m_receiveThread = std::jthread([this](const std::stop_token &token) {
bool waitingOnRead = false;
bool waitingOnRead = false;
OVERLAPPED overlapped = { 0 };
overlapped.hEvent = ::CreateEvent(nullptr, true, false, nullptr);
@ -267,16 +267,16 @@ namespace hex::plugin::windows {
waitingOnRead = true;
}
} else {
byte = 0;
byte = 0;
auto res = ::WaitForSingleObject(overlapped.hEvent, 500);
switch (res) {
case WAIT_OBJECT_0:
if (::GetOverlappedResult(this->m_portHandle, &overlapped, &bytesRead, false)) {
addByte(byte);
waitingOnRead = false;
}
default:
break;
case WAIT_OBJECT_0:
if (::GetOverlappedResult(this->m_portHandle, &overlapped, &bytesRead, false)) {
addByte(byte);
waitingOnRead = false;
}
default:
break;
}
}
}

View File

@ -119,7 +119,7 @@ int checkCrcAgainstGondenSamples(Func func, Range golden_samples) {
for (auto &i : golden_samples) {
hex::test::TestProvider provider(&i.data);
hex::prv::Provider *provider2 = &provider;
auto crc = func(provider2, 0, i.data.size(), i.poly, i.init, i.xorOut, i.refIn, i.refOut);
auto crc = func(provider2, 0, i.data.size(), i.poly, i.init, i.xorOut, i.refIn, i.refOut);
TEST_ASSERT(crc == i.result, "name: {} got: {:#x} expected: {:#x}", i.name, crc, i.result);
}
TEST_SUCCESS();
@ -142,7 +142,7 @@ int checkCrcAgainstRandomData(Func func, int width) {
hex::test::TestProvider testprovider(&c.data);
hex::prv::Provider *provider = &testprovider;
u32 crc1 = func(provider, 0, c.data.size(), c.poly, c.init, c.xorOut, c.refIn, c.refOut);
u32 crc1 = func(provider, 0, c.data.size(), c.poly, c.init, c.xorOut, c.refIn, c.refOut);
std::vector<u8> data2 = c.data;
if (width >= 32) {
@ -155,19 +155,19 @@ int checkCrcAgainstRandomData(Func func, int width) {
hex::test::TestProvider testprovider2(&data2);
hex::prv::Provider *provider2 = &testprovider2;
u32 crc2 = func(provider2, 0, data2.size(), c.poly, c.init, c.xorOut, c.refIn, c.refOut);
u32 crc2 = func(provider2, 0, data2.size(), c.poly, c.init, c.xorOut, c.refIn, c.refOut);
TEST_ASSERT(crc2 == 0, "got wrong crc2: {:#x}, crc1: {:#x}, "
"width: {:2d}, poly: {:#018x}, init: {:#018x}, xorout: {:#018x}, refin: {:5}, refout: {:5}, data: {}",
crc2,
crc1,
c.width,
c.poly,
c.init,
c.xorOut,
c.refIn,
c.refOut,
data2);
crc2,
crc1,
c.width,
c.poly,
c.init,
c.xorOut,
c.refIn,
c.refOut,
data2);
}
TEST_SUCCESS();
@ -288,12 +288,12 @@ int checkHashProviderAgainstGondenSamples(Ret (*func)(hex::prv::Provider *&, u64
std::vector<u8> data(i.data.data(), i.data.data() + i.data.size());
hex::test::TestProvider provider(&data);
hex::prv::Provider *provider2 = &provider;
auto res = func(provider2, 0, i.data.size());
auto res = func(provider2, 0, i.data.size());
TEST_ASSERT(std::equal(std::begin(res), std::end(res), hex::crypt::decode16(i.result).begin()),
"data: '{}' got: {} expected: {}",
i.data,
hex::crypt::encode16(std::vector(res.begin(), res.end())),
i.result);
"data: '{}' got: {} expected: {}",
i.data,
hex::crypt::encode16(std::vector(res.begin(), res.end())),
i.result);
}
TEST_SUCCESS();
}
@ -304,10 +304,10 @@ int checkHashVectorAgainstGondenSamples(Ret (*func)(const std::vector<u8> &), Ra
std::vector<u8> data(i.data.data(), i.data.data() + i.data.size());
auto res = func(data);
TEST_ASSERT(std::equal(std::begin(res), std::end(res), hex::crypt::decode16(i.result).begin()),
"data: '{}' got: {} expected: {}",
i.data,
hex::crypt::encode16(std::vector(res.begin(), res.end())),
i.result);
"data: '{}' got: {} expected: {}",
i.data,
hex::crypt::encode16(std::vector(res.begin(), res.end())),
i.result);
}
TEST_SUCCESS();
}

View File

@ -10,10 +10,10 @@ TEST_SEQUENCE("32BitIntegerEndianSwap") {
TEST_SEQUENCE("64BitFloatEndianSwap") {
double floatValue = 1234.5;
u64 integerValue = reinterpret_cast<u64 &>(floatValue);
u64 integerValue = reinterpret_cast<u64 &>(floatValue);
double swappedFloatValue = hex::changeEndianess(floatValue, std::endian::big);
u64 swappedIntegerValue = hex::changeEndianess(integerValue, std::endian::big);
u64 swappedIntegerValue = hex::changeEndianess(integerValue, std::endian::big);
TEST_ASSERT(std::memcmp(&floatValue, &integerValue, 8) == 0 && std::memcmp(&swappedFloatValue, &swappedIntegerValue, 8) == 0);

View File

@ -19,9 +19,9 @@
auto ret = (x); \
if (!ret) { \
hex::log::error("Test assert '" #x "' failed {} at {}:{}", \
hex::format("" __VA_ARGS__), \
__FILE__, \
__LINE__); \
hex::format("" __VA_ARGS__), \
__FILE__, \
__LINE__); \
return EXIT_FAILURE; \
} \
} while (0)

View File

@ -25,12 +25,12 @@ int test(int argc, char **argv) {
if (test.shouldFail) {
switch (result) {
case EXIT_SUCCESS:
return EXIT_FAILURE;
case EXIT_FAILURE:
return EXIT_SUCCESS;
default:
return result;
case EXIT_SUCCESS:
return EXIT_FAILURE;
case EXIT_FAILURE:
return EXIT_SUCCESS;
default:
return result;
}
} else {
return result;

View File

@ -6,7 +6,7 @@
using namespace std::literals::string_literals;
TEST_SEQUENCE("FileAccess") {
const auto FilePath = hex::fs::current_path() / "file.txt";
const auto FilePath = hex::fs::current_path() / "file.txt";
const auto FileContent = "Hello World";
{

View File

@ -5,7 +5,7 @@
using namespace std::literals::string_literals;
TEST_SEQUENCE("SplitStringAtChar") {
const std::string TestString = "Hello|World|ABCD|Test|";
const std::string TestString = "Hello|World|ABCD|Test|";
const std::vector<std::string> TestSplitVector = { "Hello", "World", "ABCD", "Test", "" };
TEST_ASSERT(hex::splitString(TestString, "|") == TestSplitVector);
@ -14,7 +14,7 @@ TEST_SEQUENCE("SplitStringAtChar") {
};
TEST_SEQUENCE("SplitStringAtString") {
const std::string TestString = "Hello|DELIM|World|DELIM|ABCD|DELIM|Test|DELIM|";
const std::string TestString = "Hello|DELIM|World|DELIM|ABCD|DELIM|Test|DELIM|";
const std::vector<std::string> TestSplitVector = { "Hello", "World", "ABCD", "Test", "" };
TEST_ASSERT(hex::splitString(TestString, "|DELIM|") == TestSplitVector);

View File

@ -10,9 +10,9 @@ namespace hex::test {
auto testBitfield = create<PatternDataBitfield>("TestBitfield", "testBitfield", 0x12, (4 * 4) / 8);
testBitfield->setEndian(std::endian::big);
testBitfield->setFields({ create<PatternDataBitfieldField>("", "a", 0x12, 0, 4, testBitfield),
create<PatternDataBitfieldField>("", "b", 0x12, 4, 4, testBitfield),
create<PatternDataBitfieldField>("", "c", 0x12, 8, 4, testBitfield),
create<PatternDataBitfieldField>("", "d", 0x12, 12, 4, testBitfield) });
create<PatternDataBitfieldField>("", "b", 0x12, 4, 4, testBitfield),
create<PatternDataBitfieldField>("", "c", 0x12, 8, 4, testBitfield),
create<PatternDataBitfieldField>("", "d", 0x12, 12, 4, testBitfield) });
addPattern(testBitfield);
}

View File

@ -10,8 +10,8 @@ namespace hex::test {
auto testStruct = create<PatternDataStruct>("TestStruct", "testStruct", 0x100, sizeof(i32) + 20 + sizeof(u8[0x10]));
auto variable = create<PatternDataSigned>("s32", "variable", 0x100, sizeof(i32));
auto padding = create<PatternDataPadding>("padding", "", 0x100 + sizeof(i32), 20);
auto array = create<PatternDataStaticArray>("u8", "array", 0x100 + sizeof(i32) + 20, sizeof(u8[0x10]));
auto padding = create<PatternDataPadding>("padding", "", 0x100 + sizeof(i32), 20);
auto array = create<PatternDataStaticArray>("u8", "array", 0x100 + sizeof(i32) + 20, sizeof(u8[0x10]));
array->setEntries(create<PatternDataUnsigned>("u8", "", 0x100 + sizeof(i32) + 20, sizeof(u8)), 0x10);
testStruct->setMembers({ variable, padding, array });

View File

@ -10,7 +10,7 @@ namespace hex::test {
auto testStruct = create<PatternDataStruct>("TestStruct", "testStruct", 0x100, sizeof(i32) + sizeof(u8[0x10]));
auto variable = create<PatternDataSigned>("s32", "variable", 0x100, sizeof(i32));
auto array = create<PatternDataStaticArray>("u8", "array", 0x100 + sizeof(i32), sizeof(u8[0x10]));
auto array = create<PatternDataStaticArray>("u8", "array", 0x100 + sizeof(i32), sizeof(u8[0x10]));
array->setEntries(create<PatternDataUnsigned>("u8", "", 0x100 + sizeof(i32), sizeof(u8)), 0x10);
testStruct->setMembers({ variable, array });

View File

@ -19,7 +19,7 @@ void addFunctions() {
hex::ContentRegistry::PatternLanguage::Namespace nsStd = { "std" };
hex::ContentRegistry::PatternLanguage::addFunction(nsStd, "assert", 2, [](Evaluator *ctx, auto params) -> Token::Literal {
auto condition = Token::literalToBoolean(params[0]);
auto message = Token::literalToString(params[1], false);
auto message = Token::literalToString(params[1], false);
if (!condition)
LogConsole::abortEvaluation(hex::format("assertion failed \"{0}\"", message));
@ -45,7 +45,7 @@ int test(int argc, char **argv) {
}
const auto &currTest = testPatterns[testName];
bool failing = currTest->getMode() == Mode::Failing;
bool failing = currTest->getMode() == Mode::Failing;
auto provider = new TestProvider();
ON_SCOPE_EXIT { delete provider; };
@ -89,7 +89,7 @@ int test(int argc, char **argv) {
// Check if the produced patterns are the ones expected
for (u32 i = 0; i < currTest->getPatterns().size(); i++) {
auto &evaluatedPattern = *language.getPatterns()[i];
auto &controlPattern = *currTest->getPatterns()[i];
auto &controlPattern = *currTest->getPatterns()[i];
if (evaluatedPattern != controlPattern) {
hex::log::fatal("Pattern with name {}:{} didn't match template", evaluatedPattern.getTypeName(), evaluatedPattern.getVariableName());