id
int64 0
755k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
65
| repo_stars
int64 100
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 9
values | repo_extraction_date
stringclasses 92
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
223
|
wiki_explainer.cpp
|
WerWolv_ImHex/plugins/builtin/source/content/tools/wiki_explainer.cpp
|
#include <hex/api/content_registry.hpp>
#include <hex/helpers/http_requests.hpp>
#include <hex/api/localization_manager.hpp>
#include <imgui.h>
#include <hex/ui/imgui_imhex_extensions.h>
#include <fonts/codicons_font.h>
#include <nlohmann/json.hpp>
namespace hex::plugin::builtin {
using namespace std::literals::string_literals;
using namespace std::literals::chrono_literals;
std::string getWikipediaApiUrl() {
auto setting = ContentRegistry::Settings::read<std::string>("hex.builtin.setting.interface", "hex.builtin.setting.interface.wiki_explain_language", "en");
return "https://" + setting + ".wikipedia.org/w/api.php?format=json&action=query&prop=extracts&explaintext&redirects=10&formatversion=2";
}
void drawWikiExplainer() {
static HttpRequest request("GET", "");
static std::string resultTitle, resultExtract;
static std::future<HttpRequest::Result<std::string>> searchProcess;
static bool extendedSearch = false;
static std::string searchString;
ImGuiExt::Header("hex.builtin.tools.wiki_explain.control"_lang, true);
bool startSearch = ImGuiExt::InputTextIcon("##search", ICON_VS_SYMBOL_KEY, searchString, ImGuiInputTextFlags_EnterReturnsTrue);
ImGui::SameLine();
ImGui::BeginDisabled((searchProcess.valid() && searchProcess.wait_for(0s) != std::future_status::ready) || searchString.empty());
startSearch = ImGui::Button("hex.builtin.tools.wiki_explain.search"_lang) || startSearch;
ImGui::EndDisabled();
if (startSearch && !searchString.empty()) {
request.setUrl(getWikipediaApiUrl() + "&exintro"s + "&titles="s + HttpRequest::urlEncode(searchString));
searchProcess = request.execute();
}
ImGuiExt::Header("hex.builtin.tools.wiki_explain.results"_lang);
if (ImGui::BeginChild("##summary", ImVec2(0, 300), true)) {
if (!resultTitle.empty() && !resultExtract.empty()) {
ImGuiExt::HeaderColored(resultTitle.c_str(), ImGuiExt::GetCustomColorVec4(ImGuiCustomCol_Highlight), true);
ImGuiExt::TextFormattedWrapped("{}", resultExtract.c_str());
}
}
ImGui::EndChild();
if (searchProcess.valid() && searchProcess.wait_for(0s) == std::future_status::ready) {
try {
auto response = searchProcess.get();
if (response.getStatusCode() != 200) throw std::runtime_error("Invalid response");
auto json = nlohmann::json::parse(response.getData());
resultTitle = json.at("query").at("pages").at(0).at("title").get<std::string>();
resultExtract = json.at("query").at("pages").at(0).at("extract").get<std::string>();
if (!extendedSearch && resultExtract.ends_with(':')) {
extendedSearch = true;
request.setUrl(getWikipediaApiUrl() + "&titles="s + HttpRequest::urlEncode(searchString));
searchProcess = request.execute();
resultTitle.clear();
resultExtract.clear();
searchString.clear();
} else {
extendedSearch = false;
searchString.clear();
}
} catch (...) {
searchString.clear();
resultTitle.clear();
resultExtract.clear();
extendedSearch = false;
searchProcess = {};
resultTitle = "???";
resultExtract = "hex.builtin.tools.wiki_explain.invalid_response"_lang.get();
}
}
}
}
| 3,708
|
C++
|
.cpp
| 68
| 42.764706
| 162
| 0.610066
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
224
|
introduction.cpp
|
WerWolv_ImHex/plugins/builtin/source/content/tutorials/introduction.cpp
|
#include <content/providers/memory_file_provider.hpp>
#include <hex/api/event_manager.hpp>
#include <hex/api/shortcut_manager.hpp>
#include <hex/api/tutorial_manager.hpp>
#include <hex/ui/view.hpp>
namespace hex::plugin::builtin {
void registerIntroductionTutorial() {
using enum TutorialManager::Position;
auto &tutorial = TutorialManager::createTutorial("hex.builtin.tutorial.introduction", "hex.builtin.tutorial.introduction.description");
{
tutorial.addStep()
.setMessage(
"hex.builtin.tutorial.introduction.step1.title",
"hex.builtin.tutorial.introduction.step1.description",
Bottom | Right
)
.allowSkip();
}
{
auto &step = tutorial.addStep();
static EventManager::EventList::iterator eventHandle;
step.setMessage(
"hex.builtin.tutorial.introduction.step2.title",
"hex.builtin.tutorial.introduction.step2.description",
Bottom | Right
)
.addHighlight("hex.builtin.tutorial.introduction.step2.highlight",
{
"Welcome Screen/Start##SubWindow_69AA6996",
Lang("hex.builtin.welcome.start.create_file")
})
.onAppear([&step] {
eventHandle = EventProviderOpened::subscribe([&step](prv::Provider *provider) {
if (dynamic_cast<MemoryFileProvider*>(provider))
step.complete();
});
})
.onComplete([] {
EventProviderOpened::unsubscribe(eventHandle);
});
}
{
tutorial.addStep()
.addHighlight("hex.builtin.tutorial.introduction.step3.highlight", {
View::toWindowName("hex.builtin.view.hex_editor.name")
})
.allowSkip();
}
{
tutorial.addStep()
.addHighlight("hex.builtin.tutorial.introduction.step4.highlight", {
View::toWindowName("hex.builtin.view.data_inspector.name")
})
.onAppear([]{
ImHexApi::HexEditor::setSelection(Region { 0, 1 });
})
.allowSkip();
}
{
tutorial.addStep()
.addHighlight("hex.builtin.tutorial.introduction.step5.highlight.pattern_editor", {
View::toWindowName("hex.builtin.view.pattern_editor.name")
})
.addHighlight("hex.builtin.tutorial.introduction.step5.highlight.pattern_data", {
View::toWindowName("hex.builtin.view.pattern_data.name")
})
.onAppear([] {
RequestSetPatternLanguageCode::post("\n\n\n\n\n\nstruct Test {\n u8 value;\n};\n\nTest test @ 0x00;");
RequestRunPatternCode::post();
})
.allowSkip();
}
{
auto &step = tutorial.addStep();
step.addHighlight("hex.builtin.tutorial.introduction.step6.highlight", {
"##MainMenuBar",
"##menubar",
Lang("hex.builtin.menu.help")
})
.addHighlight({
"##Menu_00",
Lang("hex.builtin.view.tutorials.name")
})
.onAppear([&step] {
EventViewOpened::subscribe([&step](const View *view){
if (view->getUnlocalizedName() == UnlocalizedString("hex.builtin.view.tutorials.name"))
step.complete();
});
})
.onComplete([&step]{
EventViewOpened::unsubscribe(&step);
})
.allowSkip();
}
}
}
| 3,812
|
C++
|
.cpp
| 96
| 26.46875
| 143
| 0.533873
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
225
|
tutorials.cpp
|
WerWolv_ImHex/plugins/builtin/source/content/tutorials/tutorials.cpp
|
namespace hex::plugin::builtin {
void registerIntroductionTutorial();
void registerTutorials() {
registerIntroductionTutorial();
}
}
| 155
|
C++
|
.cpp
| 6
| 21.166667
| 40
| 0.721088
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
226
|
demangle.cpp
|
WerWolv_ImHex/plugins/builtin/source/content/helpers/demangle.cpp
|
#include <content/helpers/demangle.hpp>
#include <llvm/Demangle/Demangle.h>
namespace hex::plugin::builtin {
std::string demangle(const std::string &mangled) {
std::string result = llvm::demangle(mangled);
if (result.empty() || result == mangled)
result = llvm::demangle("_" + mangled);
if (result.empty() || result == ("_" + mangled))
result = mangled;
return result;
}
}
| 441
|
C++
|
.cpp
| 12
| 30.083333
| 56
| 0.609412
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
227
|
view_highlight_rules.cpp
|
WerWolv_ImHex/plugins/builtin/source/content/views/view_highlight_rules.cpp
|
#include "content/views/view_highlight_rules.hpp"
#include <hex/api/content_registry.hpp>
#include <hex/api/project_file_manager.hpp>
#include <wolv/utils/guards.hpp>
#include <fonts/codicons_font.h>
namespace hex::plugin::builtin {
wolv::math_eval::MathEvaluator<i128> ViewHighlightRules::Rule::Expression::s_evaluator;
ViewHighlightRules::Rule::Rule(std::string name) : name(std::move(name)) { }
ViewHighlightRules::Rule::Rule(Rule &&other) noexcept {
this->name = std::move(other.name);
this->expressions = std::move(other.expressions);
this->enabled = other.enabled;
// Set the parent rule to the new rule for all expressions
for (auto &expression : this->expressions)
expression.parentRule = this;
}
ViewHighlightRules::Rule& ViewHighlightRules::Rule::operator=(Rule &&other) noexcept {
this->name = std::move(other.name);
this->expressions = std::move(other.expressions);
this->enabled = other.enabled;
// Set the parent rule to the new rule for all expressions
for (auto &expression : this->expressions)
expression.parentRule = this;
return *this;
}
void ViewHighlightRules::Rule::addExpression(Expression &&expression) {
// Add the expression to the list and set the parent rule
expression.parentRule = this;
this->expressions.emplace_back(std::move(expression));
}
ViewHighlightRules::Rule::Expression::Expression(std::string mathExpression, std::array<float, 3> color) : mathExpression(std::move(mathExpression)), color(color) {
// Create a new highlight provider function for this expression
this->addHighlight();
}
ViewHighlightRules::Rule::Expression::~Expression() {
// If there was a highlight, remove it
if (this->highlightId > 0)
ImHexApi::HexEditor::removeForegroundHighlightingProvider(this->highlightId);
}
ViewHighlightRules::Rule::Expression::Expression(Expression &&other) noexcept : mathExpression(std::move(other.mathExpression)), color(other.color), parentRule(other.parentRule) {
// Remove the highlight from the other expression and add a new one for this one
// This is necessary as the highlight provider function holds a reference to the expression
// so to avoid dangling references, we need to destroy the old one before the expression itself
// is deconstructed
other.removeHighlight();
this->addHighlight();
}
ViewHighlightRules::Rule::Expression& ViewHighlightRules::Rule::Expression::operator=(Expression &&other) noexcept {
this->mathExpression = std::move(other.mathExpression);
this->color = other.color;
this->parentRule = other.parentRule;
// Remove the highlight from the other expression and add a new one for this one
other.removeHighlight();
this->addHighlight();
return *this;
}
void ViewHighlightRules::Rule::Expression::addHighlight() {
this->highlightId = ImHexApi::HexEditor::addForegroundHighlightingProvider([this](u64 offset, const u8 *buffer, size_t size, bool) -> std::optional<color_t>{
// If the rule containing this expression is disabled, don't highlight anything
if (!this->parentRule->enabled)
return std::nullopt;
// If the expression is empty, don't highlight anything
if (this->mathExpression.empty())
return std::nullopt;
// Load the bytes that are being highlighted into a variable
u64 value = 0;
std::memcpy(&value, buffer, std::min(sizeof(value), size));
// Add the value and offset variables to the evaluator
s_evaluator.setVariable("value", value);
s_evaluator.setVariable("offset", offset);
// Evaluate the expression
auto result = s_evaluator.evaluate(this->mathExpression);
// If the evaluator has returned a value and it's not 0, return the selected color
if (result.has_value() && result.value() != 0)
return ImGui::ColorConvertFloat4ToU32(ImVec4(this->color[0], this->color[1], this->color[2], 1.0F));
else
return std::nullopt;
});
ImHexApi::Provider::markDirty();
}
void ViewHighlightRules::Rule::Expression::removeHighlight() {
ImHexApi::HexEditor::removeForegroundHighlightingProvider(this->highlightId);
this->highlightId = 0;
ImHexApi::Provider::markDirty();
}
ViewHighlightRules::ViewHighlightRules() : View::Floating("hex.builtin.view.highlight_rules.name") {
ContentRegistry::Interface::addMenuItem({ "hex.builtin.menu.file", "hex.builtin.view.highlight_rules.menu.file.rules" }, ICON_VS_TAG, 1650, Shortcut::None, [&, this] {
this->getWindowOpenState() = true;
}, ImHexApi::Provider::isValid);
ProjectFile::registerPerProviderHandler({
.basePath = "highlight_rules.json",
.required = false,
.load = [this](prv::Provider *provider, const std::fs::path &basePath, const Tar &tar) -> bool {
const auto json = nlohmann::json::parse(tar.readString(basePath));
auto &rules = m_rules.get(provider);
rules.clear();
for (const auto &entry : json) {
Rule rule(entry["name"].get<std::string>());
rule.enabled = entry["enabled"].get<bool>();
for (const auto &expression : entry["expressions"]) {
rule.addExpression(Rule::Expression(
expression["mathExpression"].get<std::string>(),
expression["color"].get<std::array<float, 3>>()
));
}
rules.emplace_back(std::move(rule));
}
return true;
},
.store = [this](prv::Provider *provider, const std::fs::path &basePath, const Tar &tar) -> bool {
nlohmann::json result = nlohmann::json::array();
for (const auto &rule : m_rules.get(provider)) {
nlohmann::json content;
content["name"] = rule.name;
content["enabled"] = rule.enabled;
for (const auto &expression : rule.expressions) {
content["expressions"].push_back({
{ "mathExpression", expression.mathExpression },
{ "color", expression.color }
});
}
result.push_back(content);
}
tar.writeString(basePath, result.dump(4));
return true;
}
});
// Initialize the selected rule iterators to point to the end of the rules lists
m_selectedRule = m_rules->end();
EventProviderCreated::subscribe([this](prv::Provider *provider) {
m_selectedRule.get(provider) = m_rules.get(provider).end();
});
}
void ViewHighlightRules::drawRulesList() {
// Draw a table containing all the existing highlighting rules
if (ImGui::BeginTable("RulesList", 2, ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersInnerH | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingStretchProp | ImGuiTableFlags_ScrollY, ImGui::GetContentRegionAvail() - ImVec2(0, ImGui::GetTextLineHeightWithSpacing() + ImGui::GetStyle().WindowPadding.y))) {
ImGui::TableSetupColumn("Name", ImGuiTableColumnFlags_WidthStretch, 1);
ImGui::TableSetupColumn("Enabled", ImGuiTableColumnFlags_WidthFixed, 10_scaled);
for (auto it = m_rules->begin(); it != m_rules->end(); ++it) {
auto &rule = *it;
ImGui::TableNextRow();
ImGui::TableNextColumn();
// Add a selectable for each rule to be able to switch between them
ImGui::PushID(&rule);
ImGui::BeginDisabled(!rule.enabled);
if (ImGui::Selectable(rule.name.c_str(), m_selectedRule == it, ImGuiSelectableFlags_SpanAvailWidth)) {
m_selectedRule = it;
}
ImGui::EndDisabled();
// Draw enabled checkbox
ImGui::TableNextColumn();
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2());
if (ImGui::Checkbox("##enabled", &rule.enabled)) {
EventHighlightingChanged::post();
}
ImGui::PopStyleVar();
ImGui::PopID();
}
ImGui::EndTable();
}
// Draw button to add a new rule
if (ImGuiExt::DimmedIconButton(ICON_VS_ADD, ImGui::GetStyleColorVec4(ImGuiCol_Text))) {
m_rules->emplace_back("hex.builtin.view.highlight_rules.new_rule"_lang);
if (m_selectedRule == m_rules->end())
m_selectedRule = m_rules->begin();
}
ImGui::SameLine();
// Draw button to remove the selected rule
ImGui::BeginDisabled(m_selectedRule == m_rules->end());
if (ImGuiExt::DimmedIconButton(ICON_VS_REMOVE, ImGui::GetStyleColorVec4(ImGuiCol_Text))) {
auto next = std::next(*m_selectedRule);
m_rules->erase(*m_selectedRule);
m_selectedRule = next;
}
ImGui::EndDisabled();
}
void ViewHighlightRules::drawRulesConfig() {
if (ImGuiExt::BeginSubWindow("hex.builtin.view.highlight_rules.config"_lang, nullptr, ImGui::GetContentRegionAvail())) {
if (m_selectedRule != m_rules->end()) {
// Draw text input field for the rule name
ImGui::PushItemWidth(-1);
ImGui::InputTextWithHint("##name", "Name", m_selectedRule.get()->name);
ImGui::PopItemWidth();
auto &rule = *m_selectedRule;
// Draw a table containing all the expressions for the selected rule
ImGui::PushID(&rule);
ImGui::PushStyleVar(ImGuiStyleVar_CellPadding, ImVec2());
if (ImGui::BeginTable("Expressions", 3, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_ScrollY, ImGui::GetContentRegionAvail() - ImVec2(0, ImGui::GetTextLineHeightWithSpacing() + ImGui::GetStyle().WindowPadding.y))) {
ImGui::TableSetupColumn("Color", ImGuiTableColumnFlags_WidthFixed, 19_scaled);
ImGui::TableSetupColumn("Expression", ImGuiTableColumnFlags_WidthStretch);
ImGui::TableSetupColumn("##Remove", ImGuiTableColumnFlags_WidthFixed, 19_scaled);
for (auto it = rule->expressions.begin(); it != rule->expressions.end(); ++it) {
auto &expression = *it;
bool updateHighlight = false;
ImGui::PushID(&expression);
ON_SCOPE_EXIT { ImGui::PopID(); };
ImGui::TableNextRow();
// Draw color picker
ImGui::TableNextColumn();
updateHighlight = ImGui::ColorEdit3("##color", expression.color.data(), ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoBorder) || updateHighlight;
// Draw math expression input field
ImGui::TableNextColumn();
ImGui::PushItemWidth(-1);
updateHighlight = ImGui::InputTextWithHint("##expression", "hex.builtin.view.highlight_rules.expression"_lang, expression.mathExpression) || updateHighlight;
ImGui::PopItemWidth();
// Draw a button to remove the expression
ImGui::TableNextColumn();
if (ImGuiExt::DimmedIconButton(ICON_VS_REMOVE, ImGui::GetStyleColorVec4(ImGuiCol_Text))) {
rule->expressions.erase(it);
break;
}
// If any of the inputs have changed, update the highlight
if (updateHighlight)
EventHighlightingChanged::post();
}
ImGui::EndTable();
}
ImGui::PopStyleVar();
// Draw button to add a new expression
if (ImGuiExt::DimmedIconButton(ICON_VS_ADD, ImGui::GetStyleColorVec4(ImGuiCol_Text))) {
m_selectedRule.get()->addExpression(Rule::Expression("", {}));
ImHexApi::Provider::markDirty();
}
ImGui::SameLine();
// Draw help info for the expressions
ImGuiExt::HelpHover("hex.builtin.view.highlight_rules.help_text"_lang);
ImGui::PopID();
} else {
ImGuiExt::TextFormattedCentered("hex.builtin.view.highlight_rules.no_rule"_lang);
}
}
ImGuiExt::EndSubWindow();
}
void ViewHighlightRules::drawContent() {
if (ImGui::BeginTable("Layout", 2)) {
ImGui::TableSetupColumn("##left", ImGuiTableColumnFlags_WidthStretch, 0.33F);
ImGui::TableSetupColumn("##right", ImGuiTableColumnFlags_WidthStretch, 0.66F);
ImGui::TableNextRow();
// Draw rules list
ImGui::TableNextColumn();
this->drawRulesList();
// Draw rules config
ImGui::TableNextColumn();
this->drawRulesConfig();
ImGui::EndTable();
}
}
}
| 13,893
|
C++
|
.cpp
| 248
| 41.891129
| 315
| 0.590537
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
228
|
view_settings.cpp
|
WerWolv_ImHex/plugins/builtin/source/content/views/view_settings.cpp
|
#include "content/views/view_settings.hpp"
#include <hex/api/content_registry.hpp>
#include <hex/helpers/logger.hpp>
#include <nlohmann/json.hpp>
#include <popups/popup_question.hpp>
#include <fonts/codicons_font.h>
namespace hex::plugin::builtin {
ViewSettings::ViewSettings() : View::Modal("hex.builtin.view.settings.name") {
// Handle window open requests
RequestOpenWindow::subscribe(this, [this](const std::string &name) {
if (name == "Settings") {
TaskManager::doLater([this] {
this->getWindowOpenState() = true;
});
}
});
// Add the settings menu item to the Extras menu
ContentRegistry::Interface::addMenuItemSeparator({ "hex.builtin.menu.extras" }, 3000);
ContentRegistry::Interface::addMenuItem({ "hex.builtin.menu.extras", "hex.builtin.view.settings.name" }, ICON_VS_SETTINGS_GEAR, 4000, Shortcut::None, [&, this] {
this->getWindowOpenState() = true;
});
EventImHexStartupFinished::subscribe(this, [] {
for (const auto &[unlocalizedCategory, unlocalizedDescription, subCategories] : ContentRegistry::Settings::impl::getSettings()) {
for (const auto &[unlocalizedSubCategory, entries] : subCategories) {
for (const auto &[unlocalizedName, widget] : entries) {
try {
auto defaultValue = widget->store();
widget->load(ContentRegistry::Settings::impl::getSetting(unlocalizedCategory, unlocalizedName, defaultValue));
widget->onChanged();
} catch (const std::exception &e) {
log::error("Failed to load setting [{} / {}]: {}", unlocalizedCategory.get(), unlocalizedName.get(), e.what());
}
}
}
}
});
}
ViewSettings::~ViewSettings() {
RequestOpenWindow::unsubscribe(this);
EventImHexStartupFinished::unsubscribe(this);
}
void ViewSettings::drawContent() {
if (ImGui::BeginTable("Settings", 2, ImGuiTableFlags_BordersInner)) {
ImGui::TableSetupColumn("##category", ImGuiTableColumnFlags_WidthFixed, 120_scaled);
ImGui::TableSetupColumn("##settings", ImGuiTableColumnFlags_WidthStretch);
ImGui::TableNextRow();
ImGui::TableNextColumn();
{
auto &categories = ContentRegistry::Settings::impl::getSettings();
// Draw all categories
bool categorySet = false;
for (auto &category : categories) {
// Skip empty categories
if (category.subCategories.empty())
continue;
if (ImGui::Selectable(Lang(category.unlocalizedName), m_selectedCategory == &category, ImGuiSelectableFlags_NoAutoClosePopups) || m_selectedCategory == nullptr)
m_selectedCategory = &category;
if (m_selectedCategory == &category)
categorySet = true;
}
if (!categorySet)
m_selectedCategory = nullptr;
}
ImGui::TableNextColumn();
if (m_selectedCategory != nullptr) {
auto &category = *m_selectedCategory;
if (ImGui::BeginChild("scrolling")) {
// Draw the category description
if (!category.unlocalizedDescription.empty()) {
ImGuiExt::TextFormattedWrapped("{}", Lang(category.unlocalizedDescription));
ImGui::NewLine();
}
// Draw all settings of that category
for (auto &subCategory : category.subCategories) {
// Skip empty subcategories
if (subCategory.entries.empty())
continue;
if (ImGuiExt::BeginSubWindow(Lang(subCategory.unlocalizedName))) {
for (auto &setting : subCategory.entries) {
ImGui::BeginDisabled(!setting.widget->isEnabled());
ImGui::PushItemWidth(-200_scaled);
bool settingChanged = setting.widget->draw(Lang(setting.unlocalizedName));
ImGui::PopItemWidth();
ImGui::EndDisabled();
if (const auto &tooltip = setting.widget->getTooltip(); tooltip.has_value() && ImGui::IsItemHovered())
ImGuiExt::InfoTooltip(Lang(tooltip.value()));
auto &widget = setting.widget;
// Handle a setting being changed
if (settingChanged) {
auto newValue = widget->store();
// Write new value to settings
ContentRegistry::Settings::write<nlohmann::json>(category.unlocalizedName, setting.unlocalizedName, newValue);
// Print a debug message
log::debug("Setting [{} / {}]: Value was changed to {}", category.unlocalizedName.get(), setting.unlocalizedName.get(), nlohmann::to_string(newValue));
// Signal that the setting was changed
widget->onChanged();
// Request a restart if the setting requires it
if (widget->doesRequireRestart()) {
m_restartRequested = true;
m_triggerPopup = true;
}
}
}
}
ImGuiExt::EndSubWindow();
ImGui::NewLine();
}
}
ImGui::EndChild();
}
ImGui::EndTable();
}
}
void ViewSettings::drawAlwaysVisibleContent() {
// If a restart is required, ask the user if they want to restart
if (!this->getWindowOpenState() && m_triggerPopup) {
m_triggerPopup = false;
ui::PopupQuestion::open("hex.builtin.view.settings.restart_question"_lang,
ImHexApi::System::restartImHex,
[this]{
m_restartRequested = false;
}
);
}
}
}
| 6,798
|
C++
|
.cpp
| 126
| 34.619048
| 187
| 0.506327
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
229
|
view_about.cpp
|
WerWolv_ImHex/plugins/builtin/source/content/views/view_about.cpp
|
#include "content/views/view_about.hpp"
#include "hex/ui/popup.hpp"
#include <hex/api_urls.hpp>
#include <hex/api/content_registry.hpp>
#include <hex/api/achievement_manager.hpp>
#include <hex/api/plugin_manager.hpp>
#include <hex/helpers/fmt.hpp>
#include <hex/helpers/fs.hpp>
#include <hex/helpers/utils.hpp>
#include <hex/helpers/http_requests.hpp>
#include <hex/helpers/default_paths.hpp>
#include <content/popups/popup_docs_question.hpp>
#include <fonts/codicons_font.h>
#include <romfs/romfs.hpp>
#include <wolv/utils/string.hpp>
#include <string>
namespace hex::plugin::builtin {
class PopupEE : public Popup<PopupEE> {
public:
PopupEE() : Popup("Se" /* Not going to */ "cr" /* make it that easy */ "et") {
}
void drawContent() override {
ImGuiIO& io = ImGui::GetIO();
ImVec2 size = scaled({ 320, 180 });
ImGui::InvisibleButton("canvas", size);
ImVec2 p0 = ImGui::GetItemRectMin();
ImVec2 p1 = ImGui::GetItemRectMax();
ImDrawList* drawList = ImGui::GetWindowDrawList();
drawList->PushClipRect(p0, p1);
ImVec4 mouseData;
mouseData.x = (io.MousePos.x - p0.x) / size.x;
mouseData.y = (io.MousePos.y - p0.y) / size.y;
mouseData.z = io.MouseDownDuration[0];
mouseData.w = io.MouseDownDuration[1];
fx(drawList, p0, p1, size, mouseData, float(ImGui::GetTime()));
}
void fx(ImDrawList* drawList, ImVec2 startPos, ImVec2 endPos, ImVec2, ImVec4, float t) {
const float CircleRadius = 5_scaled;
const float Gap = 1_scaled;
constexpr static auto func = [](i32 x, i32 y, float t) {
return std::sin(t - std::sqrt(std::pow((x - 14), 2) + std::pow((y - 8), 2)));
};
float x = startPos.x + CircleRadius + Gap;
u32 ix = 0;
while (x < endPos.x) {
float y = startPos.y + CircleRadius + Gap;
u32 iy = 0;
while (y < endPos.y) {
const float result = func(ix, iy, t);
const float radius = CircleRadius * std::abs(result);
const auto color = result < 0 ? ImColor(0xFF, 0, 0, 0xFF) : ImColor(0xFF, 0xFF, 0xFF, 0xFF);
drawList->AddCircleFilled(ImVec2(x, y), radius, color);
y += CircleRadius * 2 + Gap;
iy += 1;
}
x += CircleRadius * 2 + Gap;
ix += 1;
}
}
};
ViewAbout::ViewAbout() : View::Modal("hex.builtin.view.help.about.name") {
// Add "About" menu item to the help menu
ContentRegistry::Interface::addMenuItem({ "hex.builtin.menu.help", "hex.builtin.view.help.about.name" }, ICON_VS_INFO, 1000, Shortcut::None, [this] {
this->getWindowOpenState() = true;
});
ContentRegistry::Interface::addMenuItemSeparator({ "hex.builtin.menu.help" }, 2000);
ContentRegistry::Interface::addMenuItemSubMenu({ "hex.builtin.menu.help" }, 3000, [] {
static std::string content;
if (ImGui::InputTextWithHint("##search", "hex.builtin.view.help.documentation_search"_lang, content, ImGuiInputTextFlags_AutoSelectAll | ImGuiInputTextFlags_EscapeClearsAll | ImGuiInputTextFlags_EnterReturnsTrue)) {
PopupDocsQuestion::open(content);
content.clear();
ImGui::CloseCurrentPopup();
}
});
ContentRegistry::Interface::addMenuItemSeparator({ "hex.builtin.menu.help" }, 4000);
// Add documentation link to the help menu
ContentRegistry::Interface::addMenuItem({ "hex.builtin.menu.help", "hex.builtin.view.help.documentation" }, ICON_VS_BOOK, 5000, Shortcut::None, [] {
hex::openWebpage("https://docs.werwolv.net/imhex");
AchievementManager::unlockAchievement("hex.builtin.achievement.starting_out", "hex.builtin.achievement.starting_out.docs.name");
});
}
void ViewAbout::drawAboutMainPage() {
// Draw main about table
if (ImGui::BeginTable("about_table", 2, ImGuiTableFlags_SizingFixedFit)) {
ImGui::TableNextRow();
ImGui::TableNextColumn();
// Draw the ImHex icon
if (!m_logoTexture.isValid())
m_logoTexture = ImGuiExt::Texture::fromImage(romfs::get("assets/common/logo.png").span(), ImGuiExt::Texture::Filter::Linear);
ImGui::Image(m_logoTexture, scaled({ 100, 100 }));
if (ImGui::IsItemClicked()) {
m_clickCount += 1;
}
if (m_clickCount >= (2 * 3 + 4)) {
this->getWindowOpenState() = false;
PopupEE::open();
m_clickCount = 0;
}
ImGui::TableNextColumn();
if (ImGuiExt::BeginSubWindow("Build Information", nullptr, ImVec2(450_scaled, 0), ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY)) {
this->drawBuildInformation();
}
ImGuiExt::EndSubWindow();
ImGui::EndTable();
}
// Draw donation links
ImGuiExt::Header("hex.builtin.view.help.about.donations"_lang);
if (ImGui::BeginChild("##ThanksWrapper", ImVec2(ImGui::GetContentRegionAvail().x, ImGui::GetTextLineHeightWithSpacing() * 3))) {
ImGui::PushTextWrapPos(ImGui::GetContentRegionAvail().x * 0.8F);
ImGuiExt::TextFormattedCentered("{}", static_cast<const char *>("hex.builtin.view.help.about.thanks"_lang));
ImGui::PopTextWrapPos();
}
ImGui::EndChild();
ImGui::NewLine();
struct DonationPage {
ImGuiExt::Texture texture;
const char *link;
};
static std::array DonationPages = {
DonationPage { ImGuiExt::Texture::fromImage(romfs::get("assets/common/donation/paypal.png").span<std::byte>(), ImGuiExt::Texture::Filter::Linear), "https://werwolv.net/donate" },
DonationPage { ImGuiExt::Texture::fromImage(romfs::get("assets/common/donation/github.png").span<std::byte>(), ImGuiExt::Texture::Filter::Linear), "https://github.com/sponsors/WerWolv" },
DonationPage { ImGuiExt::Texture::fromImage(romfs::get("assets/common/donation/patreon.png").span<std::byte>(), ImGuiExt::Texture::Filter::Linear), "https://patreon.com/werwolv" },
};
if (ImGui::BeginTable("DonationLinks", 5, ImGuiTableFlags_SizingStretchSame)) {
ImGui::TableNextRow();
ImGui::TableNextColumn();
for (const auto &page : DonationPages) {
ImGui::TableNextColumn();
const auto size = page.texture.getSize() / 1.5F;
const auto startPos = ImGui::GetCursorScreenPos();
ImGui::Image(page.texture, page.texture.getSize() / 1.5F);
if (ImGui::IsItemHovered()) {
ImGui::GetForegroundDrawList()->AddShadowCircle(startPos + size / 2, size.x / 2, ImGui::GetColorU32(ImGuiCol_Button), 100.0F, ImVec2(), ImDrawFlags_ShadowCutOutShapeBackground);
}
if (ImGui::IsItemClicked()) {
hex::openWebpage(page.link);
}
}
ImGui::EndTable();
}
ImGui::NewLine();
}
void ViewAbout::drawBuildInformation() {
if (ImGui::BeginTable("Information", 1, ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersInner)) {
ImGui::Indent();
ImGui::TableNextRow();
ImGui::TableNextColumn();
{
// Draw basic information about ImHex and its version
ImGuiExt::TextFormatted("ImHex Hex Editor v{} by WerWolv", ImHexApi::System::getImHexVersion());
ImGui::Indent(25_scaled);
ImGuiExt::TextFormatted("Powered by Dear ImGui v{}", ImGui::GetVersion());
ImGui::Unindent(25_scaled);
}
ImGui::TableNextColumn();
{
ImGuiExt::TextFormatted(" {} ", ICON_VS_SOURCE_CONTROL);
ImGui::SameLine(0, 0);
// Draw a clickable link to the current commit
if (ImGuiExt::Hyperlink(hex::format("{0}@{1}", ImHexApi::System::getCommitBranch(), ImHexApi::System::getCommitHash()).c_str()))
hex::openWebpage("https://github.com/WerWolv/ImHex/commit/" + ImHexApi::System::getCommitHash(true));
}
ImGui::TableNextColumn();
{
// Draw the build date and time
ImGuiExt::TextFormatted("Compiled on {} at {}", __DATE__, __TIME__);
}
ImGui::TableNextColumn();
{
// Draw the author of the current translation
ImGui::TextUnformatted("hex.builtin.view.help.about.translator"_lang);
}
ImGui::TableNextColumn();
{
// Draw information about the open-source nature of ImHex
ImGui::TextUnformatted("hex.builtin.view.help.about.source"_lang);
ImGui::SameLine();
// Draw a clickable link to the GitHub repository
if (ImGuiExt::Hyperlink(ICON_VS_LOGO_GITHUB " " "WerWolv/ImHex"))
hex::openWebpage("https://github.com/WerWolv/ImHex");
}
ImGui::Unindent();
ImGui::EndTable();
}
}
static void drawContributorTable(const char *title, const auto &contributors) {
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2());
auto result = ImGuiExt::BeginSubWindow(title, nullptr, ImVec2(ImGui::GetContentRegionAvail().x, 0), ImGuiChildFlags_AutoResizeX);
ImGui::PopStyleVar();
if (result) {
if (ImGui::BeginTable(title, 1, ImGuiTableFlags_RowBg | ImGuiTableFlags_Borders)) {
for (const auto &contributor : contributors) {
ImGui::TableNextRow();
if (contributor.mainContributor) {
ImGui::TableSetBgColor(ImGuiTableBgTarget_RowBg0, ImGui::GetColorU32(ImGuiCol_PlotHistogram) & 0x1FFFFFFF);
}
ImGui::TableNextColumn();
if (ImGuiExt::Hyperlink(contributor.name))
hex::openWebpage(contributor.link);
if (contributor.description[0] != '\0') {
ImGui::Indent();
ImGui::TextUnformatted(contributor.description);
ImGui::Unindent();
}
}
ImGui::EndTable();
}
}
ImGuiExt::EndSubWindow();
}
void ViewAbout::drawContributorPage() {
struct Contributor {
const char *name;
const char *description;
const char *link;
bool mainContributor;
};
constexpr static std::array Contributors = {
Contributor { "iTrooz", "A huge amount of help maintaining ImHex and the CI", "https://github.com/iTrooz", true },
Contributor { "jumanji144", "A ton of help with the Pattern Language, API and usage stats", "https://github.com/jumanji144", true },
Contributor { "AxCut", "A ton of great pattern language improvements and help with the issue tracker", "https://github.com/paxcut", false },
Contributor { "Mary", "Porting ImHex to macOS originally", "https://github.com/marysaka", false },
Contributor { "Roblabla", "Adding the MSI Windows installer", "https://github.com/roblabla", false },
Contributor { "jam1garner", "Adding support for Rust plugins", "https://github.com/jam1garner", false },
Contributor { "All other amazing contributors", "Being part of the community, opening issues, PRs and donating", "https://github.com/WerWolv/ImHex/graphs/contributors", false }
};
constexpr static std::array Testers = {
Contributor { "Nemoumbra", "Breaking my code literal seconds after I push it", "https://github.com/Nemoumbra", true },
Contributor { "Berylskid", "", "https://github.com/Berylskid", false },
Contributor { "Jan Polak", "", "https://github.com/polak-jan", false },
Contributor { "Ken-Kaneki", "", "https://github.com/loneicewolf", false },
Contributor { "Everybody who has reported issues", "Helping me find bugs and improve the software", "https://github.com/WerWolv/ImHex/issues", false }
};
ImGuiExt::TextFormattedWrapped("These amazing people have contributed some incredible things to ImHex in the past.\nConsider opening a PR on the Git Repository to take your place among them!");
ImGui::NewLine();
drawContributorTable("Contributors", Contributors);
ImGui::NewLine();
ImGuiExt::TextFormattedWrapped("All of these great people made ImHex work much much smoother.\nConsider joining our Tester team to help making ImHex better for everyone!");
ImGui::NewLine();
drawContributorTable("Testers", Testers);
}
void ViewAbout::drawLibraryCreditsPage() {
struct Library {
const char *name;
const char *author;
const char *link;
};
constexpr static std::array ImGuiLibraries = {
Library { "ImGui", "ocornut", "https://github.com/ocornut/imgui" },
Library { "ImPlot", "epezent", "https://github.com/epezent/implot" },
Library { "imnodes", "Nelarius", "https://github.com/Nelarius/imnodes" },
Library { "ImGuiColorTextEdit", "BalazsJako", "https://github.com/BalazsJako/ImGuiColorTextEdit" },
};
constexpr static std::array ExternalLibraries = {
Library { "PatternLanguage", "WerWolv", "https://github.com/WerWolv/PatternLanguage" },
Library { "libwolv", "WerWolv", "https://github.com/WerWolv/libwolv" },
Library { "libromfs", "WerWolv", "https://github.com/WerWolv/libromfs" },
};
constexpr static std::array ThirdPartyLibraries = {
Library { "json", "nlohmann", "https://github.com/nlohmann/json" },
Library { "fmt", "fmtlib", "https://github.com/fmtlib/fmt" },
Library { "nativefiledialog-extended", "btzy", "https://github.com/btzy/nativefiledialog-extended" },
Library { "xdgpp", "danyspin97", "https://sr.ht/~danyspin97/xdgpp" },
Library { "capstone", "aquynh", "https://github.com/aquynh/capstone" },
Library { "microtar", "rxi", "https://github.com/rxi/microtar" },
Library { "yara", "VirusTotal", "https://github.com/VirusTotal/yara" },
Library { "edlib", "Martinsos", "https://github.com/Martinsos/edlib" },
Library { "HashLibPlus", "ron4fun", "https://github.com/ron4fun/HashLibPlus" },
Library { "miniaudio", "mackron", "https://github.com/mackron/miniaudio" },
Library { "freetype", "freetype", "https://gitlab.freedesktop.org/freetype/freetype" },
Library { "mbedTLS", "ARMmbed", "https://github.com/ARMmbed/mbedtls" },
Library { "curl", "curl", "https://github.com/curl/curl" },
Library { "file", "file", "https://github.com/file/file" },
Library { "glfw", "glfw", "https://github.com/glfw/glfw" },
Library { "llvm", "llvm-project", "https://github.com/llvm/llvm-project" },
Library { "Boost.Regex", "John Maddock", "https://github.com/boostorg/regex" },
};
constexpr static auto drawTable = [](const char *category, const auto &libraries) {
const auto width = ImGui::GetContentRegionAvail().x;
if (ImGuiExt::BeginSubWindow(category)) {
for (const auto &library : libraries) {
ImGui::PushStyleColor(ImGuiCol_ChildBg, ImGui::GetColorU32(ImGuiCol_TableHeaderBg));
ImGui::PushStyleVar(ImGuiStyleVar_ChildRounding, 50);
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, scaled({ 12, 3 }));
if (ImGui::BeginChild(library.link, ImVec2(), ImGuiChildFlags_Border | ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY)) {
if (ImGuiExt::Hyperlink(hex::format("{}/{}", library.author, library.name).c_str())) {
hex::openWebpage(library.link);
}
ImGui::SetItemTooltip("%s", library.link);
}
ImGui::EndChild();
ImGui::SameLine();
if (ImGui::GetCursorPosX() > (width - 100_scaled))
ImGui::NewLine();
ImGui::PopStyleColor();
ImGui::PopStyleVar(2);
}
}
ImGuiExt::EndSubWindow();
ImGui::NewLine();
};
ImGuiExt::TextFormattedWrapped("ImHex builds on top of the amazing work of a ton of talented library developers without which this project wouldn't stand.");
ImGui::NewLine();
drawTable("ImGui", ImGuiLibraries);
drawTable("External", ExternalLibraries);
drawTable("Third Party", ThirdPartyLibraries);
}
void ViewAbout::drawLoadedPlugins() {
const auto &plugins = PluginManager::getPlugins();
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2());
auto result = ImGuiExt::BeginSubWindow("hex.builtin.view.help.about.plugins"_lang);
ImGui::PopStyleVar();
if (result) {
if (ImGui::BeginTable("plugins", 4, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingFixedFit)) {
ImGui::TableSetupScrollFreeze(0, 1);
ImGui::TableSetupColumn("hex.builtin.view.help.about.plugins.plugin"_lang);
ImGui::TableSetupColumn("hex.builtin.view.help.about.plugins.author"_lang);
ImGui::TableSetupColumn("hex.builtin.view.help.about.plugins.desc"_lang, ImGuiTableColumnFlags_WidthStretch, 0.5);
ImGui::TableSetupColumn("##loaded", ImGuiTableColumnFlags_WidthFixed, ImGui::GetTextLineHeight());
ImGui::TableHeadersRow();
for (const auto &plugin : plugins) {
this->drawPluginRow(plugin);
}
ImGui::EndTable();
}
}
ImGuiExt::EndSubWindow();
}
void ViewAbout::drawPluginRow(const hex::Plugin& plugin) {
if (plugin.isLibraryPlugin())
return;
auto features = plugin.getFeatures();
ImGui::TableNextRow();
ImGui::TableNextColumn();
bool open = false;
ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetColorU32(ImGuiCol_Text));
if (features.empty())
ImGui::BulletText("%s", plugin.getPluginName().c_str());
else
open = ImGui::TreeNode(plugin.getPluginName().c_str());
ImGui::PopStyleColor();
ImGui::TableNextColumn();
ImGui::TextUnformatted(plugin.getPluginAuthor().c_str());
ImGui::TableNextColumn();
ImGui::TextUnformatted(plugin.getPluginDescription().c_str());
ImGui::TableNextColumn();
ImGui::TextUnformatted(plugin.isLoaded() ? ICON_VS_CHECK : ICON_VS_CLOSE);
if (open) {
for (const auto &feature : plugin.getFeatures()) {
ImGui::TableNextRow();
ImGui::TableNextColumn();
ImGuiExt::TextFormatted(" {}", feature.name.c_str());
ImGui::TableNextColumn();
ImGui::TableNextColumn();
ImGui::TableNextColumn();
ImGui::TextUnformatted(feature.enabled ? ICON_VS_CHECK : ICON_VS_CLOSE);
}
ImGui::TreePop();
}
}
void ViewAbout::drawPathsPage() {
constexpr static std::array<std::pair<const char *, const paths::impl::DefaultPath*>, paths::All.size()> PathTypes = {
{
{ "Patterns", &paths::Patterns },
{ "Patterns Includes", &paths::PatternsInclude },
{ "Magic", &paths::Magic },
{ "Plugins", &paths::Plugins },
{ "Yara Patterns", &paths::Yara },
{ "Yara Advaned Analysis", &paths::YaraAdvancedAnalysis },
{ "Config", &paths::Config },
{ "Backups", &paths::Backups },
{ "Resources", &paths::Resources },
{ "Constants lists", &paths::Constants },
{ "Custom encodings", &paths::Encodings },
{ "Logs", &paths::Logs },
{ "Recent files", &paths::Recent },
{ "Scripts", &paths::Scripts },
{ "Data inspector scripts", &paths::Inspectors },
{ "Themes", &paths::Themes },
{ "Native Libraries", &paths::Libraries },
{ "Custom data processor nodes", &paths::Nodes },
{ "Layouts", &paths::Layouts },
{ "Workspaces", &paths::Workspaces },
}
};
static_assert(PathTypes.back().first != nullptr, "All path items need to be populated!");
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2());
if (ImGuiExt::BeginSubWindow("Paths", nullptr, ImGui::GetContentRegionAvail())) {
if (ImGui::BeginTable("##imhex_paths", 2, ImGuiTableFlags_ScrollY | ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingFixedFit)) {
ImGui::TableSetupScrollFreeze(0, 1);
ImGui::TableSetupColumn("Type");
ImGui::TableSetupColumn("Paths");
// Draw the table
ImGui::TableHeadersRow();
for (const auto &[name, paths] : PathTypes) {
ImGui::TableNextRow();
ImGui::TableNextColumn();
ImGui::TextUnformatted(name);
ImGui::TableNextColumn();
for (auto &path : paths->all()){
// Draw hyperlink to paths that exist or red text if they don't
if (wolv::io::fs::isDirectory(path)){
if (ImGuiExt::Hyperlink(wolv::util::toUTF8String(path).c_str())) {
fs::openFolderExternal(path);
}
} else {
ImGuiExt::TextFormattedColored(ImGuiExt::GetCustomColorVec4(ImGuiCustomCol_ToolbarRed), wolv::util::toUTF8String(path));
}
}
}
ImGui::EndTable();
}
}
ImGuiExt::EndSubWindow();
ImGui::PopStyleVar();
}
static void drawRegularLine(const std::string& line) {
ImGui::Bullet();
ImGui::SameLine();
// Check if the line contains bold text
auto boldStart = line.find("**");
if (boldStart == std::string::npos) {
// Draw the line normally
ImGui::TextUnformatted(line.c_str());
return;
}
// Find the end of the bold text
auto boldEnd = line.find("**", boldStart + 2);
// Draw the line with the bold text highlighted
ImGui::TextUnformatted(line.substr(0, boldStart).c_str());
ImGui::SameLine(0, 0);
ImGuiExt::TextFormattedColored(ImGuiExt::GetCustomColorVec4(ImGuiCustomCol_Highlight), "{}",
line.substr(boldStart + 2, boldEnd - boldStart - 2).c_str());
ImGui::SameLine(0, 0);
ImGui::TextUnformatted(line.substr(boldEnd + 2).c_str());
}
struct ReleaseNotes {
std::string title;
std::string versionString;
std::vector<std::string> notes;
};
static ReleaseNotes parseReleaseNotes(const HttpRequest::Result<std::string>& response) {
ReleaseNotes notes;
nlohmann::json json;
if (!response.isSuccess()) {
// An error occurred, display it
notes.notes.push_back("## HTTP Error: " + std::to_string(response.getStatusCode()));
return notes;
}
// A valid response was received, parse it
try {
json = nlohmann::json::parse(response.getData());
// Get the release title
notes.title = json["name"].get<std::string>();
// Get the release version string
notes.versionString = json["tag_name"].get<std::string>();
// Get the release notes and split it into lines
auto body = json["body"].get<std::string>();
notes.notes = wolv::util::splitString(body, "\r\n");
} catch (std::exception &e) {
notes.notes.push_back("## Error: " + std::string(e.what()));
}
return notes;
}
void ViewAbout::drawReleaseNotesPage() {
static ReleaseNotes notes;
// Set up the request to get the release notes the first time the page is opened
const static auto ImHexVersionString = ImHexApi::System::getImHexVersion(false);
AT_FIRST_TIME {
static HttpRequest request("GET", GitHubApiURL + std::string("/releases/") + (ImHexVersionString.ends_with(".WIP") ? "latest" : ( "tags/v" + ImHexVersionString)));
m_releaseNoteRequest = request.execute();
};
// Wait for the request to finish and parse the response
if (m_releaseNoteRequest.valid()) {
if (m_releaseNoteRequest.wait_for(std::chrono::seconds(0)) == std::future_status::ready) {
notes = parseReleaseNotes(m_releaseNoteRequest.get());
} else {
// Draw a spinner while the release notes are loading
ImGuiExt::TextSpinner("hex.ui.common.loading"_lang);
}
}
// Draw the release title
if (!notes.title.empty()) {
auto title = hex::format("{}: {}", notes.versionString, notes.title);
ImGuiExt::Header(title.c_str(), true);
ImGui::Separator();
}
// Draw the release notes and format them using parts of the GitHub Markdown syntax
// This is not a full implementation of the syntax, but it's enough to make the release notes look good.
for (const auto &line : notes.notes) {
if (line.starts_with("## ")) {
// Draw H2 Header
ImGuiExt::Header(line.substr(3).c_str());
} else if (line.starts_with("### ")) {
// Draw H3 Header
ImGuiExt::Header(line.substr(4).c_str());
} else if (line.starts_with("- ")) {
// Draw bullet point
drawRegularLine(line.substr(2));
} else if (line.starts_with(" - ")) {
// Draw further indented bullet point
ImGui::Indent();
ImGui::Indent();
drawRegularLine(line.substr(6));
ImGui::Unindent();
ImGui::Unindent();
}
}
}
struct Commit {
std::string hash;
std::string message;
std::string description;
std::string author;
std::string date;
std::string url;
};
static std::vector<Commit> parseCommits(const HttpRequest::Result<std::string>& response) {
nlohmann::json json;
std::vector<Commit> commits;
if (!response.isSuccess()) {
// An error occurred, display it
commits.emplace_back(
"hex.ui.common.error"_lang,
"HTTP " + std::to_string(response.getStatusCode()),
"",
"",
""
);
return { };
}
// A valid response was received, parse it
try {
json = nlohmann::json::parse(response.getData());
for (auto &commit: json) {
const auto message = commit["commit"]["message"].get<std::string>();
// Split commit title and description. They're separated by two newlines.
const auto messageEnd = message.find("\n\n");
auto commitTitle = messageEnd == std::string::npos ? message : message.substr(0, messageEnd);
auto commitDescription =
messageEnd == std::string::npos ? "" : message.substr(commitTitle.size() + 2);
auto url = commit["html_url"].get<std::string>();
auto sha = commit["sha"].get<std::string>();
auto date = commit["commit"]["author"]["date"].get<std::string>();
auto author = hex::format("{} <{}>",
commit["commit"]["author"]["name"].get<std::string>(),
commit["commit"]["author"]["email"].get<std::string>()
);
// Move the commit data into the list of commits
commits.emplace_back(
std::move(sha),
std::move(commitTitle),
std::move(commitDescription),
std::move(author),
std::move(date),
std::move(url)
);
}
} catch (std::exception &e) {
commits.emplace_back(
"hex.ui.common.error"_lang,
e.what(),
"",
"",
""
);
}
return commits;
}
void ViewAbout::drawCommitHistoryPage() {
static std::vector<Commit> commits;
// Set up the request to get the commit history the first time the page is opened
AT_FIRST_TIME {
static HttpRequest request("GET", GitHubApiURL + std::string("/commits?per_page=100"));
m_commitHistoryRequest = request.execute();
};
// Wait for the request to finish and parse the response
if (m_commitHistoryRequest.valid()) {
if (m_commitHistoryRequest.wait_for(std::chrono::seconds(0)) == std::future_status::ready) {
commits = parseCommits(m_commitHistoryRequest.get());
} else {
// Draw a spinner while the commits are loading
ImGuiExt::TextSpinner("hex.ui.common.loading"_lang);
}
}
// Draw commits table
if (commits.empty()) return;
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2());
auto result = ImGuiExt::BeginSubWindow("Commits", nullptr, ImGui::GetContentRegionAvail());
ImGui::PopStyleVar();
if (result) {
this->drawCommitsTable(commits);
}
ImGuiExt::EndSubWindow();
}
void ViewAbout::drawCommitsTable(const auto& commits) {
if (ImGui::BeginTable("##commits", 2, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_ScrollY)) {
// Draw commits
for (const auto &commit: commits) {
ImGui::PushID(commit.hash.c_str());
ImGui::TableNextRow();
this->drawCommitRow(commit);
ImGui::PopID();
}
ImGui::EndTable();
}
}
void ViewAbout::drawCommitRow(const auto &commit) {
// Draw hover tooltip
ImGui::TableNextColumn();
if (ImGui::Selectable("##commit", false, ImGuiSelectableFlags_SpanAllColumns)) {
hex::openWebpage(commit.url);
}
if (ImGui::IsItemHovered()) {
if (ImGui::BeginTooltip()) {
// Draw author and commit date
ImGuiExt::TextFormattedColored(ImGuiExt::GetCustomColorVec4(ImGuiCustomCol_Highlight), "{}",
commit.author);
ImGui::SameLine();
ImGuiExt::TextFormatted("@ {}", commit.date.c_str());
// Draw description if there is one
if (!commit.description.empty()) {
ImGui::Separator();
ImGuiExt::TextFormatted("{}", commit.description);
}
ImGui::EndTooltip();
}
}
// Draw commit hash
ImGui::SameLine(0, 0);
ImGuiExt::TextFormattedColored(ImGuiExt::GetCustomColorVec4(ImGuiCustomCol_Highlight), "{}",
commit.hash.substr(0, 7));
// Draw the commit message
ImGui::TableNextColumn();
const ImColor color = [&] {
if (commit.hash == ImHexApi::System::getCommitHash(true))
return ImGui::GetStyleColorVec4(ImGuiCol_HeaderActive);
else
return ImGui::GetStyleColorVec4(ImGuiCol_Text);
}();
ImGuiExt::TextFormattedColored(color, commit.message);
}
void ViewAbout::drawLicensePage() {
const auto indentation = 50_scaled;
ImGui::Indent(indentation);
ImGuiExt::TextFormattedWrapped("{}", romfs::get("licenses/LICENSE").string());
ImGui::Unindent(indentation);
}
void ViewAbout::drawAboutPopup() {
struct Tab {
using Function = void (ViewAbout::*)();
const char *unlocalizedName;
Function function;
};
constexpr std::array Tabs = {
Tab { "ImHex", &ViewAbout::drawAboutMainPage },
Tab { "hex.builtin.view.help.about.contributor", &ViewAbout::drawContributorPage },
Tab { "hex.builtin.view.help.about.libs", &ViewAbout::drawLibraryCreditsPage },
Tab { "hex.builtin.view.help.about.plugins", &ViewAbout::drawLoadedPlugins },
Tab { "hex.builtin.view.help.about.paths", &ViewAbout::drawPathsPage },
Tab { "hex.builtin.view.help.about.release_notes", &ViewAbout::drawReleaseNotesPage },
Tab { "hex.builtin.view.help.about.commits", &ViewAbout::drawCommitHistoryPage },
Tab { "hex.builtin.view.help.about.license", &ViewAbout::drawLicensePage },
};
// Allow the window to be closed by pressing ESC
if (ImGui::IsKeyDown(ImGuiKey_Escape))
ImGui::CloseCurrentPopup();
if (ImGui::BeginTabBar("about_tab_bar")) {
// Draw all tabs
for (const auto &[unlocalizedName, function] : Tabs) {
if (ImGui::BeginTabItem(Lang(unlocalizedName))) {
ImGui::NewLine();
if (ImGui::BeginChild(1)) {
(this->*function)();
}
ImGui::EndChild();
ImGui::EndTabItem();
}
}
ImGui::EndTabBar();
}
}
void ViewAbout::drawContent() {
this->drawAboutPopup();
}
}
| 35,916
|
C++
|
.cpp
| 686
| 39.017493
| 227
| 0.553369
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
230
|
view_provider_settings.cpp
|
WerWolv_ImHex/plugins/builtin/source/content/views/view_provider_settings.cpp
|
#include "content/views/view_provider_settings.hpp"
#include <hex/api/content_registry.hpp>
#include <hex/api/task_manager.hpp>
#include <toasts/toast_notification.hpp>
namespace hex::plugin::builtin {
ViewProviderSettings::ViewProviderSettings() : View::Modal("hex.builtin.view.provider_settings.name") {
EventProviderCreated::subscribe(this, [this](const hex::prv::Provider *provider) {
if (provider->hasLoadInterface() && !provider->shouldSkipLoadInterface())
this->getWindowOpenState() = true;
});
ContentRegistry::Interface::addSidebarItem(ICON_VS_SERVER_PROCESS, [] {
auto provider = hex::ImHexApi::Provider::get();
if (provider != nullptr)
provider->drawInterface();
},
[] {
auto provider = hex::ImHexApi::Provider::get();
return provider != nullptr && provider->hasInterface() && provider->isAvailable();
});
}
ViewProviderSettings::~ViewProviderSettings() {
EventProviderCreated::unsubscribe(this);
}
void ViewProviderSettings::drawContent() {
auto provider = hex::ImHexApi::Provider::get();
if (provider != nullptr) {
bool settingsValid = provider->drawLoadInterface();
ImGui::NewLine();
ImGui::Separator();
ImGui::BeginDisabled(!settingsValid);
if (ImGui::Button("hex.ui.common.open"_lang)) {
if (provider->open()) {
EventProviderOpened::post(provider);
this->getWindowOpenState() = false;
ImGui::CloseCurrentPopup();
}
else {
this->getWindowOpenState() = false;
ImGui::CloseCurrentPopup();
auto errorMessage = provider->getErrorMessage();
if (errorMessage.empty()) {
ui::ToastError::open("hex.builtin.view.provider_settings.load_error"_lang);
} else {
ui::ToastError::open(hex::format("hex.builtin.view.provider_settings.load_error_details"_lang, errorMessage));
}
TaskManager::doLater([=] { ImHexApi::Provider::remove(provider); });
}
}
ImGui::EndDisabled();
ImGui::SameLine();
if (ImGui::Button("hex.ui.common.cancel"_lang)) {
ImGui::CloseCurrentPopup();
this->getWindowOpenState() = false;
TaskManager::doLater([=] { ImHexApi::Provider::remove(provider); });
}
}
}
bool ViewProviderSettings::hasViewMenuItemEntry() const {
return false;
}
}
| 2,764
|
C++
|
.cpp
| 61
| 32.704918
| 134
| 0.56792
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
231
|
view_constants.cpp
|
WerWolv_ImHex/plugins/builtin/source/content/views/view_constants.cpp
|
#include "content/views/view_constants.hpp"
#include <hex/helpers/logger.hpp>
#include <hex/helpers/utils.hpp>
#include <hex/helpers/default_paths.hpp>
#include <wolv/utils/string.hpp>
#include <wolv/io/file.hpp>
#include <filesystem>
#include <nlohmann/json.hpp>
#include <fonts/codicons_font.h>
namespace hex::plugin::builtin {
ViewConstants::ViewConstants() : View::Window("hex.builtin.view.constants.name", ICON_VS_SYMBOL_CONSTANT) {
this->reloadConstants();
}
void ViewConstants::reloadConstants() {
m_constants.clear();
m_filterIndices.clear();
for (const auto &path : paths::Constants.read()) {
if (!wolv::io::fs::exists(path)) continue;
std::error_code error;
for (auto &file : std::fs::directory_iterator(path, error)) {
if (!file.is_regular_file()) continue;
if (file.path().extension() != ".json") continue;
if (file.path().filename().u8string().starts_with('_')) continue;
try {
auto fileData = wolv::io::File(file.path(), wolv::io::File::Mode::Read).readString();
auto content = nlohmann::json::parse(fileData);
for (auto value : content.at("values")) {
Constant constant;
constant.category = content.at("name").get<std::string>();
constant.name = value.at("name").get<std::string>();
if (value.contains("desc"))
constant.description = value.at("desc").get<std::string>();
constant.value = value.at("value").get<std::string>();
auto type = value.at("type");
if (type == "int10")
constant.type = ConstantType::Int10;
else if (type == "int16be")
constant.type = ConstantType::Int16BigEndian;
else if (type == "int16le")
constant.type = ConstantType::Int16LittleEndian;
else
throw std::runtime_error("Invalid type");
m_filterIndices.push_back(m_constants.size());
m_constants.push_back(constant);
}
} catch (...) {
log::error("Failed to parse constants file {}", wolv::util::toUTF8String(file.path()));
}
}
}
}
void ViewConstants::drawContent() {
ImGui::PushItemWidth(-1);
if (ImGuiExt::InputTextIcon("##search", ICON_VS_FILTER, m_filter)) {
m_filterIndices.clear();
// Filter the constants according to the entered value
for (u64 i = 0; i < m_constants.size(); i++) {
auto &constant = m_constants[i];
if (hex::containsIgnoreCase(constant.name, m_filter) ||
hex::containsIgnoreCase(constant.category, m_filter) ||
hex::containsIgnoreCase(constant.description, m_filter) ||
hex::containsIgnoreCase(constant.value, m_filter))
m_filterIndices.push_back(i);
}
}
ImGui::PopItemWidth();
if (ImGui::BeginTable("##strings", 4, ImGuiTableFlags_Borders | ImGuiTableFlags_Resizable | ImGuiTableFlags_Sortable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_RowBg | ImGuiTableFlags_ScrollY)) {
ImGui::TableSetupScrollFreeze(0, 1);
ImGui::TableSetupColumn("hex.builtin.view.constants.row.category"_lang, 0, -1, ImGui::GetID("category"));
ImGui::TableSetupColumn("hex.builtin.view.constants.row.name"_lang, 0, -1, ImGui::GetID("name"));
ImGui::TableSetupColumn("hex.builtin.view.constants.row.desc"_lang, 0, -1, ImGui::GetID("desc"));
ImGui::TableSetupColumn("hex.builtin.view.constants.row.value"_lang, 0, -1, ImGui::GetID("value"));
auto sortSpecs = ImGui::TableGetSortSpecs();
// Handle table sorting
if (sortSpecs->SpecsDirty) {
std::sort(m_constants.begin(), m_constants.end(), [&sortSpecs](const Constant &left, const Constant &right) -> bool {
if (sortSpecs->Specs->ColumnUserID == ImGui::GetID("category")) {
if (sortSpecs->Specs->SortDirection == ImGuiSortDirection_Ascending)
return left.category > right.category;
else
return left.category < right.category;
} else if (sortSpecs->Specs->ColumnUserID == ImGui::GetID("name")) {
if (sortSpecs->Specs->SortDirection == ImGuiSortDirection_Ascending)
return left.name > right.name;
else
return left.name < right.name;
} else if (sortSpecs->Specs->ColumnUserID == ImGui::GetID("desc")) {
if (sortSpecs->Specs->SortDirection == ImGuiSortDirection_Ascending)
return left.description > right.description;
else
return left.description < right.description;
} else if (sortSpecs->Specs->ColumnUserID == ImGui::GetID("value")) {
if (sortSpecs->Specs->SortDirection == ImGuiSortDirection_Ascending)
return left.value > right.value;
else
return left.value < right.value;
}
return false;
});
sortSpecs->SpecsDirty = false;
}
ImGui::TableHeadersRow();
ImGuiListClipper clipper;
clipper.Begin(m_filterIndices.size());
// Draw the constants table
while (clipper.Step()) {
for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) {
auto &constant = m_constants[m_filterIndices[i]];
ImGui::TableNextRow();
ImGui::TableNextColumn();
ImGui::TextUnformatted(constant.category.c_str());
ImGui::TableNextColumn();
ImGui::TextUnformatted(constant.name.c_str());
ImGui::TableNextColumn();
ImGui::TextUnformatted(constant.description.c_str());
ImGui::TableNextColumn();
ImGui::TextUnformatted(constant.value.c_str());
}
}
clipper.End();
ImGui::EndTable();
}
}
}
| 6,792
|
C++
|
.cpp
| 124
| 37.717742
| 208
| 0.529137
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
232
|
view_bookmarks.cpp
|
WerWolv_ImHex/plugins/builtin/source/content/views/view_bookmarks.cpp
|
#include "content/views/view_bookmarks.hpp"
#include <hex/api/content_registry.hpp>
#include <hex/api/project_file_manager.hpp>
#include <hex/api/achievement_manager.hpp>
#include <hex/api/task_manager.hpp>
#include <hex/helpers/fmt.hpp>
#include <hex/helpers/utils.hpp>
#include <hex/providers/provider.hpp>
#include <content/providers/view_provider.hpp>
#include <fonts/codicons_font.h>
#include <nlohmann/json.hpp>
#include <wolv/io/file.hpp>
#include <wolv/utils/guards.hpp>
namespace hex::plugin::builtin {
ViewBookmarks::ViewBookmarks() : View::Window("hex.builtin.view.bookmarks.name", ICON_VS_BOOKMARK) {
// Handle bookmark add requests sent by the API
RequestAddBookmark::subscribe(this, [this](Region region, std::string name, std::string comment, color_t color, u64 *id) {
if (name.empty()) {
name = hex::format("hex.builtin.view.bookmarks.default_title"_lang, region.address, region.address + region.size - 1);
}
if (color == 0x00)
color = ImGui::GetColorU32(ImGuiCol_Header);
m_currBookmarkId += 1;
u64 bookmarkId = m_currBookmarkId;
if (id != nullptr)
*id = bookmarkId;
auto bookmark = ImHexApi::Bookmarks::Entry {
region,
name,
std::move(comment),
color,
true,
bookmarkId
};
m_bookmarks->emplace_back(std::move(bookmark), TextEditor());
ImHexApi::Provider::markDirty();
EventBookmarkCreated::post(m_bookmarks->back().entry);
EventHighlightingChanged::post();
});
RequestRemoveBookmark::subscribe([this](u64 id) {
std::erase_if(m_bookmarks.get(), [id](const auto &bookmark) {
return bookmark.entry.id == id;
});
});
// Draw hex editor background highlights for bookmarks
ImHexApi::HexEditor::addBackgroundHighlightingProvider([this](u64 address, const u8* data, size_t size, bool) -> std::optional<color_t> {
hex::unused(data);
// Check all bookmarks for potential overlaps with the current address
for (const auto &bookmark : *m_bookmarks) {
if (Region { address, size }.isWithin(bookmark.entry.region))
return bookmark.entry.color;
}
return std::nullopt;
});
// Draw hex editor tooltips for bookmarks
ImHexApi::HexEditor::addTooltipProvider([this](u64 address, const u8 *data, size_t size) {
hex::unused(data);
// Loop over all bookmarks
for (const auto &[bookmark, editor] : *m_bookmarks) {
// Make sure the bookmark overlaps the currently hovered address
if (!Region { address, size }.isWithin(bookmark.region))
continue;
// Draw tooltip
ImGui::BeginTooltip();
ImGui::PushID(&bookmark);
if (ImGui::BeginTable("##tooltips", 1, ImGuiTableFlags_RowBg | ImGuiTableFlags_NoClip)) {
ImGui::TableNextRow();
ImGui::TableNextColumn();
{
// Draw bookmark header
ImGui::ColorButton("##color", ImColor(bookmark.color));
ImGui::SameLine(0, 10);
ImGuiExt::TextFormatted("{} ", bookmark.name);
// Draw extra information table when holding down shift
if (ImGui::GetIO().KeyShift) {
ImGui::Indent();
if (ImGui::BeginTable("##extra_info", 2, ImGuiTableFlags_RowBg | ImGuiTableFlags_NoClip)) {
ImGui::TableNextRow();
ImGui::TableNextColumn();
// Draw region
ImGui::TableNextRow();
ImGui::TableNextColumn();
ImGuiExt::TextFormatted("{}: ", "hex.ui.common.region"_lang.get());
ImGui::TableNextColumn();
ImGuiExt::TextFormatted("[ 0x{:08X} - 0x{:08X} ] ", bookmark.region.getStartAddress(), bookmark.region.getEndAddress());
// Draw comment if it's not empty
if (!bookmark.comment.empty() && bookmark.comment[0] != '\x00') {
ImGui::TableNextRow();
ImGui::TableNextColumn();
ImGuiExt::TextFormatted("{}: ", "hex.builtin.view.bookmarks.header.comment"_lang.get());
ImGui::TableNextColumn();
ImGui::PushTextWrapPos(ImGui::CalcTextSize("X").x * 40);
ImGuiExt::TextFormattedWrapped("{}", bookmark.comment);
ImGui::PopTextWrapPos();
}
ImGui::EndTable();
}
ImGui::Unindent();
}
}
ImGui::PushStyleColor(ImGuiCol_TableRowBg, bookmark.color);
ImGui::PushStyleColor(ImGuiCol_TableRowBgAlt, bookmark.color);
ImGui::EndTable();
ImGui::PopStyleColor(2);
}
ImGui::PopID();
ImGui::EndTooltip();
}
});
// Handle saving / restoring of bookmarks in projects
ProjectFile::registerPerProviderHandler({
.basePath = "bookmarks.json",
.required = false,
.load = [this](prv::Provider *provider, const std::fs::path &basePath, const Tar &tar) -> bool {
auto fileContent = tar.readString(basePath);
if (fileContent.empty())
return true;
auto data = nlohmann::json::parse(fileContent.begin(), fileContent.end());
m_bookmarks.get(provider).clear();
return this->importBookmarks(provider, data);
},
.store = [this](prv::Provider *provider, const std::fs::path &basePath, const Tar &tar) -> bool {
nlohmann::json data;
bool result = this->exportBookmarks(provider, data);
tar.writeString(basePath, data.dump(4));
return result;
}
});
ContentRegistry::Reports::addReportProvider([this](prv::Provider *provider) -> std::string {
std::string result;
const auto &bookmarks = m_bookmarks.get(provider);
if (bookmarks.empty())
return "";
result += "## Bookmarks\n\n";
for (const auto &[bookmark, editor] : bookmarks) {
result += hex::format("### <span style=\"background-color: #{:06X}80\">{} [0x{:04X} - 0x{:04X}]</span>\n\n", hex::changeEndianness(bookmark.color, std::endian::big) >> 8, bookmark.name, bookmark.region.getStartAddress(), bookmark.region.getEndAddress());
for (const auto &line : hex::splitString(bookmark.comment, "\n"))
result += hex::format("> {}\n", line);
result += "\n";
result += "```\n";
result += hex::generateHexView(bookmark.region.getStartAddress(), bookmark.region.getSize(), provider);
result += "\n```\n\n";
}
return result;
});
this->registerMenuItems();
}
ViewBookmarks::~ViewBookmarks() {
RequestAddBookmark::unsubscribe(this);
EventProviderDeleted::unsubscribe(this);
}
static void drawColorPopup(ImColor &color) {
// Generate color picker palette
const static auto Palette = [] {
constexpr static auto ColorCount = 36;
std::array<ImColor, ColorCount> result = { 0 };
u32 counter = 0;
for (auto &color : result) {
ImGui::ColorConvertHSVtoRGB(float(counter) / float(ColorCount - 1), 0.8F, 0.8F, color.Value.x, color.Value.y, color.Value.z);
color.Value.w = 0.7F;
counter++;
}
return result;
}();
bool colorChanged = false;
// Draw default color picker
if (ImGui::ColorPicker4("##picker", &color.Value.x, ImGuiColorEditFlags_NoSidePreview | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoOptions | ImGuiColorEditFlags_NoSmallPreview))
colorChanged = true;
ImGui::Separator();
// Draw color palette
int id = 0;
for (const auto &paletteColor : Palette) {
ImGui::PushID(id);
if ((id % 9) != 0)
ImGui::SameLine(0.0F, ImGui::GetStyle().ItemSpacing.y);
constexpr static ImGuiColorEditFlags flags = ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_NoDragDrop;
if (ImGui::ColorButton("##palette", paletteColor.Value, flags, ImVec2(20, 20))) {
color = paletteColor;
colorChanged = true;
}
ImGui::PopID();
id++;
}
if (colorChanged)
EventHighlightingChanged::post();
}
void ViewBookmarks::drawDropTarget(std::list<Bookmark>::iterator it, float height) {
height = std::max(height, 1.0F);
if (it != m_bookmarks->begin()) {
ImGui::SetCursorPosY(ImGui::GetCursorPosY() - height);
} else {
ImGui::SetCursorPosY(ImGui::GetCursorPosY() + height);
}
ImGui::InvisibleButton("##DropTarget", ImVec2(ImGui::GetContentRegionAvail().x, height * 2.0F));
const auto dropTarget = ImRect(ImGui::GetItemRectMin(), ImVec2(ImGui::GetItemRectMax().x, ImGui::GetItemRectMin().y + 2_scaled));
if (it == m_bookmarks->begin()) {
ImGui::SetCursorPosY(ImGui::GetCursorPosY() - height);
}
ImGui::PushStyleColor(ImGuiCol_DragDropTarget, 0x00);
if (ImGui::BeginDragDropTarget()) {
ImGui::GetWindowDrawList()->AddRectFilled(dropTarget.Min, dropTarget.Max, ImGui::GetColorU32(ImGuiCol_ButtonActive));
if (auto payload = ImGui::AcceptDragDropPayload("BOOKMARK_PAYLOAD"); payload != nullptr) {
// Receive the bookmark id from the payload
u64 droppedBookmarkId = *static_cast<const u64*>(payload->Data);
// Find the correct bookmark with that id
auto droppedIter = std::ranges::find_if(m_bookmarks->begin(), m_bookmarks->end(), [droppedBookmarkId](const auto &bookmarkItem) {
return bookmarkItem.entry.id == droppedBookmarkId;
});
// Swap the two bookmarks
if (droppedIter != m_bookmarks->end()) {
m_bookmarks->splice(it, m_bookmarks, droppedIter);
EventHighlightingChanged::post();
}
}
ImGui::EndDragDropTarget();
}
ImGui::PopStyleColor();
}
void ViewBookmarks::drawContent() {
// Draw filter input
ImGui::PushItemWidth(-1);
ImGuiExt::InputTextIcon("##filter", ICON_VS_FILTER, m_currFilter);
ImGui::PopItemWidth();
if (ImGui::BeginChild("##bookmarks")) {
if (m_bookmarks->empty()) {
ImGuiExt::TextFormattedCentered("hex.builtin.view.bookmarks.no_bookmarks"_lang);
}
auto bookmarkToRemove = m_bookmarks->end();
const auto defaultItemSpacing = ImGui::GetStyle().ItemSpacing.y;
ImGui::Dummy({ ImGui::GetContentRegionAvail().x, 0 });
drawDropTarget(m_bookmarks->begin(), defaultItemSpacing);
// Draw all bookmarks
for (auto it = m_bookmarks->begin(); it != m_bookmarks->end(); ++it) {
auto &[bookmark, editor] = *it;
auto &[region, name, comment, color, locked, bookmarkId] = bookmark;
// Apply filter
if (!m_currFilter.empty()) {
if (!name.contains(m_currFilter) && !comment.contains(m_currFilter))
continue;
}
auto headerColor = ImColor(color);
auto hoverColor = ImColor(color);
hoverColor.Value.w *= 1.3F;
// Draw bookmark header in the same color as the bookmark was set to
ImGui::PushID(bookmarkId);
ImGui::PushStyleColor(ImGuiCol_Header, color);
ImGui::PushStyleColor(ImGuiCol_HeaderActive, color);
ImGui::PushStyleColor(ImGuiCol_HeaderHovered, u32(hoverColor));
ON_SCOPE_EXIT {
ImGui::PopStyleColor(3);
ImGui::PopID();
};
bool notDeleted = true;
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2());
auto expanded = ImGui::CollapsingHeader(hex::format("{}###bookmark", name).c_str(), ¬Deleted);
ImGui::PopStyleVar();
if (!expanded) {
// Handle dragging bookmarks up and down when they're collapsed
if (ImGui::BeginDragDropSource(ImGuiDragDropFlags_SourceNoHoldToOpenOthers | ImGuiDragDropFlags_SourceAllowNullID)) {
// Set the payload to the bookmark id
ImGui::SetDragDropPayload("BOOKMARK_PAYLOAD", &bookmarkId, sizeof(bookmarkId));
// Draw drag and drop tooltip
ImGui::ColorButton("##color", headerColor.Value, ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoTooltip | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_NoAlpha);
ImGui::SameLine();
ImGuiExt::TextFormatted("{}", name);
if (!comment.empty()) {
ImGui::Separator();
ImGui::PushTextWrapPos(300_scaled);
ImGuiExt::TextFormatted("{}", comment);
ImGui::PopTextWrapPos();
}
ImGui::EndDragDropSource();
}
}
auto nextPos = ImGui::GetCursorPos();
ImGui::SameLine();
ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ImGui::GetContentRegionAvail().x - 70_scaled);
{
// Draw jump to region button
if (ImGuiExt::DimmedIconButton(ICON_VS_DEBUG_STEP_BACK, ImGui::GetStyleColorVec4(ImGuiCol_Text)))
ImHexApi::HexEditor::setSelection(region);
ImGui::SetItemTooltip("%s", "hex.builtin.view.bookmarks.tooltip.jump_to"_lang.get());
ImGui::SameLine(0, 1_scaled);
// Draw open in new view button
if (ImGuiExt::DimmedIconButton(ICON_VS_GO_TO_FILE, ImGui::GetStyleColorVec4(ImGuiCol_Text))) {
auto provider = ImHexApi::Provider::get();
TaskManager::doLater([region, provider, name]{
auto newProvider = ImHexApi::Provider::createProvider("hex.builtin.provider.view", true);
if (auto *viewProvider = dynamic_cast<ViewProvider*>(newProvider); viewProvider != nullptr) {
viewProvider->setProvider(region.getStartAddress(), region.getSize(), provider);
viewProvider->setName(hex::format("'{}' View", name));
if (viewProvider->open()) {
EventProviderOpened::post(viewProvider);
AchievementManager::unlockAchievement("hex.builtin.achievement.hex_editor", "hex.builtin.achievement.hex_editor.open_new_view.name");
}
}
});
}
ImGui::SetItemTooltip("%s", "hex.builtin.view.bookmarks.tooltip.open_in_view"_lang.get());
}
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2());
drawDropTarget(std::next(it), defaultItemSpacing);
ImGui::PopStyleVar();
ImGui::SetCursorPos(nextPos);
ImGui::Dummy({});
if (expanded) {
const auto rowHeight = ImGui::GetTextLineHeightWithSpacing() + 2 * ImGui::GetStyle().FramePadding.y;
if (ImGui::BeginTable("##bookmark_table", 3, ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingFixedFit)) {
ImGui::TableSetupColumn("##name");
ImGui::TableSetupColumn("##spacing", ImGuiTableColumnFlags_WidthFixed, 20);
ImGui::TableSetupColumn("##value", ImGuiTableColumnFlags_WidthStretch);
ImGui::TableNextRow(ImGuiTableRowFlags_None, rowHeight);
ImGui::TableNextColumn();
// Draw bookmark name
ImGui::TextUnformatted("hex.builtin.view.bookmarks.header.name"_lang);
ImGui::TableNextColumn();
ImGui::TableNextColumn();
// Draw lock/unlock button
ImGuiExt::DimmedIconToggle(ICON_VS_LOCK, ICON_VS_UNLOCK, &locked);
if (locked)
ImGuiExt::InfoTooltip("hex.builtin.view.bookmarks.tooltip.unlock"_lang);
else
ImGuiExt::InfoTooltip("hex.builtin.view.bookmarks.tooltip.lock"_lang);
ImGui::SameLine();
// Draw color button
if (ImGui::ColorButton("hex.builtin.view.bookmarks.header.color"_lang, headerColor.Value, ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoTooltip | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_NoAlpha)) {
if (!locked)
ImGui::OpenPopup("hex.builtin.view.bookmarks.header.color"_lang);
}
ImGuiExt::InfoTooltip("hex.builtin.view.bookmarks.header.color"_lang);
// Draw color picker
if (ImGui::BeginPopup("hex.builtin.view.bookmarks.header.color"_lang)) {
drawColorPopup(headerColor);
color = headerColor;
ImGui::EndPopup();
}
ImGui::SameLine();
// Draw bookmark name if the bookmark is locked or an input text box if it's unlocked
if (locked) {
ImGui::TextUnformatted(name.data());
} else {
ImGui::PushItemWidth(ImGui::GetContentRegionAvail().x);
ImGui::InputText("##nameInput", name);
ImGui::PopItemWidth();
}
ImGui::TableNextRow(ImGuiTableRowFlags_None, rowHeight);
ImGui::TableNextColumn();
ImGui::TextUnformatted("hex.ui.common.address"_lang);
ImGui::TableNextColumn();
ImGui::TableNextColumn();
// Draw the address of the bookmark
u64 begin = region.getStartAddress();
u64 end = region.getEndAddress();
if (!locked) {
bool updated = false;
ImGui::PushItemWidth(100_scaled);
if (ImGuiExt::InputHexadecimal("##begin", &begin))
updated = true;
ImGui::SameLine(0, 0);
ImGui::TextUnformatted(" - ");
ImGui::SameLine(0, 0);
if (ImGuiExt::InputHexadecimal("##end", &end))
updated = true;
ImGui::PopItemWidth();
if (updated && end >= begin) {
region = Region(begin, end - begin + 1);
EventHighlightingChanged::post();
}
} else {
ImGuiExt::TextFormatted("0x{:02X} - 0x{:02X}", begin, end);
}
ImGui::TableNextRow(ImGuiTableRowFlags_None, rowHeight);
ImGui::TableNextColumn();
// Draw size of the bookmark
ImGui::TextUnformatted("hex.ui.common.size"_lang);
ImGui::TableNextColumn();
ImGui::TableNextColumn();
ImGuiExt::TextFormatted(hex::toByteString(region.size));
ImGui::EndTable();
}
// Draw comment if the bookmark is locked or an input text box if it's unlocked
editor.SetReadOnly(locked);
editor.SetShowLineNumbers(!locked);
editor.SetShowCursor(!locked);
editor.SetShowWhitespaces(false);
if (!locked || (locked && !comment.empty())) {
ImGuiExt::Header("hex.builtin.view.bookmarks.header.comment"_lang);
editor.Render("##comment", ImVec2(ImGui::GetContentRegionAvail().x, 150_scaled), true);
if (editor.IsTextChanged())
comment = editor.GetText();
}
ImGui::NewLine();
}
// Mark a bookmark for removal when the user clicks the remove button
if (!notDeleted)
bookmarkToRemove = it;
}
// Remove the bookmark that was marked for removal
if (bookmarkToRemove != m_bookmarks->end()) {
m_bookmarks->erase(bookmarkToRemove);
EventHighlightingChanged::post();
}
}
ImGui::EndChild();
}
bool ViewBookmarks::importBookmarks(prv::Provider *provider, const nlohmann::json &json) {
if (!json.contains("bookmarks"))
return false;
for (const auto &bookmark : json["bookmarks"]) {
if (!bookmark.contains("name") || !bookmark.contains("comment") || !bookmark.contains("color") || !bookmark.contains("region") || !bookmark.contains("locked"))
continue;
const auto ®ion = bookmark["region"];
if (!region.contains("address") || !region.contains("size"))
continue;
TextEditor editor;
editor.SetText(bookmark["comment"]);
m_bookmarks.get(provider).push_back({
{
.region = { region["address"], region["size"] },
.name = bookmark["name"],
.comment = bookmark["comment"],
.color = bookmark["color"],
.locked = bookmark["locked"],
.id = bookmark.contains("id") ? bookmark["id"].get<u64>() : m_currBookmarkId.get(provider)
},
editor
});
if (bookmark.contains("id"))
m_currBookmarkId.get(provider) = std::max<u64>(m_currBookmarkId.get(provider), bookmark["id"].get<i64>() + 1);
else
m_currBookmarkId.get(provider) += 1;
}
return true;
}
bool ViewBookmarks::exportBookmarks(prv::Provider *provider, nlohmann::json &json) {
json["bookmarks"] = nlohmann::json::array();
size_t index = 0;
for (const auto &[bookmark, editor] : m_bookmarks.get(provider)) {
json["bookmarks"][index] = {
{ "name", bookmark.name },
{ "comment", editor.GetText() },
{ "color", bookmark.color },
{ "region", {
{ "address", bookmark.region.address },
{ "size", bookmark.region.size }
}
},
{ "locked", bookmark.locked },
{ "id", bookmark.id }
};
index++;
}
return true;
}
void ViewBookmarks::registerMenuItems() {
/* Create bookmark */
ContentRegistry::Interface::addMenuItem({ "hex.builtin.menu.edit", "hex.builtin.menu.edit.bookmark.create" }, ICON_VS_BOOKMARK, 1900, CTRLCMD + Keys::B, [&] {
if (!ImHexApi::HexEditor::isSelectionValid())
return;
auto selection = ImHexApi::HexEditor::getSelection();
ImHexApi::Bookmarks::add(selection->getStartAddress(), selection->getSize(), {}, {});
}, []{ return ImHexApi::Provider::isValid() && ImHexApi::HexEditor::isSelectionValid(); });
ContentRegistry::Interface::addMenuItemSeparator({ "hex.builtin.menu.file", "hex.builtin.menu.file.import" }, 3000);
/* Import bookmarks */
ContentRegistry::Interface::addMenuItem({ "hex.builtin.menu.file", "hex.builtin.menu.file.import", "hex.builtin.menu.file.import.bookmark" }, ICON_VS_BOOKMARK, 3050, Shortcut::None, [this]{
fs::openFileBrowser(fs::DialogMode::Open, { { "Bookmarks File", "hexbm"} }, [&, this](const std::fs::path &path) {
try {
this->importBookmarks(ImHexApi::Provider::get(), nlohmann::json::parse(wolv::io::File(path, wolv::io::File::Mode::Read).readString()));
} catch (...) { }
});
}, ImHexApi::Provider::isValid);
ContentRegistry::Interface::addMenuItemSeparator({ "hex.builtin.menu.file", "hex.builtin.menu.file.export" }, 6200);
/* Export bookmarks */
ContentRegistry::Interface::addMenuItem({ "hex.builtin.menu.file", "hex.builtin.menu.file.export", "hex.builtin.menu.file.export.bookmark" }, ICON_VS_BOOKMARK, 6250, Shortcut::None, [this]{
fs::openFileBrowser(fs::DialogMode::Save, { { "Bookmarks File", "hexbm"} }, [&, this](const std::fs::path &path) {
nlohmann::json json;
this->exportBookmarks(ImHexApi::Provider::get(), json);
wolv::io::File(path, wolv::io::File::Mode::Create).writeString(json.dump(4));
});
}, [this]{
return ImHexApi::Provider::isValid() && !m_bookmarks->empty();
});
}
}
| 27,244
|
C++
|
.cpp
| 484
| 38.28719
| 270
| 0.522515
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
233
|
view_information.cpp
|
WerWolv_ImHex/plugins/builtin/source/content/views/view_information.cpp
|
#include "content/views/view_information.hpp"
#include <hex/api/content_registry.hpp>
#include <hex/api/achievement_manager.hpp>
#include <hex/api/project_file_manager.hpp>
#include <hex/providers/provider.hpp>
#include <hex/helpers/magic.hpp>
#include <toasts/toast_notification.hpp>
namespace hex::plugin::builtin {
using namespace hex::literals;
ViewInformation::ViewInformation() : View::Window("hex.builtin.view.information.name", ICON_VS_GRAPH_LINE) {
m_analysisData.setOnCreateCallback([](const prv::Provider *provider, AnalysisData &data) {
data.analyzedProvider = provider;
for (const auto &informationSectionConstructor : ContentRegistry::DataInformation::impl::getInformationSectionConstructors()) {
data.informationSections.push_back(informationSectionConstructor());
}
});
ProjectFile::registerPerProviderHandler({
.basePath = "data_information.json",
.required = false,
.load = [this](prv::Provider *provider, const std::fs::path &basePath, const Tar &tar) {
std::string save = tar.readString(basePath);
nlohmann::json input = nlohmann::json::parse(save);
for (const auto §ion : m_analysisData.get(provider).informationSections) {
if (!input.contains(section->getUnlocalizedName().get()))
continue;
section->load(input[section->getUnlocalizedName().get()]);
}
return true;
},
.store = [this](prv::Provider *provider, const std::fs::path &basePath, const Tar &tar) {
nlohmann::json output;
for (const auto §ion : m_analysisData.get(provider).informationSections) {
output[section->getUnlocalizedName().get()] = section->store();
}
tar.writeString(basePath, output.dump(4));
return true;
}
});
}
void ViewInformation::analyze() {
AchievementManager::unlockAchievement("hex.builtin.achievement.misc", "hex.builtin.achievement.misc.analyze_file.name");
auto provider = ImHexApi::Provider::get();
auto &analysis = m_analysisData.get(provider);
// Reset all sections
for (const auto §ion : analysis.informationSections) {
section->reset();
section->markValid(false);
}
// Run analyzers for each section
analysis.task = TaskManager::createTask("hex.builtin.view.information.analyzing"_lang, analysis.informationSections.size(), [provider, &analysis](Task &task) {
u32 progress = 0;
for (const auto §ion : analysis.informationSections) {
// Only process the section if it is enabled
if (section->isEnabled()) {
// Set the section as analyzing so a spinner can be drawn
section->setAnalyzing(true);
ON_SCOPE_EXIT { section->setAnalyzing(false); };
try {
// Process the section
section->process(task, provider, analysis.analysisRegion);
// Mark the section as valid
section->markValid();
} catch (const std::exception &e) {
// Show a toast with the error if the section failed to process
ui::ToastError::open(hex::format("hex.builtin.view.information.error_processing_section"_lang, Lang(section->getUnlocalizedName()), e.what()));
}
}
// Update the task progress
progress += 1;
task.update(progress);
}
});
}
void ViewInformation::drawContent() {
if (ImGui::BeginChild("##scrolling", ImVec2(0, 0), false, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoNav)) {
auto provider = ImHexApi::Provider::get();
if (ImHexApi::Provider::isValid() && provider->isReadable()) {
auto &analysis = m_analysisData.get(provider);
// Draw settings window
ImGui::BeginDisabled(analysis.task.isRunning());
if (ImGuiExt::BeginSubWindow("hex.ui.common.settings"_lang)) {
// Create a table so we can draw global settings on the left and section specific settings on the right
if (ImGui::BeginTable("SettingsTable", 2, ImGuiTableFlags_BordersInner | ImGuiTableFlags_SizingStretchProp, ImVec2(ImGui::GetContentRegionAvail().x, 0))) {
ImGui::TableSetupColumn("Left", ImGuiTableColumnFlags_WidthStretch, 0.3F);
ImGui::TableSetupColumn("Right", ImGuiTableColumnFlags_WidthStretch, 0.7F);
ImGui::TableNextRow();
// Draw global settings
ImGui::TableNextColumn();
ui::regionSelectionPicker(&analysis.analysisRegion, provider, &analysis.selectionType, false);
// Draw analyzed section names
ImGui::TableNextColumn();
if (ImGui::BeginTable("AnalyzedSections", 1, ImGuiTableFlags_BordersInnerH, ImVec2(ImGui::GetContentRegionAvail().x, ImGui::GetTextLineHeightWithSpacing() * 5))) {
for (const auto §ion : analysis.informationSections | std::views::reverse) {
if (section->isEnabled() && (section->isValid() || section->isAnalyzing())) {
ImGui::TableNextRow();
ImGui::TableNextColumn();
ImGui::BeginDisabled();
{
ImGui::TextUnformatted(Lang(section->getUnlocalizedName()));
if (section->isAnalyzing()) {
ImGui::SameLine();
ImGuiExt::TextSpinner("");
}
}
ImGui::EndDisabled();
}
}
ImGui::EndTable();
}
ImGui::EndTable();
}
ImGui::NewLine();
// Draw the analyze button
ImGui::SetCursorPosX(50_scaled);
if (ImGuiExt::DimmedButton("hex.builtin.view.information.analyze"_lang, ImVec2(ImGui::GetContentRegionAvail().x - 50_scaled, 0)))
this->analyze();
}
ImGuiExt::EndSubWindow();
ImGui::EndDisabled();
if (analysis.analyzedProvider != nullptr) {
for (const auto §ion : analysis.informationSections) {
ImGui::TableNextColumn();
ImGui::PushID(section.get());
bool enabled = section->isEnabled();
ImGui::PushStyleVar(ImGuiStyleVar_ChildRounding, 5.0F);
if (ImGui::BeginChild(Lang(section->getUnlocalizedName()), ImVec2(0, 0), ImGuiChildFlags_Border | ImGuiChildFlags_AutoResizeY, ImGuiWindowFlags_MenuBar)) {
if (ImGui::BeginMenuBar()) {
// Draw the enable checkbox of the section
// This is specifically split out so the checkbox does not get disabled when the section is disabled
ImGui::BeginGroup();
{
ImGui::SetCursorPosY(ImGui::GetCursorPosY() + ImGui::GetStyle().FramePadding.y);
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0));
{
if (ImGui::Checkbox("##enabled", &enabled)) {
section->setEnabled(enabled);
}
}
ImGui::PopStyleVar();
}
ImGui::EndGroup();
ImGui::SameLine();
// Draw the rest of the section header
ImGui::BeginDisabled(!enabled);
{
ImGui::TextUnformatted(Lang(section->getUnlocalizedName()));
ImGui::SameLine();
if (auto description = section->getUnlocalizedDescription(); !description.empty()) {
ImGui::SameLine();
ImGuiExt::HelpHover(Lang(description));
}
// Draw settings gear on the right
if (section->hasSettings()) {
ImGui::SameLine(0, ImGui::GetContentRegionAvail().x - ImGui::CalcTextSize(ICON_VS_SETTINGS_GEAR).x);
if (ImGuiExt::DimmedIconButton(ICON_VS_SETTINGS_GEAR, ImGui::GetStyleColorVec4(ImGuiCol_Text))) {
ImGui::OpenPopup("SectionSettings");
}
if (ImGui::BeginPopup("SectionSettings")) {
ImGuiExt::Header("hex.ui.common.settings"_lang, true);
section->drawSettings();
ImGui::EndPopup();
}
}
}
ImGui::EndDisabled();
ImGui::EndMenuBar();
}
// Draw the section content
ImGui::BeginDisabled(!enabled);
if (section->isEnabled()) {
if (section->isValid())
section->drawContent();
else if (section->isAnalyzing())
ImGuiExt::TextSpinner("hex.builtin.view.information.analyzing"_lang);
else
ImGuiExt::TextFormattedCenteredHorizontal("hex.builtin.view.information.not_analyzed"_lang);
}
ImGui::EndDisabled();
}
ImGui::EndChild();
ImGui::PopStyleVar();
ImGui::PopID();
ImGui::NewLine();
}
}
}
}
ImGui::EndChild();
}
}
| 11,329
|
C++
|
.cpp
| 190
| 36.068421
| 187
| 0.477869
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
234
|
view_data_inspector.cpp
|
WerWolv_ImHex/plugins/builtin/source/content/views/view_data_inspector.cpp
|
#include "content/views/view_data_inspector.hpp"
#include <hex/api/achievement_manager.hpp>
#include <hex/providers/provider.hpp>
#include <hex/helpers/logger.hpp>
#include <hex/helpers/default_paths.hpp>
#include <fonts/codicons_font.h>
#include <hex/ui/imgui_imhex_extensions.h>
#include <pl/pattern_language.hpp>
#include <pl/patterns/pattern.hpp>
#include <wolv/utils/string.hpp>
#include <ranges>
namespace hex::plugin::builtin {
using NumberDisplayStyle = ContentRegistry::DataInspector::NumberDisplayStyle;
ViewDataInspector::ViewDataInspector() : View::Window("hex.builtin.view.data_inspector.name", ICON_VS_INSPECT) {
// Handle region selection
EventRegionSelected::subscribe(this, [this](const auto ®ion) {
// Save current selection
if (!ImHexApi::Provider::isValid() || region == Region::Invalid()) {
m_validBytes = 0;
m_selectedProvider = nullptr;
} else {
m_validBytes = u64((region.getProvider()->getBaseAddress() + region.getProvider()->getActualSize()) - region.address);
m_startAddress = region.address;
m_selectedProvider = region.getProvider();
}
// Invalidate inspector rows
m_shouldInvalidate = true;
});
EventDataChanged::subscribe(this, [this](const auto &provider) {
if (provider == m_selectedProvider)
m_shouldInvalidate = true;
});
EventProviderClosed::subscribe(this, [this](const auto*) {
m_selectedProvider = nullptr;
});
ContentRegistry::Settings::onChange("hex.builtin.setting.data_inspector", "hex.builtin.setting.data_inspector.hidden_rows", [this](const ContentRegistry::Settings::SettingsValue &value) {
auto filterValues = value.get<std::vector<std::string>>({});
m_hiddenValues = std::set(filterValues.begin(), filterValues.end());
});
}
ViewDataInspector::~ViewDataInspector() {
EventRegionSelected::unsubscribe(this);
EventProviderClosed::unsubscribe(this);
}
void ViewDataInspector::updateInspectorRows() {
m_updateTask = TaskManager::createBackgroundTask("hex.builtin.task.updating_inspector"_lang, [this](auto &) {
this->updateInspectorRowsTask();
});
}
void ViewDataInspector::updateInspectorRowsTask() {
m_workData.clear();
if (m_selectedProvider == nullptr)
return;
// Decode bytes using registered inspectors
for (auto &entry : ContentRegistry::DataInspector::impl::getEntries()) {
if (m_validBytes < entry.requiredSize)
continue;
// Try to read as many bytes as requested and possible
std::vector<u8> buffer(m_validBytes > entry.maxSize ? entry.maxSize : m_validBytes);
m_selectedProvider->read(m_startAddress, buffer.data(), buffer.size());
// Handle invert setting
if (m_invert) {
for (auto &byte : buffer)
byte ^= 0xFF;
}
// Insert processed data into the inspector list
m_workData.emplace_back(
entry.unlocalizedName,
entry.generatorFunction(buffer, m_endian, m_numberDisplayStyle),
entry.editingFunction,
false,
entry.unlocalizedName
);
}
// Execute custom inspectors
this->executeInspectors();
m_dataValid = true;
}
void ViewDataInspector::inspectorReadFunction(u64 offset, u8 *buffer, size_t size) {
m_selectedProvider->read(offset, buffer, size);
// Handle invert setting
if (m_invert) {
for (auto &byte : std::span(buffer, size))
byte ^= 0xFF;
}
}
void ViewDataInspector::executeInspectors() {
// Decode bytes using custom inspectors defined using the pattern language
const std::map<std::string, pl::core::Token::Literal> inVariables = {
{ "numberDisplayStyle", u128(m_numberDisplayStyle) }
};
// Setup a new pattern language runtime
ContentRegistry::PatternLanguage::configureRuntime(m_runtime, m_selectedProvider);
// Setup the runtime to read from the selected provider
m_runtime.setDataSource(m_selectedProvider->getBaseAddress(), m_selectedProvider->getActualSize(), [this](u64 offset, u8 *buffer, size_t size) {
this->inspectorReadFunction(offset, buffer, size);
});
// Prevent dangerous function calls
m_runtime.setDangerousFunctionCallHandler([] { return false; });
// Set the default endianness based on the endian setting
m_runtime.setDefaultEndian(m_endian);
// Set start address to the selected address
m_runtime.setStartAddress(m_startAddress);
// Loop over all files in the inspectors folder and execute them
for (const auto &folderPath : paths::Inspectors.read()) {
for (const auto &entry: std::fs::recursive_directory_iterator(folderPath)) {
const auto &filePath = entry.path();
// Skip non-files and files that don't end with .hexpat
if (!entry.exists() || !entry.is_regular_file() || filePath.extension() != ".hexpat")
continue;
// Read the inspector file
wolv::io::File file(filePath, wolv::io::File::Mode::Read);
if (!file.isValid()) continue;
auto inspectorCode = file.readString();
// Execute the inspector file
if (inspectorCode.empty()) continue;
this->executeInspector(inspectorCode, filePath, inVariables);
}
}
}
void ViewDataInspector::executeInspector(const std::string& code, const std::fs::path& path, const std::map<std::string, pl::core::Token::Literal>& inVariables) {
if (!m_runtime.executeString(code, pl::api::Source::DefaultSource, {}, inVariables, true)) {
auto displayFunction = createPatternErrorDisplayFunction();
// Insert the inspector into the list
m_workData.emplace_back(
wolv::util::toUTF8String(path.filename()),
std::move(displayFunction),
std::nullopt,
false,
wolv::util::toUTF8String(path)
);
return;
}
// Loop over patterns produced by the runtime
const auto &patterns = m_runtime.getPatterns();
for (const auto &pattern: patterns) {
// Skip hidden patterns
if (pattern->getVisibility() == pl::ptrn::Visibility::Hidden)
continue;
// Set up the editing function if a write formatter is available
auto formatWriteFunction = pattern->getWriteFormatterFunction();
std::optional<ContentRegistry::DataInspector::impl::EditingFunction> editingFunction;
if (!formatWriteFunction.empty()) {
editingFunction = [formatWriteFunction, &pattern](const std::string &value,
std::endian) -> std::vector<u8> {
try {
pattern->setValue(value);
} catch (const pl::core::err::EvaluatorError::Exception &error) {
log::error("Failed to set value of pattern '{}' to '{}': {}",
pattern->getDisplayName(), value, error.what());
}
return {};
};
}
try {
// Set up the display function using the pattern's formatter
auto displayFunction = [value = pattern->getFormattedValue()] {
ImGui::TextUnformatted(value.c_str());
return value;
};
// Insert the inspector into the list
m_workData.emplace_back(
pattern->getDisplayName(),
displayFunction,
editingFunction,
false,
wolv::util::toUTF8String(path) + ":" + pattern->getVariableName()
);
AchievementManager::unlockAchievement("hex.builtin.achievement.patterns",
"hex.builtin.achievement.patterns.data_inspector.name");
} catch (const pl::core::err::EvaluatorError::Exception &) {
auto displayFunction = createPatternErrorDisplayFunction();
// Insert the inspector into the list
m_workData.emplace_back(
wolv::util::toUTF8String(path.filename()),
std::move(displayFunction),
std::nullopt,
false,
wolv::util::toUTF8String(path)
);
}
}
}
void ViewDataInspector::drawContent() {
if (m_dataValid && !m_updateTask.isRunning()) {
m_dataValid = false;
m_cachedData = std::move(m_workData);
}
if (m_shouldInvalidate && !m_updateTask.isRunning()) {
m_shouldInvalidate = false;
this->updateInspectorRows();
}
if (m_selectedProvider == nullptr || !m_selectedProvider->isReadable() || m_validBytes <= 0) {
// Draw a message when no bytes are selected
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);
ImGui::TextUnformatted(text.c_str());
return;
}
u32 validLineCount = m_cachedData.size();
if (!m_tableEditingModeEnabled) {
validLineCount = std::count_if(m_cachedData.begin(), m_cachedData.end(), [this](const auto &entry) {
return !m_hiddenValues.contains(entry.filterValue);
});
}
if (ImGui::BeginTable("##datainspector", m_tableEditingModeEnabled ? 3 : 2,
ImGuiTableFlags_Borders | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_RowBg,
ImVec2(0, ImGui::GetTextLineHeightWithSpacing() * (validLineCount + 1)))) {
ImGui::TableSetupScrollFreeze(0, 1);
ImGui::TableSetupColumn("hex.builtin.view.data_inspector.table.name"_lang,
ImGuiTableColumnFlags_WidthFixed);
ImGui::TableSetupColumn("hex.builtin.view.data_inspector.table.value"_lang,
ImGuiTableColumnFlags_WidthStretch);
if (m_tableEditingModeEnabled)
ImGui::TableSetupColumn("##favorite", ImGuiTableColumnFlags_WidthFixed, ImGui::GetTextLineHeight());
ImGui::TableHeadersRow();
this->drawInspectorRows();
ImGui::EndTable();
}
ImGuiExt::DimmedButtonToggle("hex.ui.common.edit"_lang, &m_tableEditingModeEnabled,
ImVec2(ImGui::GetContentRegionAvail().x, 0));
ImGui::NewLine();
ImGui::Separator();
ImGui::NewLine();
// Draw inspector settings
// Draw endian setting
this->drawEndianSetting();
// Draw radix setting
this->drawRadixSetting();
// Draw invert setting
this->drawInvertSetting();
}
void ViewDataInspector::drawInspectorRows() {
int inspectorRowId = 1;
for (auto &entry : m_cachedData) {
ON_SCOPE_EXIT {
ImGui::PopID();
inspectorRowId++;
};
ImGui::PushID(inspectorRowId);
bool grayedOut = m_hiddenValues.contains(entry.filterValue);
if (!m_tableEditingModeEnabled && grayedOut)
continue;
ImGui::TableNextRow();
ImGui::TableNextColumn();
ImGui::BeginDisabled(grayedOut);
this->drawInspectorRow(entry);
ImGui::EndDisabled();
if (!m_tableEditingModeEnabled) {
continue;
}
ImGui::TableNextColumn();
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0));
ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImGui::GetStyleColorVec4(ImGuiCol_Text));
bool hidden = m_hiddenValues.contains(entry.filterValue);
if (ImGuiExt::DimmedButton(hidden ? ICON_VS_EYE : ICON_VS_EYE_CLOSED)) {
if (hidden)
m_hiddenValues.erase(entry.filterValue);
else
m_hiddenValues.insert(entry.filterValue);
std::vector filterValues(m_hiddenValues.begin(), m_hiddenValues.end());
ContentRegistry::Settings::write<std::vector<std::string>>(
"hex.builtin.setting.data_inspector",
"hex.builtin.setting.data_inspector.hidden_rows", filterValues);
}
ImGui::PopStyleColor();
ImGui::PopStyleVar();
}
}
void ViewDataInspector::drawInspectorRow(InspectorCacheEntry& entry) {
// Render inspector row name
ImGui::TextUnformatted(Lang(entry.unlocalizedName));
ImGui::TableNextColumn();
if (!entry.editing) {
// Handle regular display case
// Render inspector row value
const auto ©Value = entry.displayFunction();
ImGui::SameLine();
// Handle copying the value to the clipboard when clicking the row
if (ImGui::Selectable("##InspectorLine", false, ImGuiSelectableFlags_SpanAllColumns |
ImGuiSelectableFlags_AllowOverlap)) {
ImGui::SetClipboardText(copyValue.c_str());
}
// Enter editing mode when double-clicking the row
if (ImGui::IsItemHovered() && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left) &&
entry.editingFunction.has_value() && m_selectedProvider->isWritable()) {
entry.editing = true;
m_editingValue = copyValue;
}
return;
}
// Handle editing mode
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0));
ImGui::SetNextItemWidth(-1);
ImGui::SetKeyboardFocusHere();
// Draw input text box
if (ImGui::InputText("##InspectorLineEditing", m_editingValue,
ImGuiInputTextFlags_EnterReturnsTrue |
ImGuiInputTextFlags_AutoSelectAll)) {
// Turn the entered value into bytes
auto bytes = entry.editingFunction.value()(m_editingValue, m_endian);
if (m_invert)
std::ranges::transform(bytes, bytes.begin(), [](auto byte) { return byte ^ 0xFF; });
// Write those bytes to the selected provider at the current address
m_selectedProvider->write(m_startAddress, bytes.data(), bytes.size());
// Disable editing mode
m_editingValue.clear();
entry.editing = false;
// Reload all inspector rows
m_shouldInvalidate = true;
}
ImGui::PopStyleVar();
// Disable editing mode when clicking outside the input text box
if (!ImGui::IsItemHovered() && ImGui::IsMouseClicked(ImGuiMouseButton_Left)) {
m_editingValue.clear();
entry.editing = false;
}
}
void ViewDataInspector::drawEndianSetting() {
int selection = [this] {
switch (m_endian) {
default:
case std::endian::little:
return 0;
case std::endian::big:
return 1;
}
}();
std::array options = {"hex.ui.common.little"_lang, "hex.ui.common.big"_lang};
if (ImGui::SliderInt("hex.ui.common.endian"_lang, &selection, 0, options.size() - 1, options[selection],
ImGuiSliderFlags_NoInput)) {
m_shouldInvalidate = true;
switch (selection) {
default:
case 0:
m_endian = std::endian::little;
break;
case 1:
m_endian = std::endian::big;
break;
}
}
}
void ViewDataInspector::drawRadixSetting() {
int selection = [this] {
switch (m_numberDisplayStyle) {
default:
case NumberDisplayStyle::Decimal:
return 0;
case NumberDisplayStyle::Hexadecimal:
return 1;
case NumberDisplayStyle::Octal:
return 2;
}
}();
std::array options = {"hex.ui.common.decimal"_lang, "hex.ui.common.hexadecimal"_lang,
"hex.ui.common.octal"_lang};
if (ImGui::SliderInt("hex.ui.common.number_format"_lang, &selection, 0, options.size() - 1,
options[selection], ImGuiSliderFlags_NoInput)) {
m_shouldInvalidate = true;
switch (selection) {
default:
case 0:
m_numberDisplayStyle = NumberDisplayStyle::Decimal;
break;
case 1:
m_numberDisplayStyle = NumberDisplayStyle::Hexadecimal;
break;
case 2:
m_numberDisplayStyle = NumberDisplayStyle::Octal;
break;
}
}
}
void ViewDataInspector::drawInvertSetting() {
int selection = m_invert ? 1 : 0;
std::array options = {"hex.ui.common.no"_lang, "hex.ui.common.yes"_lang};
if (ImGui::SliderInt("hex.builtin.view.data_inspector.invert"_lang, &selection, 0, options.size() - 1,
options[selection], ImGuiSliderFlags_NoInput)) {
m_shouldInvalidate = true;
m_invert = selection == 1;
}
}
ContentRegistry::DataInspector::impl::DisplayFunction ViewDataInspector::createPatternErrorDisplayFunction() {
// Generate error message
std::string errorMessage;
if (const auto &compileErrors = m_runtime.getCompileErrors(); !compileErrors.empty()) {
for (const auto &error : compileErrors) {
errorMessage += hex::format("{}\n", error.format());
}
} else if (const auto &evalError = m_runtime.getEvalError(); evalError.has_value()) {
errorMessage += hex::format("{}:{} {}\n", evalError->line, evalError->column, evalError->message);
}
// Create a dummy display function that displays the error message
auto displayFunction = [errorMessage = std::move(errorMessage)] {
ImGuiExt::HelpHover(
errorMessage.c_str(),
"hex.builtin.view.data_inspector.execution_error"_lang,
ImGuiExt::GetCustomColorU32(ImGuiCustomCol_LoggerError)
);
return errorMessage;
};
return displayFunction;
}
}
| 19,592
|
C++
|
.cpp
| 407
| 34.434889
| 195
| 0.571968
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
235
|
view_logs.cpp
|
WerWolv_ImHex/plugins/builtin/source/content/views/view_logs.cpp
|
#include "content/views/view_logs.hpp"
#include <hex/api/content_registry.hpp>
#include <hex/helpers/logger.hpp>
#include <fonts/codicons_font.h>
namespace hex::plugin::builtin {
ViewLogs::ViewLogs() : View::Floating("hex.builtin.view.logs.name") {
ContentRegistry::Interface::addMenuItem({ "hex.builtin.menu.extras", "hex.builtin.view.logs.name" }, ICON_VS_BRACKET_ERROR, 2500, Shortcut::None, [&, this] {
this->getWindowOpenState() = true;
});
}
static ImColor getColor(std::string_view level) {
if (level.contains("DEBUG"))
return ImGuiExt::GetCustomColorVec4(ImGuiCustomCol_LoggerDebug);
else if (level.contains("INFO"))
return ImGuiExt::GetCustomColorVec4(ImGuiCustomCol_LoggerInfo);
else if (level.contains("WARN"))
return ImGuiExt::GetCustomColorVec4(ImGuiCustomCol_LoggerWarning);
else if (level.contains("ERROR"))
return ImGuiExt::GetCustomColorVec4(ImGuiCustomCol_LoggerError);
else if (level.contains("FATAL"))
return ImGuiExt::GetCustomColorVec4(ImGuiCustomCol_LoggerFatal);
return ImGui::GetStyleColorVec4(ImGuiCol_Text);
}
static bool shouldDisplay(std::string_view messageLevel, int currLevel) {
if (messageLevel.contains("[DEBUG]"))
return currLevel <= 0;
else if (messageLevel.contains("[INFO]"))
return currLevel <= 1;
else if (messageLevel.contains("[WARN]"))
return currLevel <= 2;
else if (messageLevel.contains("[ERROR]"))
return currLevel <= 3;
else if (messageLevel.contains("[FATAL]"))
return currLevel <= 4;
else
return false;
}
void ViewLogs::drawContent() {
ImGui::Combo("hex.builtin.view.logs.log_level"_lang, &m_logLevel, "DEBUG\0INFO\0WARNING\0ERROR\0FATAL\0");
if (ImGui::BeginTable("##logs", 2, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_ScrollY)) {
ImGui::TableSetupColumn("hex.builtin.view.logs.component"_lang, ImGuiTableColumnFlags_WidthFixed, 100_scaled);
ImGui::TableSetupColumn("hex.builtin.view.logs.message"_lang);
ImGui::TableSetupScrollFreeze(0, 1);
ImGui::TableHeadersRow();
const auto &logs = log::impl::getLogEntries();
for (const auto &log : logs | std::views::reverse) {
if (!shouldDisplay(log.level, m_logLevel)) {
continue;
}
ImGui::TableNextRow();
ImGui::TableNextColumn();
ImGui::TextUnformatted(log.project.c_str());
ImGui::TableNextColumn();
ImGui::PushStyleColor(ImGuiCol_Text, getColor(log.level).Value);
ImGui::TextUnformatted(log.message.c_str());
ImGui::PopStyleColor();
}
ImGui::EndTable();
}
}
}
| 2,998
|
C++
|
.cpp
| 61
| 38.57377
| 165
| 0.62735
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
236
|
view_find.cpp
|
WerWolv_ImHex/plugins/builtin/source/content/views/view_find.cpp
|
#include "content/views/view_find.hpp"
#include <hex/api/imhex_api.hpp>
#include <hex/api/achievement_manager.hpp>
#include <hex/providers/buffered_reader.hpp>
#include <fonts/codicons_font.h>
#include <array>
#include <ranges>
#include <string>
#include <utility>
#include <content/helpers/demangle.hpp>
#include <boost/regex.hpp>
namespace hex::plugin::builtin {
ViewFind::ViewFind() : View::Window("hex.builtin.view.find.name", ICON_VS_SEARCH) {
const static auto HighlightColor = [] { return (ImGuiExt::GetCustomColorU32(ImGuiCustomCol_FindHighlight) & 0x00FFFFFF) | 0x70000000; };
ImHexApi::HexEditor::addBackgroundHighlightingProvider([this](u64 address, const u8* data, size_t size, bool) -> std::optional<color_t> {
hex::unused(data, size);
if (m_searchTask.isRunning())
return { };
if (!m_occurrenceTree->overlapping({ address, address }).empty())
return HighlightColor();
else
return std::nullopt;
});
ImHexApi::HexEditor::addTooltipProvider([this](u64 address, const u8* data, size_t size) {
hex::unused(data, size);
if (m_searchTask.isRunning())
return;
auto occurrences = m_occurrenceTree->overlapping({ address, address + size });
if (occurrences.empty())
return;
ImGui::BeginTooltip();
for (const auto &occurrence : occurrences) {
ImGui::PushID(&occurrence);
if (ImGui::BeginTable("##tooltips", 1, ImGuiTableFlags_RowBg | ImGuiTableFlags_NoClip)) {
ImGui::TableNextRow();
ImGui::TableNextColumn();
{
auto region = occurrence.value.region;
const auto value = this->decodeValue(ImHexApi::Provider::get(), occurrence.value, 256);
ImGui::ColorButton("##color", ImColor(HighlightColor()));
ImGui::SameLine(0, 10);
ImGuiExt::TextFormatted("{} ", value);
if (ImGui::GetIO().KeyShift) {
ImGui::Indent();
if (ImGui::BeginTable("##extra_info", 2, ImGuiTableFlags_RowBg | ImGuiTableFlags_NoClip)) {
ImGui::TableNextRow();
ImGui::TableNextColumn();
ImGuiExt::TextFormatted("{}: ", "hex.ui.common.region"_lang);
ImGui::TableNextColumn();
ImGuiExt::TextFormatted("[ 0x{:08X} - 0x{:08X} ]", region.getStartAddress(), region.getEndAddress());
auto demangledValue = hex::plugin::builtin::demangle(value);
if (value != demangledValue) {
ImGui::TableNextRow();
ImGui::TableNextColumn();
ImGuiExt::TextFormatted("{}: ", "hex.builtin.view.find.demangled"_lang);
ImGui::TableNextColumn();
ImGuiExt::TextFormatted("{}", demangledValue);
}
ImGui::EndTable();
}
ImGui::Unindent();
}
}
ImGui::PushStyleColor(ImGuiCol_TableRowBg, HighlightColor());
ImGui::PushStyleColor(ImGuiCol_TableRowBgAlt, HighlightColor());
ImGui::EndTable();
ImGui::PopStyleColor(2);
}
ImGui::PopID();
}
ImGui::EndTooltip();
});
ShortcutManager::addShortcut(this, CTRLCMD + Keys::A, "hex.builtin.view.find.shortcut.select_all", [this] {
if (m_filterTask.isRunning())
return;
if (m_searchTask.isRunning())
return;
for (auto &occurrence : *m_sortedOccurrences)
occurrence.selected = true;
});
}
template<typename Type, typename StorageType>
static std::tuple<bool, std::variant<u64, i64, float, double>, size_t> parseNumericValue(const std::string &string) {
static_assert(sizeof(StorageType) >= sizeof(Type));
StorageType value;
std::size_t processed = 0;
try {
if constexpr (std::floating_point<Type>)
value = std::stod(string, &processed);
else if constexpr (std::signed_integral<Type>)
value = std::stoll(string, &processed, 0);
else
value = std::stoull(string, &processed, 0);
} catch (std::exception &) {
return { false, { }, 0 };
}
if (processed != string.size())
return { false, { }, 0 };
if (value < std::numeric_limits<Type>::lowest() || value > std::numeric_limits<Type>::max())
return { false, { }, 0 };
return { true, value, sizeof(Type) };
}
std::tuple<bool, std::variant<u64, i64, float, double>, size_t> ViewFind::parseNumericValueInput(const std::string &input, SearchSettings::Value::Type type) {
switch (type) {
using enum SearchSettings::Value::Type;
case U8: return parseNumericValue<u8, u64>(input);
case U16: return parseNumericValue<u16, u64>(input);
case U32: return parseNumericValue<u32, u64>(input);
case U64: return parseNumericValue<u64, u64>(input);
case I8: return parseNumericValue<i8, i64>(input);
case I16: return parseNumericValue<i16, i64>(input);
case I32: return parseNumericValue<i32, i64>(input);
case I64: return parseNumericValue<i64, i64>(input);
case F32: return parseNumericValue<float, float>(input);
case F64: return parseNumericValue<double, double>(input);
default: return { false, { }, 0 };
}
}
template<typename T>
static std::string formatBytes(const std::vector<u8> &bytes, std::endian endian) {
if (bytes.size() > sizeof(T))
return { };
T value = 0x00;
std::memcpy(&value, bytes.data(), bytes.size());
value = hex::changeEndianness(value, bytes.size(), endian);
if (std::signed_integral<T>)
value = hex::signExtend(bytes.size() * 8, value);
return hex::format("{}", value);
}
std::vector<hex::ContentRegistry::DataFormatter::impl::FindOccurrence> ViewFind::searchStrings(Task &task, prv::Provider *provider, hex::Region searchRegion, const SearchSettings::Strings &settings) {
using enum SearchSettings::StringType;
std::vector<Occurrence> results;
if (settings.type == ASCII_UTF16BE || settings.type == ASCII_UTF16LE) {
auto newSettings = settings;
newSettings.type = ASCII;
auto asciiResults = searchStrings(task, provider, searchRegion, newSettings);
std::copy(asciiResults.begin(), asciiResults.end(), std::back_inserter(results));
if (settings.type == ASCII_UTF16BE) {
newSettings.type = UTF16BE;
auto utf16Results = searchStrings(task, provider, searchRegion, newSettings);
std::copy(utf16Results.begin(), utf16Results.end(), std::back_inserter(results));
} else if (settings.type == ASCII_UTF16LE) {
newSettings.type = UTF16LE;
auto utf16Results = searchStrings(task, provider, searchRegion, newSettings);
std::copy(utf16Results.begin(), utf16Results.end(), std::back_inserter(results));
}
return results;
}
auto reader = prv::ProviderReader(provider);
reader.seek(searchRegion.getStartAddress());
reader.setEndAddress(searchRegion.getEndAddress());
const auto [decodeType, endian] = [&] -> std::pair<Occurrence::DecodeType, std::endian> {
if (settings.type == ASCII)
return { Occurrence::DecodeType::ASCII, std::endian::native };
else if (settings.type == SearchSettings::StringType::UTF16BE)
return { Occurrence::DecodeType::UTF16, std::endian::big };
else if (settings.type == SearchSettings::StringType::UTF16LE)
return { Occurrence::DecodeType::UTF16, std::endian::little };
else
return { Occurrence::DecodeType::Binary, std::endian::native };
}();
size_t countedCharacters = 0;
u64 startAddress = reader.begin().getAddress();
u64 endAddress = reader.end().getAddress();
u64 progress = 0;
for (u8 byte : reader) {
bool validChar =
(settings.lowerCaseLetters && std::islower(byte)) ||
(settings.upperCaseLetters && std::isupper(byte)) ||
(settings.numbers && std::isdigit(byte)) ||
(settings.spaces && std::isspace(byte) && byte != '\r' && byte != '\n') ||
(settings.underscores && byte == '_') ||
(settings.symbols && std::ispunct(byte) && !std::isspace(byte)) ||
(settings.lineFeeds && (byte == '\r' || byte == '\n'));
if (settings.type == UTF16LE) {
// Check if second byte of UTF-16 encoded string is 0x00
if (countedCharacters % 2 == 1)
validChar = byte == 0x00;
} else if (settings.type == UTF16BE) {
// Check if first byte of UTF-16 encoded string is 0x00
if (countedCharacters % 2 == 0)
validChar = byte == 0x00;
}
task.update(progress);
if (validChar)
countedCharacters++;
if (!validChar || startAddress + countedCharacters == endAddress) {
if (countedCharacters >= size_t(settings.minLength)) {
if (!settings.nullTermination || byte == 0x00) {
results.push_back(Occurrence { Region { startAddress, countedCharacters }, decodeType, endian, false });
}
}
startAddress += countedCharacters + 1;
countedCharacters = 0;
progress = startAddress - searchRegion.getStartAddress();
}
}
return results;
}
std::vector<hex::ContentRegistry::DataFormatter::impl::FindOccurrence> ViewFind::searchSequence(Task &task, prv::Provider *provider, hex::Region searchRegion, const SearchSettings::Sequence &settings) {
std::vector<Occurrence> results;
auto reader = prv::ProviderReader(provider);
reader.seek(searchRegion.getStartAddress());
reader.setEndAddress(searchRegion.getEndAddress());
auto input = hex::decodeByteString(settings.sequence);
if (input.empty())
return { };
std::vector<u8> bytes;
auto decodeType = Occurrence::DecodeType::Binary;
std::endian endian;
switch (settings.type) {
default:
case SearchSettings::StringType::ASCII:
bytes = input;
decodeType = Occurrence::DecodeType::ASCII;
endian = std::endian::native;
break;
case SearchSettings::StringType::UTF16LE: {
auto wString = hex::utf8ToUtf16({ input.begin(), input.end() });
bytes.resize(wString.size() * 2);
std::memcpy(bytes.data(), wString.data(), bytes.size());
decodeType = Occurrence::DecodeType::UTF16;
endian = std::endian::little;
break;
}
case SearchSettings::StringType::UTF16BE: {
auto wString = hex::utf8ToUtf16({ input.begin(), input.end() });
bytes.resize(wString.size() * 2);
std::memcpy(bytes.data(), wString.data(), bytes.size());
decodeType = Occurrence::DecodeType::UTF16;
endian = std::endian::big;
for (size_t i = 0; i < bytes.size(); i += 2)
std::swap(bytes[i], bytes[i + 1]);
break;
}
}
auto occurrence = reader.begin();
u64 progress = 0;
auto searchPredicate = [&] -> bool(*)(u8, u8) {
if (!settings.ignoreCase)
return [](u8 left, u8 right) -> bool {
return left == right;
};
else
return [](u8 left, u8 right) -> bool {
if (std::isupper(left))
left = std::tolower(left);
if (std::isupper(right))
right = std::tolower(right);
return left == right;
};
}();
while (true) {
task.update(progress);
occurrence = std::search(reader.begin(), reader.end(), std::default_searcher(bytes.begin(), bytes.end(), searchPredicate));
if (occurrence == reader.end())
break;
auto address = occurrence.getAddress();
reader.seek(address + 1);
results.push_back(Occurrence{ Region { address, bytes.size() }, decodeType, endian, false });
progress = address - searchRegion.getStartAddress();
}
return results;
}
std::vector<hex::ContentRegistry::DataFormatter::impl::FindOccurrence> ViewFind::searchRegex(Task &task, prv::Provider *provider, hex::Region searchRegion, const SearchSettings::Regex &settings) {
auto stringOccurrences = searchStrings(task, provider, searchRegion, SearchSettings::Strings {
.minLength = settings.minLength,
.nullTermination = settings.nullTermination,
.type = settings.type,
.lowerCaseLetters = true,
.upperCaseLetters = true,
.numbers = true,
.underscores = true,
.symbols = true,
.spaces = true,
.lineFeeds = true
});
std::vector<Occurrence> result;
boost::regex regex(settings.pattern);
for (const auto &occurrence : stringOccurrences) {
std::string string(occurrence.region.getSize(), '\x00');
provider->read(occurrence.region.getStartAddress(), string.data(), occurrence.region.getSize());
task.update();
if (settings.fullMatch) {
if (boost::regex_match(string, regex))
result.push_back(occurrence);
} else {
if (boost::regex_search(string, regex))
result.push_back(occurrence);
}
}
return result;
}
std::vector<hex::ContentRegistry::DataFormatter::impl::FindOccurrence> ViewFind::searchBinaryPattern(Task &task, prv::Provider *provider, hex::Region searchRegion, const SearchSettings::BinaryPattern &settings) {
std::vector<Occurrence> results;
auto reader = prv::ProviderReader(provider);
reader.seek(searchRegion.getStartAddress());
reader.setEndAddress(searchRegion.getEndAddress());
const size_t patternSize = settings.pattern.getSize();
if (settings.alignment == 1) {
u32 matchedBytes = 0;
for (auto it = reader.begin(); it < reader.end(); it += 1) {
auto byte = *it;
task.update(it.getAddress());
if (settings.pattern.matchesByte(byte, matchedBytes)) {
matchedBytes++;
if (matchedBytes == settings.pattern.getSize()) {
auto occurrenceAddress = it.getAddress() - (patternSize - 1);
results.push_back(Occurrence { Region { occurrenceAddress, patternSize }, Occurrence::DecodeType::Binary, std::endian::native, false });
it.setAddress(occurrenceAddress);
matchedBytes = 0;
}
} else {
if (matchedBytes > 0)
it -= matchedBytes;
matchedBytes = 0;
}
}
} else {
std::vector<u8> data(patternSize);
for (u64 address = searchRegion.getStartAddress(); address < searchRegion.getEndAddress(); address += settings.alignment) {
reader.read(address, data.data(), data.size());
task.update(address);
bool match = true;
for (u32 i = 0; i < patternSize; i++) {
if (!settings.pattern.matchesByte(data[i], i)) {
match = false;
break;
}
}
if (match)
results.push_back(Occurrence { Region { address, patternSize }, Occurrence::DecodeType::Binary, std::endian::native, false });
}
}
return results;
}
std::vector<hex::ContentRegistry::DataFormatter::impl::FindOccurrence> ViewFind::searchValue(Task &task, prv::Provider *provider, Region searchRegion, const SearchSettings::Value &settings) {
std::vector<Occurrence> results;
auto reader = prv::ProviderReader(provider);
reader.seek(searchRegion.getStartAddress());
reader.setEndAddress(searchRegion.getEndAddress());
auto inputMin = settings.inputMin;
auto inputMax = settings.inputMax;
if (inputMax.empty())
inputMax = inputMin;
const auto [validMin, min, sizeMin] = parseNumericValueInput(inputMin, settings.type);
const auto [validMax, max, sizeMax] = parseNumericValueInput(inputMax, settings.type);
if (!validMin || !validMax || sizeMin != sizeMax)
return { };
const auto size = sizeMin;
const auto advance = settings.aligned ? size : 1;
for (u64 address = searchRegion.getStartAddress(); address < searchRegion.getEndAddress(); address += advance) {
task.update(address);
auto result = std::visit([&]<typename T>(T) {
using DecayedType = std::remove_cvref_t<std::decay_t<T>>;
auto minValue = std::get<DecayedType>(min);
auto maxValue = std::get<DecayedType>(max);
DecayedType value = 0;
reader.read(address, reinterpret_cast<u8*>(&value), size);
value = hex::changeEndianness(value, size, settings.endian);
return value >= minValue && value <= maxValue;
}, min);
if (result) {
Occurrence::DecodeType decodeType = [&]{
switch (settings.type) {
using enum SearchSettings::Value::Type;
using enum Occurrence::DecodeType;
case U8:
case U16:
case U32:
case U64:
return Unsigned;
case I8:
case I16:
case I32:
case I64:
return Signed;
case F32:
return Float;
case F64:
return Double;
default:
return Binary;
}
}();
results.push_back(Occurrence { Region { address, size }, decodeType, settings.endian, false });
}
}
return results;
}
void ViewFind::runSearch() {
Region searchRegion = m_searchSettings.region;
if (m_searchSettings.mode == SearchSettings::Mode::Strings) {
AchievementManager::unlockAchievement("hex.builtin.achievement.find", "hex.builtin.achievement.find.find_strings.name");
} else if (m_searchSettings.mode == SearchSettings::Mode::Sequence) {
AchievementManager::unlockAchievement("hex.builtin.achievement.find", "hex.builtin.achievement.find.find_specific_string.name");
} else if (m_searchSettings.mode == SearchSettings::Mode::Value) {
if (m_searchSettings.value.inputMin == "250" && m_searchSettings.value.inputMax == "1000")
AchievementManager::unlockAchievement("hex.builtin.achievement.find", "hex.builtin.achievement.find.find_numeric.name");
}
m_occurrenceTree->clear();
EventHighlightingChanged::post();
m_searchTask = TaskManager::createTask("hex.builtin.view.find.searching"_lang, searchRegion.getSize(), [this, settings = m_searchSettings, searchRegion](auto &task) {
auto provider = ImHexApi::Provider::get();
switch (settings.mode) {
using enum SearchSettings::Mode;
case Strings:
m_foundOccurrences.get(provider) = searchStrings(task, provider, searchRegion, settings.strings);
break;
case Sequence:
m_foundOccurrences.get(provider) = searchSequence(task, provider, searchRegion, settings.bytes);
break;
case Regex:
m_foundOccurrences.get(provider) = searchRegex(task, provider, searchRegion, settings.regex);
break;
case BinaryPattern:
m_foundOccurrences.get(provider) = searchBinaryPattern(task, provider, searchRegion, settings.binaryPattern);
break;
case Value:
m_foundOccurrences.get(provider) = searchValue(task, provider, searchRegion, settings.value);
break;
}
m_sortedOccurrences.get(provider) = m_foundOccurrences.get(provider);
m_lastSelectedOccurrence = nullptr;
for (const auto &occurrence : m_foundOccurrences.get(provider))
m_occurrenceTree->insert({ occurrence.region.getStartAddress(), occurrence.region.getEndAddress() }, occurrence);
TaskManager::doLater([] {
EventHighlightingChanged::post();
});
});
}
std::string ViewFind::decodeValue(prv::Provider *provider, const Occurrence &occurrence, size_t maxBytes) const {
std::vector<u8> bytes(std::min<size_t>(occurrence.region.getSize(), maxBytes));
provider->read(occurrence.region.getStartAddress(), bytes.data(), bytes.size());
std::string result;
switch (m_decodeSettings.mode) {
using enum SearchSettings::Mode;
case Value:
case Strings:
case Sequence:
case Regex:
{
switch (occurrence.decodeType) {
using enum Occurrence::DecodeType;
case Binary:
case ASCII:
result = hex::encodeByteString(bytes);
break;
case UTF16:
for (size_t i = occurrence.endian == std::endian::little ? 0 : 1; i < bytes.size(); i += 2)
result += hex::encodeByteString({ bytes[i] });
break;
case Unsigned:
result += formatBytes<u64>(bytes, occurrence.endian);
break;
case Signed:
result += formatBytes<i64>(bytes, occurrence.endian);
break;
case Float:
result += formatBytes<float>(bytes, occurrence.endian);
break;
case Double:
result += formatBytes<double>(bytes, occurrence.endian);
break;
}
}
break;
case BinaryPattern:
result = hex::encodeByteString(bytes);
break;
}
if (occurrence.region.getSize() > maxBytes)
result += "...";
return result;
}
void ViewFind::drawContextMenu(Occurrence &target, const std::string &value) {
if (ImGui::IsMouseClicked(ImGuiMouseButton_Right) && ImGui::IsItemHovered()) {
ImGui::OpenPopup("FindContextMenu");
target.selected = true;
m_replaceBuffer.clear();
}
if (ImGui::BeginPopup("FindContextMenu")) {
if (ImGui::MenuItem("hex.builtin.view.find.context.copy"_lang))
ImGui::SetClipboardText(value.c_str());
if (ImGui::MenuItem("hex.builtin.view.find.context.copy_demangle"_lang))
ImGui::SetClipboardText(hex::plugin::builtin::demangle(value).c_str());
if (ImGui::BeginMenu("hex.builtin.view.find.context.replace"_lang)) {
if (ImGui::BeginTabBar("##replace_tabs")) {
if (ImGui::BeginTabItem("hex.builtin.view.find.context.replace.hex"_lang)) {
ImGuiExt::InputTextIcon("##replace_input", ICON_VS_SYMBOL_NAMESPACE, m_replaceBuffer);
ImGui::BeginDisabled(m_replaceBuffer.empty());
if (ImGui::Button("hex.builtin.view.find.context.replace"_lang)) {
auto provider = ImHexApi::Provider::get();
auto bytes = parseHexString(m_replaceBuffer);
for (const auto &occurrence : *m_sortedOccurrences) {
if (occurrence.selected) {
size_t size = std::min<size_t>(occurrence.region.size, bytes.size());
provider->write(occurrence.region.getStartAddress(), bytes.data(), size);
}
}
}
ImGui::EndDisabled();
ImGui::EndTabItem();
}
if (ImGui::BeginTabItem("hex.builtin.view.find.context.replace.ascii"_lang)) {
ImGuiExt::InputTextIcon("##replace_input", ICON_VS_SYMBOL_KEY, m_replaceBuffer);
ImGui::BeginDisabled(m_replaceBuffer.empty());
if (ImGui::Button("hex.builtin.view.find.context.replace"_lang)) {
auto provider = ImHexApi::Provider::get();
auto bytes = decodeByteString(m_replaceBuffer);
for (const auto &occurrence : *m_sortedOccurrences) {
if (occurrence.selected) {
size_t size = std::min<size_t>(occurrence.region.size, bytes.size());
provider->write(occurrence.region.getStartAddress(), bytes.data(), size);
}
}
}
ImGui::EndDisabled();
ImGui::EndTabItem();
}
ImGui::EndTabBar();
}
ImGui::EndMenu();
}
ImGui::EndPopup();
}
}
void ViewFind::drawContent() {
auto provider = ImHexApi::Provider::get();
ImGui::BeginDisabled(m_searchTask.isRunning());
{
ui::regionSelectionPicker(&m_searchSettings.region, provider, &m_searchSettings.range, true, true);
ImGui::NewLine();
if (ImGui::BeginTabBar("SearchMethods")) {
const std::array<std::string, 5> StringTypes = {
"hex.ui.common.encoding.ascii"_lang,
"hex.ui.common.encoding.utf16le"_lang,
"hex.ui.common.encoding.utf16be"_lang,
hex::format("{} + {}", "hex.ui.common.encoding.ascii"_lang, "hex.ui.common.encoding.utf16le"_lang),
hex::format("{} + {}", "hex.ui.common.encoding.ascii"_lang, "hex.ui.common.encoding.utf16be"_lang)
};
auto &mode = m_searchSettings.mode;
if (ImGui::BeginTabItem("hex.builtin.view.find.strings"_lang)) {
auto &settings = m_searchSettings.strings;
mode = SearchSettings::Mode::Strings;
ImGui::InputInt("hex.builtin.view.find.strings.min_length"_lang, &settings.minLength, 1, 1);
if (settings.minLength < 1)
settings.minLength = 1;
if (ImGui::BeginCombo("hex.ui.common.type"_lang, StringTypes[std::to_underlying(settings.type)].c_str())) {
for (size_t i = 0; i < StringTypes.size(); i++) {
auto type = static_cast<SearchSettings::StringType>(i);
if (ImGui::Selectable(StringTypes[i].c_str(), type == settings.type))
settings.type = type;
}
ImGui::EndCombo();
}
if (ImGui::CollapsingHeader("hex.builtin.view.find.strings.match_settings"_lang)) {
ImGui::Checkbox("hex.builtin.view.find.strings.null_term"_lang, &settings.nullTermination);
ImGuiExt::Header("hex.builtin.view.find.strings.chars"_lang);
ImGui::Checkbox(hex::format("{} [a-z]", "hex.builtin.view.find.strings.lower_case"_lang.get()).c_str(), &settings.lowerCaseLetters);
ImGui::Checkbox(hex::format("{} [A-Z]", "hex.builtin.view.find.strings.upper_case"_lang.get()).c_str(), &settings.upperCaseLetters);
ImGui::Checkbox(hex::format("{} [0-9]", "hex.builtin.view.find.strings.numbers"_lang.get()).c_str(), &settings.numbers);
ImGui::Checkbox(hex::format("{} [_]", "hex.builtin.view.find.strings.underscores"_lang.get()).c_str(), &settings.underscores);
ImGui::Checkbox(hex::format("{} [!\"#$%...]", "hex.builtin.view.find.strings.symbols"_lang.get()).c_str(), &settings.symbols);
ImGui::Checkbox(hex::format("{} [ \\f\\t\\v]", "hex.builtin.view.find.strings.spaces"_lang.get()).c_str(), &settings.spaces);
ImGui::Checkbox(hex::format("{} [\\r\\n]", "hex.builtin.view.find.strings.line_feeds"_lang.get()).c_str(), &settings.lineFeeds);
}
m_settingsValid = true;
ImGui::EndTabItem();
}
if (ImGui::BeginTabItem("hex.builtin.view.find.sequences"_lang)) {
auto &settings = m_searchSettings.bytes;
mode = SearchSettings::Mode::Sequence;
ImGuiExt::InputTextIcon("hex.ui.common.value"_lang, ICON_VS_SYMBOL_KEY, settings.sequence);
if (ImGui::BeginCombo("hex.ui.common.type"_lang, StringTypes[std::to_underlying(settings.type)].c_str())) {
for (size_t i = 0; i < StringTypes.size() - 2; i++) {
auto type = static_cast<SearchSettings::StringType>(i);
if (ImGui::Selectable(StringTypes[i].c_str(), type == settings.type))
settings.type = type;
}
ImGui::EndCombo();
}
ImGui::Checkbox("hex.builtin.view.find.sequences.ignore_case"_lang, &settings.ignoreCase);
m_settingsValid = !settings.sequence.empty() && !hex::decodeByteString(settings.sequence).empty();
ImGui::EndTabItem();
}
if (ImGui::BeginTabItem("hex.builtin.view.find.regex"_lang)) {
auto &settings = m_searchSettings.regex;
mode = SearchSettings::Mode::Regex;
ImGui::InputInt("hex.builtin.view.find.strings.min_length"_lang, &settings.minLength, 1, 1);
if (settings.minLength < 1)
settings.minLength = 1;
if (ImGui::BeginCombo("hex.ui.common.type"_lang, StringTypes[std::to_underlying(settings.type)].c_str())) {
for (size_t i = 0; i < StringTypes.size(); i++) {
auto type = static_cast<SearchSettings::StringType>(i);
if (ImGui::Selectable(StringTypes[i].c_str(), type == settings.type))
settings.type = type;
}
ImGui::EndCombo();
}
ImGui::Checkbox("hex.builtin.view.find.strings.null_term"_lang, &settings.nullTermination);
ImGui::NewLine();
ImGuiExt::InputTextIcon("hex.builtin.view.find.regex.pattern"_lang, ICON_VS_REGEX, settings.pattern);
try {
boost::regex regex(settings.pattern);
m_settingsValid = true;
} catch (const boost::regex_error &) {
m_settingsValid = false;
}
if (settings.pattern.empty())
m_settingsValid = false;
ImGui::Checkbox("hex.builtin.view.find.regex.full_match"_lang, &settings.fullMatch);
ImGui::EndTabItem();
}
if (ImGui::BeginTabItem("hex.builtin.view.find.binary_pattern"_lang)) {
auto &settings = m_searchSettings.binaryPattern;
mode = SearchSettings::Mode::BinaryPattern;
ImGuiExt::InputTextIcon("hex.builtin.view.find.binary_pattern"_lang, ICON_VS_SYMBOL_NAMESPACE, settings.input);
constexpr static u32 min = 1, max = 0x1000;
ImGui::SliderScalar("hex.builtin.view.find.binary_pattern.alignment"_lang, ImGuiDataType_U32, &settings.alignment, &min, &max);
settings.pattern = hex::BinaryPattern(settings.input);
m_settingsValid = settings.pattern.isValid() && settings.alignment > 0;
ImGui::EndTabItem();
}
if (ImGui::BeginTabItem("hex.builtin.view.find.value"_lang)) {
auto &settings = m_searchSettings.value;
mode = SearchSettings::Mode::Value;
bool edited = false;
if (settings.range) {
if (ImGuiExt::InputTextIcon("hex.builtin.view.find.value.min"_lang, ICON_VS_SYMBOL_NUMERIC, settings.inputMin)) edited = true;
if (ImGuiExt::InputTextIcon("hex.builtin.view.find.value.max"_lang, ICON_VS_SYMBOL_NUMERIC, settings.inputMax)) edited = true;
} else {
if (ImGuiExt::InputTextIcon("hex.ui.common.value"_lang, ICON_VS_SYMBOL_NUMERIC, settings.inputMin)) {
edited = true;
settings.inputMax = settings.inputMin;
}
ImGui::BeginDisabled();
ImGuiExt::InputTextIcon("##placeholder_value", ICON_VS_SYMBOL_NUMERIC, settings.inputMax);
ImGui::EndDisabled();
}
if (ImGui::Checkbox("hex.builtin.view.find.value.range"_lang, &settings.range)) {
settings.inputMax = settings.inputMin;
}
ImGui::NewLine();
const std::array<std::string, 10> InputTypes = {
"hex.ui.common.type.u8"_lang,
"hex.ui.common.type.u16"_lang,
"hex.ui.common.type.u32"_lang,
"hex.ui.common.type.u64"_lang,
"hex.ui.common.type.i8"_lang,
"hex.ui.common.type.i16"_lang,
"hex.ui.common.type.i32"_lang,
"hex.ui.common.type.i64"_lang,
"hex.ui.common.type.f32"_lang,
"hex.ui.common.type.f64"_lang
};
if (ImGui::BeginCombo("hex.ui.common.type"_lang, InputTypes[std::to_underlying(settings.type)].c_str())) {
for (size_t i = 0; i < InputTypes.size(); i++) {
auto type = static_cast<SearchSettings::Value::Type>(i);
if (ImGui::Selectable(InputTypes[i].c_str(), type == settings.type)) {
settings.type = type;
edited = true;
}
}
ImGui::EndCombo();
}
{
int selection = [&] {
switch (settings.endian) {
default:
case std::endian::little: return 0;
case std::endian::big: return 1;
}
}();
std::array options = { "hex.ui.common.little"_lang, "hex.ui.common.big"_lang };
if (ImGui::SliderInt("hex.ui.common.endian"_lang, &selection, 0, options.size() - 1, options[selection], ImGuiSliderFlags_NoInput)) {
edited = true;
switch (selection) {
default:
case 0: settings.endian = std::endian::little; break;
case 1: settings.endian = std::endian::big; break;
}
}
}
ImGui::Checkbox("hex.builtin.view.find.value.aligned"_lang, &settings.aligned);
if (edited) {
auto [minValid, min, minSize] = parseNumericValueInput(settings.inputMin, settings.type);
auto [maxValid, max, maxSize] = parseNumericValueInput(settings.inputMax, settings.type);
m_settingsValid = minValid && maxValid && minSize == maxSize;
}
if (settings.inputMin.empty())
m_settingsValid = false;
ImGui::EndTabItem();
}
ImGui::EndTabBar();
}
ImGui::NewLine();
ImGui::BeginDisabled(!m_settingsValid);
{
if (ImGui::Button("hex.builtin.view.find.search"_lang)) {
this->runSearch();
m_decodeSettings = m_searchSettings;
}
}
ImGui::EndDisabled();
ImGui::SameLine();
ImGui::BeginDisabled(m_foundOccurrences->empty());
{
if (ImGui::Button("hex.builtin.view.find.search.reset"_lang)) {
m_foundOccurrences->clear();
m_sortedOccurrences->clear();
m_occurrenceTree->clear();
m_lastSelectedOccurrence = nullptr;
EventHighlightingChanged::post();
}
}
ImGui::EndDisabled();
ImGui::SameLine();
ImGuiExt::TextFormatted("hex.builtin.view.find.search.entries"_lang, m_foundOccurrences->size());
}
ImGui::EndDisabled();
ImGui::Separator();
ImGui::NewLine();
auto &currOccurrences = *m_sortedOccurrences;
ImGui::PushItemWidth(-30_scaled);
auto prevFilterLength = m_currFilter->length();
if (ImGuiExt::InputTextIcon("##filter", ICON_VS_FILTER, *m_currFilter)) {
if (prevFilterLength > m_currFilter->length())
*m_sortedOccurrences = *m_foundOccurrences;
if (m_filterTask.isRunning())
m_filterTask.interrupt();
if (!m_currFilter->empty()) {
m_filterTask = TaskManager::createTask("hex.builtin.task.filtering_data"_lang, currOccurrences.size(), [this, provider, &currOccurrences](Task &task) {
u64 progress = 0;
std::erase_if(currOccurrences, [this, provider, &task, &progress](const auto ®ion) {
task.update(progress);
progress += 1;
return !hex::containsIgnoreCase(this->decodeValue(provider, region), m_currFilter.get(provider));
});
});
}
}
ImGui::PopItemWidth();
ImGui::SameLine();
const auto startPos = ImGui::GetCursorPos();
ImGui::BeginDisabled(m_sortedOccurrences->empty());
if (ImGuiExt::DimmedIconButton(ICON_VS_EXPORT, ImGui::GetStyleColorVec4(ImGuiCol_Text))) {
ImGui::OpenPopup("ExportResults");
}
ImGui::EndDisabled();
ImGui::SetNextWindowPos(ImGui::GetWindowPos() + ImVec2(startPos.x, ImGui::GetCursorPosY()));
if (ImGui::BeginPopup("ExportResults")) {
for (const auto &formatter : ContentRegistry::DataFormatter::impl::getFindExporterEntries()) {
const auto formatterName = formatter.unlocalizedName;
const auto name = toUpper(formatterName);
const auto &extension = formatter.fileExtension;
if (ImGui::MenuItem(name.c_str())) {
fs::openFileBrowser(fs::DialogMode::Save, { { name.c_str(), extension.c_str() } }, [&](const std::fs::path &path) {
wolv::io::File file(path, wolv::io::File::Mode::Create);
if (!file.isValid())
return;
auto result = formatter.callback(
m_sortedOccurrences.get(provider),
[&](Occurrence o){ return this->decodeValue(provider, o); });
file.writeVector(result);
file.close();
});
}
}
ImGui::EndPopup();
}
if (ImGui::BeginTable("##entries", 3, ImGuiTableFlags_Borders | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_Sortable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_RowBg | ImGuiTableFlags_ScrollY, ImMax(ImGui::GetContentRegionAvail(), ImVec2(0, ImGui::GetTextLineHeightWithSpacing() * 5)))) {
ImGui::TableSetupScrollFreeze(0, 1);
ImGui::TableSetupColumn("hex.ui.common.offset"_lang, 0, -1, ImGui::GetID("offset"));
ImGui::TableSetupColumn("hex.ui.common.size"_lang, 0, -1, ImGui::GetID("size"));
ImGui::TableSetupColumn("hex.ui.common.value"_lang, 0, -1, ImGui::GetID("value"));
auto sortSpecs = ImGui::TableGetSortSpecs();
if (sortSpecs->SpecsDirty) {
std::sort(currOccurrences.begin(), currOccurrences.end(), [this, &sortSpecs, provider](const Occurrence &left, const Occurrence &right) -> bool {
if (sortSpecs->Specs->ColumnUserID == ImGui::GetID("offset")) {
if (sortSpecs->Specs->SortDirection == ImGuiSortDirection_Ascending)
return left.region.getStartAddress() > right.region.getStartAddress();
else
return left.region.getStartAddress() < right.region.getStartAddress();
} else if (sortSpecs->Specs->ColumnUserID == ImGui::GetID("size")) {
if (sortSpecs->Specs->SortDirection == ImGuiSortDirection_Ascending)
return left.region.getSize() > right.region.getSize();
else
return left.region.getSize() < right.region.getSize();
} else if (sortSpecs->Specs->ColumnUserID == ImGui::GetID("value")) {
if (sortSpecs->Specs->SortDirection == ImGuiSortDirection_Ascending)
return this->decodeValue(provider, left) > this->decodeValue(provider, right);
else
return this->decodeValue(provider, left) < this->decodeValue(provider, right);
}
return false;
});
sortSpecs->SpecsDirty = false;
}
ImGui::TableHeadersRow();
ImGuiListClipper clipper;
clipper.Begin(currOccurrences.size(), ImGui::GetTextLineHeightWithSpacing());
while (clipper.Step()) {
for (size_t i = clipper.DisplayStart; i < std::min<size_t>(clipper.DisplayEnd, currOccurrences.size()); i++) {
auto &foundItem = currOccurrences[i];
ImGui::TableNextRow();
ImGui::TableNextColumn();
ImGuiExt::TextFormatted("0x{:08X}", foundItem.region.getStartAddress());
ImGui::TableNextColumn();
ImGuiExt::TextFormatted("{}", hex::toByteString(foundItem.region.getSize()));
ImGui::TableNextColumn();
ImGui::PushID(i);
auto value = this->decodeValue(provider, foundItem, 256);
ImGuiExt::TextFormatted("{}", value);
ImGui::SameLine();
if (ImGui::Selectable("##line", foundItem.selected, ImGuiSelectableFlags_SpanAllColumns)) {
if (ImGui::GetIO().KeyShift && m_lastSelectedOccurrence != nullptr) {
for (auto start = std::min(&foundItem, m_lastSelectedOccurrence.get(provider)); start <= std::max(&foundItem, m_lastSelectedOccurrence.get(provider)); start += 1)
start->selected = true;
} else if (ImGui::GetIO().KeyCtrl) {
foundItem.selected = !foundItem.selected;
} else {
for (auto &occurrence : *m_sortedOccurrences)
occurrence.selected = false;
foundItem.selected = true;
ImHexApi::HexEditor::setSelection(foundItem.region.getStartAddress(), foundItem.region.getSize());
}
m_lastSelectedOccurrence = &foundItem;
}
drawContextMenu(foundItem, value);
ImGui::PopID();
}
}
clipper.End();
ImGui::EndTable();
}
}
}
| 47,280
|
C++
|
.cpp
| 838
| 38.461814
| 306
| 0.522813
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
237
|
view_achievements.cpp
|
WerWolv_ImHex/plugins/builtin/source/content/views/view_achievements.cpp
|
#include "content/views/view_achievements.hpp"
#include <hex/api/content_registry.hpp>
#include <hex/api/task_manager.hpp>
#include <fonts/codicons_font.h>
#include <cmath>
namespace hex::plugin::builtin {
ViewAchievements::ViewAchievements() : View::Floating("hex.builtin.view.achievements.name") {
// Add achievements menu item to Extas menu
ContentRegistry::Interface::addMenuItem({ "hex.builtin.menu.extras", "hex.builtin.view.achievements.name" }, ICON_VS_SPARKLE, 2600, Shortcut::None, [&, this] {
this->getWindowOpenState() = true;
});
// Add newly unlocked achievements to the display queue
EventAchievementUnlocked::subscribe(this, [this](const Achievement &achievement) {
m_achievementUnlockQueue.push_back(&achievement);
AchievementManager::storeProgress();
});
RequestOpenWindow::subscribe(this, [this](const std::string &name) {
if (name == "Achievements") {
TaskManager::doLater([this] {
this->getWindowOpenState() = true;
});
}
});
// Load settings
m_showPopup = ContentRegistry::Settings::read<bool>("hex.builtin.setting.interface", "hex.builtin.setting.interface.achievement_popup", true);
}
ViewAchievements::~ViewAchievements() {
EventAchievementUnlocked::unsubscribe(this);
}
void drawAchievement(ImDrawList *drawList, const AchievementManager::AchievementNode *node, ImVec2 position) {
const auto achievementSize = scaled({ 50, 50 });
auto &achievement = *node->achievement;
// Determine achievement border color based on unlock state
const auto borderColor = [&] {
if (achievement.isUnlocked())
return ImGuiExt::GetCustomColorU32(ImGuiCustomCol_AchievementUnlocked, 1.0F);
else if (node->isUnlockable())
return ImGui::GetColorU32(ImGuiCol_Button, 1.0F);
else
return ImGui::GetColorU32(ImGuiCol_PlotLines, 1.0F);
}();
// Determine achievement fill color based on unlock state
const auto fillColor = [&] {
if (achievement.isUnlocked()) {
return ImGui::GetColorU32(ImGuiCol_FrameBg, 1.0F) | 0xFF000000;
} else if (node->isUnlockable()) {
auto cycleProgress = sinf(float(ImGui::GetTime()) * 6.0F) * 0.5F + 0.5F;
return (u32(ImColor(ImLerp(ImGui::GetStyleColorVec4(ImGuiCol_TextDisabled), ImGui::GetStyleColorVec4(ImGuiCol_Text), cycleProgress))) & 0x00FFFFFF) | 0x80000000;
} else {
return ImGui::GetColorU32(ImGuiCol_TextDisabled, 0.5F);
}
}();
// Draw achievement background
if (achievement.isUnlocked()) {
drawList->AddRectFilled(position, position + achievementSize, fillColor, 5_scaled, 0);
drawList->AddRect(position, position + achievementSize, borderColor, 5_scaled, 0, 2_scaled);
} else {
drawList->AddRectFilled(position, position + achievementSize, ImGui::GetColorU32(ImGuiCol_WindowBg) | 0xFF000000, 5_scaled, 0);
}
// Draw achievement icon if available
if (const auto &icon = achievement.getIcon(); icon.isValid()) {
ImVec2 iconSize;
if (icon.getSize().x > icon.getSize().y) {
iconSize.x = achievementSize.x;
iconSize.y = iconSize.x / icon.getSize().x * icon.getSize().y;
} else {
iconSize.y = achievementSize.y;
iconSize.x = iconSize.y / icon.getSize().y * icon.getSize().x;
}
iconSize *= 0.7F;
ImVec2 margin = (achievementSize - iconSize) / 2.0F;
drawList->AddImage(icon, position + margin, position + margin + iconSize);
}
// Dim achievement if it is not unlocked
if (!achievement.isUnlocked()) {
drawList->AddRectFilled(position, position + achievementSize, fillColor, 5_scaled, 0);
drawList->AddRect(position, position + achievementSize, borderColor, 5_scaled, 0, 2_scaled);
}
auto tooltipPos = position + ImVec2(achievementSize.x, 0);
auto tooltipSize = achievementSize * ImVec2(4, 0);
// Draw achievement tooltip when hovering over it
if (ImGui::IsWindowHovered() && ImGui::IsMouseHoveringRect(position, position + achievementSize)) {
ImGui::SetNextWindowPos(tooltipPos);
ImGui::SetNextWindowSize(tooltipSize);
if (ImGui::BeginTooltip()) {
if (achievement.isBlacked() && !achievement.isUnlocked()) {
// Handle achievements that are blacked out
ImGui::TextUnformatted("[ ??? ]");
} else {
// Handle regular achievements
ImGui::BeginDisabled(!achievement.isUnlocked());
// Draw achievement name
ImGui::TextUnformatted(Lang(achievement.getUnlocalizedName()));
// Draw progress bar if achievement has progress
if (auto requiredProgress = achievement.getRequiredProgress(); requiredProgress > 1) {
ImGui::ProgressBar(float(achievement.getProgress()) / float(requiredProgress + 1), ImVec2(achievementSize.x * 4, 5_scaled), "");
}
bool separator = false;
// Draw prompt to click on achievement if it has a click callback
if (achievement.getClickCallback() && !achievement.isUnlocked()) {
ImGui::Separator();
separator = true;
ImGuiExt::TextFormattedColored(ImGuiExt::GetCustomColorVec4(ImGuiCustomCol_AchievementUnlocked), "[ {} ]", Lang("hex.builtin.view.achievements.click"));
}
// Draw achievement description if available
if (const auto &desc = achievement.getUnlocalizedDescription(); !desc.empty()) {
if (!separator)
ImGui::Separator();
else
ImGui::NewLine();
ImGuiExt::TextFormattedWrapped("{}", Lang(desc));
}
ImGui::EndDisabled();
}
ImGui::EndTooltip();
}
// Handle achievement click
if (!achievement.isUnlocked() && ImGui::IsMouseClicked(ImGuiMouseButton_Left)) {
if (ImGui::GetIO().KeyShift) {
// Allow achievements to be unlocked in debug mode by shift-clicking them
#if defined (DEBUG)
AchievementManager::unlockAchievement(node->achievement->getUnlocalizedCategory(), node->achievement->getUnlocalizedName());
#endif
} else {
// Trigger achievement click callback
if (auto clickCallback = achievement.getClickCallback(); clickCallback)
clickCallback(achievement);
}
}
}
}
void drawOverlay(ImDrawList *drawList, ImVec2 windowMin, ImVec2 windowMax, const std::string &currCategory) {
auto &achievements = AchievementManager::getAchievements().at(currCategory);
// Calculate number of achievements that have been unlocked
const auto unlockedCount = std::count_if(achievements.begin(), achievements.end(), [](const auto &entry) {
const auto &[name, achievement] = entry;
return achievement->isUnlocked();
});
// Calculate number of invisible achievements
const auto invisibleCount = std::count_if(achievements.begin(), achievements.end(), [](const auto &entry) {
const auto &[name, achievement] = entry;
return achievement->isInvisible() && !achievement->isUnlocked();
});
// Calculate number of visible achievements
const auto visibleCount = achievements.size() - invisibleCount;
// Construct number of unlocked achievements text
auto unlockedText = hex::format("{}: {} / {}{}", "hex.builtin.view.achievements.unlocked_count"_lang, unlockedCount, visibleCount, invisibleCount > 0 ? "+" : " ");
// Calculate overlay size
auto &style = ImGui::GetStyle();
auto overlaySize = ImGui::CalcTextSize(unlockedText.c_str()) + style.ItemSpacing + style.WindowPadding * 2.0F;
auto padding = scaled({ 10, 10 });
auto overlayPos = ImVec2(windowMax.x - overlaySize.x - padding.x, windowMin.y + padding.y);
// Draw overlay background
drawList->AddRectFilled(overlayPos, overlayPos + overlaySize, ImGui::GetColorU32(ImGuiCol_WindowBg, 0.8F));
drawList->AddRect(overlayPos, overlayPos + overlaySize, ImGui::GetColorU32(ImGuiCol_Border));
// Draw overlay content
ImGui::SetCursorScreenPos(overlayPos + padding);
ImGui::BeginGroup();
ImGui::TextUnformatted(unlockedText.c_str());
ImGui::EndGroup();
}
void drawBackground(ImDrawList *drawList, ImVec2 min, ImVec2 max, ImVec2 offset) {
const auto patternSize = scaled({ 10, 10 });
const auto darkColor = ImGui::GetColorU32(ImGuiCol_TableRowBg);
const auto lightColor = ImGui::GetColorU32(ImGuiCol_TableRowBgAlt);
// Draw a border around the entire background
drawList->AddRect(min, max, ImGui::GetColorU32(ImGuiCol_Border), 0.0F, 0, 1.0_scaled);
// Draw a checkerboard pattern
bool light = false;
bool prevStart = false;
for (float x = min.x + offset.x; x < max.x; x += i32(patternSize.x)) {
if (prevStart == light)
light = !light;
prevStart = light;
for (float y = min.y + offset.y; y < max.y; y += i32(patternSize.y)) {
drawList->AddRectFilled({ x, y }, { x + patternSize.x, y + patternSize.y }, light ? lightColor : darkColor);
light = !light;
}
}
}
ImVec2 ViewAchievements::drawAchievementTree(ImDrawList *drawList, const AchievementManager::AchievementNode * prevNode, const std::vector<AchievementManager::AchievementNode*> &nodes, ImVec2 position) {
ImVec2 maxPos = position;
// Loop over all available achievement nodes
for (auto &node : nodes) {
// If the achievement is invisible and not unlocked yet, don't draw anything
if (node->achievement->isInvisible() && !node->achievement->isUnlocked())
continue;
// If the achievement has any visibility requirements, check if they are met
if (!node->visibilityParents.empty()) {
bool visible = true;
// Check if all the visibility requirements are unlocked
for (auto &parent : node->visibilityParents) {
if (!parent->achievement->isUnlocked()) {
visible = false;
break;
}
}
// If any of the visibility requirements are not unlocked, don't draw the achievement
if (!visible)
continue;
}
drawList->ChannelsSetCurrent(1);
// Check if the achievement has any parents
if (prevNode != nullptr) {
// Check if the parent achievement is in the same category
if (prevNode->achievement->getUnlocalizedCategory() != node->achievement->getUnlocalizedCategory())
continue;
auto start = prevNode->position + scaled({ 25, 25 });
auto end = position + scaled({ 25, 25 });
auto middle = ((start + end) / 2.0F) - scaled({ 50, 0 });
const auto color = [prevNode]{
if (prevNode->achievement->isUnlocked())
return ImGui::GetColorU32(ImGuiCol_Text) | 0xFF000000;
else
return ImGui::GetColorU32(ImGuiCol_TextDisabled) | 0xFF000000;
}();
// Draw a bezier curve between the parent and child achievement
drawList->AddBezierQuadratic(start, middle, end, color, 2_scaled);
// Handle jumping to an achievement
if (m_achievementToGoto != nullptr) {
if (m_achievementToGoto == node->achievement) {
m_offset = position - scaled({ 100, 100 });
}
}
}
drawList->ChannelsSetCurrent(2);
// Draw the achievement
drawAchievement(drawList, node, position);
// Adjust the position for the next achievement and continue drawing the achievement tree
node->position = position;
auto newMaxPos = drawAchievementTree(drawList, node, node->children, position + scaled({ 150, 0 }));
if (newMaxPos.x > maxPos.x)
maxPos.x = newMaxPos.x;
if (newMaxPos.y > maxPos.y)
maxPos.y = newMaxPos.y;
position.y = maxPos.y + 100_scaled;
}
return maxPos;
}
void ViewAchievements::drawContent() {
if (ImGui::BeginTabBar("##achievement_categories")) {
auto &startNodes = AchievementManager::getAchievementStartNodes();
// Get all achievement category names
std::vector<std::string> categories;
for (const auto &[categoryName, achievements] : startNodes) {
categories.push_back(categoryName);
}
std::reverse(categories.begin(), categories.end());
// Draw each individual achievement category
for (const auto &categoryName : categories) {
const auto &achievements = startNodes.at(categoryName);
// Check if any achievements in the category are unlocked or unlockable
bool visible = false;
for (const auto &achievement : achievements) {
if (achievement->isUnlocked() || achievement->isUnlockable()) {
visible = true;
break;
}
}
// If all achievements in this category are invisible, don't draw it
if (!visible)
continue;
ImGuiTabItemFlags flags = ImGuiTabItemFlags_None;
// Handle jumping to the category of an achievement
if (m_achievementToGoto != nullptr) {
if (m_achievementToGoto->getUnlocalizedCategory() == categoryName) {
flags |= ImGuiTabItemFlags_SetSelected;
}
}
// Draw the achievement category
if (ImGui::BeginTabItem(Lang(categoryName), nullptr, flags)) {
auto drawList = ImGui::GetWindowDrawList();
const auto cursorPos = ImGui::GetCursorPos();
const auto windowPos = ImGui::GetWindowPos() + ImVec2(0, cursorPos.y);
const auto windowSize = ImGui::GetWindowSize() - ImVec2(0, cursorPos.y);
const float borderSize = 20.0_scaled;
const auto windowPadding = ImGui::GetStyle().WindowPadding;
const auto innerWindowPos = windowPos + ImVec2(borderSize, borderSize);
const auto innerWindowSize = windowSize - ImVec2(borderSize * 2, borderSize * 2) - ImVec2(0, ImGui::GetTextLineHeightWithSpacing());
// Prevent the achievement tree from being drawn outside of the window
drawList->PushClipRect(innerWindowPos, innerWindowPos + innerWindowSize, true);
drawList->ChannelsSplit(4);
drawList->ChannelsSetCurrent(0);
// Draw achievement background
drawBackground(drawList, innerWindowPos, innerWindowPos + innerWindowSize, m_offset);
// Draw the achievement tree
auto maxPos = drawAchievementTree(drawList, nullptr, achievements, innerWindowPos + scaled({ 100, 100 }) + m_offset);
drawList->ChannelsSetCurrent(3);
// Draw the achievement overlay
drawOverlay(drawList, innerWindowPos, innerWindowPos + innerWindowSize, categoryName);
drawList->ChannelsMerge();
// Handle dragging the achievement tree around
if (ImGui::IsMouseHoveringRect(innerWindowPos, innerWindowPos + innerWindowSize)) {
auto dragDelta = ImGui::GetMouseDragDelta(ImGuiMouseButton_Left);
m_offset += dragDelta;
ImGui::ResetMouseDragDelta(ImGuiMouseButton_Left);
}
// Clamp the achievement tree to the window
m_offset = -ImClamp(-m_offset, { 0, 0 }, ImMax(maxPos - innerWindowPos - innerWindowSize, { 0, 0 }));
drawList->PopClipRect();
// Draw settings below the window
ImGui::SetCursorScreenPos(innerWindowPos + ImVec2(0, innerWindowSize.y + windowPadding.y));
ImGui::BeginGroup();
{
if (ImGui::Checkbox("Show popup", &m_showPopup))
ContentRegistry::Settings::write<bool>("hex.builtin.setting.interface", "hex.builtin.setting.interface.achievement_popup", m_showPopup);
}
ImGui::EndGroup();
ImGui::EndTabItem();
}
}
ImGui::EndTabBar();
}
m_achievementToGoto = nullptr;
}
void ViewAchievements::drawAlwaysVisibleContent() {
// Handle showing the achievement unlock popup
if (m_achievementUnlockQueueTimer >= 0 && m_showPopup) {
m_achievementUnlockQueueTimer -= ImGui::GetIO().DeltaTime;
// Check if there's an achievement that can be drawn
if (m_currAchievement != nullptr) {
const ImVec2 windowSize = scaled({ 200, 55 });
ImGui::SetNextWindowPos(ImHexApi::System::getMainWindowPosition() + ImVec2 { ImHexApi::System::getMainWindowSize().x - windowSize.x - 100_scaled, 0 });
ImGui::SetNextWindowSize(windowSize);
if (ImGui::Begin("##achievement_unlocked", nullptr, ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_NoDocking | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoInputs)) {
ImGui::BringWindowToDisplayFront(ImGui::GetCurrentWindowRead());
// Draw unlock text
ImGuiExt::TextFormattedColored(ImGuiExt::GetCustomColorVec4(ImGuiCustomCol_AchievementUnlocked), "{}", "hex.builtin.view.achievements.unlocked"_lang);
// Draw achievement icon
ImGui::Image(m_currAchievement->getIcon(), scaled({ 20, 20 }));
ImGui::SameLine();
ImGui::SeparatorEx(ImGuiSeparatorFlags_Vertical);
ImGui::SameLine();
// Draw name of achievement
ImGuiExt::TextFormattedWrapped("{}", Lang(m_currAchievement->getUnlocalizedName()));
// Handle clicking on the popup
if (ImGui::IsWindowHovered() && ImGui::IsMouseReleased(ImGuiMouseButton_Left)) {
// Open the achievement window and jump to the achievement
this->getWindowOpenState() = true;
m_achievementToGoto = m_currAchievement;
}
}
ImGui::End();
}
} else {
// Reset the achievement unlock queue timer
m_achievementUnlockQueueTimer = -1.0F;
m_currAchievement = nullptr;
// If there are more achievements to draw, draw the next one
if (!m_achievementUnlockQueue.empty()) {
m_currAchievement = m_achievementUnlockQueue.front();
m_achievementUnlockQueue.pop_front();
m_achievementUnlockQueueTimer = 5.0F;
}
}
}
}
| 20,713
|
C++
|
.cpp
| 357
| 42.694678
| 320
| 0.583621
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
238
|
view_command_palette.cpp
|
WerWolv_ImHex/plugins/builtin/source/content/views/view_command_palette.cpp
|
#include "content/views/view_command_palette.hpp"
#include <hex/api/content_registry.hpp>
#include <wolv/utils/guards.hpp>
namespace hex::plugin::builtin {
ViewCommandPalette::ViewCommandPalette() : View::Special("hex.builtin.view.command_palette.name") {
// Add global shortcut to open the command palette
ShortcutManager::addGlobalShortcut(CTRLCMD + SHIFT + Keys::P, "hex.builtin.view.command_palette.name", [this] {
RequestOpenPopup::post("hex.builtin.view.command_palette.name"_lang);
m_commandPaletteOpen = true;
m_justOpened = true;
});
EventSearchBoxClicked::subscribe([this](ImGuiMouseButton button) {
if (button == ImGuiMouseButton_Left) {
RequestOpenPopup::post("hex.builtin.view.command_palette.name"_lang);
m_commandPaletteOpen = true;
m_justOpened = true;
}
});
}
void ViewCommandPalette::drawAlwaysVisibleContent() {
// If the command palette is hidden, don't draw it
if (!m_commandPaletteOpen) return;
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));
ImGui::SetNextWindowSizeConstraints(this->getMinSize(), this->getMaxSize());
if (ImGui::BeginPopup("hex.builtin.view.command_palette.name"_lang)) {
ImGui::BringWindowToDisplayFront(ImGui::GetCurrentWindowRead());
ImGui::BringWindowToFocusFront(ImGui::GetCurrentWindowRead());
// Close the popup if the user presses ESC
if (ImGui::IsKeyDown(ImGuiKey_Escape))
ImGui::CloseCurrentPopup();
const auto buttonColor = [](float alpha) {
return ImU32(ImColor(ImGui::GetStyleColorVec4(ImGuiCol_ModalWindowDimBg) * ImVec4(1, 1, 1, alpha)));
};
// Draw the main input text box
ImGui::PushItemWidth(-1);
ImGui::PushStyleColor(ImGuiCol_FrameBg, buttonColor(0.5F));
ImGui::PushStyleColor(ImGuiCol_FrameBgHovered, buttonColor(0.7F));
ImGui::PushStyleColor(ImGuiCol_FrameBgActive, buttonColor(0.9F));
ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 1.0_scaled);
ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 4_scaled);
if (ImGui::InputText("##command_input", m_commandBuffer)) {
m_lastResults = this->getCommandResults(m_commandBuffer);
}
ImGui::SetItemKeyOwner(ImGuiKey_LeftAlt, ImGuiInputFlags_CondActive);
ImGui::PopStyleVar(2);
ImGui::PopStyleColor(3);
ImGui::PopItemWidth();
ImGui::SetItemDefaultFocus();
if (m_moveCursorToEnd) {
auto textState = ImGui::GetInputTextState(ImGui::GetID("##command_input"));
if (textState != nullptr) {
textState->Stb.cursor =
textState->Stb.select_start =
textState->Stb.select_end = m_commandBuffer.size();
}
m_moveCursorToEnd = false;
}
// Handle giving back focus to the input text box
if (m_focusInputTextBox) {
ImGui::SetKeyboardFocusHere(-1);
ImGui::ActivateItemByID(ImGui::GetID("##command_input"));
m_focusInputTextBox = false;
m_moveCursorToEnd = true;
}
// Execute the currently selected command when pressing enter
if (ImGui::IsItemFocused() && (ImGui::IsKeyPressed(ImGuiKey_Enter, false) || ImGui::IsKeyPressed(ImGuiKey_KeypadEnter, false))) {
if (!m_lastResults.empty()) {
auto &[displayResult, matchedCommand, callback] = m_lastResults.front();
callback(matchedCommand);
}
ImGui::CloseCurrentPopup();
}
// Focus the input text box when the popup is opened
if (m_justOpened) {
focusInputTextBox();
m_lastResults = this->getCommandResults("");
m_commandBuffer.clear();
m_justOpened = false;
}
ImGui::SetCursorPosY(ImGui::GetCursorPosY() + ImGui::GetStyle().FramePadding.y);
ImGui::Separator();
// Draw the results
if (ImGui::BeginChild("##results", ImGui::GetContentRegionAvail(), ImGuiChildFlags_NavFlattened, ImGuiWindowFlags_AlwaysVerticalScrollbar)) {
for (const auto &[displayResult, matchedCommand, callback] : m_lastResults) {
ImGui::PushItemFlag(ImGuiItemFlags_NoTabStop, false);
ON_SCOPE_EXIT { ImGui::PopItemFlag(); };
// Allow executing a command by clicking on it or selecting it with the keyboard and pressing enter
if (ImGui::Selectable(displayResult.c_str(), false, ImGuiSelectableFlags_NoAutoClosePopups)) {
callback(matchedCommand);
break;
}
if (ImGui::IsItemFocused() && (ImGui::IsKeyDown(ImGuiKey_Enter) || ImGui::IsKeyDown(ImGuiKey_KeypadEnter))) {
callback(matchedCommand);
break;
}
}
}
ImGui::EndChild();
ImGui::EndPopup();
} else {
m_commandPaletteOpen = false;
}
}
std::vector<ViewCommandPalette::CommandResult> ViewCommandPalette::getCommandResults(const std::string &input) {
constexpr static auto MatchCommand = [](const std::string &currCommand, const std::string &commandToMatch) -> std::pair<MatchType, std::string_view> {
// Check if the current input matches a command
// NoMatch means that the input doesn't match the command
// PartialMatch means that the input partially matches the command but is not a perfect match
// PerfectMatch means that the input perfectly matches the command
if (currCommand.empty()) {
return { MatchType::InfoMatch, "" };
} else if (currCommand.size() <= commandToMatch.size()) {
if (commandToMatch.starts_with(currCommand))
return { MatchType::PartialMatch, currCommand };
else
return { MatchType::NoMatch, {} };
} else {
if (currCommand.starts_with(commandToMatch))
return { MatchType::PerfectMatch, currCommand.substr(commandToMatch.length()) };
else
return { MatchType::NoMatch, {} };
}
};
std::vector<CommandResult> results;
// Loop over every registered command and check if the input matches it
for (const auto &[type, command, unlocalizedDescription, displayCallback, executeCallback] : ContentRegistry::CommandPaletteCommands::impl::getEntries()) {
auto AutoComplete = [this, currCommand = command](auto) {
this->focusInputTextBox();
m_commandBuffer = currCommand + " ";
m_lastResults = this->getCommandResults(currCommand);
};
if (type == ContentRegistry::CommandPaletteCommands::Type::SymbolCommand) {
// Handle symbol commands
// These commands are used by entering a single symbol and then any input
if (auto [match, value] = MatchCommand(input, command); match != MatchType::NoMatch) {
if (match != MatchType::PerfectMatch) {
results.push_back({ hex::format("{} ({})", command, Lang(unlocalizedDescription)), "", AutoComplete });
} else {
auto matchedCommand = wolv::util::trim(input.substr(command.length()));
results.push_back({ displayCallback(matchedCommand), matchedCommand, executeCallback });
}
}
} else if (type == ContentRegistry::CommandPaletteCommands::Type::KeywordCommand) {
// Handle keyword commands
// These commands are used by entering a keyword followed by a space and then any input
if (auto [match, value] = MatchCommand(input, command + " "); match != MatchType::NoMatch) {
if (match != MatchType::PerfectMatch) {
results.push_back({ hex::format("{} ({})", command, Lang(unlocalizedDescription)), "", AutoComplete });
} else {
auto matchedCommand = wolv::util::trim(input.substr(command.length() + 1));
results.push_back({ displayCallback(matchedCommand), matchedCommand, executeCallback });
}
}
}
}
// WHen a command has been identified, show the query results for that command
for (const auto &handler : ContentRegistry::CommandPaletteCommands::impl::getHandlers()) {
const auto &[type, command, queryCallback, displayCallback] = handler;
auto processedInput = input;
if (processedInput.starts_with(command))
processedInput = wolv::util::trim(processedInput.substr(command.length()));
for (const auto &[description, callback] : queryCallback(processedInput)) {
if (type == ContentRegistry::CommandPaletteCommands::Type::SymbolCommand) {
if (auto [match, value] = MatchCommand(input, command); match != MatchType::NoMatch) {
results.push_back({ hex::format("{} ({})", command, description), "", callback });
}
} else if (type == ContentRegistry::CommandPaletteCommands::Type::KeywordCommand) {
if (auto [match, value] = MatchCommand(input, command + " "); match != MatchType::NoMatch) {
results.push_back({ hex::format("{} ({})", command, description), "", callback });
}
}
}
}
return results;
}
}
| 10,396
|
C++
|
.cpp
| 178
| 43.410112
| 163
| 0.584209
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
239
|
view_hex_editor.cpp
|
WerWolv_ImHex/plugins/builtin/source/content/views/view_hex_editor.cpp
|
#include "content/views/view_hex_editor.hpp"
#include <hex/api/content_registry.hpp>
#include <hex/api/shortcut_manager.hpp>
#include <hex/api/project_file_manager.hpp>
#include <hex/api/achievement_manager.hpp>
#include <hex/helpers/utils.hpp>
#include <hex/helpers/crypto.hpp>
#include <hex/helpers/default_paths.hpp>
#include <hex/providers/buffered_reader.hpp>
#include <wolv/math_eval/math_evaluator.hpp>
#include <content/providers/view_provider.hpp>
#include <fonts/codicons_font.h>
#include <popups/popup_file_chooser.hpp>
#include <content/popups/popup_blocking_task.hpp>
#include <content/popups/hex_editor/popup_hex_editor_find.hpp>
#include <pl/patterns/pattern.hpp>
using namespace std::literals::string_literals;
namespace hex::plugin::builtin {
/* Popups */
class PopupGoto : public ViewHexEditor::Popup {
public:
void draw(ViewHexEditor *editor) override {
if (ImGui::BeginTabBar("goto_tabs")) {
if (ImGui::BeginTabItem("hex.builtin.view.hex_editor.goto.offset.absolute"_lang)) {
m_mode = Mode::Absolute;
ImGui::EndTabItem();
}
ImGui::BeginDisabled(!editor->isSelectionValid());
if (ImGui::BeginTabItem("hex.builtin.view.hex_editor.goto.offset.relative"_lang)) {
m_mode = Mode::Relative;
ImGui::EndTabItem();
}
ImGui::EndDisabled();
if (ImGui::BeginTabItem("hex.builtin.view.hex_editor.goto.offset.begin"_lang)) {
m_mode = Mode::Begin;
ImGui::EndTabItem();
}
if (ImGui::BeginTabItem("hex.builtin.view.hex_editor.goto.offset.end"_lang)) {
m_mode = Mode::End;
ImGui::EndTabItem();
}
if (m_requestFocus){
ImGui::SetKeyboardFocusHere();
m_requestFocus = false;
}
if (ImGuiExt::InputTextIcon("##input", ICON_VS_SYMBOL_OPERATOR, m_input)) {
if (auto result = m_evaluator.evaluate(m_input); result.has_value()) {
const auto inputResult = result.value();
auto provider = ImHexApi::Provider::get();
switch (m_mode) {
case Mode::Absolute: {
m_newAddress = inputResult;
}
break;
case Mode::Relative: {
const auto selection = editor->getSelection();
m_newAddress = selection.getStartAddress() + inputResult;
}
break;
case Mode::Begin: {
m_newAddress = provider->getBaseAddress() + provider->getCurrentPageAddress() + inputResult;
}
break;
case Mode::End: {
m_newAddress = provider->getActualSize() - inputResult;
}
break;
}
} else {
m_newAddress.reset();
}
}
bool isOffsetValid = m_newAddress <= ImHexApi::Provider::get()->getActualSize();
bool executeGoto = false;
if (ImGui::IsWindowFocused() && (ImGui::IsKeyPressed(ImGuiKey_Enter) || ImGui::IsKeyPressed(ImGuiKey_KeypadEnter))) {
executeGoto = true;
}
ImGui::BeginDisabled(!m_newAddress.has_value() || !isOffsetValid);
{
const auto label = hex::format("{} {}", "hex.builtin.view.hex_editor.menu.file.goto"_lang, m_newAddress.has_value() ? hex::format("0x{:08X}", *m_newAddress) : "???");
const auto buttonWidth = ImGui::GetWindowWidth() - ImGui::GetStyle().WindowPadding.x * 2;
if (ImGuiExt::DimmedButton(label.c_str(), ImVec2(buttonWidth, 0))) {
executeGoto = true;
}
}
ImGui::EndDisabled();
if (executeGoto && m_newAddress.has_value()) {
editor->setSelection(*m_newAddress, *m_newAddress);
editor->jumpToSelection();
if (!this->isPinned())
editor->closePopup();
}
ImGui::EndTabBar();
}
}
[[nodiscard]] UnlocalizedString getTitle() const override {
return "hex.builtin.view.hex_editor.menu.file.goto";
}
bool canBePinned() const override {
return true;
}
private:
enum class Mode : u8 {
Absolute,
Relative,
Begin,
End
};
Mode m_mode = Mode::Absolute;
std::optional<u64> m_newAddress;
bool m_requestFocus = true;
std::string m_input = "0x";
wolv::math_eval::MathEvaluator<i128> m_evaluator;
};
class PopupSelect : public ViewHexEditor::Popup {
public:
PopupSelect(u64 address, size_t size): m_region({address, size}) {}
void draw(ViewHexEditor *editor) override {
if (ImGui::BeginTabBar("select_tabs")) {
if (ImGui::BeginTabItem("hex.builtin.view.hex_editor.select.offset.region"_lang)) {
u64 inputA = m_region.getStartAddress();
u64 inputB = m_region.getEndAddress();
if (justOpened) {
ImGui::SetKeyboardFocusHere();
justOpened = false;
}
ImGuiExt::InputHexadecimal("hex.builtin.view.hex_editor.select.offset.begin"_lang, &inputA, ImGuiInputTextFlags_AutoSelectAll);
ImGuiExt::InputHexadecimal("hex.builtin.view.hex_editor.select.offset.end"_lang, &inputB, ImGuiInputTextFlags_AutoSelectAll);
if (inputB < inputA)
inputB = inputA;
m_region = { inputA, (inputB - inputA) + 1 };
ImGui::EndTabItem();
}
if (ImGui::BeginTabItem("hex.builtin.view.hex_editor.select.offset.size"_lang)) {
u64 inputA = m_region.getStartAddress();
u64 inputB = m_region.getSize();
if (justOpened) {
ImGui::SetKeyboardFocusHere();
justOpened = false;
}
ImGuiExt::InputHexadecimal("hex.builtin.view.hex_editor.select.offset.begin"_lang, &inputA, ImGuiInputTextFlags_AutoSelectAll);
ImGuiExt::InputHexadecimal("hex.builtin.view.hex_editor.select.offset.size"_lang, &inputB, ImGuiInputTextFlags_AutoSelectAll);
if (inputB <= 0)
inputB = 1;
m_region = { inputA, inputB };
ImGui::EndTabItem();
}
const auto provider = ImHexApi::Provider::get();
bool isOffsetValid = m_region.getStartAddress() <= m_region.getEndAddress() &&
m_region.getEndAddress() < provider->getActualSize();
ImGui::BeginDisabled(!isOffsetValid);
{
if (ImGui::Button("hex.builtin.view.hex_editor.select.select"_lang) ||
(ImGui::IsWindowFocused() && (ImGui::IsKeyPressed(ImGuiKey_Enter) || ImGui::IsKeyPressed(ImGuiKey_KeypadEnter)))) {
editor->setSelection(m_region.getStartAddress(), m_region.getEndAddress());
editor->jumpToSelection();
if (!this->isPinned())
editor->closePopup();
}
}
ImGui::EndDisabled();
ImGui::EndTabBar();
}
}
[[nodiscard]] UnlocalizedString getTitle() const override {
return "hex.builtin.view.hex_editor.menu.edit.select";
}
[[nodiscard]] bool canBePinned() const override {
return true;
}
private:
Region m_region = { 0, 1 };
bool justOpened = true;
};
class PopupBaseAddress : public ViewHexEditor::Popup {
public:
explicit PopupBaseAddress(u64 baseAddress) : m_baseAddress(baseAddress) { }
void draw(ViewHexEditor *editor) override {
ImGuiExt::InputHexadecimal("##base_address", &m_baseAddress);
if (ImGui::IsItemFocused() && (ImGui::IsKeyPressed(ImGuiKey_Enter) || ImGui::IsKeyPressed(ImGuiKey_KeypadEnter))) {
setBaseAddress(m_baseAddress);
editor->closePopup();
}
ImGuiExt::ConfirmButtons("hex.ui.common.set"_lang, "hex.ui.common.cancel"_lang,
[&, this]{
setBaseAddress(m_baseAddress);
editor->closePopup();
},
[&]{
editor->closePopup();
}
);
}
[[nodiscard]] UnlocalizedString getTitle() const override {
return "hex.builtin.view.hex_editor.menu.edit.set_base";
}
private:
static void setBaseAddress(u64 baseAddress) {
if (ImHexApi::Provider::isValid())
ImHexApi::Provider::get()->setBaseAddress(baseAddress);
}
private:
u64 m_baseAddress;
};
class PopupPageSize : public ViewHexEditor::Popup {
public:
explicit PopupPageSize(u64 pageSize) : m_pageSize(pageSize) { }
void draw(ViewHexEditor *editor) override {
ImGuiExt::InputHexadecimal("##page_size", &m_pageSize);
if (ImGui::IsItemFocused() && (ImGui::IsKeyPressed(ImGuiKey_Enter) || ImGui::IsKeyPressed(ImGuiKey_KeypadEnter))) {
setPageSize(m_pageSize);
editor->closePopup();
}
ImGuiExt::ConfirmButtons("hex.ui.common.set"_lang, "hex.ui.common.cancel"_lang,
[&, this]{
setPageSize(m_pageSize);
editor->closePopup();
},
[&]{
editor->closePopup();
}
);
}
[[nodiscard]] UnlocalizedString getTitle() const override {
return "hex.builtin.view.hex_editor.menu.edit.set_page_size";
}
private:
static void setPageSize(u64 pageSize) {
if (ImHexApi::Provider::isValid()) {
auto provider = ImHexApi::Provider::get();
provider->setPageSize(pageSize);
provider->setCurrentPage(0);
}
}
private:
u64 m_pageSize;
};
class PopupResize : public ViewHexEditor::Popup {
public:
explicit PopupResize(u64 currSize) : m_size(currSize) {}
void draw(ViewHexEditor *editor) override {
ImGuiExt::InputHexadecimal("##resize", &m_size);
if (ImGui::IsItemFocused() && (ImGui::IsKeyPressed(ImGuiKey_Enter) || ImGui::IsKeyPressed(ImGuiKey_KeypadEnter))) {
this->resize(m_size);
editor->closePopup();
}
ImGuiExt::ConfirmButtons("hex.ui.common.set"_lang, "hex.ui.common.cancel"_lang,
[&, this]{
this->resize(m_size);
editor->closePopup();
},
[&]{
editor->closePopup();
});
}
[[nodiscard]] UnlocalizedString getTitle() const override {
return "hex.builtin.view.hex_editor.menu.edit.resize";
}
private:
static void resize(size_t newSize) {
if (ImHexApi::Provider::isValid())
ImHexApi::Provider::get()->resize(newSize);
}
private:
u64 m_size;
};
class PopupInsert : public ViewHexEditor::Popup {
public:
PopupInsert(u64 address, size_t size) : m_address(address), m_size(size) {}
void draw(ViewHexEditor *editor) override {
ImGuiExt::InputHexadecimal("hex.ui.common.address"_lang, &m_address);
ImGuiExt::InputHexadecimal("hex.ui.common.size"_lang, &m_size);
ImGuiExt::ConfirmButtons("hex.ui.common.set"_lang, "hex.ui.common.cancel"_lang,
[&, this]{
insert(m_address, m_size);
editor->closePopup();
},
[&]{
editor->closePopup();
});
if (ImGui::IsWindowFocused() && (ImGui::IsKeyPressed(ImGuiKey_Enter) || ImGui::IsKeyPressed(ImGuiKey_KeypadEnter))) {
insert(m_address, m_size);
editor->closePopup();
}
}
[[nodiscard]] UnlocalizedString getTitle() const override {
return "hex.builtin.view.hex_editor.menu.edit.insert";
}
private:
static void insert(u64 address, size_t size) {
if (ImHexApi::Provider::isValid())
ImHexApi::Provider::get()->insert(address, size);
}
private:
u64 m_address;
u64 m_size;
};
class PopupRemove : public ViewHexEditor::Popup {
public:
PopupRemove(u64 address, size_t size) : m_address(address), m_size(size) {}
void draw(ViewHexEditor *editor) override {
ImGuiExt::InputHexadecimal("hex.ui.common.address"_lang, &m_address);
ImGuiExt::InputHexadecimal("hex.ui.common.size"_lang, &m_size);
ImGuiExt::ConfirmButtons("hex.ui.common.set"_lang, "hex.ui.common.cancel"_lang,
[&, this]{
remove(m_address, m_size);
editor->closePopup();
},
[&]{
editor->closePopup();
});
if (ImGui::IsWindowFocused() && (ImGui::IsKeyPressed(ImGuiKey_Enter) || ImGui::IsKeyPressed(ImGuiKey_KeypadEnter))) {
remove(m_address, m_size);
editor->closePopup();
}
}
[[nodiscard]] UnlocalizedString getTitle() const override {
return "hex.builtin.view.hex_editor.menu.edit.remove";
}
private:
static void remove(u64 address, size_t size) {
if (ImHexApi::Provider::isValid())
ImHexApi::Provider::get()->remove(address, size);
}
private:
u64 m_address;
u64 m_size;
};
class PopupFill : public ViewHexEditor::Popup {
public:
PopupFill(u64 address, size_t size) : m_address(address), m_size(size) {}
void draw(ViewHexEditor *editor) override {
ImGuiExt::InputHexadecimal("hex.ui.common.address"_lang, &m_address);
ImGuiExt::InputHexadecimal("hex.ui.common.size"_lang, &m_size);
ImGui::Separator();
ImGuiExt::InputTextIcon("hex.ui.common.bytes"_lang, ICON_VS_SYMBOL_NAMESPACE, m_input);
ImGuiExt::ConfirmButtons("hex.ui.common.set"_lang, "hex.ui.common.cancel"_lang,
[&, this] {
fill(m_address, m_size, m_input);
editor->closePopup();
},
[&] {
editor->closePopup();
});
if (ImGui::IsWindowFocused() && (ImGui::IsKeyPressed(ImGuiKey_Enter) || ImGui::IsKeyPressed(ImGuiKey_KeypadEnter))) {
fill(m_address, m_size, m_input);
editor->closePopup();
}
}
[[nodiscard]] UnlocalizedString getTitle() const override {
return "hex.builtin.view.hex_editor.menu.edit.fill";
}
private:
static void fill(u64 address, size_t size, std::string input) {
if (!ImHexApi::Provider::isValid())
return;
std::erase(input, ' ');
auto bytes = crypt::decode16(input);
if (bytes.empty())
return;
auto provider = ImHexApi::Provider::get();
u32 patchCount = 0;
for (u64 i = 0; i < size; i += bytes.size()) {
auto remainingSize = std::min<size_t>(size - i, bytes.size());
provider->write(provider->getBaseAddress() + address + i, bytes.data(), remainingSize);
patchCount += 1;
}
provider->getUndoStack().groupOperations(patchCount, "hex.builtin.undo_operation.fill");
AchievementManager::unlockAchievement("hex.builtin.achievement.hex_editor", "hex.builtin.achievement.hex_editor.fill.name");
}
private:
u64 m_address;
u64 m_size;
std::string m_input;
};
/* Hex Editor */
ViewHexEditor::ViewHexEditor() : View::Window("hex.builtin.view.hex_editor.name", ICON_VS_FILE_BINARY) {
m_hexEditor.setForegroundHighlightCallback([this](u64 address, const u8 *data, size_t size) -> std::optional<color_t> {
if (auto highlight = m_foregroundHighlights->find(address); highlight != m_foregroundHighlights->end())
return highlight->second;
std::optional<color_t> result;
for (const auto &[id, callback] : ImHexApi::HexEditor::impl::getForegroundHighlightingFunctions()) {
if (auto color = callback(address, data, size, result.has_value()); color.has_value())
result = color;
}
if (!result.has_value()) {
for (const auto &[id, highlighting] : ImHexApi::HexEditor::impl::getForegroundHighlights()) {
if (highlighting.getRegion().overlaps({ address, size }))
return highlighting.getColor();
}
}
if (result.has_value())
m_foregroundHighlights->insert({ address, result.value() });
return result;
});
m_hexEditor.setBackgroundHighlightCallback([this](u64 address, const u8 *data, size_t size) -> std::optional<color_t> {
if (auto highlight = m_backgroundHighlights->find(address); highlight != m_backgroundHighlights->end()) {
if (std::ranges::any_of(*m_hoverHighlights, [region = Region(address, size)](const Region &highlight) { return highlight.overlaps(region); }))
return ImAlphaBlendColors(highlight->second, 0xA0FFFFFF);
else
return highlight->second;
}
std::optional<color_t> result;
for (const auto &[id, callback] : ImHexApi::HexEditor::impl::getBackgroundHighlightingFunctions()) {
if (auto color = callback(address, data, size, result.has_value()); color.has_value())
result = color;
}
if (!result.has_value()) {
for (const auto &[id, highlighting] : ImHexApi::HexEditor::impl::getBackgroundHighlights()) {
if (highlighting.getRegion().overlaps({ address, size }))
return highlighting.getColor();
}
}
if (result.has_value())
m_backgroundHighlights->insert({ address, result.value() });
return result;
});
m_hexEditor.setHoverChangedCallback([this](u64 address, size_t size) {
m_hoverHighlights->clear();
if (Region(address, size) == Region::Invalid())
return;
for (const auto &[id, hoverFunction] : ImHexApi::HexEditor::impl::getHoveringFunctions()) {
auto highlightedAddresses = hoverFunction(m_hexEditor.getProvider(), address, size);
m_hoverHighlights->merge(highlightedAddresses);
}
});
m_hexEditor.setTooltipCallback([](u64 address, const u8 *data, size_t size) {
for (const auto &[id, callback] : ImHexApi::HexEditor::impl::getTooltipFunctions()) {
callback(address, data, size);
}
for (const auto &[id, tooltip] : ImHexApi::HexEditor::impl::getTooltips()) {
if (tooltip.getRegion().overlaps({ address, size })) {
ImGui::BeginTooltip();
if (ImGui::BeginTable("##tooltips", 1, ImGuiTableFlags_NoHostExtendX | ImGuiTableFlags_RowBg | ImGuiTableFlags_NoClip)) {
ImGui::TableNextRow();
ImGui::TableNextColumn();
ImGui::ColorButton(tooltip.getValue().c_str(), ImColor(tooltip.getColor()));
ImGui::SameLine(0, 10);
ImGui::TextUnformatted(tooltip.getValue().c_str());
ImGui::PushStyleColor(ImGuiCol_TableRowBg, tooltip.getColor());
ImGui::PushStyleColor(ImGuiCol_TableRowBgAlt, tooltip.getColor());
ImGui::EndTable();
ImGui::PopStyleColor(2);
}
ImGui::EndTooltip();
}
}
});
this->registerShortcuts();
this->registerEvents();
this->registerMenuItems();
}
ViewHexEditor::~ViewHexEditor() {
RequestHexEditorSelectionChange::unsubscribe(this);
EventProviderChanged::unsubscribe(this);
EventProviderOpened::unsubscribe(this);
EventHighlightingChanged::unsubscribe(this);
ContentRegistry::Settings::write<int>("hex.builtin.setting.hex_editor", "hex.builtin.setting.hex_editor.bytes_per_row", m_hexEditor.getBytesPerRow());
}
void ViewHexEditor::drawPopup() {
bool open = true;
ImGui::SetNextWindowPos(ImGui::GetCurrentWindowRead()->ContentRegionRect.Min - ImGui::GetStyle().WindowPadding, ImGuiCond_Once);
const auto configuredAlpha = ImGuiExt::GetCustomStyle().PopupWindowAlpha;
bool alphaIsChanged = false;
if (m_currPopup != nullptr && !m_currentPopupHover && m_currentPopupHasHovered && m_currentPopupDetached && configuredAlpha < 0.99F && configuredAlpha > 0.01F) {
ImGui::PushStyleVar(ImGuiStyleVar_Alpha, configuredAlpha);
alphaIsChanged = true;
}
if (m_currPopup != nullptr) {
if (ImGui::Begin(hex::format("##{}", m_currPopup->getTitle().get()).c_str(), &open, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoDocking)) {
if (ImGui::IsKeyPressed(ImGuiKey_Escape)) {
this->closePopup();
} else {
float titleOffset = 7_scaled;
const ImVec2 originalCursorPos = ImGui::GetCursorPos();
if (m_currPopup->canBePinned()) {
titleOffset += 16_scaled;
ImGui::SetCursorPos(ImVec2(5_scaled, 0.0F));
bool pinned = m_currPopup->isPinned();
if (ImGuiExt::PopupTitleBarButton(pinned ? ICON_VS_PINNED : ICON_VS_PIN, pinned)) {
m_currPopup->setPinned(!pinned);
}
}
const auto popupTitle = m_currPopup->getTitle();
if (!popupTitle.empty()) {
ImGui::SetCursorPos(ImVec2(titleOffset, 0.0F));
ImGuiExt::PopupTitleBarText(Lang(popupTitle));
}
ImGui::SetCursorPos(originalCursorPos);
if (ImGui::IsWindowAppearing()) {
ImGui::SetKeyboardFocusHere();
m_currentPopupHasHovered = false;
}
m_currentPopupHover = ImGui::IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_RootAndChildWindows);
m_currentPopupDetached = !ImGui::GetCurrentWindow()->ViewportOwned;
m_currentPopupHasHovered |= m_currentPopupHover;
m_currPopup->draw(this);
}
} else {
this->closePopup();
}
if ((m_currPopup != nullptr && !m_currPopup->isPinned() && !ImGui::IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows) && !ImGui::IsWindowHovered()) || !open) {
this->closePopup();
}
ImGui::End();
}
if (alphaIsChanged)
ImGui::PopStyleVar();
// Right click menu
if (ImGui::IsMouseDown(ImGuiMouseButton_Right) && ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows) && !ImGui::IsAnyItemHovered() && !ImGui::IsMouseDragging(ImGuiMouseButton_Right))
RequestOpenPopup::post("hex.builtin.menu.edit");
}
void ViewHexEditor::drawContent() {
m_hexEditor.setProvider(ImHexApi::Provider::get());
m_hexEditor.draw();
this->drawPopup();
}
static void save() {
auto provider = ImHexApi::Provider::get();
if (provider != nullptr)
provider->save();
}
static void saveAs() {
auto provider = ImHexApi::Provider::get();
if (provider == nullptr)
return;
fs::openFileBrowser(fs::DialogMode::Save, {}, [provider](const auto &path) {
PopupBlockingTask::open(TaskManager::createTask("hex.builtin.task.saving_data"_lang, TaskManager::NoProgress, [=](Task &){
provider->saveAs(path);
}));
});
}
static void copyBytes(const Region &selection) {
constexpr static auto Format = "{0:02X} ";
auto provider = ImHexApi::Provider::get();
if (provider == nullptr)
return;
auto reader = prv::ProviderReader(provider);
reader.seek(selection.getStartAddress());
reader.setEndAddress(selection.getEndAddress());
std::string result;
result.reserve(fmt::format(Format, 0x00).size() * selection.getSize());
for (const auto &byte : reader)
result += fmt::format(Format, byte);
result.pop_back();
ImGui::SetClipboardText(result.c_str());
}
static void pasteBytes(const Region &selection, bool selectionCheck) {
auto provider = ImHexApi::Provider::get();
if (provider == nullptr)
return;
auto clipboard = ImGui::GetClipboardText();
if (clipboard == nullptr)
return;
auto buffer = parseHexString(clipboard);
if (!selectionCheck) {
if (selection.getStartAddress() + buffer.size() >= provider->getActualSize())
provider->resize(selection.getStartAddress() + buffer.size());
}
// Write bytes
auto size = selectionCheck ? std::min(buffer.size(), selection.getSize()) : buffer.size();
provider->write(selection.getStartAddress(), buffer.data(), size);
}
static void copyString(const Region &selection) {
auto provider = ImHexApi::Provider::get();
if (provider == nullptr)
return;
std::string buffer(selection.size, 0x00);
buffer.reserve(selection.size);
provider->read(selection.getStartAddress(), buffer.data(), selection.size);
ImGui::SetClipboardText(buffer.c_str());
}
static void copyCustomEncoding(const EncodingFile &customEncoding, const Region &selection) {
auto provider = ImHexApi::Provider::get();
if (provider == nullptr)
return;
std::vector<u8> buffer(customEncoding.getLongestSequence(), 0x00);
std::string string;
u64 offset = selection.getStartAddress();
while (offset < selection.getEndAddress()) {
provider->read(offset, buffer.data(), std::min<size_t>(buffer.size(), selection.size - (offset - selection.getStartAddress())));
auto [result, size] = customEncoding.getEncodingFor(buffer);
string += result;
offset += size;
}
ImGui::SetClipboardText(string.c_str());
}
void ViewHexEditor::registerShortcuts() {
// Remove selection
ShortcutManager::addShortcut(this, Keys::Escape, "hex.builtin.view.hex_editor.shortcut.remove_selection", [this] {
auto provider = ImHexApi::Provider::get();
if (provider == nullptr)
return;
m_selectionStart->reset();
m_selectionEnd->reset();
m_hexEditor.setSelectionUnchecked(std::nullopt, std::nullopt);
EventRegionSelected::post(ImHexApi::HexEditor::ProviderRegion{ Region::Invalid(), provider });
});
ShortcutManager::addShortcut(this, Keys::Enter, "hex.builtin.view.hex_editor.shortcut.enter_editing", [this] {
if (auto cursor = m_hexEditor.getCursorPosition(); cursor.has_value())
m_hexEditor.setEditingAddress(cursor.value());
});
// Move cursor around
ShortcutManager::addShortcut(this, Keys::Up, "hex.builtin.view.hex_editor.shortcut.cursor_up", [this] {
auto selection = getSelection();
auto cursor = m_hexEditor.getCursorPosition().value_or(selection.getEndAddress());
if (cursor >= m_hexEditor.getBytesPerRow()) {
auto pos = cursor - m_hexEditor.getBytesPerRow();
this->setSelection(pos, pos);
m_hexEditor.jumpIfOffScreen();
}
});
ShortcutManager::addShortcut(this, Keys::Down, "hex.builtin.view.hex_editor.shortcut.cursor_down", [this] {
auto selection = getSelection();
auto cursor = m_hexEditor.getCursorPosition().value_or(selection.getEndAddress());
auto pos = cursor + m_hexEditor.getBytesPerRow();
this->setSelection(pos, pos);
m_hexEditor.jumpIfOffScreen();
});
ShortcutManager::addShortcut(this, Keys::Left, "hex.builtin.view.hex_editor.shortcut.cursor_left", [this] {
auto selection = getSelection();
auto cursor = m_hexEditor.getCursorPosition().value_or(selection.getEndAddress());
if (cursor > 0) {
auto pos = cursor - m_hexEditor.getBytesPerCell();
this->setSelection(pos, pos);
m_hexEditor.jumpIfOffScreen();
}
});
ShortcutManager::addShortcut(this, Keys::Right, "hex.builtin.view.hex_editor.shortcut.cursor_right", [this] {
auto selection = getSelection();
auto cursor = m_hexEditor.getCursorPosition().value_or(selection.getEndAddress());
auto pos = cursor + m_hexEditor.getBytesPerCell();
this->setSelection(pos, pos);
m_hexEditor.jumpIfOffScreen();
});
ShortcutManager::addShortcut(this, Keys::PageUp, "hex.builtin.view.hex_editor.shortcut.cursor_page_up", [this] {
const i64 visibleRowCount = m_hexEditor.getVisibleRowCount();
m_hexEditor.setScrollPosition(m_hexEditor.getScrollPosition() - visibleRowCount);
});
ShortcutManager::addShortcut(this, Keys::PageDown, "hex.builtin.view.hex_editor.shortcut.cursor_page_down", [this] {
const i64 visibleRowCount = m_hexEditor.getVisibleRowCount();
m_hexEditor.setScrollPosition(m_hexEditor.getScrollPosition() + visibleRowCount);
});
ShortcutManager::addShortcut(this, Keys::Home, "hex.builtin.view.hex_editor.shortcut.cursor_start", [this] {
auto selection = getSelection();
auto cursor = m_hexEditor.getCursorPosition().value_or(selection.getEndAddress());
auto pos = cursor - cursor % m_hexEditor.getBytesPerRow();
this->setSelection(pos, (pos + m_hexEditor.getBytesPerCell()) - 1);
m_hexEditor.jumpIfOffScreen();
});
ShortcutManager::addShortcut(this, Keys::End, "hex.builtin.view.hex_editor.shortcut.cursor_end", [this] {
auto selection = getSelection();
auto cursor = m_hexEditor.getCursorPosition().value_or(selection.getEndAddress());
auto pos = cursor - cursor % m_hexEditor.getBytesPerRow() + m_hexEditor.getBytesPerRow() - m_hexEditor.getBytesPerCell();
this->setSelection(pos, (pos + m_hexEditor.getBytesPerCell()) - 1);
m_hexEditor.jumpIfOffScreen();
});
// Move selection around
ShortcutManager::addShortcut(this, SHIFT + Keys::Up, "hex.builtin.view.hex_editor.shortcut.selection_up", [this] {
auto selection = getSelection();
auto cursor = m_hexEditor.getCursorPosition();
if (cursor != selection.getStartAddress()) {
auto newCursor = std::max<u64>(cursor.value_or(selection.getEndAddress()), m_hexEditor.getBytesPerRow()) - m_hexEditor.getBytesPerRow();
setSelection(selection.getStartAddress(), newCursor);
m_hexEditor.setCursorPosition(newCursor);
} else {
auto newCursor = std::max<u64>(cursor.value_or(selection.getEndAddress()), m_hexEditor.getBytesPerRow()) - m_hexEditor.getBytesPerRow();
setSelection(newCursor, selection.getEndAddress());
m_hexEditor.setCursorPosition(newCursor);
}
m_hexEditor.jumpIfOffScreen();
});
ShortcutManager::addShortcut(this, SHIFT + Keys::Down, "hex.builtin.view.hex_editor.shortcut.selection_down", [this] {
auto selection = getSelection();
auto cursor = m_hexEditor.getCursorPosition();
if (cursor != selection.getStartAddress()) {
auto newCursor = cursor.value_or(selection.getEndAddress()) + m_hexEditor.getBytesPerRow();
setSelection(selection.getStartAddress(), newCursor);
m_hexEditor.setCursorPosition(newCursor);
} else {
auto newCursor = cursor.value_or(selection.getEndAddress()) + m_hexEditor.getBytesPerRow();
setSelection(newCursor, selection.getEndAddress());
m_hexEditor.setCursorPosition(newCursor);
}
m_hexEditor.jumpIfOffScreen();
});
ShortcutManager::addShortcut(this, SHIFT + Keys::Left, "hex.builtin.view.hex_editor.shortcut.selection_left", [this] {
auto selection = getSelection();
auto cursor = m_hexEditor.getCursorPosition();
if (cursor != selection.getStartAddress()) {
auto newCursor = cursor.value_or(selection.getEndAddress()) - m_hexEditor.getBytesPerCell();
setSelection(selection.getStartAddress(), newCursor);
m_hexEditor.setCursorPosition(newCursor);
} else {
auto newCursor = cursor.value_or(selection.getEndAddress()) - m_hexEditor.getBytesPerCell();
setSelection(newCursor, selection.getEndAddress());
m_hexEditor.setCursorPosition(newCursor);
}
m_hexEditor.jumpIfOffScreen();
});
ShortcutManager::addShortcut(this, SHIFT + Keys::Right, "hex.builtin.view.hex_editor.shortcut.selection_right", [this] {
auto selection = getSelection();
auto cursor = m_hexEditor.getCursorPosition();
if (cursor != selection.getStartAddress()) {
auto newCursor = cursor.value_or(selection.getEndAddress()) + m_hexEditor.getBytesPerCell();
setSelection(selection.getStartAddress(), newCursor);
m_hexEditor.setCursorPosition(newCursor);
} else {
auto newCursor = cursor.value_or(selection.getEndAddress()) + m_hexEditor.getBytesPerCell();
setSelection(newCursor, selection.getEndAddress());
m_hexEditor.setCursorPosition(newCursor);
}
m_hexEditor.jumpIfOffScreen();
});
ShortcutManager::addShortcut(this, SHIFT + Keys::PageUp, "hex.builtin.view.hex_editor.shortcut.selection_page_up", [this] {
auto selection = getSelection();
auto cursor = m_hexEditor.getCursorPosition().value_or(selection.getEndAddress());
if (cursor != selection.getStartAddress()) {
auto newCursor = std::max<u64>(cursor, m_hexEditor.getBytesPerRow()) - m_hexEditor.getBytesPerRow() * m_hexEditor.getVisibleRowCount();
setSelection(selection.getStartAddress(), newCursor);
m_hexEditor.setCursorPosition(newCursor);
} else {
auto newCursor = std::max<u64>(cursor, m_hexEditor.getBytesPerRow()) - m_hexEditor.getBytesPerRow() * m_hexEditor.getVisibleRowCount();
setSelection(newCursor, selection.getEndAddress());
m_hexEditor.setCursorPosition(newCursor);
}
m_hexEditor.jumpIfOffScreen();
});
ShortcutManager::addShortcut(this, SHIFT + Keys::PageDown, "hex.builtin.view.hex_editor.shortcut.selection_page_down", [this] {
auto selection = getSelection();
auto cursor = m_hexEditor.getCursorPosition().value_or(selection.getEndAddress());
if (cursor != selection.getStartAddress()) {
auto newCursor = cursor + (m_hexEditor.getBytesPerRow() * m_hexEditor.getVisibleRowCount());
setSelection(selection.getStartAddress(), newCursor);
m_hexEditor.setCursorPosition(newCursor);
} else {
auto newCursor = cursor + (m_hexEditor.getBytesPerRow() * m_hexEditor.getVisibleRowCount());
setSelection(newCursor, selection.getEndAddress());
m_hexEditor.setCursorPosition(newCursor);
}
m_hexEditor.jumpIfOffScreen();
});
}
void ViewHexEditor::registerEvents() {
RequestHexEditorSelectionChange::subscribe(this, [this](Region region) {
auto provider = ImHexApi::Provider::get();
if (region == Region::Invalid() || provider == nullptr) {
m_selectionStart->reset();
m_selectionEnd->reset();
EventRegionSelected::post(ImHexApi::HexEditor::ProviderRegion({ Region::Invalid(), nullptr }));
return;
}
auto page = provider->getPageOfAddress(region.getStartAddress());
if (!page.has_value())
return;
if (region.size != 0) {
provider->setCurrentPage(page.value());
this->setSelection(region);
this->jumpIfOffScreen();
}
});
EventProviderChanged::subscribe(this, [this](auto *oldProvider, auto *newProvider) {
if (oldProvider != nullptr) {
auto selection = m_hexEditor.getSelection();
if (selection != Region::Invalid()) {
m_selectionStart.get(oldProvider) = selection.getStartAddress();
m_selectionEnd.get(oldProvider) = selection.getEndAddress();
}
}
if (newProvider != nullptr) {
m_hexEditor.setSelectionUnchecked(m_selectionStart.get(newProvider), m_selectionEnd.get(newProvider));
} else {
m_hexEditor.setSelectionUnchecked(std::nullopt, std::nullopt);
}
if (isSelectionValid()) {
EventRegionSelected::post(ImHexApi::HexEditor::ProviderRegion{ this->getSelection(), newProvider });
}
});
EventProviderOpened::subscribe(this, [](auto *) {
ImHexApi::HexEditor::clearSelection();
});
EventHighlightingChanged::subscribe(this, [this]{
m_foregroundHighlights->clear();
m_backgroundHighlights->clear();
});
ProjectFile::registerPerProviderHandler({
.basePath = "custom_encoding.tbl",
.required = false,
.load = [this](prv::Provider *, const std::fs::path &basePath, const Tar &tar) {
if (!tar.contains(basePath))
return true;
auto content = tar.readString(basePath);
if (!content.empty())
m_hexEditor.setCustomEncoding(EncodingFile(hex::EncodingFile::Type::Thingy, content));
return true;
},
.store = [this](prv::Provider *, const std::fs::path &basePath, const Tar &tar) {
if (const auto &encoding = m_hexEditor.getCustomEncoding(); encoding.has_value()) {
auto content = encoding->getTableContent();
if (!content.empty())
tar.writeString(basePath, encoding->getTableContent());
}
return true;
}
});
m_hexEditor.setBytesPerRow(ContentRegistry::Settings::read<int>("hex.builtin.setting.hex_editor", "hex.builtin.setting.hex_editor.bytes_per_row", m_hexEditor.getBytesPerRow()));
ContentRegistry::Settings::onChange("hex.builtin.setting.hex_editor", "hex.builtin.setting.highlight_color", [this](const ContentRegistry::Settings::SettingsValue &value) {
m_hexEditor.setSelectionColor(value.get<int>(0x60C08080));
});
ContentRegistry::Settings::onChange("hex.builtin.setting.hex_editor", "hex.builtin.setting.hex_editor.sync_scrolling", [this](const ContentRegistry::Settings::SettingsValue &value) {
m_hexEditor.enableSyncScrolling(value.get<bool>(false));
});
ContentRegistry::Settings::onChange("hex.builtin.setting.hex_editor", "hex.builtin.setting.hex_editor.byte_padding", [this](const ContentRegistry::Settings::SettingsValue &value) {
m_hexEditor.setByteCellPadding(value.get<int>(0));
});
ContentRegistry::Settings::onChange("hex.builtin.setting.hex_editor", "hex.builtin.setting.hex_editor.char_padding", [this](const ContentRegistry::Settings::SettingsValue &value) {
m_hexEditor.setCharacterCellPadding(value.get<int>(0));
});
}
void ViewHexEditor::registerMenuItems() {
ContentRegistry::Interface::addMenuItemSeparator({ "hex.builtin.menu.file" }, 1300);
/* Save */
ContentRegistry::Interface::addMenuItem({ "hex.builtin.menu.file", "hex.builtin.view.hex_editor.menu.file.save" }, ICON_VS_SAVE, 1350,
CTRLCMD + Keys::S,
save,
[] {
auto provider = ImHexApi::Provider::get();
bool providerValid = ImHexApi::Provider::isValid();
return providerValid && provider->isWritable() && provider->isSavable() && provider->isDirty();
});
/* Save As */
ContentRegistry::Interface::addMenuItem({ "hex.builtin.menu.file", "hex.builtin.view.hex_editor.menu.file.save_as" }, ICON_VS_SAVE_AS, 1375,
CTRLCMD + SHIFT + Keys::S,
saveAs,
[] {
auto provider = ImHexApi::Provider::get();
bool providerValid = ImHexApi::Provider::isValid();
return providerValid && provider->isDumpable();
});
/* Load Encoding File */
ContentRegistry::Interface::addMenuItem({ "hex.builtin.menu.file", "hex.builtin.menu.file.import", "hex.builtin.menu.file.import.custom_encoding" }, "あ", 5050, Shortcut::None,
[this]{
const auto basePaths = paths::Encodings.read();
std::vector<std::fs::path> paths;
for (const auto &path : basePaths) {
std::error_code error;
for (const auto &entry : std::fs::recursive_directory_iterator(path, error)) {
if (!entry.is_regular_file()) continue;
paths.push_back(entry);
}
}
ui::PopupFileChooser::open(basePaths, paths, std::vector<hex::fs::ItemFilter>{ {"Thingy Table File", "tbl"} }, false,
[this](const auto &path) {
TaskManager::createTask("hex.builtin.task.loading_encoding_file"_lang, 0, [this, path](auto&) {
auto encoding = EncodingFile(EncodingFile::Type::Thingy, path);
ImHexApi::Provider::markDirty();
TaskManager::doLater([this, encoding = std::move(encoding)] mutable {
m_hexEditor.setCustomEncoding(std::move(encoding));
});
});
});
},
ImHexApi::Provider::isValid);
ContentRegistry::Interface::addMenuItemSeparator({ "hex.builtin.menu.file" }, 1500);
/* Search */
ContentRegistry::Interface::addMenuItem({ "hex.builtin.menu.file", "hex.builtin.view.hex_editor.menu.file.search" }, ICON_VS_SEARCH, 1550,
CTRLCMD + Keys::F,
[this] {
this->openPopup<PopupFind>(this);
},
ImHexApi::Provider::isValid);
/* Goto */
ContentRegistry::Interface::addMenuItem({ "hex.builtin.menu.file", "hex.builtin.view.hex_editor.menu.file.goto" }, ICON_VS_DEBUG_STEP_INTO, 1600,
CTRLCMD + Keys::G,
[this] {
this->openPopup<PopupGoto>();
},
ImHexApi::Provider::isValid);
ContentRegistry::Interface::addMenuItemSeparator({ "hex.builtin.menu.edit" }, 1100);
/* Copy */
ContentRegistry::Interface::addMenuItem({ "hex.builtin.menu.edit", "hex.builtin.view.hex_editor.menu.edit.copy" }, ICON_VS_COPY, 1150,
CurrentView + CTRLCMD + Keys::C,
[] {
auto selection = ImHexApi::HexEditor::getSelection();
if (selection.has_value() && selection != Region::Invalid())
copyBytes(*selection);
},
ImHexApi::HexEditor::isSelectionValid,
this);
ContentRegistry::Interface::addMenuItemSubMenu({ "hex.builtin.menu.edit", "hex.builtin.view.hex_editor.menu.edit.copy_as" }, ICON_VS_PREVIEW, 1190, []{}, ImHexApi::HexEditor::isSelectionValid);
/* Copy As */
ContentRegistry::Interface::addMenuItem({ "hex.builtin.menu.edit", "hex.builtin.view.hex_editor.menu.edit.copy_as", "hex.builtin.view.hex_editor.copy.ascii" }, ICON_VS_SYMBOL_TEXT, 1200,
CurrentView + CTRLCMD + SHIFT + Keys::C,
[] {
auto selection = ImHexApi::HexEditor::getSelection();
if (selection.has_value() && selection != Region::Invalid())
copyString(*selection);
},
ImHexApi::HexEditor::isSelectionValid,
this);
/* Copy address */
ContentRegistry::Interface::addMenuItem({ "hex.builtin.menu.edit", "hex.builtin.view.hex_editor.menu.edit.copy_as", "hex.builtin.view.hex_editor.copy.address" }, ICON_VS_LOCATION, 1250,
Shortcut::None,
[] {
auto selection = ImHexApi::HexEditor::getSelection();
if (selection.has_value() && selection != Region::Invalid())
ImGui::SetClipboardText(hex::format("0x{:08X}", selection->getStartAddress()).c_str());
},
ImHexApi::HexEditor::isSelectionValid);
/* Copy custom encoding */
ContentRegistry::Interface::addMenuItem({ "hex.builtin.menu.edit", "hex.builtin.view.hex_editor.menu.edit.copy_as", "hex.builtin.view.hex_editor.copy.custom_encoding" }, "あ", 1300,
Shortcut::None,
[this] {
auto selection = ImHexApi::HexEditor::getSelection();
auto customEncoding = m_hexEditor.getCustomEncoding();
if (customEncoding.has_value() && selection.has_value() && selection != Region::Invalid())
copyCustomEncoding(*customEncoding, *selection);
},
[this] {
return ImHexApi::HexEditor::isSelectionValid() && m_hexEditor.getCustomEncoding().has_value();
});
ContentRegistry::Interface::addMenuItemSeparator({ "hex.builtin.menu.edit", "hex.builtin.view.hex_editor.menu.edit.copy_as" }, 1350);
/* Copy as... */
ContentRegistry::Interface::addMenuItemSubMenu({ "hex.builtin.menu.edit", "hex.builtin.view.hex_editor.menu.edit.copy_as" }, ICON_VS_FILE_CODE, 1400, []{
auto selection = ImHexApi::HexEditor::getSelection();
auto provider = ImHexApi::Provider::get();
bool enabled = ImHexApi::HexEditor::isSelectionValid();
for (const auto &[unlocalizedName, callback] : ContentRegistry::DataFormatter::impl::getExportMenuEntries()) {
if (ImGui::MenuItem(Lang(unlocalizedName), nullptr, false, enabled)) {
ImGui::SetClipboardText(
callback(
provider,
selection->getStartAddress(),
selection->size
).c_str()
);
}
}
},
[] {
return ImHexApi::Provider::isValid() && ImHexApi::HexEditor::isSelectionValid();
});
/* Paste */
ContentRegistry::Interface::addMenuItem({ "hex.builtin.menu.edit", "hex.builtin.view.hex_editor.menu.edit.paste" }, ICON_VS_OUTPUT, 1450, CurrentView + CTRLCMD + Keys::V,
[] {
pasteBytes(ImHexApi::HexEditor::getSelection().value_or( ImHexApi::HexEditor::ProviderRegion(Region { 0, 0 }, ImHexApi::Provider::get())), true);
},
ImHexApi::HexEditor::isSelectionValid,
this);
/* Paste All */
ContentRegistry::Interface::addMenuItem({ "hex.builtin.menu.edit", "hex.builtin.view.hex_editor.menu.edit.paste_all" }, ICON_VS_CLIPPY, 1500, CurrentView + CTRLCMD + SHIFT + Keys::V,
[] {
pasteBytes(ImHexApi::HexEditor::getSelection().value_or( ImHexApi::HexEditor::ProviderRegion(Region { 0, 0 }, ImHexApi::Provider::get())), false);
},
ImHexApi::HexEditor::isSelectionValid,
this);
/* Select */
ContentRegistry::Interface::addMenuItem({ "hex.builtin.menu.edit", "hex.builtin.view.hex_editor.menu.edit.select" }, ICON_VS_SELECTION, 1525,
CTRLCMD + SHIFT + Keys::A,
[this] {
auto selection = ImHexApi::HexEditor::getSelection().value_or(ImHexApi::HexEditor::ProviderRegion{ { 0, 1 }, nullptr });
this->openPopup<PopupSelect>(selection.getStartAddress(), selection.getSize());
},
ImHexApi::Provider::isValid);
/* Select All */
ContentRegistry::Interface::addMenuItem({ "hex.builtin.menu.edit", "hex.builtin.view.hex_editor.menu.edit.select_all" }, ICON_VS_LIST_FLAT, 1550, CurrentView + CTRLCMD + Keys::A,
[] {
auto provider = ImHexApi::Provider::get();
ImHexApi::HexEditor::setSelection(provider->getBaseAddress(), provider->getActualSize());
},
ImHexApi::HexEditor::isSelectionValid,
this);
ContentRegistry::Interface::addMenuItemSeparator({ "hex.builtin.menu.edit" }, 1600);
/* Set Base Address */
ContentRegistry::Interface::addMenuItem({ "hex.builtin.menu.edit", "hex.builtin.view.hex_editor.menu.edit.set_base" }, ICON_VS_LOCATION, 1650, Shortcut::None,
[this] {
auto provider = ImHexApi::Provider::get();
this->openPopup<PopupBaseAddress>(provider->getBaseAddress());
},
[] { return ImHexApi::Provider::isValid() && ImHexApi::Provider::get()->isReadable(); });
/* Resize */
ContentRegistry::Interface::addMenuItem({ "hex.builtin.menu.edit", "hex.builtin.view.hex_editor.menu.edit.resize" }, ICON_VS_ARROW_BOTH, 1700, Shortcut::None,
[this] {
auto provider = ImHexApi::Provider::get();
this->openPopup<PopupResize>(provider->getActualSize());
},
[] { return ImHexApi::Provider::isValid() && ImHexApi::Provider::get()->isResizable(); });
/* Insert */
ContentRegistry::Interface::addMenuItem({ "hex.builtin.menu.edit", "hex.builtin.view.hex_editor.menu.edit.insert" }, ICON_VS_INSERT, 1750, Shortcut::None,
[this] {
auto selection = ImHexApi::HexEditor::getSelection();
this->openPopup<PopupInsert>(selection->getStartAddress(), 0x00);
},
[] { return ImHexApi::HexEditor::isSelectionValid() && ImHexApi::Provider::isValid() && ImHexApi::Provider::get()->isResizable(); });
/* Remove */
ContentRegistry::Interface::addMenuItem({ "hex.builtin.menu.edit", "hex.builtin.view.hex_editor.menu.edit.remove" }, ICON_VS_CLEAR_ALL, 1800, Shortcut::None,
[this] {
auto selection = ImHexApi::HexEditor::getSelection();
this->openPopup<PopupRemove>(selection->getStartAddress(), selection->getSize());
},
[] { return ImHexApi::HexEditor::isSelectionValid() && ImHexApi::Provider::isValid() && ImHexApi::Provider::get()->isResizable(); });
/* Fill */
ContentRegistry::Interface::addMenuItem({ "hex.builtin.menu.edit", "hex.builtin.view.hex_editor.menu.edit.fill" }, ICON_VS_PAINTCAN, 1810, Shortcut::None,
[this] {
auto selection = ImHexApi::HexEditor::getSelection();
this->openPopup<PopupFill>(selection->getStartAddress(), selection->getSize());
},
[] { return ImHexApi::HexEditor::isSelectionValid() && ImHexApi::Provider::isValid() && ImHexApi::Provider::get()->isWritable(); });
/* Toggle Overwrite/Insert mode */
ContentRegistry::Interface::addMenuItem({ "hex.builtin.menu.edit", "hex.builtin.view.hex_editor.menu.edit.insert_mode" }, ICON_VS_PENCIL, 1820, Shortcut::None,
[this] {
if (m_hexEditor.getMode() == ui::HexEditor::Mode::Insert)
m_hexEditor.setMode(ui::HexEditor::Mode::Overwrite);
else
m_hexEditor.setMode(ui::HexEditor::Mode::Insert);
},
[] {
return ImHexApi::HexEditor::isSelectionValid() &&
ImHexApi::Provider::isValid() &&
ImHexApi::Provider::get()->isWritable() &&
ImHexApi::Provider::get()->isResizable();
},
[this] {
return m_hexEditor.getMode() == ui::HexEditor::Mode::Insert;
});
/* Jump to */
ContentRegistry::Interface::addMenuItemSubMenu({ "hex.builtin.menu.edit", "hex.builtin.view.hex_editor.menu.edit.jump_to" }, ICON_VS_DEBUG_STEP_OUT, 1850,
[] {
auto provider = ImHexApi::Provider::get();
auto selection = ImHexApi::HexEditor::getSelection();
u64 value = 0;
provider->read(selection->getStartAddress(), &value, selection->getSize());
auto littleEndianValue = hex::changeEndianness(value, selection->size, std::endian::little);
auto bigEndianValue = hex::changeEndianness(value, selection->size, std::endian::big);
auto canJumpTo = [provider](u64 value) {
return (value >= provider->getBaseAddress()) && (value < (provider->getBaseAddress() + provider->getActualSize()));
};
if (ImGui::MenuItem(hex::format("0x{:08X}", littleEndianValue).c_str(), "hex.ui.common.little_endian"_lang, false, canJumpTo(littleEndianValue))) {
ImHexApi::HexEditor::setSelection(littleEndianValue, 1);
}
if (ImGui::MenuItem(hex::format("0x{:08X}", bigEndianValue).c_str(), "hex.ui.common.big_endian"_lang, false, canJumpTo(bigEndianValue))) {
ImHexApi::HexEditor::setSelection(bigEndianValue, 1);
}
if (ImGui::MenuItem("hex.builtin.view.hex_editor.menu.edit.jump_to.curr_pattern"_lang, "", false, selection.has_value() && ContentRegistry::PatternLanguage::getRuntime().getCreatedPatternCount() > 0)) {
auto patterns = ContentRegistry::PatternLanguage::getRuntime().getPatternsAtAddress(selection->getStartAddress());
if (!patterns.empty())
RequestJumpToPattern::post(patterns.front());
}
},
[] { return ImHexApi::Provider::isValid() && ImHexApi::HexEditor::isSelectionValid() && ImHexApi::HexEditor::getSelection()->getSize() <= sizeof(u64); });
/* Set Page Size */
ContentRegistry::Interface::addMenuItem({ "hex.builtin.menu.edit", "hex.builtin.view.hex_editor.menu.edit.set_page_size" }, ICON_VS_BROWSER, 1860, Shortcut::None,
[this] {
auto provider = ImHexApi::Provider::get();
this->openPopup<PopupPageSize>(provider->getPageSize());
},
[] { return ImHexApi::Provider::isValid() && ImHexApi::Provider::get()->isReadable(); });
ContentRegistry::Interface::addMenuItemSeparator({ "hex.builtin.menu.edit" }, 1900);
/* Open in new provider */
ContentRegistry::Interface::addMenuItem({ "hex.builtin.menu.edit", "hex.builtin.view.hex_editor.menu.edit.open_in_new_provider" }, ICON_VS_GO_TO_FILE, 1950, Shortcut::None,
[] {
auto selection = ImHexApi::HexEditor::getSelection();
auto newProvider = ImHexApi::Provider::createProvider("hex.builtin.provider.view", true);
if (auto *viewProvider = dynamic_cast<ViewProvider*>(newProvider); viewProvider != nullptr) {
viewProvider->setProvider(selection->getStartAddress(), selection->getSize(), selection->getProvider());
if (viewProvider->open())
EventProviderOpened::post(viewProvider);
}
},
[] { return ImHexApi::HexEditor::isSelectionValid() && ImHexApi::Provider::isValid(); });
}
}
| 64,990
|
C++
|
.cpp
| 1,072
| 40.339552
| 254
| 0.516943
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
240
|
view_patches.cpp
|
WerWolv_ImHex/plugins/builtin/source/content/views/view_patches.cpp
|
#include "content/views/view_patches.hpp"
#include <hex/providers/provider.hpp>
#include <hex/api/project_file_manager.hpp>
#include <nlohmann/json.hpp>
#include <content/providers/undo_operations/operation_write.hpp>
#include <content/providers/undo_operations/operation_insert.hpp>
#include <content/providers/undo_operations/operation_remove.hpp>
#include <ranges>
#include <string>
using namespace std::literals::string_literals;
namespace hex::plugin::builtin {
ViewPatches::ViewPatches() : View::Window("hex.builtin.view.patches.name", ICON_VS_GIT_PULL_REQUEST_NEW_CHANGES) {
ProjectFile::registerPerProviderHandler({
.basePath = "patches.json",
.required = false,
.load = [](prv::Provider *provider, const std::fs::path &basePath, const Tar &tar) {
auto json = nlohmann::json::parse(tar.readString(basePath));
auto patches = json.at("patches").get<std::map<u64, u8>>();
for (const auto &[address, value] : patches) {
provider->write(address, &value, sizeof(value));
}
provider->getUndoStack().groupOperations(patches.size(), "hex.builtin.undo_operation.patches");
return true;
},
.store = [](prv::Provider *, const std::fs::path &, Tar &) {
return true;
}
});
MovePerProviderData::subscribe(this, [this](prv::Provider *from, prv::Provider *to) {
m_savedOperations.get(from) = 0;
m_savedOperations.get(to) = 0;
});
ImHexApi::HexEditor::addForegroundHighlightingProvider([this](u64 offset, const u8* buffer, size_t, bool) -> std::optional<color_t> {
hex::unused(buffer);
if (!ImHexApi::Provider::isValid())
return std::nullopt;
auto provider = ImHexApi::Provider::get();
if (!provider->isSavable())
return std::nullopt;
offset -= provider->getBaseAddress();
const auto &undoStack = provider->getUndoStack();
const auto stackSize = undoStack.getAppliedOperations().size();
const auto savedStackSize = m_savedOperations.get(provider);
if (stackSize == savedStackSize) {
// Do nothing
} else if (stackSize > savedStackSize) {
for (const auto &operation : undoStack.getAppliedOperations() | std::views::drop(savedStackSize)) {
if (!operation->shouldHighlight())
continue;
if (operation->getRegion().overlaps(Region { offset, 1}))
return ImGuiExt::GetCustomColorU32(ImGuiCustomCol_Patches);
}
} else {
for (const auto &operation : undoStack.getUndoneOperations() | std::views::reverse | std::views::take(savedStackSize - stackSize)) {
if (!operation->shouldHighlight())
continue;
if (operation->getRegion().overlaps(Region { offset, 1}))
return ImGuiExt::GetCustomColorU32(ImGuiCustomCol_Patches);
}
}
return std::nullopt;
});
EventProviderSaved::subscribe([this](prv::Provider *provider) {
m_savedOperations.get(provider) = provider->getUndoStack().getAppliedOperations().size();
EventHighlightingChanged::post();
});
EventProviderDataModified::subscribe(this, [](prv::Provider *provider, u64 offset, u64 size, const u8 *data) {
if (size == 0)
return;
offset -= provider->getBaseAddress();
std::vector<u8> oldData(size, 0x00);
provider->read(offset, oldData.data(), size);
provider->getUndoStack().add<undo::OperationWrite>(offset, size, oldData.data(), data);
});
EventProviderDataInserted::subscribe(this, [](prv::Provider *provider, u64 offset, u64 size) {
offset -= provider->getBaseAddress();
provider->getUndoStack().add<undo::OperationInsert>(offset, size);
});
EventProviderDataRemoved::subscribe(this, [](prv::Provider *provider, u64 offset, u64 size) {
offset -= provider->getBaseAddress();
provider->getUndoStack().add<undo::OperationRemove>(offset, size);
});
}
ViewPatches::~ViewPatches() {
MovePerProviderData::unsubscribe(this);
EventProviderSaved::unsubscribe(this);
EventProviderDataModified::unsubscribe(this);
EventProviderDataInserted::unsubscribe(this);
EventProviderDataRemoved::unsubscribe(this);
}
void ViewPatches::drawContent() {
auto provider = ImHexApi::Provider::get();
if (ImHexApi::Provider::isValid() && provider->isReadable()) {
if (ImGui::BeginTable("##patchesTable", 3, ImGuiTableFlags_Borders | ImGuiTableFlags_Resizable | ImGuiTableFlags_Sortable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_RowBg | ImGuiTableFlags_ScrollY)) {
ImGui::TableSetupScrollFreeze(0, 1);
ImGui::TableSetupColumn("##PatchID", ImGuiTableColumnFlags_WidthFixed | ImGuiTableColumnFlags_NoReorder | ImGuiTableColumnFlags_NoResize);
ImGui::TableSetupColumn("hex.builtin.view.patches.offset"_lang, ImGuiTableColumnFlags_WidthFixed);
ImGui::TableSetupColumn("hex.builtin.view.patches.patch"_lang, ImGuiTableColumnFlags_WidthStretch);
ImGui::TableHeadersRow();
const auto &undoRedoStack = provider->getUndoStack();
std::vector<prv::undo::Operation*> operations;
for (const auto &operation : undoRedoStack.getUndoneOperations())
operations.push_back(operation.get());
for (const auto &operation : undoRedoStack.getAppliedOperations() | std::views::reverse)
operations.push_back(operation.get());
u32 index = 0;
ImGuiListClipper clipper;
clipper.Begin(operations.size());
while (clipper.Step()) {
auto iter = operations.begin();
for (auto i = 0; i < clipper.DisplayStart; i++)
++iter;
auto undoneOperationsCount = undoRedoStack.getUndoneOperations().size();
for (auto i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) {
const auto &operation = *iter;
const auto [address, size] = operation->getRegion();
ImGui::TableNextRow();
ImGui::TableNextColumn();
ImGui::BeginDisabled(size_t(i) < undoneOperationsCount);
if (ImGui::Selectable(hex::format("{} {}", index == undoneOperationsCount ? ICON_VS_ARROW_SMALL_RIGHT : " ", index).c_str(), false, ImGuiSelectableFlags_SpanAllColumns)) {
ImHexApi::HexEditor::setSelection(address, size);
}
if (ImGui::IsItemHovered()) {
const auto content = operation->formatContent();
if (!content.empty()) {
if (ImGui::BeginTooltip()) {
if (ImGui::BeginTable("##content_table", 1, ImGuiTableFlags_RowBg | ImGuiTableFlags_Borders)) {
for (const auto &entry : content) {
ImGui::TableNextRow();
ImGui::TableNextColumn();
ImGuiExt::TextFormatted("{}", entry);
}
ImGui::EndTable();
}
ImGui::EndTooltip();
}
}
}
if (ImGui::IsMouseReleased(1) && ImGui::IsItemHovered()) {
ImGui::OpenPopup("PatchContextMenu");
m_selectedPatch = address;
}
ImGui::TableNextColumn();
ImGuiExt::TextFormatted("0x{0:08X}", address);
ImGui::TableNextColumn();
ImGuiExt::TextFormatted("{}", operation->format());
index += 1;
++iter;
ImGui::EndDisabled();
}
}
ImGui::EndTable();
}
}
}
void ViewPatches::drawAlwaysVisibleContent() {
if (auto provider = ImHexApi::Provider::get(); provider != nullptr) {
const auto &operations = provider->getUndoStack().getAppliedOperations();
if (m_numOperations.get(provider) != operations.size()) {
m_numOperations.get(provider) = operations.size();
EventHighlightingChanged::post();
}
}
}
}
| 9,256
|
C++
|
.cpp
| 165
| 39.236364
| 217
| 0.549115
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
241
|
view_tools.cpp
|
WerWolv_ImHex/plugins/builtin/source/content/views/view_tools.cpp
|
#include "content/views/view_tools.hpp"
#include <imgui_internal.h>
#include <hex/api/content_registry.hpp>
#include <hex/api/layout_manager.hpp>
#include <fonts/codicons_font.h>
namespace hex::plugin::builtin {
ViewTools::ViewTools() : View::Window("hex.builtin.view.tools.name", ICON_VS_TOOLS) {
m_dragStartIterator = ContentRegistry::Tools::impl::getEntries().end();
LayoutManager::registerLoadCallback([this](std::string_view line) {
auto parts = wolv::util::splitString(std::string(line), "=");
if (parts.size() != 2)
return;
m_detachedTools[parts[0]] = parts[1] == "1";
});
LayoutManager::registerStoreCallback([this](ImGuiTextBuffer *buffer) {
for (auto &[unlocalizedName, function] : ContentRegistry::Tools::impl::getEntries()) {
auto detached = m_detachedTools[unlocalizedName];
buffer->appendf("%s=%d\n", unlocalizedName.get().c_str(), detached);
}
});
}
void ViewTools::drawContent() {
auto &tools = ContentRegistry::Tools::impl::getEntries();
// Draw all tools
for (auto iter = tools.begin(); iter != tools.end(); ++iter) {
auto &[unlocalizedName, function] = *iter;
// If the tool has been detached from the main window, don't draw it here anymore
if (m_detachedTools[unlocalizedName]) continue;
// Draw the tool
if (ImGui::CollapsingHeader(Lang(unlocalizedName))) {
function();
ImGui::NewLine();
} else {
// Handle dragging the tool out of the main window
// If the user clicks on the header, start dragging the tool remember the iterator
if (ImGui::IsMouseClicked(0) && ImGui::IsItemActivated() && m_dragStartIterator == tools.end())
m_dragStartIterator = iter;
// If the user released the mouse button, stop dragging the tool
if (!ImGui::IsMouseDown(0))
m_dragStartIterator = tools.end();
// Detach the tool if the user dragged it out of the main window
if (!ImGui::IsItemHovered() && m_dragStartIterator == iter) {
m_detachedTools[unlocalizedName] = true;
}
}
}
}
void ViewTools::drawAlwaysVisibleContent() {
// Make sure the tool windows never get drawn over the welcome screen
if (!ImHexApi::Provider::isValid())
return;
auto &tools = ContentRegistry::Tools::impl::getEntries();
for (auto iter = tools.begin(); iter != tools.end(); ++iter) {
auto &[unlocalizedName, function] = *iter;
// If the tool is still attached to the main window, don't draw it here
if (!m_detachedTools[unlocalizedName]) continue;
// Load the window height that is dependent on the tool content
const auto windowName = View::toWindowName(unlocalizedName);
const auto height = m_windowHeights[ImGui::FindWindowByName(windowName.c_str())];
if (height > 0)
ImGui::SetNextWindowSizeConstraints(ImVec2(400_scaled, height), ImVec2(FLT_MAX, height));
// Create a new window for the tool
if (ImGui::Begin(windowName.c_str(), &m_detachedTools[unlocalizedName], ImGuiWindowFlags_NoCollapse)) {
// Draw the tool content
function();
// Handle the first frame after the tool has been detached
if (ImGui::IsWindowAppearing() && m_dragStartIterator == iter) {
m_dragStartIterator = tools.end();
// Attach the newly created window to the cursor, so it gets dragged around
GImGui->MovingWindow = ImGui::GetCurrentWindowRead();
GImGui->ActiveId = GImGui->MovingWindow->MoveId;
}
const auto window = ImGui::GetCurrentWindowRead();
m_windowHeights[ImGui::GetCurrentWindowRead()] = ImGui::CalcWindowNextAutoFitSize(window).y;
}
ImGui::End();
}
}
}
| 4,245
|
C++
|
.cpp
| 79
| 41.037975
| 115
| 0.592226
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
242
|
view_pattern_data.cpp
|
WerWolv_ImHex/plugins/builtin/source/content/views/view_pattern_data.cpp
|
#include <content/views/view_pattern_data.hpp>
#include <hex/api/content_registry.hpp>
#include <hex/providers/memory_provider.hpp>
#include <fonts/codicons_font.h>
#include <pl/patterns/pattern.hpp>
#include <wolv/utils/lock.hpp>
namespace hex::plugin::builtin {
ViewPatternData::ViewPatternData() : View::Window("hex.builtin.view.pattern_data.name", ICON_VS_DATABASE) {
// Handle tree style setting changes
ContentRegistry::Settings::onChange("hex.builtin.setting.interface", "hex.builtin.setting.interface.pattern_tree_style", [this](const ContentRegistry::Settings::SettingsValue &value) {
m_treeStyle = ui::PatternDrawer::TreeStyle(value.get<int>(0));
for (auto &drawer : m_patternDrawer.all())
drawer->setTreeStyle(m_treeStyle);
});
ContentRegistry::Settings::onChange("hex.builtin.setting.interface", "hex.builtin.setting.interface.pattern_data_row_bg", [this](const ContentRegistry::Settings::SettingsValue &value) {
m_rowColoring = bool(value.get<int>(false));
for (auto &drawer : m_patternDrawer.all())
drawer->enableRowColoring(m_rowColoring);
});
EventPatternEvaluating::subscribe(this, [this]{
(*m_patternDrawer)->reset();
});
EventPatternExecuted::subscribe(this, [this](auto){
(*m_patternDrawer)->reset();
});
RequestJumpToPattern::subscribe(this, [this](const pl::ptrn::Pattern *pattern) {
(*m_patternDrawer)->jumpToPattern(pattern);
});
ImHexApi::HexEditor::addHoverHighlightProvider([this](const prv::Provider *, u64, size_t) -> std::set<Region> {
return { m_hoveredPatternRegion };
});
m_patternDrawer.setOnCreateCallback([this](const prv::Provider *provider, auto &drawer) {
drawer = std::make_unique<ui::PatternDrawer>();
drawer->setSelectionCallback([](const pl::ptrn::Pattern *pattern) {
ImHexApi::HexEditor::setSelection(Region { pattern->getOffset(), pattern->getSize() });
RequestPatternEditorSelectionChange::post(pattern->getLine(), 0);
});
drawer->setHoverCallback([this](const pl::ptrn::Pattern *pattern) {
if (pattern == nullptr)
m_hoveredPatternRegion = Region::Invalid();
else
m_hoveredPatternRegion = { pattern->getOffset(), pattern->getSize() };
});
drawer->setTreeStyle(m_treeStyle);
drawer->enableRowColoring(m_rowColoring);
drawer->enablePatternEditing(provider->isWritable());
});
}
ViewPatternData::~ViewPatternData() {
EventPatternEvaluating::unsubscribe(this);
EventPatternExecuted::unsubscribe(this);
}
void ViewPatternData::drawContent() {
// Draw the pattern tree if the provider is valid
if (ImHexApi::Provider::isValid()) {
// Make sure the runtime has finished evaluating and produced valid patterns
auto &runtime = ContentRegistry::PatternLanguage::getRuntime();
const auto height = std::max(ImGui::GetContentRegionAvail().y - ImGui::GetTextLineHeightWithSpacing() - ImGui::GetStyle().FramePadding.y * 2, ImGui::GetTextLineHeightWithSpacing() * 5);
if (*m_patternDrawer != nullptr) {
if (!runtime.arePatternsValid()) {
(*m_patternDrawer)->draw({ }, nullptr, height);
} else {
// If the runtime has finished evaluating, draw the patterns
if (TRY_LOCK(ContentRegistry::PatternLanguage::getRuntimeLock())) {
(*m_patternDrawer)->draw(runtime.getPatterns(), &runtime, height);
}
}
}
}
}
}
| 3,876
|
C++
|
.cpp
| 71
| 43.126761
| 197
| 0.623514
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
243
|
view_pattern_editor.cpp
|
WerWolv_ImHex/plugins/builtin/source/content/views/view_pattern_editor.cpp
|
#include "content/views/view_pattern_editor.hpp"
#include "fonts/blendericons_font.h"
#include <hex/api/content_registry.hpp>
#include <hex/api/project_file_manager.hpp>
#include <pl/patterns/pattern.hpp>
#include <pl/core/preprocessor.hpp>
#include <pl/core/parser.hpp>
#include <pl/core/ast/ast_node_variable_decl.hpp>
#include <pl/core/ast/ast_node_builtin_type.hpp>
#include <hex/helpers/fs.hpp>
#include <hex/helpers/utils.hpp>
#include <hex/helpers/magic.hpp>
#include <hex/helpers/binary_pattern.hpp>
#include <hex/helpers/default_paths.hpp>
#include <hex/providers/memory_provider.hpp>
#include <hex/helpers/fmt.hpp>
#include <fmt/chrono.h>
#include <popups/popup_question.hpp>
#include <toasts/toast_notification.hpp>
#include <chrono>
#include <wolv/io/file.hpp>
#include <wolv/io/fs.hpp>
#include <wolv/utils/guards.hpp>
#include <wolv/utils/lock.hpp>
#include <content/global_actions.hpp>
namespace hex::plugin::builtin {
using namespace hex::literals;
static const TextEditor::LanguageDefinition &PatternLanguage() {
static bool initialized = false;
static TextEditor::LanguageDefinition langDef;
if (!initialized) {
constexpr static std::array keywords = {
"using", "struct", "union", "enum", "bitfield", "be", "le", "if", "else", "match", "false", "true", "this", "parent", "addressof", "sizeof", "typenameof", "$", "while", "for", "fn", "return", "break", "continue", "namespace", "in", "out", "ref", "null", "const", "unsigned", "signed", "try", "catch", "import", "as"
};
for (auto &k : keywords)
langDef.mKeywords.insert(k);
constexpr static std::array builtInTypes = {
"u8", "u16", "u24", "u32", "u48", "u64", "u96", "u128", "s8", "s16", "s24", "s32", "s48", "s64", "s96", "s128", "float", "double", "char", "char16", "bool", "padding", "str", "auto"
};
for (const auto name : builtInTypes) {
TextEditor::Identifier id;
id.mDeclaration = "";
langDef.mIdentifiers.insert(std::make_pair(std::string(name), id));
}
langDef.mTokenize = [](const char *inBegin, const char *inEnd, const char *&outBegin, const char *&outEnd, TextEditor::PaletteIndex &paletteIndex) -> bool {
paletteIndex = TextEditor::PaletteIndex::Max;
while (inBegin < inEnd && isascii(*inBegin) && std::isblank(*inBegin))
inBegin++;
if (inBegin == inEnd) {
outBegin = inEnd;
outEnd = inEnd;
paletteIndex = TextEditor::PaletteIndex::Default;
} else if (TokenizeCStyleIdentifier(inBegin, inEnd, outBegin, outEnd)) {
paletteIndex = TextEditor::PaletteIndex::Identifier;
} else if (TokenizeCStyleNumber(inBegin, inEnd, outBegin, outEnd)) {
paletteIndex = TextEditor::PaletteIndex::Number;
} else if (TokenizeCStyleCharacterLiteral(inBegin, inEnd, outBegin, outEnd)) {
paletteIndex = TextEditor::PaletteIndex::CharLiteral;
} else if (TokenizeCStyleString(inBegin, inEnd, outBegin, outEnd)) {
paletteIndex = TextEditor::PaletteIndex::String;
}
return paletteIndex != TextEditor::PaletteIndex::Max;
};
langDef.mCommentStart = "/*";
langDef.mCommentEnd = "*/";
langDef.mSingleLineComment = "//";
langDef.mCaseSensitive = true;
langDef.mAutoIndentation = true;
langDef.mPreprocChar = '#';
langDef.mGlobalDocComment = "/*!";
langDef.mDocComment = "/**";
langDef.mName = "Pattern Language";
initialized = true;
}
return langDef;
}
static const TextEditor::LanguageDefinition &ConsoleLog() {
static bool initialized = false;
static TextEditor::LanguageDefinition langDef;
if (!initialized) {
langDef.mTokenize = [](const char *inBegin, const char *inEnd, const char *&outBegin, const char *&outEnd, TextEditor::PaletteIndex &paletteIndex) -> bool {
if (std::string_view(inBegin).starts_with("D: "))
paletteIndex = TextEditor::PaletteIndex::Comment;
else if (std::string_view(inBegin).starts_with("I: "))
paletteIndex = TextEditor::PaletteIndex::Default;
else if (std::string_view(inBegin).starts_with("W: "))
paletteIndex = TextEditor::PaletteIndex::Preprocessor;
else if (std::string_view(inBegin).starts_with("E: "))
paletteIndex = TextEditor::PaletteIndex::ErrorMarker;
else
paletteIndex = TextEditor::PaletteIndex::Max;
outBegin = inBegin;
outEnd = inEnd;
return true;
};
langDef.mName = "Console Log";
langDef.mCaseSensitive = false;
langDef.mAutoIndentation = false;
langDef.mCommentStart = "";
langDef.mCommentEnd = "";
langDef.mSingleLineComment = "";
langDef.mDocComment = "";
langDef.mGlobalDocComment = "";
initialized = true;
}
return langDef;
}
int levelId;
static void loadPatternAsMemoryProvider(const ViewPatternEditor::VirtualFile *file) {
ImHexApi::Provider::add<prv::MemoryProvider>(file->data, wolv::util::toUTF8String(file->path.filename()));
}
static void drawVirtualFileTree(const std::vector<const ViewPatternEditor::VirtualFile*> &virtualFiles, u32 level = 0) {
ImGui::PushID(level + 1);
ON_SCOPE_EXIT { ImGui::PopID(); };
std::map<std::string, std::vector<const ViewPatternEditor::VirtualFile*>> currFolderEntries;
for (const auto &file : virtualFiles) {
const auto &path = file->path;
auto currSegment = wolv::io::fs::toNormalizedPathString(*std::next(path.begin(), level));
if (std::distance(path.begin(), path.end()) == ptrdiff_t(level + 1)) {
ImGui::TableNextRow();
ImGui::TableNextColumn();
ImGui::TextUnformatted(ICON_VS_FILE);
ImGui::PushID(levelId);
ImGui::SameLine();
ImGui::TreeNodeEx(currSegment.c_str(), ImGuiTreeNodeFlags_SpanFullWidth | ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen);
if (ImGui::IsMouseDown(ImGuiMouseButton_Right) && ImGui::IsItemHovered() && !ImGui::IsMouseDragging(ImGuiMouseButton_Right)) {
ImGui::OpenPopup("##virtual_files_context_menu");
}
if (ImGui::BeginPopup("##virtual_files_context_menu")) {
if (ImGui::MenuItem("hex.builtin.view.hex_editor.menu.edit.open_in_new_provider"_lang, nullptr, false)) {
loadPatternAsMemoryProvider(file);
}
ImGui::EndPopup();
}
if (ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left) && ImGui::IsItemHovered()) {
loadPatternAsMemoryProvider(file);
}
ImGui::PopID();
levelId +=1;
continue;
}
currFolderEntries[currSegment].emplace_back(file);
}
int id = 1;
for (const auto &[segment, entries] : currFolderEntries) {
ImGui::TableNextRow();
ImGui::TableNextColumn();
if (level == 0) {
ImGui::TextUnformatted(ICON_VS_DATABASE);
} else {
ImGui::TextUnformatted(ICON_VS_FOLDER);
}
ImGui::PushID(id);
ImGui::SameLine();
if (ImGui::TreeNodeEx(segment.c_str(), ImGuiTreeNodeFlags_SpanFullWidth)) {
drawVirtualFileTree(entries, level + 1);
ImGui::TreePop();
}
ImGui::PopID();
id += 1;
}
}
ViewPatternEditor::ViewPatternEditor() : View::Window("hex.builtin.view.pattern_editor.name", ICON_VS_SYMBOL_NAMESPACE) {
m_editorRuntime = std::make_unique<pl::PatternLanguage>();
ContentRegistry::PatternLanguage::configureRuntime(*m_editorRuntime, nullptr);
m_textEditor.SetLanguageDefinition(PatternLanguage());
m_textEditor.SetShowWhitespaces(false);
m_consoleEditor.SetLanguageDefinition(ConsoleLog());
m_consoleEditor.SetShowWhitespaces(false);
m_consoleEditor.SetReadOnly(true);
m_consoleEditor.SetShowCursor(false);
m_consoleEditor.SetShowLineNumbers(false);
this->registerEvents();
this->registerMenuItems();
this->registerHandlers();
}
ViewPatternEditor::~ViewPatternEditor() {
RequestPatternEditorSelectionChange::unsubscribe(this);
RequestSetPatternLanguageCode::unsubscribe(this);
RequestRunPatternCode::unsubscribe(this);
EventFileLoaded::unsubscribe(this);
EventProviderChanged::unsubscribe(this);
EventProviderClosed::unsubscribe(this);
RequestAddVirtualFile::unsubscribe(this);
}
void ViewPatternEditor::setupFindReplace(TextEditor *editor) {
// Context menu entries that open the find/replace popup
ImGui::PushID(editor);
static std::string findWord;
static bool requestFocus = false;
static u64 position = 0;
static u64 count = 0;
static bool updateCount = false;
TextEditor::FindReplaceHandler *findReplaceHandler = editor->GetFindReplaceHandler();
static bool canReplace = true;
if (m_openFindReplacePopUp) {
m_openFindReplacePopUp = false;
// Place the popup at the top right of the window
auto windowSize = ImGui::GetWindowSize();
auto style = ImGui::GetStyle();
// Set the scrollbar size only if it is visible
float scrollbarSize = 0;
// Calculate the number of lines to display in the text editor
auto totalTextHeight = editor->GetTotalLines() * editor->GetCharAdvance().y;
// Compare it to the window height
if (totalTextHeight > windowSize.y)
scrollbarSize = style.ScrollbarSize;
auto labelSize = ImGui::CalcTextSize(ICON_VS_WHOLE_WORD);
// Six icon buttons
auto popupSize = ImVec2({(labelSize.x + style.FramePadding.x * 2.0F) * 6.0F,
labelSize.y + style.FramePadding.y * 2.0F + style.WindowPadding.y + 3 });
// 2 * 11 spacings in between elements
popupSize.x += style.FramePadding.x * 22.0F;
// Text input fields are set to 12 characters wide
popupSize.x += ImGui::GetFontSize() * 12.0F;
// IndexOfCount text
popupSize.x += ImGui::CalcTextSize("2000 of 2000").x + 2.0F;
popupSize.x += scrollbarSize;
// Position of popup relative to parent window
ImVec2 windowPosForPopup = ImGui::GetWindowPos();
// Not the window height but the content height
windowPosForPopup.y += popupSize.y;
// Add remaining window height
popupSize.y += style.WindowPadding.y + 1;
// Move to the right so as not to overlap the scrollbar
windowPosForPopup.x += windowSize.x - popupSize.x;
findReplaceHandler->SetFindWindowPos(windowPosForPopup);
if (m_replaceMode) {
// Remove one window padding
popupSize.y -= style.WindowPadding.y;
// Add the replace window height
popupSize.y *= 2;
}
if (m_focusedSubWindowName.contains(consoleView)) {
windowPosForPopup.y = m_consoleHoverBox.Min.y;
canReplace = false;
} else if (m_focusedSubWindowName.contains(textEditorView))
canReplace = true;
ImGui::SetNextWindowPos(windowPosForPopup);
ImGui::SetNextWindowSize(popupSize);
ImGui::OpenPopup("##pattern_editor_find_replace");
findReplaceHandler->resetMatches();
// Use selection as find word if there is one, otherwise use the word under the cursor
if (!editor->HasSelection())
editor->SelectWordUnderCursor();
findWord = editor->GetSelectedText();
// Find all matches to findWord
findReplaceHandler->FindAllMatches(editor,findWord);
position = findReplaceHandler->FindPosition(editor,editor->GetCursorPosition(), true);
count = findReplaceHandler->GetMatches().size();
findReplaceHandler->SetFindWord(editor,findWord);
requestFocus = true;
updateCount = true;
}
drawFindReplaceDialog(editor, findWord, requestFocus, position, count, updateCount, canReplace);
ImGui::PopID();
}
void ViewPatternEditor::drawContent() {
auto provider = ImHexApi::Provider::get();
if (ImHexApi::Provider::isValid() && provider->isAvailable()) {
static float height = 0;
static bool dragging = false;
const auto availableSize = ImGui::GetContentRegionAvail();
const auto windowPosition = ImGui::GetCursorScreenPos();
auto textEditorSize = availableSize;
textEditorSize.y *= 3.5 / 5.0;
textEditorSize.y -= ImGui::GetTextLineHeightWithSpacing();
textEditorSize.y += height;
if (availableSize.y > 1)
textEditorSize.y = std::clamp(textEditorSize.y, 1.0F, std::max(1.0F, availableSize.y - ImGui::GetTextLineHeightWithSpacing() * 3));
const ImGuiContext& g = *GImGui;
if (g.NavWindow != nullptr) {
std::string name = g.NavWindow->Name;
if (name.contains(textEditorView) || name.contains(consoleView))
m_focusedSubWindowName = name;
}
m_textEditor.Render("hex.builtin.view.pattern_editor.name"_lang, textEditorSize, true);
m_textEditorHoverBox = ImRect(windowPosition,windowPosition+textEditorSize);
m_consoleHoverBox = ImRect(ImVec2(windowPosition.x,windowPosition.y+textEditorSize.y),windowPosition+availableSize);
TextEditor::FindReplaceHandler *findReplaceHandler = m_textEditor.GetFindReplaceHandler();
if (ImGui::IsMouseDown(ImGuiMouseButton_Right) && ImGui::IsMouseHoveringRect(m_textEditorHoverBox.Min,m_textEditorHoverBox.Max) && !ImGui::IsMouseDragging(ImGuiMouseButton_Right)) {
ImGui::OpenPopup("##pattern_editor_context_menu");
}
if (ImGui::BeginPopup("##pattern_editor_context_menu")) {
// no shortcut for this
if (ImGui::MenuItem("hex.builtin.menu.file.import.pattern_file"_lang, nullptr, false))
m_importPatternFile();
if (ImGui::MenuItem("hex.builtin.menu.file.export.pattern_file"_lang, nullptr, false))
m_exportPatternFile();
ImGui::Separator();
const bool hasSelection = m_textEditor.HasSelection();
if (ImGui::MenuItem("hex.builtin.view.hex_editor.menu.edit.cut"_lang, Shortcut(CTRLCMD + Keys::X).toString().c_str(), false, hasSelection)) {
m_textEditor.Cut();
}
if (ImGui::MenuItem("hex.builtin.view.hex_editor.menu.edit.copy"_lang, Shortcut(CTRLCMD + Keys::C).toString().c_str(), false, hasSelection)) {
m_textEditor.Copy();
}
if (ImGui::MenuItem("hex.builtin.view.hex_editor.menu.edit.paste"_lang, Shortcut(CTRLCMD + Keys::V).toString().c_str())) {
m_textEditor.Paste();
}
ImGui::Separator();
if (ImGui::MenuItem("hex.builtin.menu.edit.undo"_lang, Shortcut(CTRLCMD + Keys::Z).toString().c_str(), false, m_textEditor.CanUndo())) {
m_textEditor.Undo();
}
if (ImGui::MenuItem("hex.builtin.menu.edit.redo"_lang, Shortcut(CTRLCMD + Keys::Y).toString().c_str(), false, m_textEditor.CanRedo())) {
m_textEditor.Redo();
}
ImGui::Separator();
// Search and replace entries
if (ImGui::MenuItem("hex.builtin.view.pattern_editor.menu.find"_lang, Shortcut(CTRLCMD + Keys::F).toString().c_str(),false, m_textEditor.HasSelection())){
m_replaceMode = false;
m_openFindReplacePopUp = true;
}
if (ImGui::MenuItem("hex.builtin.view.pattern_editor.menu.find_next"_lang, Shortcut(Keys::F3).toString().c_str(),false,!findReplaceHandler->GetFindWord().empty()))
findReplaceHandler->FindMatch(&m_textEditor,true);
if (ImGui::MenuItem("hex.builtin.view.pattern_editor.menu.find_previous"_lang, Shortcut(SHIFT + Keys::F3).toString().c_str(),false,!findReplaceHandler->GetFindWord().empty()))
findReplaceHandler->FindMatch(&m_textEditor,false);
if (ImGui::MenuItem("hex.builtin.view.pattern_editor.menu.replace"_lang, Shortcut(CTRLCMD + Keys::H).toString().c_str(),false,!findReplaceHandler->GetReplaceWord().empty())) {
m_replaceMode = true;
m_openFindReplacePopUp = true;
}
if (ImGui::MenuItem("hex.builtin.view.pattern_editor.menu.replace_next"_lang,"",false,!findReplaceHandler->GetReplaceWord().empty()))
findReplaceHandler->Replace(&m_textEditor,true);
if (ImGui::MenuItem("hex.builtin.view.pattern_editor.menu.replace_previous"_lang, "",false,!findReplaceHandler->GetReplaceWord().empty()))
findReplaceHandler->Replace(&m_textEditor,false);
if (ImGui::MenuItem("hex.builtin.view.pattern_editor.menu.replace_all"_lang, "",false,!findReplaceHandler->GetReplaceWord().empty()))
findReplaceHandler->ReplaceAll(&m_textEditor);
ImGui::EndPopup();
}
setupFindReplace(getEditorFromFocusedWindow());
ImGui::Button("##settings_drag_bar", ImVec2(ImGui::GetContentRegionAvail().x, 2_scaled));
if (ImGui::IsMouseDragging(ImGuiMouseButton_Left, 0)) {
if (ImGui::IsItemHovered())
dragging = true;
} else {
dragging = false;
}
if (ImGui::IsItemHovered()) {
ImGui::SetMouseCursor(ImGuiMouseCursor_ResizeNS);
}
if (dragging) {
height += ImGui::GetMouseDragDelta(ImGuiMouseButton_Left, 0).y;
ImGui::ResetMouseDragDelta(ImGuiMouseButton_Left);
}
auto settingsSize = ImGui::GetContentRegionAvail();
settingsSize.y -= ImGui::GetTextLineHeightWithSpacing() * 2.5F;
if (ImGui::BeginTabBar("##settings")) {
if (ImGui::BeginTabItem("hex.builtin.view.pattern_editor.console"_lang)) {
this->drawConsole(settingsSize);
ImGui::EndTabItem();
}
if (ImGui::BeginTabItem("hex.builtin.view.pattern_editor.env_vars"_lang)) {
this->drawEnvVars(settingsSize, *m_envVarEntries);
ImGui::EndTabItem();
}
if (ImGui::BeginTabItem("hex.builtin.view.pattern_editor.settings"_lang)) {
this->drawVariableSettings(settingsSize, *m_patternVariables);
ImGui::EndTabItem();
}
if (ImGui::BeginTabItem("hex.builtin.view.pattern_editor.sections"_lang)) {
this->drawSectionSelector(settingsSize, *m_sections);
ImGui::EndTabItem();
}
if (ImGui::BeginTabItem("hex.builtin.view.pattern_editor.virtual_files"_lang)) {
this->drawVirtualFiles(settingsSize, *m_virtualFiles);
ImGui::EndTabItem();
}
if (ImGui::BeginTabItem("hex.builtin.view.pattern_editor.debugger"_lang)) {
this->drawDebugger(settingsSize);
ImGui::EndTabItem();
}
ImGui::EndTabBar();
}
ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 1);
{
auto &runtime = ContentRegistry::PatternLanguage::getRuntime();
if (runtime.isRunning()) {
if (m_breakpointHit) {
if (ImGuiExt::IconButton(ICON_VS_DEBUG_CONTINUE, ImGuiExt::GetCustomColorVec4(ImGuiCustomCol_ToolbarYellow)))
m_breakpointHit = false;
ImGui::SameLine();
if (ImGuiExt::IconButton(ICON_VS_DEBUG_STEP_INTO, ImGuiExt::GetCustomColorVec4(ImGuiCustomCol_ToolbarYellow))) {
runtime.getInternals().evaluator->pauseNextLine();
m_breakpointHit = false;
}
} else {
if (ImGuiExt::IconButton(ICON_VS_DEBUG_STOP, ImGuiExt::GetCustomColorVec4(ImGuiCustomCol_ToolbarRed)))
runtime.abort();
}
} else {
if (ImGuiExt::IconButton(ICON_VS_DEBUG_START, ImGuiExt::GetCustomColorVec4(ImGuiCustomCol_ToolbarGreen)) || m_triggerEvaluation) {
m_triggerEvaluation = false;
this->evaluatePattern(m_textEditor.GetText(), provider);
}
}
ImGui::PopStyleVar();
ImGui::SameLine();
if (m_runningEvaluators > 0) {
if (m_breakpointHit) {
ImGuiExt::TextFormatted("hex.builtin.view.pattern_editor.breakpoint_hit"_lang, runtime.getInternals().evaluator->getPauseLine().value_or(0));
} else {
ImGuiExt::TextSpinner("hex.builtin.view.pattern_editor.evaluating"_lang);
}
ImGui::SameLine();
ImGui::SeparatorEx(ImGuiSeparatorFlags_Vertical);
ImGui::SameLine();
const auto padding = ImGui::GetStyle().FramePadding.y;
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2());
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2());
if (ImGui::BeginChild("##read_cursor", ImGui::GetContentRegionAvail() + ImVec2(0, padding), true)) {
const auto startPos = ImGui::GetCursorScreenPos();
const auto size = ImGui::GetContentRegionAvail();
const auto dataBaseAddress = runtime.getInternals().evaluator->getDataBaseAddress();
const auto dataSize = runtime.getInternals().evaluator->getDataSize();
const auto insertPos = [&, this](u64 address, u32 color) {
const auto progress = float(address - dataBaseAddress) / float(dataSize);
m_accessHistory[m_accessHistoryIndex] = { progress, color };
m_accessHistoryIndex = (m_accessHistoryIndex + 1) % m_accessHistory.size();
};
insertPos(runtime.getLastReadAddress(), ImGuiExt::GetCustomColorU32(ImGuiCustomCol_ToolbarBlue));
insertPos(runtime.getLastWriteAddress(), ImGuiExt::GetCustomColorU32(ImGuiCustomCol_ToolbarRed));
insertPos(runtime.getLastPatternPlaceAddress(), ImGuiExt::GetCustomColorU32(ImGuiCustomCol_ToolbarGreen));
const auto drawList = ImGui::GetWindowDrawList();
for (const auto &[progress, color] : m_accessHistory) {
if (progress <= 0) continue;
const auto linePos = startPos + ImVec2(size.x * progress, 0);
drawList->AddLine(linePos, linePos + ImVec2(0, size.y), color, 2_scaled);
}
}
ImGui::EndChild();
ImGui::PopStyleVar(2);
} else {
if (ImGui::Checkbox("hex.builtin.view.pattern_editor.auto"_lang, &m_runAutomatically)) {
if (m_runAutomatically)
m_hasUnevaluatedChanges = true;
}
ImGui::SameLine();
ImGui::SeparatorEx(ImGuiSeparatorFlags_Vertical);
ImGui::SameLine();
if (const auto max = runtime.getMaximumPatternCount(); max >= std::numeric_limits<u64>::max()) {
ImGuiExt::TextFormatted("{}", runtime.getCreatedPatternCount());
} else {
ImGuiExt::TextFormatted("{} / {}",
runtime.getCreatedPatternCount(),
runtime.getMaximumPatternCount());
}
}
}
if (m_textEditor.IsTextChanged()) {
m_hasUnevaluatedChanges = true;
m_lastEditorChangeTime = std::chrono::steady_clock::now();
ImHexApi::Provider::markDirty();
}
if (m_hasUnevaluatedChanges && m_runningEvaluators == 0 && m_runningParsers == 0) {
if ((std::chrono::steady_clock::now() - m_lastEditorChangeTime) > std::chrono::seconds(1LL)) {
m_hasUnevaluatedChanges = false;
auto code = m_textEditor.GetText();
EventPatternEditorChanged::post(code);
TaskManager::createBackgroundTask("hex.builtin.task.parsing_pattern"_lang, [this, code = std::move(code), provider](auto &){
this->parsePattern(code, provider);
if (m_runAutomatically)
m_triggerAutoEvaluate = true;
});
}
}
if (m_triggerAutoEvaluate.exchange(false)) {
this->evaluatePattern(m_textEditor.GetText(), provider);
}
}
if (m_dangerousFunctionCalled && !ImGui::IsPopupOpen(ImGuiID(0), ImGuiPopupFlags_AnyPopup)) {
ui::PopupQuestion::open("hex.builtin.view.pattern_editor.dangerous_function.desc"_lang,
[this] {
m_dangerousFunctionsAllowed = DangerousFunctionPerms::Allow;
}, [this] {
m_dangerousFunctionsAllowed = DangerousFunctionPerms::Deny;
}
);
m_dangerousFunctionCalled = false;
}
View::discardNavigationRequests();
}
void ViewPatternEditor::historyInsert(std::array<std::string,256> &history, u32 &size, u32 &index, const std::string &value) {
for (u64 i = 0; i < size; i++) {
if (history[i] == value)
return;
}
if (size < 256){
history[size] = value;
size++;
} else {
index = (index - 1) % 256;
history[index] = value;
index = (index + 1) % 256;
}
}
void ViewPatternEditor::drawFindReplaceDialog(TextEditor *textEditor, std::string &findWord, bool &requestFocus, u64 &position, u64 &count, bool &updateCount, bool canReplace) {
TextEditor::FindReplaceHandler *findReplaceHandler = textEditor->GetFindReplaceHandler();
bool enter = ImGui::IsKeyPressed(ImGuiKey_Enter, false) || ImGui::IsKeyPressed(ImGuiKey_KeypadEnter, false);
bool upArrow = ImGui::IsKeyPressed(ImGuiKey_UpArrow, false) || ImGui::IsKeyPressed(ImGuiKey_Keypad8, false);
bool downArrow = ImGui::IsKeyPressed(ImGuiKey_DownArrow, false) || ImGui::IsKeyPressed(ImGuiKey_Keypad2, false);
bool shift = ImGui::IsKeyDown(ImGuiKey_LeftShift) || ImGui::IsKeyDown(ImGuiKey_RightShift);
bool alt = ImGui::IsKeyDown(ImGuiKey_LeftAlt) || ImGui::IsKeyDown(ImGuiKey_RightAlt);
if (ImGui::BeginPopup("##pattern_editor_find_replace")) {
if (ImGui::BeginTable("##pattern_editor_find_replace_table", 2,
ImGuiTableFlags_SizingStretchProp | ImGuiTableFlags_BordersInnerH)) {
ImGui::TableNextRow();
ImGui::TableNextColumn();
static bool requestFocusFind = false;
static bool requestFocusReplace = false;
bool oldReplace = m_replaceMode;
if (canReplace)
ImGuiExt::DimmedIconToggle(ICON_VS_TRIANGLE_DOWN, ICON_VS_TRIANGLE_RIGHT, &m_replaceMode);
else
m_replaceMode = false;
if (oldReplace != m_replaceMode) {
if (m_replaceMode)
requestFocusReplace = true;
else
requestFocusFind = true;
}
ImGui::TableNextColumn();
static int findFlags = ImGuiInputTextFlags_None;
if (requestFocus && m_findHistoryIndex == m_findHistorySize)
findFlags |= ImGuiInputTextFlags_AutoSelectAll;
else
findFlags &= ~ImGuiInputTextFlags_AutoSelectAll;
if (m_findHistoryIndex != m_findHistorySize && requestFocusFind ) {
findFlags |= ImGuiInputTextFlags_ReadOnly;
} else
findFlags &= ~ImGuiInputTextFlags_ReadOnly;
std::string hint = "hex.builtin.view.pattern_editor.find_hint"_lang.operator std::string();
if (m_findHistorySize > 0) {
hint += " (";
hint += ICON_BI_DATA_TRANSFER_BOTH;
hint += "hex.builtin.view.pattern_editor.find_hint_history"_lang.operator std::string();
}
static bool enterPressedFind = false;
ImGui::PushItemWidth(ImGui::GetFontSize() * 12);
if (ImGui::InputTextWithHint("###findInputTextWidget", hint.c_str(), findWord, findFlags) || enter ) {
if (enter)
enterPressedFind = true;
updateCount = true;
requestFocusFind = true;
findReplaceHandler->SetFindWord(textEditor,findWord);
}
if ((!m_replaceMode && requestFocus) || requestFocusFind) {
ImGui::SetKeyboardFocusHere(-1);
requestFocus = false;
requestFocusFind = false;
}
if (ImGui::IsItemActive() && (upArrow || downArrow) && m_findHistorySize > 0) {
if (upArrow)
m_findHistoryIndex = (m_findHistoryIndex + m_findHistorySize - 1) % m_findHistorySize;
if (downArrow)
m_findHistoryIndex = (m_findHistoryIndex + 1) % m_findHistorySize;
findWord = m_findHistory[m_findHistoryIndex];
findReplaceHandler->SetFindWord(textEditor,findWord);
position = findReplaceHandler->FindPosition(textEditor,textEditor->GetCursorPosition(), true);
count = findReplaceHandler->GetMatches().size();
updateCount = true;
requestFocusFind = true;
}
ImGui::PopItemWidth();
ImGui::SameLine();
bool matchCase = findReplaceHandler->GetMatchCase();
// Allow Alt-C to toggle case sensitivity
bool altCPressed = ImGui::IsKeyPressed(ImGuiKey_C, false) && alt;
if (altCPressed || ImGuiExt::DimmedIconToggle(ICON_VS_CASE_SENSITIVE, &matchCase)) {
if (altCPressed)
matchCase = !matchCase;
findReplaceHandler->SetMatchCase(textEditor,matchCase);
position = findReplaceHandler->FindPosition(textEditor,textEditor->GetCursorPosition(), true);
count = findReplaceHandler->GetMatches().size();
updateCount = true;
requestFocusFind = true;
}
ImGui::SameLine();
bool matchWholeWord = findReplaceHandler->GetWholeWord();
// Allow Alt-W to toggle whole word
bool altWPressed = ImGui::IsKeyPressed(ImGuiKey_W, false) && alt;
if (altWPressed || ImGuiExt::DimmedIconToggle(ICON_VS_WHOLE_WORD, &matchWholeWord)) {
if (altWPressed)
matchWholeWord = !matchWholeWord;
findReplaceHandler->SetWholeWord(textEditor,matchWholeWord);
position = findReplaceHandler->FindPosition(textEditor,textEditor->GetCursorPosition(), true);
count = findReplaceHandler->GetMatches().size();
updateCount = true;
requestFocusFind = true;
}
ImGui::SameLine();
bool useRegex = findReplaceHandler->GetFindRegEx();
// Allow Alt-R to toggle regex
bool altRPressed = ImGui::IsKeyPressed(ImGuiKey_R, false) && alt;
if (altRPressed || ImGuiExt::DimmedIconToggle(ICON_VS_REGEX, &useRegex)) {
if (altRPressed)
useRegex = !useRegex;
findReplaceHandler->SetFindRegEx(textEditor,useRegex);
position = findReplaceHandler->FindPosition(textEditor,textEditor->GetCursorPosition(), true);
count = findReplaceHandler->GetMatches().size();
updateCount = true;
requestFocusFind = true;
}
static std::string counterString;
auto totalSize = ImGui::CalcTextSize("2000 of 2000");
ImVec2 buttonSize;
if (updateCount) {
updateCount = false;
if (count == 0 || position == std::numeric_limits<u64>::max())
counterString = "hex.builtin.view.pattern_editor.no_results"_lang.operator std::string();
else {
if (position > 1999)
counterString = "?";
else
counterString = hex::format("{} ", position);
counterString += "hex.builtin.view.pattern_editor.of"_lang.operator const char *();
if (count > 1999)
counterString += "1999+";
else
counterString += hex::format(" {}", count);
}
}
auto resultSize = ImGui::CalcTextSize(counterString.c_str());
if (totalSize.x > resultSize.x)
buttonSize = ImVec2(totalSize.x + 2 - resultSize.x, resultSize.y);
else
buttonSize = ImVec2(2, resultSize.y);
ImGui::SameLine();
ImGui::TextUnformatted(counterString.c_str());
ImGui::SameLine();
ImGui::InvisibleButton("##find_result_padding", buttonSize);
ImGui::SameLine();
static bool downArrowFind = false;
if (ImGuiExt::IconButton(ICON_VS_ARROW_DOWN, ImVec4(1, 1, 1, 1)))
downArrowFind = true;
ImGui::SameLine();
static bool upArrowFind = false;
if (ImGuiExt::IconButton(ICON_VS_ARROW_UP, ImVec4(1, 1, 1, 1)))
upArrowFind = true;
if (m_replaceMode) {
ImGui::TableNextRow();
ImGui::TableNextColumn();
ImGui::TableNextColumn();
static int replaceFlags = ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_AutoSelectAll;
if (m_replaceHistoryIndex != m_replaceHistorySize && requestFocusReplace) {
replaceFlags |= ImGuiInputTextFlags_ReadOnly;
} else
replaceFlags &= ~ImGuiInputTextFlags_ReadOnly;
hint = "hex.builtin.view.pattern_editor.replace_hint"_lang.operator std::string();
if (m_replaceHistorySize > 0) {
hint += " (";
hint += ICON_BI_DATA_TRANSFER_BOTH;
hint += "hex.builtin.view.pattern_editor.replace_hint_history"_lang.operator std::string();
}
ImGui::PushItemWidth(ImGui::GetFontSize() * 12);
static std::string replaceWord;
static bool downArrowReplace = false;
static bool upArrowReplace = false;
if (ImGui::InputTextWithHint("##replaceInputTextWidget", hint.c_str(), replaceWord, replaceFlags) || downArrowReplace || upArrowReplace) {
findReplaceHandler->SetReplaceWord(replaceWord);
historyInsert(m_replaceHistory, m_replaceHistorySize, m_replaceHistoryIndex, replaceWord);
bool textReplaced = findReplaceHandler->Replace(textEditor,!shift && !upArrowReplace);
if (textReplaced) {
if (count > 0) {
if (position == count)
position -= 1;
count -= 1;
if (count == 0)
requestFocusFind = true;
else
requestFocusReplace = true;
} else
requestFocusFind = true;
updateCount = true;
}
downArrowReplace = false;
upArrowReplace = false;
if (enterPressedFind) {
enterPressedFind = false;
requestFocusFind = false;
}
}
if (requestFocus || requestFocusReplace) {
ImGui::SetKeyboardFocusHere(-1);
requestFocus = false;
requestFocusReplace = false;
}
if (ImGui::IsItemActive() && (upArrow || downArrow) && m_replaceHistorySize > 0) {
if (upArrow)
m_replaceHistoryIndex = (m_replaceHistoryIndex + m_replaceHistorySize - 1) % m_replaceHistorySize;
if (downArrow)
m_replaceHistoryIndex = (m_replaceHistoryIndex + 1) % m_replaceHistorySize;
replaceWord = m_replaceHistory[m_replaceHistoryIndex];
findReplaceHandler->SetReplaceWord(replaceWord);
requestFocusReplace = true;
}
ImGui::PopItemWidth();
ImGui::SameLine();
if (ImGuiExt::IconButton(ICON_VS_FOLD_DOWN, ImVec4(1, 1, 1, 1)))
downArrowReplace = true;
ImGui::SameLine();
if (ImGuiExt::IconButton(ICON_VS_FOLD_UP, ImVec4(1, 1, 1, 1)))
upArrowReplace = true;
ImGui::SameLine();
if (ImGuiExt::IconButton(ICON_VS_REPLACE_ALL, ImVec4(1, 1, 1, 1))) {
findReplaceHandler->SetReplaceWord(replaceWord);
historyInsert(m_replaceHistory,m_replaceHistorySize, m_replaceHistoryIndex, replaceWord);
findReplaceHandler->ReplaceAll(textEditor);
count = 0;
position = 0;
requestFocusFind = true;
updateCount = true;
}
findReplaceHandler->SetFindWindowSize(ImGui::GetWindowSize());
} else
findReplaceHandler->SetFindWindowSize(ImGui::GetWindowSize());
if ((ImGui::IsKeyPressed(ImGuiKey_F3, false)) || downArrowFind || upArrowFind || enterPressedFind) {
historyInsert(m_findHistory, m_findHistorySize, m_findHistoryIndex, findWord);
position = findReplaceHandler->FindMatch(textEditor,!shift && !upArrowFind);
count = findReplaceHandler->GetMatches().size();
updateCount = true;
downArrowFind = false;
upArrowFind = false;
requestFocusFind = true;
enterPressedFind = false;
}
ImGui::EndTable();
}
// Escape key to close the popup
if (ImGui::IsKeyPressed(ImGuiKey_Escape, false))
ImGui::CloseCurrentPopup();
ImGui::EndPopup();
}
}
void ViewPatternEditor::drawConsole(ImVec2 size) {
auto findReplaceHandler = m_consoleEditor.GetFindReplaceHandler();
if (ImGui::IsMouseDown(ImGuiMouseButton_Right) && ImGui::IsMouseHoveringRect(m_consoleHoverBox.Min,m_consoleHoverBox.Max) && !ImGui::IsMouseDragging(ImGuiMouseButton_Right)) {
ImGui::OpenPopup("##console_context_menu");
}
const bool hasSelection = m_consoleEditor.HasSelection();
if (ImGui::BeginPopup("##console_context_menu")) {
if (ImGui::MenuItem("hex.builtin.view.hex_editor.menu.edit.copy"_lang, Shortcut(CTRLCMD + Keys::C).toString().c_str(), false, hasSelection)) {
m_consoleEditor.Copy();
}
if (ImGui::MenuItem("hex.builtin.view.hex_editor.menu.edit.select_all"_lang, Shortcut(CTRLCMD + Keys::A).toString().c_str())) {
m_consoleEditor.SelectAll();
}
ImGui::Separator();
// Search and replace entries
if (ImGui::MenuItem("hex.builtin.view.pattern_editor.menu.find"_lang, Shortcut(CTRLCMD + Keys::F).toString().c_str(),false, hasSelection)) {
m_openFindReplacePopUp = true;
m_replaceMode = false;
}
if (ImGui::MenuItem("hex.builtin.view.pattern_editor.menu.find_next"_lang, Shortcut(Keys::F3).toString().c_str(),false,!findReplaceHandler->GetFindWord().empty()))
findReplaceHandler->FindMatch(&m_consoleEditor,true);
if (ImGui::MenuItem("hex.builtin.view.pattern_editor.menu.find_previous"_lang, Shortcut(SHIFT + Keys::F3).toString().c_str(),false,!findReplaceHandler->GetFindWord().empty()))
findReplaceHandler->FindMatch(&m_consoleEditor,false);
ImGui::EndPopup();
}
if (m_consoleNeedsUpdate) {
std::scoped_lock lock(m_logMutex);
auto lineCount = m_consoleEditor.GetTextLines().size() - 1;
if (m_console->size() < lineCount) {
m_consoleEditor.SetText("");
lineCount = 0;
}
m_consoleEditor.SetCursorPosition({ int(lineCount + 1), 0 });
const auto linesToAdd = m_console->size() - lineCount;
for (size_t i = 0; i < linesToAdd; i += 1) {
m_consoleEditor.InsertText(m_console->at(lineCount + i));
m_consoleEditor.InsertText("\n");
}
m_consoleNeedsUpdate = false;
}
m_consoleEditor.Render("##console", size, true);
ImGui::SetCursorPosY(ImGui::GetCursorPosY() + ImGui::GetStyle().FramePadding.y + 1_scaled);
}
void ViewPatternEditor::drawEnvVars(ImVec2 size, std::list<EnvVar> &envVars) {
static u32 envVarCounter = 1;
if (ImGui::BeginChild("##env_vars", size, true, ImGuiWindowFlags_AlwaysVerticalScrollbar)) {
if (ImGui::BeginTable("##env_vars_table", 4, ImGuiTableFlags_SizingStretchProp | ImGuiTableFlags_BordersInnerH)) {
ImGui::TableSetupColumn("Type", ImGuiTableColumnFlags_WidthStretch, 0.1F);
ImGui::TableSetupColumn("Name", ImGuiTableColumnFlags_WidthStretch, 0.4F);
ImGui::TableSetupColumn("Value", ImGuiTableColumnFlags_WidthStretch, 0.38F);
ImGui::TableSetupColumn("Remove", ImGuiTableColumnFlags_WidthStretch, 0.12F);
int index = 0;
for (auto iter = envVars.begin(); iter != envVars.end(); ++iter) {
ImGui::TableNextRow();
ImGui::TableNextColumn();
auto &[id, name, value, type] = *iter;
ImGui::PushID(index++);
ON_SCOPE_EXIT { ImGui::PopID(); };
ImGui::PushItemWidth(ImGui::GetContentRegionAvail().x);
constexpr static std::array Types = { "I", "F", "S", "B" };
if (ImGui::BeginCombo("", Types[static_cast<int>(type)])) {
for (size_t i = 0; i < Types.size(); i++) {
if (ImGui::Selectable(Types[i]))
type = static_cast<EnvVarType>(i);
}
ImGui::EndCombo();
}
ImGui::PopItemWidth();
ImGui::TableNextColumn();
ImGui::PushItemWidth(ImGui::GetContentRegionAvail().x);
ImGui::InputText("###name", name);
ImGui::PopItemWidth();
ImGui::TableNextColumn();
ImGui::PushItemWidth(ImGui::GetContentRegionAvail().x);
switch (type) {
using enum EnvVarType;
case Integer:
{
i64 displayValue = hex::get_or<i128>(value, 0);
ImGui::InputScalar("###value", ImGuiDataType_S64, &displayValue);
value = i128(displayValue);
break;
}
case Float:
{
auto displayValue = hex::get_or<double>(value, 0.0);
ImGui::InputDouble("###value", &displayValue);
value = displayValue;
break;
}
case Bool:
{
auto displayValue = hex::get_or<bool>(value, false);
ImGui::Checkbox("###value", &displayValue);
value = displayValue;
break;
}
case String:
{
auto displayValue = hex::get_or<std::string>(value, "");
ImGui::InputText("###value", displayValue);
value = displayValue;
break;
}
}
ImGui::PopItemWidth();
ImGui::TableNextColumn();
if (ImGuiExt::IconButton(ICON_VS_ADD, ImGui::GetStyleColorVec4(ImGuiCol_Text))) {
envVars.insert(std::next(iter), { envVarCounter++, "", i128(0), EnvVarType::Integer });
}
ImGui::SameLine();
ImGui::BeginDisabled(envVars.size() <= 1);
{
if (ImGuiExt::IconButton(ICON_VS_REMOVE, ImGui::GetStyleColorVec4(ImGuiCol_Text))) {
const bool isFirst = iter == envVars.begin();
const bool isLast = std::next(iter) == envVars.end();
envVars.erase(iter);
if (isFirst)
iter = envVars.begin();
if (isLast)
iter = std::prev(envVars.end());
}
}
ImGui::EndDisabled();
}
ImGui::EndTable();
}
}
ImGui::EndChild();
}
void ViewPatternEditor::drawVariableSettings(ImVec2 size, std::map<std::string, PatternVariable> &patternVariables) {
if (ImGui::BeginChild("##settings", size, true, ImGuiWindowFlags_AlwaysVerticalScrollbar)) {
if (patternVariables.empty()) {
ImGuiExt::TextFormattedCentered("hex.builtin.view.pattern_editor.no_in_out_vars"_lang);
} else {
if (ImGui::BeginTable("##in_out_vars_table", 2, ImGuiTableFlags_SizingStretchProp | ImGuiTableFlags_BordersInnerH | ImGuiTableFlags_BordersOuterH | ImGuiTableFlags_RowBg)) {
ImGui::TableSetupColumn("Name", ImGuiTableColumnFlags_WidthStretch, 0.25F);
ImGui::TableSetupColumn("Value", ImGuiTableColumnFlags_WidthStretch, 0.75F);
for (auto &[name, variable] : patternVariables) {
ImGui::TableNextRow();
ImGui::TableNextColumn();
ImGui::TextUnformatted(name.c_str());
ImGui::TableNextColumn();
ImGui::PushItemWidth(-1);
if (variable.outVariable) {
ImGuiExt::TextFormattedSelectable("{}", variable.value.toString(true).c_str());
} else if (variable.inVariable) {
const std::string label { "##" + name };
if (pl::core::Token::isSigned(variable.type)) {
i64 value = hex::get_or<i128>(variable.value, 0);
if (ImGui::InputScalar(label.c_str(), ImGuiDataType_S64, &value))
m_hasUnevaluatedChanges = true;
variable.value = i128(value);
} else if (pl::core::Token::isUnsigned(variable.type)) {
u64 value = hex::get_or<u128>(variable.value, 0);
if (ImGui::InputScalar(label.c_str(), ImGuiDataType_U64, &value))
m_hasUnevaluatedChanges = true;
variable.value = u128(value);
} else if (pl::core::Token::isFloatingPoint(variable.type)) {
auto value = hex::get_or<double>(variable.value, 0.0);
if (ImGui::InputScalar(label.c_str(), ImGuiDataType_Double, &value))
m_hasUnevaluatedChanges = true;
variable.value = value;
} else if (variable.type == pl::core::Token::ValueType::Boolean) {
auto value = hex::get_or<bool>(variable.value, false);
if (ImGui::Checkbox(label.c_str(), &value))
m_hasUnevaluatedChanges = true;
variable.value = value;
} else if (variable.type == pl::core::Token::ValueType::Character) {
std::array<char, 2> buffer = { hex::get_or<char>(variable.value, '\x00') };
if (ImGui::InputText(label.c_str(), buffer.data(), buffer.size()))
m_hasUnevaluatedChanges = true;
variable.value = buffer[0];
} else if (variable.type == pl::core::Token::ValueType::String) {
std::string buffer = hex::get_or<std::string>(variable.value, "");
if (ImGui::InputText(label.c_str(), buffer))
m_hasUnevaluatedChanges = true;
variable.value = buffer;
}
}
ImGui::PopItemWidth();
}
ImGui::EndTable();
}
}
}
ImGui::EndChild();
}
void ViewPatternEditor::drawSectionSelector(ImVec2 size, const std::map<u64, pl::api::Section> §ions) {
auto &runtime = ContentRegistry::PatternLanguage::getRuntime();
if (ImGui::BeginTable("##sections_table", 3, ImGuiTableFlags_SizingStretchProp | ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_ScrollY, size)) {
ImGui::TableSetupScrollFreeze(0, 1);
ImGui::TableSetupColumn("hex.ui.common.name"_lang, ImGuiTableColumnFlags_WidthStretch, 0.5F);
ImGui::TableSetupColumn("hex.ui.common.size"_lang, ImGuiTableColumnFlags_WidthStretch, 0.5F);
ImGui::TableSetupColumn("##button", ImGuiTableColumnFlags_WidthFixed, 50_scaled);
ImGui::TableHeadersRow();
if (TRY_LOCK(ContentRegistry::PatternLanguage::getRuntimeLock())) {
for (auto &[id, section] : sections) {
if (section.name.empty())
continue;
ImGui::PushID(id);
ImGui::TableNextRow();
ImGui::TableNextColumn();
ImGui::TextUnformatted(section.name.c_str());
ImGui::TableNextColumn();
ImGuiExt::TextFormatted("{} | 0x{:02X}", hex::toByteString(section.data.size()), section.data.size());
ImGui::TableNextColumn();
if (ImGuiExt::DimmedIconButton(ICON_VS_OPEN_PREVIEW, ImGui::GetStyleColorVec4(ImGuiCol_Text))) {
auto dataProvider = std::make_shared<prv::MemoryProvider>(section.data);
auto hexEditor = auto(m_sectionHexEditor);
hexEditor.setBackgroundHighlightCallback([this, id, &runtime](u64 address, const u8 *, size_t) -> std::optional<color_t> {
if (m_runningEvaluators != 0)
return std::nullopt;
if (!ImHexApi::Provider::isValid())
return std::nullopt;
std::optional<ImColor> color;
for (const auto &pattern : runtime.getPatternsAtAddress(address, id)) {
if (pattern->getVisibility() != pl::ptrn::Visibility::Visible)
continue;
if (color.has_value())
color = ImAlphaBlendColors(*color, pattern->getColor());
else
color = pattern->getColor();
}
return color;
});
auto patternProvider = ImHexApi::Provider::get();
m_sectionWindowDrawer[patternProvider] = [this, id, patternProvider, dataProvider, hexEditor, patternDrawer = std::make_shared<ui::PatternDrawer>(), &runtime] mutable {
hexEditor.setProvider(dataProvider.get());
hexEditor.draw(480_scaled);
patternDrawer->setSelectionCallback([&](const pl::ptrn::Pattern *pattern) {
hexEditor.setSelection(Region { pattern->getOffset(), pattern->getSize() });
});
const auto &patterns = [&, this] -> const auto& {
if (patternProvider->isReadable() && *m_executionDone) {
return runtime.getPatterns(id);
} else {
static const std::vector<std::shared_ptr<pl::ptrn::Pattern>> empty;
return empty;
}
}();
if (*m_executionDone)
patternDrawer->draw(patterns, &runtime, 150_scaled);
};
}
ImGui::SetItemTooltip("%s", "hex.builtin.view.pattern_editor.sections.view"_lang.get());
ImGui::SameLine();
if (ImGuiExt::DimmedIconButton(ICON_VS_SAVE_AS, ImGui::GetStyleColorVec4(ImGuiCol_Text))) {
fs::openFileBrowser(fs::DialogMode::Save, {}, [id, &runtime](const auto &path) {
wolv::io::File file(path, wolv::io::File::Mode::Create);
if (!file.isValid()) {
ui::ToastError::open("hex.builtin.popup.error.create"_lang);
return;
}
file.writeVector(runtime.getSection(id));
});
}
ImGui::SetItemTooltip("%s", "hex.builtin.view.pattern_editor.sections.export"_lang.get());
ImGui::PopID();
}
}
ImGui::EndTable();
}
}
void ViewPatternEditor::drawVirtualFiles(ImVec2 size, const std::vector<VirtualFile> &virtualFiles) const {
std::vector<const VirtualFile*> virtualFilePointers;
for (const auto &file : virtualFiles)
virtualFilePointers.emplace_back(&file);
if (ImGui::BeginTable("Virtual File Tree", 1, ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersInnerH | ImGuiTableFlags_RowBg | ImGuiTableFlags_ScrollY, size)) {
ImGui::TableSetupColumn("##path", ImGuiTableColumnFlags_WidthStretch);
levelId = 1;
drawVirtualFileTree(virtualFilePointers);
ImGui::EndTable();
}
}
void ViewPatternEditor::drawDebugger(ImVec2 size) {
const auto &runtime = ContentRegistry::PatternLanguage::getRuntime();
if (ImGui::BeginChild("##debugger", size, true)) {
auto &evaluator = runtime.getInternals().evaluator;
const auto &breakpoints = evaluator->getBreakpoints();
const auto line = m_textEditor.GetCursorPosition().mLine + 1;
if (!breakpoints.contains(line)) {
if (ImGuiExt::IconButton(ICON_VS_DEBUG_BREAKPOINT, ImGuiExt::GetCustomColorVec4(ImGuiCustomCol_ToolbarRed))) {
evaluator->addBreakpoint(line);
m_textEditor.SetBreakpoints(breakpoints);
}
ImGuiExt::InfoTooltip("hex.builtin.view.pattern_editor.debugger.add_tooltip"_lang);
} else {
if (ImGuiExt::IconButton(ICON_VS_DEBUG_BREAKPOINT_UNVERIFIED, ImGuiExt::GetCustomColorVec4(ImGuiCustomCol_ToolbarRed))) {
evaluator->removeBreakpoint(line);
m_textEditor.SetBreakpoints(breakpoints);
}
ImGuiExt::InfoTooltip("hex.builtin.view.pattern_editor.debugger.remove_tooltip"_lang);
}
ImGui::SameLine();
if (*m_breakpointHit) {
auto displayValue = [&](const auto &parent, size_t index) {
return hex::format("{0} {1} [{2}]",
"hex.builtin.view.pattern_editor.debugger.scope"_lang,
evaluator->getScopeCount() - index - 1,
parent == nullptr ?
"hex.builtin.view.pattern_editor.debugger.scope.global"_lang :
hex::format("0x{0:08X}", parent->getOffset())
);
};
if (evaluator->getScopeCount() > 0) {
ImGui::SetNextItemWidth(-1);
const auto &currScope = evaluator->getScope(-m_debuggerScopeIndex);
if (ImGui::BeginCombo("##scope", displayValue(currScope.parent, m_debuggerScopeIndex).c_str())) {
for (size_t i = 0; i < evaluator->getScopeCount(); i++) {
auto &scope = evaluator->getScope(-i);
if (ImGui::Selectable(displayValue(scope.parent, i).c_str(), i == size_t(m_debuggerScopeIndex))) {
m_debuggerScopeIndex = i;
m_resetDebuggerVariables = true;
}
}
ImGui::EndCombo();
}
}
if (m_resetDebuggerVariables) {
const auto pauseLine = evaluator->getPauseLine();
(*m_debuggerDrawer)->reset();
m_resetDebuggerVariables = false;
m_textEditor.SetCursorPosition(TextEditor::Coordinates(pauseLine.value_or(0) - 1, 0));
if (pauseLine.has_value())
m_textEditor.SetCursorPosition({ int(pauseLine.value() - 1), 0 });
}
const auto &currScope = evaluator->getScope(-m_debuggerScopeIndex);
(*m_debuggerDrawer)->draw(*currScope.scope, &runtime, size.y - ImGui::GetTextLineHeightWithSpacing() * 4);
}
}
ImGui::EndChild();
}
void ViewPatternEditor::drawAlwaysVisibleContent() {
auto provider = ImHexApi::Provider::get();
auto open = m_sectionWindowDrawer.contains(provider);
if (open) {
ImGui::SetNextWindowSize(scaled(ImVec2(600, 700)), ImGuiCond_Appearing);
if (ImGui::Begin("hex.builtin.view.pattern_editor.section_popup"_lang, &open, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoDocking | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse)) {
m_sectionWindowDrawer[provider]();
}
ImGui::End();
}
if (!open && m_sectionWindowDrawer.contains(provider)) {
ImHexApi::HexEditor::setSelection(Region::Invalid());
m_sectionWindowDrawer.erase(provider);
}
if (!m_lastEvaluationProcessed) {
if (!m_lastEvaluationResult) {
const auto processMessage = [](const auto &message) {
auto lines = wolv::util::splitString(message, "\n");
std::ranges::transform(lines, lines.begin(), [](auto line) {
if (line.size() >= 128)
line = wolv::util::trim(line);
return hex::limitStringLength(line, 128);
});
return wolv::util::combineStrings(lines, "\n");
};
TextEditor::ErrorMarkers errorMarkers;
if (!(*m_callStack)->empty()) {
for (const auto &frame : **m_callStack | std::views::reverse) {
auto location = frame->getLocation();
std::string message;
if (location.source->source == pl::api::Source::DefaultSource) {
if (m_lastEvaluationError->has_value())
message = processMessage((*m_lastEvaluationError)->message);
auto key = TextEditor::Coordinates(location.line, location.column);
errorMarkers[key] = std::make_pair(location.length, message);
}
}
}
if (!m_lastCompileError->empty()) {
for (const auto &error : *m_lastCompileError) {
auto source = error.getLocation().source;
if (source != nullptr && source->source == pl::api::Source::DefaultSource) {
auto key = TextEditor::Coordinates(error.getLocation().line, error.getLocation().column);
if (!errorMarkers.contains(key) ||errorMarkers[key].first < error.getLocation().length)
errorMarkers[key] = std::make_pair(error.getLocation().length,processMessage(error.getMessage()));
}
}
}
m_textEditor.SetErrorMarkers(errorMarkers);
} else {
for (auto &[name, variable] : *m_patternVariables) {
if (variable.outVariable && m_lastEvaluationOutVars->contains(name))
variable.value = m_lastEvaluationOutVars->at(name);
}
EventHighlightingChanged::post();
}
m_lastEvaluationProcessed = true;
*m_executionDone = true;
}
if (m_shouldAnalyze) {
m_shouldAnalyze = false;
m_analysisTask = TaskManager::createBackgroundTask("hex.builtin.task.analyzing_data"_lang, [this, provider](const Task &task) {
if (!m_autoLoadPatterns)
return;
pl::PatternLanguage runtime;
ContentRegistry::PatternLanguage::configureRuntime(runtime, provider);
bool foundCorrectType = false;
auto mimeType = magic::getMIMEType(provider, 0, 100_KiB, true);
runtime.addPragma("MIME", [&mimeType, &foundCorrectType](const pl::PatternLanguage &runtime, const std::string &value) {
hex::unused(runtime);
if (!magic::isValidMIMEType(value))
return false;
if (value == mimeType) {
foundCorrectType = true;
return true;
}
return !std::ranges::all_of(value, isspace) && !value.ends_with('\n') && !value.ends_with('\r');
});
// Format: [ AA BB CC DD ] @ 0x12345678
runtime.addPragma("magic", [provider, &foundCorrectType](pl::PatternLanguage &, const std::string &value) -> bool {
const auto pattern = [value = value] mutable -> std::optional<BinaryPattern> {
value = wolv::util::trim(value);
if (value.empty())
return std::nullopt;
if (!value.starts_with('['))
return std::nullopt;
value = value.substr(1);
const auto end = value.find(']');
if (end == std::string::npos)
return std::nullopt;
value.resize(end);
//value = value.substr(0, end);
value = wolv::util::trim(value);
return BinaryPattern(value);
}();
const auto address = [value = value] mutable -> std::optional<u64> {
value = wolv::util::trim(value);
if (value.empty())
return std::nullopt;
const auto start = value.find('@');
if (start == std::string::npos)
return std::nullopt;
value = value.substr(start + 1);
value = wolv::util::trim(value);
size_t end = 0;
auto result = std::stoull(value, &end, 0);
if (end != value.length())
return std::nullopt;
return result;
}();
if (!address)
return false;
if (!pattern)
return false;
std::vector<u8> bytes(pattern->getSize());
if (bytes.empty())
return false;
provider->read(*address, bytes.data(), bytes.size());
if (pattern->matches(bytes))
foundCorrectType = true;
return true;
});
std::string author;
runtime.addPragma("author", [&author](pl::PatternLanguage &, const std::string &value) -> bool {
author = value;
return true;
});
std::string description;
runtime.addPragma("description", [&description](pl::PatternLanguage &, const std::string &value) -> bool {
description = value;
return true;
});
m_possiblePatternFiles.get(provider).clear();
bool popupOpen = false;
std::error_code errorCode;
for (const auto &dir : paths::Patterns.read()) {
for (auto &entry : std::fs::recursive_directory_iterator(dir, errorCode)) {
task.update();
foundCorrectType = false;
if (!entry.is_regular_file())
continue;
wolv::io::File file(entry.path(), wolv::io::File::Mode::Read);
if (!file.isValid())
continue;
author.clear();
description.clear();
auto result = runtime.preprocessString(file.readString(), pl::api::Source::DefaultSource);
if (!result.has_value()) {
log::warn("Failed to preprocess file {} during MIME analysis", entry.path().string());
}
if (foundCorrectType) {
{
std::scoped_lock lock(m_possiblePatternFilesMutex);
m_possiblePatternFiles.get(provider).emplace_back(
entry.path(),
std::move(author),
std::move(description)
);
}
if (!popupOpen) {
PopupAcceptPattern::open(this);
popupOpen = true;
}
}
runtime.reset();
}
}
});
}
}
void ViewPatternEditor::drawPatternTooltip(pl::ptrn::Pattern *pattern) {
ImGui::PushID(pattern);
{
const bool shiftHeld = ImGui::GetIO().KeyShift;
ImGui::ColorButton(pattern->getVariableName().c_str(), ImColor(pattern->getColor()));
ImGui::SameLine(0, 10);
ImGuiExt::TextFormattedColored(TextEditor::GetPalette()[u32(TextEditor::PaletteIndex::KnownIdentifier)], "{} ", pattern->getFormattedName());
ImGui::SameLine(0, 5);
ImGuiExt::TextFormatted("{}", pattern->getDisplayName());
ImGui::SameLine();
ImGui::SeparatorEx(ImGuiSeparatorFlags_Vertical);
ImGui::SameLine();
ImGuiExt::TextFormatted("{: <{}} ", hex::limitStringLength(pattern->getFormattedValue(), 64), shiftHeld ? 40 : 0);
if (shiftHeld) {
ImGui::Indent();
if (ImGui::BeginTable("##extra_info", 2, ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersInnerV | ImGuiTableFlags_NoClip)) {
ImGui::TableNextRow();
ImGui::TableNextColumn();
ImGui::TableNextRow();
ImGui::TableNextColumn();
ImGuiExt::TextFormatted("{} ", "hex.ui.common.path"_lang);
ImGui::TableNextColumn();
std::string path;
{
std::vector<std::string> pathSegments;
const pl::ptrn::Pattern *entry = pattern;
while (entry != nullptr) {
pathSegments.push_back(entry->getVariableName());
entry = entry->getParent();
}
for (const auto &segment : pathSegments | std::views::reverse) {
if (!segment.starts_with('['))
path += '.';
path += segment;
}
if (path.starts_with('.'))
path = path.substr(1);
}
ImGui::Indent();
ImGui::PushTextWrapPos(500_scaled);
ImGuiExt::TextFormattedWrapped("{}", path);
ImGui::PopTextWrapPos();
ImGui::Unindent();
ImGui::TableNextRow();
ImGui::TableNextColumn();
ImGuiExt::TextFormatted("{} ", "hex.ui.common.type"_lang);
ImGui::TableNextColumn();
ImGui::Indent();
ImGuiExt::TextFormatted("{}", pattern->getFormattedName());
ImGui::Unindent();
ImGui::TableNextRow();
ImGui::TableNextColumn();
ImGuiExt::TextFormatted("{} ", "hex.ui.common.address"_lang);
ImGui::TableNextColumn();
ImGui::Indent();
ImGuiExt::TextFormatted("0x{:08X}", pattern->getOffset());
ImGui::Unindent();
ImGui::TableNextRow();
ImGui::TableNextColumn();
ImGuiExt::TextFormatted("{} ", "hex.ui.common.size"_lang);
ImGui::TableNextColumn();
ImGui::Indent();
ImGuiExt::TextFormatted("{}", hex::toByteString(pattern->getSize()));
ImGui::Unindent();
{
const auto provider = ImHexApi::Provider::get();
const auto baseAddress = provider != nullptr ? provider->getBaseAddress() : 0x00;
const auto parent = pattern->getParent();
const auto parentAddress = parent == nullptr ? baseAddress : parent->getOffset();
const auto parentSize = parent == nullptr ? baseAddress : parent->getSize();
const auto patternAddress = pattern->getOffset();
if (patternAddress >= parentAddress && patternAddress + pattern->getSize() <= parentAddress + parentSize) {
ImGui::TableNextRow();
ImGui::TableNextColumn();
ImGuiExt::TextFormatted("{} ", "hex.builtin.view.pattern_editor.tooltip.parent_offset"_lang);
ImGui::TableNextColumn();
ImGui::Indent();
ImGuiExt::TextFormatted("0x{:02X}", pattern->getOffset() - parentAddress);
ImGui::Unindent();
}
}
ImGui::TableNextRow();
ImGui::TableNextColumn();
ImGuiExt::TextFormatted("{} ", "hex.ui.common.endian"_lang);
ImGui::TableNextColumn();
ImGui::Indent();
ImGuiExt::TextFormatted("{}", pattern->getEndian() == std::endian::little ? "hex.ui.common.little"_lang : "hex.ui.common.big"_lang);
ImGui::Unindent();
if (const auto &comment = pattern->getComment(); !comment.empty()) {
ImGui::TableNextRow();
ImGui::TableNextColumn();
ImGuiExt::TextFormatted("{} ", "hex.ui.common.comment"_lang);
ImGui::TableNextColumn();
ImGui::Indent();
ImGuiExt::TextFormattedWrapped("\"{}\"", comment);
ImGui::Unindent();
}
ImGui::EndTable();
}
ImGui::Unindent();
}
}
ImGui::PopID();
}
void ViewPatternEditor::loadPatternFile(const std::fs::path &path, prv::Provider *provider) {
wolv::io::File file(path, wolv::io::File::Mode::Read);
if (file.isValid()) {
auto code = file.readString();
this->evaluatePattern(code, provider);
m_textEditor.SetText(code);
m_sourceCode.set(provider, code);
TaskManager::createBackgroundTask("hex.builtin.task.parsing_pattern"_lang, [this, code, provider](auto&) { this->parsePattern(code, provider); });
}
}
void ViewPatternEditor::parsePattern(const std::string &code, prv::Provider *provider) {
m_runningParsers += 1;
ContentRegistry::PatternLanguage::configureRuntime(*m_editorRuntime, nullptr);
const auto &ast = m_editorRuntime->parseString(code, pl::api::Source::DefaultSource);
auto &patternVariables = m_patternVariables.get(provider);
auto oldPatternVariables = std::move(patternVariables);
if (ast.has_value()) {
for (auto &node : *ast) {
if (const auto variableDecl = dynamic_cast<pl::core::ast::ASTNodeVariableDecl *>(node.get())) {
const auto type = variableDecl->getType().get();
if (type == nullptr) continue;
const auto builtinType = dynamic_cast<pl::core::ast::ASTNodeBuiltinType *>(type->getType().get());
if (builtinType == nullptr)
continue;
const PatternVariable variable = {
.inVariable = variableDecl->isInVariable(),
.outVariable = variableDecl->isOutVariable(),
.type = builtinType->getType(),
.value = oldPatternVariables.contains(variableDecl->getName()) ? oldPatternVariables[variableDecl->getName()].value : pl::core::Token::Literal()
};
if (variable.inVariable || variable.outVariable) {
if (!patternVariables.contains(variableDecl->getName()))
patternVariables[variableDecl->getName()] = variable;
}
}
}
} else {
patternVariables = std::move(oldPatternVariables);
}
m_runningParsers -= 1;
}
void ViewPatternEditor::evaluatePattern(const std::string &code, prv::Provider *provider) {
EventPatternEvaluating::post();
auto lock = std::scoped_lock(ContentRegistry::PatternLanguage::getRuntimeLock());
m_runningEvaluators += 1;
*m_executionDone = false;
m_textEditor.SetErrorMarkers({});
m_console->clear();
m_consoleNeedsUpdate = true;
m_sectionWindowDrawer.clear();
m_consoleEditor.SetText("");
m_virtualFiles->clear();
m_accessHistory = {};
m_accessHistoryIndex = 0;
EventHighlightingChanged::post();
TaskManager::createTask("hex.builtin.view.pattern_editor.evaluating"_lang, TaskManager::NoProgress, [this, code, provider](auto &task) {
auto lock = std::scoped_lock(ContentRegistry::PatternLanguage::getRuntimeLock());
auto &runtime = ContentRegistry::PatternLanguage::getRuntime();
ContentRegistry::PatternLanguage::configureRuntime(runtime, provider);
runtime.getInternals().evaluator->setBreakpointHitCallback([this]{
m_debuggerScopeIndex = 0;
*m_breakpointHit = true;
m_resetDebuggerVariables = true;
while (*m_breakpointHit) {
std::this_thread::sleep_for(std::chrono::milliseconds(100LL));
}
});
task.setInterruptCallback([this, &runtime] {
m_breakpointHit = false;
runtime.abort();
});
std::map<std::string, pl::core::Token::Literal> envVars;
for (const auto &[id, name, value, type] : *m_envVarEntries)
envVars.insert({ name, value });
std::map<std::string, pl::core::Token::Literal> inVariables;
for (auto &[name, variable] : *m_patternVariables) {
if (variable.inVariable)
inVariables[name] = variable.value;
}
runtime.setDangerousFunctionCallHandler([this]{
m_dangerousFunctionCalled = true;
while (m_dangerousFunctionsAllowed == DangerousFunctionPerms::Ask) {
std::this_thread::sleep_for(std::chrono::milliseconds(100LL));
}
return m_dangerousFunctionsAllowed == DangerousFunctionPerms::Allow;
});
runtime.setLogCallback([this](auto level, auto message) {
std::scoped_lock lock(m_logMutex);
for (auto line : wolv::util::splitString(message, "\n")) {
if (!wolv::util::trim(line).empty()) {
switch (level) {
using enum pl::core::LogConsole::Level;
case Debug: line = hex::format("D: {}", line); break;
case Info: line = hex::format("I: {}", line); break;
case Warning: line = hex::format("W: {}", line); break;
case Error: line = hex::format("E: {}", line); break;
default: break;
}
}
m_console->emplace_back(line);
m_consoleNeedsUpdate = true;
}
});
ON_SCOPE_EXIT {
runtime.getInternals().evaluator->setDebugMode(false);
*m_lastEvaluationOutVars = runtime.getOutVariables();
*m_sections = runtime.getSections();
m_runningEvaluators -= 1;
m_lastEvaluationProcessed = false;
std::scoped_lock lock(m_logMutex);
m_console->emplace_back(
hex::format("I: Evaluation took {}", std::chrono::duration<double>(runtime.getLastRunningTime()))
);
m_consoleNeedsUpdate = true;
};
m_lastEvaluationResult = runtime.executeString(code, pl::api::Source::DefaultSource, envVars, inVariables);
if (!m_lastEvaluationResult) {
*m_lastEvaluationError = runtime.getEvalError();
*m_lastCompileError = runtime.getCompileErrors();
*m_callStack = &runtime.getInternals().evaluator->getCallStack();
}
TaskManager::doLater([code] {
EventPatternExecuted::post(code);
});
});
}
void ViewPatternEditor::registerEvents() {
RequestPatternEditorSelectionChange::subscribe(this, [this](u32 line, u32 column) {
const TextEditor::Coordinates coords = { int(line) - 1, int(column) };
m_textEditor.SetCursorPosition(coords);
});
RequestLoadPatternLanguageFile::subscribe(this, [this](const std::fs::path &path) {
this->loadPatternFile(path, ImHexApi::Provider::get());
});
RequestRunPatternCode::subscribe(this, [this] {
m_triggerAutoEvaluate = true;
});
RequestSavePatternLanguageFile::subscribe(this, [this](const std::fs::path &path) {
wolv::io::File file(path, wolv::io::File::Mode::Create);
file.writeString(wolv::util::trim(m_textEditor.GetText()));
});
RequestSetPatternLanguageCode::subscribe(this, [this](const std::string &code) {
m_textEditor.SetText(code);
m_sourceCode.set(ImHexApi::Provider::get(), code);
m_hasUnevaluatedChanges = true;
});
ContentRegistry::Settings::onChange("hex.builtin.setting.general", "hex.builtin.setting.general.sync_pattern_source", [this](const ContentRegistry::Settings::SettingsValue &value) {
m_sourceCode.enableSync(value.get<bool>(false));
});
ContentRegistry::Settings::onChange("hex.builtin.setting.general", "hex.builtin.setting.general.auto_load_patterns", [this](const ContentRegistry::Settings::SettingsValue &value) {
m_autoLoadPatterns = value.get<bool>(true);
});
EventProviderOpened::subscribe(this, [this](prv::Provider *provider) {
m_shouldAnalyze.get(provider) = true;
m_envVarEntries->emplace_back(0, "", i128(0), EnvVarType::Integer);
m_debuggerDrawer.get(provider) = std::make_unique<ui::PatternDrawer>();
m_cursorPosition.get(provider) = TextEditor::Coordinates(0, 0);
});
EventProviderChanged::subscribe(this, [this](prv::Provider *oldProvider, prv::Provider *newProvider) {
if (oldProvider != nullptr) {
m_sourceCode.set(oldProvider, m_textEditor.GetText());
m_cursorPosition.set(m_textEditor.GetCursorPosition(),oldProvider);
}
if (newProvider != nullptr) {
m_textEditor.SetText(m_sourceCode.get(newProvider));
m_textEditor.SetCursorPosition(m_cursorPosition.get(newProvider));
} else
m_textEditor.SetText("");
});
RequestAddVirtualFile::subscribe(this, [this](const std::fs::path &path, const std::vector<u8> &data, Region region) {
m_virtualFiles->emplace_back(path, data, region);
});
}
static void createNestedMenu(const std::vector<std::string> &menus, const std::function<void()> &function) {
if (menus.empty())
return;
if (menus.size() == 1) {
if (ImGui::MenuItem(menus.front().c_str()))
function();
} else {
if (ImGui::BeginMenu(menus.front().c_str())) {
createNestedMenu({ menus.begin() + 1, menus.end() }, function);
ImGui::EndMenu();
}
}
}
void ViewPatternEditor::appendEditorText(const std::string &text) {
m_textEditor.SetCursorPosition(TextEditor::Coordinates { m_textEditor.GetTotalLines(), 0 });
m_textEditor.InsertText(hex::format("\n{0}", text));
m_triggerEvaluation = true;
}
void ViewPatternEditor::appendVariable(const std::string &type) {
const auto &selection = ImHexApi::HexEditor::getSelection();
appendEditorText(hex::format("{0} {0}_at_0x{1:02X} @ 0x{1:02X};", type, selection->getStartAddress()));
AchievementManager::unlockAchievement("hex.builtin.achievement.patterns", "hex.builtin.achievement.patterns.place_menu.name");
}
void ViewPatternEditor::appendArray(const std::string &type, size_t size) {
const auto &selection = ImHexApi::HexEditor::getSelection();
appendEditorText(hex::format("{0} {0}_array_at_0x{1:02X}[0x{2:02X}] @ 0x{1:02X};", type, selection->getStartAddress(), (selection->getSize() + (size - 1)) / size));
}
TextEditor *ViewPatternEditor::getEditorFromFocusedWindow() {
if (m_focusedSubWindowName.contains(consoleView)) {
return &m_consoleEditor;
}
if (m_focusedSubWindowName.contains(textEditorView)) {
return &m_textEditor;
}
return nullptr;
}
void ViewPatternEditor::registerMenuItems() {
/* Import Pattern */
ContentRegistry::Interface::addMenuItem({ "hex.builtin.menu.file", "hex.builtin.menu.file.import", "hex.builtin.menu.file.import.pattern" }, ICON_VS_FILE_CODE, 4050, Shortcut::None,
m_importPatternFile, ImHexApi::Provider::isValid);
/* Export Pattern */
ContentRegistry::Interface::addMenuItem({ "hex.builtin.menu.file", "hex.builtin.menu.file.export", "hex.builtin.menu.file.export.pattern" }, ICON_VS_FILE_CODE, 7050, Shortcut::None,
m_exportPatternFile, [this] {
return !wolv::util::trim(m_textEditor.GetText()).empty() && ImHexApi::Provider::isValid();
}
);
constexpr static std::array<std::pair<const char *, size_t>, 21> Types = {{
{ "u8", 1 }, { "u16", 2 }, { "u24", 3 }, { "u32", 4 }, { "u48", 6 }, { "u64", 8 }, { "u96", 12 }, { "u128", 16 },
{ "s8", 1 }, { "s16", 2 }, { "s24", 3 }, { "s32", 4 }, { "s48", 6 }, { "s64", 8 }, { "s96", 12 }, { "s128", 16 },
{ "float", 4 }, { "double", 8 },
{ "bool", 1 }, { "char", 1 }, { "char16", 2 }
}};
/* Place pattern... */
ContentRegistry::Interface::addMenuItemSubMenu({ "hex.builtin.menu.edit", "hex.builtin.view.pattern_editor.menu.edit.place_pattern" }, ICON_VS_LIBRARY, 3000,
[&, this] {
if (ImGui::BeginMenu("hex.builtin.view.pattern_editor.menu.edit.place_pattern.builtin"_lang)) {
if (ImGui::BeginMenu("hex.builtin.view.pattern_editor.menu.edit.place_pattern.builtin.single"_lang)) {
for (const auto &[type, size] : Types) {
if (ImGui::MenuItem(type))
appendVariable(type);
}
ImGui::EndMenu();
}
if (ImGui::BeginMenu("hex.builtin.view.pattern_editor.menu.edit.place_pattern.builtin.array"_lang)) {
for (const auto &[type, size] : Types) {
if (ImGui::MenuItem(type))
appendArray(type, size);
}
ImGui::EndMenu();
}
ImGui::EndMenu();
}
const auto &types = m_editorRuntime->getInternals().parser->getTypes();
const bool hasPlaceableTypes = std::ranges::any_of(types, [](const auto &type) { return !type.second->isTemplateType(); });
if (ImGui::BeginMenu("hex.builtin.view.pattern_editor.menu.edit.place_pattern.custom"_lang, hasPlaceableTypes)) {
const auto &selection = ImHexApi::HexEditor::getSelection();
for (const auto &[typeName, type] : types) {
if (type->isTemplateType())
continue;
createNestedMenu(hex::splitString(typeName, "::"), [&, this] {
std::string variableName;
for (const char c : hex::replaceStrings(typeName, "::", "_"))
variableName += static_cast<char>(std::tolower(c));
variableName += hex::format("_at_0x{:02X}", selection->getStartAddress());
appendEditorText(hex::format("{0} {1} @ 0x{2:02X};", typeName, variableName, selection->getStartAddress()));
});
}
ImGui::EndMenu();
}
}, [this] {
return ImHexApi::Provider::isValid() && ImHexApi::HexEditor::isSelectionValid() && m_runningParsers == 0;
});
}
void ViewPatternEditor::registerHandlers() {
ContentRegistry::FileHandler::add({ ".hexpat", ".pat" }, [](const std::fs::path &path) -> bool {
wolv::io::File file(path, wolv::io::File::Mode::Read);
if (file.isValid()) {
RequestSetPatternLanguageCode::post(file.readString());
return true;
} else {
return false;
}
});
ContentRegistry::Settings::onChange("hex.builtin.setting.hex_editor", "hex.builtin.setting.hex_editor.pattern_parent_highlighting", [this](const ContentRegistry::Settings::SettingsValue &value) {
m_parentHighlightingEnabled = bool(value.get<int>(false));
});
ImHexApi::HexEditor::addBackgroundHighlightingProvider([this](u64 address, const u8 *data, size_t size, bool) -> std::optional<color_t> {
hex::unused(data, size);
if (m_runningEvaluators != 0)
return std::nullopt;
const auto &runtime = ContentRegistry::PatternLanguage::getRuntime();
std::optional<ImColor> color;
if (TRY_LOCK(ContentRegistry::PatternLanguage::getRuntimeLock())) {
for (const auto &patternColor : runtime.getColorsAtAddress(address)) {
if (color.has_value())
color = ImAlphaBlendColors(*color, patternColor);
else
color = patternColor;
}
}
return color;
});
ImHexApi::HexEditor::addHoverHighlightProvider([this](const prv::Provider *, u64 address, size_t size) {
std::set<Region> result;
if (!m_parentHighlightingEnabled)
return result;
const auto &runtime = ContentRegistry::PatternLanguage::getRuntime();
const auto hoveredRegion = Region { address, size };
for (const auto &pattern : runtime.getPatternsAtAddress(hoveredRegion.getStartAddress())) {
const pl::ptrn::Pattern * checkPattern = pattern;
if (auto parent = checkPattern->getParent(); parent != nullptr)
checkPattern = parent;
result.emplace(checkPattern->getOffset(), checkPattern->getSize());
}
return result;
});
ImHexApi::HexEditor::addTooltipProvider([this](u64 address, const u8 *data, size_t size) {
hex::unused(data, size);
if (TRY_LOCK(ContentRegistry::PatternLanguage::getRuntimeLock())) {
const auto &runtime = ContentRegistry::PatternLanguage::getRuntime();
auto patterns = runtime.getPatternsAtAddress(address);
if (!patterns.empty() && !std::ranges::all_of(patterns, [](const auto &pattern) { return pattern->getVisibility() == pl::ptrn::Visibility::Hidden; })) {
ImGui::BeginTooltip();
for (const auto &pattern : patterns) {
if (pattern->getVisibility() != pl::ptrn::Visibility::Visible)
continue;
const auto tooltipColor = (pattern->getColor() & 0x00FF'FFFF) | 0x7000'0000;
ImGui::PushID(pattern);
if (ImGui::BeginTable("##tooltips", 1, ImGuiTableFlags_RowBg | ImGuiTableFlags_NoClip)) {
ImGui::TableNextRow();
ImGui::TableNextColumn();
this->drawPatternTooltip(pattern);
ImGui::PushStyleColor(ImGuiCol_TableRowBg, tooltipColor);
ImGui::PushStyleColor(ImGuiCol_TableRowBgAlt, tooltipColor);
ImGui::EndTable();
ImGui::PopStyleColor(2);
}
ImGui::PopID();
}
ImGui::EndTooltip();
}
}
});
ProjectFile::registerPerProviderHandler({
.basePath = "pattern_source_code.hexpat",
.required = false,
.load = [this](prv::Provider *provider, const std::fs::path &basePath, const Tar &tar) {
const auto sourceCode = tar.readString(basePath);
m_sourceCode.set(provider, sourceCode);
if (provider == ImHexApi::Provider::get())
m_textEditor.SetText(sourceCode);
m_hasUnevaluatedChanges = true;
return true;
},
.store = [this](prv::Provider *provider, const std::fs::path &basePath, const Tar &tar) {
if (provider == ImHexApi::Provider::get())
m_sourceCode.set(provider, m_textEditor.GetText());
const auto &sourceCode = m_sourceCode.get(provider);
tar.writeString(basePath, wolv::util::trim(sourceCode));
return true;
}
});
ShortcutManager::addShortcut(this, CTRL + Keys::F + AllowWhileTyping, "hex.builtin.view.pattern_editor.shortcut.find", [this] {
m_openFindReplacePopUp = true;
m_replaceMode = false;
});
ShortcutManager::addShortcut(this, CTRL + Keys::H + AllowWhileTyping, "hex.builtin.view.pattern_editor.shortcut.replace", [this] {
if (m_focusedSubWindowName.contains(textEditorView)) {
m_openFindReplacePopUp = true;
m_replaceMode = true;
}
});
ShortcutManager::addShortcut(this, Keys::F3 + AllowWhileTyping, "hex.builtin.view.pattern_editor.shortcut.find_next", [this] {
if (auto editor = getEditorFromFocusedWindow(); editor != nullptr) {
TextEditor::FindReplaceHandler *findReplaceHandler = editor->GetFindReplaceHandler();
findReplaceHandler->FindMatch(editor, true);
}
});
ShortcutManager::addShortcut(this, SHIFT + Keys::F3 + AllowWhileTyping, "hex.builtin.view.pattern_editor.shortcut.find_previous", [this] {
if (auto editor = getEditorFromFocusedWindow(); editor != nullptr) {
TextEditor::FindReplaceHandler *findReplaceHandler = editor->GetFindReplaceHandler();
findReplaceHandler->FindMatch(editor, false);
}
});
ShortcutManager::addShortcut(this, ALT + Keys::C + AllowWhileTyping, "hex.builtin.view.pattern_editor.shortcut.match_case_toggle", [this] {
if (auto editor = getEditorFromFocusedWindow(); editor != nullptr) {
TextEditor::FindReplaceHandler *findReplaceHandler = editor->GetFindReplaceHandler();
findReplaceHandler->SetMatchCase(editor, !findReplaceHandler->GetMatchCase());
}
});
ShortcutManager::addShortcut(this, ALT + Keys::R + AllowWhileTyping, "hex.builtin.view.pattern_editor.shortcut.regex_toggle", [this] {
if (auto editor = getEditorFromFocusedWindow(); editor != nullptr) {
TextEditor::FindReplaceHandler *findReplaceHandler = editor->GetFindReplaceHandler();
findReplaceHandler->SetFindRegEx(editor, !findReplaceHandler->GetFindRegEx());
}
});
ShortcutManager::addShortcut(this, ALT + Keys::W + AllowWhileTyping, "hex.builtin.view.pattern_editor.shortcut.whole_word_toggle", [this] {
if (auto editor = getEditorFromFocusedWindow(); editor != nullptr) {
TextEditor::FindReplaceHandler *findReplaceHandler = editor->GetFindReplaceHandler();
findReplaceHandler->SetWholeWord(editor, !findReplaceHandler->GetWholeWord());
}
});
ShortcutManager::addShortcut(this, ALT + Keys::S + AllowWhileTyping, "hex.builtin.view.pattern_editor.shortcut.save_project", [] {
hex::plugin::builtin::saveProject();
});
ShortcutManager::addShortcut(this, ALT + Keys::O + AllowWhileTyping, "hex.builtin.view.pattern_editor.shortcut.open_project", [] {
hex::plugin::builtin::openProject();
});
ShortcutManager::addShortcut(this, ALT + SHIFT + Keys::S + AllowWhileTyping, "hex.builtin.view.pattern_editor.shortcut.save_project_as", [] {
hex::plugin::builtin::saveProjectAs();
});
// ShortcutManager::addShortcut(this, CTRL + Keys::Insert + AllowWhileTyping, "hex.builtin.view.pattern_editor.shortcut.copy", [this] {
// m_textEditor.Copy();
// });
ShortcutManager::addShortcut(this, CTRL + Keys::C + AllowWhileTyping, "hex.builtin.view.pattern_editor.shortcut.copy", [this] {
if (auto editor = getEditorFromFocusedWindow(); editor != nullptr)
editor->Copy();
});
// ShortcutManager::addShortcut(this, SHIFT + Keys::Insert + AllowWhileTyping, "hex.builtin.view.pattern_editor.shortcut.paste", [this] {
// m_textEditor.Paste();
// });
ShortcutManager::addShortcut(this, CTRL + Keys::V + AllowWhileTyping, "hex.builtin.view.pattern_editor.shortcut.paste", [this] {
if (m_focusedSubWindowName.contains(textEditorView))
m_textEditor.Paste();
});
ShortcutManager::addShortcut(this, CTRL + Keys::X + AllowWhileTyping, "hex.builtin.view.pattern_editor.shortcut.cut", [this] {
if (m_focusedSubWindowName.contains(textEditorView))
m_textEditor.Cut();
});
// ShortcutManager::addShortcut(this, SHIFT + Keys::Delete + AllowWhileTyping, "hex.builtin.view.pattern_editor.shortcut.cut", [this] {
// m_textEditor.Cut();
// });
ShortcutManager::addShortcut(this, CTRL + Keys::Z + AllowWhileTyping, "hex.builtin.view.pattern_editor.shortcut.undo", [this] {
if (m_focusedSubWindowName.contains(textEditorView))
m_textEditor.Undo();
});
// ShortcutManager::addShortcut(this, ALT + Keys::Backspace + AllowWhileTyping, "hex.builtin.view.pattern_editor.shortcut.undo", [this] {
// m_textEditor.Undo();
// });
ShortcutManager::addShortcut(this, Keys::Delete + AllowWhileTyping, "hex.builtin.view.pattern_editor.shortcut.delete", [this] {
if (m_focusedSubWindowName.contains(textEditorView))
m_textEditor.Delete();
});
ShortcutManager::addShortcut(this, CTRL + Keys::Y + AllowWhileTyping, "hex.builtin.view.pattern_editor.shortcut.redo", [this] {
if (m_focusedSubWindowName.contains(textEditorView))
m_textEditor.Redo();
});
ShortcutManager::addShortcut(this, CTRL + Keys::A + AllowWhileTyping, "hex.builtin.view.pattern_editor.shortcut.select_all", [this] {
if (auto editor = getEditorFromFocusedWindow(); editor != nullptr)
editor->SelectAll();
});
ShortcutManager::addShortcut(this, SHIFT + Keys::Right + AllowWhileTyping, "hex.builtin.view.pattern_editor.shortcut.select_right", [this] {
if (auto editor = getEditorFromFocusedWindow(); editor != nullptr)
editor->MoveRight(1, true, false);
});
ShortcutManager::addShortcut(this, CTRL + SHIFT + Keys::Right + AllowWhileTyping, "hex.builtin.view.pattern_editor.shortcut.select_word_right", [this] {
if (auto editor = getEditorFromFocusedWindow(); editor != nullptr)
editor->MoveRight(1, true, true);
});
ShortcutManager::addShortcut(this, SHIFT + Keys::Left + AllowWhileTyping, "hex.builtin.view.pattern_editor.shortcut.select_left", [this] {
if (auto editor = getEditorFromFocusedWindow(); editor != nullptr)
editor->MoveLeft(1, true, false);
});
ShortcutManager::addShortcut(this, CTRL + SHIFT + Keys::Left + AllowWhileTyping, "hex.builtin.view.pattern_editor.shortcut.select_word_left", [this] {
if (auto editor = getEditorFromFocusedWindow(); editor != nullptr)
editor->MoveLeft(1, true, true);
});
ShortcutManager::addShortcut(this, SHIFT + Keys::Up + AllowWhileTyping, "hex.builtin.view.pattern_editor.shortcut.select_up", [this] {
if (auto editor = getEditorFromFocusedWindow(); editor != nullptr)
editor->MoveUp(1, true);
});
ShortcutManager::addShortcut(this, SHIFT +Keys::PageUp + AllowWhileTyping, "hex.builtin.view.pattern_editor.shortcut.select_page_up", [this] {
if (auto editor = getEditorFromFocusedWindow(); editor != nullptr)
editor->MoveUp(editor->GetPageSize()-4, true);
});
ShortcutManager::addShortcut(this, SHIFT + Keys::Down + AllowWhileTyping, "hex.builtin.view.pattern_editor.shortcut.select_down", [this] {
if (auto editor = getEditorFromFocusedWindow(); editor != nullptr)
editor->MoveDown(1, true);
});
ShortcutManager::addShortcut(this, SHIFT +Keys::PageDown + AllowWhileTyping, "hex.builtin.view.pattern_editor.shortcut.select_page_down", [this] {
if (auto editor = getEditorFromFocusedWindow(); editor != nullptr)
editor->MoveDown(editor->GetPageSize()-4, true);
});
ShortcutManager::addShortcut(this, CTRL + SHIFT + Keys::Home + AllowWhileTyping, "hex.builtin.view.pattern_editor.shortcut.select_top", [this] {
if (auto editor = getEditorFromFocusedWindow(); editor != nullptr)
editor->MoveTop(true);
});
ShortcutManager::addShortcut(this, CTRL + SHIFT + Keys::End + AllowWhileTyping, "hex.builtin.view.pattern_editor.shortcut.select_bottom", [this] {
if (auto editor = getEditorFromFocusedWindow(); editor != nullptr)
editor->MoveBottom(true);
});
ShortcutManager::addShortcut(this, SHIFT + Keys::Home + AllowWhileTyping, "hex.builtin.view.pattern_editor.shortcut.select_home", [this] {
if (auto editor = getEditorFromFocusedWindow(); editor != nullptr)
editor->MoveHome(true);
});
ShortcutManager::addShortcut(this, SHIFT + Keys::End + AllowWhileTyping, "hex.builtin.view.pattern_editor.shortcut.select_end", [this] {
if (auto editor = getEditorFromFocusedWindow(); editor != nullptr)
editor->MoveEnd(true);
});
ShortcutManager::addShortcut(this, CTRL + Keys::Delete + AllowWhileTyping, "hex.builtin.view.pattern_editor.shortcut.delete_word_right", [this] {
if (m_focusedSubWindowName.contains(textEditorView))
m_textEditor.DeleteWordRight();
});
ShortcutManager::addShortcut(this, CTRL + Keys::Backspace + AllowWhileTyping, "hex.builtin.view.pattern_editor.shortcut.delete_word_left", [this] {
if (m_focusedSubWindowName.contains(textEditorView))
m_textEditor.DeleteWordLeft();
});
ShortcutManager::addShortcut(this, Keys::Backspace + AllowWhileTyping, "hex.builtin.view.pattern_editor.shortcut.backspace", [this] {
if (m_focusedSubWindowName.contains(textEditorView))
m_textEditor.Backspace();
});
ShortcutManager::addShortcut(this, Keys::Insert + AllowWhileTyping, "hex.builtin.view.pattern_editor.shortcut.toggle_insert", [this] {
if (m_focusedSubWindowName.contains(textEditorView))
m_textEditor.SetOverwrite(!m_textEditor.IsOverwrite());
});
ShortcutManager::addShortcut(this, CTRL + Keys::Right + AllowWhileTyping, "hex.builtin.view.pattern_editor.shortcut.move_word_right", [this] {
if (auto editor = getEditorFromFocusedWindow(); editor != nullptr)
editor->MoveRight(1, false, true);
});
ShortcutManager::addShortcut(this, Keys::Right + AllowWhileTyping, "hex.builtin.view.pattern_editor.shortcut.move_right", [this] {
if (auto editor = getEditorFromFocusedWindow(); editor != nullptr)
editor->MoveRight(1, false, false);
});
ShortcutManager::addShortcut(this, CTRL + Keys::Left + AllowWhileTyping, "hex.builtin.view.pattern_editor.shortcut.move_word_left", [this] {
if (auto editor = getEditorFromFocusedWindow(); editor != nullptr)
editor->MoveLeft(1, false, true);
});
ShortcutManager::addShortcut(this, Keys::Left + AllowWhileTyping, "hex.builtin.view.pattern_editor.shortcut.move_left", [this] {
if (auto editor = getEditorFromFocusedWindow(); editor != nullptr)
editor->MoveLeft(1, false, false);
});
ShortcutManager::addShortcut(this, Keys::Up + AllowWhileTyping, "hex.builtin.view.pattern_editor.shortcut.move_up", [this] {
if (auto editor = getEditorFromFocusedWindow(); editor != nullptr)
editor->MoveUp(1, false);
});
ShortcutManager::addShortcut(this, Keys::PageUp + AllowWhileTyping, "hex.builtin.view.pattern_editor.shortcut.move_page_up", [this] {
if (auto editor = getEditorFromFocusedWindow(); editor != nullptr)
editor->MoveUp(editor->GetPageSize()-4, false);
});
ShortcutManager::addShortcut(this, Keys::Down + AllowWhileTyping, "hex.builtin.view.pattern_editor.shortcut.move_down", [this] {
if (auto editor = getEditorFromFocusedWindow(); editor != nullptr)
editor->MoveDown(1, false);
});
ShortcutManager::addShortcut(this, Keys::PageDown + AllowWhileTyping, "hex.builtin.view.pattern_editor.shortcut.move_page_down", [this] {
if (auto editor = getEditorFromFocusedWindow(); editor != nullptr)
editor->MoveDown(editor->GetPageSize()-4, false);
});
ShortcutManager::addShortcut(this, CTRL + Keys::Home + AllowWhileTyping, "hex.builtin.view.pattern_editor.shortcut.move_top", [this] {
if (auto editor = getEditorFromFocusedWindow(); editor != nullptr)
editor->MoveTop(false);
});
ShortcutManager::addShortcut(this, CTRL + Keys::End + AllowWhileTyping, "hex.builtin.view.pattern_editor.shortcut.move_bottom", [this] {
if (auto editor = getEditorFromFocusedWindow(); editor != nullptr)
editor->MoveBottom(false);
});
ShortcutManager::addShortcut(this, Keys::Home + AllowWhileTyping, "hex.builtin.view.pattern_editor.shortcut.move_home", [this] {
if (auto editor = getEditorFromFocusedWindow(); editor != nullptr)
editor->MoveHome(false);
});
ShortcutManager::addShortcut(this, Keys::End + AllowWhileTyping, "hex.builtin.view.pattern_editor.shortcut.move_end", [this] {
if (auto editor = getEditorFromFocusedWindow(); editor != nullptr)
editor->MoveEnd(false);
});
ShortcutManager::addShortcut(this, Keys::F8 + AllowWhileTyping, "hex.builtin.view.pattern_editor.shortcut.add_breakpoint", [this] {
const auto line = m_textEditor.GetCursorPosition().mLine + 1;
const auto &runtime = ContentRegistry::PatternLanguage::getRuntime();
auto &evaluator = runtime.getInternals().evaluator;
auto &breakpoints = evaluator->getBreakpoints();
if (breakpoints.contains(line)) {
evaluator->removeBreakpoint(line);
} else {
evaluator->addBreakpoint(line);
}
m_textEditor.SetBreakpoints(breakpoints);
});
/* Trigger evaluation */
ShortcutManager::addGlobalShortcut(Keys::F5 + AllowWhileTyping, "hex.builtin.view.pattern_editor.shortcut.run_pattern", [this] {
m_triggerAutoEvaluate = true;
});
/* Continue debugger */
ShortcutManager::addGlobalShortcut(SHIFT + Keys::F9 + AllowWhileTyping, "hex.builtin.view.pattern_editor.shortcut.continue_debugger", [this] {
const auto &runtime = ContentRegistry::PatternLanguage::getRuntime();
if (runtime.isRunning())
m_breakpointHit = false;
});
/* Step debugger */
ShortcutManager::addGlobalShortcut(SHIFT + Keys::F7 + AllowWhileTyping, "hex.builtin.view.pattern_editor.shortcut.step_debugger", [this] {
const auto &runtime = ContentRegistry::PatternLanguage::getRuntime();
if (runtime.isRunning()) {
runtime.getInternals().evaluator->pauseNextLine();
m_breakpointHit = false;
}
});
// Generate pattern code report
ContentRegistry::Reports::addReportProvider([this](prv::Provider *provider) -> std::string {
const auto &patternCode = m_sourceCode.get(provider);
if (wolv::util::trim(patternCode).empty())
return "";
std::string result;
result += "## Pattern Code\n\n";
result += "```cpp\n";
result += patternCode;
result += "\n```\n\n";
return result;
});
}
}
| 113,976
|
C++
|
.cpp
| 1,940
| 40.997423
| 331
| 0.542957
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
244
|
view_data_processor.cpp
|
WerWolv_ImHex/plugins/builtin/source/content/views/view_data_processor.cpp
|
#include "content/views/view_data_processor.hpp"
#include <toasts/toast_notification.hpp>
#include <hex/api/content_registry.hpp>
#include <hex/api/project_file_manager.hpp>
#include <hex/api/achievement_manager.hpp>
#include <hex/providers/provider.hpp>
#include <hex/helpers/logger.hpp>
#include <hex/helpers/default_paths.hpp>
#include <imnodes.h>
#include <imnodes_internal.h>
#include <nlohmann/json.hpp>
#include <wolv/io/file.hpp>
#include <wolv/utils/guards.hpp>
#include <wolv/utils/core.hpp>
namespace hex::plugin::builtin {
/**
* @brief Input node that can be used to add an input to a custom node
*/
class NodeCustomInput : public dp::Node {
public:
NodeCustomInput() : Node("hex.builtin.nodes.custom.input.header", { dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.common.input") }) { }
~NodeCustomInput() override = default;
void drawNode() override {
ImGui::PushItemWidth(100_scaled);
// Draw combo box to select the type of the input
if (ImGui::Combo("##type", &m_type, "Integer\0Float\0Buffer\0")) {
this->setAttributes({
{ dp::Attribute(dp::Attribute::IOType::Out, this->getType(), "hex.builtin.nodes.common.input") }
});
}
// Draw text input to set the name of the input
if (ImGui::InputText("##name", m_name)) {
this->setUnlocalizedTitle(m_name);
}
ImGui::PopItemWidth();
}
void setValue(auto value) { m_value = std::move(value); }
const std::string &getName() const { return m_name; }
dp::Attribute::Type getType() const {
switch (m_type) {
default:
case 0: return dp::Attribute::Type::Integer;
case 1: return dp::Attribute::Type::Float;
case 2: return dp::Attribute::Type::Buffer;
}
}
void process() override {
std::visit(wolv::util::overloaded {
[this](i128 value) { this->setIntegerOnOutput(0, value); },
[this](long double value) { this->setFloatOnOutput(0, value); },
[this](const std::vector<u8> &value) { this->setBufferOnOutput(0, value); }
}, m_value);
}
void store(nlohmann::json &j) const override {
j = nlohmann::json::object();
j["name"] = m_name;
j["type"] = m_type;
}
void load(const nlohmann::json &j) override {
m_name = j.at("name").get<std::string>();
m_type = j.at("type");
this->setUnlocalizedTitle(m_name);
this->setAttributes({
{ dp::Attribute(dp::Attribute::IOType::Out, this->getType(), "hex.builtin.nodes.common.input") }
});
}
private:
std::string m_name = Lang(this->getUnlocalizedName());
int m_type = 0;
std::variant<i128, long double, std::vector<u8>> m_value;
};
/**
* @brief Input node that can be used to add an output to a custom node
*/
class NodeCustomOutput : public dp::Node {
public:
NodeCustomOutput() : Node("hex.builtin.nodes.custom.output.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.common.output") }) { }
~NodeCustomOutput() override = default;
void drawNode() override {
ImGui::PushItemWidth(100_scaled);
// Draw combo box to select the type of the output
if (ImGui::Combo("##type", &m_type, "Integer\0Float\0Buffer\0")) {
this->setAttributes({
{ dp::Attribute(dp::Attribute::IOType::In, this->getType(), "hex.builtin.nodes.common.output") }
});
}
// Draw text input to set the name of the output
if (ImGui::InputText("##name", m_name)) {
this->setUnlocalizedTitle(m_name);
}
ImGui::PopItemWidth();
}
const std::string &getName() const { return m_name; }
dp::Attribute::Type getType() const {
switch (m_type) {
case 0: return dp::Attribute::Type::Integer;
case 1: return dp::Attribute::Type::Float;
case 2: return dp::Attribute::Type::Buffer;
default: return dp::Attribute::Type::Integer;
}
}
void process() override {
switch (this->getType()) {
case dp::Attribute::Type::Integer: m_value = this->getIntegerOnInput(0); break;
case dp::Attribute::Type::Float: m_value = static_cast<long double>(this->getFloatOnInput(0)); break;
case dp::Attribute::Type::Buffer: m_value = this->getBufferOnInput(0); break;
}
}
const auto& getValue() const { return m_value; }
void store(nlohmann::json &j) const override {
j = nlohmann::json::object();
j["name"] = m_name;
j["type"] = m_type;
}
void load(const nlohmann::json &j) override {
m_name = j.at("name").get<std::string>();
m_type = j.at("type");
this->setUnlocalizedTitle(m_name);
this->setAttributes({
{ dp::Attribute(dp::Attribute::IOType::In, this->getType(), "hex.builtin.nodes.common.output") }
});
}
private:
std::string m_name = Lang(this->getUnlocalizedName());
int m_type = 0;
std::variant<i128, long double, std::vector<u8>> m_value;
};
/**
* @brief Custom node that can be used to create custom data processing nodes
*/
class NodeCustom : public dp::Node {
public:
explicit NodeCustom(ViewDataProcessor *dataProcessor) : Node("hex.builtin.nodes.custom.custom.header", {}), m_dataProcessor(dataProcessor) { }
~NodeCustom() override = default;
void drawNode() override {
// Update attributes if we have to
if (m_requiresAttributeUpdate) {
m_requiresAttributeUpdate = false;
// Find all input and output nodes that are used by the workspace of this node
// and set the attributes of this node to the attributes of the input and output nodes
this->setAttributes(this->findAttributes());
}
ImGui::PushItemWidth(200_scaled);
bool editing = false;
if (m_editable) {
// Draw name input field
ImGuiExt::InputTextIcon("##name", ICON_VS_SYMBOL_KEY, m_name);
// Prevent editing mode from deactivating when the input field is focused
editing = ImGui::IsItemActive();
// Draw edit button
if (ImGui::Button("hex.builtin.nodes.custom.custom.edit"_lang, ImVec2(200_scaled, ImGui::GetTextLineHeightWithSpacing()))) {
AchievementManager::unlockAchievement("hex.builtin.achievement.data_processor", "hex.builtin.achievement.data_processor.custom_node.name");
// Open the custom node's workspace
m_dataProcessor->getWorkspaceStack().push_back(&m_workspace);
m_requiresAttributeUpdate = true;
m_dataProcessor->updateNodePositions();
}
} else {
this->setUnlocalizedTitle(m_name);
if (this->getAttributes().empty()) {
ImGui::TextUnformatted("hex.builtin.nodes.custom.custom.edit_hint"_lang);
}
}
// Enable editing mode when the shift button is pressed
m_editable = ImGui::GetIO().KeyShift || editing;
ImGui::PopItemWidth();
}
void process() override {
// Find the index of an attribute by its id
auto indexFromId = [this](u32 id) -> std::optional<u32> {
const auto &attributes = this->getAttributes();
for (u32 i = 0; i < attributes.size(); i++) {
if (u32(attributes[i].getId()) == id)
return i;
}
return std::nullopt;
};
auto prevContext = ImNodes::GetCurrentContext();
ImNodes::SetCurrentContext(m_workspace.context.get());
ON_SCOPE_EXIT { ImNodes::SetCurrentContext(prevContext); };
// Forward inputs to input nodes values
for (auto &attribute : this->getAttributes()) {
auto index = indexFromId(attribute.getId());
if (!index.has_value())
continue;
if (auto input = this->findInput(attribute.getUnlocalizedName()); input != nullptr) {
switch (attribute.getType()) {
case dp::Attribute::Type::Integer: {
const auto &value = this->getIntegerOnInput(*index);
input->setValue(value);
break;
}
case dp::Attribute::Type::Float: {
const auto &value = this->getFloatOnInput(*index);
input->setValue(value);
break;
}
case dp::Attribute::Type::Buffer: {
const auto &value = this->getBufferOnInput(*index);
input->setValue(value);
break;
}
}
}
}
// Process all nodes in our workspace
for (auto &endNode : m_workspace.endNodes) {
endNode->resetOutputData();
// Reset processed inputs of all nodes
for (auto &node : m_workspace.nodes)
node->resetProcessedInputs();
endNode->process();
}
// Forward output node values to outputs
for (auto &attribute : this->getAttributes()) {
// Find the index of the attribute
auto index = indexFromId(attribute.getId());
if (!index.has_value())
continue;
// Find the node that is connected to the attribute
if (auto output = this->findOutput(attribute.getUnlocalizedName()); output != nullptr) {
switch (attribute.getType()) {
case dp::Attribute::Type::Integer: {
auto value = std::get<i128>(output->getValue());
this->setIntegerOnOutput(*index, value);
break;
}
case dp::Attribute::Type::Float: {
auto value = std::get<long double>(output->getValue());
this->setFloatOnOutput(*index, value);
break;
}
case dp::Attribute::Type::Buffer: {
auto value = std::get<std::vector<u8>>(output->getValue());
this->setBufferOnOutput(*index, value);
break;
}
}
}
}
}
void store(nlohmann::json &j) const override {
j = nlohmann::json::object();
j["nodes"] = m_dataProcessor->saveNodes(m_workspace);
}
void load(const nlohmann::json &j) override {
m_dataProcessor->loadNodes(m_workspace, j.at("nodes"));
m_name = Lang(this->getUnlocalizedTitle()).get();
m_requiresAttributeUpdate = true;
}
private:
std::vector<dp::Attribute> findAttributes() const {
std::vector<dp::Attribute> result;
// Search through all nodes in the workspace and add all input and output nodes to the result
for (auto &node : m_workspace.nodes) {
if (auto *inputNode = dynamic_cast<NodeCustomInput*>(node.get()); inputNode != nullptr)
result.emplace_back(dp::Attribute::IOType::In, inputNode->getType(), inputNode->getName());
else if (auto *outputNode = dynamic_cast<NodeCustomOutput*>(node.get()); outputNode != nullptr)
result.emplace_back(dp::Attribute::IOType::Out, outputNode->getType(), outputNode->getName());
}
return result;
}
NodeCustomInput* findInput(const std::string &name) const {
for (auto &node : m_workspace.nodes) {
if (auto *inputNode = dynamic_cast<NodeCustomInput*>(node.get()); inputNode != nullptr && inputNode->getName() == name)
return inputNode;
}
return nullptr;
}
NodeCustomOutput* findOutput(const std::string &name) const {
for (auto &node : m_workspace.nodes) {
if (auto *outputNode = dynamic_cast<NodeCustomOutput*>(node.get()); outputNode != nullptr && outputNode->getName() == name)
return outputNode;
}
return nullptr;
}
private:
std::string m_name = "hex.builtin.nodes.custom.custom.header"_lang;
bool m_editable = false;
bool m_requiresAttributeUpdate = false;
ViewDataProcessor *m_dataProcessor;
ViewDataProcessor::Workspace m_workspace;
};
ViewDataProcessor::ViewDataProcessor() : View::Window("hex.builtin.view.data_processor.name", ICON_VS_CHIP) {
ContentRegistry::DataProcessorNode::add<NodeCustom>("hex.builtin.nodes.custom", "hex.builtin.nodes.custom.custom", this);
ContentRegistry::DataProcessorNode::add<NodeCustomInput>("hex.builtin.nodes.custom", "hex.builtin.nodes.custom.input");
ContentRegistry::DataProcessorNode::add<NodeCustomOutput>("hex.builtin.nodes.custom", "hex.builtin.nodes.custom.output");
ProjectFile::registerPerProviderHandler({
.basePath = "data_processor.json",
.required = false,
.load = [this](prv::Provider *provider, const std::fs::path &basePath, const Tar &tar) {
std::string save = tar.readString(basePath);
ViewDataProcessor::loadNodes(m_mainWorkspace.get(provider), nlohmann::json::parse(save));
m_updateNodePositions = true;
return true;
},
.store = [this](prv::Provider *provider, const std::fs::path &basePath, const Tar &tar) {
tar.writeString(basePath, ViewDataProcessor::saveNodes(m_mainWorkspace.get(provider)).dump(4));
return true;
}
});
EventProviderCreated::subscribe(this, [this](auto *provider) {
m_mainWorkspace.get(provider) = { };
m_workspaceStack.get(provider).push_back(&m_mainWorkspace.get(provider));
});
EventProviderChanged::subscribe(this, [this](const auto *, const auto *) {
for (auto *workspace : *m_workspaceStack) {
for (auto &node : workspace->nodes) {
node->setCurrentOverlay(nullptr);
}
workspace->dataOverlays.clear();
}
m_updateNodePositions = true;
});
/* Import Nodes */
ContentRegistry::Interface::addMenuItem({ "hex.builtin.menu.file", "hex.builtin.menu.file.import", "hex.builtin.menu.file.import.data_processor" }, ICON_VS_CHIP, 4050, Shortcut::None, [this]{
fs::openFileBrowser(fs::DialogMode::Open, { {"hex.builtin.view.data_processor.name"_lang, "hexnode" } },
[&](const std::fs::path &path) {
wolv::io::File file(path, wolv::io::File::Mode::Read);
if (file.isValid()) {
ViewDataProcessor::loadNodes(*m_mainWorkspace, nlohmann::json::parse(file.readString()));
m_updateNodePositions = true;
}
});
}, ImHexApi::Provider::isValid);
/* Export Nodes */
ContentRegistry::Interface::addMenuItem({ "hex.builtin.menu.file", "hex.builtin.menu.file.export", "hex.builtin.menu.file.export.data_processor" }, ICON_VS_CHIP, 8050, Shortcut::None, [this]{
fs::openFileBrowser(fs::DialogMode::Save, { {"hex.builtin.view.data_processor.name"_lang, "hexnode" } },
[&, this](const std::fs::path &path) {
wolv::io::File file(path, wolv::io::File::Mode::Create);
if (file.isValid())
file.writeString(ViewDataProcessor::saveNodes(*m_mainWorkspace).dump(4));
});
}, [this]{
return !m_workspaceStack->empty() && !m_workspaceStack->back()->nodes.empty() && ImHexApi::Provider::isValid();
});
ContentRegistry::FileHandler::add({ ".hexnode" }, [this](const auto &path) {
wolv::io::File file(path, wolv::io::File::Mode::Read);
if (!file.isValid()) return false;
ViewDataProcessor::loadNodes(*m_mainWorkspace, file.readString());
m_updateNodePositions = true;
return true;
});
}
ViewDataProcessor::~ViewDataProcessor() {
EventProviderCreated::unsubscribe(this);
EventProviderChanged::unsubscribe(this);
RequestChangeTheme::unsubscribe(this);
EventFileLoaded::unsubscribe(this);
EventDataChanged::unsubscribe(this);
}
void ViewDataProcessor::eraseLink(Workspace &workspace, int id) {
// Find the link with the given ID
auto link = std::find_if(workspace.links.begin(), workspace.links.end(),
[&id](auto link) {
return link.getId() == id;
});
// Return if the link was not found
if (link == workspace.links.end())
return;
// Remove the link from all attributes that are connected to it
for (auto &node : workspace.nodes) {
for (auto &attribute : node->getAttributes()) {
attribute.removeConnectedAttribute(id);
}
}
// Remove the link from the workspace
workspace.links.erase(link);
ImHexApi::Provider::markDirty();
}
void ViewDataProcessor::eraseNodes(Workspace &workspace, const std::vector<int> &ids) {
// Loop over the IDs of all nodes that should be removed
// and remove all links that are connected to the attributes of the node
for (int id : ids) {
// Find the node with the given ID
auto node = std::find_if(workspace.nodes.begin(), workspace.nodes.end(),
[&id](const auto &node) {
return node->getId() == id;
});
// Loop over all attributes of that node
for (auto &attr : (*node)->getAttributes()) {
std::vector<int> linksToRemove;
// Find all links that are connected to the attribute and remove them
for (auto &[linkId, connectedAttr] : attr.getConnectedAttributes())
linksToRemove.push_back(linkId);
// Remove the links from the workspace
for (auto linkId : linksToRemove)
eraseLink(workspace, linkId);
}
}
// Loop over the IDs of all nodes that should be removed
// and remove the nodes from the workspace
for (int id : ids) {
// Find the node with the given ID
auto node = std::find_if(workspace.nodes.begin(), workspace.nodes.end(),
[&id](const auto &node) {
return node->getId() == id;
});
// Remove the node from the workspace
std::erase_if(workspace.endNodes,
[&id](const auto &node) {
return node->getId() == id;
});
// Remove the node from the workspace
workspace.nodes.erase(node);
}
ImHexApi::Provider::markDirty();
}
void ViewDataProcessor::processNodes(Workspace &workspace) {
// If the number of end nodes does not match the number of data overlays,
// the overlays have to be recreated
if (workspace.dataOverlays.size() != workspace.endNodes.size()) {
// Delete all the overlays from the current provider
for (auto overlay : workspace.dataOverlays)
ImHexApi::Provider::get()->deleteOverlay(overlay);
workspace.dataOverlays.clear();
// Create a new overlay for each end node
for (u32 i = 0; i < workspace.endNodes.size(); i += 1)
workspace.dataOverlays.push_back(ImHexApi::Provider::get()->newOverlay());
}
// Set the current overlay of each end node to the corresponding overlay
size_t overlayIndex = 0;
for (auto endNode : workspace.endNodes) {
endNode->setCurrentOverlay(workspace.dataOverlays[overlayIndex]);
overlayIndex += 1;
}
// Reset any potential node errors
workspace.currNodeError.reset();
m_evaluationTask = TaskManager::createTask("hex.builtin.task.evaluating_nodes"_lang, 0, [this, workspace = &workspace](Task& task) {
task.setInterruptCallback([]{
dp::Node::interrupt();
});
const auto handleError = [workspace] {
TaskManager::doLater([workspace] {
// Delete all overlays
for (auto overlay : workspace->dataOverlays)
ImHexApi::Provider::get()->deleteOverlay(overlay);
workspace->dataOverlays.clear();
});
};
do {
// Process all nodes in the workspace
try {
for (auto &endNode : workspace->endNodes) {
task.update();
// Reset the output data of the end node
endNode->resetOutputData();
// Reset processed inputs of all nodes
for (auto &node : workspace->nodes) {
node->reset();
node->resetProcessedInputs();
}
// Process the end node
endNode->process();
}
} catch (const dp::Node::NodeError &e) {
// Handle user errors
// Add the node error to the current workspace, so it can be displayed
workspace->currNodeError = e;
handleError();
break;
} catch (const std::runtime_error &e) {
// Handle internal errors
log::fatal("Data processor node implementation bug! {}", e.what());
handleError();
break;
} catch (const std::exception &e) {
// Handle other fatal errors
log::fatal("Unhandled exception thrown in data processor node! {}", e.what());
handleError();
break;
}
} while (m_continuousEvaluation);
});
}
void ViewDataProcessor::reloadCustomNodes() {
// Delete all custom nodes
m_customNodes.clear();
// Loop over all custom node folders
for (const auto &basePath : paths::Nodes.read()) {
// Loop over all files in the folder
for (const auto &entry : std::fs::recursive_directory_iterator(basePath)) {
// Skip files that are not .hexnode files
if (entry.path().extension() != ".hexnode")
continue;
try {
// Load the content of the file as JSON
wolv::io::File file(entry.path(), wolv::io::File::Mode::Read);
nlohmann::json nodeJson = nlohmann::json::parse(file.readString());
// Add the loaded node to the list of custom nodes
m_customNodes.push_back(CustomNode { Lang(nodeJson.at("name").get<std::string>()), nodeJson });
} catch (nlohmann::json::exception &e) {
log::warn("Failed to load custom node '{}': {}", entry.path().string(), e.what());
}
}
}
}
void ViewDataProcessor::updateNodePositions() {
m_updateNodePositions = true;
}
void ViewDataProcessor::drawContextMenus(ViewDataProcessor::Workspace &workspace) {
// Handle the right click context menus
if (ImGui::IsMouseDown(ImGuiMouseButton_Right) && ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows) && !ImGui::IsMouseDragging(ImGuiMouseButton_Right)) {
// Clear selections
ImNodes::ClearNodeSelection();
ImNodes::ClearLinkSelection();
// Save the current mouse position
m_rightClickedCoords = ImGui::GetMousePos();
// Show a different context menu depending on if a node, a link
// or the background was right-clicked
if (ImNodes::IsNodeHovered(&m_rightClickedId)) {
ImGui::OpenPopup("Node Menu");
} else if (ImNodes::IsLinkHovered(&m_rightClickedId)) {
ImGui::OpenPopup("Link Menu");
} else {
ImGui::OpenPopup("Context Menu");
this->reloadCustomNodes();
}
}
// Draw main context menu
if (ImGui::BeginPopup("Context Menu")) {
std::unique_ptr<dp::Node> node;
// Check if any link or node has been selected previously
if (ImNodes::NumSelectedNodes() > 0 || ImNodes::NumSelectedLinks() > 0) {
if (ImGui::MenuItem("hex.builtin.view.data_processor.menu.remove_selection"_lang)) {
// Delete selected nodes
{
std::vector<int> ids;
ids.resize(ImNodes::NumSelectedNodes());
ImNodes::GetSelectedNodes(ids.data());
this->eraseNodes(workspace, ids);
ImNodes::ClearNodeSelection();
}
// Delete selected links
{
std::vector<int> ids;
ids.resize(ImNodes::NumSelectedLinks());
ImNodes::GetSelectedLinks(ids.data());
for (auto id : ids)
this->eraseLink(workspace, id);
ImNodes::ClearLinkSelection();
}
}
}
// Draw all nodes that are registered in the content registry
for (const auto &[unlocalizedCategory, unlocalizedName, function] : ContentRegistry::DataProcessorNode::impl::getEntries()) {
if (unlocalizedCategory.empty() && unlocalizedName.empty()) {
// Draw a separator if the node has no category and no name
ImGui::Separator();
} else if (unlocalizedCategory.empty()) {
// Draw the node if it has no category
if (ImGui::MenuItem(Lang(unlocalizedName))) {
node = function();
}
} else {
// Draw the node inside its sub menu if it has a category
if (ImGui::BeginMenu(Lang(unlocalizedCategory))) {
if (ImGui::MenuItem(Lang(unlocalizedName))) {
node = function();
}
ImGui::EndMenu();
}
}
}
// Draw custom nodes submenu
if (ImGui::BeginMenu("hex.builtin.nodes.custom"_lang)) {
ImGui::Separator();
// Draw entries for each custom node
for (auto &customNode : m_customNodes) {
if (ImGui::MenuItem(customNode.name.c_str())) {
node = loadNode(customNode.data);
}
}
ImGui::EndMenu();
}
// Check if a node has been selected in the menu
if (node != nullptr) {
// Place the node in the workspace
// Check if the node has inputs and/or outputs
bool hasOutput = false;
bool hasInput = false;
for (auto &attr : node->getAttributes()) {
if (attr.getIOType() == dp::Attribute::IOType::Out)
hasOutput = true;
if (attr.getIOType() == dp::Attribute::IOType::In)
hasInput = true;
}
// If the node has only inputs and no outputs, it's considered an end node
// Add it to the list of end nodes to be processed
if (hasInput && !hasOutput)
workspace.endNodes.push_back(node.get());
// Set the position of the node to the position where the user right-clicked
ImNodes::SetNodeScreenSpacePos(node->getId(), m_rightClickedCoords);
node->setPosition(m_rightClickedCoords);
workspace.nodes.push_back(std::move(node));
ImHexApi::Provider::markDirty();
AchievementManager::unlockAchievement("hex.builtin.achievement.data_processor", "hex.builtin.achievement.data_processor.place_node.name");
}
ImGui::EndPopup();
}
// Draw node right click menu
if (ImGui::BeginPopup("Node Menu")) {
if (ImGui::MenuItem("hex.builtin.view.data_processor.menu.save_node"_lang)) {
// Find the node that was right-clicked
auto it = std::find_if(workspace.nodes.begin(), workspace.nodes.end(),
[this](const auto &node) {
return node->getId() == m_rightClickedId;
});
// Check if the node was found
if (it != workspace.nodes.end()) {
auto &node = *it;
// Save the node to a file
fs::openFileBrowser(fs::DialogMode::Save, { {"hex.builtin.view.data_processor.name"_lang, "hexnode" } }, [&](const std::fs::path &path){
wolv::io::File outputFile(path, wolv::io::File::Mode::Create);
outputFile.writeString(ViewDataProcessor::saveNode(node.get()).dump(4));
});
}
}
ImGui::Separator();
if (ImGui::MenuItem("hex.builtin.view.data_processor.menu.remove_node"_lang))
this->eraseNodes(workspace, { m_rightClickedId });
ImGui::EndPopup();
}
// Draw link right click menu
if (ImGui::BeginPopup("Link Menu")) {
if (ImGui::MenuItem("hex.builtin.view.data_processor.menu.remove_link"_lang))
this->eraseLink(workspace, m_rightClickedId);
ImGui::EndPopup();
}
}
void ViewDataProcessor::drawNode(dp::Node &node) const {
// If a node position update is pending, update the node position
int nodeId = node.getId();
if (m_updateNodePositions) {
ImNodes::SetNodeGridSpacePos(nodeId, node.getPosition());
} else {
if (ImNodes::ObjectPoolFind(ImNodes::EditorContextGet().Nodes, nodeId) >= 0)
node.setPosition(ImNodes::GetNodeGridSpacePos(nodeId));
}
// Draw the node
ImNodes::BeginNode(nodeId);
{
// Draw the node's title bar
ImNodes::BeginNodeTitleBar();
{
ImGui::TextUnformatted(Lang(node.getUnlocalizedTitle()));
}
ImNodes::EndNodeTitleBar();
// Draw the node's body
ImGui::PopStyleVar();
if (!m_evaluationTask.isRunning()) {
node.draw();
}
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(1.0F, 1.0F));
// Draw all attributes of the node
for (auto &attribute : node.getAttributes()) {
ImNodesPinShape pinShape;
// Set the pin shape depending on the attribute type
auto attributeType = attribute.getType();
switch (attributeType) {
default:
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;
}
// Draw the attribute
if (attribute.getIOType() == dp::Attribute::IOType::In) {
ImNodes::BeginInputAttribute(attribute.getId(), pinShape);
// Draw input fields for attributes that have no connected links
if (attribute.getConnectedAttributes().empty() && attributeType != dp::Attribute::Type::Buffer) {
auto &defaultValue = attribute.getDefaultData();
ImGui::PushItemWidth(100_scaled);
if (attributeType == dp::Attribute::Type::Integer) {
defaultValue.resize(sizeof(i128));
auto value = i64(*reinterpret_cast<i128*>(defaultValue.data()));
if (ImGui::InputScalar(Lang(attribute.getUnlocalizedName()), ImGuiDataType_S64, &value)) {
std::fill(defaultValue.begin(), defaultValue.end(), 0x00);
i128 writeValue = value;
std::memcpy(defaultValue.data(), &writeValue, sizeof(writeValue));
}
} else if (attributeType == dp::Attribute::Type::Float) {
defaultValue.resize(sizeof(long double));
auto value = double(*reinterpret_cast<long double*>(defaultValue.data()));
if (ImGui::InputScalar(Lang(attribute.getUnlocalizedName()), ImGuiDataType_Double, &value)) {
std::fill(defaultValue.begin(), defaultValue.end(), 0x00);
long double writeValue = value;
std::memcpy(defaultValue.data(), &writeValue, sizeof(writeValue));
}
}
ImGui::PopItemWidth();
} else {
ImGui::TextUnformatted(Lang(attribute.getUnlocalizedName()));
}
ImNodes::EndInputAttribute();
} else if (attribute.getIOType() == dp::Attribute::IOType::Out) {
ImNodes::BeginOutputAttribute(attribute.getId(), ImNodesPinShape(pinShape + 1));
ImGui::TextUnformatted(Lang(attribute.getUnlocalizedName()));
ImNodes::EndOutputAttribute();
}
}
}
ImNodes::EndNode();
ImNodes::SetNodeGridSpacePos(nodeId, node.getPosition());
}
void ViewDataProcessor::drawContent() {
auto &workspace = *m_workspaceStack->back();
ImGui::BeginDisabled(m_evaluationTask.isRunning());
bool popWorkspace = false;
// Set the ImNodes context to the current workspace context
ImNodes::SetCurrentContext(workspace.context.get());
this->drawContextMenus(workspace);
// Draw error tooltip when hovering over a node that has an error
{
int nodeId;
if (ImNodes::IsNodeHovered(&nodeId) && workspace.currNodeError.has_value() && workspace.currNodeError->node->getId() == nodeId) {
ImGui::BeginTooltip();
ImGui::TextUnformatted("hex.ui.common.error"_lang);
ImGui::Separator();
ImGui::TextUnformatted(workspace.currNodeError->message.c_str());
ImGui::EndTooltip();
}
}
// Draw the main node editor workspace window
if (ImGui::BeginChild("##node_editor", ImGui::GetContentRegionAvail() - ImVec2(0, ImGui::GetTextLineHeightWithSpacing() * 1.3F))) {
ImNodes::BeginNodeEditor();
if (m_evaluationTask.isRunning())
ImNodes::GetCurrentContext()->MousePos = { FLT_MAX, FLT_MAX };
// Loop over all nodes that have been placed in the workspace
bool stillUpdating = m_updateNodePositions;
for (auto &node : workspace.nodes) {
ImNodes::SnapNodeToGrid(node->getId());
// If the node has an error, draw it with a red outline
const bool hasError = workspace.currNodeError.has_value() && workspace.currNodeError->node == node.get();
if (hasError)
ImNodes::PushColorStyle(ImNodesCol_NodeOutline, 0xFF0000FF);
// Draw the node
this->drawNode(*node);
if (hasError)
ImNodes::PopColorStyle();
}
if (stillUpdating)
m_updateNodePositions = false;
// Handle removing links that are connected to attributes that don't exist anymore
{
std::vector<int> linksToRemove;
for (const auto &link : workspace.links) {
if (ImNodes::ObjectPoolFind(ImNodes::EditorContextGet().Pins, link.getFromId()) == -1 ||
ImNodes::ObjectPoolFind(ImNodes::EditorContextGet().Pins, link.getToId()) == -1) {
linksToRemove.push_back(link.getId());
}
}
for (auto linkId : linksToRemove)
this->eraseLink(workspace, linkId);
}
// Draw links
for (const auto &link : workspace.links) {
ImNodes::Link(link.getId(), link.getFromId(), link.getToId());
}
// Draw the mini map in the bottom right
ImNodes::MiniMap(0.2F, ImNodesMiniMapLocation_BottomRight);
// Draw the help text if no nodes have been placed yet
if (workspace.nodes.empty())
ImGuiExt::TextFormattedCentered("{}", "hex.builtin.view.data_processor.help_text"_lang);
// Draw a close button if there is more than one workspace on the stack
if (m_workspaceStack->size() > 1) {
ImGui::SetCursorPos(ImVec2(ImGui::GetContentRegionAvail().x - ImGui::GetTextLineHeightWithSpacing() * 1.5F, ImGui::GetTextLineHeightWithSpacing() * 0.2F));
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(4.0F, 4.0F));
if (ImGuiExt::DimmedIconButton(ICON_VS_CLOSE, ImGuiExt::GetCustomColorVec4(ImGuiCustomCol_ToolbarRed))) {
popWorkspace = true;
}
ImGui::PopStyleVar();
}
ImNodes::EndNodeEditor();
}
ImGui::EndChild();
ImGui::EndDisabled();
// Draw the control bar at the bottom
{
if (!m_evaluationTask.isRunning()) {
if (ImGuiExt::IconButton(ICON_VS_DEBUG_START, ImGuiExt::GetCustomColorVec4(ImGuiCustomCol_ToolbarGreen))) {
this->processNodes(workspace);
}
} else {
if (ImGuiExt::IconButton(ICON_VS_DEBUG_STOP, ImGuiExt::GetCustomColorVec4(ImGuiCustomCol_ToolbarRed))) {
m_evaluationTask.interrupt();
}
}
ImGui::SameLine();
ImGui::Checkbox("Continuous evaluation", &m_continuousEvaluation);
}
// Erase links that have been destroyed
{
int linkId;
if (ImNodes::IsLinkDestroyed(&linkId)) {
this->eraseLink(workspace, linkId);
}
}
// Handle creation of new links
{
int from, to;
if (ImNodes::IsLinkCreated(&from, &to)) {
do {
dp::Attribute *fromAttr = nullptr, *toAttr = nullptr;
// Find the attributes that are connected by the link
for (auto &node : workspace.nodes) {
for (auto &attribute : node->getAttributes()) {
if (attribute.getId() == from)
fromAttr = &attribute;
else if (attribute.getId() == to)
toAttr = &attribute;
}
}
// If one of the attributes could not be found, the link is invalid and can't be created
if (fromAttr == nullptr || toAttr == nullptr)
break;
// If the attributes have different types, don't create the link
if (fromAttr->getType() != toAttr->getType())
break;
// If the link tries to connect two input or two output attributes, don't create the link
if (fromAttr->getIOType() == toAttr->getIOType())
break;
// If the link tries to connect to a input attribute that already has a link connected to it, don't create the link
if (!toAttr->getConnectedAttributes().empty())
break;
// Add a new link to the current workspace
auto newLink = workspace.links.emplace_back(from, to);
// Add the link to the attributes that are connected by it
fromAttr->addConnectedAttribute(newLink.getId(), toAttr);
toAttr->addConnectedAttribute(newLink.getId(), fromAttr);
AchievementManager::unlockAchievement("hex.builtin.achievement.data_processor", "hex.builtin.achievement.data_processor.create_connection.name");
} while (false);
}
}
// Handle deletion of links using the Delete key
{
const int selectedLinkCount = ImNodes::NumSelectedLinks();
if (selectedLinkCount > 0 && ImGui::IsKeyPressed(ImGuiKey_Delete)) {
std::vector<int> selectedLinks;
selectedLinks.resize(static_cast<size_t>(selectedLinkCount));
ImNodes::GetSelectedLinks(selectedLinks.data());
ImNodes::ClearLinkSelection();
for (const int id : selectedLinks) {
eraseLink(workspace, id);
}
}
}
// Handle deletion of noes using the Delete key
{
const int selectedNodeCount = ImNodes::NumSelectedNodes();
if (selectedNodeCount > 0 && ImGui::IsKeyPressed(ImGuiKey_Delete)) {
std::vector<int> selectedNodes;
selectedNodes.resize(static_cast<size_t>(selectedNodeCount));
ImNodes::GetSelectedNodes(selectedNodes.data());
ImNodes::ClearNodeSelection();
this->eraseNodes(workspace, selectedNodes);
}
}
// Remove the top-most workspace from the stack if requested
if (popWorkspace) {
m_workspaceStack->pop_back();
m_updateNodePositions = true;
}
}
nlohmann::json ViewDataProcessor::saveNode(const dp::Node *node) {
nlohmann::json output;
output["name"] = node->getUnlocalizedTitle();
output["type"] = node->getUnlocalizedName();
nlohmann::json nodeData;
node->store(nodeData);
output["data"] = nodeData;
output["attrs"] = nlohmann::json::array();
u32 attrIndex = 0;
for (auto &attr : node->getAttributes()) {
output["attrs"][attrIndex] = attr.getId();
attrIndex++;
}
return output;
}
nlohmann::json ViewDataProcessor::saveNodes(const ViewDataProcessor::Workspace &workspace) {
nlohmann::json output;
output["nodes"] = nlohmann::json::object();
for (auto &node : workspace.nodes) {
auto id = node->getId();
auto &currNodeOutput = output["nodes"][std::to_string(id)];
auto pos = node->getPosition();
currNodeOutput = saveNode(node.get());
currNodeOutput["id"] = id;
currNodeOutput["pos"] = {
{ "x", pos.x },
{ "y", pos.y }
};
}
output["links"] = nlohmann::json::object();
for (auto &link : workspace.links) {
auto id = link.getId();
auto &currOutput = output["links"][std::to_string(id)];
currOutput["id"] = id;
currOutput["from"] = link.getFromId();
currOutput["to"] = link.getToId();
}
return output;
}
std::unique_ptr<dp::Node> ViewDataProcessor::loadNode(nlohmann::json data) {
try {
auto &nodeEntries = ContentRegistry::DataProcessorNode::impl::getEntries();
std::unique_ptr<dp::Node> newNode;
for (auto &entry : nodeEntries) {
if (data.contains("name") && entry.unlocalizedName == data["type"].get<std::string>())
newNode = entry.creatorFunction();
}
if (newNode == nullptr)
return nullptr;
if (data.contains("id"))
newNode->setId(data["id"]);
if (data.contains("name"))
newNode->setUnlocalizedTitle(data["name"]);
u32 attrIndex = 0;
for (auto &attr : newNode->getAttributes()) {
if (attrIndex < data["attrs"].size())
attr.setId(data["attrs"][attrIndex]);
else
attr.setId(-1);
attrIndex++;
}
if (!data["data"].is_null())
newNode->load(data["data"]);
return newNode;
} catch (nlohmann::json::exception &e) {
log::error("Failed to load node: {}", e.what());
return nullptr;
}
}
void ViewDataProcessor::loadNodes(ViewDataProcessor::Workspace &workspace, nlohmann::json data) {
workspace.nodes.clear();
workspace.endNodes.clear();
workspace.links.clear();
try {
for (auto &node : data["nodes"]) {
auto newNode = loadNode(node);
if (newNode == nullptr)
continue;
if (!node["data"].is_null())
newNode->load(node["data"]);
bool hasOutput = false;
bool hasInput = false;
u32 attrIndex = 0;
for (auto &attr : newNode->getAttributes()) {
if (attr.getIOType() == dp::Attribute::IOType::Out)
hasOutput = true;
if (attr.getIOType() == dp::Attribute::IOType::In)
hasInput = true;
if (attrIndex < node["attrs"].size())
attr.setId(node["attrs"][attrIndex]);
else
attr.setId(-1);
attrIndex++;
}
if (hasInput && !hasOutput)
workspace.endNodes.push_back(newNode.get());
newNode->setPosition(ImVec2(node["pos"]["x"], node["pos"]["y"]));
workspace.nodes.push_back(std::move(newNode));
}
int maxLinkId = 0;
for (auto &link : data["links"]) {
dp::Link newLink(link["from"], link["to"]);
int linkId = link["id"];
maxLinkId = std::max(linkId, maxLinkId);
newLink.setId(linkId);
workspace.links.push_back(newLink);
dp::Attribute *fromAttr = nullptr, *toAttr = nullptr;
for (auto &node : workspace.nodes) {
for (auto &attribute : node->getAttributes()) {
if (attribute.getId() == newLink.getFromId())
fromAttr = &attribute;
else if (attribute.getId() == newLink.getToId())
toAttr = &attribute;
}
}
if (fromAttr == nullptr || toAttr == nullptr)
continue;
if (fromAttr->getType() != toAttr->getType())
continue;
if (fromAttr->getIOType() == toAttr->getIOType())
continue;
if (!toAttr->getConnectedAttributes().empty())
continue;
fromAttr->addConnectedAttribute(newLink.getId(), toAttr);
toAttr->addConnectedAttribute(newLink.getId(), fromAttr);
}
int maxNodeId = 0;
int maxAttrId = 0;
for (auto &node : workspace.nodes) {
maxNodeId = std::max(maxNodeId, node->getId());
for (auto &attr : node->getAttributes()) {
maxAttrId = std::max(maxAttrId, attr.getId());
}
}
for (auto &node : workspace.nodes) {
if (node->getId() == -1) {
maxNodeId += 1;
node->setId(maxNodeId);
}
}
dp::Node::setIdCounter(maxNodeId + 1);
dp::Attribute::setIdCounter(maxAttrId + 1);
dp::Link::setIdCounter(maxLinkId + 1);
m_updateNodePositions = true;
} catch (nlohmann::json::exception &e) {
ui::ToastError::open(hex::format("Failed to load nodes: {}", e.what()));
}
}
}
| 51,266
|
C++
|
.cpp
| 1,018
| 34.434185
| 199
| 0.525211
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
245
|
view_theme_manager.cpp
|
WerWolv_ImHex/plugins/builtin/source/content/views/view_theme_manager.cpp
|
#include "content/views/view_theme_manager.hpp"
#include <hex/api/content_registry.hpp>
#include <hex/api/theme_manager.hpp>
#include <wolv/io/file.hpp>
#include <fonts/codicons_font.h>
namespace hex::plugin::builtin {
ViewThemeManager::ViewThemeManager() : View::Floating("hex.builtin.view.theme_manager.name") {
ContentRegistry::Interface::addMenuItem({ "hex.builtin.menu.extras", "hex.builtin.view.theme_manager.name" }, ICON_VS_SYMBOL_COLOR, 2000, Shortcut::None, [&, this] {
this->getWindowOpenState() = true;
});
}
void ViewThemeManager::drawContent() {
ImGuiExt::Header("hex.builtin.view.theme_manager.colors"_lang, true);
// Draw theme handlers
ImGui::PushID(1);
// Loop over each theme handler
bool anyColorHovered = false;
for (auto &[name, handler] : ThemeManager::getThemeHandlers()) {
// Create a new collapsable header for each category
if (ImGui::CollapsingHeader(name.c_str())) {
// Loop over all the individual theme settings
for (auto &[colorName, colorId] : handler.colorMap) {
if (m_startingColor.has_value()) {
if (m_hoveredColorId == colorId && m_hoveredHandlerName == name) {
handler.setFunction(colorId, m_startingColor.value());
}
}
// Get the current color value
auto color = handler.getFunction(colorId);
// Draw a color picker for the color
if (ImGui::ColorEdit4(colorName.c_str(), &color.Value.x, ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_AlphaBar | ImGuiColorEditFlags_AlphaPreviewHalf)) {
// Update the color value
handler.setFunction(colorId, color);
EventThemeChanged::post();
}
if (ImGui::IsItemHovered()) {
anyColorHovered = true;
if (!m_hoveredColorId.has_value()) {
m_hoveredColorId = colorId;
m_startingColor = color;
m_hoveredHandlerName = name;
}
}
}
}
if (m_hoveredHandlerName == name && m_startingColor.has_value() && m_hoveredColorId.has_value()) {
auto flashingColor = m_startingColor.value();
const float flashProgress = std::min(1.0F, (1.0F + sinf(ImGui::GetTime() * 6)) / 2.0F);
flashingColor.Value.x = std::lerp(flashingColor.Value.x / 2, 1.0F, flashProgress);
flashingColor.Value.y = std::lerp(flashingColor.Value.y / 2, 1.0F, flashProgress);
flashingColor.Value.z = flashingColor.Value.z / 2;
flashingColor.Value.w = 1.0F;
handler.setFunction(*m_hoveredColorId, flashingColor);
if (!anyColorHovered) {
handler.setFunction(m_hoveredColorId.value(), m_startingColor.value());
m_startingColor.reset();
m_hoveredColorId.reset();
}
}
}
ImGui::PopID();
ImGuiExt::Header("hex.builtin.view.theme_manager.styles"_lang);
// Draw style handlers
ImGui::PushID(2);
// Loop over each style handler
for (auto &[name, handler] : ThemeManager::getStyleHandlers()) {
// Create a new collapsable header for each category
if (ImGui::CollapsingHeader(name.c_str())) {
// Loop over all the individual style settings
for (auto &[styleName, style] : handler.styleMap) {
// Get the current style value
auto &[value, min, max, needsScaling] = style;
// Styles can either be floats or ImVec2s
// Determine which one it is and draw the appropriate slider
if (auto floatValue = std::get_if<float*>(&value); floatValue != nullptr) {
if (ImGui::SliderFloat(styleName.c_str(), *floatValue, min, max, "%.1f")) {
EventThemeChanged::post();
}
} else if (auto vecValue = std::get_if<ImVec2*>(&value); vecValue != nullptr) {
if (ImGui::SliderFloat2(styleName.c_str(), &(*vecValue)->x, min, max, "%.1f")) {
EventThemeChanged::post();
}
}
}
}
}
ImGui::PopID();
// Draw export settings
ImGuiExt::Header("hex.builtin.view.theme_manager.export"_lang);
ImGuiExt::InputTextIcon("hex.builtin.view.theme_manager.export.name"_lang, ICON_VS_SYMBOL_KEY, m_themeName);
// Draw the export buttons
if (ImGui::Button("hex.builtin.view.theme_manager.save_theme"_lang, ImVec2(ImGui::GetContentRegionAvail().x, 0))) {
fs::openFileBrowser(fs::DialogMode::Save, { { "ImHex Theme", "json" } }, [this](const std::fs::path &path){
// Export the current theme as json
auto json = ThemeManager::exportCurrentTheme(m_themeName);
// Write the json to the file
wolv::io::File outputFile(path, wolv::io::File::Mode::Create);
outputFile.writeString(json.dump(4));
});
}
}
}
| 5,591
|
C++
|
.cpp
| 102
| 38.970588
| 179
| 0.543474
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
246
|
view_store.cpp
|
WerWolv_ImHex/plugins/builtin/source/content/views/view_store.cpp
|
#include "content/views/view_store.hpp"
#include <hex/api/theme_manager.hpp>
#include <hex/api/achievement_manager.hpp>
#include <hex/api_urls.hpp>
#include <hex/api/content_registry.hpp>
#include <popups/popup_notification.hpp>
#include <toasts/toast_notification.hpp>
#include <imgui.h>
#include <hex/helpers/utils.hpp>
#include <hex/helpers/crypto.hpp>
#include <hex/helpers/logger.hpp>
#include <hex/helpers/magic.hpp>
#include <hex/helpers/fs.hpp>
#include <hex/helpers/tar.hpp>
#include <filesystem>
#include <functional>
#include <nlohmann/json.hpp>
#include <wolv/io/file.hpp>
namespace hex::plugin::builtin {
using namespace std::literals::string_literals;
using namespace std::literals::chrono_literals;
ViewStore::ViewStore() : View::Floating("hex.builtin.view.store.name") {
ContentRegistry::Interface::addMenuItem({ "hex.builtin.menu.extras", "hex.builtin.view.store.name" }, ICON_VS_GLOBE, 1000, Shortcut::None, [&, this] {
if (m_requestStatus == RequestStatus::NotAttempted)
this->refresh();
this->getWindowOpenState() = true;
});
m_httpRequest.setTimeout(30'0000);
addCategory("hex.builtin.view.store.tab.patterns", "patterns", &paths::Patterns);
addCategory("hex.builtin.view.store.tab.includes", "includes", &paths::PatternsInclude);
addCategory("hex.builtin.view.store.tab.magic", "magic", &paths::Magic, []{
magic::compile();
});
addCategory("hex.builtin.view.store.tab.nodes", "nodes", &paths::Nodes);
addCategory("hex.builtin.view.store.tab.encodings", "encodings", &paths::Encodings);
addCategory("hex.builtin.view.store.tab.constants", "constants", &paths::Constants);
addCategory("hex.builtin.view.store.tab.themes", "themes", &paths::Themes, [this]{
auto themeFile = wolv::io::File(m_downloadPath, wolv::io::File::Mode::Read);
ThemeManager::addTheme(themeFile.readString());
});
addCategory("hex.builtin.view.store.tab.yara", "yara", &paths::Yara);
}
void updateEntryMetadata(StoreEntry &storeEntry, const StoreCategory &category) {
// Check if file is installed already or has an update available
for (const auto &folder : category.path->write()) {
auto path = folder / std::fs::path(storeEntry.fileName);
if (wolv::io::fs::exists(path)) {
storeEntry.installed = true;
wolv::io::File file(path, wolv::io::File::Mode::Read);
auto bytes = file.readVector();
auto fileHash = crypt::sha256(bytes);
// Compare installed file hash with hash of repo file
if (std::vector(fileHash.begin(), fileHash.end()) != crypt::decode16(storeEntry.hash))
storeEntry.hasUpdate = true;
storeEntry.system = !fs::isPathWritable(folder);
return;
}
}
storeEntry.installed = false;
storeEntry.hasUpdate = false;
storeEntry.system = false;
}
void ViewStore::drawTab(hex::plugin::builtin::StoreCategory &category) {
if (ImGui::BeginTabItem(Lang(category.unlocalizedName))) {
if (ImGui::BeginTable("##pattern_language", 4, ImGuiTableFlags_ScrollY | ImGuiTableFlags_Borders | ImGuiTableFlags_SizingStretchSame | ImGuiTableFlags_RowBg)) {
ImGui::TableSetupScrollFreeze(0, 1);
ImGui::TableSetupColumn("hex.builtin.view.store.row.name"_lang, ImGuiTableColumnFlags_WidthFixed);
ImGui::TableSetupColumn("hex.builtin.view.store.row.description"_lang, ImGuiTableColumnFlags_None);
ImGui::TableSetupColumn("hex.builtin.view.store.row.authors"_lang, ImGuiTableColumnFlags_WidthFixed);
ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthFixed);
ImGui::TableHeadersRow();
u32 id = 1;
for (auto &entry : category.entries) {
ImGui::TableNextRow();
ImGui::TableNextColumn();
ImGui::TextUnformatted(entry.name.c_str());
ImGui::TableNextColumn();
ImGui::TextUnformatted(entry.description.c_str());
if (ImGui::IsItemHovered()) {
ImGui::BeginTooltip();
ImGui::PushTextWrapPos(500);
ImGui::TextUnformatted(entry.description.c_str());
ImGui::PopTextWrapPos();
ImGui::EndTooltip();
}
ImGui::TableNextColumn();
// The space makes a padding in the UI
ImGuiExt::TextFormatted("{} ", wolv::util::combineStrings(entry.authors, ", "));
ImGui::TableNextColumn();
const auto buttonSize = ImVec2(100_scaled, ImGui::GetTextLineHeightWithSpacing());
ImGui::PushID(id);
ImGui::BeginDisabled(m_updateAllTask.isRunning() || (m_download.valid() && m_download.wait_for(0s) != std::future_status::ready));
{
if (entry.downloading) {
ImGui::ProgressBar(m_httpRequest.getProgress(), buttonSize, "");
if (m_download.valid() && m_download.wait_for(0s) == std::future_status::ready) {
this->handleDownloadFinished(category, entry);
}
} else {
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0));
if (entry.hasUpdate) {
if (ImGui::Button("hex.builtin.view.store.update"_lang, buttonSize)) {
entry.downloading = this->download(category.path, entry.fileName, entry.link);
}
} else if (entry.system) {
ImGui::BeginDisabled();
ImGui::Button("hex.builtin.view.store.system"_lang, buttonSize);
ImGui::EndDisabled();
if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) {
ImGui::BeginTooltip();
ImGui::TextUnformatted("hex.builtin.view.store.system.explanation"_lang);
ImGui::EndTooltip();
}
} else if (!entry.installed) {
if (ImGui::Button("hex.builtin.view.store.download"_lang, buttonSize)) {
entry.downloading = this->download(category.path, entry.fileName, entry.link);
AchievementManager::unlockAchievement("hex.builtin.achievement.misc", "hex.builtin.achievement.misc.download_from_store.name");
}
} else {
if (ImGui::Button("hex.builtin.view.store.remove"_lang, buttonSize)) {
entry.installed = !this->remove(category.path, entry.fileName);
// remove() will not update the entry to mark it as a system entry, so we do it manually
updateEntryMetadata(entry, category);
}
}
ImGui::PopStyleVar();
}
}
ImGui::EndDisabled();
ImGui::PopID();
id++;
}
ImGui::EndTable();
}
ImGui::EndTabItem();
}
}
void ViewStore::drawStore() {
ImGuiExt::Header("hex.builtin.view.store.desc"_lang, true);
bool reloading = false;
if (m_apiRequest.valid()) {
if (m_apiRequest.wait_for(0s) != std::future_status::ready)
reloading = true;
else {
try {
this->parseResponse();
} catch (nlohmann::json::exception &e) {
log::error("Failed to parse store response: {}", e.what());
}
}
}
ImGui::BeginDisabled(reloading);
if (ImGui::Button("hex.builtin.view.store.reload"_lang)) {
this->refresh();
}
ImGui::EndDisabled();
if (reloading) {
ImGui::SameLine();
ImGuiExt::TextSpinner("hex.builtin.view.store.loading"_lang);
}
// Align the button to the right
ImGui::SameLine(ImGui::GetWindowWidth() - ImGui::GetCursorPosX() - 25_scaled);
ImGui::BeginDisabled(m_updateAllTask.isRunning() || m_updateCount == 0);
if (ImGuiExt::IconButton(ICON_VS_CLOUD_DOWNLOAD, ImGui::GetStyleColorVec4(ImGuiCol_Text))) {
m_updateAllTask = TaskManager::createTask("hex.builtin.task.updating_store"_lang, m_updateCount, [this](auto &task) {
for (auto &category : m_categories) {
for (auto &entry : category.entries) {
if (entry.hasUpdate) {
entry.downloading = this->download(category.path, entry.fileName, entry.link);
if (!m_download.valid())
continue;
m_download.wait();
while (m_download.valid() && m_download.wait_for(100ms) != std::future_status::ready) {
task.update();
}
entry.hasUpdate = false;
entry.downloading = false;
task.increment();
}
}
}
});
}
ImGuiExt::InfoTooltip(hex::format("hex.builtin.view.store.update_count"_lang, m_updateCount.load()).c_str());
ImGui::EndDisabled();
if (ImGui::BeginTabBar("storeTabs")) {
for (auto &category : m_categories) {
this->drawTab(category);
}
ImGui::EndTabBar();
}
}
void ViewStore::refresh() {
// Do not refresh if a refresh is already in progress
if (m_requestStatus == RequestStatus::InProgress)
return;
m_requestStatus = RequestStatus::InProgress;
for (auto &category : m_categories) {
category.entries.clear();
}
m_httpRequest.setUrl(ImHexApiURL + "/store"s);
m_apiRequest = m_httpRequest.execute();
}
void ViewStore::parseResponse() {
auto response = m_apiRequest.get();
m_requestStatus = response.isSuccess() ? RequestStatus::Succeeded : RequestStatus::Failed;
if (m_requestStatus == RequestStatus::Succeeded) {
auto json = nlohmann::json::parse(response.getData());
auto parseStoreEntries = [](auto storeJson, StoreCategory &category) {
// Check if the response handles the type of files
if (storeJson.contains(category.requestName)) {
for (auto &entry : storeJson[category.requestName]) {
// Check if entry is valid
if (entry.contains("name") && entry.contains("desc") && entry.contains("authors") && entry.contains("file") && entry.contains("url") && entry.contains("hash") && entry.contains("folder")) {
// Parse entry
StoreEntry storeEntry = { entry["name"], entry["desc"], entry["authors"], entry["file"], entry["url"], entry["hash"], entry["folder"], false, false, false, false };
updateEntryMetadata(storeEntry, category);
category.entries.push_back(storeEntry);
}
}
}
std::sort(category.entries.begin(), category.entries.end(), [](const auto &lhs, const auto &rhs) {
return lhs.name < rhs.name;
});
};
for (auto &category : m_categories) {
parseStoreEntries(json, category);
}
m_updateCount = 0;
for (auto &category : m_categories) {
for (auto &entry : category.entries) {
if (entry.hasUpdate)
m_updateCount += 1;
}
}
}
m_apiRequest = {};
}
void ViewStore::drawContent() {
if (m_requestStatus == RequestStatus::Failed)
ImGuiExt::TextFormattedColored(ImGuiExt::GetCustomColorVec4(ImGuiCustomCol_ToolbarRed), "hex.builtin.view.store.netfailed"_lang);
this->drawStore();
}
bool ViewStore::download(const paths::impl::DefaultPath *pathType, const std::string &fileName, const std::string &url) {
bool downloading = false;
for (const auto &folderPath : pathType->write()) {
if (!fs::isPathWritable(folderPath))
continue;
// Verify that we write the file to the right folder
// this is to prevent the filename from having elements like ../
auto fullPath = std::fs::weakly_canonical(folderPath / std::fs::path(fileName));
auto [folderIter, pathIter] = std::mismatch(folderPath.begin(), folderPath.end(), fullPath.begin());
if (folderIter != folderPath.end()) {
log::warn("The destination file name '{}' is invalid", fileName);
return false;
}
downloading = true;
m_downloadPath = fullPath;
m_httpRequest.setUrl(url);
m_download = m_httpRequest.downloadFile(fullPath);
break;
}
if (!downloading) {
ui::ToastError::open("hex.builtin.view.store.download_error"_lang);
return false;
}
return downloading;
}
bool ViewStore::remove(const paths::impl::DefaultPath *pathType, const std::string &fileName) {
bool removed = true;
for (const auto &path : pathType->write()) {
const auto filePath = path / fileName;
const auto folderPath = (path / std::fs::path(fileName).stem());
wolv::io::fs::remove(filePath);
wolv::io::fs::removeAll(folderPath);
removed = removed && !wolv::io::fs::exists(filePath) && !wolv::io::fs::exists(folderPath);
EventStoreContentRemoved::post(filePath);
}
return removed;
}
void ViewStore::addCategory(const UnlocalizedString &unlocalizedName, const std::string &requestName, const paths::impl::DefaultPath *path, std::function<void()> downloadCallback) {
m_categories.push_back({ unlocalizedName, requestName, path, { }, std::move(downloadCallback) });
}
void ViewStore::handleDownloadFinished(const StoreCategory &category, StoreEntry &entry) {
entry.downloading = false;
auto response = m_download.get();
if (response.isSuccess()) {
if (entry.hasUpdate)
m_updateCount -= 1;
entry.installed = true;
entry.hasUpdate = false;
entry.system = false;
if (entry.isFolder) {
Tar tar(m_downloadPath, Tar::Mode::Read);
tar.extractAll(m_downloadPath.parent_path() / m_downloadPath.stem());
EventStoreContentDownloaded::post(m_downloadPath.parent_path() / m_downloadPath.stem());
} else {
EventStoreContentDownloaded::post(m_downloadPath);
}
category.downloadCallback();
} else {
log::error("Download failed! HTTP Code {}", response.getStatusCode());
}
m_download = {};
}
}
| 16,185
|
C++
|
.cpp
| 306
| 37.388889
| 213
| 0.544575
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
247
|
view_tutorials.cpp
|
WerWolv_ImHex/plugins/builtin/source/content/views/view_tutorials.cpp
|
#include "content/views/view_tutorials.hpp"
#include <hex/api/content_registry.hpp>
#include <hex/api/tutorial_manager.hpp>
#include <hex/api/task_manager.hpp>
#include <fonts/codicons_font.h>
#include <ranges>
namespace hex::plugin::builtin {
ViewTutorials::ViewTutorials() : View::Floating("hex.builtin.view.tutorials.name") {
ContentRegistry::Interface::addMenuItem({ "hex.builtin.menu.help", "hex.builtin.view.tutorials.name" }, ICON_VS_COMPASS, 4000, Shortcut::None, [&, this] {
this->getWindowOpenState() = true;
});
RequestOpenWindow::subscribe(this, [this](const std::string &name) {
if (name == "Tutorials") {
TaskManager::doLater([this] {
this->getWindowOpenState() = true;
});
}
});
}
void ViewTutorials::drawContent() {
const auto& tutorials = TutorialManager::getTutorials();
const auto& currTutorial = TutorialManager::getCurrentTutorial();
if (ImGui::BeginTable("TutorialLayout", 2, ImGuiTableFlags_SizingFixedFit)) {
ImGui::TableSetupColumn("Name", ImGuiTableColumnFlags_WidthStretch, 0.3F);
ImGui::TableSetupColumn("Description", ImGuiTableColumnFlags_WidthStretch, 0.7F);
ImGui::TableNextRow();
ImGui::TableNextColumn();
if (ImGui::BeginTable("Tutorials", 1, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg, ImGui::GetContentRegionAvail())) {
for (const auto &tutorial : tutorials | std::views::values) {
if (m_selectedTutorial == nullptr)
m_selectedTutorial = &tutorial;
ImGui::TableNextRow();
ImGui::TableNextColumn();
if (ImGui::Selectable(Lang(tutorial.getUnlocalizedName()), m_selectedTutorial == &tutorial, ImGuiSelectableFlags_SpanAllColumns)) {
m_selectedTutorial = &tutorial;
}
}
ImGui::EndTable();
}
ImGui::TableNextColumn();
if (m_selectedTutorial != nullptr) {
if (ImGuiExt::BeginSubWindow("hex.builtin.view.tutorials.description"_lang, nullptr, ImGui::GetContentRegionAvail() - ImVec2(0, ImGui::GetTextLineHeightWithSpacing() + ImGui::GetStyle().ItemSpacing.y * 2))) {
ImGuiExt::TextFormattedWrapped(Lang(m_selectedTutorial->getUnlocalizedDescription()));
}
ImGuiExt::EndSubWindow();
ImGui::BeginDisabled(currTutorial != tutorials.end());
if (ImGuiExt::DimmedButton("hex.builtin.view.tutorials.start"_lang, ImVec2(ImGui::GetContentRegionAvail().x, 0))) {
TutorialManager::startTutorial(m_selectedTutorial->getUnlocalizedName());
this->getWindowOpenState() = false;
}
ImGui::EndDisabled();
}
ImGui::EndTable();
}
}
}
| 3,021
|
C++
|
.cpp
| 56
| 40.910714
| 224
| 0.604004
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
248
|
popup_hex_editor_find.cpp
|
WerWolv_ImHex/plugins/builtin/source/content/popups/hex_editor/popup_hex_editor_find.cpp
|
#include "content/popups/hex_editor/popup_hex_editor_find.hpp"
#include "content/views/view_hex_editor.hpp"
#include <hex/helpers/crypto.hpp>
#include <hex/helpers/utils.hpp>
#include <hex/providers/buffered_reader.hpp>
#include <fonts/codicons_font.h>
#include <bit>
#include <codecvt>
namespace hex::plugin::builtin {
PerProvider<std::string> PopupFind::s_inputString;
PerProvider<PopupFind::SearchMode> PopupFind::s_searchMode;
PopupFind::PopupFind(ViewHexEditor *editor) noexcept {
EventRegionSelected::subscribe(this, [this](Region region) {
m_foundRegion = region;
});
m_foundRegion = editor->getSelection();
}
PopupFind::~PopupFind() {
EventRegionSelected::unsubscribe(this);
}
void PopupFind::draw(ViewHexEditor *editor) {
auto lastMode = *s_searchMode;
if (ImGui::BeginTabBar("##find_tabs")) {
if (ImGui::BeginTabItem("hex.builtin.view.hex_editor.search.hex"_lang)) {
s_searchMode = SearchMode::ByteSequence;
this->drawTabContents();
ImGui::EndTabItem();
}
if (ImGui::BeginTabItem("hex.builtin.view.hex_editor.search.string"_lang)) {
s_searchMode = SearchMode::String;
this->drawTabContents();
ImGui::EndTabItem();
}
ImGui::EndTabBar();
}
if(ImGuiExt::IconHyperlink(ICON_VS_SEARCH, "hex.builtin.view.hex_editor.search.advanced"_lang)) {
TaskManager::doLater([editor] {
const auto& view = ContentRegistry::Views::getViewByName("hex.builtin.view.find.name");
view->getWindowOpenState() = true;
ImGui::SetWindowFocus(view->getName().c_str());
editor->closePopup();
});
}
if (lastMode != *s_searchMode) {
m_requestFocus = true;
s_inputString->clear();
}
const auto doSearch = [this, editor](auto &) {
auto region = this->findByteSequence(m_searchByteSequence);
if (region.has_value()) {
m_foundRegion = region.value();
if (editor->getSelection() != region) {
TaskManager::doLater([editor, region] {
editor->setSelection(region->getStartAddress(), region->getEndAddress());
editor->jumpToSelection();
});
}
m_reachedEnd = false;
} else {
m_reachedEnd = true;
}
m_requestSearch = false;
m_requestFocus = true;
};
if (m_requestSearch) {
this->processInputString();
if (!m_searchTask.isRunning() && !m_searchByteSequence.empty()) {
m_searchTask = TaskManager::createTask("hex.ui.common.processing"_lang,
ImHexApi::Provider::get()->getActualSize(),
doSearch);
}
m_requestSearch = false;
}
}
void PopupFind::drawSearchDirectionButtons() {
const auto ButtonSize = ImVec2(ImGui::CalcTextSize(ICON_VS_SEARCH).x, ImGui::GetTextLineHeight()) +
ImGui::GetStyle().CellPadding * 2;
const auto ButtonColor = ImGui::GetStyleColorVec4(ImGuiCol_Text);
if (m_requestFocus) {
ImGui::SetKeyboardFocusHere(-1);
m_requestFocus = false;
}
ImGui::BeginDisabled(m_searchTask.isRunning());
{
ImGui::SameLine();
if (ImGuiExt::IconButton(ICON_VS_ARROW_UP "##up", ButtonColor, ButtonSize)) {
m_requestSearch = true;
m_searchBackwards = true;
}
ImGui::SameLine();
if (ImGuiExt::IconButton(ICON_VS_ARROW_DOWN "##down", ButtonColor, ButtonSize)) {
m_requestSearch = true;
m_searchBackwards = false;
}
}
ImGui::EndDisabled();
}
void PopupFind::drawTabContents() {
constexpr static std::array EncodingNames = {
"hex.builtin.view.hex_editor.search.string.encoding.utf8",
"hex.builtin.view.hex_editor.search.string.encoding.utf16",
"hex.builtin.view.hex_editor.search.string.encoding.utf32"
};
constexpr static std::array EndiannessNames = {
"hex.builtin.view.hex_editor.search.string.endianness.little",
"hex.builtin.view.hex_editor.search.string.endianness.big"
};
const char *searchInputIcon = nullptr;
ImGuiInputTextFlags searchInputFlags = 0;
// Set search input icon and flags
switch (*s_searchMode) {
case SearchMode::ByteSequence:
searchInputIcon = ICON_VS_SYMBOL_NUMERIC;
searchInputFlags = ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_AutoSelectAll |
ImGuiInputTextFlags_CharsHexadecimal;
break;
case SearchMode::String:
searchInputIcon = ICON_VS_SYMBOL_KEY;
searchInputFlags = ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_AutoSelectAll;
break;
default:
break;
}
// Draw search input
if (ImGuiExt::InputTextIcon("##input", searchInputIcon, s_inputString, searchInputFlags)) {
if (!s_inputString->empty()) {
m_requestSearch = true;
m_searchBackwards = ImGui::GetIO().KeyShift;
}
}
// Draw search direction buttons
ImGui::BeginDisabled(s_inputString->empty());
this->drawSearchDirectionButtons();
ImGui::EndDisabled();
// Draw search options for string search
if (*s_searchMode == SearchMode::String) {
if (ImGui::BeginCombo("hex.builtin.view.hex_editor.search.string.encoding"_lang, Lang(EncodingNames[std::to_underlying<Encoding>(m_stringEncoding.load())]))) {
if (ImGui::Selectable(Lang(EncodingNames[0]), m_stringEncoding == Encoding::UTF8)) {
m_stringEncoding = Encoding::UTF8;
}
if (ImGui::Selectable(Lang(EncodingNames[1]), m_stringEncoding == Encoding::UTF16)) {
m_stringEncoding = Encoding::UTF16;
}
if (ImGui::Selectable(Lang(EncodingNames[2]), m_stringEncoding == Encoding::UTF32)) {
m_stringEncoding = Encoding::UTF32;
}
ImGui::EndCombo();
}
ImGui::BeginDisabled(m_stringEncoding == Encoding::UTF8);
{
if (ImGui::BeginCombo("hex.builtin.view.hex_editor.search.string.endianness"_lang, Lang(EndiannessNames[std::to_underlying<Endianness>(m_stringEndianness.load())]))) {
if (ImGui::Selectable(Lang(EndiannessNames[0]), m_stringEndianness == Endianness::Little)) {
m_stringEndianness = Endianness::Little;
}
if (ImGui::Selectable(Lang(EndiannessNames[1]), m_stringEndianness == Endianness::Big)) {
m_stringEndianness = Endianness::Big;
}
ImGui::EndCombo();
}
}
ImGui::EndDisabled();
}
if (m_reachedEnd) {
ImGui::TextUnformatted("hex.builtin.view.hex_editor.search.no_more_results"_lang);
} else {
ImGui::NewLine();
}
}
std::optional<Region> PopupFind::findByteSequence(const std::vector<u8> &sequence) const {
if (sequence.empty())
return std::nullopt;
auto provider = ImHexApi::Provider::get();
if (provider == nullptr)
return std::nullopt;
const auto providerSize = provider->getActualSize();
if (providerSize == 0x00)
return std::nullopt;
prv::ProviderReader reader(provider);
auto startAbsolutePosition = provider->getBaseAddress();
auto endAbsolutePosition = provider->getBaseAddress() + providerSize - 1;
constexpr static auto searchFunction = [](const auto &haystackBegin, const auto &haystackEnd,
const auto &needleBegin, const auto &needleEnd) {
return std::search(haystackBegin, haystackEnd, needleBegin, needleEnd);
};
if (!m_searchBackwards) {
if (m_reachedEnd || !m_foundRegion.has_value()) {
reader.seek(startAbsolutePosition);
} else {
reader.seek(m_foundRegion->getStartAddress() + 1);
}
reader.setEndAddress(endAbsolutePosition);
auto occurrence = searchFunction(reader.begin(), reader.end(), sequence.begin(), sequence.end());
if (occurrence != reader.end()) {
return Region{occurrence.getAddress(), sequence.size()};
}
} else {
if (m_reachedEnd || !m_foundRegion.has_value()) {
reader.setEndAddress(endAbsolutePosition);
} else {
reader.setEndAddress(m_foundRegion->getEndAddress() - 1);
}
reader.seek(startAbsolutePosition);
auto occurrence = searchFunction(reader.rbegin(), reader.rend(), sequence.rbegin(), sequence.rend());
if (occurrence != reader.rend()) {
return Region{occurrence.getAddress() - (sequence.size() - 1), sequence.size()};
}
}
return std::nullopt;
}
void PopupFind::processInputString() {
m_searchByteSequence.clear();
constexpr auto swapEndianness = [](auto &value, Encoding encoding, Endianness endianness) {
if (encoding == Encoding::UTF16 || encoding == Encoding::UTF32) {
std::endian endian = (endianness == Endianness::Little)
? std::endian::little
: std::endian::big;
value = hex::changeEndianness(value, endian);
}
};
switch (*s_searchMode) {
case SearchMode::ByteSequence: {
m_searchByteSequence = crypt::decode16(s_inputString);
break;
}
case SearchMode::String: {
switch (m_stringEncoding) {
case Encoding::UTF8: {
std::copy_n(s_inputString->data(), s_inputString->size(),
std::back_inserter(m_searchByteSequence));
break;
}
case Encoding::UTF16: {
std::wstring_convert<std::codecvt_utf8<char16_t>, char16_t> convert16;
auto utf16 = convert16.from_bytes(s_inputString);
for (auto &c: utf16) {
swapEndianness(c, Encoding::UTF16, m_stringEndianness);
}
std::copy(reinterpret_cast<const u8 *>(utf16.data()),
reinterpret_cast<const u8 *>(utf16.data() + utf16.size()),
std::back_inserter(m_searchByteSequence));
break;
}
case Encoding::UTF32: {
std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> convert32;
auto utf32 = convert32.from_bytes(s_inputString);
for (auto &c: utf32) {
swapEndianness(c, Encoding::UTF32, m_stringEndianness);
}
std::copy(reinterpret_cast<const u8 *>(utf32.data()),
reinterpret_cast<const u8 *>(utf32.data() + utf32.size()),
std::back_inserter(m_searchByteSequence));
break;
}
default:
break;
}
break;
}
default:
break;
}
}
[[nodiscard]] UnlocalizedString PopupFind::getTitle() const {
return "hex.builtin.view.hex_editor.menu.file.search";
}
}
| 12,845
|
C++
|
.cpp
| 266
| 32.233083
| 184
| 0.530342
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
249
|
library_ui.cpp
|
WerWolv_ImHex/plugins/ui/source/library_ui.cpp
|
#include <hex/plugin.hpp>
#include <hex/api/content_registry.hpp>
#include <hex/helpers/logger.hpp>
#include <romfs/romfs.hpp>
#include <ui/hex_editor.hpp>
#include <ui/pattern_drawer.hpp>
#include <ui/widgets.hpp>
IMHEX_LIBRARY_SETUP("UI") {
hex::log::debug("Using romfs: '{}'", romfs::name());
for (auto &path : romfs::list("lang"))
hex::ContentRegistry::Language::addLocalization(nlohmann::json::parse(romfs::get(path).string()));
}
| 455
|
C++
|
.cpp
| 12
| 35.333333
| 106
| 0.704545
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
250
|
pattern_drawer.cpp
|
WerWolv_ImHex/plugins/ui/source/ui/pattern_drawer.cpp
|
#include <ui/pattern_drawer.hpp>
#include <pl/core/lexer.hpp>
#include <pl/patterns/pattern_array_dynamic.hpp>
#include <pl/patterns/pattern_array_static.hpp>
#include <pl/patterns/pattern_bitfield.hpp>
#include <pl/patterns/pattern_boolean.hpp>
#include <pl/patterns/pattern_character.hpp>
#include <pl/patterns/pattern_enum.hpp>
#include <pl/patterns/pattern_float.hpp>
#include <pl/patterns/pattern_pointer.hpp>
#include <pl/patterns/pattern_signed.hpp>
#include <pl/patterns/pattern_string.hpp>
#include <pl/patterns/pattern_struct.hpp>
#include <pl/patterns/pattern_union.hpp>
#include <pl/patterns/pattern_unsigned.hpp>
#include <pl/patterns/pattern_wide_character.hpp>
#include <pl/patterns/pattern_wide_string.hpp>
#include <string>
#include <hex/api/imhex_api.hpp>
#include <hex/api/content_registry.hpp>
#include <hex/api/achievement_manager.hpp>
#include <hex/api/localization_manager.hpp>
#include <hex/helpers/utils.hpp>
#include <wolv/math_eval/math_evaluator.hpp>
#include <TextEditor.h>
#include <imgui.h>
#include <hex/ui/imgui_imhex_extensions.h>
#include <fonts/codicons_font.h>
#include <wolv/io/file.hpp>
namespace hex::ui {
namespace {
std::mutex s_resetDrawMutex;
constexpr auto DisplayEndDefault = 50U;
using namespace ::std::literals::string_literals;
bool isPatternOverlapSelected(u64 address, u64 size) {
auto currSelection = ImHexApi::HexEditor::getSelection();
if (!currSelection.has_value())
return false;
return Region(address, size).overlaps(*currSelection);
}
bool isPatternFullySelected(u64 address, u64 size) {
auto currSelection = ImHexApi::HexEditor::getSelection();
if (!currSelection.has_value())
return false;
return currSelection->address == address && currSelection->size == size;
}
template<typename T>
auto highlightWhenSelected(u64 address, u64 size, const T &callback) {
constexpr static bool HasReturn = !requires(T t) { { t() } -> std::same_as<void>; };
const auto overlapSelected = isPatternOverlapSelected(address, size);
const auto fullySelected = isPatternFullySelected(address, size);
const u32 selectionColor = ImColor(ImGuiExt::GetCustomColorVec4(ImGuiCustomCol_PatternSelected));
if (overlapSelected)
ImGui::PushStyleColor(ImGuiCol_Text, selectionColor);
if (fullySelected)
ImGui::TableSetBgColor(ImGuiTableBgTarget_RowBg0, (selectionColor & 0x00'FF'FF'FF) | 0x30'00'00'00);
if constexpr (HasReturn) {
auto result = callback();
if (overlapSelected)
ImGui::PopStyleColor();
return result;
} else {
callback();
if (overlapSelected)
ImGui::PopStyleColor();
}
}
template<typename T>
auto highlightWhenSelected(const pl::ptrn::Pattern& pattern, const T &callback) {
return highlightWhenSelected(pattern.getOffset(), pattern.getSize(), callback);
}
void drawTypeNameColumn(const pl::ptrn::Pattern& pattern, const std::string& structureTypeName) {
ImGui::TableNextColumn();
ImGuiExt::TextFormattedColored(TextEditor::GetPalette()[u32(TextEditor::PaletteIndex::Keyword)], structureTypeName);
ImGui::SameLine();
ImGui::TextUnformatted(pattern.getTypeName().c_str());
}
void drawOffsetColumnForBitfieldMember(const pl::ptrn::PatternBitfieldMember &pattern) {
if (pattern.isPatternLocal()) {
ImGui::TableNextColumn();
ImGuiExt::TextFormatted("[{}]", "hex.ui.pattern_drawer.local"_lang);
ImGui::TableNextColumn();
ImGuiExt::TextFormatted("[{}]", "hex.ui.pattern_drawer.local"_lang);
} else {
ImGui::TableNextColumn();
ImGuiExt::TextFormatted("0x{0:08X}.{1}", pattern.getOffset(), pattern.getBitOffsetForDisplay());
ImGui::TableNextColumn();
const auto bitSize = (pattern.getBitOffsetForDisplay() + pattern.getBitSize() - (pattern.getSize() == 0 ? 0 : 1));
ImGuiExt::TextFormatted("0x{0:08X}.{1}", pattern.getOffset() + (bitSize / 8), bitSize % 8);
}
}
void drawOffsetColumns(const pl::ptrn::Pattern& pattern) {
auto *bitfieldMember = dynamic_cast<const pl::ptrn::PatternBitfieldMember*>(&pattern);
if (bitfieldMember != nullptr && bitfieldMember->getParentBitfield() != nullptr) {
drawOffsetColumnForBitfieldMember(*bitfieldMember);
return;
}
ImGui::TableNextColumn();
if (pattern.isPatternLocal()) {
ImGuiExt::TextFormatted("[{}]", "hex.ui.pattern_drawer.local"_lang);
} else {
ImGuiExt::TextFormatted("0x{0:08X}", pattern.getOffset());
}
ImGui::TableNextColumn();
if (pattern.isPatternLocal()) {
ImGuiExt::TextFormatted("[{}]", "hex.ui.pattern_drawer.local"_lang);
} else {
ImGuiExt::TextFormatted("0x{0:08X}", pattern.getOffset() + pattern.getSize() - (pattern.getSize() == 0 ? 0 : 1));
}
}
void drawSizeColumnForBitfieldMember(const pl::ptrn::PatternBitfieldMember &pattern) {
ImGui::TableNextColumn();
auto bits = pattern.getBitSize();
auto bytes = bits / 8;
bits = bits % 8;
std::string text;
if (bytes != 0) {
if (bytes == 1)
text += hex::format("{0} byte", bytes);
else
text += hex::format("{0} bytes", bytes);
if (bits != 0)
text += ", ";
}
if (bits != 0) {
if (bits == 1)
text += hex::format("{0} bit", bits);
else
text += hex::format("{0} bits", bits);
}
if (bytes == 0 && bits == 0) {
text = "0 bytes";
}
ImGui::TextUnformatted(text.c_str());
}
void drawSizeColumn(const pl::ptrn::Pattern& pattern) {
if (pattern.isPatternLocal()) {
ImGui::TableNextColumn();
return;
}
if (auto *bitfieldMember = dynamic_cast<const pl::ptrn::PatternBitfieldMember*>(&pattern); bitfieldMember != nullptr && bitfieldMember->getParentBitfield() != nullptr)
drawSizeColumnForBitfieldMember(*bitfieldMember);
else {
ImGui::TableNextColumn();
auto size = pattern.getSize();
ImGuiExt::TextFormatted("{0:d} {1}", size, size == 1 ? "byte" : "bytes");
}
}
void drawCommentTooltip(const pl::ptrn::Pattern &pattern) {
if (auto comment = pattern.getComment(); !comment.empty()) {
ImGuiExt::InfoTooltip(comment.c_str());
}
}
}
std::optional<PatternDrawer::Filter> PatternDrawer::parseRValueFilter(const std::string &filter) {
Filter result;
if (filter.empty()) {
return result;
}
result.path.emplace_back();
for (size_t i = 0; i < filter.size(); i += 1) {
char c = filter[i];
if (i < filter.size() - 1 && c == '=' && filter[i + 1] == '=') {
pl::core::Lexer lexer;
pl::api::Source source(filter.substr(i + 2));
auto tokens = lexer.lex(&source);
if (!tokens.isOk() || tokens.unwrap().size() != 2)
return std::nullopt;
auto literal = std::get_if<pl::core::Token::Literal>(&tokens.unwrap().front().value);
if (literal == nullptr)
return std::nullopt;
result.value = *literal;
break;
} else if (c == '.') {
result.path.emplace_back();
} else if (c == '[') {
result.path.emplace_back();
result.path.back() += c;
} else if (c == ' ') {
// Skip whitespace
} else {
result.path.back() += c;
}
}
return result;
}
void PatternDrawer::updateFilter() {
m_filteredPatterns.clear();
if (m_filter.path.empty()) {
m_filteredPatterns = m_sortedPatterns;
return;
}
std::vector<std::string> treePath;
for (auto &pattern : m_sortedPatterns) {
traversePatternTree(*pattern, treePath, [this, &treePath](auto &pattern){
if (matchesFilter(m_filter.path, treePath, false))
m_filteredPatterns.push_back(&pattern);
});
}
}
bool PatternDrawer::isEditingPattern(const pl::ptrn::Pattern& pattern) const {
return m_editingPattern == &pattern && m_editingPatternOffset == pattern.getOffset();
}
void PatternDrawer::resetEditing() {
m_editingPattern = nullptr;
m_editingPatternOffset = 0x00;
}
bool PatternDrawer::matchesFilter(const std::vector<std::string> &filterPath, const std::vector<std::string> &patternPath, bool fullMatch) {
if (fullMatch) {
if (patternPath.size() != filterPath.size())
return false;
}
if (filterPath.size() > patternPath.size())
return false;
auto commonSize = std::min(filterPath.size(), patternPath.size());
for (size_t i = patternPath.size() - commonSize; i < patternPath.size(); i += 1) {
const auto &filter = filterPath[i - (patternPath.size() - commonSize)];
if (filter.empty())
return false;
if (filter != "*") {
if (i == (patternPath.size() - 1)) {
if (!patternPath[i].starts_with(filter))
return false;
} else {
if (patternPath[i] != filter)
return false;
}
}
}
return true;
}
void PatternDrawer::drawFavoriteColumn(const pl::ptrn::Pattern& pattern) {
ImGui::TableNextColumn();
if (!m_showFavoriteStars) {
return;
}
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0));
if (m_favorites.contains(m_currPatternPath)) {
if (ImGuiExt::DimmedIconButton(ICON_VS_STAR_DELETE, ImGui::GetStyleColorVec4(ImGuiCol_PlotHistogram))) {
m_favorites.erase(m_currPatternPath);
}
}
else {
if (ImGuiExt::DimmedIconButton(ICON_VS_STAR_ADD, ImGui::GetStyleColorVec4(ImGuiCol_TextDisabled))) {
m_favorites.insert({ m_currPatternPath, pattern.clone() });
}
}
ImGui::PopStyleVar();
}
bool PatternDrawer::drawNameColumn(const pl::ptrn::Pattern &pattern, bool leaf) {
bool open = createTreeNode(pattern, leaf);
ImGui::SameLine(0, 0);
makeSelectable(pattern);
drawCommentTooltip(pattern);
return open;
}
void PatternDrawer::drawColorColumn(const pl::ptrn::Pattern& pattern) {
ImGui::TableNextColumn();
if (pattern.getVisibility() == pl::ptrn::Visibility::Visible) {
ImGui::TableSetBgColor(ImGuiTableBgTarget_CellBg, (pattern.getColor() & 0x00'FF'FF'FF) | 0xC0'00'00'00);
if (m_rowColoring)
ImGui::TableSetBgColor(ImGuiTableBgTarget_RowBg0, (pattern.getColor() & 0x00'FF'FF'FF) | 0x30'00'00'00);
}
}
void PatternDrawer::drawCommentColumn(const pl::ptrn::Pattern& pattern) {
ImGui::TableNextColumn();
ImGui::TextUnformatted(pattern.getComment().c_str());
}
void PatternDrawer::drawVisualizer(const std::map<std::string, ContentRegistry::PatternLanguage::impl::Visualizer> &visualizers, const std::vector<pl::core::Token::Literal> &arguments, pl::ptrn::Pattern &pattern, bool reset) {
auto visualizerName = arguments.front().toString(true);
if (auto entry = visualizers.find(visualizerName); entry != visualizers.end()) {
const auto &[name, visualizer] = *entry;
auto paramCount = arguments.size() - 1;
auto [minParams, maxParams] = visualizer.parameterCount;
if (paramCount >= minParams && paramCount <= maxParams) {
try {
visualizer.callback(pattern, reset, { arguments.begin() + 1, arguments.end() });
} catch (std::exception &e) {
m_lastVisualizerError = e.what();
}
} else {
ImGui::TextUnformatted("hex.ui.pattern_drawer.visualizer.invalid_parameter_count"_lang);
}
} else {
ImGui::TextUnformatted("hex.ui.pattern_drawer.visualizer.unknown"_lang);
}
if (!m_lastVisualizerError.empty())
ImGui::TextUnformatted(m_lastVisualizerError.c_str());
}
void PatternDrawer::drawValueColumn(pl::ptrn::Pattern& pattern) {
ImGui::TableNextColumn();
std::string value;
try {
value = pattern.getFormattedValue();
} catch (const std::exception &e) {
value = e.what();
}
const auto width = ImGui::GetColumnWidth();
if (const auto &visualizeArgs = pattern.getAttributeArguments("hex::visualize"); !visualizeArgs.empty()) {
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0));
ImGui::PushStyleVar(ImGuiStyleVar_ButtonTextAlign, ImVec2(0, 0.5F));
bool shouldReset = false;
if (ImGui::Button(hex::format(" {} {}", ICON_VS_EYE_WATCH, value).c_str(), ImVec2(width, ImGui::GetTextLineHeight()))) {
auto previousPattern = m_currVisualizedPattern;
m_currVisualizedPattern = &pattern;
if (!m_lastVisualizerError.empty() || m_currVisualizedPattern != previousPattern)
shouldReset = true;
m_lastVisualizerError.clear();
ImGui::OpenPopup("Visualizer");
}
ImGui::PopStyleVar(2);
ImGui::SameLine();
if (ImGui::BeginPopup("Visualizer")) {
if (m_currVisualizedPattern == &pattern) {
drawVisualizer(ContentRegistry::PatternLanguage::impl::getVisualizers(), visualizeArgs, pattern, !m_visualizedPatterns.contains(&pattern) || shouldReset);
m_visualizedPatterns.insert(&pattern);
}
ImGui::EndPopup();
}
} else if (const auto &inlineVisualizeArgs = pattern.getAttributeArguments("hex::inline_visualize"); !inlineVisualizeArgs.empty()) {
drawVisualizer(ContentRegistry::PatternLanguage::impl::getInlineVisualizers(), inlineVisualizeArgs, pattern, true);
} else {
ImGuiExt::TextFormatted("{}", value);
}
if (ImGui::CalcTextSize(value.c_str()).x > width) {
ImGuiExt::InfoTooltip(value.c_str());
}
}
std::string PatternDrawer::getDisplayName(const pl::ptrn::Pattern& pattern) const {
if (m_showSpecName && pattern.hasAttribute("hex::spec_name"))
return pattern.getAttributeArguments("hex::spec_name")[0].toString(true);
else
return pattern.getDisplayName();
}
bool PatternDrawer::createTreeNode(const pl::ptrn::Pattern& pattern, bool leaf) {
ImGui::TableNextRow();
drawFavoriteColumn(pattern);
bool shouldOpen = false;
if (m_jumpToPattern != nullptr) {
if (m_jumpToPattern == &pattern) {
ImGui::SetScrollHereY();
m_jumpToPattern = nullptr;
}
else {
auto parent = m_jumpToPattern->getParent();
while (parent != nullptr) {
if (&pattern == parent) {
ImGui::SetScrollHereY();
shouldOpen = true;
break;
}
parent = parent->getParent();
}
}
}
ImGui::TableNextColumn();
if (pattern.isSealed() || leaf) {
ImGui::Indent();
highlightWhenSelected(pattern, [&]{ ImGui::TextUnformatted(this->getDisplayName(pattern).c_str()); });
ImGui::Unindent();
return false;
}
return highlightWhenSelected(pattern, [&]{
if (shouldOpen)
ImGui::SetNextItemOpen(true, ImGuiCond_Always);
switch (m_treeStyle) {
using enum TreeStyle;
default:
case Default:
return ImGui::TreeNodeEx(this->getDisplayName(pattern).c_str(), ImGuiTreeNodeFlags_SpanFullWidth);
case AutoExpanded:
return ImGui::TreeNodeEx(this->getDisplayName(pattern).c_str(), ImGuiTreeNodeFlags_SpanFullWidth | ImGuiTreeNodeFlags_DefaultOpen);
case Flattened:
return ImGui::TreeNodeEx(this->getDisplayName(pattern).c_str(), ImGuiTreeNodeFlags_SpanFullWidth | ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen);
}
});
}
void PatternDrawer::makeSelectable(const pl::ptrn::Pattern &pattern) {
ImGui::PushID(static_cast<int>(pattern.getOffset()));
ImGui::PushID(pattern.getVariableName().c_str());
if (ImGui::Selectable("##PatternLine", false, ImGuiSelectableFlags_SpanAllColumns | ImGuiSelectableFlags_AllowOverlap)) {
m_selectionCallback(&pattern);
if (m_editingPattern != &pattern) {
this->resetEditing();
}
}
if (ImGui::IsItemHovered()) {
m_hoverCallback(&pattern);
if (ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left) && m_editingEnabled) {
m_editingPattern = &pattern;
m_editingPatternOffset = pattern.getOffset();
AchievementManager::unlockAchievement("hex.builtin.achievement.patterns", "hex.builtin.achievement.patterns.modify_data.name");
}
}
ImGui::SameLine(0, 0);
ImGui::PopID();
ImGui::PopID();
}
void PatternDrawer::createDefaultEntry(const pl::ptrn::Pattern &pattern) {
// Draw Name column
drawNameColumn(pattern, true);
// Draw Color column
drawColorColumn(pattern);
// Draw Start / End columns
drawOffsetColumns(pattern);
// Draw Size column
drawSizeColumn(pattern);
// Draw type column
ImGui::TableNextColumn();
ImGuiExt::TextFormattedColored(TextEditor::GetPalette()[u32(TextEditor::PaletteIndex::KnownIdentifier)], "{}", pattern.getFormattedName().empty() ? pattern.getTypeName() : pattern.getFormattedName());
}
void PatternDrawer::closeTreeNode(bool inlined) const {
if (!inlined && m_treeStyle != TreeStyle::Flattened)
ImGui::TreePop();
}
void PatternDrawer::visit(pl::ptrn::PatternArrayDynamic& pattern) {
drawArray(pattern, pattern, pattern.isInlined());
}
void PatternDrawer::visit(pl::ptrn::PatternArrayStatic& pattern) {
drawArray(pattern, pattern, pattern.isInlined());
}
void PatternDrawer::visit(pl::ptrn::PatternBitfieldField& pattern) {
drawNameColumn(pattern, true);
drawColorColumn(pattern);
drawOffsetColumnForBitfieldMember(pattern);
drawSizeColumnForBitfieldMember(pattern);
ImGui::TableNextColumn();
if (dynamic_cast<pl::ptrn::PatternBitfieldFieldSigned*>(&pattern) != nullptr) {
ImGuiExt::TextFormattedColored(TextEditor::GetPalette()[u32(TextEditor::PaletteIndex::Keyword)], "signed");
ImGui::SameLine();
ImGuiExt::TextFormattedColored(TextEditor::GetPalette()[u32(TextEditor::PaletteIndex::KnownIdentifier)], pattern.getBitSize() == 1 ? "bit" : "bits");
} else if (dynamic_cast<pl::ptrn::PatternBitfieldFieldEnum*>(&pattern) != nullptr) {
ImGuiExt::TextFormattedColored(TextEditor::GetPalette()[u32(TextEditor::PaletteIndex::Keyword)], "enum");
ImGui::SameLine();
ImGui::TextUnformatted(pattern.getTypeName().c_str());
} else if (dynamic_cast<pl::ptrn::PatternBitfieldFieldBoolean*>(&pattern) != nullptr) {
ImGuiExt::TextFormattedColored(TextEditor::GetPalette()[u32(TextEditor::PaletteIndex::KnownIdentifier)], "bool");
ImGui::SameLine();
ImGuiExt::TextFormattedColored(TextEditor::GetPalette()[u32(TextEditor::PaletteIndex::KnownIdentifier)], "bit");
} else {
ImGuiExt::TextFormattedColored(TextEditor::GetPalette()[u32(TextEditor::PaletteIndex::Keyword)], "unsigned");
ImGui::SameLine();
ImGuiExt::TextFormattedColored(TextEditor::GetPalette()[u32(TextEditor::PaletteIndex::KnownIdentifier)], pattern.getBitSize() == 1 ? "bit" : "bits");
}
if (!this->isEditingPattern(pattern)) {
drawValueColumn(pattern);
} else {
ImGui::TableNextColumn();
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0));
ImGui::PushItemWidth(ImGui::GetContentRegionAvail().x);
auto value = pattern.getValue();
auto valueString = pattern.toString();
if (auto enumPattern = dynamic_cast<pl::ptrn::PatternBitfieldFieldEnum*>(&pattern); enumPattern != nullptr) {
if (ImGui::BeginCombo("##Enum", pattern.getFormattedValue().c_str())) {
auto currValue = pattern.getValue().toUnsigned();
for (auto &[name, enumValue] : enumPattern->getEnumValues()) {
auto min = enumValue.min.toUnsigned();
auto max = enumValue.max.toUnsigned();
bool isSelected = min <= currValue && max >= currValue;
if (ImGui::Selectable(fmt::format("{}::{}", pattern.getTypeName(), name, min, pattern.getSize() * 2).c_str(), isSelected)) {
pattern.setValue(enumValue.min);
this->resetEditing();
}
if (isSelected)
ImGui::SetItemDefaultFocus();
}
ImGui::EndCombo();
}
} else if (dynamic_cast<pl::ptrn::PatternBitfieldFieldBoolean*>(&pattern) != nullptr) {
bool boolValue = value.toBoolean();
if (ImGui::Checkbox("##boolean", &boolValue)) {
pattern.setValue(boolValue);
}
} else if (std::holds_alternative<i128>(value)) {
ImGui::SetKeyboardFocusHere();
if (ImGui::InputText("##Value", valueString, ImGuiInputTextFlags_AutoSelectAll | ImGuiInputTextFlags_EnterReturnsTrue)) {
wolv::math_eval::MathEvaluator<i128> mathEvaluator;
if (auto result = mathEvaluator.evaluate(valueString); result.has_value())
pattern.setValue(result.value());
this->resetEditing();
}
} else if (std::holds_alternative<u128>(value)) {
ImGui::SetKeyboardFocusHere();
if (ImGui::InputText("##Value", valueString, ImGuiInputTextFlags_AutoSelectAll | ImGuiInputTextFlags_EnterReturnsTrue)) {
wolv::math_eval::MathEvaluator<u128> mathEvaluator;
if (auto result = mathEvaluator.evaluate(valueString); result.has_value())
pattern.setValue(result.value());
this->resetEditing();
}
}
ImGui::PopItemWidth();
ImGui::PopStyleVar();
}
drawCommentColumn(pattern);
}
void PatternDrawer::visit(pl::ptrn::PatternBitfieldArray& pattern) {
drawArray(pattern, pattern, pattern.isInlined());
}
void PatternDrawer::visit(pl::ptrn::PatternBitfield& pattern) {
bool open = true;
if (!pattern.isInlined() && m_treeStyle != TreeStyle::Flattened) {
open = drawNameColumn(pattern);
if (pattern.isSealed())
drawColorColumn(pattern);
else
ImGui::TableNextColumn();
drawOffsetColumns(pattern);
drawSizeColumn(pattern);
drawTypeNameColumn(pattern, "bitfield");
drawValueColumn(pattern);
drawCommentColumn(pattern);
}
if (!open) {
return;
}
int id = 1;
pattern.forEachEntry(0, pattern.getEntryCount(), [&] (u64, auto *field) {
ImGui::PushID(id);
this->draw(*field);
ImGui::PopID();
id += 1;
});
closeTreeNode(pattern.isInlined());
}
void PatternDrawer::visit(pl::ptrn::PatternBoolean& pattern) {
createDefaultEntry(pattern);
if (!this->isEditingPattern(pattern)) {
drawValueColumn(pattern);
} else {
ImGui::TableNextColumn();
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0));
ImGui::PushItemWidth(ImGui::GetContentRegionAvail().x);
bool value = pattern.getValue().toBoolean();
if (ImGui::Checkbox("##boolean", &value)) {
pattern.setValue(value);
}
ImGui::PopItemWidth();
ImGui::PopStyleVar();
}
drawCommentColumn(pattern);
}
void PatternDrawer::visit(pl::ptrn::PatternCharacter& pattern) {
createDefaultEntry(pattern);
if (!this->isEditingPattern(pattern)) {
drawValueColumn(pattern);
} else {
ImGui::TableNextColumn();
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0));
ImGui::PushItemWidth(ImGui::GetContentRegionAvail().x);
ImGui::SetKeyboardFocusHere();
auto value = hex::encodeByteString(pattern.getBytes());
if (ImGui::InputText("##Character", value.data(), value.size() + 1, ImGuiInputTextFlags_AutoSelectAll | ImGuiInputTextFlags_EnterReturnsTrue)) {
if (!value.empty()) {
auto result = hex::decodeByteString(value);
if (!result.empty())
pattern.setValue(char(result[0]));
this->resetEditing();
}
}
ImGui::PopItemWidth();
ImGui::PopStyleVar();
}
drawCommentColumn(pattern);
}
void PatternDrawer::visit(pl::ptrn::PatternEnum& pattern) {
drawNameColumn(pattern, true);
drawColorColumn(pattern);
drawOffsetColumns(pattern);
drawSizeColumn(pattern);
drawTypeNameColumn(pattern, "enum");
if (!this->isEditingPattern(pattern)) {
drawValueColumn(pattern);
} else {
ImGui::TableNextColumn();
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0));
ImGui::PushItemWidth(ImGui::GetContentRegionAvail().x);
if (ImGui::BeginCombo("##Enum", pattern.getFormattedValue().c_str())) {
auto currValue = pattern.getValue().toUnsigned();
for (auto &[name, enumValue] : pattern.getEnumValues()) {
auto min = enumValue.min.toUnsigned();
auto max = enumValue.max.toUnsigned();
bool isSelected = min <= currValue && max >= currValue;
if (ImGui::Selectable(fmt::format("{}::{}", pattern.getTypeName(), name, min, pattern.getSize() * 2).c_str(), isSelected)) {
pattern.setValue(enumValue.min);
this->resetEditing();
}
if (isSelected)
ImGui::SetItemDefaultFocus();
}
ImGui::EndCombo();
}
ImGui::PopItemWidth();
ImGui::PopStyleVar();
}
drawCommentColumn(pattern);
}
void PatternDrawer::visit(pl::ptrn::PatternFloat& pattern) {
createDefaultEntry(pattern);
if (!this->isEditingPattern(pattern)) {
drawValueColumn(pattern);
} else {
ImGui::TableNextColumn();
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0));
ImGui::PushItemWidth(ImGui::GetContentRegionAvail().x);
ImGui::SetKeyboardFocusHere();
auto value = pattern.toString();
if (ImGui::InputText("##Value", value, ImGuiInputTextFlags_AutoSelectAll | ImGuiInputTextFlags_EnterReturnsTrue)) {
wolv::math_eval::MathEvaluator<long double> mathEvaluator;
if (auto result = mathEvaluator.evaluate(value); result.has_value())
pattern.setValue(double(result.value()));
this->resetEditing();
}
ImGui::PopItemWidth();
ImGui::PopStyleVar();
}
drawCommentColumn(pattern);
}
void PatternDrawer::visit(pl::ptrn::PatternPadding& pattern) {
// Do nothing
hex::unused(pattern);
}
void PatternDrawer::visit(pl::ptrn::PatternPointer& pattern) {
bool open = true;
if (!pattern.isInlined() && m_treeStyle != TreeStyle::Flattened) {
open = drawNameColumn(pattern);
drawColorColumn(pattern);
drawOffsetColumns(pattern);
drawSizeColumn(pattern);
ImGui::TableNextColumn();
ImGuiExt::TextFormattedColored(TextEditor::GetPalette()[u32(TextEditor::PaletteIndex::KnownIdentifier)], "{}", pattern.getFormattedName());
drawValueColumn(pattern);
drawCommentColumn(pattern);
}
if (open) {
pattern.getPointedAtPattern()->accept(*this);
closeTreeNode(pattern.isInlined());
}
}
void PatternDrawer::visit(pl::ptrn::PatternSigned& pattern) {
createDefaultEntry(pattern);
if (!this->isEditingPattern(pattern)) {
drawValueColumn(pattern);
} else {
ImGui::TableNextColumn();
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0));
ImGui::PushItemWidth(ImGui::GetContentRegionAvail().x);
ImGui::SetKeyboardFocusHere();
auto value = pattern.getFormattedValue();
if (ImGui::InputText("##Value", value, ImGuiInputTextFlags_AutoSelectAll | ImGuiInputTextFlags_EnterReturnsTrue)) {
wolv::math_eval::MathEvaluator<i128> mathEvaluator;
if (auto result = mathEvaluator.evaluate(value); result.has_value())
pattern.setValue(result.value());
this->resetEditing();
}
ImGui::PopItemWidth();
ImGui::PopStyleVar();
}
drawCommentColumn(pattern);
}
void PatternDrawer::visit(pl::ptrn::PatternString& pattern) {
if (pattern.getSize() > 0) {
createDefaultEntry(pattern);
if (!this->isEditingPattern(pattern)) {
drawValueColumn(pattern);
} else {
ImGui::TableNextColumn();
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0));
ImGui::PushItemWidth(ImGui::GetContentRegionAvail().x);
ImGui::SetKeyboardFocusHere();
auto value = pattern.toString();
if (ImGui::InputText("##Value", value.data(), value.size() + 1, ImGuiInputTextFlags_AutoSelectAll | ImGuiInputTextFlags_EnterReturnsTrue)) {
pattern.setValue(value);
this->resetEditing();
}
ImGui::PopItemWidth();
ImGui::PopStyleVar();
}
drawCommentColumn(pattern);
}
}
void PatternDrawer::visit(pl::ptrn::PatternStruct& pattern) {
bool open = true;
if (!pattern.isInlined() && m_treeStyle != TreeStyle::Flattened) {
open = drawNameColumn(pattern);
if (pattern.isSealed())
drawColorColumn(pattern);
else
ImGui::TableNextColumn();
drawOffsetColumns(pattern);
drawSizeColumn(pattern);
drawTypeNameColumn(pattern, "struct");
if (this->isEditingPattern(pattern) && !pattern.getWriteFormatterFunction().empty()) {
ImGui::TableNextColumn();
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0));
ImGui::PushItemWidth(ImGui::GetContentRegionAvail().x);
ImGui::SetKeyboardFocusHere();
auto value = pattern.toString();
if (ImGui::InputText("##Value", value, ImGuiInputTextFlags_AutoSelectAll | ImGuiInputTextFlags_EnterReturnsTrue)) {
pattern.setValue(value);
this->resetEditing();
}
ImGui::PopItemWidth();
ImGui::PopStyleVar();
} else {
drawValueColumn(pattern);
}
drawCommentColumn(pattern);
}
if (!open) {
return;
}
int id = 1;
pattern.forEachEntry(0, pattern.getEntryCount(), [&](u64, auto *member){
ImGui::PushID(id);
this->draw(*member);
ImGui::PopID();
id += 1;
});
closeTreeNode(pattern.isInlined());
}
void PatternDrawer::visit(pl::ptrn::PatternUnion& pattern) {
bool open = true;
if (!pattern.isInlined() && m_treeStyle != TreeStyle::Flattened) {
open = drawNameColumn(pattern);
if (pattern.isSealed())
drawColorColumn(pattern);
else
ImGui::TableNextColumn();
drawOffsetColumns(pattern);
drawSizeColumn(pattern);
drawTypeNameColumn(pattern, "union");
if (this->isEditingPattern(pattern) && !pattern.getWriteFormatterFunction().empty()) {
ImGui::TableNextColumn();
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0));
ImGui::PushItemWidth(ImGui::GetContentRegionAvail().x);
ImGui::SetKeyboardFocusHere();
auto value = pattern.toString();
if (ImGui::InputText("##Value", value, ImGuiInputTextFlags_AutoSelectAll | ImGuiInputTextFlags_EnterReturnsTrue)) {
pattern.setValue(value);
this->resetEditing();
}
ImGui::PopItemWidth();
ImGui::PopStyleVar();
} else {
drawValueColumn(pattern);
}
drawCommentColumn(pattern);
}
if (!open) {
return;
}
int id = 1;
pattern.forEachEntry(0, pattern.getEntryCount(), [&](u64, auto *member) {
ImGui::PushID(id);
this->draw(*member);
ImGui::PopID();
id += 1;
});
closeTreeNode(pattern.isInlined());
}
void PatternDrawer::visit(pl::ptrn::PatternUnsigned& pattern) {
createDefaultEntry(pattern);
if (!this->isEditingPattern(pattern)) {
drawValueColumn(pattern);
} else {
ImGui::TableNextColumn();
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0));
ImGui::PushItemWidth(ImGui::GetContentRegionAvail().x);
ImGui::SetKeyboardFocusHere();
auto value = pattern.toString();
if (ImGui::InputText("##Value", value, ImGuiInputTextFlags_AutoSelectAll | ImGuiInputTextFlags_EnterReturnsTrue)) {
wolv::math_eval::MathEvaluator<u128> mathEvaluator;
if (auto result = mathEvaluator.evaluate(value); result.has_value())
pattern.setValue(result.value());
this->resetEditing();
}
ImGui::PopItemWidth();
ImGui::PopStyleVar();
}
drawCommentColumn(pattern);
}
void PatternDrawer::visit(pl::ptrn::PatternWideCharacter& pattern) {
createDefaultEntry(pattern);
drawValueColumn(pattern);
drawCommentColumn(pattern);
}
void PatternDrawer::visit(pl::ptrn::PatternWideString& pattern) {
if (pattern.getSize() > 0) {
createDefaultEntry(pattern);
drawValueColumn(pattern);
drawCommentColumn(pattern);
}
}
void PatternDrawer::draw(pl::ptrn::Pattern& pattern) {
if (pattern.getVisibility() == pl::ptrn::Visibility::Hidden)
return;
m_currPatternPath.push_back(pattern.getVariableName());
ON_SCOPE_EXIT { m_currPatternPath.pop_back(); };
pattern.accept(*this);
}
void PatternDrawer::drawArray(pl::ptrn::Pattern& pattern, pl::ptrn::IIterable &iterable, bool isInlined) {
if (iterable.getEntryCount() == 0)
return;
bool open = true;
if (!isInlined && m_treeStyle != TreeStyle::Flattened) {
open = drawNameColumn(pattern);
if (pattern.isSealed())
drawColorColumn(pattern);
else
ImGui::TableNextColumn();
drawOffsetColumns(pattern);
drawSizeColumn(pattern);
ImGui::TableNextColumn();
ImGuiExt::TextFormattedColored(TextEditor::GetPalette()[u32(TextEditor::PaletteIndex::KnownIdentifier)], "{0}", pattern.getTypeName());
ImGui::SameLine(0, 0);
ImGui::TextUnformatted("[");
ImGui::SameLine(0, 0);
ImGuiExt::TextFormattedColored(TextEditor::GetPalette()[u32(TextEditor::PaletteIndex::Number)], "{0}", iterable.getEntryCount());
ImGui::SameLine(0, 0);
ImGui::TextUnformatted("]");
drawValueColumn(pattern);
drawCommentColumn(pattern);
}
if (!open) {
return;
}
u64 chunkCount = 0;
for (u64 i = 0; i < iterable.getEntryCount(); i += ChunkSize) {
chunkCount++;
auto &displayEnd = this->getDisplayEnd(pattern);
if (chunkCount > displayEnd) {
ImGui::TableNextRow();
ImGui::TableNextColumn();
ImGui::TableNextColumn();
ImGui::Selectable(hex::format("... ({})", "hex.ui.pattern_drawer.double_click"_lang).c_str(), false, ImGuiSelectableFlags_SpanAllColumns);
if (ImGui::IsItemHovered() && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left))
displayEnd += DisplayEndStep;
break;
}
auto endIndex = std::min<u64>(iterable.getEntryCount(), i + ChunkSize);
bool chunkOpen = true;
if (iterable.getEntryCount() > ChunkSize) {
auto startOffset = iterable.getEntry(i)->getOffset();
auto endOffset = iterable.getEntry(endIndex - 1)->getOffset();
auto endSize = iterable.getEntry(endIndex - 1)->getSize();
size_t chunkSize = (endOffset - startOffset) + endSize;
ImGui::TableNextRow();
ImGui::TableNextColumn();
ImGui::TableNextColumn();
chunkOpen = highlightWhenSelected(startOffset, ((endOffset + endSize) - startOffset) - 1, [&]{
return ImGui::TreeNodeEx(hex::format("{0}[{1} ... {2}]", m_treeStyle == TreeStyle::Flattened ? this->getDisplayName(pattern).c_str() : "", i, endIndex - 1).c_str(), ImGuiTreeNodeFlags_SpanFullWidth);
});
ImGui::TableNextColumn();
if (!pattern.isLocal()) {
ImGui::TableNextColumn();
ImGuiExt::TextFormatted("0x{0:08X}", startOffset);
ImGui::TableNextColumn();
ImGuiExt::TextFormatted("0x{0:08X}", endOffset + endSize - (endSize == 0 ? 0 : 1));
} else {
ImGui::TableNextColumn();
ImGuiExt::TextFormatted("[{}]", "hex.ui.pattern_drawer.local"_lang);
ImGui::TableNextColumn();
ImGuiExt::TextFormatted("[{}]", "hex.ui.pattern_drawer.local"_lang);
}
ImGui::TableNextColumn();
ImGuiExt::TextFormatted("{0} {1}", chunkSize, chunkSize == 1 ? "byte" : "bytes");
ImGui::TableNextColumn();
ImGuiExt::TextFormattedColored(TextEditor::GetPalette()[u32(TextEditor::PaletteIndex::KnownIdentifier)], "{0}", pattern.getTypeName());
ImGui::SameLine(0, 0);
ImGui::TextUnformatted("[");
ImGui::SameLine(0, 0);
ImGuiExt::TextFormattedColored(TextEditor::GetPalette()[u32(TextEditor::PaletteIndex::Number)], "{0}", endIndex - i);
ImGui::SameLine(0, 0);
ImGui::TextUnformatted("]");
ImGui::TableNextColumn();
ImGuiExt::TextFormatted("[ ... ]");
}
if (!chunkOpen) {
continue;
}
int id = 1;
iterable.forEachEntry(i, endIndex, [&](u64, auto *entry){
ImGui::PushID(id);
this->draw(*entry);
ImGui::PopID();
id += 1;
});
if (iterable.getEntryCount() > ChunkSize)
ImGui::TreePop();
}
closeTreeNode(isInlined);
}
u64& PatternDrawer::getDisplayEnd(const pl::ptrn::Pattern& pattern) {
auto it = m_displayEnd.find(&pattern);
if (it != m_displayEnd.end()) {
return it->second;
}
auto [value, success] = m_displayEnd.emplace(&pattern, DisplayEndDefault);
return value->second;
}
bool PatternDrawer::sortPatterns(const ImGuiTableSortSpecs* sortSpecs, const pl::ptrn::Pattern * left, const pl::ptrn::Pattern * right) const {
auto result = std::strong_ordering::less;
if (sortSpecs->Specs->ColumnUserID == ImGui::GetID("name")) {
result = this->getDisplayName(*left) <=> this->getDisplayName(*right);
} else if (sortSpecs->Specs->ColumnUserID == ImGui::GetID("start")) {
result = left->getOffsetForSorting() <=> right->getOffsetForSorting();
} else if (sortSpecs->Specs->ColumnUserID == ImGui::GetID("end")) {
result = (left->getOffsetForSorting() + left->getSizeForSorting()) <=> (right->getOffsetForSorting() + right->getSizeForSorting());
} else if (sortSpecs->Specs->ColumnUserID == ImGui::GetID("size")) {
result = left->getSizeForSorting() <=> right->getSizeForSorting();
} else if (sortSpecs->Specs->ColumnUserID == ImGui::GetID("value")) {
result = left->getValue() <=> right->getValue();
} else if (sortSpecs->Specs->ColumnUserID == ImGui::GetID("type")) {
result = left->getTypeName() <=> right->getTypeName();
} else if (sortSpecs->Specs->ColumnUserID == ImGui::GetID("color")) {
result = left->getColor() <=> right->getColor();
} else if (sortSpecs->Specs->ColumnUserID == ImGui::GetID("comment")) {
result = left->getComment() <=> right->getComment();
}
return sortSpecs->Specs->SortDirection == ImGuiSortDirection_Ascending ? result == std::strong_ordering::less : result == std::strong_ordering::greater;
}
bool PatternDrawer::beginPatternTable(const std::vector<std::shared_ptr<pl::ptrn::Pattern>> &patterns, std::vector<pl::ptrn::Pattern*> &sortedPatterns, float height) const {
if (!ImGui::BeginTable("##Patterntable", 9, ImGuiTableFlags_Borders | ImGuiTableFlags_Resizable | ImGuiTableFlags_Sortable | ImGuiTableFlags_Hideable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_RowBg | ImGuiTableFlags_ScrollY, ImVec2(0, height))) {
return false;
}
ImGui::TableSetupScrollFreeze(0, 1);
ImGui::TableSetupColumn("hex.ui.pattern_drawer.favorites"_lang, ImGuiTableColumnFlags_NoHeaderLabel | ImGuiTableColumnFlags_NoSort | ImGuiTableColumnFlags_WidthFixed | ImGuiTableColumnFlags_NoResize | ImGuiTableColumnFlags_NoReorder | ImGuiTableColumnFlags_NoHide | ImGuiTableColumnFlags_IndentDisable, ImGui::GetTextLineHeight(), ImGui::GetID("favorite"));
ImGui::TableSetupColumn("hex.ui.pattern_drawer.var_name"_lang, ImGuiTableColumnFlags_PreferSortAscending | ImGuiTableColumnFlags_NoHide | ImGuiTableColumnFlags_IndentEnable, 0, ImGui::GetID("name"));
ImGui::TableSetupColumn("hex.ui.pattern_drawer.color"_lang, ImGuiTableColumnFlags_PreferSortAscending, 0, ImGui::GetID("color"));
ImGui::TableSetupColumn("hex.ui.pattern_drawer.start"_lang, ImGuiTableColumnFlags_PreferSortAscending | ImGuiTableColumnFlags_DefaultSort, 0, ImGui::GetID("start"));
ImGui::TableSetupColumn("hex.ui.pattern_drawer.end"_lang, ImGuiTableColumnFlags_PreferSortAscending | ImGuiTableColumnFlags_DefaultSort, 0, ImGui::GetID("end"));
ImGui::TableSetupColumn("hex.ui.pattern_drawer.size"_lang, ImGuiTableColumnFlags_PreferSortAscending, 0, ImGui::GetID("size"));
ImGui::TableSetupColumn("hex.ui.pattern_drawer.type"_lang, ImGuiTableColumnFlags_PreferSortAscending, 0, ImGui::GetID("type"));
ImGui::TableSetupColumn("hex.ui.pattern_drawer.value"_lang, ImGuiTableColumnFlags_PreferSortAscending, 0, ImGui::GetID("value"));
ImGui::TableSetupColumn("hex.ui.pattern_drawer.comment"_lang, ImGuiTableColumnFlags_PreferSortAscending | ImGuiTableColumnFlags_DefaultHide, 0, ImGui::GetID("comment"));
auto sortSpecs = ImGui::TableGetSortSpecs();
if (patterns.empty()) {
sortedPatterns.clear();
return true;
}
if (!sortSpecs->SpecsDirty && !sortedPatterns.empty()) {
return true;
}
if (!m_favoritesUpdateTask.isRunning()) {
sortedPatterns.clear();
std::transform(patterns.begin(), patterns.end(), std::back_inserter(sortedPatterns), [](const std::shared_ptr<pl::ptrn::Pattern> &pattern) {
return pattern.get();
});
std::stable_sort(sortedPatterns.begin(), sortedPatterns.end(), [this, &sortSpecs](const pl::ptrn::Pattern *left, const pl::ptrn::Pattern *right) -> bool {
return this->sortPatterns(sortSpecs, left, right);
});
for (auto &pattern : sortedPatterns) {
pattern->sort([this, &sortSpecs](const pl::ptrn::Pattern *left, const pl::ptrn::Pattern *right){
return this->sortPatterns(sortSpecs, left, right);
});
}
sortSpecs->SpecsDirty = false;
}
return true;
}
void PatternDrawer::traversePatternTree(pl::ptrn::Pattern &pattern, std::vector<std::string> &patternPath, const std::function<void(pl::ptrn::Pattern&)> &callback) {
patternPath.push_back(pattern.getVariableName());
ON_SCOPE_EXIT { patternPath.pop_back(); };
callback(pattern);
if (auto iterable = dynamic_cast<pl::ptrn::IIterable*>(&pattern); iterable != nullptr) {
iterable->forEachEntry(0, iterable->getEntryCount(), [&](u64, pl::ptrn::Pattern *entry) {
traversePatternTree(*entry, patternPath, callback);
});
}
}
void PatternDrawer::draw(const std::vector<std::shared_ptr<pl::ptrn::Pattern>> &patterns, const pl::PatternLanguage *runtime, float height) {
if (runtime == nullptr) {
this->reset();
} else {
auto runId = runtime->getRunId();
if (runId != m_lastRunId) {
this->reset();
m_lastRunId = runId;
}
}
std::scoped_lock lock(s_resetDrawMutex);
m_hoverCallback(nullptr);
const auto treeStyleButton = [this](auto icon, TreeStyle style, const char *tooltip) {
bool pushed = false;
if (m_treeStyle == style) {
ImGui::PushStyleColor(ImGuiCol_Border, ImGui::GetStyleColorVec4(ImGuiCol_ButtonActive));
pushed = true;
}
if (ImGuiExt::DimmedIconButton(icon, ImGui::GetStyleColorVec4(ImGuiCol_Text)))
m_treeStyle = style;
if (pushed)
ImGui::PopStyleColor();
ImGuiExt::InfoTooltip(tooltip);
};
if (ImGui::IsMouseClicked(ImGuiMouseButton_Left) && !ImGui::IsAnyItemHovered()) {
this->resetEditing();
}
ImGui::PushItemWidth(ImGui::GetContentRegionAvail().x - (ImGui::GetTextLineHeightWithSpacing() * 9.4F));
if (ImGuiExt::InputTextIcon("##Search", ICON_VS_FILTER, m_filterText)) {
m_filter = parseRValueFilter(m_filterText).value_or(Filter{ });
updateFilter();
}
ImGui::PopItemWidth();
ImGui::SameLine();
ImGuiExt::DimmedIconToggle(ICON_VS_BOOK, &m_showSpecName);
ImGuiExt::InfoTooltip("hex.ui.pattern_drawer.spec_name"_lang);
ImGui::SameLine();
treeStyleButton(ICON_VS_SYMBOL_KEYWORD, TreeStyle::Default, "hex.ui.pattern_drawer.tree_style.tree"_lang);
ImGui::SameLine(0, 0);
treeStyleButton(ICON_VS_LIST_TREE, TreeStyle::AutoExpanded, "hex.ui.pattern_drawer.tree_style.auto_expanded"_lang);
ImGui::SameLine(0, 0);
treeStyleButton(ICON_VS_LIST_FLAT, TreeStyle::Flattened, "hex.ui.pattern_drawer.tree_style.flattened"_lang);
ImGui::SameLine(0, 15_scaled);
const auto startPos = ImGui::GetCursorPos();
ImGui::BeginDisabled(runtime == nullptr);
if (ImGuiExt::DimmedIconButton(ICON_VS_EXPORT, ImGui::GetStyleColorVec4(ImGuiCol_Text))) {
ImGui::OpenPopup("ExportPatterns");
}
ImGui::EndDisabled();
ImGuiExt::InfoTooltip("hex.ui.pattern_drawer.export"_lang);
ImGui::SetNextWindowPos(ImGui::GetWindowPos() + ImVec2(startPos.x, ImGui::GetCursorPosY()));
if (ImGui::BeginPopup("ExportPatterns")) {
for (const auto &formatter : m_formatters) {
const auto name = [&]{
auto formatterName = formatter->getName();
std::transform(formatterName.begin(), formatterName.end(), formatterName.begin(), [](char c){ return char(std::toupper(c)); });
return formatterName;
}();
const auto &extension = formatter->getFileExtension();
if (ImGui::MenuItem(name.c_str())) {
fs::openFileBrowser(fs::DialogMode::Save, { fs::ItemFilter(name, extension) }, [&](const std::fs::path &path) {
auto result = formatter->format(*runtime);
wolv::io::File output(path, wolv::io::File::Mode::Create);
output.writeVector(result);
});
}
}
ImGui::EndPopup();
}
if (beginPatternTable(patterns, m_sortedPatterns, height)) {
ImGui::PushStyleColor(ImGuiCol_HeaderHovered, ImGui::GetColorU32(ImGuiCol_HeaderHovered, 0.4F));
ImGui::PushStyleColor(ImGuiCol_HeaderActive, ImGui::GetColorU32(ImGuiCol_HeaderActive, 0.4F));
ImGui::TableHeadersRow();
m_showFavoriteStars = false;
if (!m_favoritesUpdateTask.isRunning()) {
int id = 1;
bool doTableNextRow = false;
if (!m_favorites.empty() && !patterns.empty()) {
ImGui::TableNextColumn();
ImGui::TableNextColumn();
ImGui::PushID(id);
if (ImGui::TreeNodeEx("hex.ui.pattern_drawer.favorites"_lang, ImGuiTreeNodeFlags_SpanFullWidth)) {
for (auto &[path, pattern] : m_favorites) {
if (pattern == nullptr)
continue;
ImGui::PushID(pattern->getDisplayName().c_str());
this->draw(*pattern);
ImGui::PopID();
}
ImGui::TreePop();
}
ImGui::PopID();
id += 1;
doTableNextRow = true;
}
if (!m_groups.empty() && !patterns.empty()) {
for (auto &[groupName, groupPatterns]: m_groups) {
if (doTableNextRow) {
ImGui::TableNextRow();
}
ImGui::TableNextColumn();
ImGui::TableNextColumn();
ImGui::PushID(id);
if (ImGui::TreeNodeEx(groupName.c_str(), ImGuiTreeNodeFlags_SpanFullWidth)) {
for (auto &groupPattern: groupPatterns) {
if (groupPattern == nullptr)
continue;
ImGui::PushID(id);
this->draw(*groupPattern);
ImGui::PopID();
id += 1;
}
ImGui::TreePop();
}
ImGui::PopID();
id += 1;
doTableNextRow = true;
}
}
m_showFavoriteStars = true;
for (auto &pattern : m_filter.path.empty() ? m_sortedPatterns : m_filteredPatterns) {
ImGui::PushID(id);
this->draw(*pattern);
ImGui::PopID();
id += 1;
}
}
ImGui::PopStyleColor(2);
ImGui::EndTable();
}
if (!m_filtersUpdated && !patterns.empty()) {
m_filtersUpdated = true;
if (!m_favoritesUpdateTask.isRunning()) {
m_favoritesUpdateTask = TaskManager::createTask("hex.ui.pattern_drawer.updating"_lang, TaskManager::NoProgress, [this, patterns](auto &task) {
size_t updatedFavorites = 0;
for (auto &pattern : patterns) {
std::vector<std::string> patternPath;
size_t startFavoriteCount = m_favorites.size();
traversePatternTree(*pattern, patternPath, [&, this](const pl::ptrn::Pattern &currPattern) {
if (currPattern.hasAttribute("hex::favorite"))
m_favorites.insert({ patternPath, currPattern.clone() });
if (const auto &args = currPattern.getAttributeArguments("hex::group"); !args.empty()) {
auto groupName = args.front().toString();
if (!m_groups.contains(groupName))
m_groups.insert({groupName, std::vector<std::unique_ptr<pl::ptrn::Pattern>>()});
m_groups[groupName].push_back(currPattern.clone());
}
task.update();
});
task.update();
if (startFavoriteCount == m_favorites.size())
continue;
patternPath.clear();
traversePatternTree(*pattern, patternPath, [&, this](const pl::ptrn::Pattern &currPattern) {
for (auto &[path, favoritePattern] : m_favorites) {
if (updatedFavorites == m_favorites.size())
task.interrupt();
task.update();
if (matchesFilter(patternPath, path, true)) {
favoritePattern = currPattern.clone();
updatedFavorites += 1;
break;
}
}
});
}
std::erase_if(m_favorites, [](const auto &entry) {
const auto &[path, favoritePattern] = entry;
return favoritePattern == nullptr;
});
});
}
updateFilter();
}
m_jumpToPattern = nullptr;
if (m_favoritesUpdateTask.isRunning()) {
ImGuiExt::TextOverlay("hex.ui.pattern_drawer.updating"_lang, ImGui::GetWindowPos() + ImGui::GetWindowSize() / 2);
}
}
void PatternDrawer::reset() {
std::scoped_lock lock(s_resetDrawMutex);
this->resetEditing();
m_displayEnd.clear();
m_visualizedPatterns.clear();
m_currVisualizedPattern = nullptr;
m_sortedPatterns.clear();
m_filteredPatterns.clear();
m_lastVisualizerError.clear();
m_currPatternPath.clear();
m_favoritesUpdateTask.interrupt();
for (auto &[path, pattern] : m_favorites)
pattern = nullptr;
for (auto &[groupName, patterns]: m_groups) {
for (auto &pattern: patterns)
pattern = nullptr;
}
m_groups.clear();
m_filtersUpdated = false;
}
}
| 58,298
|
C++
|
.cpp
| 1,170
| 36.149573
| 365
| 0.568051
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
251
|
hex_editor.cpp
|
WerWolv_ImHex/plugins/ui/source/ui/hex_editor.cpp
|
#include <algorithm>
#include <ui/hex_editor.hpp>
#include <hex/api/content_registry.hpp>
#include <hex/api/localization_manager.hpp>
#include <hex/helpers/encoding_file.hpp>
#include <hex/helpers/utils.hpp>
#include <wolv/utils/guards.hpp>
#include <fonts/codicons_font.h>
#include <hex/providers/buffered_reader.hpp>
namespace hex::ui {
/* Data Visualizer */
class DataVisualizerAscii : public hex::ContentRegistry::HexEditor::DataVisualizer {
public:
DataVisualizerAscii() : DataVisualizer("ASCII", 1, 1) { }
void draw(u64 address, const u8 *data, size_t size, bool upperCase) override {
hex::unused(address, upperCase);
if (size == 1) {
const char c = char(data[0]);
if (std::isprint(c) != 0) {
const std::array<char, 2> string = { c, 0x00 };
ImGui::TextUnformatted(string.data());
}
else
ImGuiExt::TextFormattedDisabled(".");
} else {
ImGuiExt::TextFormattedDisabled(".");
}
}
bool drawEditing(u64 address, u8 *data, size_t size, bool upperCase, bool startedEditing) override {
hex::unused(address, startedEditing, upperCase);
if (size == 1) {
struct UserData {
u8 *data;
i32 maxChars;
bool editingDone;
};
UserData userData = {
.data = data,
.maxChars = this->getMaxCharsPerCell(),
.editingDone = false
};
ImGui::PushID(reinterpret_cast<void*>(address));
ON_SCOPE_EXIT { ImGui::PopID(); };
std::array<char, 2> buffer = { std::isprint(data[0]) != 0 ? char(data[0]) : '.', 0x00 };
ImGui::InputText("##editing_input", buffer.data(), buffer.size(), TextInputFlags | ImGuiInputTextFlags_CallbackEdit, [](ImGuiInputTextCallbackData *data) -> int {
auto &userData = *static_cast<UserData*>(data->UserData);
if (data->BufTextLen >= userData.maxChars) {
userData.editingDone = true;
userData.data[0] = data->Buf[0];
}
return 0;
}, &userData);
return userData.editingDone || ImGui::IsKeyPressed(ImGuiKey_Enter) || ImGui::IsKeyPressed(ImGuiKey_Escape);
} else {
return false;
}
}
};
/* Hex Editor */
HexEditor::HexEditor(prv::Provider *provider) : m_provider(provider) {
}
constexpr static u16 getByteColumnSeparatorCount(u16 columnCount) {
return (columnCount - 1) / 8;
}
constexpr static bool isColumnSeparatorColumn(u16 currColumn, u16 columnCount) {
return currColumn > 0 && (currColumn) < columnCount && ((currColumn) % 8) == 0;
}
std::optional<color_t> HexEditor::applySelectionColor(u64 byteAddress, std::optional<color_t> color) {
if (m_mode == Mode::Overwrite) {
if (m_frameStartSelectionRegion != Region::Invalid()) {
auto selection = m_frameStartSelectionRegion;
if (byteAddress >= selection.getStartAddress() && byteAddress <= selection.getEndAddress()) {
if (color.has_value())
color = (ImAlphaBlendColors(color.value(), m_selectionColor)) & 0x00FFFFFF;
else
color = m_selectionColor;
}
}
} else {
color = 0x00;
}
if (color.has_value())
color = (*color & 0x00FFFFFF) | (m_selectionColor & 0xFF000000);
return color;
}
struct CustomEncodingData {
std::string displayValue;
size_t advance;
ImColor color;
};
static CustomEncodingData queryCustomEncodingData(prv::Provider *provider, const EncodingFile &encodingFile, u64 address) {
const auto longestSequence = encodingFile.getLongestSequence();
if (longestSequence == 0)
return { ".", 1, 0xFFFF8000 };
size_t size = std::min<size_t>(longestSequence, provider->getActualSize() - address);
std::vector<u8> buffer(size);
provider->read(address, buffer.data(), size);
const auto [decoded, advance] = encodingFile.getEncodingFor(buffer);
const ImColor color = [&]{
if (decoded.length() == 1 && std::isalnum(decoded[0]) != 0)
return ImGuiExt::GetCustomColorU32(ImGuiCustomCol_AdvancedEncodingASCII);
else if (decoded.length() == 1 && advance == 1)
return ImGuiExt::GetCustomColorU32(ImGuiCustomCol_AdvancedEncodingSingleChar);
else if (decoded.length() > 1 && advance == 1)
return ImGuiExt::GetCustomColorU32(ImGuiCustomCol_AdvancedEncodingMultiChar);
else if (advance > 1)
return ImGui::GetColorU32(ImGuiCol_Text);
else
return ImGuiExt::GetCustomColorU32(ImGuiCustomCol_ToolbarBlue);
}();
return { std::string(decoded), advance, color };
}
static auto getCellPosition() {
return ImGui::GetCursorScreenPos() - ImGui::GetStyle().CellPadding;
}
void HexEditor::drawTooltip(u64 address, const u8 *data, size_t size) const {
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, scaled(ImVec2(5, 5)));
m_tooltipCallback(address, data, size);
ImGui::PopStyleVar();
}
void HexEditor::drawScrollbar(ImVec2 characterSize) {
ImS64 numRows = m_provider == nullptr ? 0 : (m_provider->getSize() / m_bytesPerRow) + ((m_provider->getSize() % m_bytesPerRow) == 0 ? 0 : 1);
auto window = ImGui::GetCurrentWindowRead();
const auto outerRect = window->Rect();
const auto innerRect = window->InnerRect;
const auto borderSize = window->WindowBorderSize;
const auto scrollbarWidth = ImGui::GetStyle().ScrollbarSize;
const auto bb = ImRect(ImMax(outerRect.Min.x, outerRect.Max.x - borderSize - scrollbarWidth), innerRect.Min.y, outerRect.Max.x, innerRect.Max.y);
constexpr auto roundingCorners = ImDrawFlags_RoundCornersTopRight | ImDrawFlags_RoundCornersBottomRight;
constexpr auto axis = ImGuiAxis_Y;
if (numRows > 0) {
ImGui::PushID("MainScrollBar");
ImGui::ScrollbarEx(
bb,
ImGui::GetWindowScrollbarID(window, axis),
axis,
&m_scrollPosition.get(),
(std::ceil(innerRect.Max.y - innerRect.Min.y) / characterSize.y),
std::nextafterf(numRows + ImGui::GetWindowSize().y / characterSize.y, std::numeric_limits<float>::max()),
roundingCorners);
ImGui::PopID();
}
if (m_showMiniMap && m_miniMapVisualizer != nullptr)
this->drawMinimap(characterSize);
if (ImGui::IsWindowHovered()) {
float scrollMultiplier;
if (ImGui::GetIO().KeyCtrl && ImGui::GetIO().KeyShift)
scrollMultiplier = m_visibleRowCount * 10.0F;
else if (ImGui::GetIO().KeyCtrl)
scrollMultiplier = m_visibleRowCount;
else
scrollMultiplier = 5;
m_scrollPosition += ImS64(ImGui::GetIO().MouseWheel * -scrollMultiplier);
}
if (m_scrollPosition < 0)
m_scrollPosition = 0;
if (m_scrollPosition > (numRows - 1))
m_scrollPosition = numRows - 1;
}
void HexEditor::drawMinimap(ImVec2 characterSize) {
if (m_provider == nullptr)
return;
ImS64 numRows = (m_provider->getSize() / m_bytesPerRow) + ((m_provider->getSize() % m_bytesPerRow) == 0 ? 0 : 1);
auto window = ImGui::GetCurrentWindowRead();
const auto outerRect = window->Rect();
const auto innerRect = window->InnerRect;
const auto borderSize = window->WindowBorderSize;
const auto scrollbarWidth = ImGui::GetStyle().ScrollbarSize;
const auto bb = ImRect(ImMax(outerRect.Min.x, outerRect.Max.x - borderSize - scrollbarWidth) - scrollbarWidth * (1 + m_miniMapWidth), innerRect.Min.y, outerRect.Max.x - scrollbarWidth, innerRect.Max.y);
constexpr auto roundingCorners = ImDrawFlags_RoundCornersTopRight | ImDrawFlags_RoundCornersBottomRight;
constexpr auto axis = ImGuiAxis_Y;
const auto rowHeight = 4_scaled;
const u64 rowCount = innerRect.GetSize().y / rowHeight;
const ImS64 scrollPos = m_scrollPosition.get();
const auto grabSize = rowHeight * m_visibleRowCount;
const ImS64 grabPos = (rowCount - m_visibleRowCount) * (double(scrollPos) / numRows);
auto drawList = ImGui::GetWindowDrawList();
drawList->ChannelsSplit(2);
drawList->ChannelsSetCurrent(1);
if (numRows > 0) {
ImGui::PushID("MiniMapScrollBar");
ImGui::PushStyleVar(ImGuiStyleVar_GrabMinSize, grabSize);
ImGui::PushStyleVar(ImGuiStyleVar_ScrollbarRounding, 0);
ImGui::PushStyleColor(ImGuiCol_ScrollbarGrab, ImGui::GetColorU32(ImGuiCol_ScrollbarGrab, 0.4F));
ImGui::PushStyleColor(ImGuiCol_ScrollbarGrabActive, ImGui::GetColorU32(ImGuiCol_ScrollbarGrabActive, 0.5F));
ImGui::PushStyleColor(ImGuiCol_ScrollbarGrabHovered, ImGui::GetColorU32(ImGuiCol_ScrollbarGrabHovered, 0.5F));
ImGui::ScrollbarEx(
bb,
ImGui::GetWindowScrollbarID(window, axis),
axis,
&m_scrollPosition.get(),
(std::ceil(innerRect.Max.y - innerRect.Min.y) / characterSize.y),
std::nextafterf((numRows - m_visibleRowCount) + ImGui::GetWindowSize().y / characterSize.y, std::numeric_limits<float>::max()),
roundingCorners);
ImGui::PopStyleVar(2);
ImGui::PopStyleColor(3);
ImGui::PopID();
}
drawList->ChannelsSetCurrent(0);
std::vector<u8> rowData(m_bytesPerRow);
std::vector<ImColor> rowColors;
const auto drawStart = std::max<ImS64>(0, scrollPos - grabPos);
for (ImS64 y = drawStart; y < std::min<ImS64>(drawStart + rowCount, m_provider->getSize() / m_bytesPerRow); y += 1) {
const auto rowStart = bb.Min + ImVec2(0, (y - drawStart) * rowHeight);
const auto rowEnd = rowStart + ImVec2(bb.GetSize().x, rowHeight);
const auto rowSize = rowEnd - rowStart;
const auto address = y * m_bytesPerRow + m_provider->getBaseAddress() + m_provider->getCurrentPageAddress();
m_provider->read(address, rowData.data(), rowData.size());
m_miniMapVisualizer->callback(address, rowData, rowColors);
const auto cellSize = rowSize / ImVec2(rowColors.size(), 1);
ImVec2 cellPos = rowStart;
for (const auto &rowColor : rowColors) {
drawList->AddRectFilled(cellPos, cellPos + cellSize, rowColor);
cellPos.x += cellSize.x;
}
rowColors.clear();
}
drawList->ChannelsMerge();
}
void HexEditor::drawCell(u64 address, const u8 *data, size_t size, bool hovered, CellType cellType) {
static DataVisualizerAscii asciiVisualizer;
if (m_shouldUpdateEditingValue && address == m_editingAddress) {
m_shouldUpdateEditingValue = false;
if (m_editingBytes.size() < size) {
m_editingBytes.resize(size);
}
std::memcpy(m_editingBytes.data(), data, size);
}
if (m_editingAddress != address || m_editingCellType != cellType) {
if (cellType == CellType::Hex) {
std::array<u8, 32> buffer;
std::memcpy(buffer.data(), data, std::min(size, buffer.size()));
if (m_dataVisualizerEndianness != std::endian::native)
std::reverse(buffer.begin(), buffer.begin() + size);
m_currDataVisualizer->draw(address, buffer.data(), size, m_upperCaseHex);
} else {
asciiVisualizer.draw(address, data, size, m_upperCaseHex);
}
if (hovered && m_provider->isWritable()) {
// Enter editing mode when double-clicking a cell
if (ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left)) {
m_editingAddress = address;
m_shouldModifyValue = false;
m_enteredEditingMode = true;
m_editingBytes.resize(size);
if (m_mode == Mode::Overwrite)
std::memcpy(m_editingBytes.data(), data, size);
else if (m_mode == Mode::Insert) {
std::memset(m_editingBytes.data(), 0x00, size);
m_provider->insert(address, size);
}
m_editingCellType = cellType;
}
}
}
else {
bool shouldExitEditingMode = true;
if (cellType == m_editingCellType && cellType == CellType::Hex) {
std::vector<u8> buffer = m_editingBytes;
if (m_dataVisualizerEndianness != std::endian::native)
std::reverse(buffer.begin(), buffer.end());
shouldExitEditingMode = m_currDataVisualizer->drawEditing(*m_editingAddress, buffer.data(), buffer.size(), m_upperCaseHex, m_enteredEditingMode);
if (m_dataVisualizerEndianness != std::endian::native)
std::reverse(buffer.begin(), buffer.end());
m_editingBytes = buffer;
} else if (cellType == m_editingCellType && cellType == CellType::ASCII) {
shouldExitEditingMode = asciiVisualizer.drawEditing(*m_editingAddress, m_editingBytes.data(), m_editingBytes.size(), m_upperCaseHex, m_enteredEditingMode);
}
if (ImGui::IsWindowFocused()) {
ImGui::SetKeyboardFocusHere(-1);
ImGui::SetNextFrameWantCaptureKeyboard(true);
}
const auto anyMouseButtonClicked =
ImGui::IsMouseClicked(ImGuiMouseButton_Left) ||
ImGui::IsMouseClicked(ImGuiMouseButton_Middle) ||
ImGui::IsMouseClicked(ImGuiMouseButton_Right);
if (shouldExitEditingMode || m_shouldModifyValue) {
{
std::vector<u8> oldData(m_editingBytes.size());
m_provider->read(*m_editingAddress, oldData.data(), oldData.size());
size_t writtenBytes = 0;
for (size_t i = 0; i < m_editingBytes.size(); i += 1) {
if (m_editingBytes[i] != oldData[i]) {
m_provider->write(*m_editingAddress + i, &m_editingBytes[i], 1);
writtenBytes += 1;
}
}
m_provider->getUndoStack().groupOperations(writtenBytes, "hex.builtin.undo_operation.modification");
}
if (!m_selectionChanged && !ImGui::IsMouseDown(ImGuiMouseButton_Left) && !anyMouseButtonClicked && !ImGui::IsKeyDown(ImGuiKey_Escape)) {
auto nextEditingAddress = *m_editingAddress + m_currDataVisualizer->getBytesPerCell();
this->setSelection(nextEditingAddress, nextEditingAddress);
if (nextEditingAddress >= m_provider->getBaseAddress() + m_provider->getCurrentPageAddress() + m_provider->getSize())
m_editingAddress = std::nullopt;
else {
m_editingAddress = nextEditingAddress;
if (m_mode == Mode::Insert) {
std::memset(m_editingBytes.data(), 0x00, size);
m_provider->getUndoStack().groupOperations(2, "hex.builtin.undo_operation.insert");
m_provider->insert(nextEditingAddress, size);
}
}
} else {
if (m_mode == Mode::Insert) {
m_provider->undo();
}
m_editingAddress = std::nullopt;
}
m_shouldModifyValue = false;
m_shouldUpdateEditingValue = true;
}
if (anyMouseButtonClicked && !m_enteredEditingMode && !ImGui::IsPopupOpen("", ImGuiPopupFlags_AnyPopup)) {
if (!(ImGui::IsMouseClicked(ImGuiMouseButton_Left) && hovered)) {
m_editingAddress = std::nullopt;
m_shouldModifyValue = false;
}
}
if (!m_editingAddress.has_value())
m_editingCellType = CellType::None;
m_enteredEditingMode = false;
}
}
void HexEditor::drawSelectionFrame(u32 x, u32 y, Region selection, u64 byteAddress, u16 bytesPerCell, const ImVec2 &cellPos, const ImVec2 &cellSize, const ImColor &backgroundColor) const {
auto drawList = ImGui::GetWindowDrawList();
// Draw background color
drawList->AddRectFilled(cellPos, cellPos + cellSize, backgroundColor);
if (!this->isSelectionValid()) return;
if (!Region { byteAddress, 1 }.isWithin(selection))
return;
const color_t SelectionFrameColor = ImGui::GetColorU32(ImGuiCol_Text);
switch (m_mode) {
case Mode::Overwrite: {
// Draw vertical line at the left of first byte and the start of the line
if (x == 0 || byteAddress == selection.getStartAddress())
drawList->AddLine(ImTrunc(cellPos), ImTrunc(cellPos + ImVec2(0, cellSize.y)), ImColor(SelectionFrameColor), 1_scaled);
// Draw vertical line at the right of the last byte and the end of the line
if (x == u16((m_bytesPerRow / bytesPerCell) - 1) || (byteAddress + bytesPerCell) > selection.getEndAddress())
drawList->AddLine(ImTrunc(cellPos + ImVec2(cellSize.x, 0)), ImTrunc(cellPos + cellSize), ImColor(SelectionFrameColor), 1_scaled);
// Draw horizontal line at the top of the bytes
if (y == 0 || (byteAddress - m_bytesPerRow) < selection.getStartAddress())
drawList->AddLine(ImTrunc(cellPos), ImTrunc(cellPos + ImVec2(cellSize.x, 0)), ImColor(SelectionFrameColor), 1_scaled);
// Draw horizontal line at the bottom of the bytes
if ((byteAddress + m_bytesPerRow) > selection.getEndAddress())
drawList->AddLine(ImTrunc(cellPos + ImVec2(0, cellSize.y)), ImTrunc(cellPos + cellSize + scaled({ 1, 0 })), ImColor(SelectionFrameColor), 1_scaled);
break;
}
case Mode::Insert: {
bool cursorVisible = (!ImGui::GetIO().ConfigInputTextCursorBlink) || (m_cursorBlinkTimer <= 0.0F) || std::fmod(m_cursorBlinkTimer, 1.20F) <= 0.80F;
if (cursorVisible && byteAddress == selection.getStartAddress()) {
// Draw vertical line at the left of first byte and the start of the line
drawList->AddLine(ImTrunc(cellPos), ImTrunc(cellPos + ImVec2(0, cellSize.y)), ImColor(SelectionFrameColor), 1_scaled);
}
}
}
}
void HexEditor::drawEditor(const ImVec2 &size) {
const float SeparatorColumWidth = 6_scaled;
const auto CharacterSize = ImGui::CalcTextSize("0");
if (m_currDataVisualizer == nullptr) {
if (const auto &visualizer = ContentRegistry::HexEditor::getVisualizerByName("hex.builtin.visualizer.hexadecimal.8bit"); visualizer != nullptr) {
m_currDataVisualizer = visualizer;
return;
}
}
if (m_miniMapVisualizer == nullptr) {
if (const auto &visualizers = ContentRegistry::HexEditor::impl::getMiniMapVisualizers(); !visualizers.empty())
m_miniMapVisualizer = visualizers.front();
}
const auto bytesPerCell = m_currDataVisualizer->getBytesPerCell();
const u16 columnCount = m_bytesPerRow / bytesPerCell;
auto byteColumnCount = 2 + columnCount + getByteColumnSeparatorCount(columnCount) + 2 + 2;
if (byteColumnCount >= IMGUI_TABLE_MAX_COLUMNS) {
m_bytesPerRow = 64;
return;
}
const auto selection = getSelection();
m_frameStartSelectionRegion = selection;
if (m_provider == nullptr || m_provider->getActualSize() == 0) {
ImGuiExt::TextFormattedCentered("{}", "hex.ui.hex_editor.no_bytes"_lang);
}
if (!m_editingAddress.has_value() && ImGui::IsKeyPressed(ImGuiKey_Escape))
m_mode = Mode::Overwrite;
Region hoveredCell = Region::Invalid();
if (ImGui::BeginChild("Hex View", size, ImGuiChildFlags_None, ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse)) {
this->drawScrollbar(CharacterSize);
ImGui::PushStyleVar(ImGuiStyleVar_CellPadding, ImVec2(0.5, 0));
if (ImGui::BeginTable("##hex", byteColumnCount, ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_NoKeepColumnsVisible, size)) {
View::discardNavigationRequests();
ImGui::TableSetupScrollFreeze(0, 2);
// Row address column
ImGui::TableSetupColumn("hex.ui.common.address"_lang);
ImGui::TableSetupColumn("");
// Byte columns
for (u16 i = 0; i < columnCount; i++) {
if (isColumnSeparatorColumn(i, columnCount))
ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthFixed, SeparatorColumWidth);
ImGui::TableSetupColumn(hex::format(m_upperCaseHex ? "{:0{}X}" : "{:0{}x}", i * bytesPerCell, m_currDataVisualizer->getMaxCharsPerCell()).c_str(), ImGuiTableColumnFlags_WidthFixed, CharacterSize.x * m_currDataVisualizer->getMaxCharsPerCell() + std::ceil((6 + m_byteCellPadding) * 1_scaled));
}
// ASCII column
ImGui::TableSetupColumn("");
if (m_showAscii) {
ImGui::TableSetupColumn("hex.ui.common.encoding.ascii"_lang, ImGuiTableColumnFlags_WidthFixed, (CharacterSize.x + m_characterCellPadding * 1_scaled) * m_bytesPerRow);
} else {
ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthFixed, 0);
}
ImGui::TableSetupColumn("");
// Custom encoding column
{
if (m_currCustomEncoding.has_value() && m_showCustomEncoding) {
ImGui::TableSetupColumn(m_currCustomEncoding->getName().c_str(), ImGuiTableColumnFlags_WidthStretch);
} else {
ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthFixed, 0);
}
}
ImGui::TableNextRow();
for (i32 i = 0; i < ImGui::TableGetColumnCount(); i++) {
ImGui::TableNextColumn();
ImGui::TextUnformatted(ImGui::TableGetColumnName(i));
ImGui::Dummy(ImVec2(0, CharacterSize.y / 2));
}
ImGui::TableNextRow();
ImGui::TableNextColumn();
if (m_provider != nullptr && m_provider->isReadable()) {
const auto isCurrRegionValid = [this](u64 address) {
auto &[currRegion, currRegionValid] = m_currValidRegion;
if (!Region{ address, 1 }.isWithin(currRegion)) {
m_currValidRegion = m_provider->getRegionValidity(address);
}
return currRegionValid;
};
ImS64 numRows = (m_provider->getSize() / m_bytesPerRow) + ((m_provider->getSize() % m_bytesPerRow) == 0 ? 0 : 1);
if (numRows == 0) {
ImGui::TableNextRow();
ImGui::TableNextColumn();
ImGuiExt::TextFormatted(" ");
}
m_visibleRowCount = size.y / CharacterSize.y;
m_visibleRowCount = std::max<i64>(m_visibleRowCount, 1);
// Loop over rows
std::vector<u8> bytes(m_bytesPerRow, 0x00);
std::vector<std::tuple<std::optional<color_t>, std::optional<color_t>>> cellColors(m_bytesPerRow / bytesPerCell);
for (ImS64 y = m_scrollPosition; y < (m_scrollPosition + m_visibleRowCount + 5) && y < numRows && numRows != 0; y++) {
// Draw address column
ImGui::TableNextRow();
ImGui::TableNextColumn();
ImGuiExt::TextFormatted(m_upperCaseHex ? "{:08X}: " : "{:08x}: ", y * m_bytesPerRow + m_provider->getBaseAddress() + m_provider->getCurrentPageAddress());
ImGui::TableNextColumn();
const u8 validBytes = std::min<u64>(m_bytesPerRow, m_provider->getSize() - y * m_bytesPerRow);
m_provider->read(y * m_bytesPerRow + m_provider->getBaseAddress() + m_provider->getCurrentPageAddress(), bytes.data(), validBytes);
{
for (u64 x = 0; x < std::ceil(float(validBytes) / bytesPerCell); x++) {
const u64 byteAddress = y * m_bytesPerRow + x * bytesPerCell + m_provider->getBaseAddress() + m_provider->getCurrentPageAddress();
const auto cellBytes = std::min<u64>(validBytes, bytesPerCell);
// Query cell colors
if (x < std::ceil(float(validBytes) / bytesPerCell)) {
auto foregroundColor = m_foregroundColorCallback(byteAddress, &bytes[x * cellBytes], cellBytes);
auto backgroundColor = m_backgroundColorCallback(byteAddress, &bytes[x * cellBytes], cellBytes);
if (m_grayOutZero && !foregroundColor.has_value()) {
bool allZero = true;
for (u64 i = 0; i < cellBytes && (x * cellBytes + i) < bytes.size(); i++) {
if (bytes[x * cellBytes + i] != 0x00) {
allZero = false;
break;
}
}
if (allZero)
foregroundColor = ImGui::GetColorU32(ImGuiCol_TextDisabled);
}
cellColors[x] = {
foregroundColor,
backgroundColor
};
} else {
cellColors[x] = {
std::nullopt,
std::nullopt
};
}
}
}
// Draw byte columns
ImGui::PushStyleVar(ImGuiStyleVar_CellPadding, scaled(ImVec2(2.75F, 0.0F)));
for (u64 x = 0; x < columnCount; x++) {
const u64 byteAddress = y * m_bytesPerRow + x * bytesPerCell + m_provider->getBaseAddress() + m_provider->getCurrentPageAddress();
ImGui::TableNextColumn();
if (isColumnSeparatorColumn(x, columnCount))
ImGui::TableNextColumn();
if (x < std::ceil(float(validBytes) / bytesPerCell)) {
auto cellStartPos = getCellPosition();
auto cellSize = (CharacterSize * ImVec2(m_currDataVisualizer->getMaxCharsPerCell(), 1)) + (ImVec2(2, 2) * ImGui::GetStyle().CellPadding) + scaled(ImVec2(1 + m_byteCellPadding, 0));
auto maxCharsPerCell = m_currDataVisualizer->getMaxCharsPerCell();
cellSize = ImVec2(std::ceil(cellSize.x), std::ceil(cellSize.y));
auto [foregroundColor, backgroundColor] = cellColors[x];
if (isColumnSeparatorColumn(x + 1, columnCount) && cellColors.size() > x + 1) {
auto separatorAddress = x + y * columnCount;
auto [nextForegroundColor, nextBackgroundColor] = cellColors[x + 1];
if ((isSelectionValid() && getSelection().overlaps({ separatorAddress, 1 }) && getSelection().getEndAddress() != separatorAddress) || backgroundColor == nextBackgroundColor)
cellSize.x += SeparatorColumWidth + 1;
}
if (y == m_scrollPosition)
cellSize.y -= (ImGui::GetStyle().CellPadding.y);
backgroundColor = applySelectionColor(byteAddress, backgroundColor);
// Draw highlights and selection
if (backgroundColor.has_value()) {
// Draw frame around mouse selection
this->drawSelectionFrame(x, y, selection, byteAddress, bytesPerCell, cellStartPos, cellSize, backgroundColor.value());
}
const bool cellHovered = ImGui::IsMouseHoveringRect(cellStartPos, cellStartPos + cellSize, false) && ImGui::IsWindowHovered();
this->handleSelection(byteAddress, bytesPerCell, &bytes[x * bytesPerCell], cellHovered);
// Set byte foreground color
auto popForeground = SCOPE_GUARD { ImGui::PopStyleColor(); };
if (foregroundColor.has_value() && m_editingAddress != byteAddress)
ImGui::PushStyleColor(ImGuiCol_Text, *foregroundColor);
else
popForeground.release();
// Draw cell content
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0));
ImGui::PushItemWidth((CharacterSize * maxCharsPerCell).x);
if (isCurrRegionValid(byteAddress))
this->drawCell(byteAddress, &bytes[x * bytesPerCell], bytesPerCell, cellHovered, CellType::Hex);
else
ImGuiExt::TextFormatted("{:?>{}}", "", maxCharsPerCell);
if (cellHovered) {
Region newHoveredCell = { byteAddress, bytesPerCell };
if (hoveredCell != newHoveredCell) {
hoveredCell = newHoveredCell;
}
}
ImGui::PopItemWidth();
ImGui::PopStyleVar();
}
}
ImGui::PopStyleVar();
ImGui::TableNextColumn();
ImGui::TableNextColumn();
// Draw ASCII column
if (m_showAscii) {
ImGui::PushStyleVar(ImGuiStyleVar_CellPadding, ImVec2(0, 0));
if (ImGui::BeginTable("##ascii_column", m_bytesPerRow)) {
for (u64 x = 0; x < m_bytesPerRow; x++)
ImGui::TableSetupColumn(hex::format("##ascii_cell{}", x).c_str(), ImGuiTableColumnFlags_WidthFixed, CharacterSize.x + m_characterCellPadding * 1_scaled);
ImGui::TableNextRow();
for (u64 x = 0; x < m_bytesPerRow; x++) {
ImGui::TableNextColumn();
const u64 byteAddress = y * m_bytesPerRow + x + m_provider->getBaseAddress() + m_provider->getCurrentPageAddress();
const auto cellStartPos = getCellPosition();
const auto cellSize = CharacterSize + scaled(ImVec2(m_characterCellPadding, 0));
const bool cellHovered = ImGui::IsMouseHoveringRect(cellStartPos, cellStartPos + cellSize, true) && ImGui::IsWindowHovered();
if (x < validBytes) {
this->handleSelection(byteAddress, bytesPerCell, &bytes[x], cellHovered);
auto [foregroundColor, backgroundColor] = cellColors[x / bytesPerCell];
backgroundColor = applySelectionColor(byteAddress, backgroundColor);
// Draw highlights and selection
if (backgroundColor.has_value()) {
this->drawSelectionFrame(x, y, selection, byteAddress, 1, cellStartPos, cellSize, backgroundColor.value());
}
// Set cell foreground color
auto popForeground = SCOPE_GUARD { ImGui::PopStyleColor(); };
if (foregroundColor.has_value() && m_editingAddress != byteAddress)
ImGui::PushStyleColor(ImGuiCol_Text, *foregroundColor);
else
popForeground.release();
ImGui::SetCursorPosX(ImGui::GetCursorPosX() + (m_characterCellPadding * 1_scaled) / 2);
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0));
ImGui::PushItemWidth(CharacterSize.x);
if (!isCurrRegionValid(byteAddress))
ImGuiExt::TextFormattedDisabled("{}", m_unknownDataCharacter);
else
this->drawCell(byteAddress, &bytes[x], 1, cellHovered, CellType::ASCII);
if (cellHovered) {
Region newHoveredCell = { byteAddress, bytesPerCell };
if (hoveredCell != newHoveredCell) {
hoveredCell = newHoveredCell;
}
}
ImGui::PopItemWidth();
ImGui::PopStyleVar();
}
}
ImGui::EndTable();
}
ImGui::PopStyleVar();
}
ImGui::TableNextColumn();
ImGui::TableNextColumn();
// Draw Custom encoding column
if (m_showCustomEncoding && m_currCustomEncoding.has_value()) {
if (m_encodingLineStartAddresses.empty()) {
m_encodingLineStartAddresses.push_back(0);
}
const bool singleByteEncoding = m_currCustomEncoding->getLongestSequence() == 1 && m_currCustomEncoding->getShortestSequence() == 1;
if (size_t(y) < m_encodingLineStartAddresses.size() || singleByteEncoding) {
std::vector<std::pair<u64, CustomEncodingData>> encodingData;
if (singleByteEncoding) {
u64 offset = 0;
do {
const u64 address = y * m_bytesPerRow + offset + m_provider->getBaseAddress() + m_provider->getCurrentPageAddress();
auto result = queryCustomEncodingData(m_provider, *m_currCustomEncoding, address);
offset += result.advance;
encodingData.emplace_back(address, result);
} while (offset < m_bytesPerRow);
} else {
if (m_encodingLineStartAddresses[y] >= m_bytesPerRow) {
encodingData.emplace_back(y * m_bytesPerRow + m_provider->getBaseAddress() + m_provider->getCurrentPageAddress(), CustomEncodingData(".", 1, ImGuiExt::GetCustomColorU32(ImGuiCustomCol_AdvancedEncodingUnknown)));
m_encodingLineStartAddresses.push_back(0);
} else {
u64 offset = m_encodingLineStartAddresses[y];
do {
const u64 address = y * m_bytesPerRow + offset + m_provider->getBaseAddress() + m_provider->getCurrentPageAddress();
auto result = queryCustomEncodingData(m_provider, *m_currCustomEncoding, address);
offset += result.advance;
encodingData.emplace_back(address, result);
} while (offset < m_bytesPerRow);
m_encodingLineStartAddresses.push_back(offset - m_bytesPerRow);
}
}
ImGui::PushStyleVar(ImGuiStyleVar_CellPadding, ImVec2(0, 0));
ImGui::PushID(y);
ON_SCOPE_EXIT { ImGui::PopID(); };
if (ImGui::BeginTable("##encoding_cell", encodingData.size(), ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_NoKeepColumnsVisible)) {
ImGui::TableNextRow();
for (const auto &[address, data] : encodingData) {
ImGui::TableNextColumn();
const auto cellStartPos = getCellPosition();
const auto cellSize = ImGui::CalcTextSize(data.displayValue.c_str()) * ImVec2(1, 0) + ImVec2(m_characterCellPadding * 1_scaled, CharacterSize.y);
const bool cellHovered = ImGui::IsMouseHoveringRect(cellStartPos, cellStartPos + cellSize, true) && ImGui::IsWindowHovered();
const auto x = address % m_bytesPerRow;
if (x < validBytes && isCurrRegionValid(address)) {
auto [foregroundColor, backgroundColor] = cellColors[x / bytesPerCell];
backgroundColor = applySelectionColor(address, backgroundColor);
// Draw highlights and selection
if (backgroundColor.has_value()) {
this->drawSelectionFrame(x, y, selection, address, 1, cellStartPos, cellSize, backgroundColor.value());
}
auto startPos = ImGui::GetCursorPos();
ImGuiExt::TextFormattedColored(data.color, "{}", data.displayValue);
ImGui::SetCursorPosX(startPos.x + cellSize.x);
ImGui::SameLine(0, 0);
ImGui::Dummy({ 0, 0 });
this->handleSelection(address, data.advance, &bytes[address % m_bytesPerRow], cellHovered);
if (cellHovered) {
Region newHoveredCell = { address, data.advance };
if (hoveredCell != newHoveredCell) {
hoveredCell = newHoveredCell;
}
}
}
}
ImGui::EndTable();
}
ImGui::PopStyleVar();
}
}
// Scroll to the cursor if it's either at the top or bottom edge of the screen
if (m_shouldScrollToSelection && isSelectionValid()) {
// Make sure simply clicking on a byte at the edge of the screen won't cause scrolling
if ((ImGui::IsMouseDragging(ImGuiMouseButton_Left))) {
if ((*m_selectionStart >= (*m_selectionEnd + m_bytesPerRow)) && y == (m_scrollPosition + 1)) {
if (i128(m_selectionEnd.value() - m_provider->getBaseAddress() - m_provider->getCurrentPageAddress()) <= (ImS64(m_scrollPosition + 1) * m_bytesPerRow)) {
m_shouldScrollToSelection = false;
m_scrollPosition -= 3;
}
} else if ((*m_selectionStart <= (*m_selectionEnd - m_bytesPerRow)) && y == ((m_scrollPosition + m_visibleRowCount) - 1)) {
if (i128(m_selectionEnd.value() - m_provider->getBaseAddress() - m_provider->getCurrentPageAddress()) >= (ImS64((m_scrollPosition + m_visibleRowCount) - 2) * m_bytesPerRow)) {
m_shouldScrollToSelection = false;
m_scrollPosition += 3;
}
}
}
// If the cursor is off-screen, directly jump to the byte
if (m_shouldJumpWhenOffScreen) {
m_shouldJumpWhenOffScreen = false;
const auto pageAddress = m_provider->getCurrentPageAddress() + m_provider->getBaseAddress();
auto newSelection = getSelection();
newSelection.address -= pageAddress;
if ((newSelection.getStartAddress()) < u64(m_scrollPosition * m_bytesPerRow))
this->jumpToSelection(0.0F);
if ((newSelection.getEndAddress()) > u64((m_scrollPosition + m_visibleRowCount) * m_bytesPerRow))
this->jumpToSelection(1.0F);
}
}
}
// Handle jumping to selection
if (m_shouldJumpToSelection) {
m_shouldJumpToSelection = false;
auto newSelection = getSelection();
m_provider->setCurrentPage(m_provider->getPageOfAddress(newSelection.address).value_or(0));
const auto pageAddress = m_provider->getCurrentPageAddress() + m_provider->getBaseAddress();
const auto targetRowNumber = (newSelection.getStartAddress() - pageAddress) / m_bytesPerRow;
// Calculate the current top and bottom row numbers of the viewport
ImS64 currentTopRow = m_scrollPosition;
ImS64 currentBottomRow = m_scrollPosition + m_visibleRowCount - 3;
// Check if the targetRowNumber is outside the current visible range
if (ImS64(targetRowNumber) < currentTopRow) {
// If target is above the current view, scroll just enough to bring it into view at the top
m_scrollPosition = targetRowNumber - m_visibleRowCount * m_jumpPivot;
} else if (ImS64(targetRowNumber) > currentBottomRow) {
// If target is below the current view, scroll just enough to bring it into view at the bottom
m_scrollPosition = targetRowNumber - (m_visibleRowCount - 3);
}
m_jumpPivot = 0.0F;
}
}
ImGui::EndTable();
ImGui::PopStyleVar();
}
}
ImGui::EndChild();
ImHexApi::HexEditor::impl::setHoveredRegion(m_provider, hoveredCell);
if (m_hoveredRegion != hoveredCell) {
m_hoveredRegion = hoveredCell;
m_hoverChangedCallback(m_hoveredRegion.address, m_hoveredRegion.size);
}
m_shouldScrollToSelection = false;
}
void HexEditor::drawFooter(const ImVec2 &size) {
const auto windowEndPos = ImGui::GetWindowPos() + size - ImGui::GetStyle().WindowPadding;
ImGui::GetWindowDrawList()->AddLine(windowEndPos - ImVec2(0, size.y - 1_scaled), windowEndPos - size + ImVec2(0, 1_scaled), ImGui::GetColorU32(ImGuiCol_Separator), 2.0_scaled);
if (ImGui::BeginChild("##footer", size, ImGuiChildFlags_Border, ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse)) {
ImGui::SetCursorPosY(ImGui::GetCursorPosY() - 8_scaled);
ImGui::Dummy({});
if (ImGui::BeginTable("##footer_table", 3, ImGuiTableFlags_SizingFixedFit)) {
ImGui::TableSetupColumn("Left", ImGuiTableColumnFlags_WidthStretch, 0.5F);
ImGui::TableSetupColumn("Center", ImGuiTableColumnFlags_WidthFixed, 20_scaled);
ImGui::TableSetupColumn("Right", ImGuiTableColumnFlags_WidthStretch, 0.5F);
ImGui::TableNextRow();
if (m_provider != nullptr && m_provider->isReadable()) {
const auto pageCount = std::max<u32>(1, m_provider->getPageCount());
constexpr static u32 MinPage = 1;
const auto pageAddress = m_provider->getCurrentPageAddress();
const auto pageSize = m_provider->getSize();
ImGui::TableNextRow();
ImGui::TableNextColumn();
{
ImGui::SetCursorPosX(ImGui::GetCursorPosX() + 2_scaled);
// Upper/lower case hex
ImGuiExt::DimmedIconToggle(ICON_VS_CASE_SENSITIVE, &m_upperCaseHex);
ImGuiExt::InfoTooltip("hex.ui.hex_editor.uppercase_hex"_lang);
ImGui::SameLine();
// Grayed out zeros
ImGuiExt::DimmedIconToggle(ICON_VS_LIGHTBULB, &m_grayOutZero);
ImGuiExt::InfoTooltip("hex.ui.hex_editor.gray_out_zero"_lang);
ImGui::SameLine();
// ASCII view
ImGuiExt::DimmedIconToggle(ICON_VS_SYMBOL_KEY, &m_showAscii);
ImGuiExt::InfoTooltip("hex.ui.hex_editor.ascii_view"_lang);
ImGui::SameLine(0, 1_scaled);
// Custom encoding view
ImGui::BeginDisabled(!m_currCustomEncoding.has_value());
ImGuiExt::DimmedIconToggle(ICON_VS_WHITESPACE, &m_showCustomEncoding);
ImGuiExt::InfoTooltip("hex.ui.hex_editor.custom_encoding_view"_lang);
ImGui::EndDisabled();
ImGui::SameLine(0, 1_scaled);
// Minimap
ImGuiExt::DimmedIconToggle(ICON_VS_MAP, &m_showMiniMap);
ImGuiExt::InfoTooltip("hex.ui.hex_editor.minimap"_lang);
if (ImGui::IsItemClicked(ImGuiMouseButton_Right) && m_miniMapVisualizer != nullptr)
ImGui::OpenPopup("MiniMapOptions");
if (ImGui::BeginPopup("MiniMapOptions")) {
ImGui::SliderInt("hex.ui.hex_editor.minimap.width"_lang, &m_miniMapWidth, 1, 25, "%d", ImGuiSliderFlags_AlwaysClamp);
if (ImGui::BeginCombo("##minimap_visualizer", Lang(m_miniMapVisualizer->unlocalizedName))) {
for (const auto &visualizer : ContentRegistry::HexEditor::impl::getMiniMapVisualizers()) {
if (ImGui::Selectable(Lang(visualizer->unlocalizedName))) {
m_miniMapVisualizer = visualizer;
}
}
ImGui::EndCombo();
}
ImGui::EndPopup();
}
ImGui::SameLine(0, 1_scaled);
// Data Cell configuration
if (ImGuiExt::DimmedIconButton(ICON_VS_TABLE, ImGui::GetStyleColorVec4(ImGuiCol_Text))) {
ImGui::OpenPopup("DataCellOptions");
}
ImGuiExt::InfoTooltip("hex.ui.hex_editor.data_cell_options"_lang);
if (ImGui::BeginPopup("DataCellOptions")) {
if (ImGui::BeginCombo("##visualizer", Lang(m_currDataVisualizer->getUnlocalizedName()))) {
for (const auto &visualizer : ContentRegistry::HexEditor::impl::getVisualizers()) {
if (ImGui::Selectable(Lang(visualizer->getUnlocalizedName()))) {
m_currDataVisualizer = visualizer;
m_encodingLineStartAddresses.clear();
m_bytesPerRow = std::max(m_bytesPerRow, visualizer->getBytesPerCell());
}
}
ImGui::EndCombo();
}
{
bool hasEndianness = m_currDataVisualizer->getBytesPerCell() > 1;
if (!hasEndianness)
m_dataVisualizerEndianness = std::endian::native;
ImGui::BeginDisabled(!hasEndianness);
{
int sliderPos = m_dataVisualizerEndianness == std::endian::little ? 0 : 1;
ImGui::SliderInt("##visualizer_endianness", &sliderPos, 0, 1, sliderPos == 0 ? "hex.ui.common.little"_lang : "hex.ui.common.big"_lang);
m_dataVisualizerEndianness = sliderPos == 0 ? std::endian::little : std::endian::big;
}
ImGui::EndDisabled();
}
ImGui::NewLine();
int bytesPerRow = m_bytesPerRow / this->getBytesPerCell();
if (ImGui::SliderInt("##row_size", &bytesPerRow, 1, 128 / this->getBytesPerCell(), hex::format("{} {}", bytesPerRow * this->getBytesPerCell(), "hex.ui.hex_editor.columns"_lang).c_str())) {
m_bytesPerRow = bytesPerRow * this->getBytesPerCell();
m_encodingLineStartAddresses.clear();
}
ImGui::EndPopup();
}
}
// Collapse button
ImGui::TableNextColumn();
{
if (ImGuiExt::DimmedIconButton(m_footerCollapsed ? ICON_VS_FOLD_UP : ICON_VS_FOLD_DOWN, ImGui::GetStyleColorVec4(ImGuiCol_Text)))
m_footerCollapsed = !m_footerCollapsed;
}
ImGui::TableNextColumn();
ImGui::SameLine(0, 20_scaled);
if (m_mode == Mode::Insert) {
ImGui::TextUnformatted("[ INSERT ]");
}
if (!m_footerCollapsed) {
ImGui::SetCursorPosY(ImGui::GetCursorPosY() + 3_scaled);
ImGui::Dummy({});
ImGui::TableNextRow();
// Page slider
ImGui::TableNextColumn();
{
u32 page = m_provider->getCurrentPage() + 1;
ImGui::BeginDisabled(pageCount <= 1);
{
ImGui::PushItemWidth(-1);
if (ImGui::SliderScalar("##page_selection", ImGuiDataType_U32, &page, &MinPage, &pageCount,
hex::format("%llu / {0} [0x{1:04X} - 0x{2:04X}]",
pageCount,
pageAddress,
pageSize == 0 ? 0 : (pageAddress + pageSize - 1)).c_str()))
m_provider->setCurrentPage(page - 1);
ImGui::PopItemWidth();
}
ImGui::EndDisabled();
}
ImGui::TableNextColumn();
// Loaded data size
ImGui::TableNextColumn();
{
ImGuiExt::TextFormattedSelectable("0x{0:08X} (0x{1:X} | {2})",
m_provider->getBaseAddress(),
m_provider->getBaseAddress() + m_provider->getActualSize(),
ImGui::GetIO().KeyCtrl
? hex::format("{}", m_provider->getActualSize())
: hex::toByteString(m_provider->getActualSize())
);
ImGui::SetItemTooltip("%s", "hex.ui.hex_editor.data_size"_lang.get());
}
}
}
ImGui::EndTable();
}
}
ImGui::EndChild();
}
void HexEditor::handleSelection(u64 address, u32 bytesPerCell, const u8 *data, bool cellHovered) {
if (ImGui::IsWindowHovered() && cellHovered) {
drawTooltip(address, data, bytesPerCell);
auto endAddress = address + bytesPerCell - 1;
auto &selectionStart = m_selectionStart;
if (ImGui::IsMouseDragging(ImGuiMouseButton_Left)) {
this->setSelection(selectionStart.value_or(address), endAddress);
this->scrollToSelection();
}
else if (ImGui::IsMouseDown(ImGuiMouseButton_Left) || (ImGui::IsMouseDown(ImGuiMouseButton_Right) && (address < std::min(m_selectionStart, m_selectionEnd) || address > std::max(m_selectionStart, m_selectionEnd)))) {
if (ImGui::GetIO().KeyShift)
this->setSelection(selectionStart.value_or(address), endAddress);
else
this->setSelection(address, endAddress);
this->scrollToSelection();
}
}
}
void HexEditor::draw(float height) {
const auto width = ImGui::GetContentRegionAvail().x;
auto footerSize = ImVec2(width, 0);
if (!m_footerCollapsed)
footerSize.y = ImGui::GetTextLineHeightWithSpacing() * 4.0F;
else
footerSize.y = ImGui::GetTextLineHeightWithSpacing() * 2.4F;
auto tableSize = ImVec2(width, height - footerSize.y);
if (tableSize.y <= 0)
tableSize.y = height;
this->drawEditor(tableSize);
if (tableSize.y > 0)
this->drawFooter(footerSize);
m_selectionChanged = false;
m_cursorBlinkTimer += ImGui::GetIO().DeltaTime;
}
}
| 57,807
|
C++
|
.cpp
| 895
| 41.910615
| 311
| 0.505109
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
252
|
plugin_visualizers.cpp
|
WerWolv_ImHex/plugins/visualizers/source/plugin_visualizers.cpp
|
#include <hex/plugin.hpp>
#include <hex/api/content_registry.hpp>
#include <hex/helpers/logger.hpp>
#include <romfs/romfs.hpp>
namespace hex::plugin::visualizers {
void registerPatternLanguageVisualizers();
void registerPatternLanguageInlineVisualizers();
}
using namespace hex;
using namespace hex::plugin::visualizers;
IMHEX_PLUGIN_SETUP("Visualizers", "WerWolv", "Visualizers for the Pattern Language") {
hex::log::debug("Using romfs: '{}'", romfs::name());
for (auto &path : romfs::list("lang"))
hex::ContentRegistry::Language::addLocalization(nlohmann::json::parse(romfs::get(path).string()));
registerPatternLanguageVisualizers();
registerPatternLanguageInlineVisualizers();
}
| 723
|
C++
|
.cpp
| 17
| 39.176471
| 106
| 0.756447
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
253
|
pl_inline_visualizers.cpp
|
WerWolv_ImHex/plugins/visualizers/source/content/pl_inline_visualizers.cpp
|
#include <hex/api/content_registry.hpp>
#include <imgui.h>
#include <pl/patterns/pattern.hpp>
#include <hex/helpers/fmt.hpp>
#include <fonts/codicons_font.h>
namespace hex::plugin::visualizers {
namespace {
void drawColorInlineVisualizer(pl::ptrn::Pattern &, bool, std::span<const pl::core::Token::Literal> arguments) {
auto r = arguments[0].toFloatingPoint();
auto g = arguments[1].toFloatingPoint();
auto b = arguments[2].toFloatingPoint();
auto a = arguments[3].toFloatingPoint();
ImGui::ColorButton("color", ImVec4(r / 255.0F, g / 255.0F, b / 255.0F, a / 255.0F), ImGuiColorEditFlags_NoTooltip, ImVec2(ImGui::GetColumnWidth(), ImGui::GetTextLineHeight()));
}
void drawGaugeInlineVisualizer(pl::ptrn::Pattern &, bool, std::span<const pl::core::Token::Literal> arguments) {
auto value = arguments[0].toFloatingPoint();
const auto color = ImGui::GetStyleColorVec4(ImGuiCol_Text);
ImGui::PushStyleColor(ImGuiCol_PlotHistogram, ImVec4(color.x, color.y, color.z, 0.2F));
ImGui::PushStyleColor(ImGuiCol_FrameBg, ImVec4(0.0F, 0.0F, 0.0F, 0.0F));
ImGui::PushStyleColor(ImGuiCol_Border, ImVec4(color.x, color.y, color.z, 0.5F));
ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 1.0F);
ImGui::ProgressBar(value / 100.0F, ImVec2(ImGui::GetColumnWidth(), ImGui::GetTextLineHeight()), "");
ImGui::PopStyleVar(1);
ImGui::PopStyleColor(3);
}
void drawButtonInlineVisualizer(pl::ptrn::Pattern &pattern, bool, std::span<const pl::core::Token::Literal> arguments) {
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0));
ImGui::PushStyleVar(ImGuiStyleVar_ButtonTextAlign, ImVec2(0, 0.5F));
if (ImGui::Button(hex::format(" {} {}", ICON_VS_PLAY, pattern.getFormattedValue()).c_str(), ImVec2(ImGui::GetColumnWidth(), ImGui::GetTextLineHeight()))) {
auto *evaluator = pattern.getEvaluator();
const auto functionName = arguments[0].toString(false);
const auto &function = evaluator->findFunction(functionName);
if (function.has_value())
function->func(evaluator, { pattern.clone() });
}
ImGui::PopStyleVar(2);
}
}
void registerPatternLanguageInlineVisualizers() {
using ParamCount = pl::api::FunctionParameterCount;
ContentRegistry::PatternLanguage::addInlineVisualizer("color", drawColorInlineVisualizer, ParamCount::exactly(4));
ContentRegistry::PatternLanguage::addInlineVisualizer("gauge", drawGaugeInlineVisualizer, ParamCount::exactly(1));
ContentRegistry::PatternLanguage::addInlineVisualizer("button", drawButtonInlineVisualizer, ParamCount::exactly(1));
}
}
| 2,891
|
C++
|
.cpp
| 45
| 53.711111
| 188
| 0.661593
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
254
|
pl_visualizers.cpp
|
WerWolv_ImHex/plugins/visualizers/source/content/pl_visualizers.cpp
|
#include <hex/api/content_registry.hpp>
#include <pl/patterns/pattern.hpp>
namespace hex::plugin::visualizers {
void drawLinePlotVisualizer(pl::ptrn::Pattern &, bool, std::span<const pl::core::Token::Literal> arguments);
void drawScatterPlotVisualizer(pl::ptrn::Pattern &, bool, std::span<const pl::core::Token::Literal> arguments);
void drawImageVisualizer(pl::ptrn::Pattern &, bool, std::span<const pl::core::Token::Literal> arguments);
void drawBitmapVisualizer(pl::ptrn::Pattern &, bool, std::span<const pl::core::Token::Literal> arguments);
void draw3DVisualizer(pl::ptrn::Pattern &, bool, std::span<const pl::core::Token::Literal> arguments);
void drawSoundVisualizer(pl::ptrn::Pattern &, bool, std::span<const pl::core::Token::Literal> arguments);
void drawCoordinateVisualizer(pl::ptrn::Pattern &, bool, std::span<const pl::core::Token::Literal> arguments);
void drawTimestampVisualizer(pl::ptrn::Pattern &, bool, std::span<const pl::core::Token::Literal> arguments);
void drawTableVisualizer(pl::ptrn::Pattern &, bool, std::span<const pl::core::Token::Literal> arguments);
void drawDigitalSignalVisualizer(pl::ptrn::Pattern &, bool, std::span<const pl::core::Token::Literal> arguments);
void registerPatternLanguageVisualizers() {
using ParamCount = pl::api::FunctionParameterCount;
ContentRegistry::PatternLanguage::addVisualizer("line_plot", drawLinePlotVisualizer, ParamCount::exactly(1));
ContentRegistry::PatternLanguage::addVisualizer("scatter_plot", drawScatterPlotVisualizer, ParamCount::exactly(2));
ContentRegistry::PatternLanguage::addVisualizer("image", drawImageVisualizer, ParamCount::exactly(1));
ContentRegistry::PatternLanguage::addVisualizer("bitmap", drawBitmapVisualizer, ParamCount::between(3, 4));
ContentRegistry::PatternLanguage::addVisualizer("3d", draw3DVisualizer, ParamCount::between(2, 6));
ContentRegistry::PatternLanguage::addVisualizer("sound", drawSoundVisualizer, ParamCount::exactly(3));
ContentRegistry::PatternLanguage::addVisualizer("coordinates", drawCoordinateVisualizer, ParamCount::exactly(2));
ContentRegistry::PatternLanguage::addVisualizer("timestamp", drawTimestampVisualizer, ParamCount::exactly(1));
ContentRegistry::PatternLanguage::addVisualizer("table", drawTableVisualizer, ParamCount::exactly(3));
ContentRegistry::PatternLanguage::addVisualizer("digital_signal", drawDigitalSignalVisualizer, ParamCount::exactly(1));
}
}
| 2,735
|
C++
|
.cpp
| 27
| 95
| 139
| 0.696779
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
255
|
3d_model.cpp
|
WerWolv_ImHex/plugins/visualizers/source/content/pl_visualizers/3d_model.cpp
|
#include <algorithm>
#include <hex/helpers/utils.hpp>
#include <content/visualizer_helpers.hpp>
#include <fonts/codicons_font.h>
#include <fonts/blendericons_font.h>
#include <imgui.h>
#include <imgui_internal.h>
#include <hex/helpers/opengl.hpp>
#include <opengl_support.h>
#include <numbers>
#include <hex/ui/imgui_imhex_extensions.h>
#include <hex/api/imhex_api.hpp>
#include <hex/api/localization_manager.hpp>
#include <romfs/romfs.hpp>
#include <numeric>
namespace hex::plugin::visualizers {
namespace {
enum class IndexType : u8 {
U8,
U16,
U32,
Undefined,
};
template<class T>
struct Vectors {
std::vector<float> vertices;
std::vector<float> normals;
std::vector<float> colors;
std::vector<float> uv;
std::vector<T> indices;
};
template <class T>
struct LineVectors {
std::vector<float> vertices;
std::vector<float> colors;
std::vector<T> indices;
};
template<class T>
struct Buffers {
gl::Buffer<float> vertices;
gl::Buffer<float> normals;
gl::Buffer<float> colors;
gl::Buffer<float> uv;
gl::Buffer<T> indices;
};
template<class T>
struct LineBuffers {
gl::Buffer<float> vertices;
gl::Buffer<float> colors;
gl::Buffer<T> indices;
};
ImVec2 s_renderingWindowSize;
int s_drawMode = GL_TRIANGLES;
float s_nearLimit = 0.9F;
float s_farLimit = 100.0F;
float s_scaling = 1.0F;
float s_max;
bool s_isPerspective = true;
bool s_drawAxes = true;
bool s_drawGrid = true;
bool s_drawLightSource = true;
bool s_drawTexture = false;
bool s_shouldReset = false;
bool s_shouldUpdateLightSource = true;
bool s_shouldUpdateTexture = false;
std::vector<u32> s_badIndices;
IndexType s_indexType;
ImGuiExt::Texture s_modelTexture;
gl::Vector<float, 3> s_translation = { { 0.0F, 0.0F, -3.0F } };
gl::Vector<float, 3> s_rotation = { { 0.0F, 0.0F, 0.0F } };
gl::Vector<float, 3> s_lightPosition = { { -0.7F, 0.0F, 0.0F } };
gl::Vector<float, 4> s_lightBrightness = { { 0.5F, 0.5F, 0.5F, 32.0F } };
gl::Vector<float, 3> s_lightColor = { { 1.0F, 1.0F, 1.0F } };
gl::Matrix<float, 4, 4> s_rotate = gl::Matrix<float, 4, 4>::identity();
ImGuiExt::Texture s_texture;
std::fs::path s_texturePath;
u32 s_vertexCount;
const auto isIndexInRange = [](auto index) {
if (index >= s_vertexCount)
s_badIndices.push_back(index);
return index < s_vertexCount;
};
template<typename T>
void indicesForLines(std::vector<T> &vertexIndices) {
std::vector<u32> indices;
u32 vertexCount = vertexIndices.size() / 3;
indices.resize(vertexCount * 6);
for (u32 i = 0; i < vertexCount; i += 1) {
indices[i * 6] = vertexIndices[3 * i];
indices[(i * 6) + 1] = vertexIndices[(3 * i) + 1];
indices[(i * 6) + 2] = vertexIndices[(3 * i) + 1];
indices[(i * 6) + 3] = vertexIndices[(3 * i) + 2];
indices[(i * 6) + 4] = vertexIndices[(3 * i) + 2];
indices[(i * 6) + 5] = vertexIndices[3 * i];
}
vertexIndices.resize(indices.size());
for (u32 i = 0; i < indices.size(); ++i)
vertexIndices[i] = indices[i];
}
float getBoundingBox(const std::vector<float> &vertices) {
gl::Vector<float, 4> minWorld(std::numeric_limits<float>::infinity()), maxWorld(-std::numeric_limits<float>::infinity());
for (u32 i = 0; i < vertices.size(); i += 3) {
minWorld[0] = std::min(vertices[i], minWorld[0]);
minWorld[1] = std::min(vertices[i + 1], minWorld[1]);
minWorld[2] = std::min(vertices[i + 2], minWorld[2]);
maxWorld[0] = std::max(vertices[i], maxWorld[0]);
maxWorld[1] = std::max(vertices[i + 1], maxWorld[1]);
maxWorld[2] = std::max(vertices[i + 2], maxWorld[2]);
}
minWorld[3] = 1;
maxWorld[3] = 1;
gl::Vector<float, 4> minCamera = minWorld, maxCamera = maxWorld;
if (maxCamera[3] != 0)
maxCamera = maxCamera * (1.0F / maxCamera[3]);
if (minCamera[3] != 0)
minCamera = minCamera * (1.0F / minCamera[3]);
float max_X = std::max(std::fabs(minCamera[0]), std::fabs(maxCamera[0]));
float max_Y = std::max(std::fabs(minCamera[1]), std::fabs(maxCamera[1]));
return std::max(max_X, max_Y);
}
void setDefaultUVs(std::vector<float> &uv, size_t size) {
uv.resize(size / 3 * 2);
for (u32 i = 0; i < uv.size(); i += 2) {
uv[i ] = 0.0F;
uv[i + 1] = 0.0F;
}
}
void setDefaultColors(std::vector<float> &colors, size_t size, u32 color) {
colors.resize(size / 3 * 4);
float red = float((color >> 0) & 0xFF) / 255.0F;
float green = float((color >> 8) & 0xFF) / 255.0F;
float blue = float((color >> 16) & 0xFF) / 255.0F;
float alpha = float((color >> 24) & 0xFF) / 255.0F;
for (u32 i = 0; i < colors.size(); i += 4) {
colors[i] = red;
colors[i + 1] = green;
colors[i + 2] = blue;
colors[i + 3] = alpha;
}
}
void setNormals(const std::vector<float> &vertices, std::vector<float> &normals) {
for (u32 i = 0; i < normals.size(); i += 9) {
auto v1 = gl::Vector<float, 3>({vertices[i], vertices[i + 1], vertices[i + 2]});
auto v2 = gl::Vector<float, 3>({vertices[i + 3], vertices[i + 4], vertices[i + 5]});
auto v3 = gl::Vector<float, 3>({vertices[i + 6], vertices[i + 7], vertices[i + 8]});
auto normal = ((v2 - v1).cross(v3 - v1));
normals[i] += normal[0];
normals[i + 1] += normal[1];
normals[i + 2] += normal[2];
normals[i + 3] += normal[0];
normals[i + 4] += normal[1];
normals[i + 5] += normal[2];
normals[i + 6] += normal[0];
normals[i + 7] += normal[1];
normals[i + 8] += normal[2];
}
for (u32 i = 0; i < normals.size(); i += 3) {
auto normal = gl::Vector<float, 3>({normals[i], normals[i + 1], normals[i + 2]});
normal.normalize();
normals[i] = normal[0];
normals[i + 1] = normal[1];
normals[i + 2] = normal[2];
}
}
void setNormalsWithIndices(const std::vector<float> &vertices, std::vector<float> &normals, const std::vector<u32> &indices) {
for (u32 i = 0; i < indices.size(); i += 3) {
auto idx = indices[i];
auto idx1 = indices[i + 1];
auto idx2 = indices[i + 2];
auto v1 = gl::Vector<float, 3>({vertices[3 * idx], vertices[(3 * idx) + 1], vertices[(3 * idx) + 2]});
auto v2 = gl::Vector<float, 3>(
{vertices[3 * idx1], vertices[(3 * idx1) + 1], vertices[(3 * idx1) + 2]});
auto v3 = gl::Vector<float, 3>(
{vertices[3 * idx2], vertices[(3 * idx2) + 1], vertices[(3 * idx2) + 2]});
auto weighted = ((v2 - v1).cross(v3 - v1));
normals[3 * idx] += weighted[0];
normals[(3 * idx) + 1] += weighted[1];
normals[(3 * idx) + 2] += weighted[2];
normals[(3 * idx1)] += weighted[0];
normals[(3 * idx1) + 1] += weighted[1];
normals[(3 * idx1) + 2] += weighted[2];
normals[(3 * idx2)] += weighted[0];
normals[(3 * idx2) + 1] += weighted[1];
normals[(3 * idx2) + 2] += weighted[2];
}
for (u32 i = 0; i < normals.size(); i += 3) {
auto normal = gl::Vector<float, 3>({normals[i], normals[i + 1], normals[i + 2]});
auto mag = normal.magnitude();
if (mag > 0.001F) {
normals[i] = normal[0] / mag;
normals[i + 1] = normal[1] / mag;
normals[i + 2] = normal[2] / mag;
}
}
}
template<class T>
void loadVectors(Vectors<T> &vectors, IndexType indexType) {
s_max = getBoundingBox(vectors.vertices);
if (s_drawTexture)
setDefaultColors(vectors.colors, vectors.vertices.size(), 0x00000000);
else if (vectors.colors.empty())
setDefaultColors(vectors.colors, vectors.vertices.size(), 0xFF337FFF);
if (vectors.uv.empty())
setDefaultUVs(vectors.uv, vectors.vertices.size());
if (vectors.normals.empty()) {
vectors.normals.resize(vectors.vertices.size());
if (vectors.indices.empty() || (indexType == IndexType::Undefined)) {
setNormals(vectors.vertices, vectors.normals);
} else {
std::vector<u32> indices;
indices.resize(vectors.indices.size());
for (u32 i = 0; i < vectors.indices.size(); i += 1)
indices[i] = vectors.indices[i];
setNormalsWithIndices(vectors.vertices, vectors.normals, indices);
}
}
}
template<class T>
void loadLineVectors(LineVectors<T> &lineVectors, IndexType indexType) {
s_max = getBoundingBox(lineVectors.vertices);
if (lineVectors.colors.empty())
setDefaultColors(lineVectors.colors, lineVectors.vertices.size(), 0xFF337FFF);
if (indexType != IndexType::Undefined)
indicesForLines(lineVectors.indices);
}
void processKeyEvent(ImGuiKey key, float &variable, float increment, float acceleration) {
if (ImGui::IsKeyPressed(key)) {
auto temp = variable + (increment * acceleration);
if (variable * temp < 0.0F)
variable = 0.0F;
else
variable = temp;
}
}
void processInputEvents(gl::Vector<float, 3> &rotation, gl::Vector<float, 3> &translation, float &scaling, float &nearLimit, float &farLimit) {
auto accel = 1.0F;
if (ImGui::IsKeyDown(ImGuiKey_LeftShift) ||
ImGui::IsKeyDown(ImGuiKey_RightShift))
accel = 10.0F;
auto dragDelta = ImGui::GetMouseDragDelta(ImGuiMouseButton_Middle);
if (dragDelta.x != 0) {
rotation[1] += dragDelta.x * 0.0075F * accel;
}
if (dragDelta.y != 0) {
rotation[0] += dragDelta.y * 0.0075F * accel;
}
ImGui::ResetMouseDragDelta(ImGuiMouseButton_Middle);
dragDelta = ImGui::GetMouseDragDelta(ImGuiMouseButton_Right);
translation[0] += dragDelta.x * 0.0075F * accel;
translation[1] -= dragDelta.y * 0.0075F * accel;
ImGui::ResetMouseDragDelta(ImGuiMouseButton_Right);
auto scrollDelta = ImGui::GetIO().MouseWheel;
scaling += scrollDelta * 0.1F * accel;
scaling = std::max(scaling, 0.01F);
processKeyEvent(ImGuiKey_Keypad4, translation[0], -0.1F, accel);
processKeyEvent(ImGuiKey_Keypad6, translation[0], 0.1F, accel);
processKeyEvent(ImGuiKey_Keypad8, translation[1], 0.1F, accel);
processKeyEvent(ImGuiKey_Keypad2, translation[1], -0.1F, accel);
processKeyEvent(ImGuiKey_Keypad1, translation[2], 0.1F, accel);
processKeyEvent(ImGuiKey_Keypad7, translation[2], -0.1F, accel);
processKeyEvent(ImGuiKey_Keypad9, nearLimit, -0.01F, accel);
processKeyEvent(ImGuiKey_Keypad3, nearLimit, 0.01F, accel);
if (ImHexApi::System::isDebugBuild()) {
processKeyEvent(ImGuiKey_KeypadDivide, farLimit, -1.0F, accel);
processKeyEvent(ImGuiKey_KeypadMultiply, farLimit, 1.0F, accel);
}
processKeyEvent(ImGuiKey_KeypadAdd, rotation[2], -0.075F, accel);
processKeyEvent(ImGuiKey_KeypadSubtract, rotation[2], 0.075F, accel);
rotation[2] = std::fmod(rotation[2], 2 * std::numbers::pi_v<float>);
}
bool validateVector(const std::vector<float> &vector, u32 vertexCount, u32 divisor, const std::string &name,std::string &errorMessage) {
if (!vector.empty()) {
if (vector.size() % divisor != 0) {
errorMessage = name + " must be a multiple of " + std::to_string(divisor);
return false;
}
} else {
errorMessage = name + " can't be empty";
return false;
}
auto vectorCount = vector.size()/divisor;
if (vectorCount != vertexCount) {
errorMessage = hex::format("Expected {} colors, got {}", vertexCount, vectorCount);
return false;
}
return true;
}
template <class T>
void bindBuffers(Buffers<T> &buffers, const gl::VertexArray &vertexArray, Vectors<T> vectors, IndexType indexType) {
buffers.vertices = {};
buffers.normals = {};
buffers.colors = {};
buffers.uv = {};
buffers.indices = {};
vertexArray.bind();
u32 vertexCount = vectors.vertices.size() / 3;
std::string errorMessage;
if (indexType != IndexType::Undefined && !vectors.indices.empty())
buffers.indices = gl::Buffer<T>(gl::BufferType::Index, vectors.indices);
if (validateVector(vectors.vertices, vertexCount, 3, "Positions", errorMessage)) {
if ((indexType == IndexType::Undefined || vectors.indices.empty()) && vertexCount % 3 != 0)
throw std::runtime_error("Without indices vertices must be a multiple of 3");
else
buffers.vertices = gl::Buffer<float>(gl::BufferType::Vertex, vectors.vertices);
} else
throw std::runtime_error(errorMessage);
if (validateVector(vectors.colors, vertexCount, 4, "Colors", errorMessage))
buffers.colors = gl::Buffer<float>(gl::BufferType::Vertex, vectors.colors);
else
throw std::runtime_error(errorMessage);
if (validateVector(vectors.normals, vertexCount, 3, "Normals", errorMessage))
buffers.normals = gl::Buffer<float>(gl::BufferType::Vertex, vectors.normals);
else
throw std::runtime_error(errorMessage);
if (validateVector(vectors.uv, vertexCount, 2, "UV coordinates", errorMessage))
buffers.uv = gl::Buffer<float>(gl::BufferType::Vertex, vectors.uv);
else
throw std::runtime_error(errorMessage);
vertexArray.addBuffer(0, buffers.vertices);
vertexArray.addBuffer(1, buffers.colors, 4);
vertexArray.addBuffer(2, buffers.normals);
vertexArray.addBuffer(3, buffers.uv, 2);
buffers.vertices.unbind();
buffers.colors.unbind();
buffers.normals.unbind();
buffers.uv.unbind();
if (indexType != IndexType::Undefined)
buffers.indices.unbind();
vertexArray.unbind();
}
template <class T>
void bindLineBuffers(LineBuffers<T> &lineBuffers, const gl::VertexArray &vertexArray, const LineVectors<T> &lineVectors, IndexType indexType) {
lineBuffers.vertices = {};
lineBuffers.colors = {};
lineBuffers.indices = {};
u32 vertexCount = lineVectors.vertices.size() / 3;
vertexArray.bind();
std::string errorMessage;
if (indexType != IndexType::Undefined)
lineBuffers.indices = gl::Buffer<T>(gl::BufferType::Index, lineVectors.indices);
if (validateVector(lineVectors.vertices, vertexCount, 3, "Positions", errorMessage)) {
if ((indexType == IndexType::Undefined || lineVectors.indices.empty()) && vertexCount % 3 != 0)
throw std::runtime_error("Without indices vertices must be a multiple of 3");
else
lineBuffers.vertices = gl::Buffer<float>(gl::BufferType::Vertex, lineVectors.vertices);
} else
throw std::runtime_error(errorMessage);
if (validateVector(lineVectors.colors, vertexCount, 4, "Colors", errorMessage))
lineBuffers.colors = gl::Buffer<float>(gl::BufferType::Vertex, lineVectors.colors);
else
throw std::runtime_error(errorMessage);
vertexArray.addBuffer(0, lineBuffers.vertices);
vertexArray.addBuffer(1, lineBuffers.colors, 4);
lineBuffers.vertices.unbind();
lineBuffers.colors.unbind();
if (indexType != IndexType::Undefined)
lineBuffers.indices.unbind();
vertexArray.unbind();
}
void drawWindow(const ImGuiExt::Texture &texture, ImVec2 &renderingWindowSize, const gl::Matrix<float, 4, 4> &mvp) {
auto textureSize = texture.getSize();
auto textureWidth = textureSize.x;
auto textureHeight = textureSize.y;
ImVec2 screenPos = ImGui::GetCursorScreenPos();
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0));
ImGui::SetNextWindowSizeConstraints(scaled({ 350, 350 }), ImVec2(FLT_MAX, FLT_MAX));
if (ImGui::BeginChild("##image", textureSize, ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY | ImGuiChildFlags_Border, ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse)) {
renderingWindowSize = ImGui::GetContentRegionAvail();
ImGui::Image(texture, textureSize, ImVec2(0, 1), ImVec2(1, 0));
if (s_drawAxes) {
gl::Matrix<float, 4, 4> axes = gl::Matrix<float, 4, 4>::identity();
axes(0, 3) = 1.0F;
axes(1, 3) = 1.0F;
axes(2, 3) = 1.0F;
axes = axes * mvp;
bool showX = axes(0, 3) > 0.0F;
bool showY = axes(1, 3) > 0.0F;
bool showZ = axes(2, 3) > 0.0F;
axes.updateRow(0, axes.getRow(0) * (1.0F / axes(0, 3)));
axes.updateRow(1, axes.getRow(1) * (1.0F / axes(1, 3)));
axes.updateRow(2, axes.getRow(2) * (1.0F / axes(2, 3)));
auto axesPosx = (axes.getColumn(0) + 1.0F) * (textureWidth / 2.0F);
auto axesPosy = (axes.getColumn(1) + 1.0F) * (-textureHeight / 2.0F) + textureHeight;
ImDrawList *drawList = ImGui::GetWindowDrawList();
if (showX)
drawList->AddText(ImVec2(axesPosx[0], axesPosy[0]) + screenPos, IM_COL32(255, 0, 0, 255), "X");
if (showY)
drawList->AddText(ImVec2(axesPosx[1], axesPosy[1]) + screenPos, IM_COL32(0, 255, 0, 255), "Y");
if (showZ)
drawList->AddText(ImVec2(axesPosx[2], axesPosy[2]) + screenPos, IM_COL32(0, 0, 255, 255), "Z");
}
if (ImHexApi::System::isDebugBuild()) {
auto mousePos = ImClamp(ImGui::GetMousePos() - screenPos, { 0, 0 }, textureSize);
ImDrawList *drawList = ImGui::GetWindowDrawList();
drawList->AddText(
screenPos + scaled({ 5, 5 }),
ImGui::GetColorU32(ImGuiCol_Text),
hex::format("X: {:.5}\nY: {:.5}", mousePos.x, mousePos.y).c_str());
}
}
ImGui::EndChild();
ImGui::PopStyleVar();
{
ImGui::SameLine();
{
ImGui::PushID(5);
ImGui::Dummy(ImVec2(0, 0));
ImGui::PopID();
}
}
// Draw axis arrows toggle
{
ImGui::PushID(1);
if (ImGuiExt::DimmedIconToggle(ICON_BI_EMPTY_ARROWS, &s_drawAxes))
s_shouldReset = true;
ImGui::PopID();
}
ImGui::SameLine();
// Draw grid toggle
{
ImGui::PushID(2);
if (ImGuiExt::DimmedIconToggle(s_isPerspective ? ICON_BI_GRID : ICON_VS_SYMBOL_NUMBER, &s_drawGrid))
s_shouldReset = true;
ImGui::PopID();
}
ImGui::SameLine();
// Draw light source toggle
{
ImGui::PushID(3);
if (ImGuiExt::DimmedIconToggle(ICON_VS_LIGHTBULB, &s_drawLightSource))
s_shouldReset = true;
if (ImGui::IsItemClicked(ImGuiMouseButton_Right)) {
ImGui::OpenPopup("LightSettings");
}
if (ImGui::BeginPopup("LightSettings")) {
if (ImGui::DragFloat3("hex.visualizers.pl_visualizer.3d.light_position"_lang, s_lightPosition.data(), 0.05F)) {
s_shouldUpdateLightSource = true;
}
ImGui::SliderFloat("hex.visualizers.pl_visualizer.3d.ambient_brightness"_lang, &s_lightBrightness.data()[0], 0, 2);
ImGui::SliderFloat("hex.visualizers.pl_visualizer.3d.diffuse_brightness"_lang, &s_lightBrightness.data()[1], 0, 2);
ImGui::SliderFloat("hex.visualizers.pl_visualizer.3d.specular_brightness"_lang, &s_lightBrightness.data()[2], 0, 2);
ImGui::SliderFloat("hex.visualizers.pl_visualizer.3d.object_reflectiveness"_lang, &s_lightBrightness.data()[3], 0, 64);
if (ImGui::ColorEdit3("hex.visualizers.pl_visualizer.3d.light_color"_lang, s_lightColor.data()))
s_shouldUpdateLightSource = true;
ImGui::EndPopup();
}
ImGui::PopID();
}
ImGui::SameLine();
ImGui::SeparatorEx(ImGuiSeparatorFlags_Vertical);
ImGui::SameLine();
// Draw projection toggle
{
ImGui::PushID(4);
if (ImGuiExt::DimmedIconToggle(ICON_BI_VIEW_PERSPECTIVE, ICON_BI_VIEW_ORTHO, &s_isPerspective)) {
s_shouldReset = true;
}
ImGui::PopID();
}
ImGui::SameLine();
// Draw solid / line mode toggle
{
ImGui::PushID(4);
bool isSolid = s_drawMode == GL_TRIANGLES;
if (ImGuiExt::DimmedIconToggle(ICON_BI_MOD_SOLIDIFY, ICON_BI_CUBE , &isSolid)) {
s_shouldReset = true;
s_drawMode = isSolid ? GL_TRIANGLES : GL_LINES;
}
ImGui::PopID();
}
ImGui::SameLine();
ImGui::SeparatorEx(ImGuiSeparatorFlags_Vertical);
ImGui::SameLine();
if (ImGuiExt::DimmedButton("hex.ui.common.reset"_lang, ImVec2(renderingWindowSize.x-ImGui::GetCursorPosX(), 0))) {
s_translation = { { 0.0F, 0.0F, -3.0F } };
s_rotation = { { 0.0F, 0.0F, 0.0F } };
s_scaling = 1.0F;
}
// Draw more settings
if (ImGui::CollapsingHeader("hex.visualizers.pl_visualizer.3d.more_settings"_lang)) {
if (ImGuiExt::InputFilePicker("hex.visualizers.pl_visualizer.3d.texture_file"_lang, s_texturePath, {}))
s_shouldUpdateTexture = true;
}
}
}
template <class T>
void processRendering(std::shared_ptr<pl::ptrn::Pattern> verticesPattern, std::shared_ptr<pl::ptrn::Pattern> indicesPattern,
std::shared_ptr<pl::ptrn::Pattern> normalsPattern, std::shared_ptr<pl::ptrn::Pattern> colorsPattern,
std::shared_ptr<pl::ptrn::Pattern> uvPattern) {
static gl::LightSourceVectors sourceVectors(20);
static gl::VertexArray sourceVertexArray = {};
static gl::LightSourceBuffers sourceBuffers(sourceVertexArray, sourceVectors);
static gl::VertexArray gridVertexArray = {};
static gl::GridVectors gridVectors(9);
static gl::GridBuffers gridBuffers(gridVertexArray, gridVectors);
static gl::VertexArray axesVertexArray = {};
static gl::AxesVectors axesVectors;
static gl::AxesBuffers axesBuffers(axesVertexArray, axesVectors);
static gl::VertexArray vertexArray = {};
if (s_renderingWindowSize.x <= 0 || s_renderingWindowSize.y <= 0)
s_renderingWindowSize = {350_scaled, 350_scaled};
gl::Matrix<float, 4, 4> mvp(0);
static Buffers<T> buffers;
static LineBuffers<T> lineBuffers;
if (s_shouldReset) {
s_shouldReset = false;
s_shouldUpdateLightSource = true;
if (s_drawMode == GL_TRIANGLES) {
Vectors<T> vectors;
vectors.vertices = patternToArray<float>(verticesPattern.get());
s_vertexCount = vectors.vertices.size() / 3;
if (s_indexType != IndexType::Undefined) {
vectors.indices = patternToArray<T>(indicesPattern.get());
s_badIndices.clear();
auto indexCount = vectors.indices.size();
if (indexCount < 3 || indexCount % 3 != 0) {
throw std::runtime_error("Index count must be a multiple of 3");
}
auto booleans = std::views::transform(vectors.indices,isIndexInRange);
if (!std::accumulate(std::begin(booleans), std::end(booleans), true, std::logical_and<>())) {
std::string badIndicesStr = "Invalid indices: ";
for (auto badIndex : s_badIndices)
badIndicesStr += std::to_string(badIndex) + ", ";
badIndicesStr.pop_back();
badIndicesStr.pop_back();
badIndicesStr += hex::format(" for {} vertices",s_vertexCount);
throw std::runtime_error(badIndicesStr);
}
}
if (colorsPattern != nullptr)
vectors.colors = patternToArray<float>(colorsPattern.get());
if (normalsPattern != nullptr)
vectors.normals = patternToArray<float>(normalsPattern.get());
if (uvPattern != nullptr)
vectors.uv = patternToArray<float>(uvPattern.get());
loadVectors(vectors, s_indexType);
bindBuffers(buffers, vertexArray, vectors, s_indexType);
} else {
LineVectors<T> lineVectors;
lineVectors.vertices = patternToArray<float>(verticesPattern.get());
s_vertexCount = lineVectors.vertices.size() / 3;
if (s_indexType != IndexType::Undefined) {
lineVectors.indices = patternToArray<T>(indicesPattern.get());
auto indexCount = lineVectors.indices.size();
if (indexCount < 3 || indexCount % 3 != 0) {
throw std::runtime_error("Index count must be a multiple of 3");
}
s_badIndices.clear();
if (!std::ranges::all_of(lineVectors.indices,isIndexInRange)) {
std::string badIndicesStr = "Invalid indices: ";
for (auto badIndex : s_badIndices)
badIndicesStr += std::to_string(badIndex) + ", ";
badIndicesStr.pop_back();
badIndicesStr.pop_back();
badIndicesStr += hex::format(" for {} vertices",s_vertexCount);
throw std::runtime_error(badIndicesStr);
}
}
if (colorsPattern != nullptr)
lineVectors.colors = patternToArray<float>(colorsPattern.get());
loadLineVectors(lineVectors, s_indexType);
bindLineBuffers(lineBuffers, vertexArray, lineVectors, s_indexType);
}
}
if (s_shouldUpdateLightSource) {
s_shouldUpdateLightSource = false;
sourceVectors.moveTo(s_lightPosition);
sourceVectors.setColor(s_lightColor[0], s_lightColor[1], s_lightColor[2]);
sourceBuffers.moveVertices(sourceVertexArray, sourceVectors);
sourceBuffers.updateColors(sourceVertexArray, sourceVectors);
}
{
gl::Matrix<float, 4, 4> model(0);
gl::Matrix<float, 4, 4> scaledModel(0);
gl::Matrix<float, 4, 4> view(0);
gl::Matrix<float, 4, 4> projection(0);
unsigned width = std::floor(s_renderingWindowSize.x);
unsigned height = std::floor(s_renderingWindowSize.y);
gl::FrameBuffer frameBuffer(width, height);
gl::Texture renderTexture(width, height);
frameBuffer.attachTexture(renderTexture);
frameBuffer.bind();
s_rotate = gl::getRotationMatrix<float>(s_rotation, true, gl::RotationSequence::ZYX);
gl::Matrix<float, 4, 4> scale = gl::Matrix<float, 4, 4>::identity();
gl::Matrix<float, 4, 4> scaleForVertices = gl::Matrix<float, 4, 4>::identity();
gl::Matrix<float, 4, 4> translate = gl::Matrix<float, 4, 4>::identity();
float totalScale;
float viewWidth = s_renderingWindowSize.x / 500.0F;
float viewHeight = s_renderingWindowSize.y / 500.0F;
glViewport(0,0 , GLsizei(renderTexture.getWidth()), GLsizei(renderTexture.getHeight()));
glDepthRangef(s_nearLimit, s_farLimit);
glClearColor(0.00F, 0.00F, 0.00F, 0.00F);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
if (!s_isPerspective) {
projection = gl::GetOrthographicMatrix(viewWidth, viewHeight, s_nearLimit, s_farLimit, false);
totalScale = s_scaling / (std::fabs(s_translation[2]));
scale(0, 0) = totalScale;
scale(1, 1) = totalScale;
scale(2, 2) = totalScale;
translate(3, 0) = s_translation[0] / std::fabs(s_translation[2]);
translate(3, 1) = s_translation[1] / std::fabs(s_translation[2]);
translate(3, 2) = s_translation[2];
} else {
projection = gl::GetPerspectiveMatrix(viewWidth, viewHeight, s_nearLimit, s_farLimit, false);
totalScale = s_scaling;
scale(0, 0) = totalScale;
scale(1, 1) = totalScale;
scale(2, 2) = totalScale;
translate(3, 0) = s_translation[0];
translate(3, 1) = s_translation[1];
translate(3, 2) = s_translation[2];
}
totalScale /= (3.0F * s_max);
scaleForVertices(0, 0) = totalScale;
scaleForVertices(1, 1) = totalScale;
scaleForVertices(2, 2) = totalScale;
model = s_rotate * scale;
scaledModel = s_rotate * scaleForVertices;
view = translate;
mvp = model * view * projection;
if (s_drawMode == GL_TRIANGLES) {
static gl::Shader shader = gl::Shader(
romfs::get("shaders/default/vertex.glsl").string(),
romfs::get("shaders/default/fragment.glsl").string()
);
shader.bind();
shader.setUniform("modelScale", scaledModel);
shader.setUniform("modelMatrix", model);
shader.setUniform("viewMatrix", view);
shader.setUniform("projectionMatrix",projection);
shader.setUniform("lightPosition", s_lightPosition);
shader.setUniform("lightBrightness", s_lightBrightness);
shader.setUniform("lightColor", s_lightColor);
vertexArray.bind();
if (s_shouldUpdateTexture) {
s_shouldUpdateTexture = false;
s_modelTexture = ImGuiExt::Texture::fromImage(s_texturePath, ImGuiExt::Texture::Filter::Nearest);
if (s_modelTexture.isValid()) {
s_drawTexture = true;
}
}
if (s_drawTexture)
glBindTexture(GL_TEXTURE_2D, s_modelTexture);
buffers.indices.bind();
if (buffers.indices.getSize() == 0)
buffers.vertices.draw(s_drawMode);
else
buffers.indices.draw(s_drawMode);
buffers.indices.unbind();
} else {
static gl::Shader lineShader = gl::Shader(
romfs::get("shaders/default/lineVertex.glsl").string(),
romfs::get("shaders/default/lineFragment.glsl").string()
);
lineShader.bind();
lineShader.setUniform("modelMatrix", scaledModel);
lineShader.setUniform("viewMatrix", view);
lineShader.setUniform("projectionMatrix", projection);
vertexArray.bind();
lineBuffers.indices.bind();
if (lineBuffers.indices.getSize() == 0)
lineBuffers.vertices.draw(s_drawMode);
else
lineBuffers.indices.draw(s_drawMode);
lineBuffers.indices.unbind();
}
if (s_drawGrid || s_drawAxes) {
static auto gridAxesShader = gl::Shader(
romfs::get("shaders/default/lineVertex.glsl").string(),
romfs::get("shaders/default/lineFragment.glsl").string()
);
gridAxesShader.bind();
gridAxesShader.setUniform("modelMatrix", model);
gridAxesShader.setUniform("viewMatrix", view);
gridAxesShader.setUniform("projectionMatrix", projection);
if (s_drawGrid) {
gridVertexArray.bind();
gridBuffers.getIndices().bind();
gridBuffers.getIndices().draw(GL_LINES);
gridBuffers.getIndices().unbind();
gridVertexArray.unbind();
}
if (s_drawAxes) {
axesVertexArray.bind();
axesBuffers.getIndices().bind();
axesBuffers.getIndices().draw(GL_LINES);
axesBuffers.getIndices().unbind();
axesVertexArray.unbind();
}
gridAxesShader.unbind();
}
if (s_drawLightSource) {
static auto sourceShader = gl::Shader(
romfs::get("shaders/default/lightVertex.glsl").string(),
romfs::get("shaders/default/lightFragment.glsl").string()
);
sourceShader.bind();
sourceShader.setUniform("modelMatrix", model);
sourceShader.setUniform("viewMatrix", view);
sourceShader.setUniform("projectionMatrix", projection);
sourceVertexArray.bind();
sourceBuffers.getIndices().bind();
sourceBuffers.getIndices().draw(GL_TRIANGLES);
sourceBuffers.getIndices().unbind();
sourceVertexArray.unbind();
sourceShader.unbind();
}
vertexArray.unbind();
frameBuffer.unbind();
s_texture = ImGuiExt::Texture::fromGLTexture(renderTexture.release(), GLsizei(renderTexture.getWidth()), GLsizei(renderTexture.getHeight()));
drawWindow(s_texture, s_renderingWindowSize, mvp);
}
}
void draw3DVisualizer(pl::ptrn::Pattern &, bool shouldReset, std::span<const pl::core::Token::Literal> arguments) {
std::shared_ptr<pl::ptrn::Pattern> verticesPattern = arguments[0].toPattern();
std::shared_ptr<pl::ptrn::Pattern> indicesPattern = arguments[1].toPattern();
std::shared_ptr<pl::ptrn::Pattern> normalsPattern = nullptr;
std::shared_ptr<pl::ptrn::Pattern> colorsPattern = nullptr;
std::shared_ptr<pl::ptrn::Pattern> uvPattern = nullptr;
std::string textureFile;
if (arguments.size() > 2) {
normalsPattern = arguments[2].toPattern();
if (arguments.size() > 3) {
colorsPattern = arguments[3].toPattern();
if (arguments.size() > 4) {
uvPattern = arguments[4].toPattern();
if (arguments.size() > 5)
textureFile = arguments[5].toString();
}
}
}
s_texturePath = textureFile;
s_drawTexture = !textureFile.empty();
if (shouldReset)
s_shouldReset = true;
processInputEvents(s_rotation, s_translation, s_scaling, s_nearLimit, s_farLimit);
auto *iterable = dynamic_cast<pl::ptrn::IIterable*>(indicesPattern.get());
if (iterable != nullptr && iterable->getEntryCount() > 0) {
const auto &content = iterable->getEntry(0);
if (content->getSize() == 1) {
s_indexType = IndexType::U8;
processRendering<u8>(verticesPattern, indicesPattern, normalsPattern, colorsPattern, uvPattern);
} else if (content->getSize() == 2) {
s_indexType = IndexType::U16;
processRendering<u16>(verticesPattern, indicesPattern, normalsPattern, colorsPattern, uvPattern);
} else if (content->getSize() == 4) {
s_indexType = IndexType::U32;
processRendering<u32>(verticesPattern, indicesPattern, normalsPattern, colorsPattern, uvPattern);
}
} else {
s_indexType = IndexType::Undefined;
processRendering<u8>(verticesPattern, indicesPattern, normalsPattern, colorsPattern, uvPattern);
}
}
}
| 39,521
|
C++
|
.cpp
| 757
| 37.083223
| 203
| 0.534622
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
256
|
scatter_plot.cpp
|
WerWolv_ImHex/plugins/visualizers/source/content/pl_visualizers/scatter_plot.cpp
|
#include <hex/helpers/utils.hpp>
#include <content/visualizer_helpers.hpp>
#include <implot.h>
#include <imgui.h>
#include <hex/ui/imgui_imhex_extensions.h>
namespace hex::plugin::visualizers {
void drawScatterPlotVisualizer(pl::ptrn::Pattern &, bool shouldReset, std::span<const pl::core::Token::Literal> arguments) {
static std::vector<float> xValues, yValues;
auto xPattern = arguments[0].toPattern();
auto yPattern = arguments[1].toPattern();
if (ImPlot::BeginPlot("##plot", ImVec2(400, 250), ImPlotFlags_CanvasOnly)) {
ImPlot::SetupAxes("X", "Y", ImPlotAxisFlags_AutoFit, ImPlotAxisFlags_AutoFit);
if (shouldReset) {
xValues.clear(); yValues.clear();
xValues = sampleData(patternToArray<float>(xPattern.get()), ImPlot::GetPlotSize().x * 4);
yValues = sampleData(patternToArray<float>(yPattern.get()), ImPlot::GetPlotSize().x * 4);
}
ImPlot::PlotScatter("##scatter", xValues.data(), yValues.data(), xValues.size());
ImPlot::EndPlot();
}
}
}
| 1,111
|
C++
|
.cpp
| 22
| 41.954545
| 128
| 0.643188
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
257
|
image.cpp
|
WerWolv_ImHex/plugins/visualizers/source/content/pl_visualizers/image.cpp
|
#include <hex/helpers/utils.hpp>
#include <content/visualizer_helpers.hpp>
#include <imgui.h>
#include <hex/ui/imgui_imhex_extensions.h>
namespace hex::plugin::visualizers {
std::vector<u32> getIndices(pl::ptrn::Pattern *colorTablePattern, u128 width, u128 height);
ImGuiExt::Texture getTexture(pl::ptrn::Pattern *colorTablePattern, std::vector<u32>& indices, u128 width, u128 height);
void drawImageVisualizer(pl::ptrn::Pattern &, bool shouldReset, std::span<const pl::core::Token::Literal> arguments) {
static ImGuiExt::Texture texture;
static float scale = 1.0F;
if (shouldReset) {
auto pattern = arguments[0].toPattern();
auto data = pattern->getBytes();
texture = ImGuiExt::Texture::fromImage(data.data(), data.size(), ImGuiExt::Texture::Filter::Nearest);
scale = 200_scaled / texture.getSize().x;
}
if (texture.isValid())
ImGui::Image(texture, texture.getSize() * scale);
if (ImGui::IsWindowHovered()) {
auto scrollDelta = ImGui::GetIO().MouseWheel;
if (scrollDelta != 0.0F) {
scale += scrollDelta * 0.1F;
scale = std::clamp(scale, 0.1F, 10.0F);
}
}
}
void drawBitmapVisualizer(pl::ptrn::Pattern &, bool shouldReset, std::span<const pl::core::Token::Literal> arguments) {
static ImGuiExt::Texture texture;
static float scale = 1.0F;
if (shouldReset) {
auto pattern = arguments[0].toPattern();
auto width = arguments[1].toUnsigned();
auto height = arguments[2].toUnsigned();
bool hasColorTable = false;
if (arguments.size() == 4) {
auto colorTablePattern = arguments[3].toPattern();
if (colorTablePattern->getSize() > 0) {
auto indices = getIndices(pattern.get(), width, height);
texture = getTexture(colorTablePattern.get(), indices, width, height);
hasColorTable = true;
}
}
if (!hasColorTable) {
auto data = pattern->getBytes();
texture = ImGuiExt::Texture::fromBitmap(data.data(), data.size(), width, height,ImGuiExt::Texture::Filter::Nearest);
}
}
if (texture.isValid())
ImGui::Image(texture, texture.getSize() * scale);
if (ImGui::IsWindowHovered()) {
auto scrollDelta = ImGui::GetIO().MouseWheel;
if (scrollDelta != 0.0F) {
scale += scrollDelta * 0.1F;
scale = std::clamp(scale, 0.1F, 10.0F);
}
}
}
template <typename T> ImGuiExt::Texture unmapColors(pl::ptrn::Pattern *colorTablePattern, std::vector<u32>& indices, u128 width, u128 height) {
std::vector<T> colorTable = patternToArray<T>(colorTablePattern);
auto colorCount = colorTable.size();
auto indexCount = indices.size();
std::vector<T> image(indexCount);
for (u32 i = 0; i < indexCount; i++) {
auto index = indices[i];
if (index >= colorCount)
index = 0;
image[i] = colorTable[index];
}
void *tmp = image.data();
ImU8 *data = static_cast<ImU8 *>(tmp);
ImGuiExt::Texture texture = ImGuiExt::Texture::fromBitmap(data, indexCount*sizeof(T), width, height, ImGuiExt::Texture::Filter::Nearest);
return texture;
}
std::vector<u32> getIndices(pl::ptrn::Pattern *pattern, u128 width, u128 height) {
auto indexCount = 2 * width * height / pattern->getSize();
std::vector<u32> indices;
auto *iterable = dynamic_cast<pl::ptrn::IIterable *>(pattern);
if (iterable == nullptr || iterable->getEntryCount() <= 0)
return indices;
auto content = iterable->getEntry(0);
auto byteCount = content->getSize();
if (byteCount >= indexCount && indexCount != 0) {
auto bytePerIndex = byteCount / indexCount;
if (bytePerIndex == 1) {
auto temp = patternToArray<u8>(pattern);
indices = std::vector<u32>(temp.begin(), temp.end());
} else if (bytePerIndex == 2) {
auto temp = patternToArray<u16>(pattern);
indices = std::vector<u32>(temp.begin(), temp.end());
} else if (bytePerIndex == 4) {
auto temp = patternToArray<u32>(pattern);
indices = std::vector<u32>(temp.begin(), temp.end());
}
} else if (indexCount != 0) {
auto indicesPerByte = indexCount / byteCount;
auto temp = patternToArray<u8>(pattern);
if (indicesPerByte == 2) {
for (u32 i = 0; i < temp.size(); i++) {
indices.push_back(temp[i] & 0xF);
indices.push_back((temp[i] >> 4) & 0xF);
}
} else if (indicesPerByte == 4) {
for (u32 i = 0; i < temp.size(); i++) {
indices.push_back(temp[i] & 0x3);
indices.push_back((temp[i] >> 2) & 0x3);
indices.push_back((temp[i] >> 4) & 0x3);
indices.push_back((temp[i] >> 6) & 0x3);
}
}
}
return indices;
}
ImGuiExt::Texture getTexture(pl::ptrn::Pattern *colorTablePattern, std::vector<u32>& indices, u128 width, u128 height) {
ImGuiExt::Texture texture;
auto iterable = dynamic_cast<pl::ptrn::IIterable *>(colorTablePattern);
if (iterable == nullptr || iterable->getEntryCount() <= 0)
return texture;
auto content = iterable->getEntry(0);
auto colorTypeSize = content->getSize()*2;
if (colorTypeSize == 1) {
texture = unmapColors<u8>(colorTablePattern, indices, width, height);
} else if (colorTypeSize == 2) {
texture = unmapColors<u16>(colorTablePattern, indices, width, height);
} else if (colorTypeSize == 4) {
texture = unmapColors<u32>(colorTablePattern, indices, width, height);
}
return texture;
}
}
| 6,239
|
C++
|
.cpp
| 129
| 36.627907
| 148
| 0.56471
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
258
|
coordinates.cpp
|
WerWolv_ImHex/plugins/visualizers/source/content/pl_visualizers/coordinates.cpp
|
#include <hex/helpers/utils.hpp>
#include <content/visualizer_helpers.hpp>
#include <imgui.h>
#include <hex/api/task_manager.hpp>
#include <hex/api/localization_manager.hpp>
#include <hex/helpers/http_requests.hpp>
#include <nlohmann/json.hpp>
#include <hex/ui/imgui_imhex_extensions.h>
#include <romfs/romfs.hpp>
namespace hex::plugin::visualizers {
void drawCoordinateVisualizer(pl::ptrn::Pattern &, bool shouldReset, std::span<const pl::core::Token::Literal> arguments) {
static ImVec2 coordinate;
static double latitude, longitude;
static std::string address;
static std::mutex addressMutex;
static TaskHolder addressTask;
static auto mapTexture = ImGuiExt::Texture::fromImage(romfs::get("assets/common/map.jpg").span(), ImGuiExt::Texture::Filter::Linear);
static ImVec2 mapSize = scaled(ImVec2(500, 500 / mapTexture.getAspectRatio()));
if (shouldReset) {
std::scoped_lock lock(addressMutex);
address.clear();
latitude = arguments[0].toFloatingPoint();
longitude = arguments[1].toFloatingPoint();
// Convert latitude and longitude to X/Y coordinates on the image
coordinate.x = float((longitude + 180) / 360 * mapSize.x);
coordinate.y = float((-latitude + 90) / 180 * mapSize.y);
}
const auto startPos = ImGui::GetWindowPos() + ImGui::GetCursorPos();
// Draw background image
ImGui::Image(mapTexture, mapSize);
// Draw Longitude / Latitude text below image
ImGui::PushTextWrapPos(startPos.x + mapSize.x);
ImGuiExt::TextFormattedWrapped("{}: {:.0f}° {:.0f}' {:.4f}\" {} | {}: {:.0f}° {:.0f}' {:.4f}\" {}",
"hex.visualizers.pl_visualizer.coordinates.latitude"_lang,
std::floor(std::abs(latitude)),
std::floor(std::abs(latitude - std::floor(latitude)) * 60),
(std::abs(latitude - std::floor(latitude)) * 60 - std::floor(std::abs(latitude - std::floor(latitude)) * 60)) * 60,
latitude >= 0 ? "N" : "S",
"hex.visualizers.pl_visualizer.coordinates.longitude"_lang,
std::floor(std::abs(longitude)),
std::floor(std::abs(longitude - std::floor(longitude)) * 60),
(std::abs(longitude - std::floor(longitude)) * 60 - std::floor(std::abs(longitude - std::floor(longitude)) * 60)) * 60,
longitude >= 0 ? "E" : "W"
);
ImGui::PopTextWrapPos();
if (addressTask.isRunning()) {
ImGuiExt::TextSpinner("hex.visualizers.pl_visualizer.coordinates.querying"_lang);
} else if (address.empty()) {
if (ImGuiExt::DimmedButton("hex.visualizers.pl_visualizer.coordinates.query"_lang)) {
addressTask = TaskManager::createBackgroundTask("hex.visualizers.pl_visualizer.coordinates.querying"_lang, [lat = latitude, lon = longitude](auto &) {
constexpr static auto ApiURL = "https://geocode.maps.co/reverse?lat={}&lon={}&format=jsonv2";
HttpRequest request("GET", hex::format(ApiURL, lat, lon));
auto response = request.execute().get();
if (!response.isSuccess())
return;
try {
auto json = nlohmann::json::parse(response.getData());
auto jsonAddr = json["address"];
std::scoped_lock lock(addressMutex);
if (jsonAddr.contains("village")) {
address = hex::format("{} {}, {} {}",
jsonAddr["village"].get<std::string>(),
jsonAddr["county"].get<std::string>(),
jsonAddr["state"].get<std::string>(),
jsonAddr["country"].get<std::string>());
} else if (jsonAddr.contains("city")) {
address = hex::format("{}, {} {}, {} {}",
jsonAddr["road"].get<std::string>(),
jsonAddr["quarter"].get<std::string>(),
jsonAddr["city"].get<std::string>(),
jsonAddr["state"].get<std::string>(),
jsonAddr["country"].get<std::string>());
}
} catch (std::exception &) {
address = std::string("hex.visualizers.pl_visualizer.coordinates.querying_no_address"_lang);
}
});
}
} else {
ImGui::PushTextWrapPos(startPos.x + mapSize.x);
ImGuiExt::TextFormattedWrapped("{}", address);
ImGui::PopTextWrapPos();
}
// Draw crosshair pointing to the coordinates
{
constexpr static u32 CrossHairColor = 0xFF00D0D0;
constexpr static u32 BorderColor = 0xFF000000;
auto drawList = ImGui::GetWindowDrawList();
drawList->AddLine(startPos + ImVec2(coordinate.x, 0), startPos + ImVec2(coordinate.x, mapSize.y), CrossHairColor, 2_scaled);
drawList->AddLine(startPos + ImVec2(0, coordinate.y), startPos + ImVec2(mapSize.x, coordinate.y), CrossHairColor, 2_scaled);
drawList->AddCircleFilled(startPos + coordinate, 5, CrossHairColor);
drawList->AddCircle(startPos + coordinate, 5, BorderColor);
}
}
}
| 5,868
|
C++
|
.cpp
| 95
| 43.463158
| 166
| 0.526957
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
259
|
digital_signal.cpp
|
WerWolv_ImHex/plugins/visualizers/source/content/pl_visualizers/digital_signal.cpp
|
#include <hex/helpers/utils.hpp>
#include <content/visualizer_helpers.hpp>
#include <implot.h>
#include <imgui.h>
#include <hex/ui/imgui_imhex_extensions.h>
#include <pl/patterns/pattern_bitfield.hpp>
namespace hex::plugin::visualizers {
void drawDigitalSignalVisualizer(pl::ptrn::Pattern &, bool shouldReset, std::span<const pl::core::Token::Literal> arguments) {
auto *bitfield = dynamic_cast<pl::ptrn::PatternBitfield*>(arguments[0].toPattern().get());
if (bitfield == nullptr)
throw std::logic_error("Digital signal visualizer only works with bitfields.");
struct DataPoint {
std::array<ImVec2, 2> points;
std::string label;
std::string value;
ImColor color;
};
static std::vector<DataPoint> dataPoints;
static ImVec2 lastPoint;
if (shouldReset) {
dataPoints.clear();
lastPoint = { 0, 0 };
bitfield->forEachEntry(0, bitfield->getEntryCount(), [&](u64, pl::ptrn::Pattern *entry) {
size_t bitSize;
if (auto bitfieldField = dynamic_cast<pl::ptrn::PatternBitfieldField*>(entry); bitfieldField != nullptr)
bitSize = bitfieldField->getBitSize();
else
bitSize = entry->getSize() * 8;
auto value = entry->getValue();
bool high = value.toUnsigned() > 0;
dataPoints.emplace_back(
std::array<ImVec2, 2> { lastPoint, { lastPoint.x, high ? 1.0F : 0.0F } },
entry->getDisplayName(),
entry->getFormattedValue(),
entry->getColor()
);
lastPoint = dataPoints.back().points[1];
lastPoint.x += float(bitSize);
});
dataPoints.push_back({
.points = { lastPoint, { lastPoint.x, 0 } },
.label = "",
.value = "",
.color = ImColor(0x00)
});
}
if (ImPlot::BeginPlot("##Signal", ImVec2(600_scaled, 200_scaled), ImPlotFlags_NoLegend | ImPlotFlags_NoFrame | ImPlotFlags_NoMenus | ImPlotFlags_NoMouseText)) {
ImPlot::SetupAxisLimitsConstraints(ImAxis_X1, 0, lastPoint.x);
ImPlot::SetupAxis(ImAxis_Y1, "", ImPlotAxisFlags_LockMin | ImPlotAxisFlags_LockMax);
ImPlot::SetupAxisFormat(ImAxis_Y1, "");
ImPlot::SetupAxisLimits(ImAxis_Y1, -0.1F, 1.1F);
for (size_t i = 0; i < dataPoints.size() - 1; i += 1) {
const auto &left = dataPoints[i];
const auto &right = dataPoints[i + 1];
{
auto x = left.points[1].x + ((right.points[0].x - left.points[1].x) / 2);
ImPlot::Annotation(x, 0.55F, left.color, {}, false, "%s", left.label.c_str());
ImPlot::Annotation(x, 0.40F, left.color, {}, false, "%s", left.value.c_str());
}
{
ImVec2 min = ImPlot::PlotToPixels(ImPlotPoint(left.points[0].x, 0));
ImVec2 max = ImPlot::PlotToPixels(ImPlotPoint(right.points[1].x, 1));
ImPlot::PushPlotClipRect();
auto transparentColor = left.color;
transparentColor.Value.w = 0.2F;
ImPlot::GetPlotDrawList()->AddRectFilled(min, max, transparentColor);
ImPlot::PopPlotClipRect();
}
}
ImPlot::PushStyleVar(ImPlotStyleVar_LineWeight, 2_scaled);
ImPlot::PlotLineG("Signal", [](int idx, void*) -> ImPlotPoint {
return dataPoints[idx / 2].points[idx % 2];
}, nullptr, dataPoints.size() * 2);
ImPlot::PopStyleVar();
ImPlot::EndPlot();
}
}
}
| 3,888
|
C++
|
.cpp
| 78
| 35.846154
| 168
| 0.540512
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
260
|
line_plot.cpp
|
WerWolv_ImHex/plugins/visualizers/source/content/pl_visualizers/line_plot.cpp
|
#include <hex/helpers/utils.hpp>
#include <content/visualizer_helpers.hpp>
#include <implot.h>
#include <imgui.h>
#include <hex/ui/imgui_imhex_extensions.h>
namespace hex::plugin::visualizers {
void drawLinePlotVisualizer(pl::ptrn::Pattern &, bool shouldReset, std::span<const pl::core::Token::Literal> arguments) {
static std::vector<float> values;
auto dataPattern = arguments[0].toPattern();
if (ImPlot::BeginPlot("##plot", ImVec2(400, 250), ImPlotFlags_CanvasOnly)) {
ImPlot::SetupAxes("X", "Y", ImPlotAxisFlags_AutoFit, ImPlotAxisFlags_AutoFit);
if (shouldReset) {
values.clear();
values = sampleData(patternToArray<float>(dataPattern.get()), ImPlot::GetPlotSize().x * 4);
}
ImPlot::PlotLine("##line", values.data(), values.size());
ImPlot::EndPlot();
}
}
}
| 904
|
C++
|
.cpp
| 20
| 37.15
| 125
| 0.638857
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
261
|
timestamp.cpp
|
WerWolv_ImHex/plugins/visualizers/source/content/pl_visualizers/timestamp.cpp
|
#include <hex/helpers/utils.hpp>
#include <content/visualizer_helpers.hpp>
#include <numbers>
#include <imgui.h>
#include <hex/api/imhex_api.hpp>
#include <hex/ui/imgui_imhex_extensions.h>
#include <chrono>
#include <fmt/chrono.h>
namespace hex::plugin::visualizers {
void drawTimestampVisualizer(pl::ptrn::Pattern &, bool, std::span<const pl::core::Token::Literal> arguments) {
time_t timestamp = arguments[0].toUnsigned();
auto tm = fmt::gmtime(timestamp);
auto date = std::chrono::year_month_day(std::chrono::year(tm.tm_year + 1900), std::chrono::month(tm.tm_mon + 1), std::chrono::day(tm.tm_mday));
auto lastMonthDay = std::chrono::year_month_day_last(date.year(), date.month() / std::chrono::last);
auto firstWeekDay = std::chrono::weekday(std::chrono::year_month_day(date.year(), date.month(), std::chrono::day(1)));
const auto scale = 1_scaled * (ImHexApi::Fonts::getFontSize() / ImHexApi::Fonts::DefaultFontSize);
// Draw calendar
if (ImGui::BeginTable("##month_table", 2)) {
ImGui::TableNextRow();
ImGui::TableNextColumn();
// Draw centered month name and year
ImGuiExt::TextFormattedCenteredHorizontal("{:%B %Y}", tm);
if (ImGui::BeginTable("##days_table", 7, ImGuiTableFlags_Borders | ImGuiTableFlags_NoHostExtendX, ImVec2(160, 120) * scale)) {
constexpr static auto ColumnFlags = ImGuiTableColumnFlags_WidthFixed | ImGuiTableColumnFlags_NoResize | ImGuiTableColumnFlags_NoReorder | ImGuiTableColumnFlags_NoHide;
ImGui::TableSetupColumn("M", ColumnFlags);
ImGui::TableSetupColumn("T", ColumnFlags);
ImGui::TableSetupColumn("W", ColumnFlags);
ImGui::TableSetupColumn("T", ColumnFlags);
ImGui::TableSetupColumn("F", ColumnFlags);
ImGui::TableSetupColumn("S", ColumnFlags);
ImGui::TableSetupColumn("S", ColumnFlags);
ImGui::TableHeadersRow();
ImGui::TableNextRow();
// Skip days before the first day of the month
for (u8 i = 0; i < firstWeekDay.c_encoding() - 1; ++i)
ImGui::TableNextColumn();
// Draw days
for (u8 i = 1; i <= u32(lastMonthDay.day()); ++i) {
ImGui::TableNextColumn();
ImGuiExt::TextFormatted("{:02}", i);
if (std::chrono::day(i) == date.day())
ImGui::TableSetBgColor(ImGuiTableBgTarget_CellBg, ImGuiExt::GetCustomColorU32(ImGuiCustomCol_ToolbarRed));
if (std::chrono::weekday(std::chrono::year_month_day(date.year(), date.month(), std::chrono::day(i))) == std::chrono::Sunday)
ImGui::TableNextRow();
}
ImGui::EndTable();
}
ImGui::TableNextColumn();
// Draw analog clock
const auto size = ImVec2(120, 120) * scale;
if (ImGui::BeginChild("##clock", size + ImVec2(0, ImGui::GetTextLineHeightWithSpacing()))) {
// Draw centered digital hour, minute and seconds
ImGuiExt::TextFormattedCenteredHorizontal("{:%H:%M:%S}", tm);
auto drawList = ImGui::GetWindowDrawList();
const auto center = ImGui::GetWindowPos() + ImVec2(0, ImGui::GetTextLineHeightWithSpacing()) + size / 2;
// Draw clock face
drawList->AddCircle(center, size.x / 2, ImGui::GetColorU32(ImGuiCol_TextDisabled), 0);
auto sectionPos = [](float i) {
return ImVec2(std::sin(-i * 30.0F * std::numbers::pi / 180.0F + std::numbers::pi / 2), std::cos(-i * 30.0F * std::numbers::pi / 180.0F + std::numbers::pi / 2));
};
// Draw clock sections and numbers
for (u8 i = 0; i < 12; ++i) {
auto text = hex::format("{}", (((i + 2) % 12) + 1));
drawList->AddLine(center + sectionPos(i) * size / 2.2, center + sectionPos(i) * size / 2, ImGui::GetColorU32(ImGuiCol_TextDisabled), 1_scaled);
drawList->AddText(center + sectionPos(i) * size / 3 - ImGui::CalcTextSize(text.c_str()) / 2, ImGui::GetColorU32(ImGuiCol_Text), text.c_str());
}
// Draw hour hand
drawList->AddLine(center, center + sectionPos((tm.tm_hour + 9) % 12 + float(tm.tm_min) / 60.0) * size / 3.5, ImGui::GetColorU32(ImGuiCol_TextDisabled), 3_scaled);
// Draw minute hand
drawList->AddLine(center, center + sectionPos((float(tm.tm_min) / 5.0F) - 3) * size / 2.5, ImGui::GetColorU32(ImGuiCol_TextDisabled), 3_scaled);
// Draw second hand
drawList->AddLine(center, center + sectionPos((float(tm.tm_sec) / 5.0F) - 3) * size / 2.5, ImGuiExt::GetCustomColorU32(ImGuiCustomCol_ToolbarRed), 2_scaled);
}
ImGui::EndChild();
ImGui::EndTable();
}
}
}
| 5,094
|
C++
|
.cpp
| 78
| 51.230769
| 183
| 0.579791
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
262
|
sound.cpp
|
WerWolv_ImHex/plugins/visualizers/source/content/pl_visualizers/sound.cpp
|
#include <hex/helpers/utils.hpp>
#include <content/visualizer_helpers.hpp>
#include <implot.h>
#include <imgui.h>
#include <miniaudio.h>
#include <fonts/codicons_font.h>
#include <hex/api/task_manager.hpp>
#include <hex/ui/imgui_imhex_extensions.h>
namespace hex::plugin::visualizers {
void drawSoundVisualizer(pl::ptrn::Pattern &, bool shouldReset, std::span<const pl::core::Token::Literal> arguments) {
auto wavePattern = arguments[0].toPattern();
auto channels = arguments[1].toUnsigned();
auto sampleRate = arguments[2].toUnsigned();
static std::vector<i16> waveData, sampledData;
static ma_device audioDevice;
static ma_device_config deviceConfig;
static bool shouldStop = false;
static u64 index = 0;
static TaskHolder resetTask;
if (sampleRate == 0)
throw std::logic_error(hex::format("Invalid sample rate: {}", sampleRate));
else if (channels == 0)
throw std::logic_error(hex::format("Invalid channel count: {}", channels));
if (shouldReset) {
waveData.clear();
resetTask = TaskManager::createTask("hex.visualizers.pl_visualizer.task.visualizing"_lang, TaskManager::NoProgress, [=](Task &) {
ma_device_stop(&audioDevice);
waveData = patternToArray<i16>(wavePattern.get());
sampledData = sampleData(waveData, 300_scaled * 4);
index = 0;
deviceConfig = ma_device_config_init(ma_device_type_playback);
deviceConfig.playback.format = ma_format_s16;
deviceConfig.playback.channels = channels;
deviceConfig.sampleRate = sampleRate;
deviceConfig.pUserData = &waveData;
deviceConfig.dataCallback = [](ma_device *device, void *pOutput, const void *, ma_uint32 frameCount) {
if (index >= waveData.size()) {
index = 0;
shouldStop = true;
return;
}
ma_copy_pcm_frames(pOutput, waveData.data() + index, frameCount, device->playback.format, device->playback.channels);
index += frameCount;
};
ma_device_init(nullptr, &deviceConfig, &audioDevice);
});
}
ImGui::BeginDisabled(resetTask.isRunning());
ImPlot::PushStyleVar(ImPlotStyleVar_PlotPadding, ImVec2(0, 0));
if (ImPlot::BeginPlot("##amplitude_plot", scaled(ImVec2(300, 80)), ImPlotFlags_CanvasOnly | ImPlotFlags_NoFrame | ImPlotFlags_NoInputs)) {
ImPlot::SetupAxes("##time", "##amplitude", ImPlotAxisFlags_NoDecorations | ImPlotAxisFlags_NoMenus, ImPlotAxisFlags_NoDecorations | ImPlotAxisFlags_NoMenus);
ImPlot::SetupAxesLimits(0, waveData.size(), std::numeric_limits<i16>::min(), std::numeric_limits<i16>::max(), ImGuiCond_Always);
double dragPos = index;
if (ImPlot::DragLineX(1, &dragPos, ImGui::GetStyleColorVec4(ImGuiCol_Text))) {
if (dragPos < 0) dragPos = 0;
if (dragPos >= waveData.size()) dragPos = waveData.size() - 1;
index = dragPos;
}
ImPlot::PlotLine("##audio", sampledData.data(), sampledData.size());
ImPlot::EndPlot();
}
ImPlot::PopStyleVar();
{
const u64 min = 0, max = waveData.size();
ImGui::PushItemWidth(300_scaled);
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0));
ImGui::SliderScalar("##index", ImGuiDataType_U64, &index, &min, &max, "");
ImGui::PopStyleVar();
ImGui::PopItemWidth();
}
if (shouldStop) {
shouldStop = false;
ma_device_stop(&audioDevice);
}
bool playing = ma_device_is_started(&audioDevice);
if (ImGuiExt::IconButton(playing ? ICON_VS_DEBUG_PAUSE : ICON_VS_PLAY, ImGuiExt::GetCustomColorVec4(ImGuiCustomCol_ToolbarGreen))) {
if (playing)
ma_device_stop(&audioDevice);
else
ma_device_start(&audioDevice);
}
ImGui::SameLine();
if (ImGuiExt::IconButton(ICON_VS_DEBUG_STOP, ImGuiExt::GetCustomColorVec4(ImGuiCustomCol_ToolbarRed))) {
index = 0;
ma_device_stop(&audioDevice);
}
ImGui::EndDisabled();
ImGui::SameLine();
if (resetTask.isRunning())
ImGuiExt::TextSpinner("");
else
ImGuiExt::TextFormatted("{:02d}:{:02d} / {:02d}:{:02d}",
(index / sampleRate) / 60, (index / sampleRate) % 60,
(waveData.size() / sampleRate) / 60, (waveData.size() / sampleRate) % 60);
}
}
| 4,880
|
C++
|
.cpp
| 96
| 38.447917
| 169
| 0.584822
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
263
|
table.cpp
|
WerWolv_ImHex/plugins/visualizers/source/content/pl_visualizers/table.cpp
|
#include <hex/helpers/utils.hpp>
#include <content/visualizer_helpers.hpp>
#include <imgui.h>
#include <imgui_internal.h>
#include <hex/ui/imgui_imhex_extensions.h>
#include <pl/patterns/pattern_array_static.hpp>
#include <pl/patterns/pattern_array_dynamic.hpp>
#include <pl/patterns/pattern_bitfield.hpp>
namespace hex::plugin::visualizers {
void drawTableVisualizer(pl::ptrn::Pattern &, bool shouldReset, std::span<const pl::core::Token::Literal> arguments) {
static std::vector<std::string> tableContent;
static u128 width = 0, height = 0;
if (shouldReset) {
tableContent.clear();
width = height = 0;
auto pattern = arguments[0].toPattern();
if (dynamic_cast<pl::ptrn::PatternArrayStatic*>(pattern.get()) == nullptr &&
dynamic_cast<pl::ptrn::PatternArrayDynamic*>(pattern.get()) == nullptr &&
dynamic_cast<pl::ptrn::PatternBitfieldArray*>(pattern.get()) == nullptr)
{
throw std::logic_error("Table visualizer requires an array pattern as the first argument.");
}
width = arguments[1].toUnsigned();
height = arguments[2].toUnsigned();
auto iterable = dynamic_cast<pl::ptrn::IIterable*>(pattern.get());
iterable->forEachEntry(0, iterable->getEntryCount(), [&](u64, pl::ptrn::Pattern *entry) {
tableContent.push_back(entry->toString());
});
}
if (width >= IMGUI_TABLE_MAX_COLUMNS)
throw std::logic_error(hex::format("Table visualizer cannot have more than {} columns.", IMGUI_TABLE_MAX_COLUMNS));
if (ImGui::BeginTable("##visualizer_table", width, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg)) {
for (u128 i = 0; i < height; i += 1) {
ImGui::TableNextRow();
for (u128 j = 0; j < width; j += 1) {
ImGui::TableSetColumnIndex(j);
if (i * width + j < tableContent.size())
ImGui::TextUnformatted(tableContent[(i * width) + j].c_str());
else
ImGui::TextUnformatted("??");
}
}
ImGui::EndTable();
}
}
}
| 2,276
|
C++
|
.cpp
| 46
| 38.130435
| 127
| 0.582507
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
264
|
plugin_yara.cpp
|
WerWolv_ImHex/plugins/yara_rules/source/plugin_yara.cpp
|
#include <hex/plugin.hpp>
#include <hex/api/content_registry.hpp>
#include <hex/helpers/logger.hpp>
#include <romfs/romfs.hpp>
#include "content/views/view_yara.hpp"
using namespace hex;
using namespace hex::plugin::yara;
namespace hex::plugin::yara {
void registerDataInformationSections();
void registerViews() {
ContentRegistry::Views::add<ViewYara>();
}
}
IMHEX_PLUGIN_SETUP("Yara Rules", "WerWolv", "Support for matching Yara rules") {
hex::log::debug("Using romfs: '{}'", romfs::name());
for (auto &path : romfs::list("lang"))
hex::ContentRegistry::Language::addLocalization(nlohmann::json::parse(romfs::get(path).string()));
registerViews();
registerDataInformationSections();
}
| 739
|
C++
|
.cpp
| 20
| 33.3
| 106
| 0.715493
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
265
|
data_information_sections.cpp
|
WerWolv_ImHex/plugins/yara_rules/source/content/data_information_sections.cpp
|
#include <hex/api/content_registry.hpp>
#include <imgui.h>
#include <hex/api/task_manager.hpp>
#include <hex/helpers/default_paths.hpp>
#include <hex/ui/imgui_imhex_extensions.h>
#include <content/yara_rule.hpp>
#include <romfs/romfs.hpp>
namespace hex::plugin::yara {
class InformationAdvancedFileInformation : public ContentRegistry::DataInformation::InformationSection {
public:
InformationAdvancedFileInformation() : InformationSection("hex.yara.information_section.advanced_data_info") { }
~InformationAdvancedFileInformation() override = default;
struct Category {
struct Comperator {
bool operator()(const YaraRule::Rule &a, const YaraRule::Rule &b) const {
return a.identifier < b.identifier;
}
};
std::set<YaraRule::Rule, Comperator> matchedRules;
};
void process(Task &task, prv::Provider *provider, Region region) override {
for (const auto &yaraSignaturePath : paths::YaraAdvancedAnalysis.read()) {
for (const auto &ruleFilePath : std::fs::recursive_directory_iterator(yaraSignaturePath)) {
wolv::io::File file(ruleFilePath.path(), wolv::io::File::Mode::Read);
if (!file.isValid())
continue;
YaraRule yaraRule(file.readString());
task.setInterruptCallback([&yaraRule] {
yaraRule.interrupt();
});
const auto result = yaraRule.match(provider, region);
if (result.has_value()) {
const auto &rules = result.value().matchedRules;
for (const auto &rule : rules) {
if (!rule.metadata.contains("category")) continue;
const auto &categoryName = rule.metadata.at("category");
m_categories[categoryName].matchedRules.insert(rule);
}
}
task.update();
}
}
}
void reset() override {
m_categories.clear();
}
void drawContent() override {
const auto empty = !std::ranges::any_of(m_categories, [](const auto &entry) {
const auto &[categoryName, category] = entry;
return !category.matchedRules.empty();
});
if (!empty) {
if (ImGui::BeginTable("information", 2, ImGuiTableFlags_SizingStretchProp | ImGuiTableFlags_NoKeepColumnsVisible)) {
ImGui::TableSetupColumn("Left", ImGuiTableColumnFlags_WidthStretch, 0.5F);
ImGui::TableSetupColumn("Right", ImGuiTableColumnFlags_WidthStretch, 0.5F);
ImGui::TableNextRow();
for (auto &[categoryName, category] : m_categories) {
if (category.matchedRules.empty())
continue;
ImGui::TableNextColumn();
if (ImGuiExt::BeginSubWindow(categoryName.c_str())) {
for (const auto &match : category.matchedRules) {
const auto &ruleName = match.metadata.contains("name") ? match.metadata.at("name") : match.identifier;
ImGui::TextUnformatted(ruleName.c_str());
}
}
ImGuiExt::EndSubWindow();
}
ImGui::EndTable();
}
} else {
ImGui::NewLine();
ImGuiExt::TextFormattedCenteredHorizontal("{}", "hex.yara.information_section.advanced_data_info.no_information"_lang);
ImGui::NewLine();
}
}
private:
std::map<std::string, Category> m_categories;
};
void registerDataInformationSections() {
ContentRegistry::DataInformation::addInformationSection<InformationAdvancedFileInformation>();
}
}
| 4,143
|
C++
|
.cpp
| 83
| 33.951807
| 135
| 0.544081
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
266
|
yara_rule.cpp
|
WerWolv_ImHex/plugins/yara_rules/source/content/yara_rule.cpp
|
#include <content/yara_rule.hpp>
#include <wolv/literals.hpp>
#include <wolv/utils/guards.hpp>
#include <wolv/utils/string.hpp>
#include <wolv/io/file.hpp>
// <yara/types.h>'s RE type has a zero-sized array, which is not allowed in ISO C++.
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpedantic"
#include <yara.h>
#pragma GCC diagnostic pop
namespace hex::plugin::yara {
using namespace wolv::literals;
struct ResultContext {
YaraRule *rule;
std::vector<YaraRule::Rule> matchedRules;
std::vector<std::string> consoleMessages;
std::string includeBuffer;
};
void YaraRule::init() {
yr_initialize();
}
void YaraRule::cleanup() {
yr_finalize();
}
YaraRule::YaraRule(const std::string &content) : m_content(content) { }
YaraRule::YaraRule(const std::fs::path &path) : m_filePath(path) {
wolv::io::File file(path, wolv::io::File::Mode::Read);
if (!file.isValid())
return;
m_content = file.readString();
}
static int scanFunction(YR_SCAN_CONTEXT *context, int message, void *data, void *userData) {
auto &resultContext = *static_cast<ResultContext *>(userData);
switch (message) {
case CALLBACK_MSG_RULE_MATCHING: {
const auto *rule = static_cast<const YR_RULE *>(data);
if (rule->strings != nullptr) {
YR_STRING *string;
yr_rule_strings_foreach(rule, string) {
YaraRule::Rule newRule;
newRule.identifier = rule->identifier;
YR_MATCH *match;
yr_string_matches_foreach(context, string, match) {
newRule.matches.push_back({ string->identifier, Region { u64(match->offset), size_t(match->match_length) }, false });
}
YR_META *meta;
yr_rule_metas_foreach(rule, meta) {
newRule.metadata[meta->identifier] = meta->string;
}
const char *tag;
yr_rule_tags_foreach(rule, tag) {
newRule.tags.emplace_back(tag);
}
resultContext.matchedRules.emplace_back(std::move(newRule));
}
} else {
YaraRule::Rule newRule;
newRule.identifier = rule->identifier;
newRule.matches.push_back({ "", Region::Invalid(), true });
}
break;
}
case CALLBACK_MSG_CONSOLE_LOG: {
resultContext.consoleMessages.emplace_back(static_cast<const char *>(data));
break;
}
default:
break;
}
return resultContext.rule->isInterrupted() ? CALLBACK_ABORT : CALLBACK_CONTINUE;
}
wolv::util::Expected<YaraRule::Result, YaraRule::Error> YaraRule::match(prv::Provider *provider, Region region) {
YR_COMPILER *compiler = nullptr;
yr_compiler_create(&compiler);
ON_SCOPE_EXIT {
yr_compiler_destroy(compiler);
};
m_interrupted = false;
ResultContext resultContext = {};
resultContext.rule = this;
yr_compiler_set_include_callback(
compiler,
[](const char *includeName, const char *, const char *, void *userData) -> const char * {
auto context = static_cast<ResultContext *>(userData);
wolv::io::File file(context->rule->m_filePath.parent_path() / includeName, wolv::io::File::Mode::Read);
if (!file.isValid())
return nullptr;
context->includeBuffer = file.readString();
return context->includeBuffer.c_str();
},
[](const char *ptr, void *userData) {
hex::unused(ptr, userData);
},
&resultContext
);
if (yr_compiler_add_string(compiler, m_content.c_str(), nullptr) != ERROR_SUCCESS) {
std::string errorMessage(0xFFFF, '\x00');
yr_compiler_get_error_message(compiler, errorMessage.data(), errorMessage.size());
return wolv::util::Unexpected(Error { Error::Type::CompileError, errorMessage.c_str() });
}
YR_RULES *yaraRules;
yr_compiler_get_rules(compiler, &yaraRules);
ON_SCOPE_EXIT { yr_rules_destroy(yaraRules); };
YR_MEMORY_BLOCK_ITERATOR iterator;
struct ScanContext {
prv::Provider *provider;
Region region;
std::vector<u8> buffer;
YR_MEMORY_BLOCK currBlock = {};
};
ScanContext context;
context.provider = provider;
context.region = region;
context.currBlock.base = 0;
context.currBlock.fetch_data = [](YR_MEMORY_BLOCK *block) -> const u8 * {
auto &context = *static_cast<ScanContext *>(block->context);
context.buffer.resize(context.currBlock.size);
if (context.buffer.empty())
return nullptr;
block->size = context.currBlock.size;
context.provider->read(context.provider->getBaseAddress() + context.currBlock.base, context.buffer.data(), context.buffer.size());
return context.buffer.data();
};
iterator.file_size = [](YR_MEMORY_BLOCK_ITERATOR *iterator) -> u64 {
auto &context = *static_cast<ScanContext *>(iterator->context);
return context.region.size;
};
iterator.context = &context;
iterator.first = [](YR_MEMORY_BLOCK_ITERATOR *iterator) -> YR_MEMORY_BLOCK *{
auto &context = *static_cast<ScanContext *>(iterator->context);
context.currBlock.base = context.region.address;
context.currBlock.size = 0;
context.buffer.clear();
iterator->last_error = ERROR_SUCCESS;
return iterator->next(iterator);
};
iterator.next = [](YR_MEMORY_BLOCK_ITERATOR *iterator) -> YR_MEMORY_BLOCK * {
auto &context = *static_cast<ScanContext *>(iterator->context);
u64 address = context.currBlock.base + context.currBlock.size;
iterator->last_error = ERROR_SUCCESS;
context.currBlock.base = address;
context.currBlock.size = std::min<size_t>(context.region.size - (address - context.region.address), 10_MiB);
context.currBlock.context = &context;
if (context.currBlock.size == 0) return nullptr;
return &context.currBlock;
};
if (yr_rules_scan_mem_blocks(yaraRules, &iterator, 0, scanFunction, &resultContext, 0) != ERROR_SUCCESS) {
std::string errorMessage(0xFFFF, '\x00');
yr_compiler_get_error_message(compiler, errorMessage.data(), errorMessage.size());
return wolv::util::Unexpected(Error { Error::Type::RuntimeError, errorMessage.c_str() });
}
if (m_interrupted)
return wolv::util::Unexpected(Error { Error::Type::Interrupted, "" });
return Result { resultContext.matchedRules, resultContext.consoleMessages };
}
void YaraRule::interrupt() {
m_interrupted = true;
}
bool YaraRule::isInterrupted() const {
return m_interrupted;
}
}
| 7,546
|
C++
|
.cpp
| 162
| 34.351852
| 145
| 0.570844
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
267
|
view_yara.cpp
|
WerWolv_ImHex/plugins/yara_rules/source/content/views/view_yara.cpp
|
#include "content/views/view_yara.hpp"
#include <hex/api/content_registry.hpp>
#include <hex/api/project_file_manager.hpp>
#include <hex/helpers/fs.hpp>
#include <hex/helpers/default_paths.hpp>
#include <toasts/toast_notification.hpp>
#include <popups/popup_file_chooser.hpp>
#include <filesystem>
#include <wolv/io/fs.hpp>
#include <wolv/literals.hpp>
namespace hex::plugin::yara {
using namespace wolv::literals;
ViewYara::ViewYara() : View::Window("hex.yara_rules.view.yara.name", ICON_VS_BUG) {
YaraRule::init();
ContentRegistry::FileHandler::add({ ".yar", ".yara" }, [](const auto &path) {
for (const auto &destPath : paths::Yara.write()) {
if (wolv::io::fs::copyFile(path, destPath / path.filename(), std::fs::copy_options::overwrite_existing)) {
ui::ToastInfo::open("hex.yara_rules.view.yara.rule_added"_lang);
return true;
}
}
return false;
});
ProjectFile::registerPerProviderHandler({
.basePath = "yara.json",
.required = false,
.load = [this](prv::Provider *provider, const std::fs::path &basePath, const Tar &tar) -> bool {
auto fileContent = tar.readString(basePath);
if (fileContent.empty())
return true;
auto data = nlohmann::json::parse(fileContent.begin(), fileContent.end());
if (!data.contains("rules"))
return false;
auto &rules = data["rules"];
if (!rules.is_array())
return false;
m_matchedRules.get(provider).clear();
for (auto &rule : rules) {
if (!rule.contains("name") || !rule.contains("path"))
return false;
auto &name = rule["name"];
auto &path = rule["path"];
if (!name.is_string() || !path.is_string())
return false;
m_rulePaths.get(provider).emplace_back(std::fs::path(name.get<std::string>()), std::fs::path(path.get<std::string>()));
}
return true;
},
.store = [this](prv::Provider *provider, const std::fs::path &basePath, const Tar &tar) -> bool {
nlohmann::json data;
data["rules"] = nlohmann::json::array();
for (auto &[name, path] : m_rulePaths.get(provider)) {
data["rules"].push_back({
{ "name", wolv::util::toUTF8String(name) },
{ "path", wolv::util::toUTF8String(path) }
});
}
tar.writeString(basePath, data.dump(4));
return true;
}
});
ImHexApi::HexEditor::addBackgroundHighlightingProvider([this](u64 address, const u8 *, size_t size, bool) -> std::optional<color_t> {
auto &highlights = m_highlights.get();
const auto regions = highlights.overlapping({ address, address + (size - 1) });
constexpr static color_t YaraColor = 0x70B4771F;
if (regions.empty())
return std::nullopt;
else
return YaraColor;
});
ImHexApi::HexEditor::addTooltipProvider([this](u64 address, const u8 *, size_t size) {
if (m_matcherTask.isRunning())
return;
auto occurrences = m_highlights->overlapping({ address, (address + size - 1) });
if (occurrences.empty())
return;
ImGui::BeginTooltip();
for (const auto &occurrence : occurrences) {
ImGui::PushID(&occurrence);
if (ImGui::BeginTable("##tooltips", 1, ImGuiTableFlags_RowBg | ImGuiTableFlags_NoClip)) {
ImGui::TableNextRow();
ImGui::TableNextColumn();
{
const auto &tooltipValue = *occurrence.value;
ImGuiExt::TextFormatted("{}", tooltipValue);
}
ImGui::EndTable();
}
ImGui::PopID();
}
ImGui::EndTooltip();
});
}
ViewYara::~ViewYara() {
YaraRule::cleanup();
}
void ViewYara::drawContent() {
ImGuiExt::Header("hex.yara_rules.view.yara.header.rules"_lang, true);
if (ImGui::BeginListBox("##rules", ImVec2(-FLT_MIN, ImGui::GetTextLineHeightWithSpacing() * 5))) {
for (u32 i = 0; i < m_rulePaths->size(); i++) {
const bool selected = (*m_selectedRule == i);
if (ImGui::Selectable(wolv::util::toUTF8String((*m_rulePaths)[i].first).c_str(), selected)) {
*m_selectedRule = i;
}
}
ImGui::EndListBox();
}
if (ImGuiExt::IconButton(ICON_VS_ADD, ImGui::GetStyleColorVec4(ImGuiCol_Text))) {
const auto basePaths = paths::Yara.read();
std::vector<std::fs::path> paths;
for (const auto &path : basePaths) {
std::error_code error;
for (const auto &entry : std::fs::recursive_directory_iterator(path, error)) {
if (!entry.is_regular_file()) continue;
if (entry.path().extension() != ".yara" && entry.path().extension() != ".yar") continue;
paths.push_back(entry);
}
}
ui::PopupFileChooser::open(basePaths, paths, std::vector<hex::fs::ItemFilter>{ { "Yara File", "yara" }, { "Yara File", "yar" } }, true,
[&](const auto &path) {
m_rulePaths->push_back({ path.filename(), path });
});
}
ImGui::SameLine();
if (ImGuiExt::IconButton(ICON_VS_REMOVE, ImGui::GetStyleColorVec4(ImGuiCol_Text))) {
if (*m_selectedRule < m_rulePaths->size()) {
m_rulePaths->erase(m_rulePaths->begin() + *m_selectedRule);
m_selectedRule = std::min(*m_selectedRule, u32(m_rulePaths->size() - 1));
}
}
ImGui::NewLine();
if (ImGui::Button("hex.yara_rules.view.yara.match"_lang)) this->applyRules();
if (m_matcherTask.isRunning()) {
ImGui::SameLine();
ImGuiExt::TextSpinner("hex.yara_rules.view.yara.matching"_lang);
}
ImGuiExt::Header("hex.yara_rules.view.yara.header.matches"_lang);
auto matchesTableSize = ImGui::GetContentRegionAvail();
matchesTableSize.y *= 3.75 / 5.0;
matchesTableSize.y -= ImGui::GetTextLineHeightWithSpacing();
if (ImGui::BeginTable("matches", 3, ImGuiTableFlags_Borders | ImGuiTableFlags_Resizable | ImGuiTableFlags_Sortable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_RowBg | ImGuiTableFlags_ScrollY, matchesTableSize)) {
ImGui::TableSetupScrollFreeze(0, 1);
ImGui::TableSetupColumn("hex.yara_rules.view.yara.matches.variable"_lang, ImGuiTableColumnFlags_PreferSortAscending, 0, ImGui::GetID("variable"));
ImGui::TableSetupColumn("hex.ui.common.address"_lang, ImGuiTableColumnFlags_PreferSortAscending, 0, ImGui::GetID("address"));
ImGui::TableSetupColumn("hex.ui.common.size"_lang, ImGuiTableColumnFlags_PreferSortAscending, 0, ImGui::GetID("size"));
ImGui::TableHeadersRow();
if (!m_matcherTask.isRunning()) {
for (const auto &rule : *m_matchedRules) {
if (rule.matches.empty()) continue;
ImGui::TableNextRow();
ImGui::TableNextColumn();
if (ImGui::TreeNode(rule.identifier.c_str())) {
for (const auto &match : rule.matches) {
ImGui::TableNextRow();
ImGui::TableNextColumn();
ImGui::TextUnformatted(match.variable.c_str());
ImGui::TableNextColumn();
ImGui::TextUnformatted(hex::format("0x{0:08X}", match.region.getStartAddress()).c_str());
ImGui::TableNextColumn();
ImGui::TextUnformatted(hex::format("0x{0:08X}", match.region.getSize()).c_str());
}
ImGui::TreePop();
}
}
}
ImGui::EndTable();
}
auto consoleSize = ImGui::GetContentRegionAvail();
if (ImGui::BeginChild("##console", consoleSize, true, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_HorizontalScrollbar)) {
ImGuiListClipper clipper;
clipper.Begin(m_consoleMessages->size());
while (clipper.Step()) {
for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) {
const auto &message = m_consoleMessages->at(i);
if (ImGui::Selectable(message.c_str()))
ImGui::SetClipboardText(message.c_str());
}
}
}
ImGui::EndChild();
}
void ViewYara::clearResult() {
m_matchedRules->clear();
m_consoleMessages->clear();
}
void ViewYara::applyRules() {
this->clearResult();
auto provider = ImHexApi::Provider::get();
if (provider == nullptr)
return;
m_matcherTask = TaskManager::createTask("hex.yara_rules.view.yara.matching"_lang, 0, [this, provider](auto &task) {
std::vector<YaraRule::Result> results;
for (const auto &[fileName, filePath] : *m_rulePaths) {
YaraRule rule(filePath);
task.setInterruptCallback([&rule] {
rule.interrupt();
});
auto result = rule.match(provider, { provider->getBaseAddress(), provider->getSize() });
if (!result.has_value()) {
TaskManager::doLater([this, error = result.error()] {
m_consoleMessages->emplace_back(error.message);
});
return;
}
results.emplace_back(result.value());
task.increment();
}
TaskManager::doLater([this, results = std::move(results)] {
this->clearResult();
for (auto &result : results) {
m_matchedRules->insert(m_matchedRules->end(), result.matchedRules.begin(), result.matchedRules.end());
m_consoleMessages->insert(m_consoleMessages->end(), result.consoleMessages.begin(), result.consoleMessages.end());
}
for (YaraRule::Rule &rule : *m_matchedRules) {
for (auto &match : rule.matches) {
auto tags = hex::format("{}", fmt::join(rule.tags, ", "));
m_highlights->insert(
{ match.region.getStartAddress(), match.region.getEndAddress() },
hex::format("rule {0}{1} {{ {2} }}",
rule.identifier,
tags.empty() ? "" : hex::format(" : {}", tags),
match.variable
)
);
}
}
});
});
}
}
| 11,585
|
C++
|
.cpp
| 230
| 34.886957
| 224
| 0.520376
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
268
|
plugin_hashes.cpp
|
WerWolv_ImHex/plugins/hashes/source/plugin_hashes.cpp
|
#include <hex/plugin.hpp>
#include <hex/api/achievement_manager.hpp>
#include <hex/api/content_registry.hpp>
#include <hex/helpers/logger.hpp>
#include <romfs/romfs.hpp>
#include <content/views/view_hashes.hpp>
namespace hex::plugin::hashes {
void registerHashes();
}
using namespace hex;
using namespace hex::plugin::hashes;
IMHEX_PLUGIN_SETUP("Hashes", "WerWolv", "Hashing algorithms") {
hex::log::debug("Using romfs: '{}'", romfs::name());
for (auto &path : romfs::list("lang"))
hex::ContentRegistry::Language::addLocalization(nlohmann::json::parse(romfs::get(path).string()));
registerHashes();
ContentRegistry::Views::add<ViewHashes>();
AchievementManager::addAchievement<Achievement>("hex.builtin.achievement.misc", "hex.hashes.achievement.misc.create_hash.name")
.setDescription("hex.hashes.achievement.misc.create_hash.desc")
.setIcon(romfs::get("assets/achievements/fortune-cookie.png").span())
.addRequirement("hex.builtin.achievement.starting_out.open_file.name");
}
| 1,045
|
C++
|
.cpp
| 22
| 43.454545
| 131
| 0.733202
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
269
|
hashes.cpp
|
WerWolv_ImHex/plugins/hashes/source/content/hashes.cpp
|
#include <hex/api/content_registry.hpp>
#include <hex/api/localization_manager.hpp>
#include <hex/helpers/crypto.hpp>
#include <hex/helpers/utils.hpp>
#include <hex/providers/buffered_reader.hpp>
#include <hex/ui/imgui_imhex_extensions.h>
#include <nlohmann/json.hpp>
#include <wolv/literals.hpp>
#include <HashFactory.h>
namespace hex::plugin::hashes {
namespace {
using namespace wolv::literals;
std::vector<u8> hashProviderRegionWithHashLib(const Region& region, prv::Provider *provider, auto &hashFunction) {
auto reader = prv::ProviderReader(provider);
reader.seek(region.getStartAddress());
reader.setEndAddress(region.getEndAddress());
for (u64 address = region.getStartAddress(); address < region.getEndAddress(); address += 1_MiB) {
u64 readSize = std::min<u64>(1_MiB, (region.getEndAddress() - address) + 1);
auto data = reader.read(address, readSize);
hashFunction->TransformBytes({ data.begin(), data.end() }, 0, data.size());
}
auto result = hashFunction->TransformFinal();
auto bytes = result->GetBytes();
return { bytes.begin(), bytes.end() };
}
}
class HashMD5 : public ContentRegistry::Hashes::Hash {
public:
HashMD5() : Hash("hex.hashes.hash.md5") {}
Function create(std::string name) override {
return Hash::create(name, [](const Region& region, prv::Provider *provider) -> std::vector<u8> {
auto array = crypt::md5(provider, region.address, region.size);
return { array.begin(), array.end() };
});
}
[[nodiscard]] nlohmann::json store() const override { return { }; }
void load(const nlohmann::json &) override {}
};
class HashSHA1 : public ContentRegistry::Hashes::Hash {
public:
HashSHA1() : Hash("hex.hashes.hash.sha1") {}
Function create(std::string name) override {
return Hash::create(name, [](const Region& region, prv::Provider *provider) -> std::vector<u8> {
auto array = crypt::sha1(provider, region.address, region.size);
return { array.begin(), array.end() };
});
}
[[nodiscard]] nlohmann::json store() const override { return { }; }
void load(const nlohmann::json &) override {}
};
class HashSHA224 : public ContentRegistry::Hashes::Hash {
public:
HashSHA224() : Hash("hex.hashes.hash.sha224") {}
Function create(std::string name) override {
return Hash::create(name, [](const Region& region, prv::Provider *provider) -> std::vector<u8> {
auto array = crypt::sha224(provider, region.address, region.size);
return { array.begin(), array.end() };
});
}
[[nodiscard]] nlohmann::json store() const override { return { }; }
void load(const nlohmann::json &) override {}
};
class HashSHA256 : public ContentRegistry::Hashes::Hash {
public:
HashSHA256() : Hash("hex.hashes.hash.sha256") {}
Function create(std::string name) override {
return Hash::create(name, [](const Region& region, prv::Provider *provider) -> std::vector<u8> {
auto array = crypt::sha256(provider, region.address, region.size);
return { array.begin(), array.end() };
});
}
[[nodiscard]] nlohmann::json store() const override { return { }; }
void load(const nlohmann::json &) override {}
};
class HashSHA384 : public ContentRegistry::Hashes::Hash {
public:
HashSHA384() : Hash("hex.hashes.hash.sha384") {}
Function create(std::string name) override {
return Hash::create(name, [](const Region& region, prv::Provider *provider) -> std::vector<u8> {
auto array = crypt::sha384(provider, region.address, region.size);
return { array.begin(), array.end() };
});
}
[[nodiscard]] nlohmann::json store() const override { return { }; }
void load(const nlohmann::json &) override {}
};
class HashSHA512 : public ContentRegistry::Hashes::Hash {
public:
HashSHA512() : Hash("hex.hashes.hash.sha512") {}
Function create(std::string name) override {
return Hash::create(name, [](const Region& region, prv::Provider *provider) -> std::vector<u8> {
auto array = crypt::sha512(provider, region.address, region.size);
return { array.begin(), array.end() };
});
}
[[nodiscard]] nlohmann::json store() const override { return { }; }
void load(const nlohmann::json &) override {}
};
class HashCRC : public ContentRegistry::Hashes::Hash {
public:
HashCRC() : Hash("Cyclic Redundancy Check (CRC)") {
m_crcs.push_back(HashFactory::Checksum::CreateCRC(3, 0, 0, false, false, 0, 0, { "hex.hashes.hash.common.standard.custom" }));
for (CRCStandard standard = CRC3_GSM; standard < CRC64_XZ; standard = CRCStandard(int(standard) + 1)) {
m_crcs.push_back(HashFactory::Checksum::CreateCRC(standard));
}
}
void draw() override {
if (ImGui::BeginCombo("hex.hashes.hash.common.standard"_lang, Lang(m_crcs[m_selectedCrc]->GetName()))) {
for (size_t i = 0; i < m_crcs.size(); i++) {
const bool selected = m_selectedCrc == i;
if (ImGui::Selectable(Lang(m_crcs[i]->GetName()), selected))
m_selectedCrc = i;
if (selected)
ImGui::SetItemDefaultFocus();
}
ImGui::EndCombo();
}
if (m_selectedCrc != 0) {
const auto crc = dynamic_cast<const IICRC*>(m_crcs[m_selectedCrc].get());
m_width = crc->GetWidth();
m_polynomial = crc->GetPolynomial();
m_initialValue = crc->GetInit();
m_xorOut = crc->GetXOROut();
m_reflectIn = crc->GetReflectIn();
m_reflectOut = crc->GetReflectOut();
}
ImGui::BeginDisabled(m_selectedCrc != 0);
ImGuiExt::InputHexadecimal("hex.hashes.hash.common.size"_lang, &m_width);
ImGuiExt::InputHexadecimal("hex.hashes.hash.common.poly"_lang, &m_polynomial);
ImGuiExt::InputHexadecimal("hex.hashes.hash.common.iv"_lang, &m_initialValue);
ImGuiExt::InputHexadecimal("hex.hashes.hash.common.xor_out"_lang, &m_xorOut);
ImGui::NewLine();
ImGui::Checkbox("hex.hashes.hash.common.refl_in"_lang, &m_reflectIn);
ImGui::Checkbox("hex.hashes.hash.common.refl_out"_lang, &m_reflectOut);
ImGui::EndDisabled();
}
Function create(std::string name) override {
return Hash::create(name, [hash = *this](const Region& region, prv::Provider *provider) -> std::vector<u8> {
auto crc = HashFactory::Checksum::CreateCRC(hash.m_width, hash.m_polynomial, hash.m_initialValue, hash.m_reflectIn, hash.m_reflectOut, hash.m_xorOut, 0, { "CRC" });
crc->Initialize();
auto bytes = hashProviderRegionWithHashLib(region, provider, crc);
return bytes;
});
}
[[nodiscard]] nlohmann::json store() const override {
nlohmann::json result;
result["polynomial"] = m_polynomial;
result["initialValue"] = m_initialValue;
result["xorOut"] = m_xorOut;
result["reflectIn"] = m_reflectIn;
result["reflectOut"] = m_reflectOut;
return result;
}
void load(const nlohmann::json &json) override {
try {
m_polynomial = json.at("polynomial");
m_initialValue = json.at("initialValue");
m_xorOut = json.at("xorOut");
m_reflectIn = json.at("reflectIn");
m_reflectOut = json.at("reflectOut");
} catch (std::exception&) { }
}
private:
std::vector<IHash> m_crcs;
size_t m_selectedCrc = 0;
u32 m_width = 3;
u32 m_polynomial = 0;
u32 m_initialValue = 0;
u32 m_xorOut = 0;
bool m_reflectIn = false, m_reflectOut = false;
};
class HashBasic : public ContentRegistry::Hashes::Hash {
public:
using FactoryFunction = IHash(*)();
explicit HashBasic(FactoryFunction function) : Hash(function()->GetName()), m_factoryFunction(function) {}
Function create(std::string name) override {
return Hash::create(name, [hash = *this](const Region& region, prv::Provider *provider) -> std::vector<u8> {
IHash hashFunction = hash.m_factoryFunction();
hashFunction->Initialize();
return hashProviderRegionWithHashLib(region, provider, hashFunction);
});
}
[[nodiscard]] nlohmann::json store() const override { return { }; }
void load(const nlohmann::json &) override {}
private:
FactoryFunction m_factoryFunction;
};
class HashWithKey : public ContentRegistry::Hashes::Hash {
public:
using FactoryFunction = IHashWithKey(*)();
explicit HashWithKey(FactoryFunction function) : Hash(function()->GetName()), m_factoryFunction(function) {}
void draw() override {
ImGui::InputText("hex.hashes.hash.common.key"_lang, m_key, ImGuiInputTextFlags_CharsHexadecimal);
}
Function create(std::string name) override {
return Hash::create(name, [hash = *this, key = hex::parseByteString(m_key)](const Region& region, prv::Provider *provider) -> std::vector<u8> {
IHashWithKey hashFunction = hash.m_factoryFunction();
hashFunction->Initialize();
hashFunction->SetKey(key);
return hashProviderRegionWithHashLib(region, provider, hashFunction);
});
}
[[nodiscard]] nlohmann::json store() const override {
nlohmann::json result;
result["key"] = m_key;
return result;
}
void load(const nlohmann::json &data) override {
try {
m_key = data.at("key").get<std::string>();
} catch (std::exception&) { }
}
private:
FactoryFunction m_factoryFunction;
std::string m_key;
};
class HashInitialValue : public ContentRegistry::Hashes::Hash {
public:
using FactoryFunction = IHash(*)(const Int32);
explicit HashInitialValue(FactoryFunction function) : Hash(function(0)->GetName()), m_factoryFunction(function) {}
void draw() override {
ImGuiExt::InputHexadecimal("hex.hashes.hash.common.iv"_lang, &m_initialValue);
}
Function create(std::string name) override {
return Hash::create(name, [hash = *this](const Region& region, prv::Provider *provider) -> std::vector<u8> {
IHash hashFunction = hash.m_factoryFunction(Int32(hash.m_initialValue));
hashFunction->Initialize();
return hashProviderRegionWithHashLib(region, provider, hashFunction);
});
}
[[nodiscard]] nlohmann::json store() const override {
nlohmann::json result;
result["iv"] = m_initialValue;
return result;
}
void load(const nlohmann::json &data) override {
try {
m_initialValue = data.at("iv").get<u32>();
} catch (std::exception&) { }
}
private:
FactoryFunction m_factoryFunction;
u32 m_initialValue = 0x00;
};
class HashTiger : public ContentRegistry::Hashes::Hash {
public:
using FactoryFunction = IHash(*)(const Int32, const HashRounds&);
explicit HashTiger(std::string name, FactoryFunction function) : Hash(std::move(name)), m_factoryFunction(function) {}
void draw() override {
ImGui::Combo("hex.hashes.hash.common.size"_lang, &m_hashSize, "128 Bits\0" "160 Bits\0" "192 Bits\0");
ImGui::Combo("hex.hashes.hash.common.rounds"_lang, &m_hashRounds, "3 Rounds\0" "4 Rounds\0" "5 Rounds\0" "8 Rounds\0");
}
Function create(std::string name) override {
return Hash::create(name, [hash = *this](const Region& region, prv::Provider *provider) -> std::vector<u8> {
Int32 hashSize = 16;
switch (hash.m_hashSize) {
case 0: hashSize = 16; break;
case 1: hashSize = 20; break;
case 2: hashSize = 24; break;
}
HashRounds hashRounds = HashRounds::Rounds3;
switch (hash.m_hashRounds) {
case 0: hashRounds = HashRounds::Rounds3; break;
case 1: hashRounds = HashRounds::Rounds4; break;
case 2: hashRounds = HashRounds::Rounds5; break;
case 3: hashRounds = HashRounds::Rounds8; break;
}
IHash hashFunction = hash.m_factoryFunction(hashSize, hashRounds);
hashFunction->Initialize();
return hashProviderRegionWithHashLib(region, provider, hashFunction);
});
}
[[nodiscard]] nlohmann::json store() const override {
nlohmann::json result;
result["size"] = m_hashSize;
result["rounds"] = m_hashRounds;
return result;
}
void load(const nlohmann::json &data) override {
try {
m_hashSize = data.at("size").get<int>();
m_hashRounds = data.at("rounds").get<int>();
} catch (std::exception&) { }
}
private:
FactoryFunction m_factoryFunction;
int m_hashSize = 0, m_hashRounds = 0;
};
template<typename Config, typename T1, typename T2>
class HashBlake2 : public ContentRegistry::Hashes::Hash {
public:
using FactoryFunction = IHash(*)(T1 a_Config, T2 a_TreeConfig);
explicit HashBlake2(std::string name, FactoryFunction function) : Hash(std::move(name)), m_factoryFunction(function) {}
void draw() override {
ImGui::InputText("hex.hashes.hash.common.salt"_lang, m_salt, ImGuiInputTextFlags_CharsHexadecimal);
ImGui::InputText("hex.hashes.hash.common.key"_lang, m_key, ImGuiInputTextFlags_CharsHexadecimal);
ImGui::InputText("hex.hashes.hash.common.personalization"_lang, m_personalization, ImGuiInputTextFlags_CharsHexadecimal);
ImGui::Combo("hex.hashes.hash.common.size"_lang, &m_hashSize, "128 Bits\0" "160 Bits\0" "192 Bits\0" "224 Bits\0" "256 Bits\0" "288 Bits\0" "384 Bits\0" "512 Bits\0");
}
Function create(std::string name) override {
return Hash::create(name, [hash = *this, key = hex::parseByteString(m_key), salt = hex::parseByteString(m_salt), personalization = hex::parseByteString(m_personalization)](const Region& region, prv::Provider *provider) -> std::vector<u8> {
u32 hashSize = 16;
switch (hash.m_hashSize) {
case 0: hashSize = 16; break;
case 1: hashSize = 20; break;
case 2: hashSize = 24; break;
case 3: hashSize = 28; break;
case 4: hashSize = 32; break;
case 5: hashSize = 36; break;
case 6: hashSize = 48; break;
case 7: hashSize = 64; break;
}
auto config = Config::GetDefaultConfig();
config->SetKey(key);
config->SetSalt(salt);
config->SetPersonalization(personalization);
config->SetHashSize(hashSize);
IHash hashFunction = hash.m_factoryFunction(config, nullptr);
hashFunction->Initialize();
return hashProviderRegionWithHashLib(region, provider, hashFunction);
});
}
[[nodiscard]] nlohmann::json store() const override {
nlohmann::json result;
result["salt"] = m_salt;
result["key"] = m_key;
result["personalization"] = m_personalization;
result["size"] = m_hashSize;
return result;
}
void load(const nlohmann::json &data) override {
try {
m_hashSize = data.at("size").get<int>();
m_salt = data.at("salt").get<std::string>();
m_key = data.at("key").get<std::string>();
m_personalization = data.at("personalization").get<std::string>();
} catch (std::exception&) { }
}
private:
FactoryFunction m_factoryFunction;
std::string m_salt, m_key, m_personalization;
int m_hashSize = 0;
};
class HashSum : public ContentRegistry::Hashes::Hash {
public:
HashSum() : Hash("hex.hashes.hash.sum") {}
Function create(std::string name) override {
return Hash::create(name, [hash = *this](const Region& region, prv::Provider *provider) -> std::vector<u8> {
std::array<u8, 8> result = { 0x00 };
auto reader = prv::ProviderReader(provider);
reader.seek(region.getStartAddress());
reader.setEndAddress(region.getEndAddress());
u64 sum = hash.m_initialValue;
u8 progress = 0;
for (u8 byte : reader) {
sum += (byte << (8 * progress));
progress += 1;
progress = progress % hash.m_inputSize;
}
u64 foldedSum = sum;
if (hash.m_foldOutput) {
while (foldedSum >= (1LLU << (hash.m_outputSize * 8))) {
u64 partialSum = 0;
for (size_t i = 0; i < sizeof(u64); i += hash.m_inputSize) {
u64 value = 0;
std::memcpy(&value, reinterpret_cast<const u8*>(&foldedSum) + i, hash.m_inputSize);
partialSum += value;
}
foldedSum = partialSum;
}
}
std::memcpy(result.data(), &foldedSum, hash.m_outputSize);
return { result.begin(), result.begin() + hash.m_outputSize };
});
}
void draw() override {
ImGuiExt::InputHexadecimal("hex.hashes.hash.common.iv"_lang, &m_initialValue);
ImGui::SliderInt("hex.hashes.hash.common.input_size"_lang, &m_inputSize, 1, 8, "%d", ImGuiSliderFlags_AlwaysClamp);
ImGui::SliderInt("hex.hashes.hash.common.output_size"_lang, &m_outputSize, 1, 8, "%d", ImGuiSliderFlags_AlwaysClamp);
ImGui::Checkbox("hex.hashes.hash.sum.fold"_lang, &m_foldOutput);
}
[[nodiscard]] nlohmann::json store() const override {
nlohmann::json result;
result["iv"] = m_initialValue;
result["size"] = m_outputSize;
return result;
}
void load(const nlohmann::json &data) override {
try {
m_initialValue = data.at("iv").get<int>();
m_outputSize = data.at("size").get<int>();
} catch (std::exception&) { }
}
private:
u64 m_initialValue = 0x00;
int m_inputSize = 1;
int m_outputSize = 1;
bool m_foldOutput = false;
};
class HashSnefru : public ContentRegistry::Hashes::Hash {
public:
using FactoryFunction = IHash(*)(Int32 a_security_level, const HashSize &a_hash_size);
explicit HashSnefru(FactoryFunction function) : Hash("Snefru"), m_factoryFunction(function) {}
void draw() override {
ImGui::SliderInt("hex.hashes.hash.common.security_level"_lang, &m_securityLevel, 1, 1024);
ImGui::Combo("hex.hashes.hash.common.size"_lang, &m_hashSize, "128 Bits\0" "256 Bits\0");
}
Function create(std::string name) override {
return Hash::create(name, [hash = *this](const Region& region, prv::Provider *provider) -> std::vector<u8> {
u32 hashSize = 16;
switch (hash.m_hashSize) {
case 0: hashSize = 16; break;
case 1: hashSize = 32; break;
}
IHash hashFunction = hash.m_factoryFunction(hash.m_securityLevel, HashSize(hashSize));
hashFunction->Initialize();
return hashProviderRegionWithHashLib(region, provider, hashFunction);
});
}
[[nodiscard]] nlohmann::json store() const override {
nlohmann::json result;
result["securityLevel"] = m_securityLevel;
result["size"] = m_hashSize;
return result;
}
void load(const nlohmann::json &data) override {
try {
m_securityLevel = data.at("securityLevel").get<int>();
m_hashSize = data.at("size").get<int>();
} catch (std::exception&) { }
}
private:
FactoryFunction m_factoryFunction;
int m_securityLevel = 8;
int m_hashSize = 0;
};
class HashHaval : public ContentRegistry::Hashes::Hash {
public:
using FactoryFunction = IHash(*)(const HashRounds& a_rounds, const HashSize& a_hash_size);
explicit HashHaval(FactoryFunction function) : Hash("Haval"), m_factoryFunction(function) {}
void draw() override {
ImGui::Combo("hex.hashes.hash.common.rounds"_lang, &m_hashRounds, "3 Rounds\0" "4 Rounds\0" "5 Rounds\0");
ImGui::Combo("hex.hashes.hash.common.size"_lang, &m_hashSize, "128 Bits\0" "160 Bits\0" "192 Bits\0" "224 Bits\0" "256 Bits\0");
}
Function create(std::string name) override {
return Hash::create(name, [hash = *this](const Region& region, prv::Provider *provider) -> std::vector<u8> {
u32 hashSize = 16;
switch (hash.m_hashSize) {
case 0: hashSize = 16; break;
case 1: hashSize = 32; break;
}
u32 hashRounds = 3;
switch (hash.m_hashRounds) {
case 0: hashRounds = 3; break;
case 1: hashRounds = 4; break;
case 2: hashRounds = 5; break;
}
IHash hashFunction = hash.m_factoryFunction(HashRounds(hashRounds), HashSize(hashSize));
hashFunction->Initialize();
return hashProviderRegionWithHashLib(region, provider, hashFunction);
});
}
[[nodiscard]] nlohmann::json store() const override {
nlohmann::json result;
result["rounds"] = m_hashRounds;
result["size"] = m_hashSize;
return result;
}
void load(const nlohmann::json &data) override {
try {
m_hashRounds = data.at("rounds").get<int>();
m_hashSize = data.at("size").get<int>();
} catch (std::exception&) { }
}
private:
FactoryFunction m_factoryFunction;
int m_hashRounds = 0;
int m_hashSize = 0;
};
void registerHashes() {
ContentRegistry::Hashes::add<HashSum>();
ContentRegistry::Hashes::add<HashCRC>();
ContentRegistry::Hashes::add<HashBasic>(HashFactory::Checksum::CreateAdler32);
ContentRegistry::Hashes::add<HashBasic>(HashFactory::Crypto::CreateMD2);
ContentRegistry::Hashes::add<HashBasic>(HashFactory::Crypto::CreateMD4);
ContentRegistry::Hashes::add<HashBasic>(HashFactory::Crypto::CreateMD5);
ContentRegistry::Hashes::add<HashBasic>(HashFactory::Crypto::CreateSHA0);
ContentRegistry::Hashes::add<HashBasic>(HashFactory::Crypto::CreateSHA1);
ContentRegistry::Hashes::add<HashBasic>(HashFactory::Crypto::CreateSHA2_224);
ContentRegistry::Hashes::add<HashBasic>(HashFactory::Crypto::CreateSHA2_256);
ContentRegistry::Hashes::add<HashBasic>(HashFactory::Crypto::CreateSHA2_384);
ContentRegistry::Hashes::add<HashBasic>(HashFactory::Crypto::CreateSHA2_512);
ContentRegistry::Hashes::add<HashBasic>(HashFactory::Crypto::CreateSHA2_512_224);
ContentRegistry::Hashes::add<HashBasic>(HashFactory::Crypto::CreateSHA2_512_256);
ContentRegistry::Hashes::add<HashBasic>(HashFactory::Crypto::CreateSHA3_224);
ContentRegistry::Hashes::add<HashBasic>(HashFactory::Crypto::CreateSHA3_256);
ContentRegistry::Hashes::add<HashBasic>(HashFactory::Crypto::CreateSHA3_384);
ContentRegistry::Hashes::add<HashBasic>(HashFactory::Crypto::CreateSHA3_512);
ContentRegistry::Hashes::add<HashBasic>(HashFactory::Crypto::CreateKeccak_224);
ContentRegistry::Hashes::add<HashBasic>(HashFactory::Crypto::CreateKeccak_256);
ContentRegistry::Hashes::add<HashBasic>(HashFactory::Crypto::CreateKeccak_288);
ContentRegistry::Hashes::add<HashBasic>(HashFactory::Crypto::CreateKeccak_384);
ContentRegistry::Hashes::add<HashBasic>(HashFactory::Crypto::CreateKeccak_512);
ContentRegistry::Hashes::add<HashBasic>(HashFactory::Crypto::CreateGrindahl256);
ContentRegistry::Hashes::add<HashBasic>(HashFactory::Crypto::CreateGrindahl512);
ContentRegistry::Hashes::add<HashBasic>(HashFactory::Crypto::CreatePanama);
ContentRegistry::Hashes::add<HashBasic>(HashFactory::Crypto::CreateWhirlPool);
ContentRegistry::Hashes::add<HashBasic>(HashFactory::Crypto::CreateRadioGatun32);
ContentRegistry::Hashes::add<HashBasic>(HashFactory::Crypto::CreateRadioGatun64);
ContentRegistry::Hashes::add<HashBasic>(HashFactory::Crypto::CreateGost);
ContentRegistry::Hashes::add<HashBasic>(HashFactory::Crypto::CreateGOST3411_2012_256);
ContentRegistry::Hashes::add<HashBasic>(HashFactory::Crypto::CreateGOST3411_2012_512);
ContentRegistry::Hashes::add<HashBasic>(HashFactory::Crypto::CreateHAS160);
ContentRegistry::Hashes::add<HashBasic>(HashFactory::Crypto::CreateRIPEMD);
ContentRegistry::Hashes::add<HashBasic>(HashFactory::Crypto::CreateRIPEMD128);
ContentRegistry::Hashes::add<HashBasic>(HashFactory::Crypto::CreateRIPEMD160);
ContentRegistry::Hashes::add<HashBasic>(HashFactory::Crypto::CreateRIPEMD256);
ContentRegistry::Hashes::add<HashBasic>(HashFactory::Crypto::CreateRIPEMD320);
ContentRegistry::Hashes::add<HashSnefru>(HashFactory::Crypto::CreateSnefru);
ContentRegistry::Hashes::add<HashHaval>(HashFactory::Crypto::CreateHaval);
ContentRegistry::Hashes::add<HashTiger>("Tiger", HashFactory::Crypto::CreateTiger);
ContentRegistry::Hashes::add<HashTiger>("Tiger2", HashFactory::Crypto::CreateTiger2);
ContentRegistry::Hashes::add<HashBlake2<Blake2BConfig, IBlake2BConfig, IBlake2BTreeConfig>>("Blake2b", HashFactory::Crypto::CreateBlake2B);
ContentRegistry::Hashes::add<HashBlake2<Blake2SConfig, IBlake2SConfig, IBlake2STreeConfig>>("Blake2s", HashFactory::Crypto::CreateBlake2S);
ContentRegistry::Hashes::add<HashBasic>(HashFactory::Hash32::CreateAP);
ContentRegistry::Hashes::add<HashBasic>(HashFactory::Hash32::CreateBKDR);
ContentRegistry::Hashes::add<HashBasic>(HashFactory::Hash32::CreateBernstein);
ContentRegistry::Hashes::add<HashBasic>(HashFactory::Hash32::CreateBernstein1);
ContentRegistry::Hashes::add<HashBasic>(HashFactory::Hash32::CreateDEK);
ContentRegistry::Hashes::add<HashBasic>(HashFactory::Hash32::CreateDJB);
ContentRegistry::Hashes::add<HashBasic>(HashFactory::Hash32::CreateELF);
ContentRegistry::Hashes::add<HashBasic>(HashFactory::Hash32::CreateFNV1a_32);
ContentRegistry::Hashes::add<HashBasic>(HashFactory::Hash32::CreateFNV32);
ContentRegistry::Hashes::add<HashBasic>(HashFactory::Hash32::CreateJS);
ContentRegistry::Hashes::add<HashBasic>(HashFactory::Hash32::CreateOneAtTime);
ContentRegistry::Hashes::add<HashBasic>(HashFactory::Hash32::CreatePJW);
ContentRegistry::Hashes::add<HashBasic>(HashFactory::Hash32::CreateRotating);
ContentRegistry::Hashes::add<HashBasic>(HashFactory::Hash32::CreateRS);
ContentRegistry::Hashes::add<HashBasic>(HashFactory::Hash32::CreateSDBM);
ContentRegistry::Hashes::add<HashBasic>(HashFactory::Hash32::CreateShiftAndXor);
ContentRegistry::Hashes::add<HashBasic>(HashFactory::Hash32::CreateSuperFast);
ContentRegistry::Hashes::add<HashWithKey>(HashFactory::Hash32::CreateMurmur2_32);
ContentRegistry::Hashes::add<HashWithKey>(HashFactory::Hash32::CreateMurmurHash3_x86_32);
ContentRegistry::Hashes::add<HashWithKey>(HashFactory::Hash32::CreateXXHash32);
ContentRegistry::Hashes::add<HashInitialValue>(HashFactory::Hash32::CreateJenkins3);
ContentRegistry::Hashes::add<HashBasic>(HashFactory::Hash64::CreateFNV64);
ContentRegistry::Hashes::add<HashBasic>(HashFactory::Hash64::CreateFNV1a_64);
ContentRegistry::Hashes::add<HashWithKey>(HashFactory::Hash64::CreateMurmur2_64);
ContentRegistry::Hashes::add<HashWithKey>(HashFactory::Hash64::CreateSipHash64_2_4);
ContentRegistry::Hashes::add<HashWithKey>(HashFactory::Hash64::CreateXXHash64);
ContentRegistry::Hashes::add<HashWithKey>(HashFactory::Hash128::CreateSipHash128_2_4);
ContentRegistry::Hashes::add<HashWithKey>(HashFactory::Hash128::CreateMurmurHash3_x86_128);
ContentRegistry::Hashes::add<HashWithKey>(HashFactory::Hash128::CreateMurmurHash3_x64_128);
}
}
| 30,194
|
C++
|
.cpp
| 555
| 42.322523
| 251
| 0.606055
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
270
|
view_hashes.cpp
|
WerWolv_ImHex/plugins/hashes/source/content/views/view_hashes.cpp
|
#include "content/views/view_hashes.hpp"
#include <hex/api/project_file_manager.hpp>
#include <hex/api/achievement_manager.hpp>
#include <hex/providers/memory_provider.hpp>
#include <hex/helpers/crypto.hpp>
#include <hex/ui/popup.hpp>
#include <fonts/codicons_font.h>
#include <vector>
namespace hex::plugin::hashes {
class PopupTextHash : public Popup<PopupTextHash> {
public:
explicit PopupTextHash(const ContentRegistry::Hashes::Hash::Function &hash)
: hex::Popup<PopupTextHash>(hash.getName(), true, false),
m_hash(hash) { }
void drawContent() override {
ImGuiExt::Header(this->getUnlocalizedName(), true);
ImGui::PushItemWidth(-1);
if (ImGui::InputTextMultiline("##input", m_input)) {
prv::MemoryProvider provider({ m_input.begin(), m_input.end() });
m_hash.reset();
auto bytes = m_hash.get(Region { 0x00, provider.getActualSize() }, &provider);
m_result = crypt::encode16(bytes);
}
ImGui::NewLine();
ImGui::InputText("##result", m_result, ImGuiInputTextFlags_ReadOnly);
ImGui::PopItemWidth();
if (ImGui::IsKeyPressed(ImGuiKey_Escape))
this->close();
}
[[nodiscard]] ImGuiWindowFlags getFlags() const override {
return ImGuiWindowFlags_AlwaysAutoResize;
}
ImVec2 getMinSize() const override {
return scaled({ 400, 200 });
}
ImVec2 getMaxSize() const override { return this->getMinSize(); }
private:
std::string m_input;
std::string m_result;
ContentRegistry::Hashes::Hash::Function m_hash;
};
ViewHashes::ViewHashes() : View::Window("hex.hashes.view.hashes.name", ICON_VS_KEY) {
EventRegionSelected::subscribe(this, [this](const auto &providerRegion) {
for (auto &function : m_hashFunctions.get(providerRegion.getProvider()))
function.reset();
});
ImHexApi::HexEditor::addTooltipProvider([this](u64 address, const u8 *data, size_t size) {
hex::unused(data);
auto selection = ImHexApi::HexEditor::getSelection();
if (selection.has_value() && ImGui::GetIO().KeyShift) {
auto &hashFunctions = m_hashFunctions.get(selection->getProvider());
if (!hashFunctions.empty() && selection.has_value() && selection->overlaps(Region { address, size })) {
ImGui::BeginTooltip();
if (ImGui::BeginTable("##tooltips", 1, ImGuiTableFlags_NoHostExtendX | ImGuiTableFlags_RowBg | ImGuiTableFlags_NoClip, ImMax(ImGui::GetContentRegionAvail(), ImVec2(0, ImGui::GetTextLineHeightWithSpacing() * 5)))) {
ImGui::TableNextRow();
ImGui::TableNextColumn();
ImGui::TextUnformatted("hex.hashes.view.hashes.name"_lang);
ImGui::Separator();
ImGui::Indent();
if (ImGui::BeginTable("##hashes_tooltip", 3, ImGuiTableFlags_NoHostExtendX | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingFixedFit)) {
auto provider = ImHexApi::Provider::get();
for (auto &function : hashFunctions) {
if (provider == nullptr)
continue;
std::vector<u8> bytes;
try {
bytes = function.get(*selection, provider);
} catch (const std::exception &) {
continue;
}
ImGui::TableNextRow();
ImGui::TableNextColumn();
ImGuiExt::TextFormatted("{}", function.getName());
ImGui::TableNextColumn();
ImGuiExt::TextFormatted(" ");
ImGui::TableNextColumn();
ImGuiExt::TextFormatted("{}", crypt::encode16(bytes));
}
ImGui::EndTable();
}
ImGui::Unindent();
ImGui::EndTable();
}
ImGui::EndTooltip();
}
}
});
ProjectFile::registerPerProviderHandler({
.basePath = "hashes.json",
.required = false,
.load = [this](prv::Provider *provider, const std::fs::path &basePath, const Tar &tar) -> bool {
auto fileContent = tar.readString(basePath);
if (fileContent.empty())
return true;
auto data = nlohmann::json::parse(fileContent.begin(), fileContent.end());
m_hashFunctions->clear();
return this->importHashes(provider, data);
},
.store = [this](prv::Provider *provider, const std::fs::path &basePath, const Tar &tar) -> bool {
nlohmann::json data;
bool result = this->exportHashes(provider, data);
tar.writeString(basePath, data.dump(4));
return result;
}
});
}
ViewHashes::~ViewHashes() {
EventRegionSelected::unsubscribe(this);
}
void ViewHashes::drawContent() {
const auto &hashes = ContentRegistry::Hashes::impl::getHashes();
if (m_selectedHash == nullptr && !hashes.empty()) {
m_selectedHash = hashes.front().get();
}
if (ImGui::BeginCombo("hex.hashes.view.hashes.function"_lang, m_selectedHash != nullptr ? Lang(m_selectedHash->getUnlocalizedName()) : "")) {
for (const auto &hash : hashes) {
if (ImGui::Selectable(Lang(hash->getUnlocalizedName()), m_selectedHash == hash.get())) {
m_selectedHash = hash.get();
m_newHashName.clear();
}
}
ImGui::EndCombo();
}
if (m_newHashName.empty() && m_selectedHash != nullptr)
m_newHashName = hex::format("{} {}", Lang(m_selectedHash->getUnlocalizedName()), static_cast<const char *>("hex.hashes.view.hashes.hash"_lang));
if (ImGui::BeginChild("##settings", ImVec2(ImGui::GetContentRegionAvail().x, 200_scaled), true)) {
if (m_selectedHash != nullptr) {
auto startPos = ImGui::GetCursorPosY();
m_selectedHash->draw();
// Check if no elements have been added
if (startPos == ImGui::GetCursorPosY()) {
ImGuiExt::TextFormattedCentered("hex.hashes.view.hashes.no_settings"_lang);
}
}
}
ImGui::EndChild();
ImGuiExt::InputTextIcon("##hash_name", ICON_VS_SYMBOL_KEY, m_newHashName);
ImGui::SameLine();
ImGui::BeginDisabled(m_newHashName.empty() || m_selectedHash == nullptr);
if (ImGuiExt::IconButton(ICON_VS_ADD, ImGui::GetStyleColorVec4(ImGuiCol_Text))) {
if (m_selectedHash != nullptr) {
m_hashFunctions->push_back(m_selectedHash->create(m_newHashName));
AchievementManager::unlockAchievement("hex.builtin.achievement.misc", "hex.hashes.achievement.misc.create_hash.name");
}
}
ImGui::EndDisabled();
ImGui::SameLine();
ImGuiExt::HelpHover("hex.hashes.view.hashes.hover_info"_lang);
if (ImGui::BeginTable("##hashes", 4, ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_Borders | ImGuiTableFlags_ScrollY)) {
ImGui::TableSetupColumn("hex.hashes.view.hashes.table.name"_lang);
ImGui::TableSetupColumn("hex.hashes.view.hashes.table.type"_lang);
ImGui::TableSetupColumn("hex.hashes.view.hashes.table.result"_lang, ImGuiTableColumnFlags_WidthStretch);
ImGui::TableSetupColumn("##buttons", ImGuiTableColumnFlags_WidthFixed, 50_scaled);
ImGui::TableHeadersRow();
auto provider = ImHexApi::Provider::get();
auto selection = ImHexApi::HexEditor::getSelection();
std::optional<u32> indexToRemove;
for (u32 i = 0; i < m_hashFunctions->size(); i++) {
auto &function = (*m_hashFunctions)[i];
ImGui::PushID(i);
ImGui::TableNextRow();
ImGui::TableNextColumn();
ImGui::PushStyleColor(ImGuiCol_Header, 0x00);
ImGui::PushStyleColor(ImGuiCol_HeaderActive, 0x00);
ImGui::PushStyleColor(ImGuiCol_HeaderHovered, 0x00);
ImGui::Selectable(function.getName().c_str(), false);
ImGui::PopStyleColor(3);
ImGui::TableNextColumn();
ImGuiExt::TextFormatted("{}", Lang(function.getType()->getUnlocalizedName()));
ImGui::TableNextColumn();
std::string result;
if (provider != nullptr && selection.has_value()) {
try {
result = crypt::encode16(function.get(*selection, provider));
} catch (const std::exception &e) {
result = e.what();
}
}
else
result = "???";
ImGui::PushItemWidth(-1);
ImGui::InputText("##result", result, ImGuiInputTextFlags_ReadOnly);
ImGui::PopItemWidth();
ImGui::TableNextColumn();
if (ImGuiExt::IconButton(ICON_VS_OPEN_PREVIEW, ImGui::GetStyleColorVec4(ImGuiCol_Text))) {
PopupTextHash::open(function);
}
ImGui::SameLine();
if (ImGuiExt::IconButton(ICON_VS_X, ImGuiExt::GetCustomColorVec4(ImGuiCustomCol_ToolbarRed))) {
indexToRemove = i;
}
ImGui::PopID();
}
if (indexToRemove.has_value()) {
m_hashFunctions->erase(m_hashFunctions->begin() + indexToRemove.value());
}
ImGui::EndTable();
}
}
bool ViewHashes::importHashes(prv::Provider *provider, const nlohmann::json &json) {
if (!json.contains("hashes"))
return false;
const auto &hashes = ContentRegistry::Hashes::impl::getHashes();
for (const auto &hash : json["hashes"]) {
if (!hash.contains("name") || !hash.contains("type") || !hash.contains("settings"))
continue;
for (const auto &newHash : hashes) {
if (newHash->getUnlocalizedName() == hash["type"].get<std::string>()) {
auto newFunction = newHash->create(hash["name"]);
newFunction.getType()->load(hash["settings"]);
m_hashFunctions.get(provider).push_back(std::move(newFunction));
break;
}
}
}
return true;
}
bool ViewHashes::exportHashes(prv::Provider *provider, nlohmann::json &json) {
json["hashes"] = nlohmann::json::array();
size_t index = 0;
for (const auto &hashFunction : m_hashFunctions.get(provider)) {
json["hashes"][index] = {
{ "name", hashFunction.getName() },
{ "type", hashFunction.getType()->getUnlocalizedName() },
{ "settings", hashFunction.getType()->store() }
};
index++;
}
return true;
}
}
| 11,837
|
C++
|
.cpp
| 231
| 35.78355
| 234
| 0.538241
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
271
|
plugin_windows.cpp
|
WerWolv_ImHex/plugins/windows/source/plugin_windows.cpp
|
#include <hex/plugin.hpp>
#include <hex/api/content_registry.hpp>
#include <hex/api/theme_manager.hpp>
#include <hex/helpers/logger.hpp>
#include <romfs/romfs.hpp>
#include <nlohmann/json.hpp>
#include "views/view_tty_console.hpp"
#include <windows.h>
using namespace hex;
namespace hex::plugin::windows {
void addFooterItems();
void addTitleBarButtons();
void registerSettings();
}
static void detectSystemTheme() {
// Setup system theme change detector
EventOSThemeChanged::subscribe([] {
bool themeFollowSystem = ContentRegistry::Settings::read<std::string>("hex.builtin.setting.interface", "hex.builtin.setting.interface.color", ThemeManager::NativeTheme) == ThemeManager::NativeTheme;
if (!themeFollowSystem)
return;
HKEY hkey;
if (RegOpenKeyW(HKEY_CURRENT_USER, LR"(Software\Microsoft\Windows\CurrentVersion\Themes\Personalize)", &hkey) == ERROR_SUCCESS) {
DWORD value = 0;
DWORD size = sizeof(DWORD);
auto error = RegQueryValueExW(hkey, L"AppsUseLightTheme", nullptr, nullptr, reinterpret_cast<LPBYTE>(&value), &size);
if (error == ERROR_SUCCESS) {
RequestChangeTheme::post(value == 0 ? "Dark" : "Light");
}
}
});
EventWindowInitialized::subscribe([=] {
bool themeFollowSystem = ContentRegistry::Settings::read<std::string>("hex.builtin.setting.interface", "hex.builtin.setting.interface.color", ThemeManager::NativeTheme) == ThemeManager::NativeTheme;
if (themeFollowSystem)
EventOSThemeChanged::post();
});
}
IMHEX_PLUGIN_SETUP("Windows", "WerWolv", "Windows-only features") {
using namespace hex::plugin::windows;
hex::log::debug("Using romfs: '{}'", romfs::name());
for (auto &path : romfs::list("lang"))
hex::ContentRegistry::Language::addLocalization(nlohmann::json::parse(romfs::get(path).string()));
hex::ContentRegistry::Views::add<ViewTTYConsole>();
addFooterItems();
registerSettings();
detectSystemTheme();
}
| 2,070
|
C++
|
.cpp
| 46
| 38.76087
| 206
| 0.686597
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
272
|
view_tty_console.cpp
|
WerWolv_ImHex/plugins/windows/source/views/view_tty_console.cpp
|
#include "views/view_tty_console.hpp"
#include <imgui_internal.h>
#include <hex/api/task_manager.hpp>
#include <hex/helpers/utils.hpp>
#include <toasts/toast_notification.hpp>
#include <wolv/utils/guards.hpp>
#include <windows.h>
namespace hex::plugin::windows {
ViewTTYConsole::ViewTTYConsole() : View::Window("hex.windows.view.tty_console.name", ICON_VS_TERMINAL) {
m_comPorts = getAvailablePorts();
m_transmitDataBuffer.resize(0xFFF, 0x00);
m_receiveDataBuffer.reserve(0xFFF);
m_receiveDataBuffer.push_back(0x00);
}
void ViewTTYConsole::drawContent() {
ImGuiExt::Header("hex.windows.view.tty_console.config"_lang, true);
bool connected = m_portHandle != INVALID_HANDLE_VALUE;
ImGui::PushItemFlag(ImGuiItemFlags_Disabled, connected);
ImGui::PushStyleVar(ImGuiStyleVar_Alpha, connected ? 0.5F : 1.0F);
ImGui::Combo(
"hex.windows.view.tty_console.port"_lang, &m_selectedPort, [](void *data, int idx) {
auto &ports = *static_cast<std::vector<std::pair<std::string, std::string>> *>(data);
return ports[idx].first.c_str();
},
&m_comPorts,
m_comPorts.size());
ImGui::SameLine();
if (ImGui::Button("hex.windows.view.tty_console.reload"_lang))
m_comPorts = getAvailablePorts();
ImGui::Combo(
"hex.windows.view.tty_console.baud"_lang, &m_selectedBaudRate, [](void *data, int idx) {
hex::unused(data);
return ViewTTYConsole::BaudRates[idx];
},
nullptr,
ViewTTYConsole::BaudRates.size());
ImGui::Combo(
"hex.windows.view.tty_console.num_bits"_lang, &m_selectedNumBits, [](void *data, int idx) {
hex::unused(data);
return ViewTTYConsole::NumBits[idx];
},
nullptr,
ViewTTYConsole::NumBits.size());
ImGui::Combo(
"hex.windows.view.tty_console.stop_bits"_lang, &m_selectedStopBits, [](void *data, int idx) {
hex::unused(data);
return ViewTTYConsole::StopBits[idx];
},
nullptr,
ViewTTYConsole::StopBits.size());
ImGui::Combo(
"hex.windows.view.tty_console.parity_bits"_lang, &m_selectedParityBits, [](void *data, int idx) {
hex::unused(data);
return ViewTTYConsole::ParityBits[idx];
},
nullptr,
ViewTTYConsole::ParityBits.size());
ImGui::Checkbox("hex.windows.view.tty_console.cts"_lang, &m_hasCTSFlowControl);
ImGui::PopStyleVar();
ImGui::PopItemFlag();
ImGui::NewLine();
if (m_portHandle == INVALID_HANDLE_VALUE) {
if (ImGui::Button("hex.windows.view.tty_console.connect"_lang))
if (!this->connect())
ui::ToastError::open("hex.windows.view.tty_console.connect_error"_lang);
} else {
if (ImGui::Button("hex.windows.view.tty_console.disconnect"_lang))
this->disconnect();
}
ImGui::NewLine();
if (ImGui::Button("hex.windows.view.tty_console.clear"_lang)) {
std::scoped_lock lock(m_receiveBufferMutex);
m_receiveDataBuffer.clear();
m_wrapPositions.clear();
}
ImGui::SameLine();
ImGui::Checkbox("hex.windows.view.tty_console.auto_scroll"_lang, &m_shouldAutoScroll);
ImGuiExt::Header("hex.windows.view.tty_console.console"_lang);
auto consoleSize = ImMax(ImGui::GetContentRegionAvail(), ImVec2(0, ImGui::GetTextLineHeightWithSpacing() * 5));
consoleSize.y -= ImGui::GetTextLineHeight() + ImGui::GetStyle().FramePadding.y * 4;
if (ImGui::BeginChild("##scrolling", consoleSize, true, ImGuiWindowFlags_HorizontalScrollbar)) {
ImGuiListClipper clipper;
clipper.Begin(m_wrapPositions.size(), ImGui::GetTextLineHeight());
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(4, 1));
while (clipper.Step()) {
std::scoped_lock lock(m_receiveBufferMutex);
for (int i = clipper.DisplayStart + 1; i < clipper.DisplayEnd; i++) {
ImGui::TextUnformatted(m_receiveDataBuffer.data() + m_wrapPositions[i - 1], m_receiveDataBuffer.data() + m_wrapPositions[i]);
}
if (!m_receiveDataBuffer.empty() && !m_wrapPositions.empty())
if (static_cast<size_t>(clipper.DisplayEnd) >= m_wrapPositions.size() - 1)
ImGui::TextUnformatted(m_receiveDataBuffer.data() + m_wrapPositions.back());
if (m_shouldAutoScroll && ImGui::GetScrollY() >= ImGui::GetScrollMaxY()) {
ImGui::SetScrollHereY(0.0F);
}
}
ImGui::PopStyleVar();
}
ImGui::EndChild();
ImGui::PushItemWidth(-1);
if (ImGui::InputText("##transmit", m_transmitDataBuffer.data(), m_transmitDataBuffer.size() - 2, ImGuiInputTextFlags_EnterReturnsTrue)) {
auto size = strlen(m_transmitDataBuffer.data());
m_transmitDataBuffer[size + 0] = '\n';
m_transmitDataBuffer[size + 1] = 0x00;
this->transmitData(m_transmitDataBuffer);
ImGui::SetKeyboardFocusHere(0);
}
ImGui::PopItemWidth();
if (ImGui::IsMouseDown(ImGuiMouseButton_Right) && ImGui::IsItemHovered() && m_portHandle != INVALID_HANDLE_VALUE && !m_transmitting)
ImGui::OpenPopup("ConsoleMenu");
if (ImGui::BeginPopup("ConsoleMenu")) {
static std::vector<char> buffer(2, 0x00);
if (ImGui::MenuItem("hex.windows.view.tty_console.send_etx"_lang, "CTRL + C")) {
buffer[0] = 0x03;
this->transmitData(buffer);
}
if (ImGui::MenuItem("hex.windows.view.tty_console.send_eot"_lang, "CTRL + D")) {
buffer[0] = 0x04;
this->transmitData(buffer);
}
if (ImGui::MenuItem("hex.windows.view.tty_console.send_sub"_lang, "CTRL + Z")) {
buffer[0] = 0x1A;
this->transmitData(buffer);
}
ImGui::EndPopup();
}
}
std::vector<std::pair<std::wstring, std::wstring>> ViewTTYConsole::getAvailablePorts() const {
std::vector<std::pair<std::wstring, std::wstring>> result;
std::vector<wchar_t> buffer(0xFFF, 0x00);
for (u16 portNumber = 0; portNumber <= 255; portNumber++) {
std::wstring port = L"COM" + std::to_wstring(portNumber);
if (::QueryDosDeviceW(port.c_str(), buffer.data(), buffer.size()) != 0) {
result.emplace_back(port, buffer.data());
}
}
return result;
}
bool ViewTTYConsole::connect() {
if (m_comPorts.empty() || static_cast<size_t>(m_selectedPort) >= m_comPorts.size()) {
ui::ToastError::open("hex.windows.view.tty_console.no_available_port"_lang);
return true; // If false, connect_error error popup will override this error popup
}
m_portHandle = ::CreateFileW((LR"(\\.\)" + m_comPorts[m_selectedPort].first).c_str(),
GENERIC_READ | GENERIC_WRITE,
0,
nullptr,
OPEN_EXISTING,
FILE_FLAG_OVERLAPPED,
nullptr);
if (m_portHandle == INVALID_HANDLE_VALUE)
return false;
auto closeHandle = SCOPE_GUARD { CloseHandle(m_portHandle); };
if (!::SetupComm(m_portHandle, 10000, 10000))
return false;
DCB serialParams;
serialParams.DCBlength = sizeof(DCB);
if (!::GetCommState(m_portHandle, &serialParams))
return false;
serialParams.BaudRate = std::stoi(ViewTTYConsole::BaudRates[m_selectedBaudRate]);
serialParams.ByteSize = std::stoi(ViewTTYConsole::NumBits[m_selectedNumBits]);
serialParams.StopBits = m_selectedStopBits;
serialParams.Parity = m_selectedParityBits;
serialParams.fOutxCtsFlow = m_hasCTSFlowControl;
if (!::SetCommState(m_portHandle, &serialParams))
return false;
COMMTIMEOUTS timeouts;
timeouts.ReadIntervalTimeout = 500;
timeouts.ReadTotalTimeoutConstant = 500;
timeouts.ReadTotalTimeoutMultiplier = 100;
timeouts.WriteTotalTimeoutConstant = 500;
timeouts.WriteTotalTimeoutMultiplier = 100;
if (!::SetCommTimeouts(m_portHandle, &timeouts))
return false;
closeHandle.release();
m_receiveThread = std::jthread([this](const std::stop_token &token) {
bool waitingOnRead = false;
OVERLAPPED overlapped = { };
overlapped.hEvent = ::CreateEvent(nullptr, true, false, nullptr);
ON_SCOPE_EXIT { ::CloseHandle(&overlapped); };
auto addByte = [this](char byte) {
std::scoped_lock lock(m_receiveBufferMutex);
if (byte >= 0x20 && byte <= 0x7E) {
m_receiveDataBuffer.back() = byte;
m_receiveDataBuffer.push_back(0x00);
} else if (byte == '\n' || byte == '\r') {
if (m_receiveDataBuffer.empty())
return;
u32 wrapPos = m_receiveDataBuffer.size() - 1;
if (m_wrapPositions.empty() || m_wrapPositions.back() != wrapPos)
m_wrapPositions.push_back(wrapPos);
}
};
while (!token.stop_requested()) {
DWORD bytesRead = 0;
char byte = 0;
if (!waitingOnRead) {
if (::ReadFile(m_portHandle, &byte, sizeof(char), &bytesRead, &overlapped)) {
addByte(byte);
} else if (::GetLastError() == ERROR_IO_PENDING) {
waitingOnRead = true;
}
} else {
byte = 0;
switch (::WaitForSingleObject(overlapped.hEvent, 500)) {
case WAIT_OBJECT_0:
if (::GetOverlappedResult(m_portHandle, &overlapped, &bytesRead, false)) {
addByte(byte);
waitingOnRead = false;
}
default:
break;
}
}
}
});
return true;
}
bool ViewTTYConsole::disconnect() {
::SetCommMask(m_portHandle, EV_TXEMPTY);
m_receiveThread.request_stop();
m_receiveThread.join();
::CloseHandle(m_portHandle);
m_portHandle = INVALID_HANDLE_VALUE;
return true;
}
void ViewTTYConsole::transmitData(std::vector<char> &data) {
if (m_transmitting)
return;
TaskManager::createBackgroundTask("hex.windows.view.tty_console.task.transmitting"_lang, [&, this](auto&) {
OVERLAPPED overlapped = { };
overlapped.hEvent = ::CreateEvent(nullptr, true, false, nullptr);
ON_SCOPE_EXIT { ::CloseHandle(&overlapped); };
m_transmitting = true;
DWORD bytesWritten = 0;
if (!::WriteFile(m_portHandle, data.data(), strlen(data.data()), &bytesWritten, &overlapped)) {
if (::GetLastError() == ERROR_IO_PENDING) {
::GetOverlappedResult(m_portHandle, &overlapped, &bytesWritten, true);
}
}
if (bytesWritten > 0)
data[0] = 0x00;
m_transmitting = false;
});
}
}
| 11,882
|
C++
|
.cpp
| 246
| 35.296748
| 145
| 0.563803
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
273
|
settings_entries.cpp
|
WerWolv_ImHex/plugins/windows/source/content/settings_entries.cpp
|
#include <hex/api/content_registry.hpp>
#include <hex/helpers/fmt.hpp>
#include <imgui.h>
#include <nlohmann/json.hpp>
#include <windows.h>
namespace hex::plugin::windows {
namespace {
constexpr auto ImHexContextMenuKey = R"(Software\Classes\*\shell\ImHex)";
void addImHexContextMenuEntry() {
// Create ImHex Root Key
HKEY imHexRootKey;
RegCreateKeyExA(HKEY_CURRENT_USER, ImHexContextMenuKey, 0x00, nullptr, REG_OPTION_NON_VOLATILE, KEY_SET_VALUE, nullptr, &imHexRootKey, nullptr);
RegSetValueA(imHexRootKey, nullptr, REG_SZ, "Open with ImHex", 0x00);
// Add 'Icon' key to use first icon embedded in exe
std::array<char, MAX_PATH> imHexPath = { 0 };
GetModuleFileNameA(nullptr, imHexPath.data(), imHexPath.size());
auto iconValue = hex::format(R"("{}",0)", imHexPath.data());
RegSetKeyValueA(imHexRootKey, nullptr, "Icon", REG_SZ, iconValue.c_str(), iconValue.size() + 1);
// Add 'command' key to pass the right-clicked file path as first argument to ImHex
auto commandValue = hex::format(R"("{}" "%1")", imHexPath.data());
RegSetValueA(imHexRootKey, "command", REG_SZ, commandValue.c_str(), commandValue.size() + 1);
RegCloseKey(imHexRootKey);
}
void removeImHexContextMenuEntry() {
RegDeleteTreeA(HKEY_CURRENT_USER, ImHexContextMenuKey);
}
bool hasImHexContextMenuEntry() {
HKEY key;
bool keyExists = (RegOpenKeyExA(HKEY_CURRENT_USER, ImHexContextMenuKey, 0x00, KEY_SET_VALUE, &key) == ERROR_SUCCESS);
RegCloseKey(key);
return keyExists;
}
}
void registerSettings() {
/* General */
namespace Widgets = ContentRegistry::Settings::Widgets;
ContentRegistry::Settings::add<Widgets::Checkbox>("hex.builtin.setting.general", "", "hex.builtin.setting.general.context_menu_entry", false)
.setChangedCallback([](auto &widget) {
auto checked = static_cast<Widgets::Checkbox &>(widget).isChecked();
if (checked)
addImHexContextMenuEntry();
else
removeImHexContextMenuEntry();
widget.load(hasImHexContextMenuEntry());
});
ContentRegistry::Settings::add<Widgets::Checkbox>("hex.builtin.setting.interface", "hex.builtin.setting.interface.window", "hex.builtin.setting.interface.show_resource_usage", false);
}
}
| 2,600
|
C++
|
.cpp
| 48
| 42.75
| 191
| 0.627172
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
274
|
ui_items.cpp
|
WerWolv_ImHex/plugins/windows/source/content/ui_items.cpp
|
#include <hex/api/content_registry.hpp>
#include <hex/helpers/utils.hpp>
#include <windows.h>
#include <psapi.h>
#include <imgui.h>
#include <fonts/codicons_font.h>
#include <hex/ui/imgui_imhex_extensions.h>
#include <hex/api/event_manager.hpp>
namespace hex::plugin::windows {
void addFooterItems() {
static bool showResourceUsage = true;
ContentRegistry::Settings::onChange("hex.builtin.setting.interface", "hex.builtin.setting.interface.show_resource_usage", [](const ContentRegistry::Settings::SettingsValue &value) {
showResourceUsage = value.get<bool>(false);
});
ContentRegistry::Interface::addFooterItem([] {
if (!showResourceUsage)
return;
static float cpuUsage = 0.0F;
if (ImGuiExt::HasSecondPassed()) {
static ULARGE_INTEGER lastCPU, lastSysCPU, lastUserCPU;
static u32 numProcessors;
static HANDLE self = GetCurrentProcess();
ULARGE_INTEGER now, sys, user;
{
FILETIME ftime, fsys, fuser;
GetSystemTimeAsFileTime(&ftime);
memcpy(&now, &ftime, sizeof(FILETIME));
GetProcessTimes(self, &ftime, &ftime, &fsys, &fuser);
memcpy(&sys, &fsys, sizeof(FILETIME));
memcpy(&user, &fuser, sizeof(FILETIME));
}
if (lastCPU.QuadPart == 0) {
SYSTEM_INFO sysInfo;
FILETIME ftime, fsys, fuser;
GetSystemInfo(&sysInfo);
numProcessors = sysInfo.dwNumberOfProcessors;
GetSystemTimeAsFileTime(&ftime);
memcpy(&lastCPU, &ftime, sizeof(FILETIME));
self = GetCurrentProcess();
GetProcessTimes(self, &ftime, &ftime, &fsys, &fuser);
memcpy(&lastSysCPU, &fsys, sizeof(FILETIME));
memcpy(&lastUserCPU, &fuser, sizeof(FILETIME));
} else {
cpuUsage = (sys.QuadPart - lastSysCPU.QuadPart) +
(user.QuadPart - lastUserCPU.QuadPart);
cpuUsage /= (now.QuadPart - lastCPU.QuadPart);
cpuUsage /= numProcessors;
lastCPU = now;
lastUserCPU = user;
lastSysCPU = sys;
}
cpuUsage *= 100;
}
ImGuiExt::TextFormatted(ICON_VS_DASHBOARD " {0:2}.{1:02}%", u32(cpuUsage), u32(cpuUsage * 100) % 100);
});
ContentRegistry::Interface::addFooterItem([] {
if (!showResourceUsage)
return;
static MEMORYSTATUSEX memInfo;
static PROCESS_MEMORY_COUNTERS_EX pmc;
if (ImGuiExt::HasSecondPassed()) {
memInfo.dwLength = sizeof(MEMORYSTATUSEX);
GlobalMemoryStatusEx(&memInfo);
GetProcessMemoryInfo(GetCurrentProcess(), reinterpret_cast<PROCESS_MEMORY_COUNTERS *>(&pmc), sizeof(pmc));
}
auto totalMem = memInfo.ullTotalPhys;
auto usedMem = pmc.WorkingSetSize;
ImGuiExt::TextFormatted(ICON_VS_CHIP " {0} / {1}", hex::toByteString(usedMem), hex::toByteString(totalMem));
});
}
}
| 3,398
|
C++
|
.cpp
| 71
| 33.225352
| 189
| 0.552392
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
275
|
plugin_diffing.cpp
|
WerWolv_ImHex/plugins/diffing/source/plugin_diffing.cpp
|
#include <hex/plugin.hpp>
#include <hex/api/content_registry.hpp>
#include <hex/helpers/logger.hpp>
#include <romfs/romfs.hpp>
#include "content/views/view_diff.hpp"
namespace hex::plugin::diffing {
void registerDiffingAlgorithms();
}
using namespace hex;
using namespace hex::plugin::diffing;
IMHEX_PLUGIN_SETUP("Diffing", "WerWolv", "Support for diffing data") {
hex::log::debug("Using romfs: '{}'", romfs::name());
for (auto &path : romfs::list("lang"))
hex::ContentRegistry::Language::addLocalization(nlohmann::json::parse(romfs::get(path).string()));
registerDiffingAlgorithms();
ContentRegistry::Views::add<ViewDiff>();
}
| 668
|
C++
|
.cpp
| 17
| 35.941176
| 106
| 0.726135
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
276
|
diffing_algorithms.cpp
|
WerWolv_ImHex/plugins/diffing/source/content/diffing_algorithms.cpp
|
#include <hex.hpp>
#include <hex/api/content_registry.hpp>
#include <hex/providers/buffered_reader.hpp>
#include <wolv/utils/guards.hpp>
#include <wolv/literals.hpp>
#include <edlib.h>
#include <imgui.h>
#include <hex/api/task_manager.hpp>
namespace hex::plugin::diffing {
using namespace ContentRegistry::Diffing;
using namespace wolv::literals;
class AlgorithmSimple : public Algorithm {
public:
AlgorithmSimple() : Algorithm("hex.diffing.algorithm.simple.name", "hex.diffing.algorithm.simple.description") {}
[[nodiscard]] std::vector<DiffTree> analyze(prv::Provider *providerA, prv::Provider *providerB) const override {
wolv::container::IntervalTree<DifferenceType> differences;
// Set up readers for both providers
auto readerA = prv::ProviderReader(providerA);
auto readerB = prv::ProviderReader(providerB);
auto &task = TaskManager::getCurrentTask();
// Iterate over both providers and compare the bytes
for (auto itA = readerA.begin(), itB = readerB.begin(); itA < readerA.end() && itB < readerB.end(); ++itA, ++itB) {
// Stop comparing if the diff task was canceled
if (task.wasInterrupted())
break;
// If the bytes are different, find the end of the difference
if (*itA != *itB) {
u64 start = itA.getAddress();
size_t size = 0;
while (itA != readerA.end() && itB != readerB.end() && *itA != *itB) {
++itA;
++itB;
++size;
}
// Add the difference to the list
differences.emplace({ start, (start + size) - 1 }, DifferenceType::Mismatch);
}
// Update the progress bar
task.update(itA.getAddress());
}
auto otherDifferences = differences;
// If one provider is larger than the other, add the extra bytes to the list
if (providerA->getActualSize() != providerB->getActualSize()) {
auto endA = providerA->getActualSize() + 1;
auto endB = providerB->getActualSize() + 1;
if (endA > endB) {
differences.emplace({ endB, endA }, DifferenceType::Insertion);
otherDifferences.emplace({ endB, endA }, DifferenceType::Deletion);
}
else {
differences.emplace({ endA, endB }, DifferenceType::Insertion);
otherDifferences.emplace({ endB, endA }, DifferenceType::Insertion);
}
}
return { differences, otherDifferences };
}
};
class AlgorithmMyers : public Algorithm {
public:
AlgorithmMyers() : Algorithm("hex.diffing.algorithm.myers.name", "hex.diffing.algorithm.myers.description") {}
[[nodiscard]] std::vector<DiffTree> analyze(prv::Provider *providerA, prv::Provider *providerB) const override {
DiffTree differencesA, differencesB;
EdlibAlignConfig edlibConfig;
edlibConfig.k = -1;
edlibConfig.additionalEqualities = nullptr;
edlibConfig.additionalEqualitiesLength = 0;
edlibConfig.mode = EdlibAlignMode::EDLIB_MODE_NW;
edlibConfig.task = EdlibAlignTask::EDLIB_TASK_PATH;
const auto providerAStart = providerA->getBaseAddress();
const auto providerBStart = providerB->getBaseAddress();
const auto providerAEnd = providerAStart + providerA->getActualSize();
const auto providerBEnd = providerBStart + providerB->getActualSize();
const auto windowStart = std::max(providerAStart, providerBStart);
const auto windowEnd = std::min(providerAEnd, providerBEnd);
auto &task = TaskManager::getCurrentTask();
if (providerAStart > providerBStart) {
differencesA.insert({ providerBStart, providerAStart }, DifferenceType::Deletion);
differencesB.insert({ providerBStart, providerAStart }, DifferenceType::Deletion);
} else if (providerAStart < providerBStart) {
differencesA.insert({ providerAStart, providerBStart }, DifferenceType::Insertion);
differencesB.insert({ providerAStart, providerBStart }, DifferenceType::Insertion);
}
for (u64 address = windowStart; address < windowEnd; address += m_windowSize) {
if (task.wasInterrupted())
break;
auto currWindowSizeA = std::min<u64>(m_windowSize, providerA->getActualSize() - address);
auto currWindowSizeB = std::min<u64>(m_windowSize, providerB->getActualSize() - address);
std::vector<u8> dataA(currWindowSizeA, 0x00), dataB(currWindowSizeB, 0x00);
providerA->read(address, dataA.data(), dataA.size());
providerB->read(address, dataB.data(), dataB.size());
const auto commonSize = std::min(dataA.size(), dataB.size());
EdlibAlignResult result = edlibAlign(
reinterpret_cast<const char*>(dataA.data()), commonSize,
reinterpret_cast<const char*>(dataB.data()), commonSize,
edlibConfig
);
auto currentOperation = DifferenceType(0xFF);
Region regionA = {}, regionB = {};
u64 currentAddressA = address, currentAddressB = address;
const auto insertDifference = [&] {
switch (currentOperation) {
using enum DifferenceType;
case Match:
break;
case Mismatch:
differencesA.insert({ regionA.getStartAddress(), regionA.getEndAddress() }, Mismatch);
differencesB.insert({ regionB.getStartAddress(), regionB.getEndAddress() }, Mismatch);
break;
case Insertion:
differencesA.insert({ regionA.getStartAddress(), regionA.getEndAddress() }, Insertion);
differencesB.insert({ regionB.getStartAddress(), regionB.getEndAddress() }, Insertion);
currentAddressB -= regionA.size;
break;
case Deletion:
differencesA.insert({ regionA.getStartAddress(), regionA.getEndAddress() }, Deletion);
differencesB.insert({ regionB.getStartAddress(), regionB.getEndAddress() }, Deletion);
currentAddressA -= regionB.size;
break;
}
};
for (const u8 alignmentType : std::span(result.alignment, result.alignmentLength)) {
ON_SCOPE_EXIT {
currentAddressA++;
currentAddressB++;
};
if (currentOperation == DifferenceType(alignmentType)) {
regionA.size++;
regionB.size++;
continue;
} else if (currentOperation != DifferenceType(0xFF)) {
insertDifference();
currentOperation = DifferenceType(0xFF);
}
currentOperation = DifferenceType(alignmentType);
regionA.address = currentAddressA;
regionB.address = currentAddressB;
regionA.size = 1;
regionB.size = 1;
}
insertDifference();
task.update(address);
}
if (providerAEnd > providerBEnd) {
differencesA.insert({ providerBEnd, providerAEnd }, DifferenceType::Insertion);
differencesB.insert({ providerBEnd, providerAEnd }, DifferenceType::Insertion);
} else if (providerAEnd < providerBEnd) {
differencesA.insert({ providerAEnd, providerBEnd }, DifferenceType::Deletion);
differencesB.insert({ providerAEnd, providerBEnd }, DifferenceType::Deletion);
}
return { differencesA, differencesB };
}
void drawSettings() override {
static u64 min = 32_kiB, max = 128_kiB;
ImGui::SliderScalar("hex.diffing.algorithm.myers.settings.window_size"_lang, ImGuiDataType_U64, &m_windowSize, &min, &max, "0x%X");
}
private:
u64 m_windowSize = 64_kiB;
};
void registerDiffingAlgorithms() {
ContentRegistry::Diffing::addAlgorithm<AlgorithmSimple>();
ContentRegistry::Diffing::addAlgorithm<AlgorithmMyers>();
}
}
| 9,030
|
C++
|
.cpp
| 163
| 39.104294
| 143
| 0.563478
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
277
|
view_diff.cpp
|
WerWolv_ImHex/plugins/diffing/source/content/views/view_diff.cpp
|
#include "content/views/view_diff.hpp"
#include <hex/api/imhex_api.hpp>
#include <hex/helpers/fmt.hpp>
#include <hex/providers/buffered_reader.hpp>
#include <fonts/codicons_font.h>
#include <wolv/utils/guards.hpp>
namespace hex::plugin::diffing {
using DifferenceType = ContentRegistry::Diffing::DifferenceType;
ViewDiff::ViewDiff() : View::Window("hex.diffing.view.diff.name", ICON_VS_DIFF_SIDEBYSIDE) {
// Clear the selected diff providers when a provider is closed
EventProviderClosed::subscribe(this, [this](prv::Provider *) {
this->reset();
});
EventDataChanged::subscribe(this, [this](prv::Provider *) {
m_analyzed = false;
});
// Set the background highlight callbacks for the two hex editor columns
m_columns[0].hexEditor.setBackgroundHighlightCallback(this->createCompareFunction(1));
m_columns[1].hexEditor.setBackgroundHighlightCallback(this->createCompareFunction(0));
}
ViewDiff::~ViewDiff() {
EventProviderClosed::unsubscribe(this);
EventDataChanged::unsubscribe(this);
}
namespace {
bool drawDiffColumn(ViewDiff::Column &column, float height) {
if (height < 0)
return false;
bool scrolled = false;
ImGui::PushID(&column);
ON_SCOPE_EXIT { ImGui::PopID(); };
// Draw the hex editor
float prevScroll = column.hexEditor.getScrollPosition();
column.hexEditor.draw(height);
float currScroll = column.hexEditor.getScrollPosition();
// Check if the user scrolled the hex editor
if (prevScroll != currScroll) {
scrolled = true;
column.scrollLock = 5;
}
return scrolled;
}
bool drawProviderSelector(ViewDiff::Column &column) {
bool shouldReanalyze = false;
ImGui::PushID(&column);
auto providers = ImHexApi::Provider::getProviders();
auto &providerIndex = column.provider;
// Get the name of the currently selected provider
std::string preview;
if (ImHexApi::Provider::isValid() && providerIndex >= 0)
preview = providers[providerIndex]->getName();
// Draw combobox with all available providers
ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x);
if (ImGui::BeginCombo("", preview.c_str())) {
for (size_t i = 0; i < providers.size(); i++) {
ImGui::PushID(i + 1);
if (ImGui::Selectable(providers[i]->getName().c_str())) {
providerIndex = i;
shouldReanalyze = true;
}
ImGui::PopID();
}
ImGui::EndCombo();
}
ImGui::PopID();
return shouldReanalyze;
}
}
void ViewDiff::analyze(prv::Provider *providerA, prv::Provider *providerB) {
auto commonSize = std::max(providerA->getActualSize(), providerB->getActualSize());
m_diffTask = TaskManager::createTask("hex.diffing.view.diff.task.diffing"_lang, commonSize, [this, providerA, providerB](Task &) {
auto differences = m_algorithm->analyze(providerA, providerB);
auto providers = ImHexApi::Provider::getProviders();
// Move the calculated differences over so they can be displayed
for (size_t i = 0; i < m_columns.size(); i++) {
auto &column = m_columns[i];
auto &provider = providers[column.provider];
column.differences = differences[i].overlapping({ provider->getBaseAddress(), provider->getBaseAddress() + provider->getActualSize() });
std::ranges::sort(
column.differences,
std::less(),
[](const auto &a) { return a.interval; }
);
column.diffTree = std::move(differences[i]);
}
m_analyzed = true;
});
}
void ViewDiff::reset() {
for (auto &column : m_columns) {
column.provider = -1;
column.hexEditor.setSelectionUnchecked(std::nullopt, std::nullopt);
column.diffTree.clear();
}
}
std::function<std::optional<color_t>(u64, const u8*, size_t)> ViewDiff::createCompareFunction(size_t otherIndex) const {
const auto currIndex = otherIndex == 0 ? 1 : 0;
return [=, this](u64 address, const u8 *, size_t size) -> std::optional<color_t> {
if (!m_analyzed)
return std::nullopt;
const auto matches = m_columns[currIndex].diffTree.overlapping({ address, (address + size) - 1 });
if (matches.empty())
return std::nullopt;
const auto type = matches[0].value;
if (type == DifferenceType::Mismatch) {
return ImGuiExt::GetCustomColorU32(ImGuiCustomCol_DiffChanged);
} else if (type == DifferenceType::Insertion && currIndex == 0) {
return ImGuiExt::GetCustomColorU32(ImGuiCustomCol_DiffAdded);
} else if (type == DifferenceType::Deletion && currIndex == 1) {
return ImGuiExt::GetCustomColorU32(ImGuiCustomCol_DiffRemoved);
}
return std::nullopt;
};
}
void ViewDiff::drawContent() {
auto &[a, b] = m_columns;
a.hexEditor.enableSyncScrolling(false);
b.hexEditor.enableSyncScrolling(false);
if (a.scrollLock > 0) a.scrollLock--;
if (b.scrollLock > 0) b.scrollLock--;
// Change the hex editor providers if the user selected a new provider
{
const auto &providers = ImHexApi::Provider::getProviders();
if (a.provider >= 0 && size_t(a.provider) < providers.size())
a.hexEditor.setProvider(providers[a.provider]);
else
a.hexEditor.setProvider(nullptr);
if (b.provider >= 0 && size_t(b.provider) < providers.size())
b.hexEditor.setProvider(providers[b.provider]);
else
b.hexEditor.setProvider(nullptr);
}
// Analyze the providers if they are valid and the user selected a new provider
if (!m_analyzed && a.provider != -1 && b.provider != -1 && !m_diffTask.isRunning() && m_algorithm != nullptr) {
const auto &providers = ImHexApi::Provider::getProviders();
auto providerA = providers[a.provider];
auto providerB = providers[b.provider];
this->analyze(providerA, providerB);
}
if (auto &algorithms = ContentRegistry::Diffing::impl::getAlgorithms(); m_algorithm == nullptr && !algorithms.empty())
m_algorithm = algorithms.front().get();
static float height = 0;
static bool dragging = false;
const auto availableSize = ImGui::GetContentRegionAvail();
auto diffingColumnSize = availableSize;
diffingColumnSize.y *= 3.5 / 5.0;
diffingColumnSize.y -= ImGui::GetTextLineHeightWithSpacing();
diffingColumnSize.y += height;
if (availableSize.y > 1)
diffingColumnSize.y = std::clamp(diffingColumnSize.y, 1.0F, std::max(1.0F, availableSize.y - ImGui::GetTextLineHeightWithSpacing() * 3));
// Draw the two hex editor columns side by side
if (ImGui::BeginTable("##binary_diff", 2, ImGuiTableFlags_None, diffingColumnSize)) {
ImGui::TableSetupColumn("hex.diffing.view.diff.provider_a"_lang);
ImGui::TableSetupColumn("hex.diffing.view.diff.provider_b"_lang);
ImGui::TableHeadersRow();
ImGui::BeginDisabled(m_diffTask.isRunning());
{
// Draw settings button
ImGui::TableNextColumn();
if (ImGuiExt::DimmedIconButton(ICON_VS_SETTINGS_GEAR, ImGui::GetStyleColorVec4(ImGuiCol_Text)))
RequestOpenPopup::post("##DiffingAlgorithmSettings");
ImGui::SameLine();
// Draw first provider selector
if (drawProviderSelector(a)) m_analyzed = false;
// Draw second provider selector
ImGui::TableNextColumn();
if (drawProviderSelector(b)) m_analyzed = false;
}
ImGui::EndDisabled();
ImGui::TableNextRow();
// Draw first hex editor column
ImGui::TableNextColumn();
bool scrollB = drawDiffColumn(a, diffingColumnSize.y);
// Draw second hex editor column
ImGui::TableNextColumn();
bool scrollA = drawDiffColumn(b, diffingColumnSize.y);
// Sync the scroll positions of the hex editors
{
if (scrollA && a.scrollLock == 0) {
a.hexEditor.setScrollPosition(b.hexEditor.getScrollPosition());
a.hexEditor.forceUpdateScrollPosition();
}
if (scrollB && b.scrollLock == 0) {
b.hexEditor.setScrollPosition(a.hexEditor.getScrollPosition());
b.hexEditor.forceUpdateScrollPosition();
}
}
ImGui::EndTable();
}
ImGui::Button("##table_drag_bar", ImVec2(ImGui::GetContentRegionAvail().x, 2_scaled));
if (ImGui::IsMouseDragging(ImGuiMouseButton_Left, 0)) {
if (ImGui::IsItemHovered())
dragging = true;
} else {
dragging = false;
}
if (ImGui::IsItemHovered()) {
ImGui::SetMouseCursor(ImGuiMouseCursor_ResizeNS);
}
if (dragging) {
height += ImGui::GetMouseDragDelta(ImGuiMouseButton_Left, 0).y;
ImGui::ResetMouseDragDelta(ImGuiMouseButton_Left);
}
// Draw the differences table
if (ImGui::BeginTable("##differences", 3, ImGuiTableFlags_Borders | ImGuiTableFlags_ScrollY | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Resizable)) {
ImGui::TableSetupScrollFreeze(0, 1);
ImGui::TableSetupColumn("hex.ui.common.begin"_lang);
ImGui::TableSetupColumn("hex.ui.common.end"_lang);
ImGui::TableSetupColumn("hex.ui.common.type"_lang);
ImGui::TableHeadersRow();
// Draw the differences if the providers have been analyzed
if (m_analyzed) {
ImGuiListClipper clipper;
auto &differencesA = m_columns[0].differences;
auto &differencesB = m_columns[1].differences;
clipper.Begin(int(std::min(differencesA.size(), differencesB.size())));
while (clipper.Step()) {
for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) {
ImGui::TableNextRow();
ImGui::PushID(i);
const auto &[regionA, typeA] = differencesA[i];
const auto &[regionB, typeB] = differencesB[i];
// Draw a clickable row for each difference that will select the difference in both hex editors
// Draw start address
ImGui::TableNextColumn();
if (ImGui::Selectable(hex::format("0x{:02X}", regionA.start).c_str(), false, ImGuiSelectableFlags_SpanAllColumns)) {
const Region selectionA = { regionA.start, ((regionA.end - regionA.start) + 1) };
const Region selectionB = { regionB.start, ((regionB.end - regionB.start) + 1) };
a.hexEditor.setSelection(selectionA);
a.hexEditor.jumpToSelection();
b.hexEditor.setSelection(selectionB);
b.hexEditor.jumpToSelection();
const auto &providers = ImHexApi::Provider::getProviders();
auto openProvider = ImHexApi::Provider::get();
if (providers[a.provider] == openProvider)
ImHexApi::HexEditor::setSelection(selectionA);
else if (providers[b.provider] == openProvider)
ImHexApi::HexEditor::setSelection(selectionB);
}
// Draw end address
ImGui::TableNextColumn();
ImGui::TextUnformatted(hex::format("0x{:02X}", regionA.end).c_str());
// Draw difference type
ImGui::TableNextColumn();
switch (typeA) {
case DifferenceType::Mismatch:
ImGuiExt::TextFormattedColored(ImGuiExt::GetCustomColorVec4(ImGuiCustomCol_DiffChanged), "hex.diffing.view.diff.modified"_lang);
break;
case DifferenceType::Insertion:
ImGuiExt::TextFormattedColored(ImGuiExt::GetCustomColorVec4(ImGuiCustomCol_DiffAdded), "hex.diffing.view.diff.added"_lang);
break;
case DifferenceType::Deletion:
ImGuiExt::TextFormattedColored(ImGuiExt::GetCustomColorVec4(ImGuiCustomCol_DiffRemoved), "hex.diffing.view.diff.removed"_lang);
break;
default:
break;
}
ImGui::PopID();
}
}
}
ImGui::EndTable();
}
}
void ViewDiff::drawAlwaysVisibleContent() {
ImGui::SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(400_scaled, 600_scaled));
if (ImGui::BeginPopup("##DiffingAlgorithmSettings")) {
ImGuiExt::Header("hex.diffing.view.diff.algorithm"_lang, true);
ImGui::PushItemWidth(300_scaled);
if (ImGui::BeginCombo("##Algorithm", m_algorithm == nullptr ? "" : Lang(m_algorithm->getUnlocalizedName()))) {
for (const auto &algorithm : ContentRegistry::Diffing::impl::getAlgorithms()) {
ImGui::PushID(algorithm.get());
if (ImGui::Selectable(Lang(algorithm->getUnlocalizedName()))) {
m_algorithm = algorithm.get();
m_analyzed = false;
}
ImGui::PopID();
}
ImGui::EndCombo();
}
ImGui::PopItemWidth();
if (m_algorithm != nullptr) {
ImGuiExt::TextFormattedWrapped("{}", Lang(m_algorithm->getUnlocalizedDescription()));
}
ImGuiExt::Header("hex.diffing.view.diff.settings"_lang);
if (m_algorithm != nullptr) {
auto drawList = ImGui::GetWindowDrawList();
auto prevIdx = drawList->_VtxCurrentIdx;
m_algorithm->drawSettings();
auto currIdx = drawList->_VtxCurrentIdx;
if (prevIdx == currIdx)
ImGuiExt::TextFormatted("hex.diffing.view.diff.settings.no_settings"_lang);
}
ImGui::EndPopup();
}
}
}
| 15,487
|
C++
|
.cpp
| 297
| 37.037037
| 161
| 0.559571
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
278
|
plugins.cpp
|
WerWolv_ImHex/tests/plugins/source/plugins.cpp
|
#include <hex/api/plugin_manager.hpp>
#include <hex/helpers/utils.hpp>
#include <hex/helpers/default_paths.hpp>
using namespace hex;
class PluginLoader {
public:
PluginLoader() {
for (const auto &dir : paths::Plugins.read()) {
PluginManager::addLoadPath(dir);
}
PluginManager::loadLibraries();
PluginManager::load();
}
};
static PluginLoader pluginLoader;
| 411
|
C++
|
.cpp
| 15
| 22.733333
| 55
| 0.684478
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
279
|
endian.cpp
|
WerWolv_ImHex/tests/algorithms/source/endian.cpp
|
#include <hex/helpers/utils.hpp>
#include <hex/test/test_provider.hpp>
#include <hex/test/tests.hpp>
TEST_SEQUENCE("32BitIntegerEndianSwap") {
TEST_ASSERT(hex::changeEndianness<u32>(0xAABBCCDD, std::endian::big) == 0xDDCCBBAA);
TEST_SUCCESS();
};
TEST_SEQUENCE("64BitFloatEndianSwap") {
double floatValue = 1234.5;
u64 integerValue = reinterpret_cast<u64 &>(floatValue);
double swappedFloatValue = hex::changeEndianness(floatValue, std::endian::big);
u64 swappedIntegerValue = hex::changeEndianness(integerValue, std::endian::big);
TEST_ASSERT(std::memcmp(&floatValue, &integerValue, 8) == 0 && std::memcmp(&swappedFloatValue, &swappedIntegerValue, 8) == 0);
TEST_SUCCESS();
};
| 718
|
C++
|
.cpp
| 15
| 44.333333
| 130
| 0.733142
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
280
|
crypto.cpp
|
WerWolv_ImHex/tests/algorithms/source/crypto.cpp
|
#include <hex/helpers/crypto.hpp>
#include <hex/helpers/logger.hpp>
#include <hex/test/test_provider.hpp>
#include <hex/test/tests.hpp>
#include <random>
#include <vector>
#include <array>
#include <algorithm>
#include <fmt/ranges.h>
struct EncodeChek {
std::vector<u8> vec;
std::string string;
};
TEST_SEQUENCE("EncodeDecode16") {
std::array golden_samples = {
// source: created by hand
EncodeChek {{}, "" },
EncodeChek { { 0x2a }, "2A" },
EncodeChek { { 0x00, 0x2a }, "002A" },
EncodeChek { { 0x2a, 0x00 }, "2A00" },
EncodeChek { { 0xde, 0xad, 0xbe, 0xef, 0x42, 0x2a, 0x00, 0xff }, "DEADBEEF422A00FF"},
};
for (auto &i : golden_samples) {
std::string string;
TEST_ASSERT((string = hex::crypt::encode16(i.vec)) == i.string, "string: '{}' i.string: '{}' from: {}", string, i.string, i.vec);
std::vector<u8> vec;
TEST_ASSERT((vec = hex::crypt::decode16(i.string)) == i.vec, "vec: {} i.vec: {} from: '{}'", vec, i.vec, i.string);
}
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution dataLen(0, 1024);
std::uniform_int_distribution<u8> data;
for (int i = 0; i < 1000; i++) {
std::vector<u8> original(dataLen(gen));
std::generate(std::begin(original), std::end(original), [&] { return data(gen); });
auto encoded = hex::crypt::encode16(original);
auto decoded = hex::crypt::decode16(encoded);
TEST_ASSERT(decoded == original, "decoded: {} encoded: '{}' original: {}", decoded, encoded, original);
}
if (hex::crypt::encode16({ 0x00, 0x2a }) == "2A") {
hex::log::error("Known bug: in function hex::crypt::encode16 mbedtls_mpi_read_binary ingores initial null bytes");
TEST_FAIL();
}
TEST_SUCCESS();
};
std::string vectorToString(std::vector<u8> in) {
return std::string(reinterpret_cast<char *>(in.data()), in.size());
}
std::vector<u8> stringToVector(std::string in) {
return std::vector<u8>(in.begin(), in.end());
}
TEST_SEQUENCE("EncodeDecode64") {
std::array golden_samples = {
// source: linux command base64 (from GNU coreutils)
EncodeChek {{}, "" },
EncodeChek { { 0x2a }, "Kg==" },
EncodeChek { { 0x00, 0x2a }, "ACo=" },
EncodeChek { { 0x2a, 0x00 }, "KgA=" },
EncodeChek { { 0x42, 0xff, 0x55 }, "Qv9V" },
EncodeChek { { 0xde, 0xad, 0xbe, 0xef, 0x42, 0x2a, 0x00, 0xff }, "3q2+70IqAP8="},
};
for (auto &i : golden_samples) {
std::string string;
TEST_ASSERT((string = vectorToString(hex::crypt::encode64(i.vec))) == i.string, "string: '{}' i.string: '{}' from: {}", string, i.string, i.vec);
std::vector<u8> vec;
TEST_ASSERT((vec = hex::crypt::decode64(stringToVector(i.string))) == i.vec, "vec: {} i.vec: {} from: '{}'", vec, i.vec, i.string);
}
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution dataLen(0, 1024);
std::uniform_int_distribution<u8> data;
for (int i = 0; i < 1000; i++) {
std::vector<u8> original(dataLen(gen));
std::generate(std::begin(original), std::end(original), [&] { return data(gen); });
auto encoded = vectorToString(hex::crypt::encode64(original));
auto decoded = hex::crypt::decode64(stringToVector(encoded));
TEST_ASSERT(decoded == original, "decoded: {} encoded: '{}' original: {}", decoded, encoded, original);
}
TEST_SUCCESS();
};
TEST_SEQUENCE("EncodeDecodeLEB128") {
TEST_ASSERT(hex::crypt::encodeUleb128(0) == (std::vector<u8>{ 0 }));
TEST_ASSERT(hex::crypt::encodeUleb128(0x7F) == (std::vector<u8>{ 0x7F }));
TEST_ASSERT(hex::crypt::encodeUleb128(0xFF) == (std::vector<u8>{ 0xFF, 0x01 }));
TEST_ASSERT(hex::crypt::encodeUleb128(0xF0F0) == (std::vector<u8>{ 0xF0, 0xE1, 0x03 }));
TEST_ASSERT(hex::crypt::encodeSleb128(0) == (std::vector<u8>{ 0 }));
TEST_ASSERT(hex::crypt::encodeSleb128(0x7F) == (std::vector<u8>{ 0xFF, 0x00 }));
TEST_ASSERT(hex::crypt::encodeSleb128(0xFF) == (std::vector<u8>{ 0xFF, 0x01 }));
TEST_ASSERT(hex::crypt::encodeSleb128(0xF0F0) == (std::vector<u8>{ 0xF0, 0xE1, 0x03 }));
TEST_ASSERT(hex::crypt::encodeSleb128(-1) == (std::vector<u8>{ 0x7F }));
TEST_ASSERT(hex::crypt::encodeSleb128(-128) == (std::vector<u8>{ 0x80, 0x7F }));
TEST_ASSERT(hex::crypt::decodeUleb128({}) == 0);
TEST_ASSERT(hex::crypt::decodeUleb128({ 1 }) == 0x01);
TEST_ASSERT(hex::crypt::decodeUleb128({ 0x7F }) == 0x7F);
TEST_ASSERT(hex::crypt::decodeUleb128({ 0xFF }) == 0x7F);
TEST_ASSERT(hex::crypt::decodeUleb128({ 0xFF, 0x7F }) == 0x3FFF);
TEST_ASSERT(hex::crypt::decodeUleb128({
0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0x7F,
}) == ((static_cast<u128>(0xFFFF'FFFF'FFFF) << 64) | 0xFFFF'FFFF'FFFF'FFFF));
TEST_ASSERT(hex::crypt::decodeUleb128({ 0xAA, 0xBB, 0xCC, 0x00, 0xFF }) == 0x131DAA);
TEST_ASSERT(hex::crypt::decodeSleb128({}) == 0);
TEST_ASSERT(hex::crypt::decodeSleb128({ 1 }) == 0x01);
TEST_ASSERT(hex::crypt::decodeSleb128({ 0x3F }) == 0x3F);
TEST_ASSERT(hex::crypt::decodeSleb128({ 0x7F }) == -1);
TEST_ASSERT(hex::crypt::decodeSleb128({ 0xFF }) == -1);
TEST_ASSERT(hex::crypt::decodeSleb128({ 0xFF, 0x7F }) == -1);
TEST_ASSERT(hex::crypt::decodeSleb128({
0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0x7F,
}) == -1);
TEST_ASSERT(hex::crypt::decodeSleb128({ 0xAA, 0xBB, 0xCC, 0x00, 0xFF }) == 0x131DAA);
TEST_ASSERT(hex::crypt::decodeSleb128({ 0xAA, 0xBB, 0x4C }) == -0xCE256);
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<u8> data;
for (int i = 0; i < 1000; i++) {
std::vector<u8> original(sizeof(u128));
std::generate(std::begin(original), std::end(original), [&] { return data(gen); });
u128 u = *reinterpret_cast<u128*>(original.data());
i128 s = *reinterpret_cast<i128*>(original.data());
auto encodedS = hex::crypt::encodeSleb128(s);
i128 decodedS = hex::crypt::decodeSleb128(encodedS);
auto encodedU = hex::crypt::encodeUleb128(u);
u128 decodedU = hex::crypt::decodeUleb128(encodedU);
TEST_ASSERT(decodedS == s, "encoded: {0} decoded: {1:X} original: {2:X}", encodedS, static_cast<u128>(decodedS), static_cast<u128>(s));
TEST_ASSERT(decodedU == u, "encoded: {0} decoded: {1:X} original: {2:X}", encodedU, decodedU, u);
}
TEST_SUCCESS();
};
struct CrcCheck {
std::string name;
int width;
u64 poly;
u64 init;
u64 xorOut;
bool refIn;
bool refOut;
u64 result;
std::vector<u8> data;
};
template<std::invocable<hex::prv::Provider *&, u64, size_t, u32, u32, u32, bool, bool> Func, typename Range>
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);
TEST_ASSERT(crc == i.result, "name: {} got: {:#x} expected: {:#x}", i.name, crc, i.result);
}
TEST_SUCCESS();
}
template<std::invocable<hex::prv::Provider *&, u64, size_t, u32, u32, u32, bool, bool> Func>
int checkCrcAgainstRandomData(Func func, int width) {
// crc( message + crc(message) ) should be 0
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution distribLen(0, 1024);
std::uniform_int_distribution<uint64_t> distribPoly(0, (0b10ull << (width - 1)) - 1);
std::uniform_int_distribution<u8> distribData;
for (int i = 0; i < 500; i++) {
CrcCheck c { "", width, distribPoly(gen), distribPoly(gen), 0, false, false, 0, {} };
c.data.resize(distribLen(gen));
std::generate(std::begin(c.data), std::end(c.data), [&] { return distribData(gen); });
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);
std::vector<u8> data2 = c.data;
if (width >= 32) {
data2.push_back((crc1 >> 24) & 0xff);
data2.push_back((crc1 >> 16) & 0xff);
}
if (width >= 16)
data2.push_back((crc1 >> 8) & 0xff);
data2.push_back((crc1 >> 0) & 0xff);
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);
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);
}
TEST_SUCCESS();
}
TEST_SEQUENCE("CRC32") {
std::array golden_samples = {
// source: A Painless Guide to CRC Error Detection Algorithms [https://zlib.net/crc_v3.txt]
CrcCheck {"CRC-32-CRC32-check", 32, 0x4C11DB7, 0xFFFFFFFF, 0xFFFFFFFF, true, true, 0xCBF43926, { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39 } },
// source: Sunshine's Homepage - Online CRC Calculator Javascript [http://www.sunshine2k.de/coding/javascript/crc/crc_js.html]
CrcCheck { "CRC-32-1-check", 32, 0x4C11DB7, 0xFFFFFFFF, 0xFFFFFFFF, true, false, 0x649C2FD3, { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39 } },
CrcCheck { "CRC-32-2-check", 32, 0x4C11DB7, 0xFFFFFFFF, 0xFFFFFFFF, false, true, 0x1898913F, { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39 } },
CrcCheck { "CRC-32-3-check", 32, 0x4C11DB7, 0xFFFFFFFF, 0xFFFFFFFF, false, false, 0xFC891918, { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39 } },
CrcCheck { "CRC-32-4-check", 32, 0x4C11DB7, 0x55422a00, 0xaa004422, false, false, 0x41A1D8EE, { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39 } },
CrcCheck { "CRC-32-5-check", 32, 0x4C11DB7, 0x55422a00, 0xaa004422, false, false, 0xFF426E22, {} },
// source: generated by Boost CRC from random data and random parameters
CrcCheck { "CRC-32-RANDOM-170", 32, 0x000000005c0dd7fd, 0x000000001c8be2e1, 0x00000000efdedd60, false, true, 0x000000004e9b67a8, { 181, 235, 196, 140, 43, 8, 101, 39, 17, 128, 187, 117, 118, 75, 41, 240, 228, 60, 93, 101, 228, 235, 36, 117, 208, 54, 218, 57, 24, 84, 54, 173, 13, 66, 42, 232, 206, 49, 210, 165, 146, 145, 234, 88, 76, 130, 154, 231, 247, 66, 73, 150, 163, 104, 42, 77, 214, 16, 53, 120, 210, 74, 215, 54, 88, 171, 137, 133, 26, 29, 134, 0, 103, 240, 146, 220, 169, 64, 155, 162, 23, 73, 73, 87, 224, 106, 121, 58, 66, 146, 158, 101, 196, 62, 153, 143, 86, 87, 147, 4, 36, 248, 41, 6, 213, 233, 27, 24, 42, 207, 24, 167, 72, 216, 24, 27, 59, 205, 184, 0, 101, 102, 34, 32, 248, 213, 53, 244, 83, 60, 8, 249, 115, 214, 144, 109, 245, 119, 137, 225, 156, 247, 250, 230, 147, 201, 1, 14, 111, 148, 214, 90, 80, 156, 31, 85, 186, 165, 218, 127, 66, 9, 191, 215, 17, 253, 32, 162, 28, 223, 61, 7, 115, 177, 58 } },
CrcCheck { "CRC-32-RANDOM-171", 32, 0x00000000380bb4f5, 0x00000000c6c652b3, 0x000000003a5ee7d1, false, false, 0x000000002f5a76b0, { 59, 215, 138, 110, 177, 211, 25, 172, 77, 145, 155, 166, 99, 202, 132, 92, 179, 249, 223, 254, 103, 9, 16, 218, 42 } },
CrcCheck { "CRC-32-RANDOM-172", 32, 0x000000000dc7ba53, 0x00000000acfa5319, 0x00000000ee250595, true, true, 0x00000000b3e56ef4, { 218, 89, 16, 112, 197, 97, 69, 29, 33, 173, 8, 121, 78, 23, 131, 152, 82, 174, 94, 206, 33, 228, 35, 205, 83, 71, 219, 99, 13, 48, 105, 180, 187, 246, 101, 249, 91, 67, 207, 177, 61, 108, 144, 73, 209, 201, 166, 115, 2, 110, 70, 67, 25, 31, 0, 20, 83, 9, 152, 169, 125, 74, 246, 183, 186, 70, 199, 106, 38, 127, 230, 44, 43, 64, 119, 14, 97, 127, 127, 166, 98, 157, 71, 109, 3, 15, 197, 223 } },
CrcCheck { "CRC-32-RANDOM-173", 32, 0x00000000fd5a3b2e, 0x00000000580018a2, 0x000000002dbfb987, true, true, 0x0000000040c086a9, { 0, 90, 253, 254, 61, 67, 185, 88, 110, 58, 243, 86, 43, 183, 21, 161, 192, 81, 10, 83, 147, 21, 235, 250, 195, 201, 199, 36, 254, 107, 191, 212, 27, 30, 173, 247, 174, 219, 240, 39, 0, 72, 146, 155, 72, 250, 252, 51, 250, 195, 161, 241, 75, 244, 13, 85, 233, 204, 70, 89, 110, 193, 25, 199, 179, 92, 169, 179, 75, 124, 142, 31, 36, 167, 16, 166, 119, 148, 68, 74, 8, 5, 60, 164, 217, 168, 231, 99, 214, 171, 239, 23, 36, 219, 176, 111, 210, 96, 111, 57, 231, 160, 5, 119, 76, 19, 197, 197, 3, 11, 121, 140, 182, 150, 30, 90, 160, 30, 114, 114, 214, 57, 118, 70, 219, 201, 223, 143, 0, 126, 14, 223, 175, 212, 208, 135, 104, 173, 169, 189, 5, 228, 232, 170, 191, 137, 45, 98, 43, 153, 180, 186, 46, 53, 167, 166, 99, 154, 188, 234, 37, 137, 37, 132, 251, 122, 143, 230, 151, 227, 41, 111, 6, 168, 135, 0, 239, 141, 125, 5, 199, 48, 161, 53, 186, 91, 56, 41, 227, 49, 28, 132, 88, 2, 22, 33, 21, 155, 209, 82, 116, 17, 142, 55, 87, 156, 134, 165, 153, 38, 125, 40, 80, 229, 233, 28, 23, 197 } },
CrcCheck { "CRC-32-RANDOM-174", 32, 0x000000006eae3222, 0x0000000097093735, 0x000000000460e363, false, false, 0x0000000096bf93cd, { 98, 234, 52, 152, 123 } },
CrcCheck { "CRC-32-RANDOM-175", 32, 0x000000002ac3bed5, 0x00000000c2a0964a, 0x0000000019ee4b3b, true, true, 0x00000000b7f1e6b7, { 108, 151, 223, 46, 204, 105, 253, 2, 101, 184, 48, 186, 204, 86, 230, 246, 222, 137, 136, 207, 197, 195, 33, 165, 239, 55, 92, 9, 54, 29, 189, 126, 123, 106, 19, 1, 176, 52, 87, 178, 246, 110, 75, 220, 204, 8, 11, 22 } },
CrcCheck { "CRC-32-RANDOM-176", 32, 0x000000006dc26b9c, 0x00000000096e9400, 0x000000005e4839bf, false, true, 0x0000000063d4b648, { 88, 185, 144, 84, 86, 77, 217, 85, 61, 80, 21, 84, 81, 120, 14, 247, 106, 56, 193, 3, 185, 118, 131, 196, 51, 249, 79, 252, 145, 43, 243, 120, 56, 184, 242, 226, 80, 73, 102, 179, 20, 7, 208, 70, 242, 20, 208, 180, 21, 128, 175, 195, 248, 174, 45, 187, 142, 76, 2, 6, 58, 56, 155, 28, 37, 35, 134, 50, 34, 174, 204, 170, 163, 94, 68, 161, 124, 23, 224, 38, 137, 255, 92, 228, 77, 53, 42, 145, 147, 12, 246, 23, 205, 143, 241, 201, 227, 79, 215, 65, 55, 247, 219, 209, 30, 19, 11, 211, 145, 150, 45, 200, 90, 69, 55, 234, 7, 11, 6, 113, 158, 229, 56, 131, 220, 14, 236, 127, 249, 191, 182, 108, 23, 197, 148, 247, 115, 85, 0, 86, 63, 210, 153, 112, 235, 146, 53, 249, 216, 42, 169, 18, 54, 245, 60, 232, 224, 9, 187, 125, 27, 180, 171, 138, 138, 13, 45, 125, 220, 158, 164, 21, 109, 23, 8, 2, 41, 178, 245, 226, 211, 202, 134, 4, 133, 192, 125 } },
CrcCheck { "CRC-32-RANDOM-177", 32, 0x00000000de2c5518, 0x000000003e12e6ec, 0x00000000474d1134, true, false, 0x00000000623e70f4, { 239, 114, 198, 23, 88, 133, 118, 9, 184, 162, 78, 142, 128, 165, 196, 6, 148, 0, 56, 249, 4, 126, 152, 67, 17, 48, 153, 151, 46, 183, 92, 242, 155, 233, 216, 166, 22, 107, 139, 93, 3, 239, 154, 20, 15, 69, 41, 126, 65, 76, 229, 133, 161, 181, 201, 134, 213, 158, 174, 17, 32, 45, 223, 74, 56, 194, 228, 37, 71, 128, 160, 202, 219, 173, 55, 223, 104, 90, 176, 152, 113, 160, 224, 36, 111, 170, 64, 28, 29, 239, 23, 135, 254, 240, 117, 147, 125, 138, 86, 206, 28, 48, 169, 107, 193, 186, 197, 219, 180, 83, 108, 250, 172, 21, 18, 121, 154, 77, 36, 48, 88, 167, 42, 3, 91, 172, 235, 166, 85, 93, 42, 254, 47, 37, 193, 104, 32, 171, 172, 225, 194, 80, 120, 61, 198, 108, 105, 21, 188, 51, 101, 49, 88, 97, 51, 168, 251, 4, 226, 114, 202, 53, 7, 171, 41, 72, 138, 161, 227, 182, 223, 92, 96, 196, 203, 255, 72, 190, 6, 106, 69, 172, 41, 131, 241, 34, 147, 155, 27, 67, 109, 39, 202, 82, 184, 160, 167, 163, 66, 222, 172, 65, 24, 46, 181, 217, 1, 249, 206, 171, 27, 87, 88, 40, 191, 153, 121, 206, 89, 48, 7, 86, 82, 68, 129, 224, 181, 108, 144, 1, 14, 204, 79, 183, 129, 116, 124, 175, 158, 98, 197 }},
CrcCheck { "CRC-32-RANDOM-178", 32, 0x00000000983395ff, 0x00000000b8a8a4fe, 0x00000000c0996c7c, true, true, 0x0000000003def4ee, { 81, 82, 118, 44, 112, 193, 97, 94, 233, 4, 105, 223, 158, 176, 91, 215, 162, 197, 79, 59, 191, 152, 87, 68, 79, 122, 35, 78, 180, 40, 151, 82, 199, 227 } },
CrcCheck { "CRC-32-RANDOM-179", 32, 0x0000000096345585, 0x0000000098436ef2, 0x000000000373eba2, true, false, 0x000000001a7ca97a, { 22, 29, 92, 40, 254, 225, 67, 92, 243, 28, 191, 168, 25, 228, 67, 240, 230, 20, 1, 165, 223, 154, 244, 100, 127, 254, 103, 233, 105, 139, 3, 232, 31, 57, 84, 99, 144, 1, 105, 240, 103, 118, 146, 128, 216, 43, 115, 59, 233, 56, 3, 9, 139, 64, 229, 52, 116, 210, 173, 55, 190, 126, 168, 10, 4, 72, 62, 134, 152, 151, 143, 153, 217, 50, 134, 15, 251, 158, 241, 253, 161, 36, 44, 60, 75, 74, 253, 170, 39, 43, 255, 183, 194, 176, 95, 255, 21, 122, 83, 200, 201, 249, 175, 245, 166, 128, 54, 253, 234, 106, 122, 177, 169, 162, 71, 99, 135, 204, 72, 24, 22, 170, 97, 11, 5, 165, 88, 173, 43, 138, 143, 5, 68, 12, 178, 125, 66, 132, 28, 215, 49, 47, 146, 193, 0, 193, 65, 103, 53, 81, 58, 99, 38, 224, 34, 124, 44, 165, 95, 129, 192, 160, 110, 76, 131, 157, 49, 76, 100, 83, 220, 101, 253, 108, 11, 21, 88, 178, 114, 163, 58, 200, 57, 232, 252, 216, 217, 154, 122, 251, 200, 216, 238, 165, 94, 97, 76, 112, 39, 243, 77, 81, 189, 10, 48, 10, 65, 180, 252, 15, 132, 86, 68, 199, 185, 4, 19, 19, 61, 249, 133, 80, 45, 206, 49, 16, 107, 176 } },
};
TEST_ASSERT(!checkCrcAgainstGondenSamples(hex::crypt::crc32, golden_samples));
TEST_SUCCESS();
};
TEST_SEQUENCE("CRC32Random") {
TEST_ASSERT(!checkCrcAgainstRandomData(hex::crypt::crc32, 32));
TEST_SUCCESS();
};
TEST_SEQUENCE("CRC16") {
std::array golden_samples = {
// source: A Painless Guide to CRC Error Detection Algorithms [https://zlib.net/crc_v3.txt]
CrcCheck {"CRC-16-CRC16-check", 16, 0x8005, 0x0000, 0x0000, true, true, 0xBB3D, { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39 } },
// source: Sunshine's Homepage - Online CRC Calculator Javascript [http://www.sunshine2k.de/coding/javascript/crc/crc_js.html]
CrcCheck { "CRC-16-1-check", 16, 0x8005, 0x0000, 0x0000, true, false, 0xBCDD, { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39 } },
CrcCheck { "CRC-16-2-check", 16, 0x8005, 0x0000, 0x0000, false, true, 0x177F, { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39 } },
CrcCheck { "CRC-16-3-check", 16, 0x8005, 0x0000, 0x0000, false, false, 0xFEE8, { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39 } },
CrcCheck { "CRC-16-3-check", 16, 0x8005, 0x5042, 0xfc2a, false, false, 0xDD50, { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39 } },
// source: generated by Boost CRC from random data and random parameters
CrcCheck { "CRC-16-RANDOM-10", 16, 0x000000000000afbb, 0x00000000000091ea, 0x0000000000000ea8, true, true, 0x0000000000000670, { 239, 127, 45, 34, 24, 9, 68, 49, 206, 206, 71, 116, 233, 144, 237, 184, 241, 86, 244, 237, 163, 167, 42, 194, 69, 147, 236, 136, 245, 183, 254, 2, 67, 220, 111, 241, 168, 255, 36, 248, 147, 137, 75, 137, 201, 100, 215, 161, 36, 13, 54, 235, 34, 187, 75, 82, 227, 97, 240, 137, 173, 165, 246, 129, 30, 174, 42, 21, 185, 94, 43, 218, 126, 90, 197, 205, 15, 21, 115, 50, 103, 38, 178, 124, 27, 24, 208, 157, 41, 53, 204, 158, 198, 238, 133, 61, 164, 203, 159, 6, 94, 213, 225, 145, 61, 245, 86, 157, 126, 41, 130, 195, 130, 11, 48, 29, 193, 187, 127, 135, 83, 44, 232, 66, 169, 147, 106, 11, 118, 124, 189, 114, 131, 148, 106, 45, 250, 134, 11, 189, 179, 74, 92, 43, 8, 116, 18, 241, 53, 218, 160, 169, 65, 112, 161, 63, 208, 61, 223, 18, 254, 51, 87, 101, 180, 244, 149, 78, 135, 54, 222, 122, 244, 184, 44 } },
CrcCheck { "CRC-16-RANDOM-11", 16, 0x0000000000001b6c, 0x0000000000005bce, 0x000000000000e29c, true, true, 0x000000000000dfa2, { 92, 73, 175, 57, 17, 7, 61, 3, 7, 81, 172, 188, 91, 214, 51, 201, 52, 249, 51, 206, 210, 79, 156, 42, 36, 28, 235, 71, 83, 127, 30, 123, 200, 55, 127, 217, 218, 71, 203, 29, 223, 222, 198, 56, 138, 207, 196, 46, 195, 105, 28, 45, 5, 138, 168, 54, 239, 203, 1, 0, 105, 110, 21, 193, 207 } },
CrcCheck { "CRC-16-RANDOM-12", 16, 0x000000000000477b, 0x000000000000afa4, 0x0000000000003d01, false, false, 0x0000000000000b96, { 63, 84, 254, 94, 21, 194, 88, 199, 189, 117, 111, 234, 231, 51, 119, 117, 203, 239, 210, 109, 162, 58, 158, 239, 163, 18, 68, 233, 37, 120, 48, 205, 17, 188, 141, 44, 143, 147, 173, 105 } },
CrcCheck { "CRC-16-RANDOM-13", 16, 0x0000000000004438, 0x0000000000008e25, 0x0000000000006c55, false, false, 0x0000000000004a6d, { 179, 169, 67, 230, 228, 213, 173, 155, 152, 64, 85, 170, 20, 177, 38, 127, 169, 186, 44, 163, 153, 153, 11, 112, 63, 24, 127, 25, 135, 40, 214, 33, 88, 132, 14, 84, 82, 66, 216, 75, 55, 231, 101, 114, 68, 244, 56, 140, 100, 196, 226, 60, 0, 177, 187, 164, 237, 1, 199, 119, 249, 148, 102, 175, 32, 62, 232, 179, 30, 102, 85, 8, 188, 61, 28, 156, 74, 71, 11, 102, 51, 243, 120, 60, 146, 207, 116, 156, 219, 237, 157, 25, 0, 149, 7, 137, 248, 102, 157, 171, 60, 76, 117, 29, 34, 117, 148, 241, 142, 18, 251, 240, 37, 213, 171, 120, 85, 145, 50, 209, 130, 225, 28, 27, 170, 195, 148, 102 } },
CrcCheck { "CRC-16-RANDOM-14", 16, 0x000000000000f461, 0x0000000000004d96, 0x0000000000003e1d, true, true, 0x0000000000009eef, { 38, 252, 182, 80, 159, 97, 166, 150, 29, 9, 45, 216, 186, 165, 148, 128, 60, 170, 243, 69, 177, 203, 17, 191, 5, 60, 209, 41, 20, 42, 23, 147, 126, 209, 125, 157, 30, 45, 94, 157, 146, 7, 20, 234, 70, 23, 141, 87, 88, 93, 184, 169, 69, 88, 108, 253, 58, 157, 175, 88, 177, 154, 181, 127, 216, 82, 202, 16, 164, 227, 188, 243, 140, 84, 24, 213, 31, 130, 185, 234, 215, 248, 169, 233, 4, 208, 67, 102, 248, 13, 114, 162, 175, 187, 120, 228, 213, 93 } },
CrcCheck { "CRC-16-RANDOM-15", 16, 0x000000000000bbf3, 0x000000000000e279, 0x000000000000a01c, false, false, 0x000000000000f294, { 251, 1, 172, 207, 75, 242, 148, 19, 255, 106, 41, 114, 213, 142, 229, 239, 156, 23, 225, 4, 181, 190, 130, 111, 160, 59, 145, 253, 181, 114, 17, 118, 65, 201, 206, 61, 137, 118, 87, 156, 205, 110, 6, 63, 153, 254, 163, 225, 66, 88, 232, 189, 126, 92, 228, 204, 0, 243, 78, 239, 62, 193, 27, 197, 106, 96, 215, 1, 143, 116, 114, 112, 6, 150, 209, 152, 254, 66, 54, 94, 123, 109, 220, 31, 156, 118, 201, 119, 232, 181, 49, 140, 82, 192, 65, 167, 94, 196, 10, 162, 138, 163, 9, 240, 203, 230, 23, 117, 118, 217, 35, 59, 80, 150, 105, 253, 127, 105, 53, 54, 134, 90, 78, 161, 95, 123, 164, 235, 209, 143, 12, 199, 20, 167, 53, 246, 87, 5, 76, 164, 90, 230, 19, 34, 24, 30, 133, 190, 136, 129, 68, 208, 98, 110, 170, 174, 135, 152, 155, 76, 215, 26, 189, 63, 72, 14, 57, 186, 173, 44, 212, 212, 66, 120, 155, 51, 62, 116, 210, 218, 49, 125, 23, 134 }},
CrcCheck { "CRC-16-RANDOM-16", 16, 0x000000000000e5dd, 0x0000000000009239, 0x00000000000006f7, false, false, 0x0000000000005351, { 185, 105, 153, 99, 108, 57, 120, 51, 20, 3, 200, 10, 175, 75, 171, 152, 175, 99, 174, 14, 48, 148, 220, 47, 84, 168, 249, 218, 35, 74, 212, 106, 182, 241, 40, 210, 59, 193, 243, 1, 225, 152, 167, 139, 119, 252, 61, 192, 71, 32, 236, 161, 110, 30, 151, 179, 147, 225, 190, 238, 30, 131, 165, 128, 141, 6, 84, 62, 13, 147, 135, 190, 42, 97, 140, 154, 231, 162, 125, 98, 239, 156, 248, 149, 43, 112, 164, 127, 103, 1, 59, 30, 210, 140, 174, 72, 121, 187, 29, 204, 32, 120, 108, 243, 54, 124, 30, 88, 116, 179, 188, 230, 16, 139, 153, 151, 128, 109, 155, 131, 56, 83, 125, 11, 178, 79, 68, 209, 198, 216, 81, 133, 171, 184, 222, 68, 99, 153, 34, 93, 135, 148, 128, 21, 110, 248, 141, 92, 92, 117, 154, 56, 250, 210, 126, 109, 113, 233, 143, 253, 8, 184, 61, 223, 170, 131, 215, 150, 57, 91, 95, 200, 151, 185, 234, 166, 113, 73, 34, 83, 204, 6 } },
CrcCheck { "CRC-16-RANDOM-17", 16, 0x000000000000b4a3, 0x000000000000b94e, 0x000000000000744e, true, true, 0x000000000000cd8b, { 55, 240, 81, 130, 195, 14, 15, 70, 94, 190, 211, 82, 239, 29, 140, 56, 29, 155, 47, 100, 41, 110, 50, 185, 94, 203, 192, 11, 78, 245, 44, 158, 244, 176, 132, 85, 193, 94, 32, 74, 6, 224, 248, 2, 61, 8, 227, 112, 10, 58, 81, 76, 56, 252, 147, 99, 226, 82, 203, 87, 9, 216, 201, 189, 195, 142, 216, 248, 73, 157, 62 } },
CrcCheck { "CRC-16-RANDOM-18", 16, 0x0000000000009c67, 0x0000000000006327, 0x0000000000008e39, false, false, 0x000000000000d9e0, { 37, 181, 10, 26, 177, 9, 181, 162, 61, 13, 117, 143, 203, 86, 77, 104, 107, 0, 187, 12, 243, 73, 117, 131, 36, 34, 68, 180, 221, 2, 10, 104, 42, 247, 230, 199, 208, 83, 55, 235, 33, 104, 10, 91, 250, 88, 16, 24, 191, 252, 94, 152, 208, 179, 216, 41, 101, 64, 217, 76, 33, 231 } },
};
TEST_ASSERT(!checkCrcAgainstGondenSamples(hex::crypt::crc16, golden_samples));
TEST_SUCCESS();
};
TEST_SEQUENCE("CRC16Random") {
TEST_ASSERT(!checkCrcAgainstRandomData(hex::crypt::crc16, 16));
TEST_SUCCESS();
};
TEST_SEQUENCE("CRC8") {
std::array golden_samples = {
// source: Sunshine's Homepage - Online CRC Calculator Javascript [http://www.sunshine2k.de/coding/javascript/crc/crc_js.html]
CrcCheck {"CRC-8-0-check", 8, 0xD5, 0xff, 0x00, true, true, 0x7f, { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39 } },
CrcCheck { "CRC-8-1-check", 8, 0xD5, 0xff, 0x00, true, false, 0xfe, { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39 } },
CrcCheck { "CRC-8-2-check", 8, 0xD5, 0xff, 0x00, false, true, 0x3e, { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39 } },
CrcCheck { "CRC-8-3-check", 8, 0xD5, 0xff, 0x00, false, false, 0x7c, { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39 } },
CrcCheck { "CRC-8-3-check", 8, 0xD5, 0x42, 0x5a, false, false, 0x4a, { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39 } },
// source: generated by Boost CRC from random data and random parameters
CrcCheck { "CRC-8-RANDOM-0", 8, 0x000000000000008b, 0x00000000000000d4, 0x00000000000000c7, true, false, 0x0000000000000093, { 195, 137, 209, 107, 84, 196, 218, 41, 155, 11, 48, 19, 105, 74, 207, 198, 134, 17, 172, 76, 89, 18, 81, 236, 101, 109, 222, 62, 254, 170, 66, 240, 56, 184, 199, 187, 253, 115, 251, 59, 115, 2, 105, 234, 91, 110, 86, 36, 31, 129, 146, 217, 16, 90, 115, 35, 27, 17, 81, 247, 215, 8, 67, 77, 103, 141, 9, 101, 90, 36, 155, 193, 106, 186, 134, 46, 182, 124, 220, 46, 4, 203, 171, 215, 56, 132, 110, 146, 77, 231, 214, 233, 17, 49, 77, 119, 80, 77, 158, 253, 255, 74, 94, 232, 77, 94, 81, 48, 164, 29, 51, 81, 122, 71, 23, 57, 126, 176, 129, 250, 163, 6, 1, 191, 5, 93, 172, 176, 128, 202, 52, 89, 104, 36, 50, 30, 64, 216, 19, 140, 229, 7, 214, 168, 155 } },
CrcCheck { "CRC-8-RANDOM-1", 8, 0x000000000000005d, 0x0000000000000077, 0x0000000000000005, false, false, 0x000000000000009a, { 40, 210, 96, 74, 179, 97, 240, 65, 23, 50, 222, 233, 252, 131, 110, 135, 141, 161, 239, 91, 108, 132, 166, 169, 82, 187, 251, 92, 125, 57, 64, 207, 238, 108, 243, 72, 50, 229, 127, 224, 235, 179, 59, 107, 36, 48, 15, 165, 24, 196, 221, 5, 116, 57, 5, 124, 1, 64, 141, 134, 82, 159, 200, 171, 19, 10, 196, 70, 80, 39, 2, 188, 230, 165, 138, 178, 38, 44, 26, 225, 212, 32, 44, 139, 39, 125, 231, 94, 224, 89, 47, 125, 6, 46, 254, 49, 101, 225, 23, 44, 89, 16, 76, 50, 23, 115, 188, 185, 76, 100, 122, 1, 57, 239, 100, 180, 63, 158, 205, 6 } },
CrcCheck { "CRC-8-RANDOM-2", 8, 0x00000000000000ea, 0x00000000000000d9, 0x0000000000000000, false, false, 0x0000000000000092, { 215, 10, 66, 226, 48, 21, 189, 238, 141, 93, 174, 19, 109, 196, 154, 78, 215 } },
CrcCheck { "CRC-8-RANDOM-3", 8, 0x00000000000000f3, 0x000000000000007b, 0x000000000000007f, true, true, 0x00000000000000de, { 120, 75, 112, 57, 59, 218, 44, 68, 242, 0, 155, 24, 95, 210, 134, 36, 136, 139, 106, 190, 215, 23, 15, 45, 185, 217, 72, 219, 214, 170, 89, 93, 179, 61, 71, 162, 221, 10, 37, 163, 205, 10, 136, 200, 77, 102, 51, 188, 170, 232, 196, 184, 200, 98, 79, 150, 249, 253, 188, 27, 53, 169, 239, 246, 167, 28, 100, 86, 224, 197, 201, 8, 176, 114, 195, 40, 181, 52, 77, 27, 151, 45, 44, 205, 245, 240, 182, 223, 205, 182, 57, 102, 44, 72, 201, 233, 168, 241, 30, 253, 104, 7, 72, 227, 135, 49, 63, 209, 187, 174, 29, 255, 237, 107, 77, 22, 187, 148, 64, 207, 175, 218, 201, 104, 45, 54, 204, 65, 80, 6, 185, 187, 10, 246, 222, 62, 115, 88, 250, 65, 148, 127, 28, 93, 121, 161, 65, 87, 150, 151, 117, 199, 229, 98, 31, 145, 34, 242, 145, 146, 9, 24, 176, 248, 104, 180, 208, 181, 64, 223, 171, 144, 156, 80, 234, 169, 218, 107, 68, 62, 147, 7, 61, 102, 75, 112, 168, 33, 13, 132, 56, 46, 181, 219, 84, 137, 64, 84, 228, 172, 143 } },
CrcCheck { "CRC-8-RANDOM-4", 8, 0x00000000000000a1, 0x0000000000000035, 0x0000000000000013, true, true, 0x00000000000000e8, { 132, 238, 232, 49, 230, 205, 207, 227, 227, 111, 23, 5, 192, 33, 32, 227, 219, 48, 97, 228, 184, 213, 25, 66, 188, 16, 190, 115, 253, 113, 144, 222, 9, 120, 159, 187, 23, 146, 37, 212, 214, 3, 54, 190, 246, 3, 55, 19, 254, 150, 31, 36, 112, 89, 32, 78, 42, 171, 124, 3, 229, 191, 144, 10, 60, 209, 46, 54, 11, 205, 109, 52, 142, 67, 189, 186, 147, 219, 91, 21, 1, 61, 143, 77, 38, 15, 150, 126, 140, 139, 233, 83, 103, 162, 1, 79, 30, 223, 51, 93, 43, 131, 8, 123, 228, 37 } },
CrcCheck { "CRC-8-RANDOM-5", 8, 0x0000000000000095, 0x00000000000000d8, 0x0000000000000043, false, false, 0x0000000000000008, { 25, 135, 154, 213, 104, 181, 83, 188, 128, 84, 4, 175, 2, 108, 206, 235, 11, 252, 150, 39, 125, 195, 172, 130, 109, 181, 73, 171, 211, 35, 162, 82, 207, 1, 73, 78, 24, 102, 151, 170, 234, 242, 127, 77, 161, 43, 80, 176, 5, 89, 11, 51, 24, 60, 144, 187, 182, 70, 177, 218, 126, 230, 188, 108, 205, 181, 17, 55, 154, 207, 228, 209, 77, 99, 122, 146, 209, 199, 47, 177, 200, 178, 139, 239, 27, 56, 183, 228, 153, 127, 47, 34, 111, 78, 161, 54, 86, 110, 244, 126, 108, 95, 7, 100, 160, 26, 133, 76, 101, 59, 25, 54, 23, 83, 148, 90, 26, 252, 213, 37, 9, 97, 10, 56, 53, 213, 152, 111, 126, 254, 101, 232, 71, 1, 166, 14, 159, 196, 71, 113, 20, 232, 138, 115, 126, 64, 140, 11, 52, 78, 240, 45, 160, 103, 212, 19, 188, 238, 141, 92, 126, 36, 160, 44, 72, 121, 60, 8, 211, 112, 192, 198, 50, 83, 177, 80, 166, 107, 96, 205, 183, 126, 229, 254, 128, 154, 191, 242, 251, 248, 122, 174, 162, 89, 136, 83, 217, 220, 224, 106, 23, 22, 33, 63, 142, 226, 83, 247, 60, 102, 193, 36, 63, 235, 97, 182, 86, 229, 85, 98, 90, 17, 253, 134, 201, 253, 64, 39, 33, 223, 8, 110, 55, 10, 223, 136, 14, 229, 66, 179, 79, 203, 110, 41, 151, 194, 85, 190, 122, 114, 109, 209, 59, 8 }},
CrcCheck { "CRC-8-RANDOM-6", 8, 0x0000000000000081, 0x0000000000000083, 0x00000000000000d7, true, true, 0x000000000000006d, { 7, 210, 211, 232, 246, 26, 147, 95, 236, 136, 206, 194, 251, 106, 140, 115, 125, 183, 176, 39, 84, 236, 236, 111, 120, 165, 211, 12, 217, 60, 139, 2, 182, 81, 158, 49, 38, 96, 93, 49, 197, 88, 114, 50, 235, 119, 196, 122, 165, 157, 234, 65, 166, 237, 217, 3, 247, 96, 50, 108, 153, 156, 123, 252, 224, 187, 215, 151, 52, 160, 149, 74, 50, 125, 233, 96, 242, 124, 176, 78, 178, 23, 232, 133, 191, 213, 121, 225, 34, 220, 87, 25, 187, 26, 22, 92, 92, 249, 175, 216, 162, 190, 191, 198, 166, 49, 225, 161, 117, 215, 227, 218, 80, 32, 253, 0, 19, 26, 235, 9, 23, 198, 23, 181, 161, 152, 121, 166, 57, 189, 66, 197, 72, 229, 18, 34, 146, 179, 93, 148, 184, 51, 143, 140, 138, 94, 45, 100, 194, 200, 80, 224, 15, 154, 31, 142, 55, 72, 252, 47, 76, 235, 189, 249, 27, 126, 101, 245, 232, 46, 46, 152, 208, 23, 9, 206, 76, 174, 133, 229, 221, 146, 243, 126, 73, 8, 98, 83 } },
CrcCheck { "CRC-8-RANDOM-7", 8, 0x00000000000000e5, 0x000000000000001e, 0x00000000000000ca, false, true, 0x00000000000000ac, { 207, 120, 96, 152, 93, 112, 171, 102, 62, 189, 137, 61, 204, 42, 249, 226, 131, 164, 162, 33, 222, 75, 84, 174, 63, 71, 125, 255, 254, 135, 241, 176, 17, 184, 193, 248, 167, 247, 117, 192, 182 } },
CrcCheck { "CRC-8-RANDOM-8", 8, 0x0000000000000003, 0x0000000000000035, 0x0000000000000033, true, false, 0x00000000000000d9, { 96, 249, 185, 15, 247, 136, 115, 115, 87, 117, 90, 120, 18, 197, 112, 61, 70, 87, 22, 98, 103, 241, 49, 87, 120, 119, 201, 92, 192, 109, 175, 86, 135, 157, 183, 66, 43, 21, 76, 201 } },
CrcCheck { "CRC-8-RANDOM-9", 8, 0x000000000000002c, 0x0000000000000094, 0x0000000000000001, false, false, 0x0000000000000095, { 52, 156, 20, 14, 1, 178, 132, 57, 220, 251, 1, 215, 195, 236, 197, 102, 193, 157, 140, 196, 132, 204, 155, 140, 185, 73, 13, 252, 175, 141, 171, 139, 221, 14, 156, 253, 107, 24, 153, 166, 217, 181, 203, 39, 172, 114, 160, 88, 197, 221, 51, 241, 70, 152, 181, 31, 88, 165, 30, 123, 231, 163, 75, 107, 55, 95, 2, 13, 70, 128, 165, 27, 224, 105, 51, 97, 76, 160, 100, 245, 174, 32, 109, 251, 43, 55, 139, 88, 89, 122, 194, 92, 245, 188, 236, 38, 211, 19, 252, 17, 209, 60, 133, 227, 36, 69, 213, 161, 162, 187, 161, 202, 3, 71, 32, 29, 131, 167, 43, 99, 175, 141, 70, 62, 3, 56, 100, 107, 165, 123, 239, 252, 219, 111, 11, 31, 216, 22, 111, 27, 7, 44, 168, 68, 216, 58, 207, 231, 94, 58, 178, 210, 149 } },
};
TEST_ASSERT(!checkCrcAgainstGondenSamples(hex::crypt::crc8, golden_samples));
TEST_SUCCESS();
};
TEST_SEQUENCE("CRC8Random") {
TEST_ASSERT(!checkCrcAgainstRandomData(hex::crypt::crc8, 8));
TEST_SUCCESS();
};
struct HashCheck {
std::string data;
std::string result;
};
template<typename Ret, typename Range>
int checkHashProviderAgainstGondenSamples(Ret (*func)(hex::prv::Provider *&, u64, size_t), Range golden_samples) {
for (auto &i : golden_samples) {
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());
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);
}
TEST_SUCCESS();
}
template<typename Ret, typename Range>
int checkHashVectorAgainstGondenSamples(Ret (*func)(const std::vector<u8> &), Range golden_samples) {
for (auto &i : golden_samples) {
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);
}
TEST_SUCCESS();
}
TEST_SEQUENCE("md5") {
std::array golden_samples = {
// source: RFC 1321: The MD5 Message-Digest Algorithm [https://datatracker.ietf.org/doc/html/rfc1321#appendix-A.5]
HashCheck {"",
"d41d8cd98f00b204e9800998ecf8427e"},
HashCheck { "a",
"0cc175b9c0f1b6a831c399e269772661"},
HashCheck { "abc",
"900150983cd24fb0d6963f7d28e17f72"},
HashCheck { "message digest",
"f96b697d7cb7938d525a2f31aaf161d0"},
HashCheck { "abcdefghijklmnopqrstuvwxyz",
"c3fcd3d76192e4007dfb496cca67e13b"},
HashCheck { "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
"d174ab98d277d9f5a5611c2c9f419d9f"},
HashCheck { "12345678901234567890123456789012345678901234567890123456789012345678901234567890",
"57edf4a22be3c955ac49da2e2107b67a"},
};
TEST_ASSERT(!checkHashProviderAgainstGondenSamples(hex::crypt::md5, golden_samples));
TEST_ASSERT(!checkHashVectorAgainstGondenSamples(hex::crypt::md5, golden_samples));
TEST_SUCCESS();
};
TEST_SEQUENCE("sha1") {
std::array golden_samples = {
// source: RFC 3174: US Secure Hash Algorithm 1 (SHA1) [https://datatracker.ietf.org/doc/html/rfc3174#section-7.3]
HashCheck {"abc",
"A9993E364706816ABA3E25717850C26C9CD0D89D"},
HashCheck { "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
"84983E441C3BD26EBAAE4AA1F95129E5E54670F1"},
};
TEST_ASSERT(!checkHashProviderAgainstGondenSamples(hex::crypt::sha1, golden_samples));
TEST_ASSERT(!checkHashVectorAgainstGondenSamples(hex::crypt::sha1, golden_samples));
TEST_SUCCESS();
};
TEST_SEQUENCE("sha224") {
std::array golden_samples = {
// source: RFC 3874: A 224-bit One-way Hash Function: SHA-224 [https://datatracker.ietf.org/doc/html/rfc3874#section-3]
HashCheck {"abc",
"23097D223405D8228642A477BDA255B32AADBCE4BDA0B3F7E36C9DA7"},
HashCheck { "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
"75388B16512776CC5DBA5DA1FD890150B0C6455CB4F58B1952522525"},
};
TEST_ASSERT(!checkHashProviderAgainstGondenSamples(hex::crypt::sha224, golden_samples));
TEST_ASSERT(!checkHashVectorAgainstGondenSamples(hex::crypt::sha224, golden_samples));
TEST_SUCCESS();
};
TEST_SEQUENCE("sha256") {
std::array golden_samples = {
// source: RFC 4634: US Secure Hash Algorithms (SHA and HMAC-SHA) [https://datatracker.ietf.org/doc/html/rfc4634#section-8.4]
HashCheck {"abc",
"BA7816BF8F01CFEA414140DE5DAE2223B00361A396177A9CB410FF61F20015AD"},
HashCheck { "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
"248D6A61D20638B8E5C026930C3E6039A33CE45964FF2167F6ECEDD419DB06C1"},
};
TEST_ASSERT(!checkHashProviderAgainstGondenSamples(hex::crypt::sha256, golden_samples));
TEST_ASSERT(!checkHashVectorAgainstGondenSamples(hex::crypt::sha256, golden_samples));
TEST_SUCCESS();
};
TEST_SEQUENCE("sha384") {
std::array golden_samples = {
// source: RFC 4634: US Secure Hash Algorithms (SHA and HMAC-SHA) [https://datatracker.ietf.org/doc/html/rfc4634#section-8.4]
HashCheck {"abc",
"CB00753F45A35E8BB5A03D699AC65007272C32AB0EDED1631A8B605A43FF5BED8086072BA1E7CC2358BAECA134C825A7"},
HashCheck { "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
"09330C33F71147E83D192FC782CD1B4753111B173B3B05D22FA08086E3B0F712FCC7C71A557E2DB966C3E9FA91746039"},
};
TEST_ASSERT(!checkHashProviderAgainstGondenSamples(hex::crypt::sha384, golden_samples));
TEST_ASSERT(!checkHashVectorAgainstGondenSamples(hex::crypt::sha384, golden_samples));
TEST_SUCCESS();
};
TEST_SEQUENCE("sha512") {
std::array golden_samples = {
// source: RFC 4634: US Secure Hash Algorithms (SHA and HMAC-SHA) [https://datatracker.ietf.org/doc/html/rfc4634#section-8.4]
HashCheck {"abc",
"DDAF35A193617ABACC417349AE20413112E6FA4E89A97EA20A9EEEE64B55D39A2192992A274FC1A836BA3C23A3FEEBBD454D4423643CE80E2A9AC94FA54CA49F"},
HashCheck { "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
"8E959B75DAE313DA8CF4F72814FC143F8F7779C6EB9F7FA17299AEADB6889018501D289E4900F7E4331B99DEC4B5433AC7D329EEB6DD26545E96E55B874BE909"},
};
TEST_ASSERT(!checkHashProviderAgainstGondenSamples(hex::crypt::sha512, golden_samples));
TEST_ASSERT(!checkHashVectorAgainstGondenSamples(hex::crypt::sha512, golden_samples));
TEST_SUCCESS();
};
| 70,660
|
C++
|
.cpp
| 392
| 173.22449
| 1,295
| 0.345302
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
281
|
main.cpp
|
WerWolv_ImHex/tests/common/source/main.cpp
|
#include <hex.hpp>
#include <hex/api/event_manager.hpp>
#include <hex/helpers/utils.hpp>
#include <hex/helpers/logger.hpp>
#include <hex/test/tests.hpp>
#include <hex/api/plugin_manager.hpp>
#include <hex/api/task_manager.hpp>
#include <hex/api/event_manager.hpp>
#include <cstdlib>
int test(int argc, char **argv) {
// Check if a test to run has been provided
if (argc != 2) {
hex::log::fatal("Invalid number of arguments specified! {}", argc);
return EXIT_FAILURE;
}
// Check if that test exists
std::string testName = argv[1];
if (!hex::test::Tests::get().contains(testName)) {
hex::log::fatal("No test with name {} found!", testName);
return EXIT_FAILURE;
}
auto test = hex::test::Tests::get()[testName];
auto result = test.function();
if (test.shouldFail) {
switch (result) {
case EXIT_SUCCESS:
return EXIT_FAILURE;
case EXIT_FAILURE:
return EXIT_SUCCESS;
default:
return result;
}
} else {
return result;
}
}
int main(int argc, char **argv) {
int result = test(argc, argv);
if (result == EXIT_SUCCESS)
hex::log::info("Success!");
else
hex::log::info("Failed!");
hex::TaskManager::exit();
hex::EventImHexClosing::post();
hex::EventManager::clear();
hex::PluginManager::unload();
return result;
}
| 1,447
|
C++
|
.cpp
| 48
| 24.020833
| 75
| 0.607631
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
282
|
common.cpp
|
WerWolv_ImHex/tests/helpers/source/common.cpp
|
#include <hex/test/tests.hpp>
#include <hex/test/test_provider.hpp>
#include <hex/helpers/crypto.hpp>
#include <algorithm>
#include <vector>
TEST_SEQUENCE("TestSucceeding") {
TEST_SUCCESS();
};
TEST_SEQUENCE("TestFailing", FAILING) {
TEST_FAIL();
};
TEST_SEQUENCE("TestProvider_read") {
std::vector<u8> data { 0xde, 0xad, 0xbe, 0xef, 0x42, 0x2a, 0x00, 0xff };
hex::test::TestProvider provider(&data);
hex::prv::Provider *provider2 = &provider;
u8 buff[1024];
std::fill(std::begin(buff), std::end(buff), 22);
provider2->read(0, buff + 1, 4);
TEST_ASSERT(buff[0] == 22); // should be unchanged
TEST_ASSERT(buff[1] == 0xde);
TEST_ASSERT(buff[2] == 0xad);
TEST_ASSERT(buff[3] == 0xbe);
TEST_ASSERT(buff[4] == 0xef);
TEST_ASSERT(buff[5] == 22); // should be unchanged
std::fill(std::begin(buff), std::end(buff), 22);
provider2->read(6, buff, 2);
TEST_ASSERT(buff[0] == 0x00);
TEST_ASSERT(buff[1] == 0xff);
TEST_ASSERT(buff[2] == 22); // should be unchanged
std::fill(std::begin(buff), std::end(buff), 22);
provider2->read(7, buff, 2);
TEST_ASSERT(std::count(std::begin(buff), std::end(buff), 22) == std::size(buff)); // buff should be unchanged
TEST_SUCCESS();
};
TEST_SEQUENCE("TestProvider_write") {
std::vector<u8> buff(8);
hex::test::TestProvider provider(&buff);
hex::prv::Provider *provider2 = &provider;
u8 data[1024] = { 0xde, 0xad, 0xbe, 0xef, 0x42, 0x2a, 0x00, 0xff };
std::fill(std::begin(buff), std::end(buff), 22);
provider2->writeRaw(1, data, 4);
TEST_ASSERT(buff[0] == 22); // should be unchanged
TEST_ASSERT(buff[1] == 0xde);
TEST_ASSERT(buff[2] == 0xad);
TEST_ASSERT(buff[3] == 0xbe);
TEST_ASSERT(buff[4] == 0xef);
TEST_ASSERT(buff[5] == 22); // should be unchanged
std::fill(std::begin(buff), std::end(buff), 22);
provider2->writeRaw(0, data + 6, 2);
TEST_ASSERT(buff[0] == 0x00);
TEST_ASSERT(buff[1] == 0xff);
TEST_ASSERT(buff[2] == 22); // should be unchanged
std::fill(std::begin(buff), std::end(buff), 22);
provider2->writeRaw(6, data, 2);
TEST_ASSERT(buff[5] == 22); // should be unchanged
TEST_ASSERT(buff[6] == 0xde);
TEST_ASSERT(buff[7] == 0xad);
std::fill(std::begin(buff), std::end(buff), 22);
provider2->writeRaw(7, data, 2);
TEST_ASSERT(std::count(std::begin(buff), std::end(buff), 22) == std::size(buff)); // buff should be unchanged
TEST_SUCCESS();
};
| 2,519
|
C++
|
.cpp
| 62
| 36.193548
| 116
| 0.622541
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
283
|
net.cpp
|
WerWolv_ImHex/tests/helpers/source/net.cpp
|
#include <hex/test/tests.hpp>
#include <hex/api_urls.hpp>
#include <hex/helpers/http_requests.hpp>
#include <wolv/io/file.hpp>
using namespace std::literals::string_literals;
TEST_SEQUENCE("StoreAPI") {
hex::HttpRequest request("GET", ImHexApiURL + "/store"s);
auto result = request.execute().get();
if (result.getStatusCode() != 200)
TEST_FAIL();
if (result.getData().empty())
TEST_FAIL();
TEST_SUCCESS();
};
TEST_SEQUENCE("TipsAPI") {
hex::HttpRequest request("GET", ImHexApiURL + "/tip"s);
auto result = request.execute().get();
if (result.getStatusCode() != 200)
TEST_FAIL();
if (result.getData().empty())
TEST_FAIL();
TEST_SUCCESS();
};
TEST_SEQUENCE("ContentAPI") {
hex::HttpRequest request("GET", "https://api.werwolv.net/content/imhex/patterns/elf.hexpat");
const auto FilePath = std::fs::current_path() / "elf.hexpat";
auto result = request.downloadFile(FilePath).get();
TEST_ASSERT(result.getStatusCode() == 200);
wolv::io::File file(FilePath, wolv::io::File::Mode::Read);
if (!file.isValid())
TEST_FAIL();
if (file.getSize() == 0)
TEST_FAIL();
TEST_SUCCESS();
};
| 1,212
|
C++
|
.cpp
| 35
| 29.685714
| 97
| 0.646247
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
284
|
file.cpp
|
WerWolv_ImHex/tests/helpers/source/file.cpp
|
#include <hex/test/tests.hpp>
#include <wolv/io/file.hpp>
using namespace std::literals::string_literals;
TEST_SEQUENCE("FileAccess") {
const auto FilePath = std::fs::current_path() / "file.txt";
const auto FileContent = "Hello World";
std::fs::create_directories(FilePath.parent_path());
{
wolv::io::File file(FilePath, wolv::io::File::Mode::Create);
TEST_ASSERT(file.isValid());
file.writeString(FileContent);
}
{
wolv::io::File file(FilePath, wolv::io::File::Mode::Read);
TEST_ASSERT(file.isValid());
TEST_ASSERT(file.readString() == FileContent);
}
{
wolv::io::File file(FilePath, wolv::io::File::Mode::Write);
TEST_ASSERT(file.isValid());
file.remove();
TEST_ASSERT(!file.isValid());
}
{
wolv::io::File file(FilePath, wolv::io::File::Mode::Read);
if (file.isValid())
TEST_FAIL();
}
TEST_SUCCESS();
};
TEST_SEQUENCE("UTF-8 Path") {
const auto FilePath = std::fs::current_path() / u8"读写汉字" / u8"привет.txt";
const auto FileContent = u8"שלום עולם";
std::fs::create_directories(FilePath.parent_path());
{
wolv::io::File file(FilePath, wolv::io::File::Mode::Create);
TEST_ASSERT(file.isValid());
file.writeU8String(FileContent);
}
{
wolv::io::File file(FilePath, wolv::io::File::Mode::Read);
TEST_ASSERT(file.isValid());
TEST_ASSERT(file.readU8String() == FileContent);
}
{
wolv::io::File file(FilePath, wolv::io::File::Mode::Write);
TEST_ASSERT(file.isValid());
file.remove();
TEST_ASSERT(!file.isValid());
}
{
wolv::io::File file(FilePath, wolv::io::File::Mode::Read);
if (file.isValid())
TEST_FAIL();
}
TEST_SUCCESS();
};
| 1,888
|
C++
|
.cpp
| 57
| 25.859649
| 81
| 0.591825
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
285
|
utils.cpp
|
WerWolv_ImHex/tests/helpers/source/utils.cpp
|
#include <hex/test/tests.hpp>
#include <hex/helpers/utils.hpp>
using namespace std::literals::string_literals;
TEST_SEQUENCE("SplitStringAtChar") {
const std::string TestString = "Hello|World|ABCD|Test|";
const std::vector<std::string> TestSplitVector = { "Hello", "World", "ABCD", "Test", "" };
TEST_ASSERT(hex::splitString(TestString, "|") == TestSplitVector);
TEST_SUCCESS();
};
TEST_SEQUENCE("SplitStringAtString") {
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);
TEST_SUCCESS();
};
TEST_SEQUENCE("ExtractBits") {
TEST_ASSERT(hex::extract(11, 4, 0xAABBU) == 0xAB);
TEST_ASSERT(hex::extract(15, 0, 0xAABBU) == 0xAABB);
TEST_ASSERT(hex::extract(35, 20, 0x8899AABBCCDDEEFFU) == 0xBCCD);
TEST_ASSERT(hex::extract(20, 35, 0x8899AABBCCDDEEFFU) == 0xBCCD);
TEST_SUCCESS();
};
| 1,069
|
C++
|
.cpp
| 22
| 44.772727
| 102
| 0.664417
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
286
|
example_plugin.cpp
|
WerWolv_ImHex/cmake/sdk/template/source/example_plugin.cpp
|
#include <hex/plugin.hpp>
// Browse through the headers in lib/libimhex/include/hex/api/ to see what you can do with the API.
// Most important ones are <hex/api/imhex_api.hpp> and <hex/api/content_registry.hpp>
// This is the main entry point of your plugin. The code in the body of this construct will be executed
// when ImHex starts up and loads the plugin.
// The strings in the header are used to display information about the plugin in the UI.
IMHEX_PLUGIN_SETUP("Example Plugin", "Author", "Description") {
// Put your init code here
}
| 549
|
C++
|
.cpp
| 9
| 59.444444
| 103
| 0.755102
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
287
|
main.cpp
|
WerWolv_ImHex/main/updater/source/main.cpp
|
#include <hex/api_urls.hpp>
#include <hex/api/imhex_api.hpp>
#include <hex/helpers/http_requests.hpp>
#include <hex/helpers/utils.hpp>
#include <hex/helpers/default_paths.hpp>
using namespace std::literals::string_literals;
std::string getUpdateUrl(std::string_view versionType, std::string_view operatingSystem) {
// Get the latest version info from the ImHex API
const auto response = hex::HttpRequest("GET",
ImHexApiURL + fmt::format("/update/{}/{}",
versionType,
operatingSystem
)
).execute().get();
const auto &data = response.getData();
// Make sure we got a valid response
if (!response.isSuccess()) {
hex::log::error("Failed to get latest version info: ({}) {}", response.getStatusCode(), data);
return { };
}
return data;
}
std::optional<std::fs::path> downloadUpdate(const std::string &url) {
// Download the update
const auto response = hex::HttpRequest("GET", url).downloadFile().get();
// Make sure we got a valid response
if (!response.isSuccess()) {
hex::log::error("Failed to download update");
return std::nullopt;
}
const auto &data = response.getData();
// Write the update to a file
std::fs::path filePath;
{
constexpr static auto UpdateFileName = "update.hexupd";
// Loop over all available paths
wolv::io::File file;
for (const auto &path : hex::paths::Config.write()) {
// Remove any existing update files
wolv::io::fs::remove(path / UpdateFileName);
// If a valid location hasn't been found already, try to create a new file
if (!file.isValid())
file = wolv::io::File(path / UpdateFileName, wolv::io::File::Mode::Create);
}
// If the update data can't be written to any of the default paths, the update cannot continue
if (!file.isValid()) {
hex::log::error("Failed to create update file");
return std::nullopt;
}
hex::log::info("Writing update to file: {}", file.getPath().string());
// Write the downloaded update data to the file
file.writeVector(data);
// Save the path to the update file
filePath = file.getPath();
}
return filePath;
}
std::string getUpdateType() {
#if defined (OS_WINDOWS)
if (!hex::ImHexApi::System::isPortableVersion())
return "win-msi";
#elif defined (OS_MACOS)
return "mac-dmg";
#elif defined (OS_LINUX)
if (hex::executeCommand("lsb_release -a | grep Ubuntu") == 0) {
if (hex::executeCommand("lsb_release -a | grep 22.") == 0)
return "linux-deb-22.04";
else if (hex::executeCommand("lsb_release -a | grep 23.") == 0)
return "linux-deb-23.04";
}
#endif
return "";
}
int installUpdate(const std::string &type, std::fs::path updatePath) {
struct UpdateHandler {
const char *type;
const char *extension;
const char *command;
};
constexpr static auto UpdateHandlers = {
UpdateHandler { "win-msi", ".msi", "msiexec /passive /package {}" },
UpdateHandler { "macos-dmg", ".dmg", "hdiutil attach {}" },
UpdateHandler { "linux-deb-22.04", ".deb", "sudo apt update && sudo apt install -y --fix-broken {}" },
UpdateHandler { "linux-deb-23.04", ".deb", "sudo apt update && sudo apt install -y --fix-broken {}" },
};
for (const auto &handler : UpdateHandlers) {
if (type == handler.type) {
// Rename the update file to the correct extension
const auto originalPath = updatePath;
updatePath.replace_extension(handler.extension);
hex::log::info("Moving update package from {} to {}", originalPath.string(), updatePath.string());
std::fs::rename(originalPath, updatePath);
// Install the update using the correct command
const auto command = hex::format(handler.command, updatePath.string());
hex::log::info("Starting update process with command: '{}'", command);
hex::startProgram(command);
return EXIT_SUCCESS;
}
}
// If the installation type isn't handled here, the detected installation type doesn't support updates through the updater
hex::log::error("Install type cannot be updated");
// Open the latest release page in the default browser to allow the user to manually update
hex::openWebpage("https://github.com/WerWolv/ImHex/releases/latest");
return EXIT_FAILURE;
}
int main(int argc, char **argv) {
hex::log::impl::enableColorPrinting();
// Check we have the correct number of arguments
if (argc != 2) {
hex::log::error("Failed to start updater: Invalid arguments");
return EXIT_FAILURE;
}
// Read the version type from the arguments
const auto versionType = argv[1];
hex::log::info("Updater started with version type: {}", versionType);
// Query the update type
const auto updateType = getUpdateType();
hex::log::info("Detected OS String: {}", updateType);
// Make sure we got a valid update type
if (updateType.empty()) {
hex::log::error("Failed to detect installation type");
return EXIT_FAILURE;
}
// Get the url to the requested update from the ImHex API
const auto updateUrl = getUpdateUrl(versionType, updateType);
if (updateUrl.empty()) {
hex::log::error("Failed to get update URL");
return EXIT_FAILURE;
}
hex::log::info("Update URL found: {}", updateUrl);
// Download the update file
const auto updatePath = downloadUpdate(updateUrl);
if (!updatePath.has_value())
return EXIT_FAILURE;
hex::log::info("Downloaded update successfully");
// Install the update
return installUpdate(updateType, *updatePath);
}
| 6,259
|
C++
|
.cpp
| 138
| 36.347826
| 126
| 0.59954
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
288
|
main.cpp
|
WerWolv_ImHex/main/forwarder/source/main.cpp
|
/**
* This is a simple forwarder that launches the main ImHex executable with the
* same command line as the current process. The reason for this is that even
* though ImHex is a GUI application in general, it also has a command line
* interface that can be used to perform various tasks. The issue with this is
* that kernel32 will automatically allocate a console for us which will float
* around in the background if we launch ImHex from the explorer. This forwarder
* will get rid of the console window if ImHex was launched from the explorer and
* enables ANSI escape sequences if ImHex was launched from the command line.
*
* The main reason this is done in a separate executable is because we use FreeConsole()
* to get rid of the console window. Due to bugs in older versions of Windows (Windows 10 and older)
* this will also close the process's standard handles (stdin, stdout, stderr) in
* a way that cannot be recovered from. This means that if we were to do this in the
* main application, if any code would try to interact with these handles (duplicate them
* or modify them in any way), the application would crash.
*
* None of this would be necessary if Windows had a third type of application (besides
* console and GUI) that would act like a console application but would not allocate
* a console window. This would allow us to have a single executable that would work
* the same as on all other platforms. There are plans to add this to Windows in the
* future, but it is not yet available. Also even if it was available, it would not
* be available on older versions of Windows, so we would still need this forwarder
*/
#include <windows.h>
#include <wolv/io/fs.hpp>
#include <fmt/format.h>
void setupConsoleWindow() {
// Get the handle of the console window
HWND consoleWindow = ::GetConsoleWindow();
// Get console process ID
DWORD processId = 0;
::GetWindowThreadProcessId(consoleWindow, &processId);
// Check if ImHex was launched from the explorer or from the command line
if (::GetCurrentProcessId() == processId) {
// If it was launched from the explorer, kernel32 has allocated a console for us
// Get rid of it to avoid having a useless console window floating around
::FreeConsole();
} else {
// If it was launched from the command line, enable ANSI escape sequences to have colored output
auto hConsole = ::GetStdHandle(STD_OUTPUT_HANDLE);
if (hConsole != INVALID_HANDLE_VALUE) {
DWORD mode = 0;
if (::GetConsoleMode(hConsole, &mode) == TRUE) {
mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING | ENABLE_PROCESSED_OUTPUT;
::SetConsoleMode(hConsole, mode);
}
}
// Set the __IMHEX_FORWARD_CONSOLE__ environment variable,
// to let ImHex know that it was launched from the forwarder
// and that it should forward it's console output to us
::SetEnvironmentVariableA("__IMHEX_FORWARD_CONSOLE__", "1");
}
}
int launchExecutable() {
// Get the path of the main ImHex executable
auto executablePath = wolv::io::fs::getExecutablePath();
auto executableFullPath = executablePath->parent_path() / "imhex-gui.exe";
::PROCESS_INFORMATION process = { };
::STARTUPINFOW startupInfo = { .cb = sizeof(::STARTUPINFOW) };
// Create a new process for imhex-gui.exe with the same command line as the current process
if (::CreateProcessW(executableFullPath.wstring().c_str(), ::GetCommandLineW(), nullptr, nullptr, FALSE, 0, nullptr, nullptr, &startupInfo, &process) == FALSE) {
// Handle error if the process could not be created
// Get formatted error message from the OS
auto errorCode = ::GetLastError();
auto errorMessageString = std::system_category().message(int(errorCode));
// Generate error message
auto errorMessage = fmt::format("Failed to start ImHex:\n\nError code: 0x{:08X}\n\n{}", errorCode, errorMessageString);
// Display a message box with the error
::MessageBoxA(nullptr, errorMessage.c_str(), "ImHex Forwarder", MB_OK | MB_ICONERROR);
return EXIT_FAILURE;
}
// Wait for the main ImHex process to exit
::WaitForSingleObject(process.hProcess, INFINITE);
::CloseHandle(process.hProcess);
return EXIT_SUCCESS;
}
int main() {
setupConsoleWindow();
return launchExecutable();
}
| 4,454
|
C++
|
.cpp
| 81
| 49.555556
| 165
| 0.712646
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
289
|
stacktrace.cpp
|
WerWolv_ImHex/main/gui/source/stacktrace.cpp
|
#include <stacktrace.hpp>
#include <hex/helpers/fmt.hpp>
#include <array>
#include <llvm/Demangle/Demangle.h>
namespace {
[[maybe_unused]] std::string tryDemangle(const std::string &symbolName) {
if (auto variant1 = llvm::demangle(symbolName); variant1 != symbolName)
return variant1;
if (auto variant2 = llvm::demangle(std::string("_") + symbolName); variant2 != std::string("_") + symbolName)
return variant2;
return symbolName;
}
}
#if defined(OS_WINDOWS)
#include <windows.h>
#include <dbghelp.h>
namespace hex::stacktrace {
void initialize() {
}
StackTraceResult getStackTrace() {
std::vector<StackFrame> stackTrace;
HANDLE process = GetCurrentProcess();
HANDLE thread = GetCurrentThread();
CONTEXT context = {};
context.ContextFlags = CONTEXT_FULL;
RtlCaptureContext(&context);
SymSetOptions(SYMOPT_CASE_INSENSITIVE | SYMOPT_UNDNAME | SYMOPT_LOAD_LINES | SYMOPT_LOAD_ANYTHING);
SymInitialize(process, nullptr, TRUE);
DWORD image;
STACKFRAME64 stackFrame;
ZeroMemory(&stackFrame, sizeof(STACKFRAME64));
image = IMAGE_FILE_MACHINE_AMD64;
stackFrame.AddrPC.Offset = context.Rip;
stackFrame.AddrPC.Mode = AddrModeFlat;
stackFrame.AddrFrame.Offset = context.Rsp;
stackFrame.AddrFrame.Mode = AddrModeFlat;
stackFrame.AddrStack.Offset = context.Rsp;
stackFrame.AddrStack.Mode = AddrModeFlat;
while (true) {
if (StackWalk64(
image, process, thread,
&stackFrame, &context, nullptr,
SymFunctionTableAccess64, SymGetModuleBase64, nullptr) == FALSE)
break;
if (stackFrame.AddrReturn.Offset == stackFrame.AddrPC.Offset)
break;
std::array<char, sizeof(SYMBOL_INFO) + MAX_SYM_NAME * sizeof(TCHAR)> buffer = {};
auto symbol = reinterpret_cast<PSYMBOL_INFO>(buffer.data());
symbol->SizeOfStruct = sizeof(SYMBOL_INFO);
symbol->MaxNameLen = MAX_SYM_NAME;
DWORD64 displacementSymbol = 0;
const char *symbolName;
if (SymFromAddr(process, stackFrame.AddrPC.Offset, &displacementSymbol, symbol) == TRUE) {
symbolName = symbol->Name;
} else {
symbolName = "??";
}
SymSetOptions(SYMOPT_LOAD_LINES);
IMAGEHLP_LINE64 line;
line.SizeOfStruct = sizeof(IMAGEHLP_LINE64);
DWORD displacementLine = 0;
u32 lineNumber = 0;
const char *fileName;
if (SymGetLineFromAddr64(process, stackFrame.AddrPC.Offset, &displacementLine, &line) == TRUE) {
lineNumber = line.LineNumber;
fileName = line.FileName;
} else {
lineNumber = 0;
fileName = "??";
}
auto demangledName = tryDemangle(symbolName);
stackTrace.push_back(StackFrame { fileName, demangledName, lineNumber });
}
SymCleanup(process);
return StackTraceResult{ stackTrace, "StackWalk" };
}
}
#elif defined(HEX_HAS_EXECINFO)
#if __has_include(BACKTRACE_HEADER)
#include BACKTRACE_HEADER
#include <hex/helpers/utils.hpp>
#include <dlfcn.h>
namespace hex::stacktrace {
void initialize() {
}
StackTraceResult getStackTrace() {
static std::vector<StackFrame> result;
std::array<void*, 128> addresses = {};
const size_t count = backtrace(addresses.data(), addresses.size());
Dl_info info;
for (size_t i = 0; i < count; i += 1) {
dladdr(addresses[i], &info);
auto fileName = info.dli_fname != nullptr ? std::fs::path(info.dli_fname).filename().string() : "??";
auto demangledName = info.dli_sname != nullptr ? tryDemangle(info.dli_sname) : "??";
result.push_back(StackFrame { std::move(fileName), std::move(demangledName), 0 });
}
return StackTraceResult{ result, "execinfo" };
}
}
#endif
#elif defined(HEX_HAS_BACKTRACE)
#if __has_include(BACKTRACE_HEADER)
#include BACKTRACE_HEADER
#include <hex/helpers/logger.hpp>
#include <hex/helpers/utils.hpp>
namespace hex::stacktrace {
static struct backtrace_state *s_backtraceState;
void initialize() {
if (auto executablePath = wolv::io::fs::getExecutablePath(); executablePath.has_value()) {
static std::string path = executablePath->string();
s_backtraceState = backtrace_create_state(path.c_str(), 1, [](void *, const char *msg, int) { log::error("{}", msg); }, nullptr);
}
}
StackTraceResult getStackTrace() {
static std::vector<StackFrame> result;
result.clear();
if (s_backtraceState != nullptr) {
backtrace_full(s_backtraceState, 0, [](void *, uintptr_t, const char *fileName, int lineNumber, const char *function) -> int {
if (fileName == nullptr)
fileName = "??";
if (function == nullptr)
function = "??";
result.push_back(StackFrame { std::fs::path(fileName).filename().string(), tryDemangle(function), u32(lineNumber) });
return 0;
}, nullptr, nullptr);
}
return StackTraceResult{ result, "backtrace" };
}
}
#endif
#else
namespace hex::stacktrace {
void initialize() { }
StackTraceResult getStackTrace() {
return StackTraceResult {
{StackFrame { "??", "Stacktrace collecting not available!", 0 }},
"none"
};
}
}
#endif
| 6,435
|
C++
|
.cpp
| 141
| 31.553191
| 149
| 0.544389
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
290
|
main.cpp
|
WerWolv_ImHex/main/gui/source/main.cpp
|
#include <hex.hpp>
#include <hex/helpers/logger.hpp>
#include "window.hpp"
#include "init/splash_window.hpp"
#include "crash_handlers.hpp"
#include <hex/api/task_manager.hpp>
#include <hex/api/plugin_manager.hpp>
namespace hex::init {
int runImHex();
void runCommandLine(int argc, char **argv);
}
/**
* @brief Main entry point of ImHex
* @param argc Argument count
* @param argv Argument values
* @return Exit code
*/
int main(int argc, char **argv) {
using namespace hex;
// Set the main thread's name to "Main"
TaskManager::setCurrentThreadName("Main");
// Setup crash handlers right away to catch crashes as early as possible
crash::setupCrashHandlers();
// Run platform-specific initialization code
Window::initNative();
// Handle command line arguments if any have been passed
if (argc > 1) {
init::runCommandLine(argc, argv);
}
// Log some system information to aid debugging when users share their logs
log::info("Welcome to ImHex {}!", ImHexApi::System::getImHexVersion());
log::info("Compiled using commit {}@{}", ImHexApi::System::getCommitBranch(), ImHexApi::System::getCommitHash());
log::info("Running on {} {} ({})", ImHexApi::System::getOSName(), ImHexApi::System::getOSVersion(), ImHexApi::System::getArchitecture());
#if defined(OS_LINUX)
auto distro = ImHexApi::System::getLinuxDistro().value();
log::info("Linux distribution: {}. Version: {}", distro.name, distro.version == "" ? "None" : distro.version);
#endif
// Run ImHex
return init::runImHex();
}
| 1,587
|
C++
|
.cpp
| 40
| 35.8
| 141
| 0.695369
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
291
|
crash_handlers.cpp
|
WerWolv_ImHex/main/gui/source/crash_handlers.cpp
|
#include <hex/api/project_file_manager.hpp>
#include <hex/api/task_manager.hpp>
#include <hex/api/workspace_manager.hpp>
#include <hex/helpers/logger.hpp>
#include <hex/helpers/fs.hpp>
#include <hex/helpers/default_paths.hpp>
#include <wolv/utils/string.hpp>
#include <window.hpp>
#include <init/tasks.hpp>
#include <stacktrace.hpp>
#include <llvm/Demangle/Demangle.h>
#include <nlohmann/json.hpp>
#include <csignal>
#include <exception>
#include <typeinfo>
#if defined (OS_MACOS)
#include <sys/utsname.h>
#endif
namespace hex::crash {
constexpr static auto CrashBackupFileName = "crash_backup.hexproj";
constexpr static auto Signals = { SIGSEGV, SIGILL, SIGABRT, SIGFPE };
void resetCrashHandlers();
static void sendNativeMessage(const std::string& message) {
hex::nativeErrorMessage(hex::format("ImHex crashed during initial setup!\nError: {}", message));
}
// Function that decides what should happen on a crash
// (either sending a message or saving a crash file, depending on when the crash occurred)
using CrashCallback = void (*) (const std::string&);
static CrashCallback crashCallback = sendNativeMessage;
static void saveCrashFile(const std::string& message) {
log::fatal(message);
nlohmann::json crashData {
{ "logFile", wolv::io::fs::toNormalizedPathString(hex::log::impl::getFile().getPath()) },
{ "project", wolv::io::fs::toNormalizedPathString(ProjectFile::getPath()) },
};
for (const auto &path : paths::Config.write()) {
wolv::io::File file(path / "crash.json", wolv::io::File::Mode::Create);
if (file.isValid()) {
file.writeString(crashData.dump(4));
file.close();
log::info("Wrote crash.json file to {}", wolv::util::toUTF8String(file.getPath()));
return;
}
}
log::warn("Could not write crash.json file!");
}
static void printStackTrace() {
auto stackTraceResult = stacktrace::getStackTrace();
log::fatal("Printing stacktrace using implementation '{}'", stackTraceResult.implementationName);
for (const auto &stackFrame : stackTraceResult.stackFrames) {
if (stackFrame.line == 0)
log::fatal(" ({}) | {}", stackFrame.file, stackFrame.function);
else
log::fatal(" ({}:{}) | {}", stackFrame.file, stackFrame.line, stackFrame.function);
}
}
extern "C" void triggerSafeShutdown(int signalNumber = 0) {
// Trigger an event so that plugins can handle crashes
EventAbnormalTermination::post(signalNumber);
// Run exit tasks
init::runExitTasks();
// Terminate all asynchronous tasks
TaskManager::exit();
// Trigger a breakpoint if we're in a debug build or raise the signal again for the default handler to handle it
#if defined(DEBUG)
static bool breakpointTriggered = false;
if (!breakpointTriggered) {
breakpointTriggered = true;
#if defined(OS_WINDOWS)
__debugbreak();
#else
raise(SIGTRAP);
#endif
}
std::exit(signalNumber);
#else
if (signalNumber == 0)
std::abort();
else
std::exit(signalNumber);
#endif
}
void handleCrash(const std::string &msg) {
// Call the crash callback
crashCallback(msg);
// Print the stacktrace to the console or log file
printStackTrace();
// Flush all streams
fflush(stdout);
fflush(stderr);
}
// Custom signal handler to print various information and a stacktrace when the application crashes
static void signalHandler(int signalNumber, const std::string &signalName) {
#if !defined (DEBUG)
if (signalNumber == SIGINT) {
ImHexApi::System::closeImHex();
return;
}
#endif
// Reset crash handlers, so we can't have a recursion if this code crashes
resetCrashHandlers();
// Actually handle the crash
handleCrash(hex::format("Received signal '{}' ({})", signalName, signalNumber));
// Detect if the crash was due to an uncaught exception
if (std::uncaught_exceptions() > 0) {
log::fatal("Uncaught exception thrown!");
}
triggerSafeShutdown(signalNumber);
}
static void uncaughtExceptionHandler() {
// Reset crash handlers, so we can't have a recursion if this code crashes
resetCrashHandlers();
// Print the current exception info
try {
std::rethrow_exception(std::current_exception());
} catch (std::exception &ex) {
std::string exceptionStr = hex::format("{}()::what() -> {}", llvm::itaniumDemangle(typeid(ex).name()), ex.what());
handleCrash(exceptionStr);
log::fatal("Program terminated with uncaught exception: {}", exceptionStr);
}
triggerSafeShutdown();
}
// Setup functions to handle signals, uncaught exception, or similar stuff that will crash ImHex
void setupCrashHandlers() {
stacktrace::initialize();
// Register signal handlers
{
#define HANDLE_SIGNAL(name) \
std::signal(name, [](int signalNumber) { \
signalHandler(signalNumber, #name); \
})
HANDLE_SIGNAL(SIGSEGV);
HANDLE_SIGNAL(SIGILL);
HANDLE_SIGNAL(SIGABRT);
HANDLE_SIGNAL(SIGFPE);
HANDLE_SIGNAL(SIGINT);
#if defined (SIGBUS)
HANDLE_SIGNAL(SIGBUS);
#endif
#undef HANDLE_SIGNAL
}
// Configure the uncaught exception handler
std::set_terminate(uncaughtExceptionHandler);
// Save a backup project when the application crashes
// We need to save the project no mater if it is dirty,
// because this save is responsible for telling us which files
// were opened in case there wasn't a project
// Only do it when ImHex has finished its loading
EventImHexStartupFinished::subscribe([] {
EventAbnormalTermination::subscribe([](int) {
WorkspaceManager::exportToFile();
// Create crash backup if any providers are open
if (ImHexApi::Provider::isValid()) {
for (const auto &path : paths::Config.write()) {
if (ProjectFile::store(path / CrashBackupFileName, false))
break;
}
}
});
});
// Change the crash callback when ImHex has finished startup
EventImHexStartupFinished::subscribe([]{
crashCallback = saveCrashFile;
});
}
void resetCrashHandlers() {
std::set_terminate(nullptr);
for (auto signal : Signals)
std::signal(signal, SIG_DFL);
}
}
| 7,206
|
C++
|
.cpp
| 171
| 32.076023
| 126
| 0.60261
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
292
|
linux.cpp
|
WerWolv_ImHex/main/gui/source/messaging/linux.cpp
|
#if defined(OS_LINUX)
#include <stdexcept>
#include <hex/helpers/intrinsics.hpp>
#include <hex/helpers/logger.hpp>
#include "messaging.hpp"
namespace hex::messaging {
void sendToOtherInstance(const std::string &eventName, const std::vector<u8> &args) {
hex::unused(eventName);
hex::unused(args);
log::error("Unimplemented function 'sendToOtherInstance()' called");
}
// Not implemented, so lets say we are the main instance every time so events are forwarded to ourselves
bool setupNative() {
return true;
}
}
#endif
| 580
|
C++
|
.cpp
| 17
| 29.411765
| 108
| 0.710145
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
293
|
macos.cpp
|
WerWolv_ImHex/main/gui/source/messaging/macos.cpp
|
#if defined(OS_MACOS)
#include <stdexcept>
#include <hex/helpers/intrinsics.hpp>
#include <hex/helpers/logger.hpp>
#include "messaging.hpp"
namespace hex::messaging {
void sendToOtherInstance(const std::string &eventName, const std::vector<u8> &args) {
hex::unused(eventName);
hex::unused(args);
log::error("Unimplemented function 'sendToOtherInstance()' called");
}
// Not implemented, so lets say we are the main instance every time so events are forwarded to ourselves
bool setupNative() {
return true;
}
}
#endif
| 576
|
C++
|
.cpp
| 17
| 29.411765
| 108
| 0.710145
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
294
|
common.cpp
|
WerWolv_ImHex/main/gui/source/messaging/common.cpp
|
#include <optional>
#include <hex/api/imhex_api.hpp>
#include <hex/api/event_manager.hpp>
#include <hex/helpers/logger.hpp>
#include "messaging.hpp"
namespace hex::messaging {
void messageReceived(const std::string &eventName, const std::vector<u8> &args) {
log::debug("Received event '{}' with size {}", eventName, args.size());
ImHexApi::Messaging::impl::runHandler(eventName, args);
}
void setupEvents() {
SendMessageToMainInstance::subscribe([](const std::string &eventName, const std::vector<u8> &eventData) {
if (ImHexApi::System::isMainInstance()) {
log::debug("Executing message '{}' in current instance", eventName);
EventImHexStartupFinished::subscribe([eventName, eventData]{
ImHexApi::Messaging::impl::runHandler(eventName, eventData);
});
} else {
log::debug("Forwarding message '{}' to existing instance", eventName);
sendToOtherInstance(eventName, eventData);
}
});
}
void setupMessaging() {
ImHexApi::System::impl::setMainInstanceStatus(setupNative());
setupEvents();
}
}
| 1,202
|
C++
|
.cpp
| 28
| 34.285714
| 113
| 0.629281
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
295
|
win.cpp
|
WerWolv_ImHex/main/gui/source/messaging/win.cpp
|
#if defined(OS_WINDOWS)
#include "messaging.hpp"
#include <hex/helpers/logger.hpp>
#include <windows.h>
namespace hex::messaging {
std::optional<HWND> getImHexWindow() {
HWND imhexWindow = nullptr;
::EnumWindows([](HWND hWnd, LPARAM ret) -> BOOL {
// Get the window name
auto length = ::GetWindowTextLength(hWnd);
std::string windowName(length + 1, '\x00');
::GetWindowTextA(hWnd, windowName.data(), windowName.size());
// Check if the window is visible and if it's an ImHex window
if (::IsWindowVisible(hWnd) == TRUE && length != 0) {
if (windowName.starts_with("ImHex")) {
// It's our window, return it and stop iteration
*reinterpret_cast<HWND*>(ret) = hWnd;
return FALSE;
}
}
// Continue iteration
return TRUE;
}, reinterpret_cast<LPARAM>(&imhexWindow));
if (imhexWindow == nullptr)
return { };
else
return imhexWindow;
}
void sendToOtherInstance(const std::string &eventName, const std::vector<u8> &args) {
log::debug("Sending event {} to another instance (not us)", eventName);
// Get the window we want to send it to
HWND imHexWindow = *getImHexWindow();
// Create the message
std::vector<u8> fulleventData(eventName.begin(), eventName.end());
fulleventData.push_back('\0');
fulleventData.insert(fulleventData.end(), args.begin(), args.end());
u8 *data = &fulleventData[0];
DWORD dataSize = fulleventData.size();
COPYDATASTRUCT message = {
.dwData = 0,
.cbData = dataSize,
.lpData = data
};
// Send the message
SendMessage(imHexWindow, WM_COPYDATA, reinterpret_cast<WPARAM>(imHexWindow), reinterpret_cast<LPARAM>(&message));
}
bool setupNative() {
constexpr static auto UniqueMutexId = L"ImHex/a477ea68-e334-4d07-a439-4f159c683763";
// Check if an ImHex instance is already running by opening a global mutex
HANDLE globalMutex = OpenMutexW(MUTEX_ALL_ACCESS, FALSE, UniqueMutexId);
if (globalMutex == nullptr) {
// If no ImHex instance is running, create a new global mutex
globalMutex = CreateMutexW(nullptr, FALSE, UniqueMutexId);
return true;
} else {
return false;
}
}
}
#endif
| 2,551
|
C++
|
.cpp
| 60
| 32.133333
| 121
| 0.595024
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
296
|
web.cpp
|
WerWolv_ImHex/main/gui/source/messaging/web.cpp
|
#if defined(OS_WEB)
#include <stdexcept>
#include <hex/helpers/intrinsics.hpp>
#include <hex/helpers/logger.hpp>
#include "messaging.hpp"
namespace hex::messaging {
void sendToOtherInstance(const std::string &eventName, const std::vector<u8> &args) {
hex::unused(eventName);
hex::unused(args);
log::error("Unimplemented function 'sendToOtherInstance()' called");
}
// Not implemented, so lets say we are the main instance every time so events are forwarded to ourselves
bool setupNative() {
return true;
}
}
#endif
| 578
|
C++
|
.cpp
| 17
| 29.294118
| 108
| 0.709091
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
297
|
splash_window.cpp
|
WerWolv_ImHex/main/gui/source/init/splash_window.cpp
|
#include "window.hpp"
#include "init/splash_window.hpp"
#include <hex/api/imhex_api.hpp>
#include <hex/api/event_manager.hpp>
#include <hex/helpers/utils.hpp>
#include <hex/helpers/fmt.hpp>
#include <hex/helpers/logger.hpp>
#include <fmt/chrono.h>
#include <romfs/romfs.hpp>
#include <imgui.h>
#include <imgui_internal.h>
#include <hex/ui/imgui_imhex_extensions.h>
#include <imgui_impl_glfw.h>
#include <imgui_impl_opengl3.h>
#include <GLFW/glfw3.h>
#include <opengl_support.h>
#include <wolv/utils/guards.hpp>
#include <future>
#include <numeric>
#include <random>
#include <hex/api/task_manager.hpp>
#include <nlohmann/json.hpp>
using namespace std::literals::chrono_literals;
namespace hex::init {
struct GlfwError {
int errorCode = 0;
std::string desc;
};
GlfwError lastGlfwError;
WindowSplash::WindowSplash() : m_window(nullptr) {
this->initGLFW();
this->initImGui();
this->loadAssets();
{
auto glVendor = reinterpret_cast<const char *>(glGetString(GL_VENDOR));
auto glRenderer = reinterpret_cast<const char *>(glGetString(GL_RENDERER));
auto glVersion = reinterpret_cast<const char *>(glGetString(GL_VERSION));
auto glShadingLanguageVersion = reinterpret_cast<const char *>(glGetString(GL_SHADING_LANGUAGE_VERSION));
log::debug("OpenGL Vendor: '{}'", glVendor);
log::debug("OpenGL Renderer: '{}'", glRenderer);
log::debug("OpenGL Version: '{}'", glVersion);
log::debug("OpenGL Shading Language Version: '{}'", glShadingLanguageVersion);
ImHexApi::System::impl::setGPUVendor(glVendor);
ImHexApi::System::impl::setGLRenderer(glRenderer);
}
RequestAddInitTask::subscribe([this](const std::string& name, bool async, const TaskFunction &function){
m_tasks.push_back(Task{ name, function, async });
});
}
WindowSplash::~WindowSplash() {
this->exitImGui();
this->exitGLFW();
}
static void centerWindow(GLFWwindow *window) {
// Get the primary monitor
GLFWmonitor *monitor = glfwGetPrimaryMonitor();
if (!monitor)
return;
// Get information about the monitor
const GLFWvidmode *mode = glfwGetVideoMode(monitor);
if (!mode)
return;
// Get the position of the monitor's viewport on the virtual screen
int monitorX, monitorY;
glfwGetMonitorPos(monitor, &monitorX, &monitorY);
// Get the window size
int windowWidth, windowHeight;
glfwGetWindowSize(window, &windowWidth, &windowHeight);
// Center the splash screen on the monitor
glfwSetWindowPos(window, monitorX + (mode->width - windowWidth) / 2, monitorY + (mode->height - windowHeight) / 2);
}
static ImColor getHighlightColor(u32 index) {
static auto highlightConfig = nlohmann::json::parse(romfs::get("splash_colors.json").string());
static std::list<nlohmann::json> selectedConfigs;
static nlohmann::json selectedConfig;
static std::mt19937 random(std::random_device{}());
if (selectedConfigs.empty()) {
const auto now = []{
const auto now = std::chrono::system_clock::now();
const auto time = std::chrono::system_clock::to_time_t(now);
return fmt::localtime(time);
}();
for (const auto &colorConfig : highlightConfig) {
if (!colorConfig.contains("time")) {
selectedConfigs.push_back(colorConfig);
} else {
const auto &time = colorConfig["time"];
const auto &start = time["start"];
const auto &end = time["end"];
if ((now.tm_mon + 1) >= start[0] && (now.tm_mon + 1) <= end[0]) {
if (now.tm_mday >= start[1] && now.tm_mday <= end[1]) {
selectedConfigs.push_back(colorConfig);
}
}
}
}
// Remove the default color theme if there's another one available
if (selectedConfigs.size() != 1)
selectedConfigs.erase(selectedConfigs.begin());
selectedConfig = *std::next(selectedConfigs.begin(), random() % selectedConfigs.size());
log::debug("Using '{}' highlight color theme", selectedConfig["name"].get<std::string>());
}
const auto colorString = selectedConfig["colors"][index % selectedConfig["colors"].size()].get<std::string>();
if (colorString == "random") {
float r, g, b;
ImGui::ColorConvertHSVtoRGB(
float(random() % 360) / 100.0F,
float(25 + random() % 70) / 100.0F,
float(85 + random() % 10) / 100.0F,
r, g, b);
return { r, g, b, 0x50 / 255.0F };
} else if (colorString.starts_with("#")) {
u32 color = std::strtoul(colorString.substr(1).c_str(), nullptr, 16);
return IM_COL32((color >> 16) & 0xFF, (color >> 8) & 0xFF, color & 0xFF, 0x50);
} else {
log::error("Invalid color string '{}'", colorString);
return IM_COL32(0xFF, 0x00, 0xFF, 0xFF);
}
}
void WindowSplash::createTask(const Task& task) {
auto runTask = [&, task] {
try {
// Save an iterator to the current task name
decltype(m_currTaskNames)::iterator taskNameIter;
{
std::lock_guard guard(m_progressMutex);
m_currTaskNames.push_back(task.name + "...");
taskNameIter = std::prev(m_currTaskNames.end());
}
// When the task finished, increment the progress bar
ON_SCOPE_EXIT {
m_completedTaskCount += 1;
m_progress = float(m_completedTaskCount) / float(m_totalTaskCount);
};
// Execute the actual task and track the amount of time it took to run
auto startTime = std::chrono::high_resolution_clock::now();
bool taskStatus = task.callback();
auto endTime = std::chrono::high_resolution_clock::now();
auto milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime).count();
if (taskStatus)
log::info("Task '{}' finished successfully in {} ms", task.name, milliseconds);
else
log::warn("Task '{}' finished unsuccessfully in {} ms", task.name, milliseconds);
// Track the overall status of the tasks
m_taskStatus = m_taskStatus && taskStatus;
// Erase the task name from the list of running tasks
{
std::lock_guard guard(m_progressMutex);
m_currTaskNames.erase(taskNameIter);
}
} catch (const std::exception &e) {
log::error("Init task '{}' threw an exception: {}", task.name, e.what());
m_taskStatus = false;
} catch (...) {
log::error("Init task '{}' threw an unidentifiable exception", task.name);
m_taskStatus = false;
}
};
m_totalTaskCount += 1;
// If the task can be run asynchronously, run it in a separate thread
// otherwise run it in this thread and wait for it to finish
if (task.async) {
std::thread([name = task.name, runTask = std::move(runTask)] {
TaskManager::setCurrentThreadName(name);
runTask();
}).detach();
} else {
runTask();
}
}
std::future<bool> WindowSplash::processTasksAsync() {
return std::async(std::launch::async, [this] {
TaskManager::setCurrentThreadName("Init Tasks");
auto startTime = std::chrono::high_resolution_clock::now();
// Loop over all registered init tasks
for (auto it = m_tasks.begin(); it != m_tasks.end(); ++it) {
// Construct a new task callback
this->createTask(*it);
}
// Check every 100ms if all tasks have run
while (true) {
{
std::scoped_lock lock(m_tasksMutex);
if (m_completedTaskCount >= m_totalTaskCount)
break;
}
std::this_thread::sleep_for(100ms);
}
auto endTime = std::chrono::high_resolution_clock::now();
auto milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime).count();
log::info("ImHex fully started in {}ms", milliseconds);
// Small extra delay so the last progress step is visible
std::this_thread::sleep_for(100ms);
return m_taskStatus.load();
});
}
FrameResult WindowSplash::fullFrame() {
glfwSetWindowSize(m_window, 640, 400);
centerWindow(m_window);
glfwPollEvents();
// Start a new ImGui frame
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
// Draw the splash screen background
auto drawList = ImGui::GetBackgroundDrawList();
{
// Draw the splash screen background
drawList->AddImage(this->m_splashBackgroundTexture, ImVec2(0, 0), this->m_splashBackgroundTexture.getSize());
{
// Function to highlight a given number of bytes at a position in the splash screen
const auto highlightBytes = [&](ImVec2 start, size_t count, ImColor color, float opacity) {
// Dimensions and number of bytes that are drawn. Taken from the splash screen image
const auto hexSize = ImVec2(29, 18);
const auto hexSpacing = ImVec2(17.4, 15);
const auto hexStart = ImVec2(27, 127);
constexpr auto HexCount = ImVec2(13, 7);
bool isStart = true;
color.Value.w *= opacity;
// Loop over all the bytes on the splash screen
for (u32 y = u32(start.y); y < u32(HexCount.y); y += 1) {
for (u32 x = u32(start.x); x < u32(HexCount.x); x += 1) {
if (count-- == 0)
return;
// Find the start position of the byte to draw
auto pos = hexStart + ImVec2(float(x), float(y)) * (hexSize + hexSpacing);
// Fill the rectangle in the byte with the given color
drawList->AddRectFilled(pos + ImVec2(0, -hexSpacing.y / 2), pos + hexSize + ImVec2(0, hexSpacing.y / 2), color);
// Add some extra color on the right if the current byte isn't the last byte, and we didn't reach the right side of the image
if (count > 0 && x != u32(HexCount.x) - 1)
drawList->AddRectFilled(pos + ImVec2(hexSize.x, -hexSpacing.y / 2), pos + hexSize + ImVec2(hexSpacing.x, hexSpacing.y / 2), color);
// Add some extra color on the left if this is the first byte we're highlighting
if (isStart) {
isStart = false;
drawList->AddRectFilled(pos - hexSpacing / 2, pos + ImVec2(0, hexSize.y + hexSpacing.y / 2), color);
}
// Add some extra color on the right if this is the last byte
if (count == 0) {
drawList->AddRectFilled(pos + ImVec2(hexSize.x, -hexSpacing.y / 2), pos + hexSize + hexSpacing / 2, color);
}
}
start.x = 0;
}
};
// Draw all highlights, slowly fading them in as the init tasks progress
for (const auto &highlight : this->m_highlights)
highlightBytes(highlight.start, highlight.count, highlight.color, this->m_progressLerp);
}
this->m_progressLerp += (m_progress - this->m_progressLerp) * 0.1F;
// Draw the splash screen foreground
drawList->AddImage(this->m_splashTextTexture, ImVec2(0, 0), this->m_splashTextTexture.getSize());
// Draw the "copyright" notice
drawList->AddText(ImVec2(35, 85), ImColor(0xFF, 0xFF, 0xFF, 0xFF), hex::format("WerWolv\n2020 - {0}", &__DATE__[7]).c_str());
// Draw version information
// In debug builds, also display the current commit hash and branch
#if defined(DEBUG)
const static auto VersionInfo = hex::format("{0} : {1}@{2}", ImHexApi::System::getImHexVersion(), ImHexApi::System::getCommitBranch(), ImHexApi::System::getCommitHash());
#else
const static auto VersionInfo = hex::format("{0}", ImHexApi::System::getImHexVersion());
#endif
drawList->AddText(ImVec2((this->m_splashBackgroundTexture.getSize().x - ImGui::CalcTextSize(VersionInfo.c_str()).x) / 2, 105), ImColor(0xFF, 0xFF, 0xFF, 0xFF), VersionInfo.c_str());
}
// Draw the task progress bar
{
std::lock_guard guard(m_progressMutex);
const auto progressBackgroundStart = ImVec2(99, 357);
const auto progressBackgroundSize = ImVec2(442, 30);
const auto progressStart = progressBackgroundStart + ImVec2(0, 20);
const auto progressSize = ImVec2(progressBackgroundSize.x * m_progress, 10);
// Draw progress bar
drawList->AddRectFilled(progressStart, progressStart + progressSize, 0xD0FFFFFF);
// Draw task names separated by | characters
if (!m_currTaskNames.empty()) {
drawList->PushClipRect(progressBackgroundStart, progressBackgroundStart + progressBackgroundSize, true);
drawList->AddText(progressStart + ImVec2(5, -20), ImColor(0xFF, 0xFF, 0xFF, 0xFF), hex::format("{}", fmt::join(m_currTaskNames, " | ")).c_str());
drawList->PopClipRect();
}
}
// Render the frame
ImGui::Render();
int displayWidth, displayHeight;
glfwGetFramebufferSize(m_window, &displayWidth, &displayHeight);
glViewport(0, 0, displayWidth, displayHeight);
glClearColor(0.00F, 0.00F, 0.00F, 0.00F);
glClear(GL_COLOR_BUFFER_BIT);
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
glfwSwapBuffers(m_window);
// Check if all background tasks have finished so the splash screen can be closed
if (this->m_tasksSucceeded.wait_for(0s) == std::future_status::ready) {
if (this->m_tasksSucceeded.get()) {
log::debug("All tasks finished successfully!");
return FrameResult::Success;
} else {
log::warn("All tasks finished, but some failed");
return FrameResult::Failure;
}
}
return FrameResult::Running;
}
bool WindowSplash::loop() {
// Splash window rendering loop
while (true) {
auto frameResult = this->fullFrame();
if (frameResult == FrameResult::Success)
return true;
else if (frameResult == FrameResult::Failure)
return false;
}
}
void WindowSplash::initGLFW() {
glfwSetErrorCallback([](int errorCode, const char *desc) {
bool isWaylandError = errorCode == GLFW_PLATFORM_ERROR;
#if defined(GLFW_FEATURE_UNAVAILABLE)
isWaylandError = isWaylandError || (errorCode == GLFW_FEATURE_UNAVAILABLE);
#endif
isWaylandError = isWaylandError && std::string_view(desc).contains("Wayland");
if (isWaylandError) {
// Ignore error spam caused by Wayland not supporting moving or resizing
// windows or querying their position and size.
return;
}
lastGlfwError.errorCode = errorCode;
lastGlfwError.desc = std::string(desc);
log::error("GLFW Error [{}] : {}", errorCode, desc);
});
if (!glfwInit()) {
log::fatal("Failed to initialize GLFW!");
std::exit(EXIT_FAILURE);
}
// Configure used OpenGL version
#if defined(OS_MACOS)
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_COCOA_RETINA_FRAMEBUFFER, GLFW_FALSE);
glfwWindowHint(GLFW_COCOA_GRAPHICS_SWITCHING, GLFW_TRUE);
#else
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
#endif
#if defined(OS_LINUX) && defined(GLFW_WAYLAND_APP_ID)
glfwWindowHintString(GLFW_WAYLAND_APP_ID, "imhex");
#endif
// Make splash screen non-resizable, undecorated and transparent
glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_TRUE);
glfwWindowHint(GLFW_TRANSPARENT_FRAMEBUFFER, GLFW_TRUE);
glfwWindowHint(GLFW_DECORATED, GLFW_FALSE);
glfwWindowHint(GLFW_FLOATING, GLFW_FALSE);
glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_API);
// Create the splash screen window
m_window = glfwCreateWindow(1, 1, "Starting ImHex...", nullptr, nullptr);
if (m_window == nullptr) {
hex::nativeErrorMessage(hex::format(
"Failed to create GLFW window: [{}] {}.\n"
"You may not have a renderer available.\n"
"The most common cause of this is using a virtual machine\n"
"You may want to try a release artifact ending with 'NoGPU'"
, lastGlfwError.errorCode, lastGlfwError.desc));
std::exit(EXIT_FAILURE);
}
// Force window to be fully opaque by default
glfwSetWindowOpacity(m_window, 1.0F);
// Calculate native scale factor for hidpi displays
{
float xScale = 0, yScale = 0;
glfwGetWindowContentScale(m_window, &xScale, &yScale);
auto meanScale = std::midpoint(xScale, yScale);
if (meanScale <= 0.0F)
meanScale = 1.0F;
#if defined(OS_MACOS)
meanScale /= getBackingScaleFactor();
#elif defined(OS_WEB)
meanScale = 1.0F;
#endif
ImHexApi::System::impl::setGlobalScale(meanScale);
ImHexApi::System::impl::setNativeScale(meanScale);
log::info("Native scaling set to: {:.1f}", meanScale);
}
glfwMakeContextCurrent(m_window);
glfwSwapInterval(1);
}
void WindowSplash::initImGui() {
// Initialize ImGui
IMGUI_CHECKVERSION();
GImGui = ImGui::CreateContext();
ImGui::StyleColorsDark();
ImGui_ImplGlfw_InitForOpenGL(m_window, true);
#if defined(OS_MACOS)
ImGui_ImplOpenGL3_Init("#version 150");
#elif defined(OS_WEB)
ImGui_ImplOpenGL3_Init();
ImGui_ImplGlfw_InstallEmscriptenCanvasResizeCallback("#canvas");
#else
ImGui_ImplOpenGL3_Init("#version 130");
#endif
auto &io = ImGui::GetIO();
ImGui::GetStyle().ScaleAllSizes(ImHexApi::System::getGlobalScale());
// Load fonts necessary for the splash screen
{
io.Fonts->Clear();
ImFontConfig cfg;
cfg.OversampleH = cfg.OversampleV = 1, cfg.PixelSnapH = true;
cfg.SizePixels = ImHexApi::Fonts::DefaultFontSize;
io.Fonts->AddFontDefault(&cfg);
std::uint8_t *px;
int w, h;
io.Fonts->GetTexDataAsAlpha8(&px, &w, &h);
// Create new font atlas
GLuint tex;
glGenTextures(1, &tex);
glBindTexture(GL_TEXTURE_2D, tex);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, w, h, 0, GL_ALPHA, GL_UNSIGNED_BYTE, px);
io.Fonts->SetTexID(reinterpret_cast<ImTextureID>(tex));
}
// Don't save window settings for the splash screen
io.IniFilename = nullptr;
}
/**
* @brief Initialize resources for the splash window
*/
void WindowSplash::loadAssets() {
// Load splash screen image from romfs
this->m_splashBackgroundTexture = ImGuiExt::Texture::fromImage(romfs::get("splash_background.png").span(), ImGuiExt::Texture::Filter::Linear);
this->m_splashTextTexture = ImGuiExt::Texture::fromImage(romfs::get("splash_text.png").span(), ImGuiExt::Texture::Filter::Linear);
// If the image couldn't be loaded correctly, something went wrong during the build process
// Close the application since this would lead to errors later on anyway.
if (!this->m_splashBackgroundTexture.isValid() || !this->m_splashTextTexture.isValid()) {
log::error("Could not load splash screen image!");
}
std::mt19937 rng(std::random_device{}());
u32 lastPos = 0;
u32 lastCount = 0;
u32 index = 0;
for (auto &highlight : this->m_highlights) {
u32 newPos = lastPos + lastCount + (rng() % 35);
u32 newCount = (rng() % 7) + 3;
highlight.start.x = float(newPos % 13);
highlight.start.y = float(newPos / 13);
highlight.count = newCount;
highlight.color = getHighlightColor(index);
lastPos = newPos;
lastCount = newCount;
index += 1;
}
}
void WindowSplash::startStartupTasks() {
// Launch init tasks in the background
this->m_tasksSucceeded = processTasksAsync();
}
void WindowSplash::exitGLFW() const {
glfwDestroyWindow(m_window);
glfwTerminate();
}
void WindowSplash::exitImGui() const {
ImGui_ImplOpenGL3_Shutdown();
ImGui_ImplGlfw_Shutdown();
ImGui::DestroyContext();
}
}
| 22,897
|
C++
|
.cpp
| 462
| 36.807359
| 193
| 0.57351
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
298
|
tasks.cpp
|
WerWolv_ImHex/main/gui/source/init/tasks.cpp
|
#include "init/tasks.hpp"
#include <imgui.h>
#include <romfs/romfs.hpp>
#include <hex/helpers/http_requests.hpp>
#include <hex/helpers/fs.hpp>
#include <hex/helpers/logger.hpp>
#include <hex/helpers/default_paths.hpp>
#include <hex/api/content_registry.hpp>
#include <hex/api/plugin_manager.hpp>
#include <hex/api/achievement_manager.hpp>
#include <hex/ui/view.hpp>
#include <hex/ui/popup.hpp>
#include <nlohmann/json.hpp>
#include <wolv/io/fs.hpp>
#include <wolv/io/file.hpp>
namespace hex::init {
using namespace std::literals::string_literals;
bool setupEnvironment() {
hex::log::debug("Using romfs: '{}'", romfs::name());
return true;
}
static bool isSubPathWritable(std::fs::path path) {
for (u32 i = 0; i < 128; i++) {
if (hex::fs::isPathWritable(path))
return true;
auto parentPath = path.parent_path();
if (parentPath == path)
break;
path = std::move(parentPath);
}
return false;
}
bool createDirectories() {
bool result = true;
// Try to create all default directories
for (auto path : paths::All) {
for (auto &folder : path->all()) {
try {
if (isSubPathWritable(folder.parent_path()))
wolv::io::fs::createDirectories(folder);
} catch (...) {
log::error("Failed to create folder {}!", wolv::util::toUTF8String(folder));
result = false;
}
}
}
if (!result)
ImHexApi::System::impl::addInitArgument("folder-creation-error");
return result;
}
bool prepareExit() {
// Terminate all asynchronous tasks
TaskManager::exit();
// Unlock font atlas, so it can be deleted in case of a crash
if (ImGui::GetCurrentContext() != nullptr) {
if (ImGui::GetIO().Fonts != nullptr) {
ImGui::GetIO().Fonts->Locked = false;
ImGui::GetIO().Fonts = nullptr;
}
}
// Print a nice message if a crash happened while cleaning up resources
// To the person fixing this:
// ALWAYS wrap static heap allocated objects inside libimhex such as std::vector, std::string, std::function, etc. in a AutoReset<T>
// e.g `AutoReset<std::vector<MyStruct>> m_structs;`
//
// The reason this is necessary because each plugin / dynamic library gets its own instance of `std::allocator`
// which will try to free the allocated memory when the object is destroyed. However since the storage is static, this
// will happen only when libimhex is unloaded after main() returns. At this point all plugins have been unloaded already so
// the std::allocator will try to free memory in a heap that does not exist anymore which will cause a crash.
// By wrapping the object in a AutoReset<T>, the `EventImHexClosing` event will automatically handle clearing the object
// while the heap is still valid.
// The heap stays valid right up to the point where `PluginManager::unload()` is called.
EventAbnormalTermination::subscribe([](int) {
log::fatal("A crash happened while cleaning up resources during exit!");
log::fatal("This is most certainly because WerWolv again forgot to mark a heap allocated object as 'AutoReset'.");
log::fatal("Please report this issue on the ImHex GitHub page!");
log::fatal("To the person fixing this, read the comment above this message for more information.");
});
ImHexApi::System::impl::cleanup();
EventImHexClosing::post();
EventManager::clear();
return true;
}
bool loadPlugins() {
// Load all plugins
#if !defined(IMHEX_STATIC_LINK_PLUGINS)
for (const auto &dir : paths::Plugins.read()) {
PluginManager::addLoadPath(dir);
}
PluginManager::loadLibraries();
PluginManager::load();
#endif
// Get loaded plugins
const auto &plugins = PluginManager::getPlugins();
// If no plugins were loaded, ImHex wasn't installed properly. This will trigger an error popup later on
if (plugins.empty()) {
log::error("No plugins found!");
ImHexApi::System::impl::addInitArgument("no-plugins");
return false;
}
const auto shouldLoadPlugin = [executablePath = wolv::io::fs::getExecutablePath()](const Plugin &plugin) {
// In debug builds, ignore all plugins that are not part of the executable directory
#if !defined(DEBUG)
return true;
#endif
if (!executablePath.has_value())
return true;
if (!PluginManager::getPluginLoadPaths().empty())
return true;
// Check if the plugin is somewhere in the same directory tree as the executable
return !std::fs::relative(plugin.getPath(), executablePath->parent_path()).string().starts_with("..");
};
u32 loadErrors = 0;
std::set<std::string> pluginNames;
// Load library plugins first since plugins might depend on them
for (const auto &plugin : plugins) {
if (!plugin.isLibraryPlugin()) continue;
if (!shouldLoadPlugin(plugin)) {
log::debug("Skipping library plugin {}", plugin.getPath().string());
continue;
}
// Initialize the library
if (!plugin.initializePlugin()) {
log::error("Failed to initialize library plugin {}", wolv::util::toUTF8String(plugin.getPath().filename()));
loadErrors++;
}
pluginNames.insert(plugin.getPluginName());
}
// Load all plugins
for (const auto &plugin : plugins) {
if (plugin.isLibraryPlugin()) continue;
if (!shouldLoadPlugin(plugin)) {
log::debug("Skipping plugin {}", plugin.getPath().string());
continue;
}
// Initialize the plugin
if (!plugin.initializePlugin()) {
log::error("Failed to initialize plugin {}", wolv::util::toUTF8String(plugin.getPath().filename()));
loadErrors++;
}
pluginNames.insert(plugin.getPluginName());
}
// If no plugins were loaded successfully, ImHex wasn't installed properly. This will trigger an error popup later on
if (loadErrors == plugins.size()) {
log::error("No plugins loaded successfully!");
ImHexApi::System::impl::addInitArgument("no-plugins");
return false;
}
if (pluginNames.size() != plugins.size()) {
log::error("Duplicate plugins detected!");
ImHexApi::System::impl::addInitArgument("duplicate-plugins");
return false;
}
return true;
}
bool deleteOldFiles() {
bool result = true;
auto keepNewest = [&](u32 count, const paths::impl::DefaultPath &pathType) {
for (const auto &path : pathType.write()) {
try {
std::vector<std::filesystem::directory_entry> files;
for (const auto& file : std::filesystem::directory_iterator(path))
files.push_back(file);
if (files.size() <= count)
return;
std::sort(files.begin(), files.end(), [](const auto& a, const auto& b) {
return std::filesystem::last_write_time(a) > std::filesystem::last_write_time(b);
});
for (auto it = files.begin() + count; it != files.end(); it += 1)
std::filesystem::remove(it->path());
} catch (std::filesystem::filesystem_error &e) {
log::error("Failed to clear old file! {}", e.what());
result = false;
}
}
};
keepNewest(10, paths::Logs);
keepNewest(25, paths::Backups);
return result;
}
bool unloadPlugins() {
PluginManager::unload();
return true;
}
bool loadSettings() {
try {
// Try to load settings from file
ContentRegistry::Settings::impl::load();
} catch (std::exception &e) {
log::error("Failed to load configuration! {}", e.what());
return false;
}
return true;
}
// Run all exit tasks, and print to console
void runExitTasks() {
for (const auto &[name, task, async] : init::getExitTasks()) {
const bool result = task();
log::info("Exit task '{0}' finished {1}", name, result ? "successfully" : "unsuccessfully");
}
}
std::vector<Task> getInitTasks() {
return {
{ "Setting up environment", setupEnvironment, false },
{ "Creating directories", createDirectories, false },
{ "Loading settings", loadSettings, false },
{ "Loading plugins", loadPlugins, false },
};
}
std::vector<Task> getExitTasks() {
return {
{ "Prepare exit", prepareExit, false },
{ "Unloading plugins", unloadPlugins, false },
{ "Deleting old files", deleteOldFiles, false },
};
}
}
| 9,722
|
C++
|
.cpp
| 217
| 33.663594
| 144
| 0.566967
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
299
|
common.cpp
|
WerWolv_ImHex/main/gui/source/init/run/common.cpp
|
#include <hex/api/event_manager.hpp>
#include <hex/api/task_manager.hpp>
#include <hex/helpers/utils.hpp>
#include <init/splash_window.hpp>
#include <init/tasks.hpp>
namespace hex::init {
/**
* @brief Handles a file open request by opening the file specified by OS-specific means
*/
void handleFileOpenRequest() {
if (auto path = hex::getInitialFilePath(); path.has_value()) {
RequestOpenFile::post(path.value());
}
}
/**
* @brief Displays ImHex's splash screen and runs all initialization tasks. The splash screen will be displayed until all tasks have finished.
*/
[[maybe_unused]]
std::unique_ptr<init::WindowSplash> initializeImHex() {
auto splashWindow = std::make_unique<init::WindowSplash>();
log::info("Using '{}' GPU", ImHexApi::System::getGPUVendor());
// Add initialization tasks to run
TaskManager::init();
for (const auto &[name, task, async] : init::getInitTasks())
splashWindow->addStartupTask(name, task, async);
splashWindow->startStartupTasks();
return splashWindow;
}
/**
* @brief Deinitializes ImHex by running all exit tasks
*/
void deinitializeImHex() {
// Run exit tasks
init::runExitTasks();
}
}
| 1,313
|
C++
|
.cpp
| 36
| 30.111111
| 146
| 0.650869
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
300
|
cli.cpp
|
WerWolv_ImHex/main/gui/source/init/run/cli.cpp
|
#include "messaging.hpp"
#include <hex/subcommands/subcommands.hpp>
#include <hex/api/plugin_manager.hpp>
#include <hex/helpers/fs.hpp>
#include <hex/helpers/logger.hpp>
#include <hex/helpers/default_paths.hpp>
#include <wolv/utils/guards.hpp>
#if defined(OS_WINDOWS)
#include <windows.h>
#include <shellapi.h>
#include <codecvt>
#endif
namespace hex::init {
/**
* @brief Handles commands passed to ImHex via the command line
* @param argc Argument count
* @param argv Argument values
*/
void runCommandLine(int argc, char **argv) {
// Suspend logging while processing command line arguments so
// we don't spam the console with log messages while printing
// CLI tool messages
log::suspendLogging();
ON_SCOPE_EXIT {
log::resumeLogging();
};
std::vector<std::string> args;
#if defined (OS_WINDOWS)
hex::unused(argv);
// On Windows, argv contains UTF-16 encoded strings, so we need to convert them to UTF-8
auto convertedCommandLine = ::CommandLineToArgvW(::GetCommandLineW(), &argc);
if (convertedCommandLine == nullptr) {
log::error("Failed to convert command line arguments to UTF-8");
std::exit(EXIT_FAILURE);
}
// Skip the first argument (the executable path) and convert the rest to a vector of UTF-8 strings
for (int i = 1; i < argc; i += 1) {
std::wstring wcharArg = convertedCommandLine[i];
std::string utf8Arg = std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>>().to_bytes(wcharArg);
args.push_back(utf8Arg);
}
::LocalFree(convertedCommandLine);
#else
// Skip the first argument (the executable path) and convert the rest to a vector of strings
args = { argv + 1, argv + argc };
#endif
// Load all plugins but don't initialize them
PluginManager::loadLibraries();
for (const auto &dir : paths::Plugins.read()) {
PluginManager::load(dir);
}
// Setup messaging system to allow sending commands to the main ImHex instance
hex::messaging::setupMessaging();
// Process the arguments
hex::subcommands::processArguments(args);
// Unload plugins again
PluginManager::unload();
}
}
| 2,447
|
C++
|
.cpp
| 59
| 32.711864
| 116
| 0.622785
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
301
|
web.cpp
|
WerWolv_ImHex/main/gui/source/init/run/web.cpp
|
#if defined(OS_WEB)
#include <emscripten.h>
#include <emscripten/html5.h>
#include <hex/api/imhex_api.hpp>
#include <hex/api/event_manager.hpp>
#include <hex/api/task_manager.hpp>
#include <window.hpp>
#include <init/run.hpp>
namespace hex::init {
void saveFsData() {
EM_ASM({
FS.syncfs(function (err) {
if (!err)
return;
alert("Failed to save permanent file system: "+err);
});
});
}
int runImHex() {
static std::unique_ptr<init::WindowSplash> splashWindow;
splashWindow = initializeImHex();
RequestRestartImHex::subscribe([&] {
MAIN_THREAD_EM_ASM({
location.reload();
});
});
// Draw the splash window while tasks are running
emscripten_set_main_loop_arg([](void *arg) {
auto &splashWindow = *reinterpret_cast<std::unique_ptr<init::WindowSplash>*>(arg);
FrameResult frameResult = splashWindow->fullFrame();
if (frameResult == FrameResult::Success) {
handleFileOpenRequest();
// Clean up everything after the main window is closed
emscripten_set_beforeunload_callback(nullptr, [](int eventType, const void *reserved, void *userData) {
hex::unused(eventType, reserved, userData);
emscripten_cancel_main_loop();
try {
saveFsData();
deinitializeImHex();
return "";
} catch (const std::exception &e) {
static std::string message;
message = hex::format("Failed to deinitialize ImHex!\nThis is just a message warning you of this, the application has already closed, you probably can't do anything about it.\n\nError: {}", e.what());
return message.c_str();
}
});
// Delete splash window (do it before creating the main window so glfw destroys the window)
splashWindow.reset();
emscripten_cancel_main_loop();
// Main window
static std::optional<Window> window;
window.emplace();
emscripten_set_main_loop([]() {
window->fullFrame();
}, 60, 0);
}
}, &splashWindow, 60, 0);
return -1;
}
}
#endif
| 2,758
|
C++
|
.cpp
| 61
| 28.295082
| 228
| 0.485437
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
302
|
native.cpp
|
WerWolv_ImHex/main/gui/source/init/run/native.cpp
|
#if !defined(OS_WEB)
#include <hex/api/event_manager.hpp>
#include <wolv/utils/guards.hpp>
#include <init/run.hpp>
#include <window.hpp>
namespace hex::init {
int runImHex() {
bool shouldRestart = false;
do {
// Register an event handler that will make ImHex restart when requested
shouldRestart = false;
RequestRestartImHex::subscribe([&] {
shouldRestart = true;
});
{
auto splashWindow = initializeImHex();
// Draw the splash window while tasks are running
if (!splashWindow->loop())
ImHexApi::System::impl::addInitArgument("tasks-failed");
handleFileOpenRequest();
}
// Clean up everything after the main window is closed
ON_SCOPE_EXIT {
deinitializeImHex();
};
// Main window
Window window;
window.loop();
} while (shouldRestart);
return EXIT_SUCCESS;
}
}
#endif
| 1,203
|
C++
|
.cpp
| 33
| 22.242424
| 88
| 0.491364
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
303
|
linux_window.cpp
|
WerWolv_ImHex/main/gui/source/window/linux_window.cpp
|
#include "window.hpp"
#if defined(OS_LINUX)
#include <hex/api/imhex_api.hpp>
#include <hex/api/content_registry.hpp>
#include <hex/api/event_manager.hpp>
#include <hex/helpers/utils.hpp>
#include <hex/helpers/utils_linux.hpp>
#include <hex/helpers/logger.hpp>
#include <hex/helpers/default_paths.hpp>
#include <wolv/utils/core.hpp>
#include <nlohmann/json.hpp>
#include <sys/wait.h>
#include <unistd.h>
#include <imgui_impl_glfw.h>
#include <string.h>
#include <ranges>
#if defined(IMHEX_HAS_FONTCONFIG)
#include <fontconfig/fontconfig.h>
#endif
namespace hex {
bool isFileInPath(const std::fs::path &filename) {
auto optPathVar = hex::getEnvironmentVariable("PATH");
if (!optPathVar.has_value()) {
log::error("Could not find variable named PATH");
return false;
}
for (auto dir : std::views::split(optPathVar.value(), ':')) {
if (std::fs::exists(std::fs::path(std::string_view(dir)) / filename)) {
return true;
}
}
return false;
}
void nativeErrorMessage(const std::string &message) {
log::fatal(message);
if (isFileInPath("zenity")) {
executeCmd({"zenity", "--error", "--text", message});
} else if (isFileInPath("notify-send")) {
executeCmd({"notify-send", "-i", "script-error", "Error", message});
} // Hopefully one of these commands is installed
}
#if defined(IMHEX_HAS_FONTCONFIG)
static bool enumerateFontConfig() {
if (!FcInit())
return false;
ON_SCOPE_EXIT { FcFini(); };
auto fonts = FcConfigGetFonts(nullptr, FcSetSystem);
if (fonts == nullptr)
return false;
for (int i = 0; i < fonts->nfont; ++i) {
auto font = fonts->fonts[i];
FcChar8 *file, *fullName;
if (FcPatternGetString(font, FC_FILE, 0, &file) != FcResultMatch) {
continue;
}
if (FcPatternGetString(font, FC_FULLNAME, 0, &fullName) != FcResultMatch
&& FcPatternGetString(font, FC_FAMILY, 0, &fullName) != FcResultMatch) {
continue;
}
registerFont(reinterpret_cast<const char *>(fullName), reinterpret_cast<const char *>(file));
}
return true;
}
#endif
void enumerateFonts() {
#if defined(IMHEX_HAS_FONTCONFIG)
if (enumerateFontConfig())
return;
#endif
const std::array FontDirectories = {
"/usr/share/fonts",
"/usr/local/share/fonts",
"~/.fonts",
"~/.local/share/fonts"
};
for (const auto &directory : FontDirectories) {
if (!std::fs::exists(directory))
continue;
for (const auto &entry : std::fs::recursive_directory_iterator(directory)) {
if (!entry.exists())
continue;
if (!entry.is_regular_file())
continue;
if (entry.path().extension() != ".ttf" && entry.path().extension() != ".otf")
continue;
registerFont(entry.path().stem().c_str(), entry.path().c_str());
}
}
}
void Window::configureGLFW() {
#if defined(GLFW_SCALE_FRAMEBUFFER)
glfwWindowHint(GLFW_SCALE_FRAMEBUFFER, GLFW_FALSE);
#endif
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
glfwWindowHint(GLFW_DECORATED, ImHexApi::System::isBorderlessWindowModeEnabled() ? GL_FALSE : GL_TRUE);
glfwWindowHint(GLFW_TRANSPARENT_FRAMEBUFFER, GLFW_TRUE);
#if defined(GLFW_WAYLAND_APP_ID)
glfwWindowHintString(GLFW_WAYLAND_APP_ID, "imhex");
#endif
}
void Window::initNative() {
log::impl::enableColorPrinting();
// Add plugin library folders to dll search path
for (const auto &path : paths::Libraries.read()) {
if (std::fs::exists(path))
setenv("LD_LIBRARY_PATH", hex::format("{};{}", hex::getEnvironmentVariable("LD_LIBRARY_PATH").value_or(""), path.string().c_str()).c_str(), true);
}
// Redirect stdout to log file if we're not running in a terminal
if (!isatty(STDOUT_FILENO)) {
log::impl::redirectToFile();
}
enumerateFonts();
}
void Window::setupNativeWindow() {
bool themeFollowSystem = ImHexApi::System::usesSystemThemeDetection();
EventOSThemeChanged::subscribe(this, [themeFollowSystem] {
if (!themeFollowSystem) return;
std::array<char, 128> buffer = { 0 };
std::string result;
// Ask dbus for the current theme. 1 for Dark, 2 for Light, 0 for default (Dark for ImHex)
// https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Settings.html
FILE *pipe = popen("dbus-send --session --print-reply --dest=org.freedesktop.portal.Desktop /org/freedesktop/portal/desktop org.freedesktop.portal.Settings.Read string:'org.freedesktop.appearance' string:'color-scheme' 2>&1", "r");
if (pipe == nullptr) return;
while (fgets(buffer.data(), buffer.size(), pipe) != nullptr)
result += buffer.data();
auto exitCode = WEXITSTATUS(pclose(pipe));
if (exitCode != 0) return;
RequestChangeTheme::post(hex::containsIgnoreCase(result, "uint32 2") ? "Light" : "Dark");
});
// Register file drop callback
glfwSetDropCallback(m_window, [](GLFWwindow *, int count, const char **paths) {
for (int i = 0; i < count; i++) {
EventFileDropped::post(reinterpret_cast<const char8_t *>(paths[i]));
}
});
glfwSetWindowRefreshCallback(m_window, [](GLFWwindow *window) {
auto win = static_cast<Window *>(glfwGetWindowUserPointer(window));
win->fullFrame();
});
if (themeFollowSystem)
EventOSThemeChanged::post();
}
void Window::beginNativeWindowFrame() {
}
void Window::endNativeWindowFrame() {
}
}
#endif
| 6,421
|
C++
|
.cpp
| 149
| 32.375839
| 243
| 0.576108
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
304
|
win_window.cpp
|
WerWolv_ImHex/main/gui/source/window/win_window.cpp
|
#include <hex/api/content_registry.hpp>
#include <hex/api/theme_manager.hpp>
#include "window.hpp"
#if defined(OS_WINDOWS)
#include "messaging.hpp"
#include <hex/helpers/utils.hpp>
#include <hex/helpers/logger.hpp>
#include <hex/helpers/default_paths.hpp>
#include <imgui.h>
#include <imgui_internal.h>
#define GLFW_EXPOSE_NATIVE_WIN32
#include <GLFW/glfw3native.h>
#undef GLFW_EXPOSE_NATIVE_WIN32
#include <winbase.h>
#include <winuser.h>
#include <dwmapi.h>
#include <windowsx.h>
#include <shobjidl.h>
#include <wrl/client.h>
#include <fcntl.h>
#include <shellapi.h>
#include <timeapi.h>
namespace hex {
template<typename T>
using WinUniquePtr = std::unique_ptr<std::remove_pointer_t<T>, BOOL(*)(T)>;
static LONG_PTR s_oldWndProc;
static float s_titleBarHeight;
static Microsoft::WRL::ComPtr<ITaskbarList4> s_taskbarList;
void nativeErrorMessage(const std::string &message) {
log::fatal(message);
MessageBoxA(nullptr, message.c_str(), "Error", MB_ICONERROR | MB_OK);
}
// Custom Window procedure for receiving OS events
static LRESULT commonWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
switch (uMsg) {
case WM_DPICHANGED: {
int interfaceScaleSetting = int(hex::ContentRegistry::Settings::read<float>("hex.builtin.setting.interface", "hex.builtin.setting.interface.scaling_factor", 0.0F) * 10.0F);
if (interfaceScaleSetting != 0)
break;
const auto newScale = LOWORD(wParam) / 96.0F;
const auto oldScale = ImHexApi::System::getNativeScale();
EventDPIChanged::post(oldScale, newScale);
ImHexApi::System::impl::setNativeScale(newScale);
ThemeManager::reapplyCurrentTheme();
ImGui::GetStyle().ScaleAllSizes(newScale);
return TRUE;
}
case WM_COPYDATA: {
// Handle opening files in existing instance
auto message = reinterpret_cast<COPYDATASTRUCT *>(lParam);
if (message == nullptr) break;
ssize_t nullIndex = -1;
auto messageData = static_cast<const char*>(message->lpData);
size_t messageSize = message->cbData;
for (size_t i = 0; i < messageSize; i++) {
if (messageData[i] == '\0') {
nullIndex = i;
break;
}
}
if (nullIndex == -1) {
log::warn("Received invalid forwarded event");
break;
}
std::string eventName(messageData, nullIndex);
std::vector<u8> eventData(messageData + nullIndex + 1, messageData + messageSize);
hex::messaging::messageReceived(eventName, eventData);
break;
}
case WM_SETTINGCHANGE: {
// Handle Windows theme changes
if (lParam == 0) break;
if (reinterpret_cast<const WCHAR*>(lParam) == std::wstring_view(L"ImmersiveColorSet")) {
EventOSThemeChanged::post();
}
break;
}
case WM_SETCURSOR: {
if (LOWORD(lParam) != HTCLIENT) {
return CallWindowProc(reinterpret_cast<WNDPROC>(s_oldWndProc), hwnd, uMsg, wParam, lParam);
} else {
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:
break;
}
return TRUE;
}
}
default:
break;
}
return CallWindowProc(reinterpret_cast<WNDPROC>(s_oldWndProc), hwnd, uMsg, wParam, lParam);
}
// Custom window procedure for borderless window
static LRESULT borderlessWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
switch (uMsg) {
case WM_MOUSELAST:
break;
case WM_NCACTIVATE:
case WM_NCPAINT:
// Handle Windows Aero Snap
return DefWindowProcW(hwnd, uMsg, wParam, lParam);
case WM_NCCALCSIZE: {
// Handle window resizing
RECT &rect = *reinterpret_cast<RECT *>(lParam);
RECT client = rect;
CallWindowProc(reinterpret_cast<WNDPROC>(s_oldWndProc), hwnd, uMsg, wParam, lParam);
if (IsMaximized(hwnd)) {
WINDOWINFO 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;
}
// This code tries to avoid DWM flickering when resizing the window
// It's not perfect, but it's really the best we can do.
LARGE_INTEGER performanceFrequency = {};
QueryPerformanceFrequency(&performanceFrequency);
TIMECAPS tc = {};
timeGetDevCaps(&tc, sizeof(tc));
const auto granularity = tc.wPeriodMin;
timeBeginPeriod(tc.wPeriodMin);
DWM_TIMING_INFO dti = {};
dti.cbSize = sizeof(dti);
::DwmGetCompositionTimingInfo(nullptr, &dti);
LARGE_INTEGER end = {};
QueryPerformanceCounter(&end);
const auto period = dti.qpcRefreshPeriod;
const i64 delta = dti.qpcVBlank - end.QuadPart;
i64 sleepTicks = 0;
i64 sleepMilliSeconds = 0;
if (delta >= 0) {
sleepTicks = delta / period;
} else {
sleepTicks = -1 + delta / period;
}
sleepMilliSeconds = delta - (period * sleepTicks);
const double sleepTime = (1000.0 * double(sleepMilliSeconds) / double(performanceFrequency.QuadPart));
Sleep(DWORD(std::round(sleepTime)));
timeEndPeriod(granularity);
return WVR_REDRAW;
}
case WM_ERASEBKGND:
return 1;
case WM_WINDOWPOSCHANGING: {
// Make sure that windows discards the entire client area when resizing to avoid flickering
const auto windowPos = reinterpret_cast<LPWINDOWPOS>(lParam);
windowPos->flags |= SWP_NOCOPYBITS;
break;
}
case WM_NCHITTEST: {
// Handle window resizing and moving
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()),
static_cast<LONG>((::GetSystemMetrics(SM_CYFRAME) + ::GetSystemMetrics(SM_CXPADDEDBORDER)) * ImHexApi::System::getGlobalScale())
};
if (glfwGetWindowMonitor(ImHexApi::System::getMainWindowHandle()) != nullptr) {
return HTCLIENT;
}
RECT window;
if (!::GetWindowRect(hwnd, &window)) {
return HTNOWHERE;
}
constexpr static auto RegionClient = 0b0000;
constexpr static auto RegionLeft = 0b0001;
constexpr static auto RegionRight = 0b0010;
constexpr static auto RegionTop = 0b0100;
constexpr static 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::IsAnyItemHovered() || ImGui::IsPopupOpen(nullptr, ImGuiPopupFlags_AnyPopupId))) {
break;
}
std::string_view hoveredWindowName = GImGui->HoveredWindow == nullptr ? "" : GImGui->HoveredWindow->Name;
if (!ImHexApi::System::impl::isWindowResizable()) {
if (result != RegionClient) {
return HTCAPTION;
}
}
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 + s_titleBarHeight * 2)) {
if (hoveredWindowName == "##MainMenuBar" || hoveredWindowName == "ImHexDockSpace") {
if (!ImGui::IsAnyItemHovered()) {
return HTCAPTION;
}
}
}
break;
}
break;
}
default:
break;
}
return commonWindowProc(hwnd, uMsg, wParam, lParam);
}
[[maybe_unused]]
static void reopenConsoleHandle(u32 stdHandleNumber, i32 stdFileDescriptor, FILE *stdStream) {
// Get the Windows handle for the standard stream
HANDLE handle = ::GetStdHandle(stdHandleNumber);
// Redirect the standard stream to the relevant console stream
if (stdFileDescriptor == STDIN_FILENO)
freopen("CONIN$", "rt", stdStream);
else
freopen("CONOUT$", "wt", stdStream);
// Disable buffering
setvbuf(stdStream, nullptr, _IONBF, 0);
// Reopen the standard stream as a file descriptor
auto unboundFd = [stdFileDescriptor, handle]{
if (stdFileDescriptor == STDIN_FILENO)
return _open_osfhandle(intptr_t(handle), _O_RDONLY);
else
return _open_osfhandle(intptr_t(handle), _O_WRONLY);
}();
// Duplicate the file descriptor to the standard stream
dup2(unboundFd, stdFileDescriptor);
}
void enumerateFonts() {
constexpr static auto FontRegistryPath = L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Fonts";
static const std::array RegistryLocations = {
HKEY_LOCAL_MACHINE,
HKEY_CURRENT_USER
};
for (const auto location : RegistryLocations) {
HKEY key;
if (RegOpenKeyExW(location, FontRegistryPath, 0, KEY_READ, &key) != ERROR_SUCCESS) {
continue;
}
DWORD index = 0;
std::wstring valueName(0xFFF, L'\0');
DWORD valueNameSize = valueName.size() * sizeof(wchar_t);
std::wstring valueData(0xFFF, L'\0');
DWORD valueDataSize = valueData.size() * sizeof(wchar_t);
DWORD valueType;
while (RegEnumValueW(key, index, valueName.data(), &valueNameSize, nullptr, &valueType, reinterpret_cast<BYTE *>(valueData.data()), &valueDataSize) == ERROR_SUCCESS) {
if (valueType == REG_SZ) {
auto fontName = hex::utf16ToUtf8(valueName.c_str());
auto fontPath = std::fs::path(valueData);
if (fontPath.is_relative())
fontPath = std::fs::path("C:\\Windows\\Fonts") / fontPath;
registerFont(fontName.c_str(), wolv::util::toUTF8String(fontPath).c_str());
}
valueNameSize = valueName.size();
valueDataSize = valueData.size();
index++;
}
RegCloseKey(key);
}
}
void Window::configureGLFW() {
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
glfwWindowHint(GLFW_DECORATED, ImHexApi::System::isBorderlessWindowModeEnabled() ? GL_FALSE : GL_TRUE);
// Windows versions before Windows 10 have issues with transparent framebuffers
// causing the entire window to be slightly transparent ignoring all configurations
OSVERSIONINFOA versionInfo = { };
if (::GetVersionExA(&versionInfo) && versionInfo.dwMajorVersion >= 10) {
glfwWindowHint(GLFW_TRANSPARENT_FRAMEBUFFER, GLFW_TRUE);
} else {
glfwWindowHint(GLFW_TRANSPARENT_FRAMEBUFFER, GLFW_FALSE);
}
}
void Window::initNative() {
// Setup DPI Awareness
{
using SetProcessDpiAwarenessContextFunc = HRESULT(WINAPI *)(DPI_AWARENESS_CONTEXT);
SetProcessDpiAwarenessContextFunc setProcessDpiAwarenessContext =
reinterpret_cast<SetProcessDpiAwarenessContextFunc>(
reinterpret_cast<void*>(
GetProcAddress(GetModuleHandleW(L"user32.dll"), "SetProcessDpiAwarenessContext")
)
);
if (setProcessDpiAwarenessContext != nullptr) {
setProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
}
}
if (ImHexApi::System::isDebugBuild()) {
// If the application is running in debug mode, ImHex runs under the CONSOLE subsystem,
// so we don't need to do anything besides enabling ANSI colors
log::impl::enableColorPrinting();
} else if (hex::getEnvironmentVariable("__IMHEX_FORWARD_CONSOLE__") == "1") {
// Check for the __IMHEX_FORWARD_CONSOLE__ environment variable that was set by the forwarder application
// If it's present, attach to its console window
::AttachConsole(ATTACH_PARENT_PROCESS);
// Reopen stdin, stdout and stderr to the console if not in debug mode
reopenConsoleHandle(STD_INPUT_HANDLE, STDIN_FILENO, stdin);
reopenConsoleHandle(STD_OUTPUT_HANDLE, STDOUT_FILENO, stdout);
// Enable ANSI colors in the console
log::impl::enableColorPrinting();
} else {
log::impl::redirectToFile();
}
// Add plugin library folders to dll search path
for (const auto &path : paths::Libraries.read()) {
if (std::fs::exists(path))
AddDllDirectory(path.c_str());
}
enumerateFonts();
}
class DropManager : public IDropTarget {
public:
DropManager() = default;
virtual ~DropManager() = default;
ULONG AddRef() override { return 1; }
ULONG Release() override { return 0; }
HRESULT QueryInterface(REFIID riid, void **ppvObject) override {
if (riid == IID_IDropTarget) {
*ppvObject = this;
return S_OK;
}
*ppvObject = nullptr;
return E_NOINTERFACE;
}
HRESULT STDMETHODCALLTYPE DragEnter(
IDataObject *,
DWORD,
POINTL,
DWORD *pdwEffect) override
{
EventFileDragged::post(true);
*pdwEffect = DROPEFFECT_COPY;
return S_OK;
}
HRESULT STDMETHODCALLTYPE DragOver(
DWORD,
POINTL,
DWORD *pdwEffect) override
{
*pdwEffect = DROPEFFECT_COPY;
return S_OK;
}
HRESULT STDMETHODCALLTYPE DragLeave() override
{
EventFileDragged::post(false);
return S_OK;
}
HRESULT STDMETHODCALLTYPE Drop(
IDataObject *pDataObj,
DWORD,
POINTL,
DWORD *pdwEffect) override
{
FORMATETC fmte = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
STGMEDIUM stgm;
if (SUCCEEDED(pDataObj->GetData(&fmte, &stgm))) {
auto hdrop = HDROP(stgm.hGlobal);
auto fileCount = DragQueryFile(hdrop, 0xFFFFFFFF, nullptr, 0);
for (UINT i = 0; i < fileCount; i++) {
WCHAR szFile[MAX_PATH];
UINT cch = DragQueryFileW(hdrop, i, szFile, MAX_PATH);
if (cch > 0 && cch < MAX_PATH) {
EventFileDropped::post(szFile);
}
}
ReleaseStgMedium(&stgm);
}
EventFileDragged::post(false);
*pdwEffect &= DROPEFFECT_COPY;
return S_OK;
}
};
void Window::setupNativeWindow() {
// Setup borderless window
auto hwnd = glfwGetWin32Window(m_window);
CoInitialize(nullptr);
OleInitialize(nullptr);
static DropManager dm;
if (RegisterDragDrop(hwnd, &dm) != S_OK) {
log::warn("Failed to register drop target");
// Register fallback drop target using glfw
glfwSetDropCallback(m_window, [](GLFWwindow *, int count, const char **paths) {
for (int i = 0; i < count; i++) {
EventFileDropped::post(reinterpret_cast<const char8_t *>(paths[i]));
}
});
}
bool borderlessWindowMode = ImHexApi::System::isBorderlessWindowModeEnabled();
// Set up the correct window procedure based on the borderless window mode state
if (borderlessWindowMode) {
s_oldWndProc = ::SetWindowLongPtr(hwnd, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(borderlessWindowProc));
MARGINS borderless = { 1, 1, 1, 1 };
::DwmExtendFrameIntoClientArea(hwnd, &borderless);
DWORD attribute = DWMNCRP_ENABLED;
::DwmSetWindowAttribute(hwnd, DWMWA_NCRENDERING_POLICY, &attribute, sizeof(attribute));
::SetWindowPos(hwnd, nullptr, 0, 0, 0, 0, SWP_NOZORDER | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSIZE | SWP_NOMOVE);
} else {
s_oldWndProc = ::SetWindowLongPtr(hwnd, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(commonWindowProc));
}
// Set up a taskbar progress handler
{
if (SUCCEEDED(CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED))) {
CoCreateInstance(CLSID_TaskbarList, nullptr, CLSCTX_INPROC_SERVER, IID_ITaskbarList4, &s_taskbarList);
}
EventSetTaskBarIconState::subscribe([hwnd](u32 state, u32 type, u32 progress){
using enum ImHexApi::System::TaskProgressState;
switch (ImHexApi::System::TaskProgressState(state)) {
case Reset:
s_taskbarList->SetProgressState(hwnd, TBPF_NOPROGRESS);
s_taskbarList->SetProgressValue(hwnd, 0, 0);
break;
case Flash:
FlashWindow(hwnd, true);
break;
case Progress:
s_taskbarList->SetProgressState(hwnd, TBPF_INDETERMINATE);
s_taskbarList->SetProgressValue(hwnd, progress, 100);
break;
}
using enum ImHexApi::System::TaskProgressType;
switch (ImHexApi::System::TaskProgressType(type)) {
case Normal:
s_taskbarList->SetProgressState(hwnd, TBPF_NORMAL);
break;
case Warning:
s_taskbarList->SetProgressState(hwnd, TBPF_PAUSED);
break;
case Error:
s_taskbarList->SetProgressState(hwnd, TBPF_ERROR);
break;
}
});
}
struct ACCENTPOLICY {
u32 accentState;
u32 accentFlags;
u32 gradientColor;
u32 animationId;
};
struct WINCOMPATTRDATA {
int attribute;
PVOID pData;
ULONG dataSize;
};
EventThemeChanged::subscribe([this]{
auto hwnd = glfwGetWin32Window(m_window);
static auto user32Dll = WinUniquePtr<HMODULE>(LoadLibraryA("user32.dll"), FreeLibrary);
if (user32Dll != nullptr) {
using SetWindowCompositionAttributeFunc = BOOL(WINAPI*)(HWND, WINCOMPATTRDATA*);
const auto setWindowCompositionAttribute =
reinterpret_cast<SetWindowCompositionAttributeFunc>(
reinterpret_cast<void*>(
GetProcAddress(user32Dll.get(), "SetWindowCompositionAttribute")
)
);
if (setWindowCompositionAttribute != nullptr) {
ACCENTPOLICY policy = { ImGuiExt::GetCustomStyle().WindowBlur > 0.5F ? 4U : 0U, 0, ImGuiExt::GetCustomColorU32(ImGuiCustomCol_BlurBackground), 0 };
WINCOMPATTRDATA data = { 19, &policy, sizeof(ACCENTPOLICY) };
setWindowCompositionAttribute(hwnd, &data);
}
}
});
RequestChangeTheme::subscribe([this](const std::string &theme) {
auto hwnd = glfwGetWin32Window(m_window);
BOOL value = theme == "Dark" ? TRUE : FALSE;
DwmSetWindowAttribute(hwnd, DWMWA_USE_IMMERSIVE_DARK_MODE, &value, sizeof(value));
});
ImGui::GetIO().ConfigDebugIsDebuggerPresent = ::IsDebuggerPresent();
glfwSetFramebufferSizeCallback(m_window, [](GLFWwindow* window, int width, int height) {
auto *win = static_cast<Window *>(glfwGetWindowUserPointer(window));
win->m_unlockFrameRate = true;
glViewport(0, 0, width, height);
ImHexApi::System::impl::setMainWindowSize(width, height);
});
DwmEnableMMCSS(TRUE);
{
constexpr BOOL value = TRUE;
DwmSetWindowAttribute(hwnd, DWMWA_NCRENDERING_ENABLED, &value, sizeof(value));
}
{
constexpr DWMNCRENDERINGPOLICY value = DWMNCRP_ENABLED;
DwmSetWindowAttribute(hwnd, DWMWA_NCRENDERING_POLICY, &value, sizeof(value));
}
glfwSetWindowRefreshCallback(m_window, [](GLFWwindow *window) {
auto win = static_cast<Window *>(glfwGetWindowUserPointer(window));
win->fullFrame();
DwmFlush();
});
}
void Window::beginNativeWindowFrame() {
s_titleBarHeight = ImGui::GetCurrentWindowRead()->MenuBarHeight;
// Remove WS_POPUP style from the window to make various window management tools work
auto hwnd = glfwGetWin32Window(m_window);
::SetWindowLong(hwnd, GWL_STYLE, (GetWindowLong(hwnd, GWL_STYLE) | WS_OVERLAPPEDWINDOW) & ~WS_POPUP);
::SetWindowLong(hwnd, GWL_EXSTYLE, GetWindowLong(hwnd, GWL_EXSTYLE) | WS_EX_COMPOSITED | WS_EX_LAYERED);
if (!ImHexApi::System::impl::isWindowResizable()) {
if (glfwGetWindowAttrib(m_window, GLFW_MAXIMIZED)) {
glfwRestoreWindow(m_window);
}
}
}
void Window::endNativeWindowFrame() {
}
}
#endif
| 25,919
|
C++
|
.cpp
| 549
| 31.965392
| 188
| 0.543336
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
305
|
web_window.cpp
|
WerWolv_ImHex/main/gui/source/window/web_window.cpp
|
#include "window.hpp"
#if defined(OS_WEB)
#include <emscripten.h>
#include <emscripten/html5.h>
#include <hex/api/event_manager.hpp>
#include <imgui.h>
#include <imgui_internal.h>
// Function used by c++ to get the size of the html canvas
EM_JS(int, canvas_get_width, (), {
return Module.canvas.width;
});
// Function used by c++ to get the size of the html canvas
EM_JS(int, canvas_get_height, (), {
return Module.canvas.height;
});
// Function called by javascript
EM_JS(void, resizeCanvas, (), {
js_resizeCanvas();
});
EM_JS(void, fixCanvasInPlace, (), {
document.getElementById('canvas').classList.add('canvas-fixed');
});
EM_JS(void, setupThemeListener, (), {
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', event => {
Module._handleThemeChange();
});
});
EM_JS(bool, isDarkModeEnabled, (), {
return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
});
EMSCRIPTEN_KEEPALIVE
extern "C" void handleThemeChange() {
hex::EventOSThemeChanged::post();
}
EM_JS(void, setupInputModeListener, (), {
Module.canvas.addEventListener('mousedown', function() {
Module._enterMouseMode();
});
Module.canvas.addEventListener('touchstart', function() {
Module._enterTouchMode();
});
});
EMSCRIPTEN_KEEPALIVE
extern "C" void enterMouseMode() {
ImGui::GetIO().AddMouseSourceEvent(ImGuiMouseSource_Mouse);
}
EMSCRIPTEN_KEEPALIVE
extern "C" void enterTouchMode() {
ImGui::GetIO().AddMouseSourceEvent(ImGuiMouseSource_TouchScreen);
}
namespace hex {
void nativeErrorMessage(const std::string &message) {
log::fatal(message);
EM_ASM({
alert(UTF8ToString($0));
}, message.c_str());
}
void Window::configureGLFW() {
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
glfwWindowHint(GLFW_DECORATED, GL_FALSE);
glfwWindowHint(GLFW_TRANSPARENT_FRAMEBUFFER, GLFW_FALSE);
}
void Window::initNative() {
EM_ASM({
// Save data directory
FS.mkdir("/home/web_user/.local");
FS.mount(IDBFS, {}, '/home/web_user/.local');
FS.syncfs(true, function (err) {
if (!err)
return;
alert("Failed to load permanent file system: "+err);
});
// Center splash screen
document.getElementById('canvas').classList.remove('canvas-fixed');
});
}
void Window::setupNativeWindow() {
resizeCanvas();
setupThemeListener();
setupInputModeListener();
fixCanvasInPlace();
bool themeFollowSystem = ImHexApi::System::usesSystemThemeDetection();
EventOSThemeChanged::subscribe(this, [themeFollowSystem] {
if (!themeFollowSystem) return;
RequestChangeTheme::post(!isDarkModeEnabled() ? "Light" : "Dark");
});
// Register file drop callback
glfwSetDropCallback(m_window, [](GLFWwindow *, int count, const char **paths) {
for (int i = 0; i < count; i++) {
EventFileDropped::post(reinterpret_cast<const char8_t *>(paths[i]));
}
});
glfwSetWindowRefreshCallback(m_window, [](GLFWwindow *window) {
auto win = static_cast<Window *>(glfwGetWindowUserPointer(window));
resizeCanvas();
win->fullFrame();
});
if (themeFollowSystem)
EventOSThemeChanged::post();
}
void Window::beginNativeWindowFrame() {
static i32 prevWidth = 0;
static i32 prevHeight = 0;
auto width = canvas_get_width();
auto height = canvas_get_height();
if (prevWidth != width || prevHeight != height) {
// Size has changed
prevWidth = width;
prevHeight = height;
this->resize(width, height);
}
}
void Window::endNativeWindowFrame() {
}
}
#endif
| 4,041
|
C++
|
.cpp
| 117
| 27.606838
| 91
| 0.628792
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
306
|
window.cpp
|
WerWolv_ImHex/main/gui/source/window/window.cpp
|
#include "window.hpp"
#include <hex.hpp>
#include <hex/api/plugin_manager.hpp>
#include <hex/api/content_registry.hpp>
#include <hex/api/imhex_api.hpp>
#include <hex/api/layout_manager.hpp>
#include <hex/api/shortcut_manager.hpp>
#include <hex/api/workspace_manager.hpp>
#include <hex/api/tutorial_manager.hpp>
#include <hex/helpers/utils.hpp>
#include <hex/helpers/fs.hpp>
#include <hex/helpers/logger.hpp>
#include <hex/helpers/default_paths.hpp>
#include <hex/ui/view.hpp>
#include <hex/ui/popup.hpp>
#include <chrono>
#include <csignal>
#include <romfs/romfs.hpp>
#include <imgui.h>
#include <imgui_internal.h>
#include <imgui_impl_glfw.h>
#include <imgui_impl_opengl3.h>
#include <hex/ui/imgui_imhex_extensions.h>
#include <implot.h>
#include <implot_internal.h>
#include <imnodes.h>
#include <imnodes_internal.h>
#include <wolv/utils/string.hpp>
#include <GLFW/glfw3.h>
#include <hex/ui/toast.hpp>
#include <wolv/utils/guards.hpp>
#include <fmt/printf.h>
namespace hex {
using namespace std::literals::chrono_literals;
Window::Window() {
const static auto openEmergencyPopup = [this](const std::string &title){
TaskManager::doLater([this, title] {
for (const auto &provider : ImHexApi::Provider::getProviders())
ImHexApi::Provider::remove(provider, false);
ImGui::OpenPopup(title.c_str());
m_emergencyPopupOpen = true;
});
};
// Handle fatal error popups for errors detected during initialization
{
for (const auto &[argument, value] : ImHexApi::System::getInitArguments()) {
if (argument == "no-plugins") {
openEmergencyPopup("No Plugins");
} else if (argument == "duplicate-plugins") {
openEmergencyPopup("Duplicate Plugins loaded");
}
}
}
// Initialize the window
this->initGLFW();
this->initImGui();
this->setupNativeWindow();
this->registerEventHandlers();
ContentRegistry::Settings::impl::store();
ContentRegistry::Settings::impl::load();
EventWindowInitialized::post();
EventImHexStartupFinished::post();
TutorialManager::init();
}
Window::~Window() {
EventProviderDeleted::unsubscribe(this);
RequestCloseImHex::unsubscribe(this);
RequestUpdateWindowTitle::unsubscribe(this);
EventAbnormalTermination::unsubscribe(this);
RequestOpenPopup::unsubscribe(this);
EventWindowDeinitializing::post(m_window);
ContentRegistry::Settings::impl::store();
this->exitImGui();
this->exitGLFW();
}
void Window::registerEventHandlers() {
// Initialize default theme
RequestChangeTheme::post("Dark");
// Handle the close window request by telling GLFW to shut down
RequestCloseImHex::subscribe(this, [this](bool noQuestions) {
glfwSetWindowShouldClose(m_window, GLFW_TRUE);
if (!noQuestions)
EventWindowClosing::post(m_window);
});
// Handle opening popups
RequestOpenPopup::subscribe(this, [this](auto name) {
std::scoped_lock lock(m_popupMutex);
m_popupsToOpen.push_back(name);
});
EventDPIChanged::subscribe([this](float oldScaling, float newScaling) {
if (oldScaling == newScaling || oldScaling == 0 || newScaling == 0)
return;
int width, height;
glfwGetWindowSize(m_window, &width, &height);
width = float(width) * newScaling / oldScaling;
height = float(height) * newScaling / oldScaling;
ImHexApi::System::impl::setMainWindowSize(width, height);
glfwSetWindowSize(m_window, width, height);
});
LayoutManager::registerLoadCallback([this](std::string_view line) {
int width = 0, height = 0;
sscanf(line.data(), "MainWindowSize=%d,%d", &width, &height);
if (width > 0 && height > 0) {
TaskManager::doLater([width, height, this]{
glfwSetWindowSize(m_window, width, height);
});
}
});
}
void handleException() {
try {
throw;
} catch (const std::exception &e) {
log::fatal("Unhandled exception: {}", e.what());
EventCrashRecovered::post(e);
} catch (...) {
log::fatal("Unhandled exception: Unknown exception");
}
}
void errorRecoverLogCallback(void*, const char* fmt, ...) {
va_list args;
std::string message;
va_start(args, fmt);
message.resize(std::vsnprintf(nullptr, 0, fmt, args));
va_end(args);
va_start(args, fmt);
std::vsnprintf(message.data(), message.size(), fmt, args);
va_end(args);
message.resize(message.size() - 1);
log::error("{}", message);
}
void Window::fullFrame() {
[[maybe_unused]] static u32 crashWatchdog = 0;
if (auto g = ImGui::GetCurrentContext(); g == nullptr || g->WithinFrameScope) {
return;
}
#if !defined(DEBUG)
try {
#endif
// Render an entire frame
this->frameBegin();
this->frame();
this->frameEnd();
#if !defined(DEBUG)
// Feed the watchdog
crashWatchdog = 0;
} catch (...) {
// If an exception keeps being thrown, abort the application after 10 frames
// This is done to avoid the application getting stuck in an infinite loop of exceptions
crashWatchdog += 1;
if (crashWatchdog > 10) {
log::fatal("Crash watchdog triggered, aborting");
std::abort();
}
// Try to recover from the exception by bringing ImGui back into a working state
ImGui::ErrorCheckEndFrameRecover(errorRecoverLogCallback, nullptr);
ImGui::EndFrame();
ImGui::UpdatePlatformWindows();
// Handle the exception
handleException();
}
#endif
}
void Window::loop() {
glfwShowWindow(m_window);
while (!glfwWindowShouldClose(m_window)) {
m_lastStartFrameTime = glfwGetTime();
{
int x = 0, y = 0;
int width = 0, height = 0;
glfwGetWindowPos(m_window, &x, &y);
glfwGetWindowSize(m_window, &width, &height);
ImHexApi::System::impl::setMainWindowPosition(x, y);
ImHexApi::System::impl::setMainWindowSize(width, height);
}
// Determine if the application should be in long sleep mode
bool shouldLongSleep = !m_unlockFrameRate;
static double lockTimeout = 0;
if (!shouldLongSleep) {
lockTimeout = 0.05;
} else if (lockTimeout > 0) {
lockTimeout -= m_lastFrameTime;
}
if (shouldLongSleep && lockTimeout > 0)
shouldLongSleep = false;
m_unlockFrameRate = false;
if (!glfwGetWindowAttrib(m_window, GLFW_VISIBLE) || glfwGetWindowAttrib(m_window, GLFW_ICONIFIED)) {
// If the application is minimized or not visible, don't render anything
glfwWaitEvents();
} else {
// If the application is visible, render a frame
// If the application is in long sleep mode, only render a frame every 200ms
// Long sleep mode is enabled automatically after a few frames if the window content hasn't changed
// and no events have been received
if (shouldLongSleep) {
// Calculate the time until the next frame
constexpr static auto LongSleepFPS = 5.0;
const double timeout = std::max(0.0, (1.0 / LongSleepFPS) - (glfwGetTime() - m_lastStartFrameTime));
glfwPollEvents();
glfwWaitEventsTimeout(timeout);
} else {
glfwPollEvents();
}
}
m_lastStartFrameTime = glfwGetTime();
static ImVec2 lastWindowSize = ImHexApi::System::getMainWindowSize();
if (ImHexApi::System::impl::isWindowResizable()) {
glfwSetWindowSizeLimits(m_window, 480_scaled, 360_scaled, GLFW_DONT_CARE, GLFW_DONT_CARE);
lastWindowSize = ImHexApi::System::getMainWindowSize();
} else {
glfwSetWindowSizeLimits(m_window, lastWindowSize.x, lastWindowSize.y, lastWindowSize.x, lastWindowSize.y);
}
this->fullFrame();
ImHexApi::System::impl::setLastFrameTime(glfwGetTime() - m_lastStartFrameTime);
// Limit frame rate
// If the target FPS are below 15, use the monitor refresh rate, if it's above 200, don't limit the frame rate
auto targetFPS = ImHexApi::System::getTargetFPS();
if (targetFPS >= 200) {
// Let it rip
} else {
// If the target frame rate is below 15, use the current monitor's refresh rate
if (targetFPS < 15) {
// Fall back to 60 FPS if the monitor refresh rate cannot be determined
targetFPS = 60;
if (auto monitor = glfwGetWindowMonitor(m_window); monitor != nullptr) {
if (auto videoMode = glfwGetVideoMode(monitor); videoMode != nullptr) {
targetFPS = videoMode->refreshRate;
}
}
}
// Sleep if we're not in long sleep mode
if (!shouldLongSleep) {
// If anything goes wrong with these checks, make sure that we're sleeping for at least 1ms
std::this_thread::sleep_for(std::chrono::milliseconds(1));
// Sleep for the remaining time if the frame rate is above the target frame rate
const auto frameTime = glfwGetTime() - m_lastStartFrameTime;
const auto targetFrameTime = 1.0 / targetFPS;
if (frameTime < targetFrameTime) {
glfwWaitEventsTimeout(targetFrameTime - frameTime);
// glfwWaitEventsTimeout might return early if there's an event
if (frameTime < targetFrameTime) {
const auto timeToSleepMs = (int)((targetFrameTime - frameTime) * 1000);
std::this_thread::sleep_for(std::chrono::milliseconds(timeToSleepMs));
}
}
}
}
m_lastFrameTime = glfwGetTime() - m_lastStartFrameTime;
}
// Hide the window as soon as the render loop exits to make the window
// disappear as soon as it's closed
glfwHideWindow(m_window);
}
void Window::frameBegin() {
// Start new ImGui Frame
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
EventFrameBegin::post();
// Handle all undocked floating windows
ImGuiViewport *viewport = ImGui::GetMainViewport();
ImGui::SetNextWindowPos(viewport->WorkPos);
ImGui::SetNextWindowSize(ImHexApi::System::getMainWindowSize() - ImVec2(0, ImGui::GetTextLineHeightWithSpacing()));
ImGui::SetNextWindowViewport(viewport->ID);
ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0F);
ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0F);
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0));
ImGuiWindowFlags windowFlags = ImGuiWindowFlags_NoDocking | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoNavFocus | ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse;
if (!m_emergencyPopupOpen)
windowFlags |= ImGuiWindowFlags_MenuBar;
// Render main dock space
if (ImGui::Begin("ImHexDockSpace", nullptr, windowFlags)) {
ImGui::PopStyleVar();
this->beginNativeWindowFrame();
} else {
ImGui::PopStyleVar();
}
ImGui::End();
ImGui::PopStyleVar(2);
// Plugin load error popups
// These are not translated because they should always be readable, no matter if any localization could be loaded or not
{
const static auto drawPluginFolderTable = [] {
ImGuiExt::UnderlinedText("Plugin folders");
if (ImGui::BeginTable("plugins", 2, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_ScrollY | ImGuiTableFlags_SizingFixedFit, ImVec2(0, 100_scaled))) {
ImGui::TableSetupScrollFreeze(0, 1);
ImGui::TableSetupColumn("Path", ImGuiTableColumnFlags_WidthStretch, 0.2);
ImGui::TableSetupColumn("Exists", ImGuiTableColumnFlags_WidthFixed, ImGui::GetTextLineHeight() * 3);
ImGui::TableHeadersRow();
for (const auto &path : paths::Plugins.all()) {
const auto filePath = path / "builtin.hexplug";
ImGui::TableNextRow();
ImGui::TableNextColumn();
ImGui::TextUnformatted(wolv::util::toUTF8String(filePath).c_str());
ImGui::TableNextColumn();
ImGui::TextUnformatted(wolv::io::fs::exists(filePath) ? "Yes" : "No");
}
ImGui::EndTable();
}
};
if (m_emergencyPopupOpen) {
const auto pos = ImHexApi::System::getMainWindowPosition();
const auto size = ImHexApi::System::getMainWindowSize();
ImGui::GetBackgroundDrawList()->AddRectFilled(pos, pos + size, ImGui::GetColorU32(ImGuiCol_WindowBg) | 0xFF000000);
}
ImGui::PushStyleColor(ImGuiCol_ModalWindowDimBg, 0x00);
ON_SCOPE_EXIT { ImGui::PopStyleColor(); };
// No plugins error popup
ImGui::SetNextWindowPos(ImGui::GetMainViewport()->GetCenter(), ImGuiCond_Always, ImVec2(0.5F, 0.5F));
if (ImGui::BeginPopupModal("No Plugins", nullptr, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoTitleBar)) {
ImGui::BringWindowToDisplayFront(ImGui::GetCurrentWindowRead());
ImGui::TextUnformatted("No ImHex plugins loaded (including the built-in plugin)!");
ImGui::TextUnformatted("Make sure you installed ImHex correctly.");
ImGui::TextUnformatted("There should be at least a 'builtin.hexplug' file in your plugins folder.");
ImGui::NewLine();
drawPluginFolderTable();
ImGui::NewLine();
if (ImGuiExt::DimmedButton("Close ImHex", ImVec2(ImGui::GetContentRegionAvail().x, 0)))
ImHexApi::System::closeImHex(true);
ImGui::EndPopup();
}
// Duplicate plugins error popup
ImGui::SetNextWindowPos(ImGui::GetMainViewport()->GetCenter(), ImGuiCond_Always, ImVec2(0.5F, 0.5F));
if (ImGui::BeginPopupModal("Duplicate Plugins loaded", nullptr, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoTitleBar)) {
ImGui::BringWindowToDisplayFront(ImGui::GetCurrentWindowRead());
ImGui::TextUnformatted("ImHex found and attempted to load multiple plugins with the same name!");
ImGui::TextUnformatted("Make sure you installed ImHex correctly and, if needed,");
ImGui::TextUnformatted("cleaned up older installations correctly.");
ImGui::TextUnformatted("Each plugin should only ever be loaded once.");
ImGui::NewLine();
drawPluginFolderTable();
ImGui::NewLine();
if (ImGuiExt::DimmedButton("Close ImHex", ImVec2(ImGui::GetContentRegionAvail().x, 0)))
ImHexApi::System::closeImHex(true);
ImGui::EndPopup();
}
}
// Open popups when plugins requested it
{
std::scoped_lock lock(m_popupMutex);
m_popupsToOpen.remove_if([](const auto &name) {
if (ImGui::IsPopupOpen(name.c_str()))
return true;
else
ImGui::OpenPopup(name.c_str());
return false;
});
}
// Draw popup stack
{
static bool positionSet = false;
static bool sizeSet = false;
static double popupDelay = -2.0;
static u32 displayFrameCount = 0;
static std::unique_ptr<impl::PopupBase> currPopup;
static Lang name("");
AT_FIRST_TIME {
EventImHexClosing::subscribe([] {
currPopup.reset();
});
};
if (auto &popups = impl::PopupBase::getOpenPopups(); !popups.empty()) {
if (!ImGui::IsPopupOpen(ImGuiID(0), ImGuiPopupFlags_AnyPopupId)) {
if (popupDelay <= -1.0) {
popupDelay = 0.2;
} else {
popupDelay -= m_lastFrameTime;
if (popupDelay < 0 || popups.size() == 1) {
popupDelay = -2.0;
currPopup = std::move(popups.back());
name = Lang(currPopup->getUnlocalizedName());
displayFrameCount = 0;
ImGui::OpenPopup(name);
popups.pop_back();
}
}
}
}
if (currPopup != nullptr) {
bool open = true;
const auto &minSize = currPopup->getMinSize();
const auto &maxSize = currPopup->getMaxSize();
const bool hasConstraints = minSize.x != 0 && minSize.y != 0 && maxSize.x != 0 && maxSize.y != 0;
if (hasConstraints)
ImGui::SetNextWindowSizeConstraints(minSize, maxSize);
else
ImGui::SetNextWindowSize(ImVec2(0, 0), ImGuiCond_Appearing);
auto* closeButton = currPopup->hasCloseButton() ? &open : nullptr;
const auto flags = currPopup->getFlags() | (!hasConstraints ? (ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoResize) : ImGuiWindowFlags_None);
if (!positionSet) {
ImGui::SetNextWindowPos(ImHexApi::System::getMainWindowPosition() + (ImHexApi::System::getMainWindowSize() / 2.0F), ImGuiCond_Always, ImVec2(0.5F, 0.5F));
if (sizeSet)
positionSet = true;
}
const auto createPopup = [&](bool displaying) {
if (displaying) {
displayFrameCount += 1;
currPopup->drawContent();
if (ImGui::GetWindowSize().x > ImGui::GetStyle().FramePadding.x * 10)
sizeSet = true;
// Reset popup position if it's outside the main window when multi-viewport is not enabled
// If not done, the popup will be stuck outside the main window and cannot be accessed anymore
if ((ImGui::GetIO().ConfigFlags & ImGuiConfigFlags_ViewportsEnable) == ImGuiConfigFlags_None) {
const auto currWindowPos = ImGui::GetWindowPos();
const auto minWindowPos = ImHexApi::System::getMainWindowPosition() - ImGui::GetWindowSize();
const auto maxWindowPos = ImHexApi::System::getMainWindowPosition() + ImHexApi::System::getMainWindowSize();
if (currWindowPos.x > maxWindowPos.x || currWindowPos.y > maxWindowPos.y || currWindowPos.x < minWindowPos.x || currWindowPos.y < minWindowPos.y) {
positionSet = false;
GImGui->MovingWindow = nullptr;
}
}
ImGui::EndPopup();
}
};
if (currPopup->isModal())
createPopup(ImGui::BeginPopupModal(name, closeButton, flags));
else
createPopup(ImGui::BeginPopup(name, flags));
if (!ImGui::IsPopupOpen(name) && displayFrameCount < 5) {
ImGui::OpenPopup(name);
}
if (currPopup->shouldClose() || !open) {
log::debug("Closing popup '{}'", name);
positionSet = sizeSet = false;
currPopup = nullptr;
}
}
}
// Draw Toasts
{
u32 index = 0;
for (const auto &toast : impl::ToastBase::getQueuedToasts() | std::views::take(4)) {
const auto toastHeight = 60_scaled;
ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 5_scaled);
ImGui::SetNextWindowSize(ImVec2(280_scaled, toastHeight));
ImGui::SetNextWindowPos((ImHexApi::System::getMainWindowPosition() + ImHexApi::System::getMainWindowSize()) - scaled({ 10, 10 }) - scaled({ 0, (10 + toastHeight) * index }), ImGuiCond_Always, ImVec2(1, 1));
if (ImGui::Begin(hex::format("##Toast_{}", index).c_str(), nullptr, ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_NoDocking | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoFocusOnAppearing)) {
auto drawList = ImGui::GetWindowDrawList();
const auto min = ImGui::GetWindowPos();
const auto max = min + ImGui::GetWindowSize();
drawList->PushClipRect(min, min + scaled({ 5, 60 }));
drawList->AddRectFilled(min, max, toast->getColor(), 5_scaled);
drawList->PopClipRect();
ImGui::Indent();
toast->draw();
ImGui::Unindent();
if (ImGui::IsWindowHovered() || toast->getAppearTime() <= 0)
toast->setAppearTime(ImGui::GetTime());
}
ImGui::End();
ImGui::PopStyleVar();
index += 1;
}
std::erase_if(impl::ToastBase::getQueuedToasts(), [](const auto &toast){
return toast->getAppearTime() > 0 && (toast->getAppearTime() + impl::ToastBase::VisibilityTime) < ImGui::GetTime();
});
}
// Run all deferred calls
TaskManager::runDeferredCalls();
}
void Window::frame() {
auto &io = ImGui::GetIO();
// Loop through all views and draw them
for (auto &[name, view] : ContentRegistry::Views::impl::getEntries()) {
ImGui::GetCurrentContext()->NextWindowData.ClearFlags();
// Draw always visible views
view->drawAlwaysVisibleContent();
// Skip views that shouldn't be processed currently
if (!view->shouldProcess())
continue;
const auto openViewCount = std::ranges::count_if(ContentRegistry::Views::impl::getEntries(), [](const auto &entry) {
const auto &[unlocalizedName, openView] = entry;
return openView->hasViewMenuItemEntry() && openView->shouldProcess();
});
ImGuiWindowClass windowClass = {};
windowClass.DockNodeFlagsOverrideSet |= ImGuiDockNodeFlags_NoCloseButton;
if (openViewCount <= 1 || LayoutManager::isLayoutLocked())
windowClass.DockNodeFlagsOverrideSet |= ImGuiDockNodeFlags_NoTabBar;
ImGui::SetNextWindowClass(&windowClass);
auto window = ImGui::FindWindowByName(view->getName().c_str());
if (window != nullptr && window->DockNode == nullptr)
ImGui::SetNextWindowBgAlpha(1.0F);
// Draw view
view->draw();
view->trackViewOpenState();
if (view->getWindowOpenState()) {
bool hasWindow = window != nullptr;
bool focused = false;
// Get the currently focused view
if (hasWindow && (window->Flags & ImGuiWindowFlags_Popup) != ImGuiWindowFlags_Popup) {
auto windowName = View::toWindowName(name);
ImGui::Begin(windowName.c_str());
// Detect if the window is focused
focused = ImGui::IsWindowFocused(ImGuiFocusedFlags_ChildWindows | ImGuiFocusedFlags_NoPopupHierarchy);
// Dock the window if it's not already docked
if (view->didWindowJustOpen() && !ImGui::IsWindowDocked()) {
ImGui::DockBuilderDockWindow(windowName.c_str(), ImHexApi::System::getMainDockSpaceId());
EventViewOpened::post(view.get());
}
// Pass on currently pressed keys to the shortcut handler
for (const auto &key : m_pressedKeys) {
ShortcutManager::process(view.get(), io.KeyCtrl, io.KeyAlt, io.KeyShift, io.KeySuper, focused, key);
}
ImGui::End();
}
}
}
// Handle global shortcuts
for (const auto &key : m_pressedKeys) {
ShortcutManager::processGlobals(io.KeyCtrl, io.KeyAlt, io.KeyShift, io.KeySuper, key);
}
m_pressedKeys.clear();
}
void Window::frameEnd() {
EventFrameEnd::post();
TutorialManager::drawTutorial();
// Clean up all tasks that are done
TaskManager::collectGarbage();
this->endNativeWindowFrame();
ImGui::ErrorCheckEndFrameRecover(errorRecoverLogCallback, nullptr);
// Finalize ImGui frame
ImGui::Render();
// Compare the previous frame buffer to the current one to determine if the window content has changed
// If not, there's no point in sending the draw data off to the GPU and swapping buffers
// NOTE: For anybody looking at this code and thinking "why not just hash the buffer and compare the hashes",
// the reason is that hashing the buffer is significantly slower than just comparing the buffers directly.
// The buffer might become quite large if there's a lot of vertices on the screen but it's still usually less than
// 10MB (out of which only the active portion needs to actually be compared) which is worth the ~60x speedup.
bool shouldRender = false;
{
static std::vector<u8> previousVtxData;
static size_t previousVtxDataSize = 0;
size_t offset = 0;
size_t vtxDataSize = 0;
for (const auto viewPort : ImGui::GetPlatformIO().Viewports) {
auto drawData = viewPort->DrawData;
for (int n = 0; n < drawData->CmdListsCount; n++) {
vtxDataSize += drawData->CmdLists[n]->VtxBuffer.size() * sizeof(ImDrawVert);
}
}
for (const auto viewPort : ImGui::GetPlatformIO().Viewports) {
auto drawData = viewPort->DrawData;
for (int n = 0; n < drawData->CmdListsCount; n++) {
const ImDrawList *cmdList = drawData->CmdLists[n];
std::string ownerName = cmdList->_OwnerName;
if (vtxDataSize == previousVtxDataSize && (!ownerName.contains("##Popup") || !ownerName.contains("##image"))) {
shouldRender = shouldRender || std::memcmp(previousVtxData.data() + offset, cmdList->VtxBuffer.Data, cmdList->VtxBuffer.size() * sizeof(ImDrawVert)) != 0;
} else {
shouldRender = true;
}
if (previousVtxData.size() < offset + cmdList->VtxBuffer.size() * sizeof(ImDrawVert)) {
previousVtxData.resize(offset + cmdList->VtxBuffer.size() * sizeof(ImDrawVert));
}
std::memcpy(previousVtxData.data() + offset, cmdList->VtxBuffer.Data, cmdList->VtxBuffer.size() * sizeof(ImDrawVert));
offset += cmdList->VtxBuffer.size() * sizeof(ImDrawVert);
}
}
previousVtxDataSize = vtxDataSize;
}
GLFWwindow *backupContext = glfwGetCurrentContext();
ImGui::UpdatePlatformWindows();
ImGui::RenderPlatformWindowsDefault();
glfwMakeContextCurrent(backupContext);
if (shouldRender) {
auto* drawData = ImGui::GetDrawData();
// Avoid accidentally clearing the viewport when the application is minimized,
// otherwise the OS will display an empty frame during deminimization on macOS
if (drawData->DisplaySize.x != 0 && drawData->DisplaySize.y != 0) {
int displayWidth, displayHeight;
glfwGetFramebufferSize(m_window, &displayWidth, &displayHeight);
glViewport(0, 0, displayWidth, displayHeight);
glClearColor(0.00F, 0.00F, 0.00F, 0.00F);
glClear(GL_COLOR_BUFFER_BIT);
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
glfwSwapBuffers(m_window);
}
m_unlockFrameRate = true;
}
// Process layout load requests
// NOTE: This needs to be done before a new frame is started, otherwise ImGui won't handle docking correctly
LayoutManager::process();
WorkspaceManager::process();
}
void Window::initGLFW() {
auto initialWindowProperties = ImHexApi::System::getInitialWindowProperties();
glfwSetErrorCallback([](int error, const char *desc) {
bool isWaylandError = error == GLFW_PLATFORM_ERROR;
#if defined(GLFW_FEATURE_UNAVAILABLE)
isWaylandError = isWaylandError || (error == GLFW_FEATURE_UNAVAILABLE);
#endif
isWaylandError = isWaylandError && std::string_view(desc).contains("Wayland");
if (isWaylandError) {
// Ignore error spam caused by Wayland not supporting moving or resizing
// windows or querying their position and size.
return;
}
try {
log::error("GLFW Error [0x{:05X}] : {}", error, desc);
} catch (const std::system_error &) {
// Catch and ignore system error that might be thrown when too many errors are being logged to a file
}
});
if (!glfwInit()) {
log::fatal("Failed to initialize GLFW!");
std::abort();
}
configureGLFW();
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);
glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_API);
if (initialWindowProperties.has_value()) {
glfwWindowHint(GLFW_MAXIMIZED, initialWindowProperties->maximized);
}
// Create window
m_windowTitle = "ImHex";
m_window = glfwCreateWindow(1280_scaled, 720_scaled, m_windowTitle.c_str(), nullptr, nullptr);
ImHexApi::System::impl::setMainWindowHandle(m_window);
glfwSetWindowUserPointer(m_window, this);
if (m_window == nullptr) {
log::fatal("Failed to create window!");
std::abort();
}
// Force window to be fully opaque by default
glfwSetWindowOpacity(m_window, 1.0F);
glfwMakeContextCurrent(m_window);
// Disable VSync. Not like any graphics driver actually cares
glfwSwapInterval(0);
// Center window
GLFWmonitor *monitor = glfwGetPrimaryMonitor();
if (monitor != nullptr) {
const GLFWvidmode *mode = glfwGetVideoMode(monitor);
if (mode != nullptr) {
int monitorX, monitorY;
glfwGetMonitorPos(monitor, &monitorX, &monitorY);
int windowWidth, windowHeight;
glfwGetWindowSize(m_window, &windowWidth, &windowHeight);
glfwSetWindowPos(m_window, monitorX + (mode->width - windowWidth) / 2, monitorY + (mode->height - windowHeight) / 2);
}
}
// Set up initial window position
{
int x = 0, y = 0;
glfwGetWindowPos(m_window, &x, &y);
if (initialWindowProperties.has_value()) {
x = initialWindowProperties->x;
y = initialWindowProperties->y;
}
ImHexApi::System::impl::setMainWindowPosition(x, y);
glfwSetWindowPos(m_window, x, y);
}
// Set up initial window size
{
int width = 0, height = 0;
glfwGetWindowSize(m_window, &width, &height);
if (initialWindowProperties.has_value()) {
width = initialWindowProperties->width;
height = initialWindowProperties->height;
}
ImHexApi::System::impl::setMainWindowSize(width, height);
glfwSetWindowSize(m_window, width, height);
}
// Register window move callback
glfwSetWindowPosCallback(m_window, [](GLFWwindow *window, int x, int y) {
ImHexApi::System::impl::setMainWindowPosition(x, y);
auto win = static_cast<Window *>(glfwGetWindowUserPointer(window));
win->m_unlockFrameRate = true;
win->fullFrame();
});
// Register window resize callback
glfwSetWindowSizeCallback(m_window, [](GLFWwindow *window, [[maybe_unused]] int width, [[maybe_unused]] int height) {
auto win = static_cast<Window *>(glfwGetWindowUserPointer(window));
win->m_unlockFrameRate = true;
#if !defined(OS_WINDOWS)
if (!glfwGetWindowAttrib(window, GLFW_ICONIFIED))
ImHexApi::System::impl::setMainWindowSize(width, height);
#endif
#if defined(OS_MACOS)
// Stop widgets registering hover effects while the window is being resized
if (macosIsWindowBeingResizedByUser(window)) {
ImGui::GetIO().MousePos = ImVec2();
}
#elif defined(OS_WEB)
win->fullFrame();
#endif
});
glfwSetCursorPosCallback(m_window, [](GLFWwindow *window, double, double) {
auto win = static_cast<Window *>(glfwGetWindowUserPointer(window));
win->m_unlockFrameRate = true;
});
glfwSetWindowFocusCallback(m_window, [](GLFWwindow *, int focused) {
EventWindowFocused::post(focused == GLFW_TRUE);
});
#if !defined(OS_WEB)
// Register key press callback
glfwSetInputMode(m_window, GLFW_LOCK_KEY_MODS, GLFW_TRUE);
glfwSetKeyCallback(m_window, [](GLFWwindow *window, int key, int scanCode, int action, int mods) {
hex::unused(mods);
// Handle A-Z keys using their ASCII value instead of the keycode
if (key >= GLFW_KEY_A && key <= GLFW_KEY_Z) {
std::string_view name = glfwGetKeyName(key, scanCode);
// If the key name is only one character long, use the ASCII value instead
// Otherwise the keyboard was set to a non-English layout and the key name
// is not the same as the ASCII value
if (!name.empty()) {
const std::uint8_t byte = name[0];
if (name.length() == 1 && byte <= 0x7F) {
key = std::toupper(byte);
}
}
}
if (key == GLFW_KEY_UNKNOWN) return;
if (action == GLFW_PRESS || action == GLFW_REPEAT) {
if (key != GLFW_KEY_LEFT_CONTROL && key != GLFW_KEY_RIGHT_CONTROL &&
key != GLFW_KEY_LEFT_ALT && key != GLFW_KEY_RIGHT_ALT &&
key != GLFW_KEY_LEFT_SHIFT && key != GLFW_KEY_RIGHT_SHIFT &&
key != GLFW_KEY_LEFT_SUPER && key != GLFW_KEY_RIGHT_SUPER
) {
auto win = static_cast<Window *>(glfwGetWindowUserPointer(window));
win->m_unlockFrameRate = true;
if (!(mods & GLFW_MOD_NUM_LOCK)) {
if (key == GLFW_KEY_KP_0) key = GLFW_KEY_INSERT;
else if (key == GLFW_KEY_KP_1) key = GLFW_KEY_END;
else if (key == GLFW_KEY_KP_2) key = GLFW_KEY_DOWN;
else if (key == GLFW_KEY_KP_3) key = GLFW_KEY_PAGE_DOWN;
else if (key == GLFW_KEY_KP_4) key = GLFW_KEY_LEFT;
else if (key == GLFW_KEY_KP_6) key = GLFW_KEY_RIGHT;
else if (key == GLFW_KEY_KP_7) key = GLFW_KEY_HOME;
else if (key == GLFW_KEY_KP_8) key = GLFW_KEY_UP;
else if (key == GLFW_KEY_KP_9) key = GLFW_KEY_PAGE_UP;
}
win->m_pressedKeys.push_back(key);
}
}
});
#endif
// Register window close callback
glfwSetWindowCloseCallback(m_window, [](GLFWwindow *window) {
EventWindowClosing::post(window);
});
glfwSetWindowSizeLimits(m_window, 480_scaled, 360_scaled, GLFW_DONT_CARE, GLFW_DONT_CARE);
}
void Window::resize(i32 width, i32 height) {
glfwSetWindowSize(m_window, width, height);
}
void Window::initImGui() {
IMGUI_CHECKVERSION();
auto fonts = ImHexApi::Fonts::getFontAtlas();
if (fonts == nullptr) {
fonts = IM_NEW(ImFontAtlas)();
fonts->AddFontDefault();
fonts->Build();
}
// Initialize ImGui and all other ImGui extensions
GImGui = ImGui::CreateContext(fonts);
GImPlot = ImPlot::CreateContext();
GImNodes = ImNodes::CreateContext();
ImGuiIO &io = ImGui::GetIO();
ImGuiStyle &style = ImGui::GetStyle();
ImNodes::GetStyle().Flags = ImNodesStyleFlags_NodeOutline | ImNodesStyleFlags_GridLines;
io.ConfigFlags |= ImGuiConfigFlags_DockingEnable | ImGuiConfigFlags_NavEnableKeyboard;
io.ConfigWindowsMoveFromTitleBarOnly = true;
io.FontGlobalScale = 1.0F;
if (glfwGetPrimaryMonitor() != nullptr) {
if (ImHexApi::System::isMutliWindowModeEnabled())
io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable;
}
io.ConfigViewportsNoTaskBarIcon = false;
ImNodes::PushAttributeFlag(ImNodesAttributeFlags_EnableLinkDetachWithDragClick);
ImNodes::PushAttributeFlag(ImNodesAttributeFlags_EnableLinkCreationOnSnap);
// Allow ImNodes links to always be detached without holding down any button
{
static bool always = true;
ImNodes::GetIO().LinkDetachWithModifierClick.Modifier = &always;
}
io.UserData = &m_imguiCustomData;
auto scale = ImHexApi::System::getGlobalScale();
style.ScaleAllSizes(scale);
io.DisplayFramebufferScale = ImVec2(scale, scale);
io.Fonts->SetTexID(fonts->TexID);
style.WindowMenuButtonPosition = ImGuiDir_None;
style.IndentSpacing = 10.0F;
style.DisplaySafeAreaPadding = ImVec2(0.0F, 0.0F);
style.Colors[ImGuiCol_TabSelectedOverline] = ImVec4(0.0F, 0.0F, 0.0F, 0.0F);
style.Colors[ImGuiCol_TabDimmedSelectedOverline] = ImVec4(0.0F, 0.0F, 0.0F, 0.0F);
// Install custom settings handler
{
ImGuiSettingsHandler handler;
handler.TypeName = "ImHex";
handler.TypeHash = ImHashStr("ImHex");
handler.ReadOpenFn = [](ImGuiContext *ctx, ImGuiSettingsHandler *, const char *) -> void* { return ctx; };
handler.ReadLineFn = [](ImGuiContext *, ImGuiSettingsHandler *, void *, const char *line) {
LayoutManager::onLoad(line);
};
handler.WriteAllFn = [](ImGuiContext *, ImGuiSettingsHandler *handler, ImGuiTextBuffer *buffer) {
buffer->appendf("[%s][General]\n", handler->TypeName);
LayoutManager::onStore(buffer);
buffer->append("\n");
};
handler.UserData = this;
auto context = ImGui::GetCurrentContext();
context->SettingsHandlers.push_back(handler);
context->TestEngineHookItems = true;
io.IniFilename = nullptr;
}
ImGui_ImplGlfw_InitForOpenGL(m_window, true);
#if defined(OS_MACOS)
ImGui_ImplOpenGL3_Init("#version 150");
#elif defined(OS_WEB)
ImGui_ImplOpenGL3_Init();
ImGui_ImplGlfw_InstallEmscriptenCanvasResizeCallback("#canvas");
#else
ImGui_ImplOpenGL3_Init("#version 130");
#endif
for (const auto &plugin : PluginManager::getPlugins())
plugin.setImGuiContext(ImGui::GetCurrentContext());
RequestInitThemeHandlers::post();
}
void Window::exitGLFW() {
glfwDestroyWindow(m_window);
glfwTerminate();
m_window = nullptr;
}
void Window::exitImGui() {
ImGui_ImplOpenGL3_Shutdown();
ImGui_ImplGlfw_Shutdown();
ImPlot::DestroyContext();
ImGui::DestroyContext();
}
}
| 42,703
|
C++
|
.cpp
| 829
| 37.347407
| 319
| 0.570155
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
307
|
macos_window.cpp
|
WerWolv_ImHex/main/gui/source/window/macos_window.cpp
|
#include "window.hpp"
#if defined(OS_MACOS)
#include <hex/api/project_file_manager.hpp>
#include <hex/api/imhex_api.hpp>
#include <hex/api/event_manager.hpp>
#include <hex/api/task_manager.hpp>
#include <hex/helpers/utils_macos.hpp>
#include <hex/helpers/logger.hpp>
#include <hex/helpers/default_paths.hpp>
#include <unistd.h>
#include <imgui_impl_glfw.h>
namespace hex {
void nativeErrorMessage(const std::string &message) {
log::fatal(message);
errorMessageMacos(message.c_str());
}
void Window::configureGLFW() {
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_COCOA_RETINA_FRAMEBUFFER, GLFW_FALSE);
glfwWindowHint(GLFW_COCOA_GRAPHICS_SWITCHING, GLFW_TRUE);
glfwWindowHint(GLFW_TRANSPARENT_FRAMEBUFFER, GLFW_TRUE);
}
void Window::initNative() {
log::impl::enableColorPrinting();
// Add plugin library folders to dll search path
for (const auto &path : paths::Libraries.read()) {
if (std::fs::exists(path))
setenv("LD_LIBRARY_PATH", hex::format("{};{}", hex::getEnvironmentVariable("LD_LIBRARY_PATH").value_or(""), path.string().c_str()).c_str(), true);
}
// Redirect stdout to log file if we're not running in a terminal
if (!isatty(STDOUT_FILENO)) {
log::impl::redirectToFile();
}
enumerateFontsMacos();
}
void Window::setupNativeWindow() {
bool themeFollowSystem = ImHexApi::System::usesSystemThemeDetection();
EventOSThemeChanged::subscribe(this, [themeFollowSystem] {
if (!themeFollowSystem) return;
if (!isMacosSystemDarkModeEnabled())
RequestChangeTheme::post("Light");
else
RequestChangeTheme::post("Dark");
});
EventProviderDirtied::subscribe([this](prv::Provider *) {
TaskManager::doLater([this] {
macosMarkContentEdited(m_window);
});
});
ProjectFile::registerHandler({
.basePath = "",
.required = true,
.load = [](const std::fs::path &, Tar &) {
return true;
},
.store = [this](const std::fs::path &, Tar &) {
TaskManager::doLater([this] {
macosMarkContentEdited(m_window, false);
});
return true;
}
});
if (themeFollowSystem)
EventOSThemeChanged::post();
// Register file drop callback
glfwSetDropCallback(m_window, [](GLFWwindow *, int count, const char **paths) {
for (int i = 0; i < count; i++) {
EventFileDropped::post(reinterpret_cast<const char8_t *>(paths[i]));
}
});
setupMacosWindowStyle(m_window, ImHexApi::System::isBorderlessWindowModeEnabled());
glfwSetWindowRefreshCallback(m_window, [](GLFWwindow *window) {
auto win = static_cast<Window *>(glfwGetWindowUserPointer(window));
win->fullFrame();
});
}
void Window::beginNativeWindowFrame() {
}
void Window::endNativeWindowFrame() {
}
}
#endif
| 3,382
|
C++
|
.cpp
| 84
| 30.571429
| 162
| 0.598411
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
308
|
api_urls.hpp
|
WerWolv_ImHex/lib/libimhex/include/hex/api_urls.hpp
|
#pragma once
constexpr static auto ImHexApiURL = "https://api.werwolv.net/imhex";
constexpr static auto GitHubApiURL = "https://api.github.com/repos/WerWolv/ImHex";
| 167
|
C++
|
.h
| 3
| 54.333333
| 82
| 0.785276
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
309
|
plugin.hpp
|
WerWolv_ImHex/lib/libimhex/include/hex/plugin.hpp
|
#pragma once
#include <hex.hpp>
#include <hex/api/plugin_manager.hpp>
#include <hex/helpers/logger.hpp>
#include <string>
#include <imgui.h>
#include <imgui_internal.h>
#include <wolv/utils/string.hpp>
#include <wolv/utils/preproc.hpp>
#include <wolv/utils/guards.hpp>
namespace {
struct PluginFunctionHelperInstantiation {};
}
template<typename T>
struct PluginFeatureFunctionHelper {
static void* getFeatures();
};
template<typename T>
struct PluginSubCommandsFunctionHelper {
static void* getSubCommands();
};
template<typename T>
void* PluginFeatureFunctionHelper<T>::getFeatures() {
return nullptr;
}
template<typename T>
void* PluginSubCommandsFunctionHelper<T>::getSubCommands() {
return nullptr;
}
[[maybe_unused]] static auto& getFeaturesImpl() {
static std::vector<hex::Feature> features;
return features;
}
#if defined (IMHEX_STATIC_LINK_PLUGINS)
#define IMHEX_PLUGIN_VISIBILITY_PREFIX static
#else
#define IMHEX_PLUGIN_VISIBILITY_PREFIX extern "C" [[gnu::visibility("default")]]
#endif
#define IMHEX_FEATURE_ENABLED(feature) WOLV_TOKEN_CONCAT(WOLV_TOKEN_CONCAT(WOLV_TOKEN_CONCAT(IMHEX_PLUGIN_, IMHEX_PLUGIN_NAME), _FEATURE_), feature)
#define IMHEX_DEFINE_PLUGIN_FEATURES() IMHEX_DEFINE_PLUGIN_FEATURES_IMPL()
#define IMHEX_DEFINE_PLUGIN_FEATURES_IMPL() \
template<> \
struct PluginFeatureFunctionHelper<PluginFunctionHelperInstantiation> { \
static void* getFeatures(); \
}; \
void* PluginFeatureFunctionHelper<PluginFunctionHelperInstantiation>::getFeatures() { \
return &getFeaturesImpl(); \
} \
static auto initFeatures = [] { getFeaturesImpl() = std::vector<hex::Feature>({ IMHEX_PLUGIN_FEATURES_CONTENT }); return 0; }()
#define IMHEX_PLUGIN_FEATURES ::getFeaturesImpl()
/**
* This macro is used to define all the required entry points for a plugin.
* Name, Author and Description will be displayed in the plugin list on the Welcome screen.
*/
#define IMHEX_PLUGIN_SETUP(name, author, description) IMHEX_PLUGIN_SETUP_IMPL(name, author, description)
#define IMHEX_LIBRARY_SETUP(name) IMHEX_LIBRARY_SETUP_IMPL(name)
#define IMHEX_LIBRARY_SETUP_IMPL(name) \
namespace { static struct EXIT_HANDLER { ~EXIT_HANDLER() { hex::log::debug("Unloaded library '{}'", name); } } HANDLER; } \
IMHEX_PLUGIN_VISIBILITY_PREFIX void WOLV_TOKEN_CONCAT(initializeLibrary_, IMHEX_PLUGIN_NAME)(); \
IMHEX_PLUGIN_VISIBILITY_PREFIX const char *WOLV_TOKEN_CONCAT(getLibraryName_, IMHEX_PLUGIN_NAME)() { return name; } \
IMHEX_PLUGIN_VISIBILITY_PREFIX void WOLV_TOKEN_CONCAT(setImGuiContext_, IMHEX_PLUGIN_NAME)(ImGuiContext *ctx) { \
ImGui::SetCurrentContext(ctx); \
GImGui = ctx; \
} \
extern "C" [[gnu::visibility("default")]] void WOLV_TOKEN_CONCAT(forceLinkPlugin_, IMHEX_PLUGIN_NAME)() { \
hex::PluginManager::addPlugin(name, hex::PluginFunctions { \
nullptr, \
WOLV_TOKEN_CONCAT(initializeLibrary_, IMHEX_PLUGIN_NAME), \
nullptr, \
WOLV_TOKEN_CONCAT(getLibraryName_, IMHEX_PLUGIN_NAME), \
nullptr, \
nullptr, \
nullptr, \
WOLV_TOKEN_CONCAT(setImGuiContext_, IMHEX_PLUGIN_NAME), \
nullptr, \
nullptr, \
nullptr \
}); \
} \
IMHEX_PLUGIN_VISIBILITY_PREFIX void WOLV_TOKEN_CONCAT(initializeLibrary_, IMHEX_PLUGIN_NAME)()
#define IMHEX_PLUGIN_SETUP_IMPL(name, author, description) \
namespace { static struct EXIT_HANDLER { ~EXIT_HANDLER() { hex::log::debug("Unloaded plugin '{}'", name); } } HANDLER; } \
IMHEX_PLUGIN_VISIBILITY_PREFIX const char *getPluginName() { return name; } \
IMHEX_PLUGIN_VISIBILITY_PREFIX const char *getPluginAuthor() { return author; } \
IMHEX_PLUGIN_VISIBILITY_PREFIX const char *getPluginDescription() { return description; } \
IMHEX_PLUGIN_VISIBILITY_PREFIX const char *getCompatibleVersion() { return IMHEX_VERSION; } \
IMHEX_PLUGIN_VISIBILITY_PREFIX void setImGuiContext(ImGuiContext *ctx) { \
ImGui::SetCurrentContext(ctx); \
GImGui = ctx; \
} \
IMHEX_DEFINE_PLUGIN_FEATURES(); \
IMHEX_PLUGIN_VISIBILITY_PREFIX void* getFeatures() { \
return PluginFeatureFunctionHelper<PluginFunctionHelperInstantiation>::getFeatures(); \
} \
IMHEX_PLUGIN_VISIBILITY_PREFIX void* getSubCommands() { \
return PluginSubCommandsFunctionHelper<PluginFunctionHelperInstantiation>::getSubCommands(); \
} \
IMHEX_PLUGIN_VISIBILITY_PREFIX void initializePlugin(); \
extern "C" [[gnu::visibility("default")]] void WOLV_TOKEN_CONCAT(forceLinkPlugin_, IMHEX_PLUGIN_NAME)() { \
hex::PluginManager::addPlugin(name, hex::PluginFunctions { \
initializePlugin, \
nullptr, \
getPluginName, \
nullptr, \
getPluginAuthor, \
getPluginDescription, \
getCompatibleVersion, \
setImGuiContext, \
nullptr, \
getSubCommands, \
getFeatures \
}); \
} \
IMHEX_PLUGIN_VISIBILITY_PREFIX void initializePlugin()
/**
* This macro is used to define subcommands defined by the plugin
* A subcommand consists of a key, a description, and a callback
* The key is what the first argument to ImHex should be, prefixed by `--`
* For example, if the key if `help`, ImHex should be started with `--help` as its first argument to trigger the subcommand
* when the subcommand is triggerred, it's callback will be executed. The callback is executed BEFORE most of ImHex initialization
* so to do anything meaningful, you should subscribe to an event (like EventImHexStartupFinished) and run your code there.
*/
#define IMHEX_PLUGIN_SUBCOMMANDS() IMHEX_PLUGIN_SUBCOMMANDS_IMPL()
#define IMHEX_PLUGIN_SUBCOMMANDS_IMPL() \
extern std::vector<hex::SubCommand> g_subCommands; \
template<> \
struct PluginSubCommandsFunctionHelper<PluginFunctionHelperInstantiation> { \
static void* getSubCommands(); \
}; \
void* PluginSubCommandsFunctionHelper<PluginFunctionHelperInstantiation>::getSubCommands() { \
return &g_subCommands; \
} \
std::vector<hex::SubCommand> g_subCommands
| 11,619
|
C++
|
.h
| 133
| 81.93985
| 148
| 0.37548
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
310
|
node.hpp
|
WerWolv_ImHex/lib/libimhex/include/hex/data_processor/node.hpp
|
#pragma once
#include <hex.hpp>
#include <hex/api/localization_manager.hpp>
#include <hex/helpers/intrinsics.hpp>
#include <hex/data_processor/attribute.hpp>
#include <set>
#include <span>
#include <vector>
#include <nlohmann/json_fwd.hpp>
#include <imgui.h>
#include <hex/providers/provider_data.hpp>
namespace hex::prv {
class Provider;
class Overlay;
}
namespace hex::dp {
class Node {
public:
Node(UnlocalizedString unlocalizedTitle, std::vector<Attribute> attributes);
virtual ~Node() = default;
[[nodiscard]] int getId() const { return m_id; }
void setId(int id) { m_id = id; }
[[nodiscard]] const UnlocalizedString &getUnlocalizedName() const { return m_unlocalizedName; }
void setUnlocalizedName(const UnlocalizedString &unlocalizedName) { m_unlocalizedName = unlocalizedName; }
[[nodiscard]] const UnlocalizedString &getUnlocalizedTitle() const { return m_unlocalizedTitle; }
void setUnlocalizedTitle(std::string title) { m_unlocalizedTitle = std::move(title); }
[[nodiscard]] std::vector<Attribute> &getAttributes() { return m_attributes; }
[[nodiscard]] const std::vector<Attribute> &getAttributes() const { return m_attributes; }
void setCurrentOverlay(prv::Overlay *overlay) {
m_overlay = overlay;
}
void draw();
virtual void process() = 0;
virtual void reset() { }
virtual void store(nlohmann::json &j) const { hex::unused(j); }
virtual void load(const nlohmann::json &j) { hex::unused(j); }
struct NodeError {
Node *node;
std::string message;
};
void resetOutputData() {
for (auto &attribute : m_attributes)
attribute.clearOutputData();
}
void resetProcessedInputs() {
m_processedInputs.clear();
}
void setPosition(ImVec2 pos) {
m_position = pos;
}
[[nodiscard]] ImVec2 getPosition() const {
return m_position;
}
static void setIdCounter(int id);
const std::vector<u8>& getBufferOnInput(u32 index);
const i128& getIntegerOnInput(u32 index);
const double& getFloatOnInput(u32 index);
void setBufferOnOutput(u32 index, std::span<const u8> data);
void setIntegerOnOutput(u32 index, i128 integer);
void setFloatOnOutput(u32 index, double floatingPoint);
static void interrupt();
protected:
virtual void drawNode() { }
private:
int m_id;
UnlocalizedString m_unlocalizedTitle, m_unlocalizedName;
std::vector<Attribute> m_attributes;
std::set<u32> m_processedInputs;
prv::Overlay *m_overlay = nullptr;
ImVec2 m_position;
static int s_idCounter;
Attribute& getAttribute(u32 index);
Attribute *getConnectedInputAttribute(u32 index);
void markInputProcessed(u32 index);
void unmarkInputProcessed(u32 index);
protected:
[[noreturn]] void throwNodeError(const std::string &message);
void setOverlayData(u64 address, const std::vector<u8> &data);
void setAttributes(std::vector<Attribute> attributes);
};
}
| 3,271
|
C++
|
.h
| 81
| 32.444444
| 114
| 0.651899
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
311
|
attribute.hpp
|
WerWolv_ImHex/lib/libimhex/include/hex/data_processor/attribute.hpp
|
#pragma once
#include <hex.hpp>
#include <hex/api/localization_manager.hpp>
#include <string>
#include <string_view>
#include <map>
#include <vector>
namespace hex::dp {
class Node;
class Attribute {
public:
enum class Type {
Integer,
Float,
Buffer
};
enum class IOType {
In,
Out
};
Attribute(IOType ioType, Type type, UnlocalizedString unlocalizedName);
~Attribute();
[[nodiscard]] int getId() const { return m_id; }
void setId(int id) { m_id = id; }
[[nodiscard]] IOType getIOType() const { return m_ioType; }
[[nodiscard]] Type getType() const { return m_type; }
[[nodiscard]] const UnlocalizedString &getUnlocalizedName() const { return m_unlocalizedName; }
void addConnectedAttribute(int linkId, Attribute *to) { m_connectedAttributes.insert({ linkId, to }); }
void removeConnectedAttribute(int linkId) { m_connectedAttributes.erase(linkId); }
[[nodiscard]] std::map<int, Attribute *> &getConnectedAttributes() { return m_connectedAttributes; }
[[nodiscard]] Node *getParentNode() const { return m_parentNode; }
[[nodiscard]] std::vector<u8>& getOutputData() {
if (!m_outputData.empty())
return m_outputData;
else
return m_defaultData;
}
void clearOutputData() { m_outputData.clear(); }
[[nodiscard]] std::vector<u8>& getDefaultData() { return m_defaultData; }
static void setIdCounter(int id);
private:
int m_id;
IOType m_ioType;
Type m_type;
UnlocalizedString m_unlocalizedName;
std::map<int, Attribute *> m_connectedAttributes;
Node *m_parentNode = nullptr;
std::vector<u8> m_outputData;
std::vector<u8> m_defaultData;
friend class Node;
void setParentNode(Node *node) { m_parentNode = node; }
static int s_idCounter;
};
}
| 2,034
|
C++
|
.h
| 54
| 29.203704
| 111
| 0.611933
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
312
|
link.hpp
|
WerWolv_ImHex/lib/libimhex/include/hex/data_processor/link.hpp
|
#pragma once
namespace hex::dp {
class Link {
public:
Link(int from, int to);
[[nodiscard]] int getId() const { return m_id; }
void setId(int id) { m_id = id; }
[[nodiscard]] int getFromId() const { return m_from; }
[[nodiscard]] int getToId() const { return m_to; }
static void setIdCounter(int id);
private:
int m_id;
int m_from, m_to;
static int s_idCounter;
};
}
| 462
|
C++
|
.h
| 16
| 21.9375
| 62
| 0.558087
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
313
|
tests.hpp
|
WerWolv_ImHex/lib/libimhex/include/hex/test/tests.hpp
|
#pragma once
#include <hex.hpp>
#include <utility>
#include <hex/helpers/utils.hpp>
#include <hex/helpers/fmt.hpp>
#include <hex/helpers/logger.hpp>
#include <hex/api/plugin_manager.hpp>
#include <wolv/utils/preproc.hpp>
#include <string>
#include <map>
#include <functional>
#define TEST_SEQUENCE(...) static auto WOLV_ANONYMOUS_VARIABLE(TEST_SEQUENCE) = ::hex::test::TestSequenceExecutor(__VA_ARGS__) + []() -> int
#define TEST_FAIL() return EXIT_FAILURE
#define TEST_SUCCESS() return EXIT_SUCCESS
#define FAILING true
#define TEST_ASSERT(x, ...) \
do { \
auto ret = (x); \
if (!ret) { \
hex::log::error("Test assert '" #x "' failed {} at {}:{}", \
hex::format("" __VA_ARGS__), \
__FILE__, \
__LINE__); \
return EXIT_FAILURE; \
} \
} while (0)
#define INIT_PLUGIN(name) \
if (!hex::test::initPluginImpl(name)) TEST_FAIL();
namespace hex::test {
using Function = int(*)();
struct Test {
Function function;
bool shouldFail;
};
class Tests {
public:
static auto addTest(const std::string &name, Function func, bool shouldFail) noexcept {
s_tests.insert({
name, {func, shouldFail}
});
return 0;
}
static auto &get() noexcept {
return s_tests;
}
private:
static std::map<std::string, Test> s_tests;
};
template<class F>
class TestSequence {
public:
TestSequence(const std::string &name, F func, bool shouldFail) noexcept {
Tests::addTest(name, func, shouldFail);
}
TestSequence &operator=(TestSequence &&) = delete;
};
struct TestSequenceExecutor {
explicit TestSequenceExecutor(std::string name, bool shouldFail = false) noexcept : m_name(std::move(name)), m_shouldFail(shouldFail) {
}
[[nodiscard]] const auto &getName() const noexcept {
return m_name;
}
[[nodiscard]] bool shouldFail() const noexcept {
return m_shouldFail;
}
private:
std::string m_name;
bool m_shouldFail;
};
template<typename F>
TestSequence<F> operator+(const TestSequenceExecutor &executor, F &&f) noexcept {
return TestSequence<F>(executor.getName(), std::forward<F>(f), executor.shouldFail());
}
bool initPluginImpl(std::string name);
}
| 2,901
|
C++
|
.h
| 75
| 31.653333
| 143
| 0.506058
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
314
|
test_provider.hpp
|
WerWolv_ImHex/lib/libimhex/include/hex/test/test_provider.hpp
|
#pragma once
#include <hex/providers/provider.hpp>
#include <nlohmann/json.hpp>
namespace hex::test {
using namespace hex::prv;
class TestProvider : public prv::Provider {
public:
explicit TestProvider(std::vector<u8> *data) {
this->setData(data);
}
~TestProvider() override = default;
[[nodiscard]] bool isAvailable() const override { return true; }
[[nodiscard]] bool isReadable() const override { return true; }
[[nodiscard]] bool isWritable() const override { return false; }
[[nodiscard]] bool isResizable() const override { return false; }
[[nodiscard]] bool isSavable() const override { return false; }
void setData(std::vector<u8> *data) {
m_data = data;
}
[[nodiscard]] std::string getName() const override {
return "";
}
[[nodiscard]] std::vector<Description> getDataDescription() const override {
return {};
}
void readRaw(u64 offset, void *buffer, size_t size) override {
if (offset + size > m_data->size()) return;
std::memcpy(buffer, m_data->data() + offset, size);
}
void writeRaw(u64 offset, const void *buffer, size_t size) override {
if (offset + size > m_data->size()) return;
std::memcpy(m_data->data() + offset, buffer, size);
}
[[nodiscard]] u64 getActualSize() const override {
return m_data->size();
}
[[nodiscard]] std::string getTypeName() const override { return "hex.test.provider.test"; }
bool open() override { return true; }
void close() override { }
nlohmann::json storeSettings(nlohmann::json) const override { return {}; }
void loadSettings(const nlohmann::json &) override {};
private:
std::vector<u8> *m_data = nullptr;
};
}
| 1,914
|
C++
|
.h
| 45
| 33.688889
| 99
| 0.597192
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
315
|
memory_provider.hpp
|
WerWolv_ImHex/lib/libimhex/include/hex/providers/memory_provider.hpp
|
#pragma once
#include <hex/providers/provider.hpp>
namespace hex::prv {
/**
* This is a simple mock provider that can be used to pass in-memory data to APIs that require a provider.
* It's NOT a provider that can be loaded by the user.
*/
class MemoryProvider : public hex::prv::Provider {
public:
MemoryProvider() = default;
explicit MemoryProvider(std::vector<u8> data, std::string name = "") : m_data(std::move(data)), m_name(std::move(name)) { }
~MemoryProvider() override = default;
MemoryProvider(const MemoryProvider&) = delete;
MemoryProvider& operator=(const MemoryProvider&) = delete;
MemoryProvider(MemoryProvider &&provider) noexcept = default;
MemoryProvider& operator=(MemoryProvider &&provider) noexcept = default;
[[nodiscard]] bool isAvailable() const override { return true; }
[[nodiscard]] bool isReadable() const override { return true; }
[[nodiscard]] bool isWritable() const override { return true; }
[[nodiscard]] bool isResizable() const override { return true; }
[[nodiscard]] bool isSavable() const override { return m_name.empty(); }
[[nodiscard]] bool isSavableAsRecent() const override { return false; }
[[nodiscard]] bool open() override;
void close() override { }
void readRaw(u64 offset, void *buffer, size_t size) override;
void writeRaw(u64 offset, const void *buffer, size_t size) override;
[[nodiscard]] u64 getActualSize() const override { return m_data.size(); }
void resizeRaw(u64 newSize) override;
[[nodiscard]] std::string getName() const override { return m_name; }
[[nodiscard]] std::string getTypeName() const override { return "MemoryProvider"; }
private:
void renameFile();
private:
std::vector<u8> m_data;
std::string m_name;
};
}
| 2,011
|
C++
|
.h
| 37
| 46.783784
| 131
| 0.62946
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
316
|
provider.hpp
|
WerWolv_ImHex/lib/libimhex/include/hex/providers/provider.hpp
|
#pragma once
#include <hex.hpp>
#include <list>
#include <map>
#include <optional>
#include <string>
#include <variant>
#include <vector>
#include <hex/providers/overlay.hpp>
#include <hex/helpers/fs.hpp>
#include <nlohmann/json_fwd.hpp>
#include <hex/providers/undo_redo/stack.hpp>
namespace hex::prv {
/**
* @brief Represent the data source for a tab in the UI
*/
class Provider {
public:
struct Description {
std::string name;
std::string value;
};
struct MenuEntry {
std::string name;
std::function<void()> callback;
};
constexpr static u64 MaxPageSize = 0xFFFF'FFFF'FFFF'FFFF;
Provider();
virtual ~Provider();
Provider(const Provider&) = delete;
Provider& operator=(const Provider&) = delete;
Provider(Provider &&provider) noexcept = default;
Provider& operator=(Provider &&provider) noexcept = default;
/**
* @brief Opens this provider
* @note The return value of this function allows to ensure the provider is available,
* so calling Provider::isAvailable() just after a call to open() that returned true is redundant.
* @note This is not related to the EventProviderOpened event
* @return true if the provider was opened successfully, else false
*/
[[nodiscard]] virtual bool open() = 0;
/**
* @brief Closes this provider
* @note This function is called when the user requests for a provider to be closed, e.g. by closing a tab.
* In general, this function should close the underlying data source but leave the provider in a state where
* it can be opened again later by calling the open() function again.
*/
virtual void close() = 0;
/**
* @brief Checks if this provider is open and can be used to access data
* @return Generally, if the open() function succeeded and the data source was successfully opened, this
* function should return true
*/
[[nodiscard]] virtual bool isAvailable() const = 0;
/**
* @brief Checks if the data in this provider can be read
* @return True if the provider is readable, false otherwise
*/
[[nodiscard]] virtual bool isReadable() const = 0;
/**
* @brief Controls if the user can write data to this specific provider.
* This may be false for e.g. a file opened in read-only
*/
[[nodiscard]] virtual bool isWritable() const = 0;
/**
* @brief Controls if the user can resize this provider
* @return True if the provider is resizable, false otherwise
*/
[[nodiscard]] virtual bool isResizable() const = 0;
/**
* @brief Controls whether the provider can be saved ("saved", not "saved as")
* This is mainly used by providers that aren't buffered, and so don't need to be saved
* This function will usually return false for providers that aren't writable, but this isn't guaranted
*/
[[nodiscard]] virtual bool isSavable() const = 0;
/**
* @brief Controls whether we can dump data from this provider (e.g. "save as", or "export -> ..").
* Typically disabled for process with sparse data, like the Process memory provider
* where the virtual address space is several TiBs large.
* Default implementation returns true.
*/
[[nodiscard]] virtual bool isDumpable() const;
/**
* @brief Controls whether this provider can be saved as a recent entry
* Typically used for providers that do not retain data, e.g. the memory provider
*/
[[nodiscard]] virtual bool isSavableAsRecent() const { return true; }
/**
* @brief Read data from this provider, applying overlays and patches
* @param offset offset to start reading the data
* @param buffer buffer to write read data
* @param size number of bytes to read
* @param overlays apply overlays and patches is true. Same as readRaw() if false
*/
void read(u64 offset, void *buffer, size_t size, bool overlays = true);
/**
* @brief Write data to the patches of this provider. Will not directly modify provider.
* @param offset offset to start writing the data
* @param buffer buffer to take data to write from
* @param size number of bytes to write
*/
void write(u64 offset, const void *buffer, size_t size);
/**
* @brief Read data from this provider, without applying overlays and patches
* @param offset offset to start reading the data
* @param buffer buffer to write read data
* @param size number of bytes to read
*/
virtual void readRaw(u64 offset, void *buffer, size_t size) = 0;
/**
* @brief Write data directly to this provider
* @param offset offset to start writing the data
* @param buffer buffer to take data to write from
* @param size number of bytes to write
*/
virtual void writeRaw(u64 offset, const void *buffer, size_t size) = 0;
/**
* @brief Get the full size of the data in this provider
* @return The size of the entire available data of this provider
*/
[[nodiscard]] virtual u64 getActualSize() const = 0;
/**
* @brief Gets the type name of this provider
* @note This is mainly used to be stored in project files and recents to be able to later on
* recreate this exact provider type. This needs to be unique across all providers, this is usually something
* like "hex.builtin.provider.mem_file" or "hex.builtin.provider.file"
* @return The provider's type name
*/
[[nodiscard]] virtual std::string getTypeName() const = 0;
/**
* @brief Gets a human readable representation of the current provider
* @note This is mainly used to display the provider in the UI. For example, the file provider
* will return the file name here
* @return The name of the current provider
*/
[[nodiscard]] virtual std::string getName() const = 0;
bool resize(u64 newSize);
void insert(u64 offset, u64 size);
void remove(u64 offset, u64 size);
virtual void resizeRaw(u64 newSize) { hex::unused(newSize); }
virtual void insertRaw(u64 offset, u64 size);
virtual void removeRaw(u64 offset, u64 size);
virtual void save();
virtual void saveAs(const std::fs::path &path);
[[nodiscard]] Overlay *newOverlay();
void deleteOverlay(Overlay *overlay);
void applyOverlays(u64 offset, void *buffer, size_t size) const;
[[nodiscard]] const std::list<std::unique_ptr<Overlay>> &getOverlays() const;
[[nodiscard]] u64 getPageSize() const;
void setPageSize(u64 pageSize);
[[nodiscard]] u32 getPageCount() const;
[[nodiscard]] u32 getCurrentPage() const;
void setCurrentPage(u32 page);
virtual void setBaseAddress(u64 address);
[[nodiscard]] virtual u64 getBaseAddress() const;
[[nodiscard]] virtual u64 getCurrentPageAddress() const;
[[nodiscard]] virtual u64 getSize() const;
[[nodiscard]] virtual std::optional<u32> getPageOfAddress(u64 address) const;
[[nodiscard]] virtual std::vector<Description> getDataDescription() const;
[[nodiscard]] virtual std::variant<std::string, i128> queryInformation(const std::string &category, const std::string &argument);
void undo();
void redo();
[[nodiscard]] bool canUndo() const;
[[nodiscard]] bool canRedo() const;
[[nodiscard]] virtual bool hasFilePicker() const;
virtual bool handleFilePicker();
virtual std::vector<MenuEntry> getMenuEntries() { return { }; }
[[nodiscard]] virtual bool hasLoadInterface() const;
[[nodiscard]] virtual bool hasInterface() const;
virtual bool drawLoadInterface();
virtual void drawInterface();
[[nodiscard]] u32 getID() const;
void setID(u32 id);
[[nodiscard]] virtual nlohmann::json storeSettings(nlohmann::json settings) const;
virtual void loadSettings(const nlohmann::json &settings);
void markDirty(bool dirty = true) { m_dirty = dirty; }
[[nodiscard]] bool isDirty() const { return m_dirty; }
[[nodiscard]] virtual std::pair<Region, bool> getRegionValidity(u64 address) const;
void skipLoadInterface() { m_skipLoadInterface = true; }
[[nodiscard]] bool shouldSkipLoadInterface() const { return m_skipLoadInterface; }
void setErrorMessage(const std::string &errorMessage) { m_errorMessage = errorMessage; }
[[nodiscard]] const std::string& getErrorMessage() const { return m_errorMessage; }
template<std::derived_from<undo::Operation> T>
bool addUndoableOperation(auto && ... args) {
return m_undoRedoStack.add<T>(std::forward<decltype(args)...>(args)...);
}
[[nodiscard]] undo::Stack& getUndoStack() { return m_undoRedoStack; }
protected:
u32 m_currPage = 0;
u64 m_baseAddress = 0;
undo::Stack m_undoRedoStack;
std::list<std::unique_ptr<Overlay>> m_overlays;
u32 m_id;
/**
* @brief true if there is any data that needs to be saved
*/
bool m_dirty = false;
/**
* @brief Control whetever to skip provider initialization
* initialization may be asking the user for information related to the provider,
* e.g. a process ID for the process memory provider
* this is used mainly when restoring a provider with already known initialization information
* for example when loading a project or loading a provider from the "recent" lsit
*
*/
bool m_skipLoadInterface = false;
std::string m_errorMessage = "Unspecified error";
u64 m_pageSize = MaxPageSize;
};
}
| 10,316
|
C++
|
.h
| 210
| 40
| 137
| 0.637359
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
317
|
buffered_reader.hpp
|
WerWolv_ImHex/lib/libimhex/include/hex/providers/buffered_reader.hpp
|
#pragma once
#include <hex/providers/provider.hpp>
#include <hex/helpers/literals.hpp>
#include <wolv/io/buffered_reader.hpp>
namespace hex::prv {
using namespace hex::literals;
inline void providerReaderFunction(Provider *provider, void *buffer, u64 address, size_t size) {
provider->read(address, buffer, size);
}
class ProviderReader : public wolv::io::BufferedReader<prv::Provider, providerReaderFunction> {
public:
using BufferedReader::BufferedReader;
explicit ProviderReader(Provider *provider, size_t bufferSize = 0x100000) : BufferedReader(provider, provider->getActualSize(), bufferSize) {
this->setEndAddress(provider->getBaseAddress() + provider->getActualSize() - 1);
this->seek(provider->getBaseAddress());
}
};
}
| 815
|
C++
|
.h
| 18
| 39.444444
| 149
| 0.716456
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
318
|
overlay.hpp
|
WerWolv_ImHex/lib/libimhex/include/hex/providers/overlay.hpp
|
#pragma once
#include <hex.hpp>
#include <vector>
namespace hex::prv {
class Overlay {
public:
Overlay() = default;
void setAddress(u64 address) { m_address = address; }
[[nodiscard]] u64 getAddress() const { return m_address; }
[[nodiscard]] u64 getSize() const { return m_data.size(); }
[[nodiscard]] std::vector<u8> &getData() { return m_data; }
private:
u64 m_address = 0;
std::vector<u8> m_data;
};
}
| 485
|
C++
|
.h
| 16
| 24.375
| 67
| 0.595238
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| true
| false
|
319
|
provider_data.hpp
|
WerWolv_ImHex/lib/libimhex/include/hex/providers/provider_data.hpp
|
#pragma once
#include <hex/api/imhex_api.hpp>
#include <hex/api/event_manager.hpp>
#include <map>
#include <ranges>
#include <utility>
namespace hex {
namespace prv {
class Provider;
}
template<typename T>
class PerProvider {
public:
PerProvider() { this->onCreate(); }
PerProvider(const PerProvider&) = delete;
PerProvider(PerProvider&&) = delete;
PerProvider& operator=(const PerProvider&) = delete;
PerProvider& operator=(PerProvider &&) = delete;
~PerProvider() { this->onDestroy(); }
T* operator->() {
return &this->get();
}
const T* operator->() const {
return &this->get();
}
T& get(const prv::Provider *provider = ImHexApi::Provider::get()) {
return m_data[provider];
}
const T& get(const prv::Provider *provider = ImHexApi::Provider::get()) const {
return m_data.at(provider);
}
void set(const T &data, const prv::Provider *provider = ImHexApi::Provider::get()) {
m_data[provider] = data;
}
void set(T &&data, const prv::Provider *provider = ImHexApi::Provider::get()) {
m_data[provider] = std::move(data);
}
T& operator*() {
return this->get();
}
const T& operator*() const {
return this->get();
}
PerProvider& operator=(const T &data) {
this->set(data);
return *this;
}
PerProvider& operator=(T &&data) {
this->set(std::move(data));
return *this;
}
operator T&() {
return this->get();
}
auto all() {
return m_data | std::views::values;
}
void setOnCreateCallback(std::function<void(prv::Provider *, T&)> callback) {
m_onCreateCallback = std::move(callback);
}
void setOnDestroyCallback(std::function<void(prv::Provider *, T&)> callback) {
m_onDestroyCallback = std::move(callback);
}
private:
void onCreate() {
EventProviderOpened::subscribe(this, [this](prv::Provider *provider) {
auto [it, inserted] = m_data.emplace(provider, T());
auto &[key, value] = *it;
if (m_onCreateCallback)
m_onCreateCallback(provider, value);
});
EventProviderDeleted::subscribe(this, [this](prv::Provider *provider){
if (auto it = m_data.find(provider); it != m_data.end()) {
if (m_onDestroyCallback)
m_onDestroyCallback(provider, m_data.at(provider));
m_data.erase(it);
}
});
EventImHexClosing::subscribe(this, [this] {
m_data.clear();
});
// Moves the data of this PerProvider instance from one provider to another
MovePerProviderData::subscribe(this, [this](prv::Provider *from, prv::Provider *to) {
// Get the value from the old provider, (removes it from the map)
auto node = m_data.extract(from);
// Ensure the value existed
if (node.empty()) return;
// Delete the value from the new provider, that we want to replace
m_data.erase(to);
// Re-insert it with the key of the new provider
node.key() = to;
m_data.insert(std::move(node));
});
}
void onDestroy() {
EventProviderOpened::unsubscribe(this);
EventProviderDeleted::unsubscribe(this);
EventImHexClosing::unsubscribe(this);
MovePerProviderData::unsubscribe(this);
}
private:
std::map<const prv::Provider *, T> m_data;
std::function<void(prv::Provider *, T&)> m_onCreateCallback, m_onDestroyCallback;
};
}
| 4,019
|
C++
|
.h
| 105
| 27.152381
| 97
| 0.539789
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
320
|
stack.hpp
|
WerWolv_ImHex/lib/libimhex/include/hex/providers/undo_redo/stack.hpp
|
#pragma once
#include <hex.hpp>
#include <hex/api/localization_manager.hpp>
#include <hex/api/event_manager.hpp>
#include <hex/providers/undo_redo/operations/operation.hpp>
#include <map>
#include <memory>
#include <vector>
namespace hex::prv {
class Provider;
}
namespace hex::prv::undo {
using Patches = std::map<u64, u8>;
class Stack {
public:
explicit Stack(Provider *provider);
void undo(u32 count = 1);
void redo(u32 count = 1);
void groupOperations(u32 count, const UnlocalizedString &unlocalizedName);
void apply(const Stack &otherStack);
void reapply();
[[nodiscard]] bool canUndo() const;
[[nodiscard]] bool canRedo() const;
template<std::derived_from<Operation> T>
bool add(auto && ... args) {
auto result = this->add(std::make_unique<T>(std::forward<decltype(args)>(args)...));
EventDataChanged::post(m_provider);
return result;
}
bool add(std::unique_ptr<Operation> &&operation);
const std::vector<std::unique_ptr<Operation>> &getAppliedOperations() const {
return m_undoStack;
}
const std::vector<std::unique_ptr<Operation>> &getUndoneOperations() const {
return m_redoStack;
}
void reset() {
m_undoStack.clear();
m_redoStack.clear();
}
private:
[[nodiscard]] Operation* getLastOperation() const {
return m_undoStack.back().get();
}
private:
std::vector<std::unique_ptr<Operation>> m_undoStack, m_redoStack;
Provider *m_provider;
};
}
| 1,667
|
C++
|
.h
| 49
| 26.530612
| 96
| 0.618125
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
321
|
operation.hpp
|
WerWolv_ImHex/lib/libimhex/include/hex/providers/undo_redo/operations/operation.hpp
|
#pragma once
#include <string>
#include <vector>
#include <hex/helpers/concepts.hpp>
namespace hex::prv {
class Provider;
}
namespace hex::prv::undo {
class Operation : public ICloneable<Operation> {
public:
virtual ~Operation() = default;
virtual void undo(Provider *provider) = 0;
virtual void redo(Provider *provider) = 0;
[[nodiscard]] virtual Region getRegion() const = 0;
[[nodiscard]] virtual std::string format() const = 0;
[[nodiscard]] virtual std::vector<std::string> formatContent() const {
return { };
}
[[nodiscard]] virtual bool shouldHighlight() const { return true; }
};
}
| 691
|
C++
|
.h
| 21
| 27.095238
| 78
| 0.642965
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
322
|
operation_group.hpp
|
WerWolv_ImHex/lib/libimhex/include/hex/providers/undo_redo/operations/operation_group.hpp
|
#pragma once
#include <hex/providers/undo_redo/operations/operation.hpp>
#include <hex/api/localization_manager.hpp>
#include <hex/helpers/fmt.hpp>
#include <hex/helpers/utils.hpp>
namespace hex::prv::undo {
class OperationGroup : public Operation {
public:
explicit OperationGroup(UnlocalizedString unlocalizedName) : m_unlocalizedName(std::move(unlocalizedName)) {}
OperationGroup(const OperationGroup &other) {
for (const auto &operation : other.m_operations)
m_operations.emplace_back(operation->clone());
}
void undo(Provider *provider) override {
for (auto &operation : m_operations)
operation->undo(provider);
}
void redo(Provider *provider) override {
for (auto &operation : m_operations)
operation->redo(provider);
}
void addOperation(std::unique_ptr<Operation> &&newOperation) {
auto newRegion = newOperation->getRegion();
if (newRegion.getStartAddress() < m_startAddress)
m_startAddress = newRegion.getStartAddress();
if (newRegion.getEndAddress() > m_endAddress)
m_endAddress = newRegion.getEndAddress();
if (m_formattedContent.size() <= 10)
m_formattedContent.emplace_back(newOperation->format());
else
m_formattedContent.back() = hex::format("[{}x] ...", (m_operations.size() - 10) + 1);
m_operations.emplace_back(std::move(newOperation));
}
[[nodiscard]] std::string format() const override {
return hex::format("{}", Lang(m_unlocalizedName));
}
[[nodiscard]] Region getRegion() const override {
return Region { m_startAddress, (m_endAddress - m_startAddress) + 1 };
}
std::unique_ptr<Operation> clone() const override {
return std::make_unique<OperationGroup>(*this);
}
std::vector<std::string> formatContent() const override {
return m_formattedContent;
}
private:
UnlocalizedString m_unlocalizedName;
std::vector<std::unique_ptr<Operation>> m_operations;
u64 m_startAddress = std::numeric_limits<u64>::max();
u64 m_endAddress = std::numeric_limits<u64>::min();
std::vector<std::string> m_formattedContent;
};
}
| 2,407
|
C++
|
.h
| 53
| 35.433962
| 117
| 0.619333
|
WerWolv/ImHex
| 43,494
| 1,905
| 221
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.