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
103
utils.cpp
WerWolv_ImHex/lib/libimhex/source/helpers/utils.cpp
#include <hex/helpers/utils.hpp> #include <hex/api/imhex_api.hpp> #include <hex/helpers/fmt.hpp> #include <hex/helpers/crypto.hpp> #include <hex/providers/buffered_reader.hpp> #include <imgui.h> #if defined(OS_WINDOWS) #include <windows.h> #include <shellapi.h> #include <wolv/utils/guards.hpp> #elif defined(OS_LINUX) #include <unistd.h> #include <dlfcn.h> #include <hex/helpers/utils_linux.hpp> #elif defined(OS_MACOS) #include <unistd.h> #include <dlfcn.h> #include <hex/helpers/utils_macos.hpp> #elif defined(OS_WEB) #include "emscripten.h" #endif namespace hex { float operator""_scaled(long double value) { return value * ImHexApi::System::getGlobalScale(); } float operator""_scaled(unsigned long long value) { return value * ImHexApi::System::getGlobalScale(); } ImVec2 scaled(const ImVec2 &vector) { return vector * ImHexApi::System::getGlobalScale(); } ImVec2 scaled(float x, float y) { return ImVec2(x, y) * ImHexApi::System::getGlobalScale(); } std::string to_string(u128 value) { char data[45] = { 0 }; u8 index = sizeof(data) - 2; while (value != 0 && index != 0) { data[index] = '0' + value % 10; value /= 10; index--; } return { data + index + 1 }; } std::string to_string(i128 value) { char data[45] = { 0 }; u128 unsignedValue = value < 0 ? -value : value; u8 index = sizeof(data) - 2; while (unsignedValue != 0 && index != 0) { data[index] = '0' + unsignedValue % 10; unsignedValue /= 10; index--; } if (value < 0) { data[index] = '-'; return { data + index }; } else { return { data + index + 1 }; } } std::string toLower(std::string string) { for (char &c : string) c = std::tolower(c); return string; } std::string toUpper(std::string string) { for (char &c : string) c = std::toupper(c); return string; } std::vector<u8> parseHexString(std::string string) { if (string.empty()) return { }; // Remove common hex prefixes and commas string = hex::replaceStrings(string, "0x", ""); string = hex::replaceStrings(string, "0X", ""); string = hex::replaceStrings(string, ",", ""); // Check for non-hex characters bool isValidHexString = std::find_if(string.begin(), string.end(), [](char c) { return !std::isxdigit(c) && !std::isspace(c); }) == string.end(); if (!isValidHexString) return { }; // Remove all whitespace std::erase_if(string, [](char c) { return std::isspace(c); }); // Only parse whole bytes if (string.length() % 2 != 0) return { }; // Convert hex string to bytes return crypt::decode16(string); } std::optional<u8> parseBinaryString(const std::string &string) { if (string.empty()) return std::nullopt; u8 byte = 0x00; for (char c : string) { byte <<= 1; if (c == '1') byte |= 0b01; else if (c == '0') byte |= 0b00; else return std::nullopt; } return byte; } std::string toByteString(u64 bytes) { double value = bytes; u8 unitIndex = 0; while (value > 1024) { value /= 1024; unitIndex++; if (unitIndex == 6) break; } std::string result; if (unitIndex == 0) result = hex::format("{0:}", value); else result = hex::format("{0:.2f}", value); switch (unitIndex) { case 0: result += ((value == 1) ? " Byte" : " Bytes"); break; case 1: result += " kiB"; break; case 2: result += " MiB"; break; case 3: result += " GiB"; break; case 4: result += " TiB"; break; case 5: result += " PiB"; break; case 6: result += " EiB"; break; default: result = "A lot!"; } return result; } std::string makeStringPrintable(const std::string &string) { std::string result; for (char c : string) { if (std::isprint(c)) result += c; else result += hex::format("\\x{0:02X}", u8(c)); } return result; } std::string makePrintable(u8 c) { switch (c) { case 0: return "NUL"; case 1: return "SOH"; case 2: return "STX"; case 3: return "ETX"; case 4: return "EOT"; case 5: return "ENQ"; case 6: return "ACK"; case 7: return "BEL"; case 8: return "BS"; case 9: return "TAB"; case 10: return "LF"; case 11: return "VT"; case 12: return "FF"; case 13: return "CR"; case 14: return "SO"; case 15: return "SI"; case 16: return "DLE"; case 17: return "DC1"; case 18: return "DC2"; case 19: return "DC3"; case 20: return "DC4"; case 21: return "NAK"; case 22: return "SYN"; case 23: return "ETB"; case 24: return "CAN"; case 25: return "EM"; case 26: return "SUB"; case 27: return "ESC"; case 28: return "FS"; case 29: return "GS"; case 30: return "RS"; case 31: return "US"; case 32: return "Space"; case 127: return "DEL"; default: if (c >= 128) return " "; else return std::string() + static_cast<char>(c); } } std::vector<std::string> splitString(const std::string &string, const std::string &delimiter) { size_t start = 0, end = 0; std::vector<std::string> res; while ((end = string.find(delimiter, start)) != std::string::npos) { size_t size = end - start; if (start + size > string.length()) break; std::string token = string.substr(start, end - start); start = end + delimiter.length(); res.push_back(token); } res.emplace_back(string.substr(start)); return res; } std::string combineStrings(const std::vector<std::string> &strings, const std::string &delimiter) { std::string result; for (const auto &string : strings) { result += string; result += delimiter; } return result.substr(0, result.length() - delimiter.length()); } std::string replaceStrings(std::string string, const std::string &search, const std::string &replace) { if (search.empty()) return string; std::size_t pos; while ((pos = string.find(search)) != std::string::npos) string.replace(pos, search.size(), replace); return string; } std::string toEngineeringString(double value) { constexpr static std::array Suffixes = { "a", "f", "p", "n", "u", "m", "", "k", "M", "G", "T", "P", "E" }; int8_t suffixIndex = 6; while (suffixIndex != 0 && suffixIndex != 12 && (value >= 1000 || value < 1) && value != 0) { if (value >= 1000) { value /= 1000; suffixIndex++; } else if (value < 1) { value *= 1000; suffixIndex--; } } return std::to_string(value).substr(0, 5) + Suffixes[suffixIndex]; } void startProgram(const std::string &command) { #if defined(OS_WINDOWS) hex::unused(system(hex::format("start {0}", command).c_str())); #elif defined(OS_MACOS) hex::unused(system(hex::format("open {0}", command).c_str())); #elif defined(OS_LINUX) executeCmd({"xdg-open", command}); #elif defined(OS_WEB) hex::unused(command); #endif } int executeCommand(const std::string &command) { return ::system(command.c_str()); } void openWebpage(std::string url) { if (!url.contains("://")) url = "https://" + url; #if defined(OS_WINDOWS) ShellExecuteA(nullptr, "open", url.c_str(), nullptr, nullptr, SW_SHOWNORMAL); #elif defined(OS_MACOS) openWebpageMacos(url.c_str()); #elif defined(OS_LINUX) executeCmd({"xdg-open", url}); #elif defined(OS_WEB) EM_ASM({ window.open(UTF8ToString($0), '_blank'); }, url.c_str()); #else #warning "Unknown OS, can't open webpages" #endif } std::optional<u8> hexCharToValue(char c) { if (std::isdigit(c)) return c - '0'; else if (std::isxdigit(c)) return std::toupper(c) - 'A' + 0x0A; else return { }; } std::string encodeByteString(const std::vector<u8> &bytes) { std::string result; for (u8 byte : bytes) { if (std::isprint(byte) && byte != '\\') { result += char(byte); } else { switch (byte) { case '\\': result += "\\"; break; case '\a': result += "\\a"; break; case '\b': result += "\\b"; break; case '\f': result += "\\f"; break; case '\n': result += "\\n"; break; case '\r': result += "\\r"; break; case '\t': result += "\\t"; break; case '\v': result += "\\v"; break; default: result += hex::format("\\x{:02X}", byte); break; } } } return result; } std::vector<u8> decodeByteString(const std::string &string) { u32 offset = 0; std::vector<u8> result; while (offset < string.length()) { auto c = [&] { return string[offset]; }; if (c() == '\\') { if ((offset + 2) > string.length()) return {}; offset++; char escapeChar = c(); offset++; switch (escapeChar) { case 'a': result.push_back('\a'); break; case 'b': result.push_back('\b'); break; case 'f': result.push_back('\f'); break; case 'n': result.push_back('\n'); break; case 'r': result.push_back('\r'); break; case 't': result.push_back('\t'); break; case 'v': result.push_back('\v'); break; case '\\': result.push_back('\\'); break; case 'x': { u8 byte = 0x00; if ((offset + 1) >= string.length()) return {}; for (u8 i = 0; i < 2; i++) { byte <<= 4; if (auto hexValue = hexCharToValue(c()); hexValue.has_value()) byte |= hexValue.value(); else return {}; offset++; } result.push_back(byte); } break; default: return {}; } } else { result.push_back(c()); offset++; } } return result; } std::wstring utf8ToUtf16(const std::string& utf8) { std::vector<u32> unicodes; for (size_t byteIndex = 0; byteIndex < utf8.size();) { u32 unicode = 0; size_t unicodeSize = 0; u8 ch = utf8[byteIndex]; byteIndex += 1; if (ch <= 0x7F) { unicode = ch; unicodeSize = 0; } else if (ch <= 0xBF) { return { }; } else if (ch <= 0xDF) { unicode = ch&0x1F; unicodeSize = 1; } else if (ch <= 0xEF) { unicode = ch&0x0F; unicodeSize = 2; } else if (ch <= 0xF7) { unicode = ch&0x07; unicodeSize = 3; } else { return { }; } for (size_t unicodeByteIndex = 0; unicodeByteIndex < unicodeSize; unicodeByteIndex += 1) { if (byteIndex == utf8.size()) return { }; u8 byte = utf8[byteIndex]; if (byte < 0x80 || byte > 0xBF) return { }; unicode <<= 6; unicode += byte & 0x3F; byteIndex += 1; } if (unicode >= 0xD800 && unicode <= 0xDFFF) return { }; if (unicode > 0x10FFFF) return { }; unicodes.push_back(unicode); } std::wstring utf16; for (auto unicode : unicodes) { if (unicode <= 0xFFFF) { utf16 += static_cast<wchar_t>(unicode); } else { unicode -= 0x10000; utf16 += static_cast<wchar_t>(((unicode >> 10) + 0xD800)); utf16 += static_cast<wchar_t>(((unicode & 0x3FF) + 0xDC00)); } } return utf16; } std::string utf16ToUtf8(const std::wstring& utf16) { std::vector<u32> unicodes; for (size_t index = 0; index < utf16.size();) { u32 unicode = 0; wchar_t wch = utf16[index]; index += 1; if (wch < 0xD800 || wch > 0xDFFF) { unicode = static_cast<u32>(wch); } else if (wch >= 0xD800 && wch <= 0xDBFF) { if (index == utf16.size()) return ""; wchar_t nextWch = utf16[index]; index += 1; if (nextWch < 0xDC00 || nextWch > 0xDFFF) return ""; unicode = static_cast<u32>(((wch - 0xD800) << 10) + (nextWch - 0xDC00) + 0x10000); } else { return ""; } unicodes.push_back(unicode); } std::string utf8; for (auto unicode : unicodes) { if (unicode <= 0x7F) { utf8 += static_cast<char>(unicode); } else if (unicode <= 0x7FF) { utf8 += static_cast<char>(0xC0 | ((unicode >> 6) & 0x1F)); utf8 += static_cast<char>(0x80 | (unicode & 0x3F)); } else if (unicode <= 0xFFFF) { utf8 += static_cast<char>(0xE0 | ((unicode >> 12) & 0x0F)); utf8 += static_cast<char>(0x80 | ((unicode >> 6) & 0x3F)); utf8 += static_cast<char>(0x80 | (unicode & 0x3F)); } else if (unicode <= 0x10FFFF) { utf8 += static_cast<char>(0xF0 | ((unicode >> 18) & 0x07)); utf8 += static_cast<char>(0x80 | ((unicode >> 12) & 0x3F)); utf8 += static_cast<char>(0x80 | ((unicode >> 6) & 0x3F)); utf8 += static_cast<char>(0x80 | (unicode & 0x3F)); } else { return ""; } } return utf8; } float float16ToFloat32(u16 float16) { u32 sign = float16 >> 15; u32 exponent = (float16 >> 10) & 0x1F; u32 mantissa = float16 & 0x3FF; u32 result = 0x00; if (exponent == 0) { if (mantissa == 0) { // +- Zero result = sign << 31; } else { // Subnormal value exponent = 0x7F - 14; while ((mantissa & (1 << 10)) == 0) { exponent--; mantissa <<= 1; } mantissa &= 0x3FF; result = (sign << 31) | (exponent << 23) | (mantissa << 13); } } else if (exponent == 0x1F) { // +-Inf or +-NaN result = (sign << 31) | (0xFF << 23) | (mantissa << 13); } else { // Normal value result = (sign << 31) | ((exponent + (0x7F - 15)) << 23) | (mantissa << 13); } float floatResult = 0; std::memcpy(&floatResult, &result, sizeof(float)); return floatResult; } bool isProcessElevated() { #if defined(OS_WINDOWS) bool elevated = false; HANDLE token = INVALID_HANDLE_VALUE; if (::OpenProcessToken(::GetCurrentProcess(), TOKEN_QUERY, &token)) { TOKEN_ELEVATION elevation; DWORD elevationSize = sizeof(TOKEN_ELEVATION); if (::GetTokenInformation(token, TokenElevation, &elevation, sizeof(elevation), &elevationSize)) elevated = elevation.TokenIsElevated; } if (token != INVALID_HANDLE_VALUE) ::CloseHandle(token); return elevated; #elif defined(OS_LINUX) || defined(OS_MACOS) return getuid() == 0 || getuid() != geteuid(); #else return false; #endif } std::optional<std::string> getEnvironmentVariable(const std::string &env) { auto value = std::getenv(env.c_str()); if (value == nullptr) return std::nullopt; else return value; } [[nodiscard]] std::string limitStringLength(const std::string &string, size_t maxLength) { // If the string is shorter than the max length, return it as is if (string.size() < maxLength) return string; // If the string is longer than the max length, find the last space before the max length auto it = string.begin() + maxLength; while (it != string.begin() && !std::isspace(*it)) --it; // If there's no space before the max length, just cut the string if (it == string.begin()) { it = string.begin() + maxLength / 2; // Try to find a UTF-8 character boundary while (it != string.begin() && (*it & 0xC0) == 0x80) --it; } // If we still didn't find a valid boundary, just return the string as is if (it == string.begin()) return string; auto result = std::string(string.begin(), it) + "…"; // If the string is longer than the max length, find the last space before the max length it = string.end() - 1 - maxLength / 2; while (it != string.end() && !std::isspace(*it)) ++it; // If there's no space before the max length, just cut the string if (it == string.end()) { it = string.end() - 1 - maxLength / 2; // Try to find a UTF-8 character boundary while (it != string.end() && (*it & 0xC0) == 0x80) ++it; } return result + std::string(it, string.end()); } static std::optional<std::fs::path> s_fileToOpen; extern "C" void openFile(const char *path) { log::info("Opening file: {0}", path); s_fileToOpen = path; } std::optional<std::fs::path> getInitialFilePath() { return s_fileToOpen; } static std::map<std::fs::path, std::string> s_fonts; extern "C" void registerFont(const char *fontName, const char *fontPath) { s_fonts[fontPath] = fontName; } const std::map<std::fs::path, std::string>& getFonts() { return s_fonts; } namespace { std::string generateHexViewImpl(u64 offset, auto begin, auto end) { constexpr static auto HeaderLine = "Hex View 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F\n"; std::string result; const auto size = std::distance(begin, end); result.reserve(std::string(HeaderLine).size() * size / 0x10); result += HeaderLine; u64 address = offset & ~u64(0x0F); std::string asciiRow; for (auto it = begin; it != end; ++it) { u8 byte = *it; if ((address % 0x10) == 0) { result += hex::format(" {}", asciiRow); result += hex::format("\n{0:08X} ", address); asciiRow.clear(); if (address == (offset & ~u64(0x0F))) { for (u64 i = 0; i < (offset - address); i++) { result += " "; asciiRow += " "; } if (offset - address >= 8) result += " "; address = offset; } } result += hex::format("{0:02X} ", byte); asciiRow += std::isprint(byte) ? char(byte) : '.'; if ((address % 0x10) == 0x07) result += " "; address++; } if ((address % 0x10) != 0x00) for (u32 i = 0; i < (0x10 - (address % 0x10)); i++) result += " "; result += hex::format(" {}", asciiRow); return result; } } std::string generateHexView(u64 offset, u64 size, prv::Provider *provider) { auto reader = prv::ProviderReader(provider); reader.seek(offset); reader.setEndAddress((offset + size) - 1); return generateHexViewImpl(offset, reader.begin(), reader.end()); } std::string generateHexView(u64 offset, const std::vector<u8> &data) { return generateHexViewImpl(offset, data.begin(), data.end()); } std::string formatSystemError(i32 error) { #if defined(OS_WINDOWS) wchar_t *message = nullptr; auto wLength = FormatMessageW( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (wchar_t*)&message, 0, nullptr ); ON_SCOPE_EXIT { LocalFree(message); }; auto length = ::WideCharToMultiByte(CP_UTF8, 0, message, wLength, nullptr, 0, nullptr, nullptr); std::string result(length, '\x00'); ::WideCharToMultiByte(CP_UTF8, 0, message, wLength, result.data(), length, nullptr, nullptr); return result; #else return std::system_category().message(error); #endif } void* getContainingModule(void* symbol) { #if defined(OS_WINDOWS) MEMORY_BASIC_INFORMATION mbi; if (VirtualQuery(symbol, &mbi, sizeof(mbi))) return mbi.AllocationBase; return nullptr; #elif !defined(OS_WEB) Dl_info info = {}; if (dladdr(symbol, &info) == 0) return nullptr; return dlopen(info.dli_fname, RTLD_LAZY); #else hex::unused(symbol); return nullptr; #endif } }
25,176
C++
.cpp
693
23.015873
114
0.447308
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
104
achievement_manager.cpp
WerWolv_ImHex/lib/libimhex/source/api/achievement_manager.cpp
#include <hex/api/achievement_manager.hpp> #include <hex/api/event_manager.hpp> #include <hex/helpers/auto_reset.hpp> #include <hex/helpers/default_paths.hpp> #include <nlohmann/json.hpp> namespace hex { static AutoReset<std::unordered_map<std::string, std::unordered_map<std::string, std::unique_ptr<Achievement>>>> s_achievements; const std::unordered_map<std::string, std::unordered_map<std::string, std::unique_ptr<Achievement>>> &AchievementManager::getAchievements() { return *s_achievements; } static AutoReset<std::unordered_map<std::string, std::list<AchievementManager::AchievementNode>>> s_nodeCategoryStorage; std::unordered_map<std::string, std::list<AchievementManager::AchievementNode>>& getAchievementNodesMutable(bool rebuild) { if (!s_nodeCategoryStorage->empty() || !rebuild) return s_nodeCategoryStorage; s_nodeCategoryStorage->clear(); // Add all achievements to the node storage for (auto &[categoryName, achievements] : AchievementManager::getAchievements()) { auto &nodes = (*s_nodeCategoryStorage)[categoryName]; for (auto &[achievementName, achievement] : achievements) { nodes.emplace_back(achievement.get()); } } return s_nodeCategoryStorage; } const std::unordered_map<std::string, std::list<AchievementManager::AchievementNode>>& AchievementManager::getAchievementNodes(bool rebuild) { return getAchievementNodesMutable(rebuild); } static AutoReset<std::unordered_map<std::string, std::vector<AchievementManager::AchievementNode*>>> s_startNodes; const std::unordered_map<std::string, std::vector<AchievementManager::AchievementNode*>>& AchievementManager::getAchievementStartNodes(bool rebuild) { if (!s_startNodes->empty() || !rebuild) return s_startNodes; auto &nodeCategoryStorage = getAchievementNodesMutable(rebuild); s_startNodes->clear(); // Add all parents and children to the nodes for (auto &[categoryName, achievements] : nodeCategoryStorage) { for (auto &achievementNode : achievements) { for (auto &requirement : achievementNode.achievement->getRequirements()) { for (auto &[requirementCategoryName, requirementAchievements] : nodeCategoryStorage) { auto iter = std::ranges::find_if(requirementAchievements, [&requirement](auto &node) { return node.achievement->getUnlocalizedName() == requirement; }); if (iter != requirementAchievements.end()) { achievementNode.parents.emplace_back(&*iter); iter->children.emplace_back(&achievementNode); } } } for (auto &requirement : achievementNode.achievement->getVisibilityRequirements()) { for (auto &[requirementCategoryName, requirementAchievements] : nodeCategoryStorage) { auto iter = std::ranges::find_if(requirementAchievements, [&requirement](auto &node) { return node.achievement->getUnlocalizedName() == requirement; }); if (iter != requirementAchievements.end()) { achievementNode.visibilityParents.emplace_back(&*iter); } } } } } for (auto &[categoryName, achievements] : nodeCategoryStorage) { for (auto &achievementNode : achievements) { if (!achievementNode.hasParents()) { (*s_startNodes)[categoryName].emplace_back(&achievementNode); } for (const auto &parent : achievementNode.parents) { if (parent->achievement->getUnlocalizedCategory() != achievementNode.achievement->getUnlocalizedCategory()) (*s_startNodes)[categoryName].emplace_back(&achievementNode); } } } return s_startNodes; } void AchievementManager::unlockAchievement(const UnlocalizedString &unlocalizedCategory, const UnlocalizedString &unlocalizedName) { auto &categories = getAchievements(); auto categoryIter = categories.find(unlocalizedCategory); if (categoryIter == categories.end()) { return; } auto &[categoryName, achievements] = *categoryIter; const auto achievementIter = achievements.find(unlocalizedName); if (achievementIter == achievements.end()) { return; } const auto &nodes = getAchievementNodes(); if (!nodes.contains(categoryName)) return; for (const auto &node : nodes.at(categoryName)) { auto &achievement = node.achievement; if (achievement->getUnlocalizedCategory() != unlocalizedCategory) { continue; } if (achievement->getUnlocalizedName() != unlocalizedName) { continue; } if (node.achievement->isUnlocked()) { return; } for (const auto &requirement : node.parents) { if (!requirement->achievement->isUnlocked()) { return; } } achievement->setUnlocked(true); if (achievement->isUnlocked()) EventAchievementUnlocked::post(*achievement); return; } } void AchievementManager::clearTemporary() { auto &categories = *s_achievements; for (auto &[categoryName, achievements] : categories) { std::erase_if(achievements, [](auto &data) { auto &[achievementName, achievement] = data; return achievement->isTemporary(); }); } std::erase_if(categories, [](auto &data) { auto &[categoryName, achievements] = data; return achievements.empty(); }); s_startNodes->clear(); s_nodeCategoryStorage->clear(); } std::pair<u32, u32> AchievementManager::getProgress() { u32 unlocked = 0; u32 total = 0; for (auto &[categoryName, achievements] : getAchievements()) { for (auto &[achievementName, achievement] : achievements) { total += 1; if (achievement->isUnlocked()) { unlocked += 1; } } } return { unlocked, total }; } void AchievementManager::achievementAdded() { s_startNodes->clear(); s_nodeCategoryStorage->clear(); } Achievement &AchievementManager::addAchievementImpl(std::unique_ptr<Achievement> &&newAchievement) { const auto &category = newAchievement->getUnlocalizedCategory(); const auto &name = newAchievement->getUnlocalizedName(); auto [categoryIter, categoryInserted] = s_achievements->insert({ category, std::unordered_map<std::string, std::unique_ptr<Achievement>>{} }); auto &[categoryKey, achievements] = *categoryIter; auto [achievementIter, achievementInserted] = achievements.insert({ name, std::move(newAchievement) }); auto &[achievementKey, achievement] = *achievementIter; achievementAdded(); return *achievement; } constexpr static auto AchievementsFile = "achievements.json"; void AchievementManager::loadProgress() { for (const auto &directory : paths::Config.read()) { auto path = directory / AchievementsFile; if (!wolv::io::fs::exists(path)) { continue; } wolv::io::File file(path, wolv::io::File::Mode::Read); if (!file.isValid()) { continue; } try { auto json = nlohmann::json::parse(file.readString()); for (const auto &[categoryName, achievements] : getAchievements()) { for (const auto &[achievementName, achievement] : achievements) { try { const auto &progress = json[categoryName][achievementName]; if (progress.is_null()) continue; achievement->setProgress(progress); } catch (const std::exception &e) { log::warn("Failed to load achievement progress for '{}::{}': {}", categoryName, achievementName, e.what()); } } } } catch (const std::exception &e) { log::error("Failed to load achievements: {}", e.what()); } } } void AchievementManager::storeProgress() { nlohmann::json json; for (const auto &[categoryName, achievements] : getAchievements()) { json[categoryName] = nlohmann::json::object(); for (const auto &[achievementName, achievement] : achievements) { json[categoryName][achievementName] = achievement->getProgress(); } } if (json.empty()) return; for (const auto &directory : paths::Config.write()) { auto path = directory / AchievementsFile; wolv::io::File file(path, wolv::io::File::Mode::Create); if (!file.isValid()) continue; file.writeString(json.dump(4)); break; } } }
9,737
C++
.cpp
200
35.52
154
0.582208
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
105
project_file_manager.cpp
WerWolv_ImHex/lib/libimhex/source/api/project_file_manager.cpp
#include <hex/api/project_file_manager.hpp> #include <hex/helpers/auto_reset.hpp> #include <wolv/io/fs.hpp> namespace hex { namespace { AutoReset<std::vector<ProjectFile::Handler>> s_handlers; AutoReset<std::vector<ProjectFile::ProviderHandler>> s_providerHandlers; AutoReset<std::fs::path> s_currProjectPath; AutoReset<std::function<bool(const std::fs::path&)>> s_loadProjectFunction; AutoReset<std::function<bool(std::optional<std::fs::path>, bool)>> s_storeProjectFunction; } void ProjectFile::setProjectFunctions( const std::function<bool(const std::fs::path&)> &loadFun, const std::function<bool(std::optional<std::fs::path>, bool)> &storeFun ) { s_loadProjectFunction = loadFun; s_storeProjectFunction = storeFun; } bool ProjectFile::load(const std::fs::path &filePath) { return (*s_loadProjectFunction)(filePath); } bool ProjectFile::store(std::optional<std::fs::path> filePath, bool updateLocation) { return (*s_storeProjectFunction)(std::move(filePath), updateLocation); } bool ProjectFile::hasPath() { return !s_currProjectPath->empty(); } void ProjectFile::clearPath() { s_currProjectPath->clear(); } std::fs::path ProjectFile::getPath() { return s_currProjectPath; } void ProjectFile::setPath(const std::fs::path &path) { s_currProjectPath = path; } void ProjectFile::registerHandler(const Handler &handler) { s_handlers->push_back(handler); } void ProjectFile::registerPerProviderHandler(const ProviderHandler &handler) { s_providerHandlers->push_back(handler); } const std::vector<ProjectFile::Handler>& ProjectFile::getHandlers() { return s_handlers; } const std::vector<ProjectFile::ProviderHandler>& ProjectFile::getProviderHandlers() { return s_providerHandlers; } }
1,962
C++
.cpp
49
33.387755
98
0.679873
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
106
workspace_manager.cpp
WerWolv_ImHex/lib/libimhex/source/api/workspace_manager.cpp
#include <hex/api/workspace_manager.hpp> #include <hex/api/layout_manager.hpp> #include <hex/helpers/logger.hpp> #include <hex/helpers/auto_reset.hpp> #include <hex/helpers/default_paths.hpp> #include <wolv/io/file.hpp> #include <nlohmann/json.hpp> #include <imgui.h> #include <wolv/utils/string.hpp> namespace hex { AutoReset<std::map<std::string, WorkspaceManager::Workspace>> WorkspaceManager::s_workspaces; decltype(WorkspaceManager::s_workspaces)::Type::iterator WorkspaceManager::s_currentWorkspace = s_workspaces->end(); decltype(WorkspaceManager::s_workspaces)::Type::iterator WorkspaceManager::s_previousWorkspace = s_workspaces->end(); decltype(WorkspaceManager::s_workspaces)::Type::iterator WorkspaceManager::s_workspaceToRemove = s_workspaces->end(); void WorkspaceManager::createWorkspace(const std::string& name, const std::string &layout) { s_currentWorkspace = s_workspaces->insert_or_assign(name, Workspace { .layout = layout.empty() ? LayoutManager::saveToString() : layout, .path = {}, .builtin = false }).first; for (const auto &workspaceFolder : paths::Workspaces.write()) { const auto workspacePath = workspaceFolder / (name + ".hexws"); if (exportToFile(workspacePath)) { s_currentWorkspace->second.path = workspacePath; break; } } } void WorkspaceManager::switchWorkspace(const std::string& name) { const auto newWorkspace = s_workspaces->find(name); if (newWorkspace != s_workspaces->end()) { s_currentWorkspace = newWorkspace; log::info("Switching to workspace '{}'", name); } } void WorkspaceManager::importFromFile(const std::fs::path& path) { if (std::ranges::any_of(*s_workspaces, [path](const auto &pair) { return pair.second.path == path; })) { return; } wolv::io::File file(path, wolv::io::File::Mode::Read); if (!file.isValid()) { log::error("Failed to load workspace from file '{}'", path.string()); file.remove(); return; } auto content = file.readString(); try { auto json = nlohmann::json::parse(content.begin(), content.end()); const std::string name = json["name"]; std::string layout = json["layout"]; const bool builtin = json.value("builtin", false); (*s_workspaces)[name] = Workspace { .layout = std::move(layout), .path = path, .builtin = builtin }; } catch (nlohmann::json::exception &e) { log::error("Failed to load workspace from file '{}': {}", path.string(), e.what()); file.remove(); } } bool WorkspaceManager::exportToFile(std::fs::path path, std::string workspaceName, bool builtin) { if (path.empty()) { if (s_currentWorkspace == s_workspaces->end()) { return false; } path = s_currentWorkspace->second.path; } if (workspaceName.empty()) { workspaceName = s_currentWorkspace->first; } wolv::io::File file(path, wolv::io::File::Mode::Create); if (!file.isValid()) { return false; } nlohmann::json json; json["name"] = workspaceName; json["layout"] = LayoutManager::saveToString(); json["builtin"] = builtin; file.writeString(json.dump(4)); return true; } void WorkspaceManager::removeWorkspace(const std::string& name) { bool deletedCurrentWorkspace = false; for (const auto &[workspaceName, workspace] : *s_workspaces) { if (workspaceName == name) { log::info("Removing workspace file '{}'", wolv::util::toUTF8String(workspace.path)); if (wolv::io::fs::remove(workspace.path)) { log::info("Removed workspace '{}'", name); if (workspaceName == s_currentWorkspace->first) { deletedCurrentWorkspace = true; } } else { log::error("Failed to remove workspace '{}'", name); } } } WorkspaceManager::reload(); if (deletedCurrentWorkspace && !s_workspaces->empty()) { s_currentWorkspace = s_workspaces->begin(); } } void WorkspaceManager::process() { if (s_previousWorkspace != s_currentWorkspace) { log::info("Updating workspace"); if (s_previousWorkspace != s_workspaces->end()) { exportToFile(s_previousWorkspace->second.path, s_previousWorkspace->first, s_previousWorkspace->second.builtin); } LayoutManager::closeAllViews(); ImGui::LoadIniSettingsFromMemory(s_currentWorkspace->second.layout.c_str()); s_previousWorkspace = s_currentWorkspace; if (s_workspaceToRemove != s_workspaces->end()) { s_workspaces->erase(s_workspaceToRemove); s_workspaceToRemove = s_workspaces->end(); } } } void WorkspaceManager::reset() { s_workspaces->clear(); s_currentWorkspace = s_workspaces->end(); s_previousWorkspace = s_workspaces->end(); } void WorkspaceManager::reload() { WorkspaceManager::reset(); for (const auto &defaultPath : paths::Workspaces.read()) { for (const auto &entry : std::fs::directory_iterator(defaultPath)) { if (!entry.is_regular_file()) { continue; } const auto &path = entry.path(); if (path.extension() != ".hexws") { continue; } WorkspaceManager::importFromFile(path); } } } }
6,021
C++
.cpp
138
32.702899
128
0.575758
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
107
plugin_manager.cpp
WerWolv_ImHex/lib/libimhex/source/api/plugin_manager.cpp
#include <hex/api/plugin_manager.hpp> #include <hex/api/imhex_api.hpp> #include <hex/helpers/logger.hpp> #include <hex/helpers/fmt.hpp> #include <hex/helpers/auto_reset.hpp> #include <hex/helpers/utils.hpp> #include <hex/helpers/default_paths.hpp> #include <wolv/utils/string.hpp> #include <filesystem> #if defined(OS_WINDOWS) #include <windows.h> #else #include <dlfcn.h> #endif namespace hex { static uintptr_t loadLibrary(const std::fs::path &path) { #if defined(OS_WINDOWS) auto handle = uintptr_t(LoadLibraryW(path.c_str())); if (handle == uintptr_t(INVALID_HANDLE_VALUE) || handle == 0) { log::error("Loading library '{}' failed: {} {}!", wolv::util::toUTF8String(path.filename()), ::GetLastError(), hex::formatSystemError(::GetLastError())); return 0; } return handle; #else auto handle = uintptr_t(dlopen(wolv::util::toUTF8String(path).c_str(), RTLD_LAZY)); if (handle == 0) { log::error("Loading library '{}' failed: {}!", wolv::util::toUTF8String(path.filename()), dlerror()); return 0; } return handle; #endif } static void unloadLibrary(uintptr_t handle, const std::fs::path &path) { #if defined(OS_WINDOWS) if (handle != 0) { if (FreeLibrary(HMODULE(handle)) == FALSE) { log::error("Error when unloading library '{}': {}!", wolv::util::toUTF8String(path.filename()), hex::formatSystemError(::GetLastError())); } } #else if (handle != 0) { if (dlclose(reinterpret_cast<void*>(handle)) != 0) { log::error("Error when unloading library '{}': {}!", path.filename().string(), dlerror()); } } #endif } Plugin::Plugin(const std::fs::path &path) : m_path(path) { log::info("Loading plugin '{}'", wolv::util::toUTF8String(path.filename())); m_handle = loadLibrary(path); if (m_handle == 0) return; const auto fileName = path.stem().string(); m_functions.initializePluginFunction = getPluginFunction<PluginFunctions::InitializePluginFunc>("initializePlugin"); m_functions.initializeLibraryFunction = getPluginFunction<PluginFunctions::InitializePluginFunc>(hex::format("initializeLibrary_{}", fileName)); m_functions.getPluginNameFunction = getPluginFunction<PluginFunctions::GetPluginNameFunc>("getPluginName"); m_functions.getLibraryNameFunction = getPluginFunction<PluginFunctions::GetLibraryNameFunc>(hex::format("getLibraryName_{}", fileName)); m_functions.getPluginAuthorFunction = getPluginFunction<PluginFunctions::GetPluginAuthorFunc>("getPluginAuthor"); m_functions.getPluginDescriptionFunction = getPluginFunction<PluginFunctions::GetPluginDescriptionFunc>("getPluginDescription"); m_functions.getCompatibleVersionFunction = getPluginFunction<PluginFunctions::GetCompatibleVersionFunc>("getCompatibleVersion"); m_functions.setImGuiContextFunction = getPluginFunction<PluginFunctions::SetImGuiContextFunc>("setImGuiContext"); m_functions.setImGuiContextLibraryFunction = getPluginFunction<PluginFunctions::SetImGuiContextFunc>(hex::format("setImGuiContext_{}", fileName)); m_functions.getSubCommandsFunction = getPluginFunction<PluginFunctions::GetSubCommandsFunc>("getSubCommands"); m_functions.getFeaturesFunction = getPluginFunction<PluginFunctions::GetSubCommandsFunc>("getFeatures"); } Plugin::Plugin(const std::string &name, const hex::PluginFunctions &functions) { m_handle = 0; m_functions = functions; m_path = name; m_addedManually = true; } Plugin::Plugin(Plugin &&other) noexcept { m_handle = other.m_handle; other.m_handle = 0; m_path = std::move(other.m_path); m_addedManually = other.m_addedManually; m_functions = other.m_functions; other.m_functions = {}; } Plugin& Plugin::operator=(Plugin &&other) noexcept { m_handle = other.m_handle; other.m_handle = 0; m_path = std::move(other.m_path); m_addedManually = other.m_addedManually; m_functions = other.m_functions; other.m_functions = {}; return *this; } Plugin::~Plugin() { if (isLoaded()) { log::info("Trying to unload plugin '{}'", getPluginName()); } unloadLibrary(m_handle, m_path); } bool Plugin::initializePlugin() const { const auto pluginName = wolv::util::toUTF8String(m_path.filename()); if (this->isLibraryPlugin()) { m_functions.initializeLibraryFunction(); log::info("Library '{}' initialized successfully", pluginName); m_initialized = true; return true; } const auto requestedVersion = getCompatibleVersion(); const auto imhexVersion = ImHexApi::System::getImHexVersion(); if (!imhexVersion.starts_with(requestedVersion)) { if (requestedVersion.empty()) { log::warn("Plugin '{}' did not specify a compatible version, assuming it is compatible with the current version of ImHex.", wolv::util::toUTF8String(m_path.filename())); } else { log::error("Refused to load plugin '{}' which was built for a different version of ImHex: '{}'", wolv::util::toUTF8String(m_path.filename()), requestedVersion); return false; } } if (m_functions.initializePluginFunction != nullptr) { try { m_functions.initializePluginFunction(); } catch (const std::exception &e) { log::error("Plugin '{}' threw an exception on init: {}", pluginName, e.what()); return false; } catch (...) { log::error("Plugin '{}' threw an exception on init", pluginName); return false; } } else { log::error("Plugin '{}' does not have a proper entrypoint", pluginName); return false; } log::info("Plugin '{}' initialized successfully", pluginName); m_initialized = true; return true; } std::string Plugin::getPluginName() const { if (m_functions.getPluginNameFunction != nullptr) { return m_functions.getPluginNameFunction(); } else { if (this->isLibraryPlugin()) return m_functions.getLibraryNameFunction(); else return hex::format("Unknown Plugin @ 0x{0:016X}", m_handle); } } std::string Plugin::getPluginAuthor() const { if (m_functions.getPluginAuthorFunction != nullptr) return m_functions.getPluginAuthorFunction(); else return "Unknown"; } std::string Plugin::getPluginDescription() const { if (m_functions.getPluginDescriptionFunction != nullptr) return m_functions.getPluginDescriptionFunction(); else return ""; } std::string Plugin::getCompatibleVersion() const { if (m_functions.getCompatibleVersionFunction != nullptr) return m_functions.getCompatibleVersionFunction(); else return ""; } void Plugin::setImGuiContext(ImGuiContext *ctx) const { if (m_functions.setImGuiContextFunction != nullptr) m_functions.setImGuiContextFunction(ctx); } const std::fs::path &Plugin::getPath() const { return m_path; } bool Plugin::isValid() const { return m_handle != 0 || m_functions.initializeLibraryFunction != nullptr || m_functions.initializePluginFunction != nullptr; } bool Plugin::isLoaded() const { return m_initialized; } std::span<SubCommand> Plugin::getSubCommands() const { if (m_functions.getSubCommandsFunction != nullptr) { const auto result = m_functions.getSubCommandsFunction(); if (result == nullptr) return { }; return *static_cast<std::vector<SubCommand>*>(result); } else { return { }; } } std::span<Feature> Plugin::getFeatures() const { if (m_functions.getFeaturesFunction != nullptr) { const auto result = m_functions.getFeaturesFunction(); if (result == nullptr) return { }; return *static_cast<std::vector<Feature>*>(result); } else { return { }; } } bool Plugin::isLibraryPlugin() const { return m_functions.initializeLibraryFunction != nullptr && m_functions.initializePluginFunction == nullptr; } bool Plugin::wasAddedManually() const { return m_addedManually; } void *Plugin::getPluginFunction(const std::string &symbol) const { #if defined(OS_WINDOWS) return reinterpret_cast<void *>(GetProcAddress(HMODULE(m_handle), symbol.c_str())); #else return dlsym(reinterpret_cast<void*>(m_handle), symbol.c_str()); #endif } AutoReset<std::vector<std::fs::path>> PluginManager::s_pluginPaths, PluginManager::s_pluginLoadPaths; void PluginManager::addLoadPath(const std::fs::path& path) { s_pluginLoadPaths->emplace_back(path); } bool PluginManager::load() { bool success = true; for (const auto &loadPath : getPluginLoadPaths()) success = PluginManager::load(loadPath) && success; return success; } bool PluginManager::load(const std::fs::path &pluginFolder) { if (!wolv::io::fs::exists(pluginFolder)) return false; s_pluginPaths->push_back(pluginFolder); // Load library plugins first for (auto &pluginPath : std::fs::directory_iterator(pluginFolder)) { if (pluginPath.is_regular_file() && pluginPath.path().extension() == ".hexpluglib") { if (!isPluginLoaded(pluginPath.path())) { getPluginsMutable().emplace_back(pluginPath.path()); } } } // Load regular plugins afterwards for (auto &pluginPath : std::fs::directory_iterator(pluginFolder)) { if (pluginPath.is_regular_file() && pluginPath.path().extension() == ".hexplug") { if (!isPluginLoaded(pluginPath.path())) { getPluginsMutable().emplace_back(pluginPath.path()); } } } std::erase_if(getPluginsMutable(), [](const Plugin &plugin) { return !plugin.isValid(); }); return true; } AutoReset<std::vector<uintptr_t>> PluginManager::s_loadedLibraries; bool PluginManager::loadLibraries() { bool success = true; for (const auto &loadPath : paths::Libraries.read()) success = PluginManager::loadLibraries(loadPath) && success; return success; } bool PluginManager::loadLibraries(const std::fs::path& libraryFolder) { bool success = true; for (const auto &entry : std::fs::directory_iterator(libraryFolder)) { if (!(entry.path().extension() == ".dll" || entry.path().extension() == ".so" || entry.path().extension() == ".dylib")) continue; auto handle = loadLibrary(entry); if (handle == 0) { success = false; } PluginManager::s_loadedLibraries->push_back(handle); } return success; } void PluginManager::initializeNewPlugins() { for (const auto &plugin : getPlugins()) { if (!plugin.isLoaded()) hex::unused(plugin.initializePlugin()); } } void PluginManager::unload() { s_pluginPaths->clear(); // Unload plugins in reverse order auto &plugins = getPluginsMutable(); std::list<Plugin> savedPlugins; while (!plugins.empty()) { if (plugins.back().wasAddedManually()) savedPlugins.emplace_front(std::move(plugins.back())); plugins.pop_back(); } while (!s_loadedLibraries->empty()) { unloadLibrary(s_loadedLibraries->back(), ""); s_loadedLibraries->pop_back(); } getPluginsMutable() = std::move(savedPlugins); } void PluginManager::addPlugin(const std::string &name, hex::PluginFunctions functions) { getPluginsMutable().emplace_back(name, functions); } const std::list<Plugin>& PluginManager::getPlugins() { return getPluginsMutable(); } std::list<Plugin>& PluginManager::getPluginsMutable() { static std::list<Plugin> plugins; return plugins; } Plugin* PluginManager::getPlugin(const std::string &name) { for (auto &plugin : getPluginsMutable()) { if (plugin.getPluginName() == name) return &plugin; } return nullptr; } const std::vector<std::fs::path>& PluginManager::getPluginPaths() { return s_pluginPaths; } const std::vector<std::fs::path>& PluginManager::getPluginLoadPaths() { return s_pluginLoadPaths; } bool PluginManager::isPluginLoaded(const std::fs::path &path) { return std::ranges::any_of(getPlugins(), [&path](const Plugin &plugin) { return plugin.getPath().filename() == path.filename(); }); } }
13,757
C++
.cpp
311
34.475884
185
0.607322
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
108
content_registry.cpp
WerWolv_ImHex/lib/libimhex/source/api/content_registry.cpp
#include <hex/api/content_registry.hpp> #include <hex/api/shortcut_manager.hpp> #include <hex/helpers/fs.hpp> #include <hex/helpers/logger.hpp> #include <hex/helpers/auto_reset.hpp> #include <hex/helpers/default_paths.hpp> #include <hex/ui/view.hpp> #include <hex/data_processor/node.hpp> #include <algorithm> #include <filesystem> #include <jthread.hpp> #if defined(OS_WEB) #include <emscripten.h> #endif #include <hex/api/task_manager.hpp> #include <nlohmann/json.hpp> #include <wolv/io/file.hpp> #include <wolv/utils/string.hpp> namespace hex { namespace ContentRegistry::Settings { [[maybe_unused]] constexpr auto SettingsFile = "settings.json"; namespace impl { struct OnChange { u32 id; OnChangeCallback callback; }; static AutoReset<std::map<std::string, std::map<std::string, std::vector<OnChange>>>> s_onChangeCallbacks; static AutoReset<nlohmann::json> s_settings; const nlohmann::json& getSettingsData() { return s_settings; } nlohmann::json& getSetting(const UnlocalizedString &unlocalizedCategory, const UnlocalizedString &unlocalizedName, const nlohmann::json &defaultValue) { auto &settings = *s_settings; if (!settings.contains(unlocalizedCategory)) settings[unlocalizedCategory] = {}; if (!settings[unlocalizedCategory].contains(unlocalizedName)) settings[unlocalizedCategory][unlocalizedName] = defaultValue; if (settings[unlocalizedCategory][unlocalizedName].is_null()) settings[unlocalizedCategory][unlocalizedName] = defaultValue; return settings[unlocalizedCategory][unlocalizedName]; } #if defined(OS_WEB) void load() { char *data = (char *) MAIN_THREAD_EM_ASM_INT({ let data = localStorage.getItem("config"); return data ? stringToNewUTF8(data) : null; }); if (data == nullptr) { store(); } else { s_settings = nlohmann::json::parse(data); } for (const auto &[category, rest] : *impl::s_onChangeCallbacks) { for (const auto &[name, callbacks] : rest) { for (const auto &[id, callback] : callbacks) { try { callback(getSetting(category, name, {})); } catch (const std::exception &e) { log::error("Failed to load setting [{}/{}]: {}", category, name, e.what()); } } } } } void store() { auto data = s_settings->dump(); MAIN_THREAD_EM_ASM({ localStorage.setItem("config", UTF8ToString($0)); }, data.c_str()); } void clear() { MAIN_THREAD_EM_ASM({ localStorage.removeItem("config"); }); } #else void load() { bool loaded = false; for (const auto &dir : paths::Config.read()) { wolv::io::File file(dir / SettingsFile, wolv::io::File::Mode::Read); if (file.isValid()) { s_settings = nlohmann::json::parse(file.readString()); loaded = true; break; } } if (!loaded) store(); for (const auto &[category, rest] : *impl::s_onChangeCallbacks) { for (const auto &[name, callbacks] : rest) { for (const auto &[id, callback] : callbacks) { try { callback(getSetting(category, name, {})); } catch (const std::exception &e) { log::error("Failed to load setting [{}/{}]: {}", category, name, e.what()); } } } } } void store() { if (!s_settings.isValid()) return; const auto &settingsData = *s_settings; // During a crash settings can be empty, causing them to be overwritten. if (settingsData.empty()) { return; } const auto result = settingsData.dump(4); if (result.empty()) { return; } for (const auto &dir : paths::Config.write()) { wolv::io::File file(dir / SettingsFile, wolv::io::File::Mode::Create); if (file.isValid()) { file.writeString(result); break; } } } void clear() { for (const auto &dir : paths::Config.write()) { wolv::io::fs::remove(dir / SettingsFile); } } #endif template<typename T> static T* insertOrGetEntry(std::vector<T> &vector, const UnlocalizedString &unlocalizedName) { T *foundEntry = nullptr; for (auto &entry : vector) { if (entry.unlocalizedName == unlocalizedName) { foundEntry = &entry; break; } } if (foundEntry == nullptr) { if (unlocalizedName.empty()) foundEntry = &*vector.emplace(vector.begin(), unlocalizedName); else foundEntry = &vector.emplace_back(unlocalizedName); } return foundEntry; } static AutoReset<std::vector<Category>> s_categories; const std::vector<Category>& getSettings() { return *s_categories; } Widgets::Widget* add(const UnlocalizedString &unlocalizedCategory, const UnlocalizedString &unlocalizedSubCategory, const UnlocalizedString &unlocalizedName, std::unique_ptr<Widgets::Widget> &&widget) { const auto category = insertOrGetEntry(*s_categories, unlocalizedCategory); const auto subCategory = insertOrGetEntry(category->subCategories, unlocalizedSubCategory); const auto entry = insertOrGetEntry(subCategory->entries, unlocalizedName); entry->widget = std::move(widget); return entry->widget.get(); } void printSettingReadError(const UnlocalizedString &unlocalizedCategory, const UnlocalizedString &unlocalizedName, const nlohmann::json::exception& e) { hex::log::error("Failed to read setting {}/{}: {}", unlocalizedCategory.get(), unlocalizedName.get(), e.what()); } void runOnChangeHandlers(const UnlocalizedString &unlocalizedCategory, const UnlocalizedString &unlocalizedName, const nlohmann::json &value) { if (auto categoryIt = s_onChangeCallbacks->find(unlocalizedCategory); categoryIt != s_onChangeCallbacks->end()) { if (auto nameIt = categoryIt->second.find(unlocalizedName); nameIt != categoryIt->second.end()) { for (const auto &[id, callback] : nameIt->second) { try { callback(value); } catch (const nlohmann::json::exception &e) { log::error("Failed to run onChange handler for setting {}/{}: {}", unlocalizedCategory.get(), unlocalizedName.get(), e.what()); } } } } } } void setCategoryDescription(const UnlocalizedString &unlocalizedCategory, const UnlocalizedString &unlocalizedDescription) { const auto category = insertOrGetEntry(*impl::s_categories, unlocalizedCategory); category->unlocalizedDescription = unlocalizedDescription; } u64 onChange(const UnlocalizedString &unlocalizedCategory, const UnlocalizedString &unlocalizedName, const OnChangeCallback &callback) { static u64 id = 1; (*impl::s_onChangeCallbacks)[unlocalizedCategory][unlocalizedName].emplace_back(id, callback); auto result = id; id += 1; return result; } void removeOnChangeHandler(u64 id) { bool done = false; auto categoryIt = impl::s_onChangeCallbacks->begin(); for (; categoryIt != impl::s_onChangeCallbacks->end(); ++categoryIt) { auto nameIt = categoryIt->second.begin(); for (; nameIt != categoryIt->second.end(); ++nameIt) { done = std::erase_if(nameIt->second, [id](const impl::OnChange &entry) { return entry.id == id; }) > 0; if (done) break; } if (done) { if (nameIt->second.empty()) categoryIt->second.erase(nameIt); break; } } if (done) { if (categoryIt->second.empty()) impl::s_onChangeCallbacks->erase(categoryIt); } } namespace Widgets { bool Checkbox::draw(const std::string &name) { return ImGui::Checkbox(name.c_str(), &m_value); } void Checkbox::load(const nlohmann::json &data) { if (data.is_number()) { m_value = data.get<int>() != 0; } else if (data.is_boolean()) { m_value = data.get<bool>(); } else { log::warn("Invalid data type loaded from settings for checkbox!"); } } nlohmann::json Checkbox::store() { return m_value; } bool SliderInteger::draw(const std::string &name) { return ImGui::SliderInt(name.c_str(), &m_value, m_min, m_max); } void SliderInteger::load(const nlohmann::json &data) { if (data.is_number_integer()) { m_value = data.get<int>(); } else { log::warn("Invalid data type loaded from settings for slider!"); } } nlohmann::json SliderInteger::store() { return m_value; } bool SliderFloat::draw(const std::string &name) { return ImGui::SliderFloat(name.c_str(), &m_value, m_min, m_max); } void SliderFloat::load(const nlohmann::json &data) { if (data.is_number()) { m_value = data.get<float>(); } else { log::warn("Invalid data type loaded from settings for slider!"); } } nlohmann::json SliderFloat::store() { return m_value; } bool SliderDataSize::draw(const std::string &name) { return ImGuiExt::SliderBytes(name.c_str(), &m_value, m_min, m_max); } void SliderDataSize::load(const nlohmann::json &data) { if (data.is_number_integer()) { m_value = data.get<u64>(); } else { log::warn("Invalid data type loaded from settings for slider!"); } } nlohmann::json SliderDataSize::store() { return m_value; } ColorPicker::ColorPicker(ImColor defaultColor) { m_value = { defaultColor.Value.x, defaultColor.Value.y, defaultColor.Value.z, defaultColor.Value.w }; } bool ColorPicker::draw(const std::string &name) { return ImGui::ColorEdit4(name.c_str(), m_value.data(), ImGuiColorEditFlags_NoInputs); } void ColorPicker::load(const nlohmann::json &data) { if (data.is_number()) { const ImColor color(data.get<u32>()); m_value = { color.Value.x, color.Value.y, color.Value.z, color.Value.w }; } else { log::warn("Invalid data type loaded from settings for color picker!"); } } nlohmann::json ColorPicker::store() { const ImColor color(m_value[0], m_value[1], m_value[2], m_value[3]); return static_cast<ImU32>(color); } ImColor ColorPicker::getColor() const { return { m_value[0], m_value[1], m_value[2], m_value[3] }; } bool DropDown::draw(const std::string &name) { auto preview = ""; if (static_cast<size_t>(m_value) < m_items.size()) preview = m_items[m_value].c_str(); bool changed = false; if (ImGui::BeginCombo(name.c_str(), Lang(preview))) { int index = 0; for (const auto &item : m_items) { const bool selected = index == m_value; if (ImGui::Selectable(Lang(item), selected)) { m_value = index; changed = true; } if (selected) ImGui::SetItemDefaultFocus(); index += 1; } ImGui::EndCombo(); } return changed; } void DropDown::load(const nlohmann::json &data) { m_value = 0; int defaultItemIndex = 0; int index = 0; for (const auto &item : m_settingsValues) { if (item == m_defaultItem) defaultItemIndex = index; if (item == data) { m_value = index; return; } index += 1; } m_value = defaultItemIndex; } nlohmann::json DropDown::store() { if (m_value == -1) return m_defaultItem; if (static_cast<size_t>(m_value) >= m_items.size()) return m_defaultItem; return m_settingsValues[m_value]; } const nlohmann::json& DropDown::getValue() const { return m_settingsValues[m_value]; } bool TextBox::draw(const std::string &name) { return ImGui::InputText(name.c_str(), m_value); } void TextBox::load(const nlohmann::json &data) { if (data.is_string()) { m_value = data.get<std::string>(); } else { log::warn("Invalid data type loaded from settings for text box!"); } } nlohmann::json TextBox::store() { return m_value; } bool FilePicker::draw(const std::string &name) { bool changed = false; auto pathString = wolv::util::toUTF8String(m_path); if (ImGui::InputText("##font_path", pathString)) { changed = true; } ImGui::SameLine(); if (ImGuiExt::IconButton("...", ImGui::GetStyleColorVec4(ImGuiCol_Text))) { changed = fs::openFileBrowser(fs::DialogMode::Open, { { "TTF Font", "ttf" }, { "OTF Font", "otf" } }, [&](const std::fs::path &path) { pathString = wolv::util::toUTF8String(path); }); } ImGui::SameLine(); ImGuiExt::TextFormatted("{}", name); if (changed) { m_path = pathString; } return changed; } void FilePicker::load(const nlohmann::json &data) { if (data.is_string()) { m_path = data.get<std::fs::path>(); } else { log::warn("Invalid data type loaded from settings for file picker!"); } } nlohmann::json FilePicker::store() { return m_path; } bool Label::draw(const std::string& name) { ImGui::NewLine(); ImGui::TextUnformatted(name.c_str()); return false; } } } namespace ContentRegistry::CommandPaletteCommands { namespace impl { static AutoReset<std::vector<Entry>> s_entries; const std::vector<Entry>& getEntries() { return *s_entries; } static AutoReset<std::vector<Handler>> s_handlers; const std::vector<Handler>& getHandlers() { return *s_handlers; } } void add(Type type, const std::string &command, const UnlocalizedString &unlocalizedDescription, const impl::DisplayCallback &displayCallback, const impl::ExecuteCallback &executeCallback) { log::debug("Registered new command palette command: {}", command); impl::s_entries->push_back(impl::Entry { type, command, unlocalizedDescription, displayCallback, executeCallback }); } void addHandler(Type type, const std::string &command, const impl::QueryCallback &queryCallback, const impl::DisplayCallback &displayCallback) { log::debug("Registered new command palette command handler: {}", command); impl::s_handlers->push_back(impl::Handler { type, command, queryCallback, displayCallback }); } } namespace ContentRegistry::PatternLanguage { namespace impl { static AutoReset<std::map<std::string, Visualizer>> s_visualizers; const std::map<std::string, Visualizer>& getVisualizers() { return *s_visualizers; } static AutoReset<std::map<std::string, Visualizer>> s_inlineVisualizers; const std::map<std::string, Visualizer>& getInlineVisualizers() { return *s_inlineVisualizers; } static AutoReset<std::map<std::string, pl::api::PragmaHandler>> s_pragmas; const std::map<std::string, pl::api::PragmaHandler>& getPragmas() { return *s_pragmas; } static AutoReset<std::vector<FunctionDefinition>> s_functions; const std::vector<FunctionDefinition>& getFunctions() { return *s_functions; } } static std::string getFunctionName(const pl::api::Namespace &ns, const std::string &name) { std::string functionName; for (auto &scope : ns) functionName += scope + "::"; functionName += name; return functionName; } pl::PatternLanguage& getRuntime() { static PerProvider<pl::PatternLanguage> runtime; AT_FIRST_TIME { runtime.setOnCreateCallback([](prv::Provider *provider, pl::PatternLanguage &runtime) { configureRuntime(runtime, provider); }); }; return *runtime; } std::mutex& getRuntimeLock() { static std::mutex runtimeLock; return runtimeLock; } void configureRuntime(pl::PatternLanguage &runtime, prv::Provider *provider) { runtime.reset(); if (provider != nullptr) { runtime.setDataSource(provider->getBaseAddress(), provider->getActualSize(), [provider](u64 offset, u8 *buffer, size_t size) { provider->read(offset, buffer, size); }, [provider](u64 offset, const u8 *buffer, size_t size) { if (provider->isWritable()) provider->write(offset, buffer, size); } ); } runtime.setIncludePaths(paths::PatternsInclude.read() | paths::Patterns.read()); for (const auto &[ns, name, paramCount, callback, dangerous] : impl::getFunctions()) { if (dangerous) runtime.addDangerousFunction(ns, name, paramCount, callback); else runtime.addFunction(ns, name, paramCount, callback); } for (const auto &[name, callback] : impl::getPragmas()) { runtime.addPragma(name, callback); } runtime.addDefine("__IMHEX__"); runtime.addDefine("__IMHEX_VERSION__", ImHexApi::System::getImHexVersion()); } void addPragma(const std::string &name, const pl::api::PragmaHandler &handler) { log::debug("Registered new pattern language pragma: {}", name); (*impl::s_pragmas)[name] = handler; } void addFunction(const pl::api::Namespace &ns, const std::string &name, pl::api::FunctionParameterCount parameterCount, const pl::api::FunctionCallback &func) { log::debug("Registered new pattern language function: {}", getFunctionName(ns, name)); impl::s_functions->push_back({ ns, name, parameterCount, func, false }); } void addDangerousFunction(const pl::api::Namespace &ns, const std::string &name, pl::api::FunctionParameterCount parameterCount, const pl::api::FunctionCallback &func) { log::debug("Registered new dangerous pattern language function: {}", getFunctionName(ns, name)); impl::s_functions->push_back({ ns, name, parameterCount, func, true }); } void addVisualizer(const std::string &name, const impl::VisualizerFunctionCallback &function, pl::api::FunctionParameterCount parameterCount) { log::debug("Registered new pattern visualizer function: {}", name); (*impl::s_visualizers)[name] = impl::Visualizer { parameterCount, function }; } void addInlineVisualizer(const std::string &name, const impl::VisualizerFunctionCallback &function, pl::api::FunctionParameterCount parameterCount) { log::debug("Registered new inline pattern visualizer function: {}", name); (*impl::s_inlineVisualizers)[name] = impl::Visualizer { parameterCount, function }; } } namespace ContentRegistry::Views { namespace impl { static AutoReset<std::map<std::string, std::unique_ptr<View>>> s_views; const std::map<std::string, std::unique_ptr<View>>& getEntries() { return *s_views; } void add(std::unique_ptr<View> &&view) { log::debug("Registered new view: {}", view->getUnlocalizedName().get()); s_views->insert({ view->getUnlocalizedName(), std::move(view) }); } } View* getViewByName(const UnlocalizedString &unlocalizedName) { auto &views = *impl::s_views; if (views.contains(unlocalizedName)) return views[unlocalizedName].get(); else return nullptr; } } namespace ContentRegistry::Tools { namespace impl { static AutoReset<std::vector<Entry>> s_tools; const std::vector<Entry>& getEntries() { return *s_tools; } } void add(const UnlocalizedString &unlocalizedName, const impl::Callback &function) { log::debug("Registered new tool: {}", unlocalizedName.get()); impl::s_tools->emplace_back(impl::Entry { unlocalizedName, function }); } } namespace ContentRegistry::DataInspector { namespace impl { static AutoReset<std::vector<Entry>> s_entries; const std::vector<Entry>& getEntries() { return *s_entries; } } void add(const UnlocalizedString &unlocalizedName, size_t requiredSize, impl::GeneratorFunction displayGeneratorFunction, std::optional<impl::EditingFunction> editingFunction) { log::debug("Registered new data inspector format: {}", unlocalizedName.get()); impl::s_entries->push_back({ unlocalizedName, requiredSize, requiredSize, std::move(displayGeneratorFunction), std::move(editingFunction) }); } void add(const UnlocalizedString &unlocalizedName, size_t requiredSize, size_t maxSize, impl::GeneratorFunction displayGeneratorFunction, std::optional<impl::EditingFunction> editingFunction) { log::debug("Registered new data inspector format: {}", unlocalizedName.get()); impl::s_entries->push_back({ unlocalizedName, requiredSize, maxSize, std::move(displayGeneratorFunction), std::move(editingFunction) }); } } namespace ContentRegistry::DataProcessorNode { namespace impl { static AutoReset<std::vector<Entry>> s_nodes; const std::vector<Entry>& getEntries() { return *s_nodes; } void add(const Entry &entry) { log::debug("Registered new data processor node type: [{}]: {}", entry.unlocalizedCategory.get(), entry.unlocalizedName.get()); s_nodes->push_back(entry); } } void addSeparator() { impl::s_nodes->push_back({ "", "", [] { return nullptr; } }); } } namespace ContentRegistry::Language { namespace impl { static AutoReset<std::map<std::string, std::string>> s_languages; const std::map<std::string, std::string>& getLanguages() { return *s_languages; } static AutoReset<std::map<std::string, std::vector<LocalizationManager::LanguageDefinition>>> s_definitions; const std::map<std::string, std::vector<LocalizationManager::LanguageDefinition>>& getLanguageDefinitions() { return *s_definitions; } } void addLocalization(const nlohmann::json &data) { if (!data.is_object()) return; if (!data.contains("code") || !data.contains("country") || !data.contains("language") || !data.contains("translations")) { log::error("Localization data is missing required fields!"); return; } const auto &code = data["code"]; const auto &country = data["country"]; const auto &language = data["language"]; const auto &translations = data["translations"]; if (!code.is_string() || !country.is_string() || !language.is_string() || !translations.is_object()) { log::error("Localization data has invalid fields!"); return; } if (data.contains("fallback")) { const auto &fallback = data["fallback"]; if (fallback.is_boolean() && fallback.get<bool>()) LocalizationManager::impl::setFallbackLanguage(code.get<std::string>()); } impl::s_languages->insert({ code.get<std::string>(), hex::format("{} ({})", language.get<std::string>(), country.get<std::string>()) }); std::map<std::string, std::string> translationDefinitions; for (auto &[key, value] : translations.items()) { if (!value.is_string()) { log::error("Localization data has invalid fields!"); continue; } translationDefinitions[key] = value.get<std::string>(); } (*impl::s_definitions)[code.get<std::string>()].emplace_back(std::move(translationDefinitions)); } } namespace ContentRegistry::Interface { namespace impl { static AutoReset<std::multimap<u32, MainMenuItem>> s_mainMenuItems; const std::multimap<u32, MainMenuItem>& getMainMenuItems() { return *s_mainMenuItems; } static AutoReset<std::multimap<u32, MenuItem>> s_menuItems; const std::multimap<u32, MenuItem>& getMenuItems() { return *s_menuItems; } static AutoReset<std::vector<MenuItem*>> s_toolbarMenuItems; const std::vector<MenuItem*>& getToolbarMenuItems() { return s_toolbarMenuItems; } std::multimap<u32, MenuItem>& getMenuItemsMutable() { return *s_menuItems; } static AutoReset<std::vector<DrawCallback>> s_welcomeScreenEntries; const std::vector<DrawCallback>& getWelcomeScreenEntries() { return *s_welcomeScreenEntries; } static AutoReset<std::vector<DrawCallback>> s_footerItems; const std::vector<DrawCallback>& getFooterItems() { return *s_footerItems; } static AutoReset<std::vector<DrawCallback>> s_toolbarItems; const std::vector<DrawCallback>& getToolbarItems() { return *s_toolbarItems; } static AutoReset<std::vector<SidebarItem>> s_sidebarItems; const std::vector<SidebarItem>& getSidebarItems() { return *s_sidebarItems; } static AutoReset<std::vector<TitleBarButton>> s_titlebarButtons; const std::vector<TitleBarButton>& getTitlebarButtons() { return *s_titlebarButtons; } } void registerMainMenuItem(const UnlocalizedString &unlocalizedName, u32 priority) { log::debug("Registered new main menu item: {}", unlocalizedName.get()); impl::s_mainMenuItems->insert({ priority, { unlocalizedName } }); } void addMenuItem(const std::vector<UnlocalizedString> &unlocalizedMainMenuNames, u32 priority, const Shortcut &shortcut, const impl::MenuCallback &function, const impl::EnabledCallback& enabledCallback, const impl::SelectedCallback &selectedCallback, View *view) { addMenuItem(unlocalizedMainMenuNames, "", priority, shortcut, function, enabledCallback, selectedCallback, view); } void addMenuItem(const std::vector<UnlocalizedString> &unlocalizedMainMenuNames, const Icon &icon, u32 priority, const Shortcut &shortcut, const impl::MenuCallback &function, const impl::EnabledCallback& enabledCallback, View *view) { addMenuItem(unlocalizedMainMenuNames, icon, priority, shortcut, function, enabledCallback, []{ return false; }, view); } void addMenuItem(const std::vector<UnlocalizedString> &unlocalizedMainMenuNames, u32 priority, const Shortcut &shortcut, const impl::MenuCallback &function, const impl::EnabledCallback& enabledCallback, View *view) { addMenuItem(unlocalizedMainMenuNames, "", priority, shortcut, function, enabledCallback, []{ return false; }, view); } void addMenuItem(const std::vector<UnlocalizedString> &unlocalizedMainMenuNames, const Icon &icon, u32 priority, const Shortcut &shortcut, const impl::MenuCallback &function, const impl::EnabledCallback& enabledCallback, const impl::SelectedCallback &selectedCallback, View *view) { log::debug("Added new menu item to menu {} with priority {}", unlocalizedMainMenuNames[0].get(), priority); Icon coloredIcon = icon; if (coloredIcon.color == 0x00) coloredIcon.color = ImGuiCustomCol_ToolbarGray; impl::s_menuItems->insert({ priority, impl::MenuItem { unlocalizedMainMenuNames, coloredIcon, std::make_unique<Shortcut>(shortcut), view, function, enabledCallback, selectedCallback, -1 } }); if (shortcut != Shortcut::None) { if (shortcut.isLocal() && view != nullptr) ShortcutManager::addShortcut(view, shortcut, unlocalizedMainMenuNames.back(), function); else ShortcutManager::addGlobalShortcut(shortcut, unlocalizedMainMenuNames.back(), function); } } void addMenuItemSubMenu(std::vector<UnlocalizedString> unlocalizedMainMenuNames, u32 priority, const impl::MenuCallback &function, const impl::EnabledCallback& enabledCallback) { addMenuItemSubMenu(std::move(unlocalizedMainMenuNames), "", priority, function, enabledCallback); } void addMenuItemSubMenu(std::vector<UnlocalizedString> unlocalizedMainMenuNames, const char *icon, u32 priority, const impl::MenuCallback &function, const impl::EnabledCallback& enabledCallback) { log::debug("Added new menu item sub menu to menu {} with priority {}", unlocalizedMainMenuNames[0].get(), priority); unlocalizedMainMenuNames.emplace_back(impl::SubMenuValue); impl::s_menuItems->insert({ priority, impl::MenuItem { unlocalizedMainMenuNames, icon, std::make_unique<Shortcut>(), nullptr, function, enabledCallback, []{ return false; }, -1 } }); } void addMenuItemSeparator(std::vector<UnlocalizedString> unlocalizedMainMenuNames, u32 priority) { unlocalizedMainMenuNames.emplace_back(impl::SeparatorValue); impl::s_menuItems->insert({ priority, impl::MenuItem { unlocalizedMainMenuNames, "", std::make_unique<Shortcut>(), nullptr, []{}, []{ return true; }, []{ return false; }, -1 } }); } void addWelcomeScreenEntry(const impl::DrawCallback &function) { impl::s_welcomeScreenEntries->push_back(function); } void addFooterItem(const impl::DrawCallback &function) { impl::s_footerItems->push_back(function); } void addToolbarItem(const impl::DrawCallback &function) { impl::s_toolbarItems->push_back(function); } void addMenuItemToToolbar(const UnlocalizedString& unlocalizedName, ImGuiCustomCol color) { const auto maxIndex = std::ranges::max_element(impl::getMenuItems(), [](const auto &a, const auto &b) { return a.second.toolbarIndex < b.second.toolbarIndex; })->second.toolbarIndex; for (auto &[priority, menuItem] : *impl::s_menuItems) { if (menuItem.unlocalizedNames.back() == unlocalizedName) { menuItem.toolbarIndex = maxIndex + 1; menuItem.icon.color = color; updateToolbarItems(); break; } } } struct MenuItemSorter { bool operator()(const auto *a, const auto *b) const { return a->toolbarIndex < b->toolbarIndex; } }; void updateToolbarItems() { std::set<ContentRegistry::Interface::impl::MenuItem*, MenuItemSorter> menuItems; for (auto &[priority, menuItem] : impl::getMenuItemsMutable()) { if (menuItem.toolbarIndex != -1) { menuItems.insert(&menuItem); } } impl::s_toolbarMenuItems->clear(); for (auto menuItem : menuItems) { impl::s_toolbarMenuItems->push_back(menuItem); } } void addSidebarItem(const std::string &icon, const impl::DrawCallback &function, const impl::EnabledCallback &enabledCallback) { impl::s_sidebarItems->push_back({ icon, function, enabledCallback }); } void addTitleBarButton(const std::string &icon, const UnlocalizedString &unlocalizedTooltip, const impl::ClickCallback &function) { impl::s_titlebarButtons->push_back({ icon, unlocalizedTooltip, function }); } } namespace ContentRegistry::Provider { namespace impl { void add(const std::string &typeName, ProviderCreationFunction creationFunction) { (void)RequestCreateProvider::subscribe([expectedName = typeName, creationFunction](const std::string &name, bool skipLoadInterface, bool selectProvider, prv::Provider **provider) { if (name != expectedName) return; auto newProvider = creationFunction(); if (provider != nullptr) { *provider = newProvider.get(); ImHexApi::Provider::add(std::move(newProvider), skipLoadInterface, selectProvider); } }); } static AutoReset<std::vector<std::string>> s_providerNames; const std::vector<std::string>& getEntries() { return *s_providerNames; } void addProviderName(const UnlocalizedString &unlocalizedName) { log::debug("Registered new provider: {}", unlocalizedName.get()); s_providerNames->push_back(unlocalizedName); } } } namespace ContentRegistry::DataFormatter { namespace impl { static AutoReset<std::vector<ExportMenuEntry>> s_exportMenuEntries; const std::vector<ExportMenuEntry>& getExportMenuEntries() { return *s_exportMenuEntries; } static AutoReset<std::vector<FindExporterEntry>> s_findExportEntries; const std::vector<FindExporterEntry>& getFindExporterEntries() { return *s_findExportEntries; } } void addExportMenuEntry(const UnlocalizedString &unlocalizedName, const impl::Callback &callback) { log::debug("Registered new data formatter: {}", unlocalizedName.get()); impl::s_exportMenuEntries->push_back({ unlocalizedName, callback }); } void addFindExportFormatter(const UnlocalizedString &unlocalizedName, const std::string fileExtension, const impl::FindExporterCallback &callback) { log::debug("Registered new export formatter: {}", unlocalizedName.get()); impl::s_findExportEntries->push_back({ unlocalizedName, fileExtension, callback }); } } namespace ContentRegistry::FileHandler { namespace impl { static AutoReset<std::vector<Entry>> s_entries; const std::vector<Entry>& getEntries() { return *s_entries; } } void add(const std::vector<std::string> &extensions, const impl::Callback &callback) { for (const auto &extension : extensions) log::debug("Registered new data handler for extensions: {}", extension); impl::s_entries->push_back({ extensions, callback }); } } namespace ContentRegistry::HexEditor { const int DataVisualizer::TextInputFlags = ImGuiInputTextFlags_AutoSelectAll | ImGuiInputTextFlags_NoHorizontalScroll | ImGuiInputTextFlags_AlwaysOverwrite; bool DataVisualizer::drawDefaultScalarEditingTextBox(u64 address, const char *format, ImGuiDataType dataType, u8 *data, ImGuiInputTextFlags flags) const { struct UserData { u8 *data; i32 maxChars; bool editingDone; }; UserData userData = { .data = data, .maxChars = this->getMaxCharsPerCell(), .editingDone = false }; ImGui::PushID(reinterpret_cast<void*>(address)); ImGuiExt::InputScalarCallback("##editing_input", dataType, data, format, flags | TextInputFlags | ImGuiInputTextFlags_CallbackEdit, [](ImGuiInputTextCallbackData *data) -> int { auto &userData = *static_cast<UserData*>(data->UserData); if (data->CursorPos >= userData.maxChars) userData.editingDone = true; data->Buf[userData.maxChars] = 0x00; return 0; }, &userData); ImGui::PopID(); return userData.editingDone || ImGui::IsKeyPressed(ImGuiKey_Enter) || ImGui::IsKeyPressed(ImGuiKey_Escape); } bool DataVisualizer::drawDefaultTextEditingTextBox(u64 address, std::string &data, ImGuiInputTextFlags flags) const { struct UserData { std::string *data; i32 maxChars; bool editingDone; }; UserData userData = { .data = &data, .maxChars = this->getMaxCharsPerCell(), .editingDone = false }; ImGui::PushID(reinterpret_cast<void*>(address)); ImGui::InputText("##editing_input", data.data(), data.size() + 1, flags | TextInputFlags | ImGuiInputTextFlags_CallbackEdit, [](ImGuiInputTextCallbackData *data) -> int { auto &userData = *static_cast<UserData*>(data->UserData); userData.data->resize(data->BufSize); if (data->BufTextLen >= userData.maxChars) userData.editingDone = true; return 0; }, &userData); ImGui::PopID(); return userData.editingDone || ImGui::IsKeyPressed(ImGuiKey_Enter) || ImGui::IsKeyPressed(ImGuiKey_Escape); } namespace impl { static AutoReset<std::vector<std::shared_ptr<DataVisualizer>>> s_visualizers; const std::vector<std::shared_ptr<DataVisualizer>>& getVisualizers() { return *s_visualizers; } static AutoReset<std::vector<std::shared_ptr<MiniMapVisualizer>>> s_miniMapVisualizers; const std::vector<std::shared_ptr<MiniMapVisualizer>>& getMiniMapVisualizers() { return *s_miniMapVisualizers; } void addDataVisualizer(std::shared_ptr<DataVisualizer> &&visualizer) { s_visualizers->emplace_back(std::move(visualizer)); } } std::shared_ptr<DataVisualizer> getVisualizerByName(const UnlocalizedString &unlocalizedName) { for (const auto &visualizer : impl::getVisualizers()) { if (visualizer->getUnlocalizedName() == unlocalizedName) return visualizer; } return nullptr; } void addMiniMapVisualizer(UnlocalizedString unlocalizedName, MiniMapVisualizer::Callback callback) { impl::s_miniMapVisualizers->emplace_back(std::make_shared<MiniMapVisualizer>(std::move(unlocalizedName), std::move(callback))); } } namespace ContentRegistry::Diffing { namespace impl { static AutoReset<std::vector<std::unique_ptr<Algorithm>>> s_algorithms; const std::vector<std::unique_ptr<Algorithm>>& getAlgorithms() { return *s_algorithms; } void addAlgorithm(std::unique_ptr<Algorithm> &&hash) { s_algorithms->emplace_back(std::move(hash)); } } } namespace ContentRegistry::Hashes { namespace impl { static AutoReset<std::vector<std::unique_ptr<Hash>>> s_hashes; const std::vector<std::unique_ptr<Hash>>& getHashes() { return *s_hashes; } void add(std::unique_ptr<Hash> &&hash) { s_hashes->emplace_back(std::move(hash)); } } } namespace ContentRegistry::BackgroundServices { namespace impl { class Service { public: Service(const UnlocalizedString &unlocalizedName, std::jthread thread) : m_unlocalizedName(std::move(unlocalizedName)), m_thread(std::move(thread)) { } Service(const Service&) = delete; Service(Service &&) = default; ~Service() { m_thread.request_stop(); if (m_thread.joinable()) m_thread.join(); } Service& operator=(const Service&) = delete; Service& operator=(Service &&) = default; [[nodiscard]] const UnlocalizedString& getUnlocalizedName() const { return m_unlocalizedName; } [[nodiscard]] const std::jthread& getThread() const { return m_thread; } private: UnlocalizedString m_unlocalizedName; std::jthread m_thread; }; static AutoReset<std::vector<Service>> s_services; const std::vector<Service>& getServices() { return *s_services; } void stopServices() { s_services->clear(); } } void registerService(const UnlocalizedString &unlocalizedName, const impl::Callback &callback) { log::debug("Registered new background service: {}", unlocalizedName.get()); impl::s_services->emplace_back( unlocalizedName, std::jthread([=](const std::stop_token &stopToken){ TaskManager::setCurrentThreadName(Lang(unlocalizedName)); while (!stopToken.stop_requested()) { callback(); std::this_thread::sleep_for(std::chrono::milliseconds(50)); } }) ); } } namespace ContentRegistry::CommunicationInterface { namespace impl { static AutoReset<std::map<std::string, NetworkCallback>> s_endpoints; const std::map<std::string, NetworkCallback>& getNetworkEndpoints() { return *s_endpoints; } } void registerNetworkEndpoint(const std::string &endpoint, const impl::NetworkCallback &callback) { log::debug("Registered new network endpoint: {}", endpoint); impl::s_endpoints->insert({ endpoint, callback }); } } namespace ContentRegistry::Experiments { namespace impl { static AutoReset<std::map<std::string, Experiment>> s_experiments; const std::map<std::string, Experiment>& getExperiments() { return *s_experiments; } } void addExperiment(const std::string &experimentName, const UnlocalizedString &unlocalizedName, const UnlocalizedString &unlocalizedDescription) { auto &experiments = *impl::s_experiments; if (experiments.contains(experimentName)) { log::error("Experiment with name '{}' already exists!", experimentName); return; } experiments[experimentName] = impl::Experiment { .unlocalizedName = unlocalizedName, .unlocalizedDescription = unlocalizedDescription, .enabled = false }; } void enableExperiement(const std::string &experimentName, bool enabled) { auto &experiments = *impl::s_experiments; if (!experiments.contains(experimentName)) { log::error("Experiment with name '{}' does not exist!", experimentName); return; } experiments[experimentName].enabled = enabled; } [[nodiscard]] bool isExperimentEnabled(const std::string &experimentName) { auto &experiments = *impl::s_experiments; if (!experiments.contains(experimentName)) { log::error("Experiment with name '{}' does not exist!", experimentName); return false; } return experiments[experimentName].enabled; } } namespace ContentRegistry::Reports { namespace impl { static AutoReset<std::vector<ReportGenerator>> s_generators; const std::vector<ReportGenerator>& getGenerators() { return *s_generators; } } void addReportProvider(impl::Callback callback) { impl::s_generators->push_back(impl::ReportGenerator { std::move(callback ) }); } } namespace ContentRegistry::DataInformation { namespace impl { static AutoReset<std::vector<CreateCallback>> s_informationSectionConstructors; const std::vector<CreateCallback>& getInformationSectionConstructors() { return *s_informationSectionConstructors; } void addInformationSectionCreator(const CreateCallback &callback) { s_informationSectionConstructors->emplace_back(callback); } } } }
50,335
C++
.cpp
992
35.336694
290
0.549564
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
109
tutorial_manager.cpp
WerWolv_ImHex/lib/libimhex/source/api/tutorial_manager.cpp
#include <hex/api/tutorial_manager.hpp> #include <hex/api/imhex_api.hpp> #include <hex/api/localization_manager.hpp> #include <hex/api/task_manager.hpp> #include <hex/helpers/auto_reset.hpp> #include <imgui_internal.h> #include <hex/helpers/utils.hpp> #include <wolv/utils/core.hpp> #include <map> namespace hex { namespace { AutoReset<std::map<std::string, TutorialManager::Tutorial>> s_tutorials; auto s_currentTutorial = s_tutorials->end(); AutoReset<std::map<ImGuiID, std::string>> s_highlights; AutoReset<std::vector<std::pair<ImRect, std::string>>> s_highlightDisplays; AutoReset<std::map<ImGuiID, std::function<void()>>> s_interactiveHelpItems; ImRect s_hoveredRect; ImGuiID s_hoveredId; bool s_helpHoverActive = false; class IDStack { public: IDStack() { idStack.push_back(0); } void add(const std::string &string) { const ImGuiID seed = idStack.back(); const ImGuiID id = ImHashStr(string.c_str(), string.length(), seed); idStack.push_back(id); } void add(const void *pointer) { const ImGuiID seed = idStack.back(); const ImGuiID id = ImHashData(&pointer, sizeof(pointer), seed); idStack.push_back(id); } void add(int value) { const ImGuiID seed = idStack.back(); const ImGuiID id = ImHashData(&value, sizeof(value), seed); idStack.push_back(id); } ImGuiID get() { return idStack.back(); } private: ImVector<ImGuiID> idStack; }; ImGuiID calculateId(const auto &ids) { IDStack idStack; for (const auto &id : ids) { std::visit(wolv::util::overloaded { [&idStack](const Lang &id) { idStack.add(id.get()); }, [&idStack](const auto &id) { idStack.add(id); } }, id); } return idStack.get(); } } void TutorialManager::init() { EventImGuiElementRendered::subscribe([](ImGuiID id, const std::array<float, 4> bb){ const auto boundingBox = ImRect(bb[0], bb[1], bb[2], bb[3]); const auto element = hex::s_highlights->find(id); if (element != hex::s_highlights->end()) { hex::s_highlightDisplays->emplace_back(boundingBox, element->second); } if (id != 0 && boundingBox.Contains(ImGui::GetMousePos())) { if ((s_hoveredRect.GetArea() == 0 || boundingBox.GetArea() < s_hoveredRect.GetArea()) && s_interactiveHelpItems->contains(id)) { s_hoveredRect = boundingBox; s_hoveredId = id; } } }); } const std::map<std::string, TutorialManager::Tutorial>& TutorialManager::getTutorials() { return s_tutorials; } std::map<std::string, TutorialManager::Tutorial>::iterator TutorialManager::getCurrentTutorial() { return s_currentTutorial; } TutorialManager::Tutorial& TutorialManager::createTutorial(const UnlocalizedString &unlocalizedName, const UnlocalizedString &unlocalizedDescription) { return s_tutorials->try_emplace(unlocalizedName, Tutorial(unlocalizedName, unlocalizedDescription)).first->second; } void TutorialManager::startHelpHover() { TaskManager::doLater([]{ s_helpHoverActive = true; }); } void TutorialManager::addInteractiveHelpText(std::initializer_list<std::variant<Lang, std::string, int>> &&ids, UnlocalizedString text) { auto id = calculateId(ids); s_interactiveHelpItems->emplace(id, [text = std::move(text)]{ log::info("{}", Lang(text).get()); }); } void TutorialManager::addInteractiveHelpLink(std::initializer_list<std::variant<Lang, std::string, int>> &&ids, std::string link) { auto id = calculateId(ids); s_interactiveHelpItems->emplace(id, [link = std::move(link)]{ hex::openWebpage(link); }); } void TutorialManager::startTutorial(const UnlocalizedString &unlocalizedName) { s_currentTutorial = s_tutorials->find(unlocalizedName); if (s_currentTutorial == s_tutorials->end()) return; s_currentTutorial->second.start(); } void TutorialManager::drawHighlights() { if (s_helpHoverActive) { const auto &drawList = ImGui::GetForegroundDrawList(); drawList->AddText(ImGui::GetMousePos() + scaled({ 10, -5, }), ImGui::GetColorU32(ImGuiCol_Text), "?"); const bool mouseClicked = ImGui::IsMouseClicked(ImGuiMouseButton_Left); if (s_hoveredId != 0) { drawList->AddRectFilled(s_hoveredRect.Min, s_hoveredRect.Max, 0x30FFFFFF); if (mouseClicked) { auto it = s_interactiveHelpItems->find(s_hoveredId); if (it != s_interactiveHelpItems->end()) { it->second(); } } s_hoveredId = 0; s_hoveredRect = {}; } if (mouseClicked || ImGui::IsKeyPressed(ImGuiKey_Escape)) { s_helpHoverActive = false; } } for (const auto &[rect, unlocalizedText] : *s_highlightDisplays) { const auto drawList = ImGui::GetForegroundDrawList(); drawList->PushClipRectFullScreen(); { auto highlightColor = ImGuiExt::GetCustomColorVec4(ImGuiCustomCol_Highlight); highlightColor.w *= ImSin(ImGui::GetTime() * 6.0F) / 4.0F + 0.75F; drawList->AddRect(rect.Min - ImVec2(5, 5), rect.Max + ImVec2(5, 5), ImColor(highlightColor), 5.0F, ImDrawFlags_None, 2.0F); } { if (!unlocalizedText.empty()) { const auto mainWindowPos = ImHexApi::System::getMainWindowPosition(); const auto mainWindowSize = ImHexApi::System::getMainWindowSize(); const auto margin = ImGui::GetStyle().WindowPadding; ImVec2 windowPos = { rect.Min.x + 20_scaled, rect.Max.y + 10_scaled }; ImVec2 windowSize = { std::max<float>(rect.Max.x - rect.Min.x - 40_scaled, 300_scaled), 0 }; const char* text = Lang(unlocalizedText); const auto textSize = ImGui::CalcTextSize(text, nullptr, false, windowSize.x - margin.x * 2); windowSize.y = textSize.y + margin.y * 2; if (windowPos.y + windowSize.y > mainWindowPos.y + mainWindowSize.y) windowPos.y = rect.Min.y - windowSize.y - 15_scaled; if (windowPos.y < mainWindowPos.y) windowPos.y = rect.Min.y + 10_scaled; ImGui::SetNextWindowPos(windowPos); ImGui::SetNextWindowSize(windowSize); ImGui::SetNextWindowViewport(ImGui::GetMainViewport()->ID); if (ImGui::Begin(unlocalizedText.c_str(), nullptr, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize)) { ImGui::BringWindowToDisplayFront(ImGui::GetCurrentWindowRead()); ImGuiExt::TextFormattedWrapped("{}", text); } ImGui::End(); } } drawList->PopClipRect(); } s_highlightDisplays->clear(); } void TutorialManager::drawMessageBox(std::optional<Tutorial::Step::Message> message) { const auto windowStart = ImHexApi::System::getMainWindowPosition() + scaled({ 10, 10 }); const auto windowEnd = ImHexApi::System::getMainWindowPosition() + ImHexApi::System::getMainWindowSize() - scaled({ 10, 10 }); ImVec2 position = ImHexApi::System::getMainWindowPosition() + ImHexApi::System::getMainWindowSize() / 2.0F; ImVec2 pivot = { 0.5F, 0.5F }; if (!message.has_value()) { message = Tutorial::Step::Message { Position::None, "", "", false }; } if (message->position == Position::None) { message->position = Position::Bottom | Position::Right; } if ((message->position & Position::Top) == Position::Top) { position.y = windowStart.y; pivot.y = 0.0F; } if ((message->position & Position::Bottom) == Position::Bottom) { position.y = windowEnd.y; pivot.y = 1.0F; } if ((message->position & Position::Left) == Position::Left) { position.x = windowStart.x; pivot.x = 0.0F; } if ((message->position & Position::Right) == Position::Right) { position.x = windowEnd.x; pivot.x = 1.0F; } ImGui::SetNextWindowPos(position, ImGuiCond_Always, pivot); if (ImGui::Begin("##TutorialMessage", nullptr, ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_NoDocking | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoFocusOnAppearing)) { ImGui::BringWindowToDisplayFront(ImGui::GetCurrentWindowRead()); if (!message->unlocalizedTitle.empty()) ImGuiExt::Header(Lang(message->unlocalizedTitle), true); if (!message->unlocalizedMessage.empty()) { ImGui::PushTextWrapPos(300_scaled); ImGui::TextUnformatted(Lang(message->unlocalizedMessage)); ImGui::PopTextWrapPos(); ImGui::NewLine(); } ImGui::BeginDisabled(s_currentTutorial->second.m_currentStep == s_currentTutorial->second.m_steps.begin()); if (ImGui::ArrowButton("Backwards", ImGuiDir_Left)) { s_currentTutorial->second.m_currentStep->advance(-1); } ImGui::EndDisabled(); ImGui::SameLine(); ImGui::BeginDisabled(!message->allowSkip && s_currentTutorial->second.m_currentStep == s_currentTutorial->second.m_latestStep); if (ImGui::ArrowButton("Forwards", ImGuiDir_Right)) { s_currentTutorial->second.m_currentStep->advance(1); } ImGui::EndDisabled(); } ImGui::End(); } void TutorialManager::drawTutorial() { drawHighlights(); if (s_currentTutorial == s_tutorials->end()) return; const auto &currentStep = s_currentTutorial->second.m_currentStep; if (currentStep == s_currentTutorial->second.m_steps.end()) return; const auto &message = currentStep->m_message; drawMessageBox(message); } void TutorialManager::reset() { s_tutorials->clear(); s_currentTutorial = s_tutorials->end(); s_highlights->clear(); s_highlightDisplays->clear(); } TutorialManager::Tutorial::Step& TutorialManager::Tutorial::addStep() { auto &newStep = m_steps.emplace_back(this); m_currentStep = m_steps.end(); m_latestStep = m_currentStep; return newStep; } void TutorialManager::Tutorial::start() { m_currentStep = m_steps.begin(); m_latestStep = m_currentStep; if (m_currentStep == m_steps.end()) return; m_currentStep->addHighlights(); } void TutorialManager::Tutorial::Step::addHighlights() const { if (m_onAppear) m_onAppear(); for (const auto &[text, ids] : m_highlights) { s_highlights->emplace(calculateId(ids), text); } } void TutorialManager::Tutorial::Step::removeHighlights() const { for (const auto &[text, ids] : m_highlights) { s_highlights->erase(calculateId(ids)); } } void TutorialManager::Tutorial::Step::advance(i32 steps) const { m_parent->m_currentStep->removeHighlights(); if (m_parent->m_currentStep == m_parent->m_latestStep && steps > 0) std::advance(m_parent->m_latestStep, steps); std::advance(m_parent->m_currentStep, steps); if (m_parent->m_currentStep != m_parent->m_steps.end()) m_parent->m_currentStep->addHighlights(); else s_currentTutorial = s_tutorials->end(); } TutorialManager::Tutorial::Step& TutorialManager::Tutorial::Step::addHighlight(const UnlocalizedString &unlocalizedText, std::initializer_list<std::variant<Lang, std::string, int>>&& ids) { m_highlights.emplace_back( unlocalizedText, ids ); return *this; } TutorialManager::Tutorial::Step& TutorialManager::Tutorial::Step::addHighlight(std::initializer_list<std::variant<Lang, std::string, int>>&& ids) { return this->addHighlight("", std::forward<decltype(ids)>(ids)); } TutorialManager::Tutorial::Step& TutorialManager::Tutorial::Step::setMessage(const UnlocalizedString &unlocalizedTitle, const UnlocalizedString &unlocalizedMessage, Position position) { m_message = Message { position, unlocalizedTitle, unlocalizedMessage, false }; return *this; } TutorialManager::Tutorial::Step& TutorialManager::Tutorial::Step::allowSkip() { if (m_message.has_value()) { m_message->allowSkip = true; } else { m_message = Message { Position::Bottom | Position::Right, "", "", true }; } return *this; } TutorialManager::Tutorial::Step& TutorialManager::Tutorial::Step::onAppear(std::function<void()> callback) { m_onAppear = std::move(callback); return *this; } TutorialManager::Tutorial::Step& TutorialManager::Tutorial::Step::onComplete(std::function<void()> callback) { m_onComplete = std::move(callback); return *this; } bool TutorialManager::Tutorial::Step::isCurrent() const { const auto &currentStep = m_parent->m_currentStep; if (currentStep == m_parent->m_steps.end()) return false; return &*currentStep == this; } void TutorialManager::Tutorial::Step::complete() const { if (this->isCurrent()) { this->advance(); if (m_onComplete) { TaskManager::doLater([this] { m_onComplete(); }); } } } }
15,034
C++
.cpp
328
33.95122
287
0.577884
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
110
imhex_api.cpp
WerWolv_ImHex/lib/libimhex/source/api/imhex_api.cpp
#include <hex/api/imhex_api.hpp> #include <hex/api/event_manager.hpp> #include <hex/api/task_manager.hpp> #include <hex/helpers/fmt.hpp> #include <hex/helpers/utils.hpp> #include <hex/helpers/auto_reset.hpp> #include <hex/providers/provider_data.hpp> #include <hex/providers/provider.hpp> #include <wolv/utils/string.hpp> #include <utility> #include <imgui.h> #include <imgui_internal.h> #include <set> #include <algorithm> #include <GLFW/glfw3.h> #if defined(OS_WINDOWS) #include <windows.h> #else #include <sys/utsname.h> #include <unistd.h> #endif namespace hex { namespace ImHexApi::HexEditor { Highlighting::Highlighting(Region region, color_t color) : m_region(region), m_color(color) { } Tooltip::Tooltip(Region region, std::string value, color_t color) : m_region(region), m_value(std::move(value)), m_color(color) { } namespace impl { static AutoReset<std::map<u32, Highlighting>> s_backgroundHighlights; const std::map<u32, Highlighting>& getBackgroundHighlights() { return *s_backgroundHighlights; } static AutoReset<std::map<u32, HighlightingFunction>> s_backgroundHighlightingFunctions; const std::map<u32, HighlightingFunction>& getBackgroundHighlightingFunctions() { return *s_backgroundHighlightingFunctions; } static AutoReset<std::map<u32, Highlighting>> s_foregroundHighlights; const std::map<u32, Highlighting>& getForegroundHighlights() { return *s_foregroundHighlights; } static AutoReset<std::map<u32, HighlightingFunction>> s_foregroundHighlightingFunctions; const std::map<u32, HighlightingFunction>& getForegroundHighlightingFunctions() { return *s_foregroundHighlightingFunctions; } static AutoReset<std::map<u32, Tooltip>> s_tooltips; const std::map<u32, Tooltip>& getTooltips() { return *s_tooltips; } static AutoReset<std::map<u32, TooltipFunction>> s_tooltipFunctions; const std::map<u32, TooltipFunction>& getTooltipFunctions() { return *s_tooltipFunctions; } static AutoReset<std::map<u32, HoveringFunction>> s_hoveringFunctions; const std::map<u32, HoveringFunction>& getHoveringFunctions() { return *s_hoveringFunctions; } static AutoReset<std::optional<ProviderRegion>> s_currentSelection; void setCurrentSelection(const std::optional<ProviderRegion> &region) { if (region == Region::Invalid()) { clearSelection(); } else { *s_currentSelection = region; } } static PerProvider<std::optional<Region>> s_hoveredRegion; void setHoveredRegion(const prv::Provider *provider, const Region &region) { if (region == Region::Invalid()) s_hoveredRegion.get(provider).reset(); else s_hoveredRegion.get(provider) = region; } } u32 addBackgroundHighlight(const Region &region, color_t color) { static u32 id = 0; id++; impl::s_backgroundHighlights->insert({ id, Highlighting { region, color } }); TaskManager::doLaterOnce([]{ EventHighlightingChanged::post(); }); return id; } void removeBackgroundHighlight(u32 id) { impl::s_backgroundHighlights->erase(id); TaskManager::doLaterOnce([]{ EventHighlightingChanged::post(); }); } u32 addBackgroundHighlightingProvider(const impl::HighlightingFunction &function) { static u32 id = 0; id++; impl::s_backgroundHighlightingFunctions->insert({ id, function }); TaskManager::doLaterOnce([]{ EventHighlightingChanged::post(); }); return id; } void removeBackgroundHighlightingProvider(u32 id) { impl::s_backgroundHighlightingFunctions->erase(id); TaskManager::doLaterOnce([]{ EventHighlightingChanged::post(); }); } u32 addForegroundHighlight(const Region &region, color_t color) { static u32 id = 0; id++; impl::s_foregroundHighlights->insert({ id, Highlighting { region, color } }); TaskManager::doLaterOnce([]{ EventHighlightingChanged::post(); }); return id; } void removeForegroundHighlight(u32 id) { impl::s_foregroundHighlights->erase(id); TaskManager::doLaterOnce([]{ EventHighlightingChanged::post(); }); } u32 addForegroundHighlightingProvider(const impl::HighlightingFunction &function) { static u32 id = 0; id++; impl::s_foregroundHighlightingFunctions->insert({ id, function }); TaskManager::doLaterOnce([]{ EventHighlightingChanged::post(); }); return id; } void removeForegroundHighlightingProvider(u32 id) { impl::s_foregroundHighlightingFunctions->erase(id); TaskManager::doLaterOnce([]{ EventHighlightingChanged::post(); }); } u32 addHoverHighlightProvider(const impl::HoveringFunction &function) { static u32 id = 0; id++; impl::s_hoveringFunctions->insert({ id, function }); return id; } void removeHoverHighlightProvider(u32 id) { impl::s_hoveringFunctions->erase(id); } static u32 s_tooltipId = 0; u32 addTooltip(Region region, std::string value, color_t color) { s_tooltipId++; impl::s_tooltips->insert({ s_tooltipId, { region, std::move(value), color } }); return s_tooltipId; } void removeTooltip(u32 id) { impl::s_tooltips->erase(id); } static u32 s_tooltipFunctionId; u32 addTooltipProvider(TooltipFunction function) { s_tooltipFunctionId++; impl::s_tooltipFunctions->insert({ s_tooltipFunctionId, std::move(function) }); return s_tooltipFunctionId; } void removeTooltipProvider(u32 id) { impl::s_tooltipFunctions->erase(id); } bool isSelectionValid() { auto selection = getSelection(); return selection.has_value() && selection->provider != nullptr; } std::optional<ProviderRegion> getSelection() { return impl::s_currentSelection; } void clearSelection() { impl::s_currentSelection->reset(); } void setSelection(const Region &region, prv::Provider *provider) { setSelection(ProviderRegion { region, provider == nullptr ? Provider::get() : provider }); } void setSelection(const ProviderRegion &region) { RequestHexEditorSelectionChange::post(region); } void setSelection(u64 address, size_t size, prv::Provider *provider) { setSelection({ { address, size }, provider == nullptr ? Provider::get() : provider }); } void addVirtualFile(const std::fs::path &path, std::vector<u8> data, Region region) { RequestAddVirtualFile::post(path, std::move(data), region); } const std::optional<Region>& getHoveredRegion(const prv::Provider *provider) { return impl::s_hoveredRegion.get(provider); } } namespace ImHexApi::Bookmarks { u64 add(Region region, const std::string &name, const std::string &comment, u32 color) { u64 id = 0; RequestAddBookmark::post(region, name, comment, color, &id); return id; } u64 add(u64 address, size_t size, const std::string &name, const std::string &comment, u32 color) { return add(Region { address, size }, name, comment, color); } void remove(u64 id) { RequestRemoveBookmark::post(id); } } namespace ImHexApi::Provider { static i64 s_currentProvider = -1; static AutoReset<std::vector<std::unique_ptr<prv::Provider>>> s_providers; static AutoReset<std::map<prv::Provider*, std::unique_ptr<prv::Provider>>> s_providersToRemove; namespace impl { static std::set<prv::Provider*> s_closingProviders; void resetClosingProvider() { s_closingProviders.clear(); } std::set<prv::Provider*> getClosingProviders() { return s_closingProviders; } static std::recursive_mutex s_providerMutex; } prv::Provider *get() { if (!ImHexApi::Provider::isValid()) return nullptr; return (*s_providers)[s_currentProvider].get(); } std::vector<prv::Provider*> getProviders() { std::vector<prv::Provider*> result; result.reserve(s_providers->size()); for (const auto &provider : *s_providers) result.push_back(provider.get()); return result; } void setCurrentProvider(i64 index) { std::scoped_lock lock(impl::s_providerMutex); if (TaskManager::getRunningTaskCount() > 0) return; if (std::cmp_less(index, s_providers->size()) && s_currentProvider != index) { auto oldProvider = get(); s_currentProvider = index; EventProviderChanged::post(oldProvider, get()); } RequestUpdateWindowTitle::post(); } void setCurrentProvider(NonNull<prv::Provider*> provider) { std::scoped_lock lock(impl::s_providerMutex); if (TaskManager::getRunningTaskCount() > 0) return; const auto providers = getProviders(); auto it = std::ranges::find(providers, provider.get()); auto index = std::distance(providers.begin(), it); setCurrentProvider(index); } i64 getCurrentProviderIndex() { return s_currentProvider; } bool isValid() { return !s_providers->empty() && s_currentProvider >= 0 && s_currentProvider < i64(s_providers->size()); } void markDirty() { const auto provider = get(); if (!provider->isDirty()) { provider->markDirty(); EventProviderDirtied::post(provider); } } void resetDirty() { for (const auto &provider : *s_providers) provider->markDirty(false); } bool isDirty() { return std::ranges::any_of(*s_providers, [](const auto &provider) { return provider->isDirty(); }); } void add(std::unique_ptr<prv::Provider> &&provider, bool skipLoadInterface, bool select) { std::scoped_lock lock(impl::s_providerMutex); if (TaskManager::getRunningTaskCount() > 0) return; if (skipLoadInterface) provider->skipLoadInterface(); EventProviderCreated::post(provider.get()); s_providers->emplace_back(std::move(provider)); if (select || s_providers->size() == 1) setCurrentProvider(s_providers->size() - 1); } void remove(prv::Provider *provider, bool noQuestions) { std::scoped_lock lock(impl::s_providerMutex); if (provider == nullptr) return; if (TaskManager::getRunningTaskCount() > 0) return; if (!noQuestions) { impl::s_closingProviders.insert(provider); bool shouldClose = true; EventProviderClosing::post(provider, &shouldClose); if (!shouldClose) return; } const auto it = std::ranges::find_if(*s_providers, [provider](const auto &p) { return p.get() == provider; }); if (it == s_providers->end()) return; if (!s_providers->empty()) { if (it == s_providers->begin()) { // If the first provider is being closed, select the one that's the first one now setCurrentProvider(0); if (s_providers->size() > 1) EventProviderChanged::post(s_providers->at(0).get(), s_providers->at(1).get()); } else if (std::distance(s_providers->begin(), it) == s_currentProvider) { // If the current provider is being closed, select the one that's before it setCurrentProvider(s_currentProvider - 1); } else { // If any other provider is being closed, find the current provider in the list again and select it again const auto currentProvider = get(); const auto currentIt = std::ranges::find_if(*s_providers, [currentProvider](const auto &p) { return p.get() == currentProvider; }); if (currentIt != s_providers->end()) { auto newIndex = std::distance(s_providers->begin(), currentIt); if (s_currentProvider == newIndex && newIndex != 0) newIndex -= 1; setCurrentProvider(newIndex); } else { // If the current provider is not in the list anymore, select the first one setCurrentProvider(0); } } } static std::mutex eraseMutex; // Move provider over to a list of providers to delete eraseMutex.lock(); auto providerToRemove = it->get(); (*s_providersToRemove)[providerToRemove] = std::move(*it); eraseMutex.unlock(); // Remove left over references from the main provider list s_providers->erase(it); impl::s_closingProviders.erase(provider); if (s_currentProvider >= i64(s_providers->size()) && !s_providers->empty()) setCurrentProvider(s_providers->size() - 1); if (s_providers->empty()) EventProviderChanged::post(provider, nullptr); EventProviderClosed::post(it->get()); RequestUpdateWindowTitle::post(); // Do the destruction of the provider in the background once all tasks have finished TaskManager::runWhenTasksFinished([providerToRemove] { EventProviderDeleted::post(providerToRemove); TaskManager::createBackgroundTask("Closing Provider", [providerToRemove](Task &) { eraseMutex.lock(); auto provider = std::move((*s_providersToRemove)[providerToRemove]); s_providersToRemove->erase(providerToRemove); eraseMutex.unlock(); provider->close(); }); }); } prv::Provider* createProvider(const UnlocalizedString &unlocalizedName, bool skipLoadInterface, bool select) { prv::Provider* result = nullptr; RequestCreateProvider::post(unlocalizedName, skipLoadInterface, select, &result); return result; } } namespace ImHexApi::System { namespace impl { // Default to true means we forward to ourselves by default static bool s_isMainInstance = true; void setMainInstanceStatus(bool status) { s_isMainInstance = status; } static ImVec2 s_mainWindowPos; static ImVec2 s_mainWindowSize; void setMainWindowPosition(i32 x, i32 y) { s_mainWindowPos = ImVec2(float(x), float(y)); } void setMainWindowSize(u32 width, u32 height) { s_mainWindowSize = ImVec2(float(width), float(height)); } static ImGuiID s_mainDockSpaceId; void setMainDockSpaceId(ImGuiID id) { s_mainDockSpaceId = id; } static GLFWwindow *s_mainWindowHandle; void setMainWindowHandle(GLFWwindow *window) { s_mainWindowHandle = window; } static float s_globalScale = 1.0; void setGlobalScale(float scale) { s_globalScale = scale; } static float s_nativeScale = 1.0; void setNativeScale(float scale) { s_nativeScale = scale; } static bool s_borderlessWindowMode; void setBorderlessWindowMode(bool enabled) { s_borderlessWindowMode = enabled; } static bool s_multiWindowMode = false; void setMultiWindowMode(bool enabled) { s_multiWindowMode = enabled; } static std::optional<InitialWindowProperties> s_initialWindowProperties; void setInitialWindowProperties(InitialWindowProperties properties) { s_initialWindowProperties = properties; } static AutoReset<std::string> s_gpuVendor; void setGPUVendor(const std::string &vendor) { s_gpuVendor = vendor; } static AutoReset<std::string> s_glRenderer; void setGLRenderer(const std::string &renderer) { s_glRenderer = renderer; } static AutoReset<std::map<std::string, std::string>> s_initArguments; void addInitArgument(const std::string &key, const std::string &value) { static std::mutex initArgumentsMutex; std::scoped_lock lock(initArgumentsMutex); (*s_initArguments)[key] = value; } static double s_lastFrameTime; void setLastFrameTime(double time) { s_lastFrameTime = time; } static bool s_windowResizable = true; bool isWindowResizable() { return s_windowResizable; } static std::vector<hex::impl::AutoResetBase*> s_autoResetObjects; void addAutoResetObject(hex::impl::AutoResetBase *object) { s_autoResetObjects.emplace_back(object); } void cleanup() { for (const auto &object : s_autoResetObjects) object->reset(); } } bool isMainInstance() { return impl::s_isMainInstance; } void closeImHex(bool noQuestions) { RequestCloseImHex::post(noQuestions); } void restartImHex() { RequestRestartImHex::post(); RequestCloseImHex::post(false); } void setTaskBarProgress(TaskProgressState state, TaskProgressType type, u32 progress) { EventSetTaskBarIconState::post(u32(state), u32(type), progress); } static float s_targetFPS = 14.0F; float getTargetFPS() { return s_targetFPS; } void setTargetFPS(float fps) { s_targetFPS = fps; } float getGlobalScale() { return impl::s_globalScale; } float getNativeScale() { return impl::s_nativeScale; } ImVec2 getMainWindowPosition() { if ((ImGui::GetIO().ConfigFlags & ImGuiConfigFlags_ViewportsEnable) != ImGuiConfigFlags_None) return impl::s_mainWindowPos; else return { 0, 0 }; } ImVec2 getMainWindowSize() { return impl::s_mainWindowSize; } ImGuiID getMainDockSpaceId() { return impl::s_mainDockSpaceId; } GLFWwindow* getMainWindowHandle() { return impl::s_mainWindowHandle; } bool isBorderlessWindowModeEnabled() { return impl::s_borderlessWindowMode; } bool isMutliWindowModeEnabled() { return impl::s_multiWindowMode; } std::optional<InitialWindowProperties> getInitialWindowProperties() { return impl::s_initialWindowProperties; } void* getLibImHexModuleHandle() { return hex::getContainingModule(reinterpret_cast<void*>(&getLibImHexModuleHandle)); } const std::map<std::string, std::string>& getInitArguments() { return *impl::s_initArguments; } std::string getInitArgument(const std::string &key) { if (impl::s_initArguments->contains(key)) return impl::s_initArguments->at(key); else return ""; } static bool s_systemThemeDetection; void enableSystemThemeDetection(bool enabled) { s_systemThemeDetection = enabled; EventOSThemeChanged::post(); } bool usesSystemThemeDetection() { return s_systemThemeDetection; } static AutoReset<std::vector<std::fs::path>> s_additionalFolderPaths; const std::vector<std::fs::path>& getAdditionalFolderPaths() { return *s_additionalFolderPaths; } void setAdditionalFolderPaths(const std::vector<std::fs::path> &paths) { s_additionalFolderPaths = paths; } const std::string &getGPUVendor() { return impl::s_gpuVendor; } const std::string &getGLRenderer() { return impl::s_glRenderer; } bool isPortableVersion() { static std::optional<bool> portable; if (portable.has_value()) return portable.value(); if (const auto executablePath = wolv::io::fs::getExecutablePath(); executablePath.has_value()) { const auto flagFile = executablePath->parent_path() / "PORTABLE"; portable = wolv::io::fs::exists(flagFile) && wolv::io::fs::isRegularFile(flagFile); } else { portable = false; } return portable.value(); } std::string getOSName() { #if defined(OS_WINDOWS) return "Windows"; #elif defined(OS_LINUX) #if defined(OS_FREEBSD) return "FreeBSD"; #else return "Linux"; #endif #elif defined(OS_MACOS) return "macOS"; #elif defined(OS_WEB) return "Web"; #else return "Unknown"; #endif } std::string getOSVersion() { #if defined(OS_WINDOWS) OSVERSIONINFOA info; info.dwOSVersionInfoSize = sizeof(OSVERSIONINFOA); ::GetVersionExA(&info); return hex::format("{}.{}.{}", info.dwMajorVersion, info.dwMinorVersion, info.dwBuildNumber); #elif defined(OS_LINUX) || defined(OS_MACOS) || defined(OS_WEB) struct utsname details = { }; if (uname(&details) != 0) { return "Unknown"; } return std::string(details.release) + " " + std::string(details.version); #else return "Unknown"; #endif } std::string getArchitecture() { #if defined(OS_WINDOWS) SYSTEM_INFO info; ::GetNativeSystemInfo(&info); switch (info.wProcessorArchitecture) { case PROCESSOR_ARCHITECTURE_AMD64: return "x86_64"; case PROCESSOR_ARCHITECTURE_ARM: return "ARM"; case PROCESSOR_ARCHITECTURE_ARM64: return "ARM64"; case PROCESSOR_ARCHITECTURE_IA64: return "IA64"; case PROCESSOR_ARCHITECTURE_INTEL: return "x86"; default: return "Unknown"; } #elif defined(OS_LINUX) || defined(OS_MACOS) || defined(OS_WEB) struct utsname details = { }; if (uname(&details) != 0) { return "Unknown"; } return { details.machine }; #else return "Unknown"; #endif } std::optional<LinuxDistro> getLinuxDistro() { wolv::io::File file("/etc/os-release", wolv::io::File::Mode::Read); std::string name; std::string version; auto fileContent = file.readString(); for (const auto &line : wolv::util::splitString(fileContent, "\n")) { if (line.find("PRETTY_NAME=") != std::string::npos) { name = line.substr(line.find("=") + 1); std::erase(name, '\"'); } else if (line.find("VERSION_ID=") != std::string::npos) { version = line.substr(line.find("=") + 1); std::erase(version, '\"'); } } return { { name, version } }; } std::string getImHexVersion(bool withBuildType) { #if defined IMHEX_VERSION if (withBuildType) { return IMHEX_VERSION; } else { auto version = std::string(IMHEX_VERSION); return version.substr(0, version.find('-')); } #else return "Unknown"; #endif } std::string getCommitHash(bool longHash) { #if defined GIT_COMMIT_HASH_LONG if (longHash) { return GIT_COMMIT_HASH_LONG; } else { return std::string(GIT_COMMIT_HASH_LONG).substr(0, 7); } #else hex::unused(longHash); return "Unknown"; #endif } std::string getCommitBranch() { #if defined GIT_BRANCH return GIT_BRANCH; #else return "Unknown"; #endif } bool isDebugBuild() { #if defined DEBUG return true; #else return false; #endif } bool isNightlyBuild() { return getImHexVersion(false).ends_with("WIP"); } bool updateImHex(UpdateType updateType) { // Get the path of the updater executable std::fs::path executablePath; for (const auto &entry : std::fs::directory_iterator(wolv::io::fs::getExecutablePath()->parent_path())) { if (entry.path().filename().string().starts_with("imhex-updater")) { executablePath = entry.path(); break; } } if (executablePath.empty() || !wolv::io::fs::exists(executablePath)) return false; std::string updateTypeString; switch (updateType) { case UpdateType::Stable: updateTypeString = "latest"; break; case UpdateType::Nightly: updateTypeString = "nightly"; break; } EventImHexClosing::subscribe([executablePath, updateTypeString] { hex::executeCommand( hex::format("\"{}\" \"{}\"", wolv::util::toUTF8String(executablePath), updateTypeString ) ); }); ImHexApi::System::closeImHex(); return true; } void addStartupTask(const std::string &name, bool async, const std::function<bool()> &function) { RequestAddInitTask::post(name, async, function); } double getLastFrameTime() { return impl::s_lastFrameTime; } void setWindowResizable(bool resizable) { glfwSetWindowAttrib(impl::s_mainWindowHandle, GLFW_RESIZABLE, int(resizable)); impl::s_windowResizable = resizable; } } namespace ImHexApi::Messaging { namespace impl { static AutoReset<std::map<std::string, MessagingHandler>> s_handlers; const std::map<std::string, MessagingHandler>& getHandlers() { return *s_handlers; } void runHandler(const std::string &eventName, const std::vector<u8> &args) { const auto& handlers = getHandlers(); const auto matchHandler = handlers.find(eventName); if (matchHandler == handlers.end()) { log::error("Forward event handler {} not found", eventName); } else { matchHandler->second(args); } } } void registerHandler(const std::string &eventName, const impl::MessagingHandler &handler) { log::debug("Registered new forward event handler: {}", eventName); impl::s_handlers->insert({ eventName, handler }); } } namespace ImHexApi::Fonts { namespace impl { static AutoReset<std::vector<Font>> s_fonts; const std::vector<Font>& getFonts() { return *s_fonts; } static AutoReset<std::fs::path> s_customFontPath; void setCustomFontPath(const std::fs::path &path) { s_customFontPath = path; } static float s_fontSize = DefaultFontSize; void setFontSize(float size) { s_fontSize = size; } static AutoReset<ImFontAtlas*> s_fontAtlas; void setFontAtlas(ImFontAtlas* fontAtlas) { s_fontAtlas = fontAtlas; } static ImFont *s_boldFont = nullptr; static ImFont *s_italicFont = nullptr; void setFonts(ImFont *bold, ImFont *italic) { s_boldFont = bold; s_italicFont = italic; } } GlyphRange glyph(const char *glyph) { u32 codepoint; ImTextCharFromUtf8(&codepoint, glyph, nullptr); return { .begin = u16(codepoint), .end = u16(codepoint) }; } GlyphRange glyph(u32 codepoint) { return { .begin = u16(codepoint), .end = u16(codepoint) }; } GlyphRange range(const char *glyphBegin, const char *glyphEnd) { u32 codepointBegin, codepointEnd; ImTextCharFromUtf8(&codepointBegin, glyphBegin, nullptr); ImTextCharFromUtf8(&codepointEnd, glyphEnd, nullptr); return { .begin = u16(codepointBegin), .end = u16(codepointEnd) }; } GlyphRange range(u32 codepointBegin, u32 codepointEnd) { return { .begin = u16(codepointBegin), .end = u16(codepointEnd) }; } void loadFont(const std::fs::path &path, const std::vector<GlyphRange> &glyphRanges, Offset offset, u32 flags, std::optional<u32> defaultSize) { wolv::io::File fontFile(path, wolv::io::File::Mode::Read); if (!fontFile.isValid()) { log::error("Failed to load font from file '{}'", wolv::util::toUTF8String(path)); return; } impl::s_fonts->emplace_back(Font { wolv::util::toUTF8String(path.filename()), fontFile.readVector(), glyphRanges, offset, flags, defaultSize }); } void loadFont(const std::string &name, const std::span<const u8> &data, const std::vector<GlyphRange> &glyphRanges, Offset offset, u32 flags, std::optional<u32> defaultSize) { impl::s_fonts->emplace_back(Font { name, { data.begin(), data.end() }, glyphRanges, offset, flags, defaultSize }); } const std::fs::path& getCustomFontPath() { return impl::s_customFontPath; } float getFontSize() { return impl::s_fontSize; } ImFontAtlas* getFontAtlas() { return impl::s_fontAtlas; } ImFont* Bold() { return impl::s_boldFont; } ImFont* Italic() { return impl::s_italicFont; } } }
33,547
C++
.cpp
791
28.863464
183
0.543745
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
111
task_manager.cpp
WerWolv_ImHex/lib/libimhex/source/api/task_manager.cpp
#include <hex/api/task_manager.hpp> #include <hex/api/localization_manager.hpp> #include <hex/helpers/logger.hpp> #include <algorithm> #include <ranges> #include <jthread.hpp> #if defined(OS_WINDOWS) #include <windows.h> #include <processthreadsapi.h> #include <hex/helpers/utils.hpp> #else #include <pthread.h> #endif namespace { struct SourceLocationWrapper { std::source_location location; bool operator==(const SourceLocationWrapper &other) const { return location.file_name() == other.location.file_name() && location.function_name() == other.location.function_name() && location.column() == other.location.column() && location.line() == other.location.line(); } }; } template<> struct std::hash<SourceLocationWrapper> { std::size_t operator()(const SourceLocationWrapper& s) const noexcept { auto h1 = std::hash<std::string>{}(s.location.file_name()); auto h2 = std::hash<std::string>{}(s.location.function_name()); auto h3 = std::hash<u32>{}(s.location.column()); auto h4 = std::hash<u32>{}(s.location.line()); return (h1 << 0) ^ (h2 << 1) ^ (h3 << 2) ^ (h4 << 3); } }; namespace hex { namespace { std::recursive_mutex s_deferredCallsMutex, s_tasksFinishedMutex; std::list<std::shared_ptr<Task>> s_tasks, s_taskQueue; std::list<std::function<void()>> s_deferredCalls; std::unordered_map<SourceLocationWrapper, std::function<void()>> s_onceDeferredCalls; std::list<std::function<void()>> s_tasksFinishedCallbacks; std::mutex s_queueMutex; std::condition_variable s_jobCondVar; std::vector<std::jthread> s_workers; thread_local std::array<char, 256> s_currentThreadName; thread_local Task* s_currentTask = nullptr; } Task::Task(const UnlocalizedString &unlocalizedName, u64 maxValue, bool background, std::function<void(Task &)> function) : m_unlocalizedName(std::move(unlocalizedName)), m_maxValue(maxValue), m_function(std::move(function)), m_background(background) { } Task::Task(hex::Task &&other) noexcept { { std::scoped_lock thisLock(m_mutex); std::scoped_lock otherLock(other.m_mutex); m_function = std::move(other.m_function); m_unlocalizedName = std::move(other.m_unlocalizedName); } m_maxValue = u64(other.m_maxValue); m_currValue = u64(other.m_currValue); m_finished = bool(other.m_finished); m_hadException = bool(other.m_hadException); m_interrupted = bool(other.m_interrupted); m_shouldInterrupt = bool(other.m_shouldInterrupt); } Task::~Task() { if (!this->isFinished()) this->interrupt(); } void Task::update(u64 value) { // Update the current progress value of the task m_currValue.store(value, std::memory_order_relaxed); // Check if the task has been interrupted by the main thread and if yes, // throw an exception that is generally not caught by the task if (m_shouldInterrupt.load(std::memory_order_relaxed)) [[unlikely]] throw TaskInterruptor(); } void Task::update() const { if (m_shouldInterrupt.load(std::memory_order_relaxed)) [[unlikely]] throw TaskInterruptor(); } void Task::increment() { m_currValue.fetch_add(1, std::memory_order_relaxed); if (m_shouldInterrupt.load(std::memory_order_relaxed)) [[unlikely]] throw TaskInterruptor(); } void Task::setMaxValue(u64 value) { m_maxValue = value; } void Task::interrupt() { m_shouldInterrupt = true; // Call the interrupt callback on the current thread if one is set if (m_interruptCallback) m_interruptCallback(); } void Task::setInterruptCallback(std::function<void()> callback) { m_interruptCallback = std::move(callback); } bool Task::isBackgroundTask() const { return m_background; } bool Task::isFinished() const { return m_finished; } bool Task::hadException() const { return m_hadException; } bool Task::shouldInterrupt() const { return m_shouldInterrupt; } bool Task::wasInterrupted() const { return m_interrupted; } void Task::clearException() { m_hadException = false; } std::string Task::getExceptionMessage() const { std::scoped_lock lock(m_mutex); return m_exceptionMessage; } const UnlocalizedString &Task::getUnlocalizedName() { return m_unlocalizedName; } u64 Task::getValue() const { return m_currValue; } u64 Task::getMaxValue() const { return m_maxValue; } void Task::finish() { m_finished = true; } void Task::interruption() { m_interrupted = true; } void Task::exception(const char *message) { std::scoped_lock lock(m_mutex); // Store information about the caught exception m_exceptionMessage = message; m_hadException = true; } bool TaskHolder::isRunning() const { const auto &task = m_task.lock(); if (!task) return false; return !task->isFinished(); } bool TaskHolder::hadException() const { const auto &task = m_task.lock(); if (!task) return false; return !task->hadException(); } bool TaskHolder::shouldInterrupt() const { const auto &task = m_task.lock(); if (!task) return false; return !task->shouldInterrupt(); } bool TaskHolder::wasInterrupted() const { const auto &task = m_task.lock(); if (!task) return false; return !task->wasInterrupted(); } void TaskHolder::interrupt() const { const auto &task = m_task.lock(); if (!task) return; task->interrupt(); } u32 TaskHolder::getProgress() const { const auto &task = m_task.lock(); if (!task) return 0; // If the max value is 0, the task has no progress if (task->getMaxValue() == 0) return 0; // Calculate the progress of the task from 0 to 100 return u32((task->getValue() * 100) / task->getMaxValue()); } void TaskManager::init() { const auto threadCount = std::thread::hardware_concurrency(); log::debug("Initializing task manager thread pool with {} workers.", threadCount); // Create worker threads for (u32 i = 0; i < threadCount; i++) { s_workers.emplace_back([](const std::stop_token &stopToken) { while (true) { std::shared_ptr<Task> task; // Set the thread name to "Idle Task" while waiting for a task TaskManager::setCurrentThreadName("Idle Task"); { // Wait for a task to be added to the queue std::unique_lock lock(s_queueMutex); s_jobCondVar.wait(lock, [&] { return !s_taskQueue.empty() || stopToken.stop_requested(); }); // Check if the thread should exit if (stopToken.stop_requested()) break; // Grab the next task from the queue task = std::move(s_taskQueue.front()); s_taskQueue.pop_front(); s_currentTask = task.get(); } try { // Set the thread name to the name of the task TaskManager::setCurrentThreadName(Lang(task->m_unlocalizedName)); // Execute the task task->m_function(*task); log::debug("Task '{}' finished", task->m_unlocalizedName.get()); } catch (const Task::TaskInterruptor &) { // Handle the task being interrupted by user request task->interruption(); } catch (const std::exception &e) { log::error("Exception in task '{}': {}", task->m_unlocalizedName.get(), e.what()); // Handle the task throwing an uncaught exception task->exception(e.what()); } catch (...) { log::error("Exception in task '{}'", task->m_unlocalizedName.get()); // Handle the task throwing an uncaught exception of unknown type task->exception("Unknown Exception"); } s_currentTask = nullptr; task->finish(); } }); } } void TaskManager::exit() { // Interrupt all tasks for (const auto &task : s_tasks) { task->interrupt(); } // Ask worker threads to exit after finishing their task for (auto &thread : s_workers) thread.request_stop(); // Wake up all the idle worker threads so they can exit s_jobCondVar.notify_all(); // Wait for all worker threads to exit s_workers.clear(); s_tasks.clear(); s_taskQueue.clear(); s_deferredCalls.clear(); s_onceDeferredCalls.clear(); s_tasksFinishedCallbacks.clear(); } TaskHolder TaskManager::createTask(const UnlocalizedString &unlocalizedName, u64 maxValue, bool background, std::function<void(Task&)> function) { std::scoped_lock lock(s_queueMutex); // Construct new task auto task = std::make_shared<Task>(std::move(unlocalizedName), maxValue, background, std::move(function)); s_tasks.emplace_back(task); // Add task to the queue for the worker to pick up s_taskQueue.emplace_back(std::move(task)); s_jobCondVar.notify_one(); return TaskHolder(s_tasks.back()); } TaskHolder TaskManager::createTask(const UnlocalizedString &unlocalizedName, u64 maxValue, std::function<void(Task &)> function) { log::debug("Creating task {}", unlocalizedName.get()); return createTask(std::move(unlocalizedName), maxValue, false, std::move(function)); } TaskHolder TaskManager::createTask(const UnlocalizedString &unlocalizedName, u64 maxValue, std::function<void()> function) { log::debug("Creating task {}", unlocalizedName.get()); return createTask(std::move(unlocalizedName), maxValue, false, [function = std::move(function)](Task&) { function(); } ); } TaskHolder TaskManager::createBackgroundTask(const UnlocalizedString &unlocalizedName, std::function<void(Task &)> function) { log::debug("Creating background task {}", unlocalizedName.get()); return createTask(std::move(unlocalizedName), 0, true, std::move(function)); } TaskHolder TaskManager::createBackgroundTask(const UnlocalizedString &unlocalizedName, std::function<void()> function) { log::debug("Creating background task {}", unlocalizedName.get()); return createTask(std::move(unlocalizedName), 0, true, [function = std::move(function)](Task&) { function(); } ); } void TaskManager::collectGarbage() { { std::scoped_lock lock(s_queueMutex); std::erase_if(s_tasks, [](const auto &task) { return task->isFinished() && !task->hadException(); }); } if (s_tasks.empty()) { std::scoped_lock lock(s_deferredCallsMutex); for (auto &call : s_tasksFinishedCallbacks) call(); s_tasksFinishedCallbacks.clear(); } } Task& TaskManager::getCurrentTask() { return *s_currentTask; } const std::list<std::shared_ptr<Task>>& TaskManager::getRunningTasks() { return s_tasks; } size_t TaskManager::getRunningTaskCount() { std::scoped_lock lock(s_queueMutex); return std::ranges::count_if(s_tasks, [](const auto &task){ return !task->isBackgroundTask(); }); } size_t TaskManager::getRunningBackgroundTaskCount() { std::scoped_lock lock(s_queueMutex); return std::ranges::count_if(s_tasks, [](const auto &task){ return task->isBackgroundTask(); }); } void TaskManager::doLater(const std::function<void()> &function) { std::scoped_lock lock(s_deferredCallsMutex); s_deferredCalls.push_back(function); } void TaskManager::doLaterOnce(const std::function<void()> &function, std::source_location location) { std::scoped_lock lock(s_deferredCallsMutex); s_onceDeferredCalls[SourceLocationWrapper{ location }] = function; } void TaskManager::runDeferredCalls() { std::scoped_lock lock(s_deferredCallsMutex); while (!s_deferredCalls.empty()) { auto callback = s_deferredCalls.front(); s_deferredCalls.pop_front(); callback(); } while (!s_onceDeferredCalls.empty()) { auto node = s_onceDeferredCalls.extract(s_onceDeferredCalls.begin()); node.mapped()(); } } void TaskManager::runWhenTasksFinished(const std::function<void()> &function) { std::scoped_lock lock(s_tasksFinishedMutex); for (const auto &task : s_tasks) { task->interrupt(); } s_tasksFinishedCallbacks.push_back(function); } void TaskManager::setCurrentThreadName(const std::string &name) { std::ranges::fill(s_currentThreadName, '\0'); std::ranges::copy(name | std::views::take(255), s_currentThreadName.begin()); #if defined(OS_WINDOWS) using SetThreadDescriptionFunc = HRESULT(WINAPI*)(HANDLE hThread, PCWSTR lpThreadDescription); static auto setThreadDescription = reinterpret_cast<SetThreadDescriptionFunc>( reinterpret_cast<uintptr_t>( ::GetProcAddress( ::GetModuleHandleW(L"Kernel32.dll"), "SetThreadDescription" ) ) ); if (setThreadDescription != nullptr) { const auto longName = hex::utf8ToUtf16(name); setThreadDescription(::GetCurrentThread(), longName.c_str()); } else { struct THREADNAME_INFO { DWORD dwType; LPCSTR szName; DWORD dwThreadID; DWORD dwFlags; }; THREADNAME_INFO info = { }; info.dwType = 0x1000; info.szName = name.c_str(); info.dwThreadID = ::GetCurrentThreadId(); info.dwFlags = 0; constexpr static DWORD MS_VC_EXCEPTION = 0x406D1388; RaiseException(MS_VC_EXCEPTION, 0, sizeof(info) / sizeof(ULONG_PTR), reinterpret_cast<ULONG_PTR*>(&info)); } #elif defined(OS_LINUX) pthread_setname_np(pthread_self(), name.c_str()); #elif defined(OS_WEB) hex::unused(name); #elif defined(OS_MACOS) pthread_setname_np(name.c_str()); #endif } std::string TaskManager::getCurrentThreadName() { return s_currentThreadName.data(); } }
15,837
C++
.cpp
381
30.908136
150
0.58136
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
112
localization_manager.cpp
WerWolv_ImHex/lib/libimhex/source/api/localization_manager.cpp
#include <hex/api/content_registry.hpp> #include <hex/api/localization_manager.hpp> #include <hex/helpers/auto_reset.hpp> namespace hex { namespace LocalizationManager { namespace { AutoReset<std::string> s_fallbackLanguage; AutoReset<std::string> s_selectedLanguage; AutoReset<std::map<size_t, std::string>> s_currStrings; } namespace impl { void resetLanguageStrings() { s_currStrings->clear(); s_selectedLanguage->clear(); } void setFallbackLanguage(const std::string &language) { s_fallbackLanguage = language; } } LanguageDefinition::LanguageDefinition(std::map<std::string, std::string> &&entries) { for (const auto &[key, value] : entries) { if (value.empty()) continue; m_entries.insert({ key, value }); } } const std::map<std::string, std::string> &LanguageDefinition::getEntries() const { return m_entries; } static void loadLanguageDefinitions(const std::vector<LanguageDefinition> &definitions) { for (const auto &definition : definitions) { const auto &entries = definition.getEntries(); if (entries.empty()) continue; for (const auto &[key, value] : entries) { if (value.empty()) continue; s_currStrings->emplace(LangConst::hash(key), value); } } } void loadLanguage(const std::string &language) { auto &definitions = ContentRegistry::Language::impl::getLanguageDefinitions(); if (!definitions.contains(language)) return; s_currStrings->clear(); loadLanguageDefinitions(definitions.at(language)); const auto& fallbackLanguage = getFallbackLanguage(); loadLanguageDefinitions(definitions.at(fallbackLanguage)); s_selectedLanguage = language; } std::string getLocalizedString(const std::string& unlocalizedString, const std::string& language) { if (language.empty()) return getLocalizedString(unlocalizedString, getSelectedLanguage()); auto &languageDefinitions = ContentRegistry::Language::impl::getLanguageDefinitions(); if (!languageDefinitions.contains(language)) return ""; std::string localizedString; for (const auto &definition : languageDefinitions.at(language)) { if (definition.getEntries().contains(unlocalizedString)) { localizedString = definition.getEntries().at(unlocalizedString); break; } } if (localizedString.empty()) return getLocalizedString(unlocalizedString, getFallbackLanguage()); return localizedString; } const std::map<std::string, std::string> &getSupportedLanguages() { return ContentRegistry::Language::impl::getLanguages(); } const std::string &getFallbackLanguage() { return s_fallbackLanguage; } const std::string &getSelectedLanguage() { return s_selectedLanguage; } } Lang::Lang(const char *unlocalizedString) : m_entryHash(LangConst::hash(unlocalizedString)), m_unlocalizedString(unlocalizedString) { } Lang::Lang(const std::string &unlocalizedString) : m_entryHash(LangConst::hash(unlocalizedString)), m_unlocalizedString(unlocalizedString) { } Lang::Lang(const LangConst &localizedString) : m_entryHash(localizedString.m_entryHash), m_unlocalizedString(localizedString.m_unlocalizedString) { } Lang::Lang(const UnlocalizedString &unlocalizedString) : m_entryHash(LangConst::hash(unlocalizedString.get())), m_unlocalizedString(unlocalizedString.get()) { } Lang::Lang(std::string_view unlocalizedString) : m_entryHash(LangConst::hash(unlocalizedString)), m_unlocalizedString(unlocalizedString) { } Lang::operator std::string() const { return get(); } Lang::operator std::string_view() const { return get(); } Lang::operator const char *() const { return get(); } const char *Lang::get() const { const auto &lang = *LocalizationManager::s_currStrings; const auto it = lang.find(m_entryHash); if (it == lang.end()) { return m_unlocalizedString.c_str(); } else { return it->second.c_str(); } } LangConst::operator std::string() const { return get(); } LangConst::operator std::string_view() const { return get(); } LangConst::operator const char *() const { return get(); } const char *LangConst::get() const { const auto &lang = *LocalizationManager::s_currStrings; const auto it = lang.find(m_entryHash); if (it == lang.end()) { return m_unlocalizedString; } else { return it->second.c_str(); } } }
5,263
C++
.cpp
120
32.733333
164
0.603529
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
113
layout_manager.cpp
WerWolv_ImHex/lib/libimhex/source/api/layout_manager.cpp
#include <hex/api/layout_manager.hpp> #include <hex/api/content_registry.hpp> #include <hex/ui/view.hpp> #include <hex/helpers/fs.hpp> #include <hex/helpers/logger.hpp> #include <hex/helpers/auto_reset.hpp> #include <hex/helpers/default_paths.hpp> #include <wolv/utils/string.hpp> #include <imgui.h> namespace hex { namespace { AutoReset<std::optional<std::fs::path>> s_layoutPathToLoad; AutoReset<std::optional<std::string>> s_layoutStringToLoad; AutoReset<std::vector<LayoutManager::Layout>> s_layouts; AutoReset<std::vector<LayoutManager::LoadCallback>> s_loadCallbacks; AutoReset<std::vector<LayoutManager::StoreCallback>> s_storeCallbacks; bool s_layoutLocked = false; } void LayoutManager::load(const std::fs::path &path) { s_layoutPathToLoad = path; } void LayoutManager::loadFromString(const std::string &content) { s_layoutStringToLoad = content; } void LayoutManager::save(const std::string &name) { auto fileName = name; fileName = wolv::util::replaceStrings(fileName, " ", "_"); std::ranges::transform(fileName, fileName.begin(), tolower); fileName += ".hexlyt"; std::fs::path layoutPath; for (const auto &path : paths::Layouts.write()) { layoutPath = path / fileName; } if (layoutPath.empty()) { log::error("Failed to save layout '{}'. No writable path found", name); return; } const auto pathString = wolv::util::toUTF8String(layoutPath); ImGui::SaveIniSettingsToDisk(pathString.c_str()); log::info("Layout '{}' saved to {}", name, pathString); LayoutManager::reload(); } std::string LayoutManager::saveToString() { return ImGui::SaveIniSettingsToMemory(); } const std::vector<LayoutManager::Layout>& LayoutManager::getLayouts() { return s_layouts; } void LayoutManager::removeLayout(const std::string& name) { for (const auto &layout : *s_layouts) { if (layout.name == name) { if (wolv::io::fs::remove(layout.path)) { log::info("Removed layout '{}'", name); } else { log::error("Failed to remove layout '{}'", name); } } } LayoutManager::reload(); } void LayoutManager::closeAllViews() { for (const auto &[name, view] : ContentRegistry::Views::impl::getEntries()) view->getWindowOpenState() = false; } void LayoutManager::process() { if (s_layoutPathToLoad->has_value()) { LayoutManager::closeAllViews(); wolv::io::File file(**s_layoutPathToLoad, wolv::io::File::Mode::Read); s_layoutStringToLoad = file.readString(); s_layoutPathToLoad->reset(); } if (s_layoutStringToLoad->has_value()) { LayoutManager::closeAllViews(); ImGui::LoadIniSettingsFromMemory((*s_layoutStringToLoad)->c_str()); s_layoutStringToLoad->reset(); log::info("Loaded new Layout"); } } void LayoutManager::reload() { s_layouts->clear(); for (const auto &directory : paths::Layouts.read()) { for (const auto &entry : std::fs::directory_iterator(directory)) { const auto &path = entry.path(); if (path.extension() != ".hexlyt") continue; auto name = path.stem().string(); name = wolv::util::replaceStrings(name, "_", " "); for (size_t i = 0; i < name.size(); i++) { if (i == 0 || name[i - 1] == '_') name[i] = char(std::toupper(name[i])); } s_layouts->push_back({ name, path }); } } } void LayoutManager::reset() { s_layoutPathToLoad->reset(); s_layoutStringToLoad->reset(); s_layouts->clear(); } bool LayoutManager::isLayoutLocked() { return s_layoutLocked; } void LayoutManager::lockLayout(bool locked) { log::info("Layout {}", locked ? "locked" : "unlocked"); s_layoutLocked = locked; } void LayoutManager::registerLoadCallback(const LoadCallback &callback) { s_loadCallbacks->push_back(callback); } void LayoutManager::registerStoreCallback(const StoreCallback &callback) { s_storeCallbacks->push_back(callback); } void LayoutManager::onLoad(std::string_view line) { for (const auto &callback : *s_loadCallbacks) callback(line); } void LayoutManager::onStore(ImGuiTextBuffer *buffer) { for (const auto &callback : *s_storeCallbacks) callback(buffer); } }
4,911
C++
.cpp
125
29.752
83
0.584019
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
114
shortcut_manager.cpp
WerWolv_ImHex/lib/libimhex/source/api/shortcut_manager.cpp
#include <hex/api/shortcut_manager.hpp> #include <imgui.h> #include <hex/api/content_registry.hpp> #include <hex/helpers/auto_reset.hpp> #include <hex/ui/view.hpp> namespace hex { namespace { AutoReset<std::map<Shortcut, ShortcutManager::ShortcutEntry>> s_globalShortcuts; std::atomic<bool> s_paused; std::optional<Shortcut> s_prevShortcut; } void ShortcutManager::addGlobalShortcut(const Shortcut &shortcut, const UnlocalizedString &unlocalizedName, const std::function<void()> &callback) { s_globalShortcuts->insert({ shortcut, { shortcut, unlocalizedName, callback } }); } void ShortcutManager::addShortcut(View *view, const Shortcut &shortcut, const UnlocalizedString &unlocalizedName, const std::function<void()> &callback) { view->m_shortcuts.insert({ shortcut + CurrentView, { shortcut, unlocalizedName, callback } }); } static Shortcut getShortcut(bool ctrl, bool alt, bool shift, bool super, bool focused, u32 keyCode) { Shortcut pressedShortcut; if (ctrl) pressedShortcut += CTRL; if (alt) pressedShortcut += ALT; if (shift) pressedShortcut += SHIFT; if (super) pressedShortcut += SUPER; if (focused) pressedShortcut += CurrentView; pressedShortcut += static_cast<Keys>(keyCode); return pressedShortcut; } static void processShortcut(const Shortcut &shortcut, const std::map<Shortcut, ShortcutManager::ShortcutEntry> &shortcuts) { if (s_paused) return; if (ImGui::IsPopupOpen(ImGuiID(0), ImGuiPopupFlags_AnyPopupId)) return; if (shortcuts.contains(shortcut + AllowWhileTyping)) { shortcuts.at(shortcut + AllowWhileTyping).callback(); } else if (shortcuts.contains(shortcut)) { if (!ImGui::GetIO().WantTextInput) shortcuts.at(shortcut).callback(); } } void ShortcutManager::process(const View *currentView, bool ctrl, bool alt, bool shift, bool super, bool focused, u32 keyCode) { const Shortcut pressedShortcut = getShortcut(ctrl, alt, shift, super, focused, keyCode); if (keyCode != 0) s_prevShortcut = Shortcut(pressedShortcut.getKeys()); processShortcut(pressedShortcut, currentView->m_shortcuts); } void ShortcutManager::processGlobals(bool ctrl, bool alt, bool shift, bool super, u32 keyCode) { const Shortcut pressedShortcut = getShortcut(ctrl, alt, shift, super, false, keyCode); if (keyCode != 0) s_prevShortcut = Shortcut(pressedShortcut.getKeys()); processShortcut(pressedShortcut, s_globalShortcuts); } void ShortcutManager::clearShortcuts() { s_globalShortcuts->clear(); } void ShortcutManager::resumeShortcuts() { s_paused = false; } void ShortcutManager::pauseShortcuts() { s_paused = true; s_prevShortcut.reset(); } std::optional<Shortcut> ShortcutManager::getPreviousShortcut() { return s_prevShortcut; } std::vector<ShortcutManager::ShortcutEntry> ShortcutManager::getGlobalShortcuts() { std::vector<ShortcutEntry> result; for (auto &[shortcut, entry] : *s_globalShortcuts) result.push_back(entry); return result; } std::vector<ShortcutManager::ShortcutEntry> ShortcutManager::getViewShortcuts(const View *view) { std::vector<ShortcutEntry> result; result.reserve(view->m_shortcuts.size()); for (auto &[shortcut, entry] : view->m_shortcuts) result.push_back(entry); return result; } static bool updateShortcutImpl(const Shortcut &oldShortcut, const Shortcut &newShortcut, std::map<Shortcut, ShortcutManager::ShortcutEntry> &shortcuts) { if (shortcuts.contains(oldShortcut)) { if (shortcuts.contains(newShortcut)) return false; shortcuts[newShortcut] = shortcuts[oldShortcut]; shortcuts[newShortcut].shortcut = newShortcut; shortcuts.erase(oldShortcut); } return true; } bool ShortcutManager::updateShortcut(const Shortcut &oldShortcut, const Shortcut &newShortcut, View *view) { if (oldShortcut == newShortcut) return true; bool result; if (view != nullptr) { result = updateShortcutImpl(oldShortcut + CurrentView, newShortcut + CurrentView , view->m_shortcuts); } else { result = updateShortcutImpl(oldShortcut, newShortcut, s_globalShortcuts); } if (result) { for (auto &[priority, menuItem] : ContentRegistry::Interface::impl::getMenuItems()) { if (menuItem.view == view && *menuItem.shortcut == oldShortcut) { *menuItem.shortcut = newShortcut; break; } } } return result; } }
4,995
C++
.cpp
111
36
158
0.653053
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
115
theme_manager.cpp
WerWolv_ImHex/lib/libimhex/source/api/theme_manager.cpp
#include <hex/api/theme_manager.hpp> #include <hex/api/event_manager.hpp> #include <hex/helpers/logger.hpp> #include <hex/helpers/utils.hpp> #include <hex/helpers/auto_reset.hpp> #include <nlohmann/json.hpp> namespace hex { namespace { AutoReset<std::map<std::string, nlohmann::json>> s_themes; AutoReset<std::map<std::string, ThemeManager::ThemeHandler>> s_themeHandlers; AutoReset<std::map<std::string, ThemeManager::StyleHandler>> s_styleHandlers; AutoReset<std::string> s_imageTheme; AutoReset<std::string> s_currTheme; std::recursive_mutex s_themeMutex; } void ThemeManager::reapplyCurrentTheme() { ThemeManager::changeTheme(s_currTheme); } void ThemeManager::addThemeHandler(const std::string &name, const ColorMap &colorMap, const std::function<ImColor(u32)> &getFunction, const std::function<void(u32, ImColor)> &setFunction) { std::unique_lock lock(s_themeMutex); (*s_themeHandlers)[name] = { colorMap, getFunction, setFunction }; } void ThemeManager::addStyleHandler(const std::string &name, const StyleMap &styleMap) { std::unique_lock lock(s_themeMutex); (*s_styleHandlers)[name] = { styleMap }; } void ThemeManager::addTheme(const std::string &content) { std::unique_lock lock(s_themeMutex); try { auto theme = nlohmann::json::parse(content); if (theme.contains("name") && theme.contains("colors")) { (*s_themes)[theme["name"].get<std::string>()] = theme; } else { hex::log::error("Invalid theme file"); } } catch (const nlohmann::json::parse_error &e) { hex::log::error("Invalid theme file: {}", e.what()); } } std::optional<ImColor> ThemeManager::parseColorString(const std::string &colorString) { if (colorString == "auto") return ImVec4(0, 0, 0, -1); if (colorString.length() != 9 || colorString[0] != '#') return std::nullopt; u32 color = 0; for (u32 i = 1; i < 9; i++) { color <<= 4; if (colorString[i] >= '0' && colorString[i] <= '9') color |= colorString[i] - '0'; else if (colorString[i] >= 'A' && colorString[i] <= 'F') color |= colorString[i] - 'A' + 10; else if (colorString[i] >= 'a' && colorString[i] <= 'f') color |= colorString[i] - 'a' + 10; else return std::nullopt; } if (color == 0x00000000) return ImVec4(0, 0, 0, -1); return ImColor(hex::changeEndianness(color, std::endian::big)); } nlohmann::json ThemeManager::exportCurrentTheme(const std::string &name) { nlohmann::json theme = { { "name", name }, { "image_theme", s_imageTheme }, { "colors", {} }, { "styles", {} }, { "base", s_currTheme } }; for (const auto &[type, handler] : *s_themeHandlers) { theme["colors"][type] = {}; for (const auto &[key, value] : handler.colorMap) { auto color = handler.getFunction(value); theme["colors"][type][key] = fmt::format("#{:08X}", hex::changeEndianness(u32(color), std::endian::big)); } } for (const auto &[type, handler] : *s_styleHandlers) { theme["styles"][type] = {}; for (const auto &[key, style] : handler.styleMap) { if (std::holds_alternative<float*>(style.value)) { theme["styles"][type][key] = *std::get<float*>(style.value); } else if (std::holds_alternative<ImVec2*>(style.value)) { theme["styles"][type][key] = { std::get<ImVec2*>(style.value)->x, std::get<ImVec2*>(style.value)->y }; } } } return theme; } void ThemeManager::changeTheme(std::string name) { std::unique_lock lock(s_themeMutex); if (!s_themes->contains(name)) { if (s_themes->empty()) { return; } else { const std::string &defaultTheme = s_themes->begin()->first; hex::log::error("Theme '{}' does not exist, using default theme '{}' instead!", name, defaultTheme); name = defaultTheme; } } const auto &theme = (*s_themes)[name]; if (theme.contains("base")) { if (theme["base"].is_string()) { if (theme["base"] != name) changeTheme(theme["base"].get<std::string>()); } else { hex::log::error("Theme '{}' has invalid base theme!", name); } } if (theme.contains("colors") && !s_themeHandlers->empty()) { for (const auto&[type, content] : theme["colors"].items()) { if (!s_themeHandlers->contains(type)) { log::warn("No theme handler found for '{}'", type); continue; } const auto &handler = (*s_themeHandlers)[type]; for (const auto &[key, value] : content.items()) { if (!handler.colorMap.contains(key)) { log::warn("No color found for '{}.{}'", type, key); continue; } auto color = parseColorString(value.get<std::string>()); if (!color.has_value()) { log::warn("Invalid color '{}' for '{}.{}'", value.get<std::string>(), type, key); continue; } (*s_themeHandlers)[type].setFunction((*s_themeHandlers)[type].colorMap.at(key), color.value()); } } } if (theme.contains("styles") && !s_styleHandlers->empty()) { for (const auto&[type, content] : theme["styles"].items()) { if (!s_styleHandlers->contains(type)) { log::warn("No style handler found for '{}'", type); continue; } auto &handler = (*s_styleHandlers)[type]; for (const auto &[key, value] : content.items()) { if (!handler.styleMap.contains(key)) continue; auto &style = handler.styleMap.at(key); const float scale = style.needsScaling ? 1_scaled : 1.0F; if (value.is_number_float()) { if (const auto newValue = std::get_if<float*>(&style.value); newValue != nullptr && *newValue != nullptr) **newValue = value.get<float>() * scale; else log::warn("Style variable '{}' was of type ImVec2 but a float was expected.", name); } else if (value.is_array() && value.size() == 2 && value[0].is_number_float() && value[1].is_number_float()) { if (const auto newValue = std::get_if<ImVec2*>(&style.value); newValue != nullptr && *newValue != nullptr) **newValue = ImVec2(value[0].get<float>() * scale, value[1].get<float>() * scale); else log::warn("Style variable '{}' was of type float but a ImVec2 was expected.", name); } else { hex::log::error("Theme '{}' has invalid style value for '{}.{}'!", name, type, key); } } } } if (theme.contains("image_theme")) { if (theme["image_theme"].is_string()) { s_imageTheme = theme["image_theme"].get<std::string>(); } else { hex::log::error("Theme '{}' has invalid image theme!", name); s_imageTheme = "dark"; } } else { s_imageTheme = "dark"; } s_currTheme = name; EventThemeChanged::post(); } const std::string &ThemeManager::getImageTheme() { return s_imageTheme; } std::vector<std::string> ThemeManager::getThemeNames() { std::vector<std::string> themeNames; for (const auto &[name, theme] : *s_themes) themeNames.push_back(name); return themeNames; } void ThemeManager::reset() { std::unique_lock lock(s_themeMutex); s_themes->clear(); s_styleHandlers->clear(); s_themeHandlers->clear(); s_imageTheme->clear(); s_currTheme->clear(); } const std::map<std::string, ThemeManager::ThemeHandler> &ThemeManager::getThemeHandlers() { return s_themeHandlers; } const std::map<std::string, ThemeManager::StyleHandler> &ThemeManager::getStyleHandlers() { return s_styleHandlers; } }
9,076
C++
.cpp
196
33.066327
193
0.511609
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
116
event_manager.cpp
WerWolv_ImHex/lib/libimhex/source/api/event_manager.cpp
#include <hex/api/event_manager.hpp> namespace hex { std::multimap<void *, EventManager::EventList::iterator>& EventManager::getTokenStore() { static std::multimap<void *, EventManager::EventList::iterator> tokenStore; return tokenStore; } EventManager::EventList& EventManager::getEvents() { static EventManager::EventList events; return events; } std::recursive_mutex& EventManager::getEventMutex() { static std::recursive_mutex mutex; return mutex; } }
536
C++
.cpp
15
29.4
93
0.688109
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
117
subcommands.cpp
WerWolv_ImHex/lib/libimhex/source/subcommands/subcommands.cpp
#include <numeric> #include <string_view> #include <ranges> #include "hex/subcommands/subcommands.hpp" #include <hex/api/event_manager.hpp> #include <hex/api/plugin_manager.hpp> #include <hex/api/imhex_api.hpp> #include <hex/helpers/logger.hpp> #include <hex/helpers/fmt.hpp> namespace hex::subcommands { std::optional<SubCommand> findSubCommand(const std::string &arg) { for (auto &plugin : PluginManager::getPlugins()) { for (auto &subCommand : plugin.getSubCommands()) { if (hex::format("--{}", subCommand.commandLong) == arg || hex::format("-{}", subCommand.commandShort) == arg) { return subCommand; } } } return std::nullopt; } void processArguments(const std::vector<std::string> &args) { // If no arguments, do not even try to process arguments // (important because this function will exit ImHex if an instance is already opened, // and we don't want that if no arguments were provided) if (args.empty()) return; std::vector<std::pair<SubCommand, std::vector<std::string>>> subCommands; auto argsIter = args.begin(); // Get subcommand associated with the first argument std::optional<SubCommand> currentSubCommand = findSubCommand(*argsIter); if (currentSubCommand) { argsIter += 1; // If it is a valid subcommand, remove it from the argument list } else { // If no (valid) subcommand was provided, the default one is --open currentSubCommand = findSubCommand("--open"); } // Arguments of the current subcommand std::vector<std::string> currentSubCommandArgs; // Compute all subcommands to run while (argsIter != args.end()) { const std::string &arg = *argsIter; if (arg == "--othercmd") { // Save command to run if (currentSubCommand) { subCommands.emplace_back(*currentSubCommand, currentSubCommandArgs); } currentSubCommand = std::nullopt; currentSubCommandArgs = { }; } else if (currentSubCommand) { // Add current argument to the current command currentSubCommandArgs.push_back(arg); } else { // Get next subcommand from current argument currentSubCommand = findSubCommand(arg); if (!currentSubCommand) { log::error("No subcommand named '{}' found", arg); exit(EXIT_FAILURE); } } argsIter += 1; } // Save last command to run if (currentSubCommand.has_value()) { subCommands.emplace_back(*currentSubCommand, currentSubCommandArgs); } // Run the subcommands for (auto &[subcommand, args] : subCommands) { subcommand.callback(args); } // Exit the process if it's not the main instance (the commands have been forwarded to another instance) if (!ImHexApi::System::isMainInstance()) { std::exit(0); } } void forwardSubCommand(const std::string &cmdName, const std::vector<std::string> &args) { log::debug("Forwarding subcommand {} (maybe to us)", cmdName); std::vector<u8> data; if (!args.empty()) { for (const auto &arg: args) { data.insert(data.end(), arg.begin(), arg.end()); data.push_back('\0'); } data.pop_back(); } SendMessageToMainInstance::post(hex::format("command/{}", cmdName), data); } void registerSubCommand(const std::string &cmdName, const ForwardCommandHandler &handler) { log::debug("Registered new forward command handler: {}", cmdName); ImHexApi::Messaging::registerHandler(hex::format("command/{}", cmdName), [handler](const std::vector<u8> &eventData){ std::string string(reinterpret_cast<const char *>(eventData.data()), eventData.size()); std::vector<std::string> args; for (const auto &argument : std::views::split(string, char(0x00))) { std::string arg(argument.data(), argument.size()); args.push_back(arg); } handler(args); }); } }
4,459
C++
.cpp
100
33.7
127
0.584853
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
138
plugin_disassembler.cpp
WerWolv_ImHex/plugins/disassembler/source/plugin_disassembler.cpp
#include <hex/plugin.hpp> #include <hex/api/content_registry.hpp> #include <hex/helpers/logger.hpp> #include <pl/api.hpp> #include <romfs/romfs.hpp> #include "content/views/view_disassembler.hpp" using namespace hex; using namespace hex::plugin::disasm; namespace hex::plugin::disasm { void drawDisassemblyVisualizer(pl::ptrn::Pattern &, bool, std::span<const pl::core::Token::Literal> arguments); } namespace { void registerViews() { ContentRegistry::Views::add<ViewDisassembler>(); } void registerPlVisualizers() { using ParamCount = pl::api::FunctionParameterCount; ContentRegistry::PatternLanguage::addVisualizer("disassembler", drawDisassemblyVisualizer, ParamCount::exactly(4)); } } IMHEX_PLUGIN_SETUP("Disassembler", "WerWolv", "Disassembler support") { 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(); registerPlVisualizers(); }
1,080
C++
.cpp
27
35.888889
123
0.725169
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
139
disassembler.cpp
WerWolv_ImHex/plugins/disassembler/source/content/pl_visualizers/disassembler.cpp
#include <hex/helpers/utils.hpp> #include <pl/pattern_language.hpp> #include <pl/patterns/pattern.hpp> #include <imgui.h> #include <capstone/capstone.h> #include <hex/ui/imgui_imhex_extensions.h> #include <hex/api/localization_manager.hpp> namespace hex::plugin::disasm { void drawDisassemblyVisualizer(pl::ptrn::Pattern &, bool shouldReset, std::span<const pl::core::Token::Literal> arguments) { struct Disassembly { u64 address; std::vector<u8> bytes; std::string instruction; }; static std::vector<Disassembly> disassembly; if (shouldReset) { auto pattern = arguments[0].toPattern(); auto baseAddress = arguments[1].toUnsigned(); auto architecture = arguments[2].toUnsigned(); auto mode = arguments[3].toUnsigned(); disassembly.clear(); csh capstone; if (cs_open(static_cast<cs_arch>(architecture), static_cast<cs_mode>(mode), &capstone) == CS_ERR_OK) { cs_option(capstone, CS_OPT_SKIPDATA, CS_OPT_ON); auto data = pattern->getBytes(); cs_insn *instructions = nullptr; size_t instructionCount = cs_disasm(capstone, data.data(), data.size(), baseAddress, 0, &instructions); for (size_t i = 0; i < instructionCount; i++) { disassembly.push_back({ instructions[i].address, { instructions[i].bytes, instructions[i].bytes + instructions[i].size }, hex::format("{} {}", instructions[i].mnemonic, instructions[i].op_str) }); } cs_free(instructions, instructionCount); cs_close(&capstone); } } if (ImGui::BeginTable("##disassembly", 3, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_ScrollY, scaled(ImVec2(0, 300)))) { ImGui::TableSetupScrollFreeze(0, 1); ImGui::TableSetupColumn("hex.ui.common.address"_lang); ImGui::TableSetupColumn("hex.ui.common.bytes"_lang); ImGui::TableSetupColumn("hex.ui.common.instruction"_lang); ImGui::TableHeadersRow(); for (auto &entry : disassembly) { ImGui::TableNextRow(); ImGui::TableNextColumn(); ImGuiExt::TextFormatted("0x{0:08X}", entry.address); ImGui::TableNextColumn(); std::string bytes; for (auto byte : entry.bytes) bytes += hex::format("{0:02X} ", byte); ImGui::TextUnformatted(bytes.c_str()); ImGui::TableNextColumn(); ImGui::TextUnformatted(entry.instruction.c_str()); } ImGui::EndTable(); } } }
2,876
C++
.cpp
56
39.321429
242
0.59444
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
140
view_disassembler.cpp
WerWolv_ImHex/plugins/disassembler/source/content/views/view_disassembler.cpp
#include "content/views/view_disassembler.hpp" #include <hex/providers/provider.hpp> #include <hex/helpers/fmt.hpp> #include <fonts/codicons_font.h> #include <cstring> using namespace std::literals::string_literals; namespace hex::plugin::disasm { ViewDisassembler::ViewDisassembler() : View::Window("hex.disassembler.view.disassembler.name", ICON_VS_FILE_CODE) { EventProviderDeleted::subscribe(this, [this](const auto*) { m_disassembly.clear(); }); } ViewDisassembler::~ViewDisassembler() { EventDataChanged::unsubscribe(this); EventRegionSelected::unsubscribe(this); EventProviderDeleted::unsubscribe(this); } void ViewDisassembler::disassemble() { m_disassembly.clear(); m_disassemblerTask = TaskManager::createTask("hex.disassembler.view.disassembler.disassembling"_lang, m_codeRegion.getSize(), [this](auto &task) { csh capstoneHandle; cs_insn *instructions = nullptr; cs_mode mode = m_mode; // Create a capstone disassembler instance if (cs_open(Disassembler::toCapstoneArchitecture(m_architecture), mode, &capstoneHandle) == CS_ERR_OK) { // Tell capstone to skip data bytes cs_option(capstoneHandle, CS_OPT_SKIPDATA, CS_OPT_ON); auto provider = ImHexApi::Provider::get(); std::vector<u8> buffer(2048, 0x00); size_t size = m_codeRegion.getSize(); // Read the data in chunks and disassemble it for (u64 address = 0; address < size; address += 2048) { task.update(address); // Read a chunk of data size_t bufferSize = std::min(u64(2048), (size - address)); provider->read(m_codeRegion.getStartAddress() + address, buffer.data(), bufferSize); // Ask capstone to disassemble the data size_t instructionCount = cs_disasm(capstoneHandle, buffer.data(), bufferSize, m_baseAddress + address, 0, &instructions); if (instructionCount == 0) break; // Reserve enough space for the disassembly m_disassembly.reserve(m_disassembly.size() + instructionCount); // Convert the capstone instructions to our disassembly format u64 usedBytes = 0; for (u32 i = 0; i < instructionCount; i++) { const auto &instr = instructions[i]; Disassembly disassembly = { }; disassembly.address = instr.address; disassembly.offset = m_codeRegion.getStartAddress() + address + usedBytes; disassembly.size = instr.size; disassembly.mnemonic = instr.mnemonic; disassembly.operators = instr.op_str; for (u16 j = 0; j < instr.size; j++) disassembly.bytes += hex::format("{0:02X} ", instr.bytes[j]); disassembly.bytes.pop_back(); m_disassembly.push_back(disassembly); usedBytes += instr.size; } // If capstone couldn't disassemble all bytes in the buffer, we might have cut off an instruction // Adjust the address,so it's being disassembled when we read the next chunk if (instructionCount < bufferSize) address -= (bufferSize - usedBytes); // Clean up the capstone instructions cs_free(instructions, instructionCount); } cs_close(&capstoneHandle); } }); } void ViewDisassembler::drawContent() { auto provider = ImHexApi::Provider::get(); if (ImHexApi::Provider::isValid() && provider->isReadable()) { ImGuiExt::Header("hex.disassembler.view.disassembler.position"_lang, true); // Draw base address input ImGuiExt::InputHexadecimal("hex.disassembler.view.disassembler.base"_lang, &m_baseAddress, ImGuiInputTextFlags_CharsHexadecimal); // Draw region selection picker ui::regionSelectionPicker(&m_codeRegion, provider, &m_range); // Draw settings { ImGuiExt::Header("hex.ui.common.settings"_lang); // Draw architecture selector if (ImGui::Combo("hex.disassembler.view.disassembler.arch"_lang, reinterpret_cast<int *>(&m_architecture), Disassembler::ArchitectureNames.data(), Disassembler::getArchitectureSupportedCount())) m_mode = cs_mode(0); // Draw sub-settings for each architecture if (ImGuiExt::BeginBox()) { // Draw endian radio buttons. This setting is available for all architectures static int littleEndian = true; ImGui::RadioButton("hex.ui.common.little_endian"_lang, &littleEndian, true); ImGui::SameLine(); ImGui::RadioButton("hex.ui.common.big_endian"_lang, &littleEndian, false); ImGui::NewLine(); // Draw architecture specific settings switch (m_architecture) { case Architecture::ARM: { static int mode = CS_MODE_ARM; ImGui::RadioButton("hex.disassembler.view.disassembler.arm.arm"_lang, &mode, CS_MODE_ARM); ImGui::SameLine(); ImGui::RadioButton("hex.disassembler.view.disassembler.arm.thumb"_lang, &mode, CS_MODE_THUMB); static int extraMode = 0; ImGui::RadioButton("hex.disassembler.view.disassembler.arm.default"_lang, &extraMode, 0); ImGui::SameLine(); ImGui::RadioButton("hex.disassembler.view.disassembler.arm.cortex_m"_lang, &extraMode, CS_MODE_MCLASS); ImGui::SameLine(); ImGui::RadioButton("hex.disassembler.view.disassembler.arm.armv8"_lang, &extraMode, CS_MODE_V8); m_mode = cs_mode(mode | extraMode); } break; case Architecture::MIPS: { static int mode = CS_MODE_MIPS32; ImGui::RadioButton("hex.disassembler.view.disassembler.mips.mips32"_lang, &mode, CS_MODE_MIPS32); ImGui::SameLine(); ImGui::RadioButton("hex.disassembler.view.disassembler.mips.mips64"_lang, &mode, CS_MODE_MIPS64); ImGui::SameLine(); ImGui::RadioButton("hex.disassembler.view.disassembler.mips.mips32R6"_lang, &mode, CS_MODE_MIPS32R6); ImGui::RadioButton("hex.disassembler.view.disassembler.mips.mips2"_lang, &mode, CS_MODE_MIPS2); ImGui::SameLine(); ImGui::RadioButton("hex.disassembler.view.disassembler.mips.mips3"_lang, &mode, CS_MODE_MIPS3); static bool microMode; ImGui::Checkbox("hex.disassembler.view.disassembler.mips.micro"_lang, &microMode); m_mode = cs_mode(mode | (microMode ? CS_MODE_MICRO : cs_mode(0))); } break; case Architecture::X86: { static int mode = CS_MODE_32; ImGui::RadioButton("hex.disassembler.view.disassembler.16bit"_lang, &mode, CS_MODE_16); ImGui::SameLine(); ImGui::RadioButton("hex.disassembler.view.disassembler.32bit"_lang, &mode, CS_MODE_32); ImGui::SameLine(); ImGui::RadioButton("hex.disassembler.view.disassembler.64bit"_lang, &mode, CS_MODE_64); m_mode = cs_mode(mode); } break; case Architecture::PPC: { static int mode = CS_MODE_32; ImGui::RadioButton("hex.disassembler.view.disassembler.32bit"_lang, &mode, CS_MODE_32); ImGui::SameLine(); ImGui::RadioButton("hex.disassembler.view.disassembler.64bit"_lang, &mode, CS_MODE_64); static bool qpx = false; ImGui::Checkbox("hex.disassembler.view.disassembler.ppc.qpx"_lang, &qpx); #if CS_API_MAJOR >= 5 static bool spe = false; ImGui::Checkbox("hex.disassembler.view.disassembler.ppc.spe"_lang, &spe); static bool booke = false; ImGui::Checkbox("hex.disassembler.view.disassembler.ppc.booke"_lang, &booke); m_mode = cs_mode(mode | (qpx ? CS_MODE_QPX : cs_mode(0)) | (spe ? CS_MODE_SPE : cs_mode(0)) | (booke ? CS_MODE_BOOKE : cs_mode(0))); #else m_mode = cs_mode(mode | (qpx ? CS_MODE_QPX : cs_mode(0))); #endif } break; case Architecture::SPARC: { static bool v9Mode = false; ImGui::Checkbox("hex.disassembler.view.disassembler.sparc.v9"_lang, &v9Mode); m_mode = cs_mode(v9Mode ? CS_MODE_V9 : cs_mode(0)); } break; #if CS_API_MAJOR >= 5 case Architecture::RISCV: { static int mode = CS_MODE_RISCV32; ImGui::RadioButton("hex.disassembler.view.disassembler.32bit"_lang, &mode, CS_MODE_RISCV32); ImGui::SameLine(); ImGui::RadioButton("hex.disassembler.view.disassembler.64bit"_lang, &mode, CS_MODE_RISCV64); static bool compressed = false; ImGui::Checkbox("hex.disassembler.view.disassembler.riscv.compressed"_lang, &compressed); m_mode = cs_mode(mode | (compressed ? CS_MODE_RISCVC : cs_mode(0))); } break; #endif case Architecture::M68K: { static int selectedMode = 0; std::pair<const char *, cs_mode> modes[] = { {"hex.disassembler.view.disassembler.m68k.000"_lang, CS_MODE_M68K_000}, { "hex.disassembler.view.disassembler.m68k.010"_lang, CS_MODE_M68K_010}, { "hex.disassembler.view.disassembler.m68k.020"_lang, CS_MODE_M68K_020}, { "hex.disassembler.view.disassembler.m68k.030"_lang, CS_MODE_M68K_030}, { "hex.disassembler.view.disassembler.m68k.040"_lang, CS_MODE_M68K_040}, { "hex.disassembler.view.disassembler.m68k.060"_lang, CS_MODE_M68K_060}, }; if (ImGui::BeginCombo("hex.disassembler.view.disassembler.settings.mode"_lang, modes[selectedMode].first)) { for (u32 i = 0; i < IM_ARRAYSIZE(modes); i++) { if (ImGui::Selectable(modes[i].first)) selectedMode = i; } ImGui::EndCombo(); } m_mode = cs_mode(modes[selectedMode].second); } break; case Architecture::M680X: { static int selectedMode = 0; std::pair<const char *, cs_mode> modes[] = { {"hex.disassembler.view.disassembler.m680x.6301"_lang, CS_MODE_M680X_6301 }, { "hex.disassembler.view.disassembler.m680x.6309"_lang, CS_MODE_M680X_6309 }, { "hex.disassembler.view.disassembler.m680x.6800"_lang, CS_MODE_M680X_6800 }, { "hex.disassembler.view.disassembler.m680x.6801"_lang, CS_MODE_M680X_6801 }, { "hex.disassembler.view.disassembler.m680x.6805"_lang, CS_MODE_M680X_6805 }, { "hex.disassembler.view.disassembler.m680x.6808"_lang, CS_MODE_M680X_6808 }, { "hex.disassembler.view.disassembler.m680x.6809"_lang, CS_MODE_M680X_6809 }, { "hex.disassembler.view.disassembler.m680x.6811"_lang, CS_MODE_M680X_6811 }, { "hex.disassembler.view.disassembler.m680x.cpu12"_lang, CS_MODE_M680X_CPU12}, { "hex.disassembler.view.disassembler.m680x.hcs08"_lang, CS_MODE_M680X_HCS08}, }; if (ImGui::BeginCombo("hex.disassembler.view.disassembler.settings.mode"_lang, modes[selectedMode].first)) { for (u32 i = 0; i < IM_ARRAYSIZE(modes); i++) { if (ImGui::Selectable(modes[i].first)) selectedMode = i; } ImGui::EndCombo(); } m_mode = cs_mode(modes[selectedMode].second); } break; #if CS_API_MAJOR >= 5 case Architecture::MOS65XX: { static int selectedMode = 0; std::pair<const char *, cs_mode> modes[] = { {"hex.disassembler.view.disassembler.mos65xx.6502"_lang, CS_MODE_MOS65XX_6502 }, { "hex.disassembler.view.disassembler.mos65xx.65c02"_lang, CS_MODE_MOS65XX_65C02 }, { "hex.disassembler.view.disassembler.mos65xx.w65c02"_lang, CS_MODE_MOS65XX_W65C02 }, { "hex.disassembler.view.disassembler.mos65xx.65816"_lang, CS_MODE_MOS65XX_65816 }, { "hex.disassembler.view.disassembler.mos65xx.65816_long_m"_lang, CS_MODE_MOS65XX_65816_LONG_M }, { "hex.disassembler.view.disassembler.mos65xx.65816_long_x"_lang, CS_MODE_MOS65XX_65816_LONG_X }, { "hex.disassembler.view.disassembler.mos65xx.65816_long_mx"_lang, CS_MODE_MOS65XX_65816_LONG_MX}, }; if (ImGui::BeginCombo("hex.disassembler.view.disassembler.settings.mode"_lang, modes[selectedMode].first)) { for (u32 i = 0; i < IM_ARRAYSIZE(modes); i++) { if (ImGui::Selectable(modes[i].first)) selectedMode = i; } ImGui::EndCombo(); } m_mode = cs_mode(modes[selectedMode].second); } break; #endif #if CS_API_MAJOR >= 5 case Architecture::BPF: { static int mode = CS_MODE_BPF_CLASSIC; ImGui::RadioButton("hex.disassembler.view.disassembler.bpf.classic"_lang, &mode, CS_MODE_BPF_CLASSIC); ImGui::SameLine(); ImGui::RadioButton("hex.disassembler.view.disassembler.bpf.extended"_lang, &mode, CS_MODE_BPF_EXTENDED); m_mode = cs_mode(mode); } break; case Architecture::SH: { static u32 selectionMode = 0; static bool fpu = false; static bool dsp = false; std::pair<const char*, cs_mode> modes[] = { { "hex.disassembler.view.disassembler.sh.sh2"_lang, CS_MODE_SH2 }, { "hex.disassembler.view.disassembler.sh.sh2a"_lang, CS_MODE_SH2A }, { "hex.disassembler.view.disassembler.sh.sh3"_lang, CS_MODE_SH3 }, { "hex.disassembler.view.disassembler.sh.sh4"_lang, CS_MODE_SH4 }, { "hex.disassembler.view.disassembler.sh.sh4a"_lang, CS_MODE_SH4A }, }; if (ImGui::BeginCombo("hex.disassembler.view.disassembler.settings.mode"_lang, modes[selectionMode].first)) { for (u32 i = 0; i < IM_ARRAYSIZE(modes); i++) { if (ImGui::Selectable(modes[i].first)) selectionMode = i; } ImGui::EndCombo(); } ImGui::Checkbox("hex.disassembler.view.disassembler.sh.fpu"_lang, &fpu); ImGui::SameLine(); ImGui::Checkbox("hex.disassembler.view.disassembler.sh.dsp"_lang, &dsp); m_mode = cs_mode(modes[selectionMode].second | (fpu ? CS_MODE_SHFPU : cs_mode(0)) | (dsp ? CS_MODE_SHDSP : cs_mode(0))); } break; case Architecture::TRICORE: { static u32 selectionMode = 0; std::pair<const char*, cs_mode> modes[] = { { "hex.disassembler.view.disassembler.tricore.110"_lang, CS_MODE_TRICORE_110 }, { "hex.disassembler.view.disassembler.tricore.120"_lang, CS_MODE_TRICORE_120 }, { "hex.disassembler.view.disassembler.tricore.130"_lang, CS_MODE_TRICORE_130 }, { "hex.disassembler.view.disassembler.tricore.131"_lang, CS_MODE_TRICORE_131 }, { "hex.disassembler.view.disassembler.tricore.160"_lang, CS_MODE_TRICORE_160 }, { "hex.disassembler.view.disassembler.tricore.161"_lang, CS_MODE_TRICORE_161 }, { "hex.disassembler.view.disassembler.tricore.162"_lang, CS_MODE_TRICORE_162 }, }; if (ImGui::BeginCombo("hex.disassembler.view.disassembler.settings.mode"_lang, modes[selectionMode].first)) { for (u32 i = 0; i < IM_ARRAYSIZE(modes); i++) { if (ImGui::Selectable(modes[i].first)) selectionMode = i; } ImGui::EndCombo(); } m_mode = cs_mode(modes[selectionMode].second); } break; case Architecture::WASM: #endif case Architecture::EVM: case Architecture::TMS320C64X: case Architecture::ARM64: case Architecture::SYSZ: case Architecture::XCORE: m_mode = cs_mode(0); break; } if (littleEndian) { m_mode = cs_mode(u32(m_mode) | CS_MODE_LITTLE_ENDIAN); } else { m_mode = cs_mode(u32(m_mode) | CS_MODE_BIG_ENDIAN); } ImGuiExt::EndBox(); } } // Draw disassemble button ImGui::BeginDisabled(m_disassemblerTask.isRunning()); { if (ImGui::Button("hex.disassembler.view.disassembler.disassemble"_lang)) this->disassemble(); } ImGui::EndDisabled(); // Draw a spinner if the disassembler is running if (m_disassemblerTask.isRunning()) { ImGui::SameLine(); ImGuiExt::TextSpinner("hex.disassembler.view.disassembler.disassembling"_lang); } ImGui::NewLine(); ImGui::TextUnformatted("hex.disassembler.view.disassembler.disassembly.title"_lang); ImGui::Separator(); // Draw disassembly table if (ImGui::BeginTable("##disassembly", 4, ImGuiTableFlags_ScrollY | ImGuiTableFlags_Borders | ImGuiTableFlags_Resizable | ImGuiTableFlags_RowBg | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable)) { ImGui::TableSetupScrollFreeze(0, 1); ImGui::TableSetupColumn("hex.disassembler.view.disassembler.disassembly.address"_lang); ImGui::TableSetupColumn("hex.disassembler.view.disassembler.disassembly.offset"_lang); ImGui::TableSetupColumn("hex.disassembler.view.disassembler.disassembly.bytes"_lang); ImGui::TableSetupColumn("hex.disassembler.view.disassembler.disassembly.title"_lang); if (!m_disassemblerTask.isRunning()) { ImGuiListClipper clipper; clipper.Begin(m_disassembly.size()); ImGui::TableHeadersRow(); while (clipper.Step()) { for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) { const auto &instruction = m_disassembly[i]; ImGui::TableNextRow(); ImGui::TableNextColumn(); // Draw a selectable label for the address ImGui::PushID(i); if (ImGui::Selectable("##DisassemblyLine", false, ImGuiSelectableFlags_SpanAllColumns)) { ImHexApi::HexEditor::setSelection(instruction.offset, instruction.size); } ImGui::PopID(); // Draw instruction address ImGui::SameLine(); ImGuiExt::TextFormatted("0x{0:X}", instruction.address); // Draw instruction offset ImGui::TableNextColumn(); ImGuiExt::TextFormatted("0x{0:X}", instruction.offset); // Draw instruction bytes ImGui::TableNextColumn(); ImGui::TextUnformatted(instruction.bytes.c_str()); // Draw instruction mnemonic and operands ImGui::TableNextColumn(); ImGuiExt::TextFormattedColored(ImColor(0xFFD69C56), "{}", instruction.mnemonic); ImGui::SameLine(); ImGui::TextUnformatted(instruction.operators.c_str()); } } clipper.End(); } ImGui::EndTable(); } } } }
25,298
C++
.cpp
379
39.891821
216
0.462821
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
141
ui.cpp
WerWolv_ImHex/plugins/script_loader/support/c/source/script_api/v1/ui.cpp
#include <script_api.hpp> #include <hex/api/content_registry.hpp> #include <hex/api/imhex_api.hpp> #include <hex/api/event_manager.hpp> #include <hex/api/localization_manager.hpp> #include <hex/ui/popup.hpp> #include <hex/helpers/utils.hpp> #include <hex/ui/view.hpp> #include <popups/popup_notification.hpp> #include <toasts/toast_notification.hpp> using namespace hex; #define VERSION V1 static std::optional<std::string> s_inputTextBoxResult; static std::optional<bool> s_yesNoQuestionBoxResult; class PopupYesNo : public Popup<PopupYesNo> { public: PopupYesNo(std::string title, std::string message) : hex::Popup<PopupYesNo>(std::move(title), false), m_message(std::move(message)) { } void drawContent() override { ImGuiExt::TextFormattedWrapped("{}", m_message.c_str()); ImGui::NewLine(); ImGui::Separator(); auto width = ImGui::GetWindowWidth(); ImGui::SetCursorPosX(width / 9); if (ImGui::Button("hex.ui.common.yes"_lang, ImVec2(width / 3, 0))) { s_yesNoQuestionBoxResult = true; this->close(); } ImGui::SameLine(); ImGui::SetCursorPosX(width / 9 * 5); if (ImGui::Button("hex.ui.common.no"_lang, ImVec2(width / 3, 0)) || ImGui::IsKeyPressed(ImGuiKey_Escape)) { s_yesNoQuestionBoxResult = false; this->close(); } ImGui::SetWindowPos((ImHexApi::System::getMainWindowSize() - ImGui::GetWindowSize()) / 2, ImGuiCond_Appearing); } [[nodiscard]] ImGuiWindowFlags getFlags() const override { return ImGuiWindowFlags_AlwaysAutoResize; } [[nodiscard]] ImVec2 getMinSize() const override { return scaled({ 400, 100 }); } [[nodiscard]] ImVec2 getMaxSize() const override { return scaled({ 600, 300 }); } private: std::string m_message; }; class PopupInputText : public Popup<PopupInputText> { public: PopupInputText(std::string title, std::string message, size_t maxSize) : hex::Popup<PopupInputText>(std::move(title), false), m_message(std::move(message)), m_maxSize(maxSize) { } void drawContent() override { ImGuiExt::TextFormattedWrapped("{}", m_message.c_str()); ImGui::NewLine(); ImGui::SetItemDefaultFocus(); ImGui::SetNextItemWidth(-1); bool submitted = ImGui::InputText("##input", m_input, ImGuiInputTextFlags_EnterReturnsTrue); if (m_input.size() > m_maxSize) m_input.resize(m_maxSize); ImGui::NewLine(); ImGui::Separator(); auto width = ImGui::GetWindowWidth(); ImGui::SetCursorPosX(width / 9); ImGui::BeginDisabled(m_input.empty()); if (ImGui::Button("hex.ui.common.okay"_lang, ImVec2(width / 3, 0)) || submitted) { s_inputTextBoxResult = m_input; this->close(); } ImGui::EndDisabled(); ImGui::SameLine(); ImGui::SetCursorPosX(width / 9 * 5); if (ImGui::Button("hex.ui.common.cancel"_lang, ImVec2(width / 3, 0)) || ImGui::IsKeyPressed(ImGuiKey_Escape)) { s_inputTextBoxResult = ""; this->close(); } ImGui::SetWindowPos((ImHexApi::System::getMainWindowSize() - ImGui::GetWindowSize()) / 2, ImGuiCond_Appearing); } [[nodiscard]] ImGuiWindowFlags getFlags() const override { return ImGuiWindowFlags_AlwaysAutoResize; } [[nodiscard]] ImVec2 getMinSize() const override { return scaled({ 400, 100 }); } [[nodiscard]] ImVec2 getMaxSize() const override { return scaled({ 600, 300 }); } private: std::string m_message; std::string m_input; size_t m_maxSize; }; SCRIPT_API(void showMessageBox, const char *message) { ui::PopupInfo::open(message); } SCRIPT_API(void showInputTextBox, const char *title, const char *message, char *buffer, u32 bufferSize) { PopupInputText::open(std::string(title), std::string(message), bufferSize - 1); while (!s_inputTextBoxResult.has_value()) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); } auto &value = s_inputTextBoxResult.value(); std::memcpy(buffer, value.c_str(), std::min<size_t>(value.size() + 1, bufferSize)); s_inputTextBoxResult.reset(); } SCRIPT_API(void showYesNoQuestionBox, const char *title, const char *message, bool *result) { PopupYesNo::open(std::string(title), std::string(message)); while (!s_yesNoQuestionBoxResult.has_value()) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); } *result = s_yesNoQuestionBoxResult.value(); s_yesNoQuestionBoxResult.reset(); } SCRIPT_API(void showToast, const char *message, u32 type) { switch (type) { case 0: ui::ToastInfo::open(message); break; case 1: ui::ToastWarning::open(message); break; case 2: ui::ToastError::open(message); break; default: break; } } SCRIPT_API(void* getImGuiContext) { return ImGui::GetCurrentContext(); } class ScriptView : public View::Window { public: using DrawFunction = void(*)(); ScriptView(const char *icon, const char *name, DrawFunction function) : View::Window(UnlocalizedString(name), icon), m_drawFunction(function) { } void drawContent() override { m_drawFunction(); } private: DrawFunction m_drawFunction; }; SCRIPT_API(void registerView, const char *icon, const char *name, void *drawFunction) { ContentRegistry::Views::add<ScriptView>(icon, name, ScriptView::DrawFunction(drawFunction)); } SCRIPT_API(void addMenuItem, const char *icon, const char *menuName, const char *itemName, void *function) { using MenuFunction = void(*)(); ContentRegistry::Interface::addMenuItem({ menuName, itemName }, icon, 9999, Shortcut::None, reinterpret_cast<MenuFunction>(function)); }
5,947
C++
.cpp
149
33.456376
149
0.655095
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
142
logger.cpp
WerWolv_ImHex/plugins/script_loader/support/c/source/script_api/v1/logger.cpp
#include <script_api.hpp> #include <hex/api/imhex_api.hpp> #include <hex/helpers/logger.hpp> #define VERSION V1 SCRIPT_API(void logPrint, const char *message) { hex::log::print("{}", message); } SCRIPT_API(void logPrintln, const char *message) { hex::log::println("{}", message); } SCRIPT_API(void logDebug, const char *message) { hex::log::debug("{}", message); } SCRIPT_API(void logInfo, const char *message) { hex::log::info("{}", message); } SCRIPT_API(void logWarn, const char *message) { hex::log::warn("{}", message); } SCRIPT_API(void logError, const char *message) { hex::log::error("{}", message); } SCRIPT_API(void logFatal, const char *message) { hex::log::fatal("{}", message); }
729
C++
.cpp
25
26.72
50
0.673851
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
143
mem.cpp
WerWolv_ImHex/plugins/script_loader/support/c/source/script_api/v1/mem.cpp
#include <script_api.hpp> #include <hex/api/content_registry.hpp> #include <hex/api/imhex_api.hpp> #include <hex/providers/provider.hpp> #define VERSION V1 SCRIPT_API(void readMemory, u64 address, size_t size, void *buffer) { auto provider = hex::ImHexApi::Provider::get(); if (provider == nullptr) { return; } provider->read(address, buffer, size); } SCRIPT_API(void writeMemory, u64 address, size_t size, const void *buffer) { auto provider = hex::ImHexApi::Provider::get(); if (provider == nullptr) { return; } provider->write(address, buffer, size); } SCRIPT_API(u64 getBaseAddress) { return hex::ImHexApi::Provider::get()->getBaseAddress(); } SCRIPT_API(u64 getDataSize) { return hex::ImHexApi::Provider::get()->getSize(); } SCRIPT_API(bool getSelection, u64 *start, u64 *end) { if (start == nullptr || end == nullptr) return false; if (!hex::ImHexApi::Provider::isValid()) return false; if (!hex::ImHexApi::HexEditor::isSelectionValid()) return false; auto selection = hex::ImHexApi::HexEditor::getSelection(); *start = selection->getStartAddress(); *end = selection->getEndAddress(); return true; } class ScriptDataProvider : public hex::prv::Provider { public: using ReadFunction = void(*)(u64, void*, u64); using WriteFunction = void(*)(u64, const void*, u64); using GetSizeFunction = u64(*)(); using GetNameFunction = std::string(*)(); bool open() override { return true; } void close() override { } [[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 true; } [[nodiscard]] bool isDumpable() const override { return true; } void readRaw(u64 offset, void *buffer, size_t size) override { m_readFunction(offset, buffer, size); } void writeRaw(u64 offset, const void *buffer, size_t size) override { m_writeFunction(offset, const_cast<void*>(buffer), size); } void setFunctions(ReadFunction readFunc, WriteFunction writeFunc, GetSizeFunction getSizeFunc) { m_readFunction = readFunc; m_writeFunction = writeFunc; m_getSizeFunction = getSizeFunc; } [[nodiscard]] u64 getActualSize() const override { return m_getSizeFunction(); } void setTypeName(std::string typeName) { m_typeName = std::move(typeName);} void setName(std::string name) { m_name = std::move(name);} [[nodiscard]] std::string getTypeName() const override { return m_typeName; } [[nodiscard]] std::string getName() const override { return m_name; } private: ReadFunction m_readFunction = nullptr; WriteFunction m_writeFunction = nullptr; GetSizeFunction m_getSizeFunction = nullptr; std::string m_typeName, m_name; }; SCRIPT_API(void registerProvider, const char *typeName, const char *name, ScriptDataProvider::ReadFunction readFunc, ScriptDataProvider::WriteFunction writeFunc, ScriptDataProvider::GetSizeFunction getSizeFunc) { auto typeNameString = std::string(typeName); auto nameString = std::string(name); hex::ContentRegistry::Provider::impl::add(typeNameString, [typeNameString, nameString, readFunc, writeFunc, getSizeFunc] -> std::unique_ptr<hex::prv::Provider> { auto provider = std::make_unique<ScriptDataProvider>(); provider->setTypeName(typeNameString); provider->setName(nameString); provider->setFunctions(readFunc, writeFunc, getSizeFunc); return provider; }); hex::ContentRegistry::Provider::impl::addProviderName(typeNameString); }
3,838
C++
.cpp
85
40.117647
212
0.698068
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
144
bookmarks.cpp
WerWolv_ImHex/plugins/script_loader/support/c/source/script_api/v1/bookmarks.cpp
#include <script_api.hpp> #include <hex/api/imhex_api.hpp> #define VERSION V1 SCRIPT_API(void createBookmark, u64 address, u64 size, u32 color, const char *name, const char *description) { hex::ImHexApi::Bookmarks::add(address, size, name, description, color); }
269
C++
.cpp
6
42.833333
110
0.754789
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
145
plugin_script_loader.cpp
WerWolv_ImHex/plugins/script_loader/source/plugin_script_loader.cpp
#include <fonts/codicons_font.h> #include <hex/plugin.hpp> #include <hex/api/content_registry.hpp> #include <hex/api/task_manager.hpp> #include <hex/api/localization_manager.hpp> #include <hex/helpers/logger.hpp> #include <hex/ui/imgui_imhex_extensions.h> #include <loaders/dotnet/dotnet_loader.hpp> #include <romfs/romfs.hpp> #include <nlohmann/json.hpp> using namespace hex; using namespace hex::script::loader; using ScriptLoaders = std::tuple< #if defined(IMHEX_DOTNET_SCRIPT_SUPPORT) DotNetLoader #endif >; namespace { ScriptLoaders s_loaders; void loadScript(std::vector<const Script*> &scripts, auto &loader) { loader.loadAll(); for (auto &script : std::as_const(loader).getScripts()) scripts.emplace_back(&script); } std::vector<const Script*> loadAllScripts() { std::vector<const Script*> scripts; try { std::apply([&scripts](auto&&... args) { (loadScript(scripts, args), ...); }, s_loaders); } catch (const std::exception &e) { log::error("Error when loading scripts: {}", e.what()); } { std::vector<hex::Feature> features; for (const auto &script : scripts) { if (!script->background) continue; features.emplace_back(script->name, true); } IMHEX_PLUGIN_FEATURES = features; } return scripts; } void initializeLoader(u32 &count, auto &loader) { try { if (loader.initialize()) count += 1; } catch (const std::exception &e) { log::error("Error when initializing script loader: {}", e.what()); } } bool initializeAllLoaders() { u32 count = 0; std::apply([&count](auto&&... args) { try { (initializeLoader(count, args), ...); } catch (const std::exception &e) { log::error("Error when initializing script loaders: {}", e.what()); } }, s_loaders); return count > 0; } void addScriptsMenu() { static std::vector<const Script*> scripts; static TaskHolder runnerTask, updaterTask; hex::ContentRegistry::Interface::addMenuItemSubMenu({ "hex.builtin.menu.extras" }, 5000, [] { static bool menuJustOpened = true; if (ImGui::BeginMenuEx("hex.script_loader.menu.run_script"_lang, ICON_VS_LIBRARY)) { if (menuJustOpened) { menuJustOpened = false; if (!updaterTask.isRunning()) { updaterTask = TaskManager::createBackgroundTask("hex.script_loader.task.updating"_lang, [] (auto&) { scripts = loadAllScripts(); }); } } if (updaterTask.isRunning()) { ImGuiExt::TextSpinner("hex.script_loader.menu.loading"_lang); } else if (scripts.empty()) { ImGui::TextUnformatted("hex.script_loader.menu.no_scripts"_lang); } for (const auto &script : scripts) { const auto &[name, path, background, entryPoint, loader] = *script; if (background) continue; if (ImGui::MenuItem(name.c_str(), loader->getTypeName().c_str())) { runnerTask = TaskManager::createTask("hex.script_loader.task.running"_lang, TaskManager::NoProgress, [entryPoint](auto&) { entryPoint(); }); } } ImGui::EndMenu(); } else { menuJustOpened = true; } }, [] { return !runnerTask.isRunning(); }); updaterTask = TaskManager::createBackgroundTask("hex.script_loader.task.updating"_lang, [] (auto&) { scripts = loadAllScripts(); }); } } IMHEX_PLUGIN_SETUP("Script Loader", "WerWolv", "Script Loader plugin") { hex::log::debug("Using romfs: '{}'", romfs::name()); for (auto &path : romfs::list("lang")) hex::ContentRegistry::Language::addLocalization(nlohmann::json::parse(romfs::get(path).string())); if (initializeAllLoaders()) { addScriptsMenu(); } }
4,444
C++
.cpp
112
28.428571
146
0.545539
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
146
dotnet_loader.cpp
WerWolv_ImHex/plugins/script_loader/source/loaders/dotnet/dotnet_loader.cpp
#include <loaders/dotnet/dotnet_loader.hpp> #include <stdexcept> #if defined(OS_WINDOWS) #define STRING(str) L##str #else #define STRING(str) str #endif #include <array> #include <nethost.h> #include <coreclr_delegates.h> #include <hostfxr.h> #include <imgui.h> #include <hex/api/plugin_manager.hpp> #include <hex/helpers/fs.hpp> #include <wolv/io/fs.hpp> #include <wolv/utils/guards.hpp> #include <wolv/utils/string.hpp> #include <hex/helpers/fmt.hpp> #include <hex/helpers/logger.hpp> #include <hex/helpers/utils.hpp> #include <hex/helpers/default_paths.hpp> #include <toasts/toast_notification.hpp> extern "C" void igSetCurrentContext(ImGuiContext* ctx); namespace hex::script::loader { namespace { using get_hostfxr_path_fn = int(*)(char_t * buffer, size_t * buffer_size, const get_hostfxr_parameters *parameters); hostfxr_initialize_for_runtime_config_fn hostfxr_initialize_for_runtime_config = nullptr; hostfxr_get_runtime_delegate_fn hostfxr_get_runtime_delegate = nullptr; hostfxr_close_fn hostfxr_close = nullptr; hostfxr_set_runtime_property_value_fn hostfxr_set_runtime_property_value = nullptr; hostfxr_set_error_writer_fn hostfxr_set_error_writer = nullptr; void* pInvokeOverride(const char *libraryName, const char *symbolName) { auto library = std::string_view(libraryName); if (library == "cimgui") { return getExport<void*>(ImHexApi::System::getLibImHexModuleHandle(), symbolName); } else if (library == "ImHex") { return getExport<void*>(hex::getContainingModule((void*)&pInvokeOverride), symbolName); } return nullptr; } bool loadHostfxr() { #if defined(OS_WINDOWS) auto netHostLibrary = loadLibrary(L"nethost.dll"); #elif defined(OS_LINUX) auto netHostLibrary = loadLibrary("libnethost.so"); #elif defined(OS_MACOS) void *netHostLibrary = nullptr; for (const auto &pluginPath : paths::Plugins.read()) { auto frameworksPath = pluginPath.parent_path().parent_path() / "Frameworks"; netHostLibrary = loadLibrary((frameworksPath / "libnethost.dylib").c_str()); if (netHostLibrary != nullptr) break; } if (netHostLibrary == nullptr) { for (const auto &librariesPath : paths::Libraries.read()) { netHostLibrary = loadLibrary((librariesPath / "libnethost.dylib").c_str()); if (netHostLibrary != nullptr) break; } } #endif if (netHostLibrary == nullptr) { log::debug("libnethost is not available! Disabling .NET support"); return false; } auto get_hostfxr_path_ptr = getExport<get_hostfxr_path_fn>(netHostLibrary, "get_hostfxr_path"); std::array<char_t, 300> buffer = { }; size_t bufferSize = buffer.size(); u32 result = get_hostfxr_path_ptr(buffer.data(), &bufferSize, nullptr); if (result != 0) { log::error(hex::format("Could not get hostfxr path! 0x{:X}", result)); return false; } void *hostfxrLibrary = loadLibrary(buffer.data()); if (hostfxrLibrary == nullptr) { log::error("Could not load hostfxr library!"); return false; } { hostfxr_initialize_for_runtime_config = getExport<hostfxr_initialize_for_runtime_config_fn>(hostfxrLibrary, "hostfxr_initialize_for_runtime_config"); hostfxr_get_runtime_delegate = getExport<hostfxr_get_runtime_delegate_fn>(hostfxrLibrary, "hostfxr_get_runtime_delegate"); hostfxr_close = getExport<hostfxr_close_fn>(hostfxrLibrary, "hostfxr_close"); hostfxr_set_runtime_property_value = getExport<hostfxr_set_runtime_property_value_fn>(hostfxrLibrary, "hostfxr_set_runtime_property_value"); hostfxr_set_error_writer = getExport<hostfxr_set_error_writer_fn>(hostfxrLibrary, "hostfxr_set_error_writer"); } hostfxr_set_error_writer([] HOSTFXR_CALLTYPE (const char_t *) { }); return hostfxr_initialize_for_runtime_config != nullptr && hostfxr_get_runtime_delegate != nullptr && hostfxr_close != nullptr && hostfxr_set_runtime_property_value != nullptr && hostfxr_set_error_writer != nullptr; } load_assembly_and_get_function_pointer_fn getLoadAssemblyFunction(const std::fs::path &path) { load_assembly_and_get_function_pointer_fn loadAssemblyFunction = nullptr; hostfxr_handle ctx = nullptr; u32 result = hostfxr_initialize_for_runtime_config(path.c_str(), nullptr, &ctx); ON_SCOPE_EXIT { hostfxr_close(ctx); }; if (result > 2 || ctx == nullptr) { if (result == /* FrameworkMissingFailure */ 0x80008096) { log::warn("ImHex has built-in support for .NET scripts and extensions. However, these can only be used when the .NET runtime is installed."); log::warn("Please install version {} or later of the .NET runtime if you plan to use them. Otherwise this error can be safely ignored.", IMHEX_DOTNET_RUNTIME_VERSION); } throw std::runtime_error(hex::format("Command line init failed 0x{:X}", result)); } #if defined (OS_WINDOWS) hostfxr_set_runtime_property_value(ctx, STRING("PINVOKE_OVERRIDE"), utf8ToUtf16(hex::format("{}", (void*)pInvokeOverride)).c_str()); #else hostfxr_set_runtime_property_value(ctx, STRING("PINVOKE_OVERRIDE"), hex::format("{}", (void*)pInvokeOverride).c_str()); #endif hostfxr_set_error_writer([] HOSTFXR_CALLTYPE (const char_t *message) { #if defined(OS_WINDOWS) log::error("{}", utf16ToUtf8(message)); #else log::error("{}", message); #endif }); result = hostfxr_get_runtime_delegate( ctx, hostfxr_delegate_type::hdt_load_assembly_and_get_function_pointer, reinterpret_cast<void**>(&loadAssemblyFunction) ); if (result != 0 || loadAssemblyFunction == nullptr) { throw std::runtime_error(hex::format("Failed to get load_assembly_and_get_function_pointer delegate 0x{:X}", result)); } return loadAssemblyFunction; } } bool DotNetLoader::initialize() { if (!loadHostfxr()) { return false; } for (const auto& path : paths::Plugins.read()) { auto assemblyLoader = path / "AssemblyLoader.dll"; if (!wolv::io::fs::exists(assemblyLoader)) continue; auto loadAssembly = getLoadAssemblyFunction(std::fs::absolute(path) / "AssemblyLoader.runtimeconfig.json"); auto dotnetType = STRING("ImHex.EntryPoint, AssemblyLoader"); const char_t *dotnetTypeMethod = STRING("ExecuteScript"); this-> m_assemblyLoaderPathString = assemblyLoader.native(); component_entry_point_fn entryPoint = nullptr; u32 result = loadAssembly( m_assemblyLoaderPathString.c_str(), dotnetType, dotnetTypeMethod, nullptr, nullptr, reinterpret_cast<void**>(&entryPoint) ); if (result != 0 || entryPoint == nullptr) { log::error("Failed to load assembly loader '{}'! 0x{:X}", assemblyLoader.string(), result); continue; } m_runMethod = [entryPoint](const std::string &methodName, bool keepLoaded, const std::fs::path &path) -> int { auto pathString = wolv::util::toUTF8String(path); auto string = hex::format("{}||{}||{}", keepLoaded ? "LOAD" : "EXEC", methodName, pathString); auto result = entryPoint(string.data(), string.size()); return result; }; m_methodExists = [entryPoint](const std::string &methodName, const std::fs::path &path) -> bool { auto pathString = wolv::util::toUTF8String(path); auto string = hex::format("CHECK||{}||{}", methodName, pathString); auto result = entryPoint(string.data(), string.size()); return result == 0; }; return true; } return false; } bool DotNetLoader::loadAll() { this->clearScripts(); for (const auto &imhexPath : paths::Scripts.read()) { auto directoryPath = imhexPath / "custom" / "dotnet"; if (!wolv::io::fs::exists(directoryPath)) wolv::io::fs::createDirectories(directoryPath); if (!wolv::io::fs::exists(directoryPath)) continue; for (const auto &entry : std::fs::directory_iterator(directoryPath)) { if (!entry.is_directory()) continue; const auto &scriptPath = entry.path() / "Main.dll"; if (!std::fs::exists(scriptPath)) continue; bool skip = false; for (const auto &existingScript : getScripts()) { if (existingScript.path == scriptPath) { skip = true; } } if (skip) continue; const bool hasMain = m_methodExists("Main", scriptPath); const bool hasOnLoad = m_methodExists("OnLoad", scriptPath); const auto scriptName = entry.path().stem().string(); if (hasMain && hasOnLoad) { log::error("Script '{}' has both a Main() and a OnLoad() function. Only one is allowed per script.", scriptName); continue; } else if (!hasMain && !hasOnLoad) { log::error("Script '{}' has neither a Main() nor a OnLoad() function.", scriptName); continue; } if (hasMain) { this->addScript(scriptName, scriptPath, false, [this, scriptPath] { auto result = m_runMethod("Main", false, scriptPath); if (result != 0) { ui::ToastError::open(hex::format("Script '{}' running failed with code {}", result)); } }); } else if (hasOnLoad) { this->addScript(scriptName, scriptPath, true, [] {}); auto result = m_runMethod("OnLoad", true, scriptPath); if (result != 0) { TaskManager::doLater([=] { ui::ToastError::open(hex::format("Script '{}' loading failed with code {}", scriptName, result)); }); } } } } return true; } void DotNetLoader::clearScripts() { std::erase_if(getScripts(), [](const Script &script) { return !script.background; }); } }
11,842
C++
.cpp
234
36.15812
187
0.550974
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
147
fonts.cpp
WerWolv_ImHex/plugins/fonts/source/fonts.cpp
#include <hex/api/imhex_api.hpp> #include <romfs/romfs.hpp> #include <hex/helpers/utils.hpp> #include <fonts/codicons_font.h> #include <fonts/blendericons_font.h> namespace hex::fonts { void registerFonts() { using namespace ImHexApi::Fonts; /** * !!IMPORTANT!! * Always load the font files in decreasing size of their glyphs. This will make the rasterize be more * efficient when packing the glyphs into the font atlas and therefor make the atlas much smaller. */ ImHexApi::Fonts::loadFont("Blender Icons", romfs::get("fonts/blendericons.ttf").span<u8>(),{ { ICON_MIN_BI, ICON_MAX_BI } }, { -1_scaled, -1_scaled }); ImHexApi::Fonts::loadFont("VS Codicons", romfs::get("fonts/codicons.ttf").span<u8>(), { { ICON_MIN_VS, ICON_MAX_VS } }, { -1_scaled, -1_scaled }); ImHexApi::Fonts::loadFont("Unifont", romfs::get("fonts/unifont.otf").span<u8>(), {}, {}, 0, 16); } }
1,014
C++
.cpp
22
38.5
160
0.615463
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
148
font_loader.cpp
WerWolv_ImHex/plugins/fonts/source/font_loader.cpp
#include <imgui.h> #include <imgui_internal.h> #include <imgui_freetype.h> #include <imgui_impl_opengl3.h> #include <memory> #include <list> #include <hex/api/imhex_api.hpp> #include <hex/api/content_registry.hpp> #include <hex/api/event_manager.hpp> #include <hex/api/task_manager.hpp> #include <hex/helpers/auto_reset.hpp> #include <hex/helpers/logger.hpp> #include <hex/helpers/fs.hpp> #include <hex/helpers/utils.hpp> #include <hex/helpers/default_paths.hpp> #include <romfs/romfs.hpp> #include <wolv/io/file.hpp> #include <wolv/utils/string.hpp> namespace hex::fonts { namespace { class Font { public: Font() = default; float getDescent() const { return m_font->Descent; } private: explicit Font(ImFont *font) : m_font(font) { } private: friend class FontAtlas; ImFont *m_font; }; class FontAtlas { public: FontAtlas() : m_fontAtlas(IM_NEW(ImFontAtlas)) { enableUnicodeCharacters(false); // Set the default configuration for the font atlas m_config.OversampleH = m_config.OversampleV = 1; m_config.PixelSnapH = true; m_config.MergeMode = false; // Make sure the font atlas doesn't get too large, otherwise weaker GPUs might reject it m_fontAtlas->Flags |= ImFontAtlasFlags_NoPowerOfTwoHeight; m_fontAtlas->TexDesiredWidth = 4096; } ~FontAtlas() { IM_DELETE(m_fontAtlas); } Font addDefaultFont() { ImFontConfig config = m_config; config.FontBuilderFlags |= ImGuiFreeTypeBuilderFlags_Monochrome | ImGuiFreeTypeBuilderFlags_MonoHinting; config.SizePixels = std::floor(ImHexApi::System::getGlobalScale()) * 13.0F; auto font = m_fontAtlas->AddFontDefault(&config); m_fontSizes.emplace_back(false, config.SizePixels); m_config.MergeMode = true; return Font(font); } Font addFontFromMemory(const std::vector<u8> &fontData, float fontSize, bool scalable, ImVec2 offset, const ImVector<ImWchar> &glyphRange = {}) { auto &storedFontData = m_fontData.emplace_back(fontData); ImFontConfig config = m_config; config.FontDataOwnedByAtlas = false; config.GlyphOffset = { offset.x, offset.y }; auto font = m_fontAtlas->AddFontFromMemoryTTF(storedFontData.data(), int(storedFontData.size()), fontSize, &config, !glyphRange.empty() ? glyphRange.Data : m_glyphRange.Data); m_fontSizes.emplace_back(scalable, fontSize); m_config.MergeMode = true; return Font(font); } Font addFontFromRomFs(const std::fs::path &path, float fontSize, bool scalable, ImVec2 offset, const ImVector<ImWchar> &glyphRange = {}) { auto data = romfs::get(path).span<u8>(); return addFontFromMemory({ data.begin(), data.end() }, fontSize, scalable, offset, glyphRange); } Font addFontFromFile(const std::fs::path &path, float fontSize, bool scalable, ImVec2 offset, const ImVector<ImWchar> &glyphRange = {}) { wolv::io::File file(path, wolv::io::File::Mode::Read); auto data = file.readVector(); return addFontFromMemory(data, fontSize, scalable, offset, glyphRange); } void setBold(bool enabled) { if (enabled) m_config.FontBuilderFlags |= ImGuiFreeTypeBuilderFlags_Bold; else m_config.FontBuilderFlags &= ~ImGuiFreeTypeBuilderFlags_Bold; } void setItalic(bool enabled) { if (enabled) m_config.FontBuilderFlags |= ImGuiFreeTypeBuilderFlags_Oblique; else m_config.FontBuilderFlags &= ~ImGuiFreeTypeBuilderFlags_Oblique; } void setAntiAliasing(bool enabled) { if (enabled) m_config.FontBuilderFlags &= ~ImGuiFreeTypeBuilderFlags_Monochrome | ImGuiFreeTypeBuilderFlags_MonoHinting; else m_config.FontBuilderFlags |= ImGuiFreeTypeBuilderFlags_Monochrome | ImGuiFreeTypeBuilderFlags_MonoHinting; } void enableUnicodeCharacters(bool enabled) { ImFontGlyphRangesBuilder glyphRangesBuilder; { constexpr static std::array<ImWchar, 3> controlCodeRange = { 0x0001, 0x001F, 0 }; constexpr static std::array<ImWchar, 3> extendedAsciiRange = { 0x007F, 0x00FF, 0 }; constexpr static std::array<ImWchar, 3> latinExtendedARange = { 0x0100, 0x017F, 0 }; glyphRangesBuilder.AddRanges(controlCodeRange.data()); glyphRangesBuilder.AddRanges(m_fontAtlas->GetGlyphRangesDefault()); glyphRangesBuilder.AddRanges(extendedAsciiRange.data()); glyphRangesBuilder.AddRanges(latinExtendedARange.data()); } if (enabled) { constexpr static std::array<ImWchar, 3> fullRange = { 0x0180, 0xFFEF, 0 }; glyphRangesBuilder.AddRanges(fullRange.data()); } else { glyphRangesBuilder.AddRanges(m_fontAtlas->GetGlyphRangesJapanese()); glyphRangesBuilder.AddRanges(m_fontAtlas->GetGlyphRangesChineseFull()); glyphRangesBuilder.AddRanges(m_fontAtlas->GetGlyphRangesCyrillic()); glyphRangesBuilder.AddRanges(m_fontAtlas->GetGlyphRangesKorean()); glyphRangesBuilder.AddRanges(m_fontAtlas->GetGlyphRangesThai()); glyphRangesBuilder.AddRanges(m_fontAtlas->GetGlyphRangesVietnamese()); } m_glyphRange.clear(); glyphRangesBuilder.BuildRanges(&m_glyphRange); } bool build() const { return m_fontAtlas->Build(); } [[nodiscard]] ImFontAtlas* getAtlas() { auto result = m_fontAtlas; return result; } float calculateFontDescend(const ImHexApi::Fonts::Font &font, float fontSize) const { auto atlas = std::make_unique<ImFontAtlas>(); auto cfg = m_config; // Calculate the expected font size auto size = fontSize; if (font.defaultSize.has_value()) size = font.defaultSize.value() * std::max(1.0F, std::floor(ImHexApi::Fonts::getFontSize() / ImHexApi::Fonts::DefaultFontSize)); else size = std::max(1.0F, std::floor(size / ImHexApi::Fonts::DefaultFontSize)) * ImHexApi::Fonts::DefaultFontSize; cfg.MergeMode = false; cfg.SizePixels = size; cfg.FontDataOwnedByAtlas = false; // Construct a range that only contains the first glyph of the font ImVector<ImWchar> queryRange; { auto firstGlyph = font.glyphRanges.empty() ? m_glyphRange.front() : font.glyphRanges.front().begin; queryRange.push_back(firstGlyph); queryRange.push_back(firstGlyph); } queryRange.push_back(0x00); // Build the font atlas with the query range auto newFont = atlas->AddFontFromMemoryTTF(const_cast<u8 *>(font.fontData.data()), int(font.fontData.size()), 0, &cfg, queryRange.Data); atlas->Build(); return newFont->Descent; } void reset() { IM_DELETE(m_fontAtlas); m_fontAtlas = IM_NEW(ImFontAtlas); m_fontData.clear(); m_config.MergeMode = false; } void updateFontScaling(float newScaling) { for (int i = 0; i < m_fontAtlas->ConfigData.size(); i += 1) { const auto &[scalable, fontSize] = m_fontSizes[i]; auto &configData = m_fontAtlas->ConfigData[i]; if (!scalable) { configData.SizePixels = fontSize * std::floor(newScaling); } else { configData.SizePixels = fontSize * newScaling; } } } private: ImFontAtlas* m_fontAtlas; std::vector<std::pair<bool, float>> m_fontSizes; ImFontConfig m_config; ImVector<ImWchar> m_glyphRange; std::list<std::vector<u8>> m_fontData; }; std::fs::path findCustomFontPath() { // Find the custom font file specified in the settings auto fontFile = ContentRegistry::Settings::read<std::fs::path>("hex.builtin.setting.font", "hex.builtin.setting.font.font_path", ""); if (!fontFile.empty()) { if (!wolv::io::fs::exists(fontFile) || !wolv::io::fs::isRegularFile(fontFile)) { log::warn("Custom font file {} not found! Falling back to default font.", wolv::util::toUTF8String(fontFile)); fontFile.clear(); } log::info("Loading custom font from {}", wolv::util::toUTF8String(fontFile)); } // If no custom font has been specified, search for a file called "font.ttf" in one of the resource folders if (fontFile.empty()) { for (const auto &dir : paths::Resources.read()) { auto path = dir / "font.ttf"; if (wolv::io::fs::exists(path)) { log::info("Loading custom font from {}", wolv::util::toUTF8String(path)); fontFile = path; break; } } } return fontFile; } float getFontSize() { float fontSize = ImHexApi::Fonts::DefaultFontSize; if (auto scaling = ImHexApi::System::getGlobalScale(); u32(scaling) * 10 == u32(scaling * 10)) fontSize *= scaling; else fontSize *= scaling * 0.75F; // Fall back to the default font if the global scale is 0 if (fontSize == 0.0F) fontSize = ImHexApi::Fonts::DefaultFontSize; // If a custom font is used, adjust the font size if (!ImHexApi::Fonts::getCustomFontPath().empty()) { fontSize = float(ContentRegistry::Settings::read<int>("hex.builtin.setting.font", "hex.builtin.setting.font.font_size", 13)) * ImHexApi::System::getGlobalScale(); } return fontSize; } } bool buildFontAtlasImpl(bool loadUnicodeCharacters) { static FontAtlas fontAtlas; fontAtlas.reset(); // Check if Unicode support is enabled in the settings and that the user doesn't use the No GPU version on Windows // The Mesa3D software renderer on Windows identifies itself as "VMware, Inc." bool shouldLoadUnicode = ContentRegistry::Settings::read<bool>("hex.builtin.setting.font", "hex.builtin.setting.font.load_all_unicode_chars", false) && ImHexApi::System::getGPUVendor() != "VMware, Inc."; if (!loadUnicodeCharacters) shouldLoadUnicode = false; fontAtlas.enableUnicodeCharacters(shouldLoadUnicode); // If a custom font is set in the settings, load the rest of the settings as well if (ContentRegistry::Settings::read<bool>("hex.builtin.setting.font", "hex.builtin.setting.font.custom_font_enable", false)) { fontAtlas.setBold(ContentRegistry::Settings::read<bool>("hex.builtin.setting.font", "hex.builtin.setting.font.font_bold", false)); fontAtlas.setItalic(ContentRegistry::Settings::read<bool>("hex.builtin.setting.font", "hex.builtin.setting.font.font_italic", false)); fontAtlas.setAntiAliasing(ContentRegistry::Settings::read<bool>("hex.builtin.setting.font", "hex.builtin.setting.font.font_antialias", true)); ImHexApi::Fonts::impl::setCustomFontPath(findCustomFontPath()); } ImHexApi::Fonts::impl::setFontSize(getFontSize()); const auto fontSize = ImHexApi::Fonts::getFontSize(); const auto &customFontPath = ImHexApi::Fonts::getCustomFontPath(); // Try to load the custom font if one was set std::optional<Font> defaultFont; if (!customFontPath.empty()) { defaultFont = fontAtlas.addFontFromFile(customFontPath, fontSize, true, ImVec2()); if (!fontAtlas.build()) { log::error("Failed to load custom font '{}'! Falling back to default font", wolv::util::toUTF8String(customFontPath)); defaultFont.reset(); } } // If there's no custom font set, or it failed to load, fall back to the default font if (!defaultFont.has_value()) { auto pixelPerfectFont = ContentRegistry::Settings::read<bool>("hex.builtin.setting.font", "hex.builtin.setting.font.pixel_perfect_default_font", true); if (pixelPerfectFont) defaultFont = fontAtlas.addDefaultFont(); else defaultFont = fontAtlas.addFontFromRomFs("fonts/firacode.ttf", fontSize * 1.1, true, ImVec2()); if (!fontAtlas.build()) { log::fatal("Failed to load default font!"); return false; } } // Add all the built-in fonts { static std::list<ImVector<ImWchar>> glyphRanges; glyphRanges.clear(); for (auto &font : ImHexApi::Fonts::impl::getFonts()) { // Construct the glyph range for the font ImVector<ImWchar> glyphRange; if (!font.glyphRanges.empty()) { for (const auto &range : font.glyphRanges) { glyphRange.push_back(range.begin); glyphRange.push_back(range.end); } glyphRange.push_back(0x00); } glyphRanges.push_back(glyphRange); // Calculate the glyph offset for the font ImVec2 offset = { font.offset.x, font.offset.y - (defaultFont->getDescent() - fontAtlas.calculateFontDescend(font, fontSize)) }; // Load the font fontAtlas.addFontFromMemory(font.fontData, font.defaultSize.value_or(fontSize), !font.defaultSize.has_value(), offset, glyphRanges.back()); } } EventDPIChanged::subscribe([](float, float newScaling) { fontAtlas.updateFontScaling(newScaling); if (fontAtlas.build()) { ImGui_ImplOpenGL3_DestroyFontsTexture(); ImGui_ImplOpenGL3_CreateFontsTexture(); ImHexApi::Fonts::impl::setFontAtlas(fontAtlas.getAtlas()); } }); // Build the font atlas const bool result = fontAtlas.build(); if (result) { // Set the font atlas if the build was successful ImHexApi::Fonts::impl::setFontAtlas(fontAtlas.getAtlas()); return true; } // If the build wasn't successful and Unicode characters are enabled, try again without them // If they were disabled already, something went wrong, and we can't recover from it if (!shouldLoadUnicode) { // Reset Unicode loading and scaling factor settings back to default to make sure the user can still use the application ContentRegistry::Settings::write<bool>("hex.builtin.setting.font", "hex.builtin.setting.font.load_all_unicode_chars", false); ContentRegistry::Settings::write<float>("hex.builtin.setting.interface", "hex.builtin.setting.interface.scaling_factor", 1.0F); ImHexApi::System::impl::setGlobalScale(1.0F); return false; } else { return buildFontAtlasImpl(false); } } bool buildFontAtlas() { return buildFontAtlasImpl(true); } }
16,526
C++
.cpp
307
39.517915
191
0.584924
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
149
library_fonts.cpp
WerWolv_ImHex/plugins/fonts/source/library_fonts.cpp
#include <hex/plugin.hpp> #include <hex/api/content_registry.hpp> #include <hex/helpers/logger.hpp> #include <romfs/romfs.hpp> namespace hex::fonts { void registerFonts(); bool buildFontAtlas(); } IMHEX_LIBRARY_SETUP("Fonts") { hex::log::debug("Using romfs: '{}'", romfs::name()); hex::ImHexApi::System::addStartupTask("Loading fonts", true, hex::fonts::buildFontAtlas); hex::fonts::registerFonts(); }
427
C++
.cpp
13
29.923077
93
0.709046
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
150
plugin_decompress.cpp
WerWolv_ImHex/plugins/decompress/source/plugin_decompress.cpp
#include <hex/plugin.hpp> #include <hex/api/content_registry.hpp> #include <hex/helpers/logger.hpp> #include <romfs/romfs.hpp> namespace hex::plugin::decompress { void registerPatternLanguageFunctions(); } using namespace hex; using namespace hex::plugin::decompress; IMHEX_PLUGIN_SETUP("Decompressing", "WerWolv", "Support for decompressing data") { hex::log::debug("Using romfs: '{}'", romfs::name()); registerPatternLanguageFunctions(); }
461
C++
.cpp
13
33
82
0.759637
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
151
pl_functions.cpp
WerWolv_ImHex/plugins/decompress/source/content/pl_functions.cpp
#include <hex.hpp> #include <hex/plugin.hpp> #include <hex/api/content_registry.hpp> #include <pl/core/evaluator.hpp> #include <pl/patterns/pattern.hpp> #include <wolv/utils/guards.hpp> #include <vector> #include <optional> #if IMHEX_FEATURE_ENABLED(ZLIB) #include <zlib.h> #endif #if IMHEX_FEATURE_ENABLED(BZIP2) #include <bzlib.h> #endif #if IMHEX_FEATURE_ENABLED(LIBLZMA) #include <lzma.h> #endif #if IMHEX_FEATURE_ENABLED(ZSTD) #include <zstd.h> #endif #if IMHEX_FEATURE_ENABLED(LZ4) #include <lz4.h> #include <lz4frame.h> #endif namespace hex::plugin::decompress { namespace { std::vector<u8> getCompressedData(pl::core::Evaluator *evaluator, const pl::core::Token::Literal &literal) { const auto inputPattern = literal.toPattern(); std::vector<u8> compressedData; compressedData.resize(inputPattern->getSize()); evaluator->readData(inputPattern->getOffset(), compressedData.data(), compressedData.size(), inputPattern->getSection()); return compressedData; } } void registerPatternLanguageFunctions() { using namespace pl::core; using FunctionParameterCount = pl::api::FunctionParameterCount; const pl::api::Namespace nsHexDec = { "builtin", "hex", "dec" }; /* zlib_decompress(compressed_pattern, section_id) */ ContentRegistry::PatternLanguage::addFunction(nsHexDec, "zlib_decompress", FunctionParameterCount::exactly(3), [](Evaluator *evaluator, auto params) -> std::optional<Token::Literal> { #if IMHEX_FEATURE_ENABLED(ZLIB) auto compressedData = getCompressedData(evaluator, params[0]); auto &section = evaluator->getSection(params[1].toUnsigned()); auto windowSize = params[2].toUnsigned(); z_stream stream = { }; if (inflateInit2(&stream, windowSize) != Z_OK) { return false; } section.resize(100); stream.avail_in = compressedData.size(); stream.avail_out = section.size(); stream.next_in = compressedData.data(); stream.next_out = section.data(); ON_SCOPE_EXIT { inflateEnd(&stream); }; while (stream.avail_in != 0) { auto res = inflate(&stream, Z_NO_FLUSH); if (res == Z_STREAM_END) { section.resize(section.size() - stream.avail_out); break; } if (res != Z_OK) return false; if (stream.avail_out != 0) break; const auto prevSectionSize = section.size(); section.resize(prevSectionSize * 2); stream.next_out = section.data() + prevSectionSize; stream.avail_out = prevSectionSize; } return true; #else hex::unused(evaluator, params); err::E0012.throwError("hex::dec::zlib_decompress is not available. Please recompile ImHex with zlib support."); #endif }); /* bzip_decompress(compressed_pattern, section_id) */ ContentRegistry::PatternLanguage::addFunction(nsHexDec, "bzip_decompress", FunctionParameterCount::exactly(2), [](Evaluator *evaluator, auto params) -> std::optional<Token::Literal> { #if IMHEX_FEATURE_ENABLED(BZIP2) auto compressedData = getCompressedData(evaluator, params[0]); auto &section = evaluator->getSection(params[1].toUnsigned()); bz_stream stream = { }; if (BZ2_bzDecompressInit(&stream, 0, 1) != Z_OK) { return false; } section.resize(100); stream.avail_in = compressedData.size(); stream.avail_out = section.size(); stream.next_in = reinterpret_cast<char*>(compressedData.data()); stream.next_out = reinterpret_cast<char*>(section.data()); ON_SCOPE_EXIT { BZ2_bzDecompressEnd(&stream); }; while (stream.avail_in != 0) { auto res = BZ2_bzDecompress(&stream); if (res == BZ_STREAM_END) { section.resize(section.size() - stream.avail_out); break; } if (res != BZ_OK) return false; if (stream.avail_out != 0) break; const auto prevSectionSize = section.size(); section.resize(prevSectionSize * 2); stream.next_out = reinterpret_cast<char*>(section.data()) + prevSectionSize; stream.avail_out = prevSectionSize; } return true; #else hex::unused(evaluator, params); err::E0012.throwError("hex::dec::bzlib_decompress is not available. Please recompile ImHex with bzip2 support."); #endif }); /* lzma_decompress(compressed_pattern, section_id) */ ContentRegistry::PatternLanguage::addFunction(nsHexDec, "lzma_decompress", FunctionParameterCount::exactly(2), [](Evaluator *evaluator, auto params) -> std::optional<Token::Literal> { #if IMHEX_FEATURE_ENABLED(LIBLZMA) auto compressedData = getCompressedData(evaluator, params[0]); auto &section = evaluator->getSection(params[1].toUnsigned()); lzma_stream stream = LZMA_STREAM_INIT; if (lzma_auto_decoder(&stream, 0x10000, LZMA_IGNORE_CHECK) != Z_OK) { return false; } section.resize(100); stream.avail_in = compressedData.size(); stream.avail_out = section.size(); stream.next_in = compressedData.data(); stream.next_out = section.data(); ON_SCOPE_EXIT { lzma_end(&stream); }; while (stream.avail_in != 0) { auto res = lzma_code(&stream, LZMA_RUN); if (res == LZMA_STREAM_END) { section.resize(section.size() - stream.avail_out); break; } if (res == LZMA_MEMLIMIT_ERROR) { auto usage = lzma_memusage(&stream); lzma_memlimit_set(&stream, usage); res = lzma_code(&stream, LZMA_RUN); } if (res != LZMA_OK) return false; if (stream.avail_out != 0) break; const auto prevSectionSize = section.size(); section.resize(prevSectionSize * 2); stream.next_out = section.data() + prevSectionSize; stream.avail_out = prevSectionSize; } return true; #else hex::unused(evaluator, params); err::E0012.throwError("hex::dec::lzma_decompress is not available. Please recompile ImHex with liblzma support."); #endif }); /* zstd_decompress(compressed_pattern, section_id) */ ContentRegistry::PatternLanguage::addFunction(nsHexDec, "zstd_decompress", FunctionParameterCount::exactly(2), [](Evaluator *evaluator, auto params) -> std::optional<Token::Literal> { #if IMHEX_FEATURE_ENABLED(ZSTD) auto compressedData = getCompressedData(evaluator, params[0]); auto &section = evaluator->getSection(params[1].toUnsigned()); ZSTD_DCtx* dctx = ZSTD_createDCtx(); if (dctx == nullptr) { return false; } ON_SCOPE_EXIT { ZSTD_freeDCtx(dctx); }; const u8* source = compressedData.data(); size_t sourceSize = compressedData.size(); size_t blockSize = ZSTD_getFrameContentSize(source, sourceSize); if (blockSize == ZSTD_CONTENTSIZE_ERROR) { return false; } if (blockSize == ZSTD_CONTENTSIZE_UNKNOWN) { // Data uses stream compression ZSTD_inBuffer dataIn = { (void*)source, sourceSize, 0 }; size_t outSize = ZSTD_DStreamOutSize(); std::vector<u8> outVec(outSize); const u8* out = outVec.data(); size_t lastRet = 0; while (dataIn.pos < dataIn.size) { ZSTD_outBuffer dataOut = { (void*)out, outSize, 0 }; size_t ret = ZSTD_decompressStream(dctx, &dataOut, &dataIn); if (ZSTD_isError(ret)) { return false; } lastRet = ret; size_t sectionSize = section.size(); section.resize(sectionSize + dataOut.pos); std::memcpy(section.data() + sectionSize, out, dataOut.pos); } // Incomplete frame if (lastRet != 0) { return false; } } else { section.resize(section.size() + blockSize); size_t ret = ZSTD_decompressDCtx(dctx, section.data() + section.size() - blockSize, blockSize, source, sourceSize); if (ZSTD_isError(ret)) { return false; } } return true; #else hex::unused(evaluator, params); err::E0012.throwError("hex::dec::zstd_decompress is not available. Please recompile ImHex with zstd support."); #endif }); /* lz4_decompress(compressed_pattern, section_id) */ ContentRegistry::PatternLanguage::addFunction(nsHexDec, "lz4_decompress", FunctionParameterCount::exactly(3), [](Evaluator *evaluator, auto params) -> std::optional<Token::Literal> { #if IMHEX_FEATURE_ENABLED(LZ4) auto compressedData = getCompressedData(evaluator, params[0]); auto &section = evaluator->getSection(params[1].toUnsigned()); bool frame = params[2].toBoolean(); if (frame) { LZ4F_decompressionContext_t dctx; LZ4F_errorCode_t err = LZ4F_createDecompressionContext(&dctx, LZ4F_VERSION); if (LZ4F_isError(err)) { return false; } std::vector<u8> outBuffer(1024 * 1024); const u8* sourcePointer = compressedData.data(); size_t srcSize = compressedData.size(); while (srcSize > 0) { u8* dstPtr = outBuffer.data(); size_t dstCapacity = outBuffer.size(); size_t ret = LZ4F_decompress(dctx, dstPtr, &dstCapacity, sourcePointer, &srcSize, nullptr); if (LZ4F_isError(ret)) { LZ4F_freeDecompressionContext(dctx); return false; } section.insert(section.end(), outBuffer.begin(), outBuffer.begin() + dstCapacity); sourcePointer += (compressedData.size() - srcSize); } LZ4F_freeDecompressionContext(dctx); } else { section.resize(1024 * 1024); while (true) { auto decompressedSize = LZ4_decompress_safe(reinterpret_cast<const char*>(compressedData.data()), reinterpret_cast<char *>(section.data()), compressedData.size(), static_cast<int>(section.size())); if (decompressedSize < 0) { return false; } else if (decompressedSize > 0) { // Successful decompression section.resize(decompressedSize); break; } else { // Buffer too small, resize and try again section.resize(section.size() * 2); } } } return true; #else hex::unused(evaluator, params); err::E0012.throwError("hex::dec::lz4_decompress is not available. Please recompile ImHex with liblz4 support."); #endif }); } }
13,143
C++
.cpp
262
32.912214
221
0.511163
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
152
main.cpp
WerWolv_ImHex/plugins/builtin/tests/source/main.cpp
#include <iostream> #include <hex/test/tests.hpp> #include <hex/api/plugin_manager.hpp> #include <content/providers/memory_file_provider.hpp> #include <content/views/view_patches.hpp> #include <hex/api/task_manager.hpp> using namespace hex; using namespace hex::plugin::builtin; TEST_SEQUENCE("Providers/ReadWrite") { INIT_PLUGIN("Built-in"); auto &pr = *ImHexApi::Provider::createProvider("hex.builtin.provider.mem_file", true); TEST_ASSERT(pr.getSize() == 0); TEST_ASSERT(!pr.isDirty()); pr.resize(50); TEST_ASSERT(pr.getSize() == 50); TEST_ASSERT(pr.isDirty()); char buf[] = "\x99\x99"; // temporary value that should be overwriten pr.read(0, buf, 2); TEST_ASSERT(std::equal(buf, buf+2, "\x00\x00")); pr.write(0, "\xFF\xFF", 2); char buf2[] = "\x99\x99"; // temporary value that should be overwriten pr.read(0, buf2, 2); TEST_ASSERT(std::equal(buf2, buf2+2, "\xFF\xFF")); TEST_SUCCESS(); }; TEST_SEQUENCE("Providers/InvalidResize") { INIT_PLUGIN("Built-in"); auto &pr = *ImHexApi::Provider::createProvider("hex.builtin.provider.mem_file", true); TEST_ASSERT(!pr.resize(-1)); TEST_SUCCESS(); };
1,188
C++
.cpp
31
34.387097
90
0.67951
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
153
plugin_builtin.cpp
WerWolv_ImHex/plugins/builtin/source/plugin_builtin.cpp
#include <hex/plugin.hpp> #include <hex/api/content_registry.hpp> #include <hex/api/task_manager.hpp> #include <hex/helpers/logger.hpp> #include <romfs/romfs.hpp> #include <nlohmann/json.hpp> #include "content/command_line_interface.hpp" using namespace hex; namespace hex::plugin::builtin { void registerEventHandlers(); void registerDataVisualizers(); void registerMiniMapVisualizers(); void registerDataInspectorEntries(); void registerToolEntries(); void registerPatternLanguageFunctions(); void registerPatternLanguagePragmas(); void registerPatternLanguageVisualizers(); void registerCommandPaletteCommands(); void registerSettings(); void loadSettings(); void registerDataProcessorNodes(); void registerProviders(); void registerDataFormatters(); void registerMainMenuEntries(); void createWelcomeScreen(); void registerViews(); void registerThemeHandlers(); void registerStyleHandlers(); void registerThemes(); void registerBackgroundServices(); void registerNetworkEndpoints(); void registerFileHandlers(); void registerProjectHandlers(); void registerAchievements(); void registerReportGenerators(); void registerTutorials(); void registerDataInformationSections(); void loadWorkspaces(); void addWindowDecoration(); void addFooterItems(); void addTitleBarButtons(); void addToolbarItems(); void addGlobalUIItems(); void addInitTasks(); void handleBorderlessWindowMode(); void setupOutOfBoxExperience(); void extractBundledFiles(); } IMHEX_PLUGIN_SUBCOMMANDS() { { "help", "h", "Print help about this command", hex::plugin::builtin::handleHelpCommand }, { "version", "", "Print ImHex version", hex::plugin::builtin::handleVersionCommand }, { "plugins", "", "Lists all plugins that have been installed", hex::plugin::builtin::handlePluginsCommand }, { "language", "", "Changes the language ImHex uses", hex::plugin::builtin::handleLanguageCommand }, { "verbose", "v", "Enables verbose debug logging", hex::plugin::builtin::handleVerboseCommand }, { "open", "o", "Open files passed as argument. [default]", hex::plugin::builtin::handleOpenCommand }, { "calc", "", "Evaluate a mathematical expression", hex::plugin::builtin::handleCalcCommand }, { "hash", "", "Calculate the hash of a file", hex::plugin::builtin::handleHashCommand }, { "encode", "", "Encode a string", hex::plugin::builtin::handleEncodeCommand }, { "decode", "", "Decode a string", hex::plugin::builtin::handleDecodeCommand }, { "magic", "", "Identify file types", hex::plugin::builtin::handleMagicCommand }, { "pl", "", "Interact with the pattern language", hex::plugin::builtin::handlePatternLanguageCommand }, { "hexdump", "", "Generate a hex dump of the provided file", hex::plugin::builtin::handleHexdumpCommand }, { "demangle", "", "Demangle a mangled symbol", hex::plugin::builtin::handleDemangleCommand }, { "reset-settings", "", "Demangle a mangled symbol", hex::plugin::builtin::handleSettingsResetCommand }, }; IMHEX_PLUGIN_SETUP("Built-in", "WerWolv", "Default ImHex functionality") { using namespace hex::plugin::builtin; hex::log::debug("Using romfs: '{}'", romfs::name()); for (auto &path : romfs::list("lang")) hex::ContentRegistry::Language::addLocalization(nlohmann::json::parse(romfs::get(path).string())); addInitTasks(); extractBundledFiles(); registerMainMenuEntries(); registerEventHandlers(); registerDataVisualizers(); registerMiniMapVisualizers(); registerDataInspectorEntries(); registerToolEntries(); registerPatternLanguageFunctions(); registerPatternLanguagePragmas(); registerPatternLanguageVisualizers(); registerCommandPaletteCommands(); registerThemes(); registerSettings(); loadSettings(); registerDataProcessorNodes(); registerProviders(); registerDataFormatters(); registerViews(); registerThemeHandlers(); registerStyleHandlers(); registerBackgroundServices(); registerNetworkEndpoints(); registerFileHandlers(); registerProjectHandlers(); registerCommandForwarders(); registerAchievements(); registerReportGenerators(); registerTutorials(); registerDataInformationSections(); loadWorkspaces(); addWindowDecoration(); createWelcomeScreen(); addFooterItems(); addTitleBarButtons(); addToolbarItems(); addGlobalUIItems(); setupOutOfBoxExperience(); }
5,065
C++
.cpp
109
41.761468
131
0.654376
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
154
data_visualizers.cpp
WerWolv_ImHex/plugins/builtin/source/content/data_visualizers.cpp
#include <hex/api/content_registry.hpp> #include <imgui.h> #include <hex/ui/imgui_imhex_extensions.h> #include <hex/helpers/utils.hpp> #include <wolv/utils/string.hpp> namespace hex::plugin::builtin { template<std::integral T> class DataVisualizerHexadecimal : public hex::ContentRegistry::HexEditor::DataVisualizer { public: explicit DataVisualizerHexadecimal(const std::string &name) : DataVisualizer(name, ByteCount, CharCount) { } void draw(u64 address, const u8 *data, size_t size, bool upperCase) override { hex::unused(address); if (size == ByteCount) ImGuiExt::TextFormatted(upperCase ? "{:0{}X}" : "{:0{}x}", *reinterpret_cast<const T*>(data), sizeof(T) * 2); else ImGuiExt::TextFormatted("{: {}s}", CharCount); } bool drawEditing(u64 address, u8 *data, size_t size, bool upperCase, bool startedEditing) override { hex::unused(address, startedEditing); if (size == ByteCount) { return drawDefaultScalarEditingTextBox(address, getFormatString(upperCase), ImGuiExt::getImGuiDataType<T>(), data, ImGuiInputTextFlags_CharsHexadecimal); } else { return false; } } private: constexpr static inline auto ByteCount = sizeof(T); constexpr static inline auto CharCount = ByteCount * 2; const static inline auto FormattingUpperCase = hex::format("%0{}{}X", CharCount, ImGuiExt::getFormatLengthSpecifier<T>()); const static inline auto FormattingLowerCase = hex::format("%0{}{}x", CharCount, ImGuiExt::getFormatLengthSpecifier<T>()); const char *getFormatString(bool upperCase) { if (upperCase) return FormattingUpperCase.c_str(); else return FormattingLowerCase.c_str(); } }; class DataVisualizerHexii : public hex::ContentRegistry::HexEditor::DataVisualizer { public: DataVisualizerHexii() : DataVisualizer("hex.builtin.visualizer.hexii", ByteCount, CharCount) { } void draw(u64 address, const u8 *data, size_t size, bool upperCase) override { hex::unused(address); if (size == ByteCount) { const u8 c = data[0]; switch (c) { case 0x00: ImGui::TextUnformatted(" "); break; case 0xFF: ImGuiExt::TextFormattedDisabled("##"); break; default: if (c >= ' ' && c <= '~') ImGuiExt::TextFormatted(".{:c}", char(c)); else ImGui::Text(getFormatString(upperCase), c); break; } } else { ImGuiExt::TextFormatted("{: {}s}", CharCount); } } bool drawEditing(u64 address, u8 *data, size_t size, bool upperCase, bool startedEditing) override { hex::unused(address, startedEditing); if (size == ByteCount) { return drawDefaultScalarEditingTextBox(address, getFormatString(upperCase), ImGuiExt::getImGuiDataType<u8>(), data, ImGuiInputTextFlags_None); } else { return false; } } private: constexpr static inline auto ByteCount = 1; constexpr static inline auto CharCount = ByteCount * 2; const static inline auto FormattingUpperCase = hex::format("%0{}{}X", CharCount, ImGuiExt::getFormatLengthSpecifier<u8>()); const static inline auto FormattingLowerCase = hex::format("%0{}{}x", CharCount, ImGuiExt::getFormatLengthSpecifier<u8>()); static const char *getFormatString(bool upperCase) { if (upperCase) return FormattingUpperCase.c_str(); else return FormattingLowerCase.c_str(); } }; template<std::integral T> class DataVisualizerDecimal : public hex::ContentRegistry::HexEditor::DataVisualizer { public: explicit DataVisualizerDecimal(const std::string &name) : DataVisualizer(name, ByteCount, CharCount) { } void draw(u64 address, const u8 *data, size_t size, bool upperCase) override { hex::unused(address, upperCase); if (size == ByteCount) { if (std::is_signed_v<T>) ImGui::Text(getFormatString(), static_cast<i64>(*reinterpret_cast<const T*>(data))); else ImGui::Text(getFormatString(), static_cast<u64>(*reinterpret_cast<const T*>(data))); } else { ImGuiExt::TextFormatted("{: {}s}", CharCount); } } bool drawEditing(u64 address, u8 *data, size_t size, bool upperCase, bool startedEditing) override { hex::unused(address, upperCase, startedEditing); if (size == ByteCount) { return drawDefaultScalarEditingTextBox(address, FormatString.c_str(), ImGuiExt::getImGuiDataType<T>(), data, ImGuiInputTextFlags_None); } else { return false; } } private: constexpr static inline auto ByteCount = sizeof(T); constexpr static inline auto CharCount = std::numeric_limits<T>::digits10 + 2; const static inline auto FormatString = hex::format("%{}{}{}", CharCount, ImGuiExt::getFormatLengthSpecifier<T>(), std::is_signed_v<T> ? "d" : "u"); const char *getFormatString() { return FormatString.c_str(); } }; enum class Float16 : u16 {}; template<typename T> class DataVisualizerFloatingPoint : public hex::ContentRegistry::HexEditor::DataVisualizer { public: explicit DataVisualizerFloatingPoint(const std::string &name) : DataVisualizer(name, ByteCount, CharCount) { } void draw(u64 address, const u8 *data, size_t size, bool upperCase) override { hex::unused(address); if (size == ByteCount) ImGui::Text(getFormatString(upperCase), *reinterpret_cast<const T*>(data)); else ImGuiExt::TextFormatted("{: {}s}", CharCount); } bool drawEditing(u64 address, u8 *data, size_t size, bool upperCase, bool startedEditing) override { hex::unused(address, upperCase, startedEditing); if (size == ByteCount) { return drawDefaultScalarEditingTextBox(address, getFormatString(upperCase), ImGuiExt::getImGuiDataType<T>(), data, ImGuiInputTextFlags_CharsScientific); } else { return false; } } private: constexpr static inline auto ByteCount = sizeof(T); constexpr static inline auto CharCount = 14; const static inline auto FormatStringUpperCase = hex::format("%{}G", CharCount); const static inline auto FormatStringLowerCase = hex::format("%{}g", CharCount); const char *getFormatString(bool upperCase) const { if (upperCase) return FormatStringUpperCase.c_str(); else return FormatStringLowerCase.c_str(); } }; template<> class DataVisualizerFloatingPoint<Float16> : public hex::ContentRegistry::HexEditor::DataVisualizer { public: explicit DataVisualizerFloatingPoint(const std::string &name) : DataVisualizer(name, ByteCount, CharCount) { } void draw(u64 address, const u8 *data, size_t size, bool upperCase) override { hex::unused(address); if (size == ByteCount) ImGui::Text(getFormatString(upperCase), hex::float16ToFloat32(*reinterpret_cast<const u16*>(data))); else ImGuiExt::TextFormatted("{: {}s}", CharCount); } bool drawEditing(u64 address, u8 *data, size_t size, bool upperCase, bool startedEditing) override { hex::unused(startedEditing); this->draw(address, data, size, upperCase); return false; } private: constexpr static inline auto ByteCount = sizeof(Float16); constexpr static inline auto CharCount = 14; const static inline auto FormatStringUpperCase = hex::format("%{}G", CharCount); const static inline auto FormatStringLowerCase = hex::format("%{}g", CharCount); static const char *getFormatString(bool upperCase) { if (upperCase) return FormatStringUpperCase.c_str(); else return FormatStringLowerCase.c_str(); } }; class DataVisualizerRGBA8 : public hex::ContentRegistry::HexEditor::DataVisualizer { public: DataVisualizerRGBA8() : DataVisualizer("hex.builtin.visualizer.rgba8", 4, 2) { } void draw(u64 address, const u8 *data, size_t size, bool upperCase) override { hex::unused(address, upperCase); if (size == 4) ImGui::ColorButton("##color", ImColor(data[0], data[1], data[2], data[3]), ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_NoDragDrop, ImVec2(ImGui::GetColumnWidth(), ImGui::GetTextLineHeight())); else ImGui::ColorButton("##color", ImColor(0, 0, 0, 0xFF), ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_NoDragDrop, ImVec2(ImGui::GetColumnWidth(), ImGui::GetTextLineHeight())); } bool drawEditing(u64 address, u8 *data, size_t size, bool upperCase, bool startedEditing) override { hex::unused(address, data, size, upperCase); m_currColor = { float(data[0]) / 0xFF, float(data[1]) / 0xFF, float(data[2]) / 0xFF, float(data[3]) / 0xFF }; if (startedEditing) { ImGui::OpenPopup("##color_popup"); } ImGui::ColorButton("##color", ImColor(m_currColor[0], m_currColor[1], m_currColor[2], m_currColor[3]), ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_NoDragDrop, ImVec2(ImGui::GetColumnWidth(), ImGui::GetTextLineHeight())); if (ImGui::BeginPopup("##color_popup")) { if (ImGui::ColorPicker4("##picker", m_currColor.data(), ImGuiColorEditFlags_AlphaBar | ImGuiColorEditFlags_InputRGB)) { for (u8 i = 0; i < 4; i++) data[i] = m_currColor[i] * 0xFF; } ImGui::EndPopup(); } else { return true; } return false; } std::array<float, 4> m_currColor = { 0 }; }; class DataVisualizerBinary : public hex::ContentRegistry::HexEditor::DataVisualizer { public: DataVisualizerBinary() : DataVisualizer("hex.builtin.visualizer.binary", 1, 8) { } void draw(u64 address, const u8 *data, size_t size, bool) override { hex::unused(address); if (size == 1) ImGuiExt::TextFormatted("{:08b}", *data); } bool drawEditing(u64 address, u8 *data, size_t, bool, bool startedEditing) override { hex::unused(address, startedEditing); if (startedEditing) { m_inputBuffer = hex::format("{:08b}", *data); } if (drawDefaultTextEditingTextBox(address, m_inputBuffer, ImGuiInputTextFlags_None)) { if (auto result = hex::parseBinaryString(wolv::util::trim(m_inputBuffer)); result.has_value()) { *data = result.value(); return true; } } return false; } private: std::string m_inputBuffer; }; void registerDataVisualizers() { ContentRegistry::HexEditor::addDataVisualizer<DataVisualizerHexadecimal<u8>>("hex.builtin.visualizer.hexadecimal.8bit"); ContentRegistry::HexEditor::addDataVisualizer<DataVisualizerHexadecimal<u16>>("hex.builtin.visualizer.hexadecimal.16bit"); ContentRegistry::HexEditor::addDataVisualizer<DataVisualizerHexadecimal<u32>>("hex.builtin.visualizer.hexadecimal.32bit"); ContentRegistry::HexEditor::addDataVisualizer<DataVisualizerHexadecimal<u64>>("hex.builtin.visualizer.hexadecimal.64bit"); ContentRegistry::HexEditor::addDataVisualizer<DataVisualizerDecimal<u8>>("hex.builtin.visualizer.decimal.unsigned.8bit"); ContentRegistry::HexEditor::addDataVisualizer<DataVisualizerDecimal<u16>>("hex.builtin.visualizer.decimal.unsigned.16bit"); ContentRegistry::HexEditor::addDataVisualizer<DataVisualizerDecimal<u32>>("hex.builtin.visualizer.decimal.unsigned.32bit"); ContentRegistry::HexEditor::addDataVisualizer<DataVisualizerDecimal<u64>>("hex.builtin.visualizer.decimal.unsigned.64bit"); ContentRegistry::HexEditor::addDataVisualizer<DataVisualizerDecimal<i8>>("hex.builtin.visualizer.decimal.signed.8bit"); ContentRegistry::HexEditor::addDataVisualizer<DataVisualizerDecimal<i16>>("hex.builtin.visualizer.decimal.signed.16bit"); ContentRegistry::HexEditor::addDataVisualizer<DataVisualizerDecimal<i32>>("hex.builtin.visualizer.decimal.signed.32bit"); ContentRegistry::HexEditor::addDataVisualizer<DataVisualizerDecimal<i64>>("hex.builtin.visualizer.decimal.signed.64bit"); ContentRegistry::HexEditor::addDataVisualizer<DataVisualizerFloatingPoint<Float16>>("hex.builtin.visualizer.floating_point.16bit"); ContentRegistry::HexEditor::addDataVisualizer<DataVisualizerFloatingPoint<float>>("hex.builtin.visualizer.floating_point.32bit"); ContentRegistry::HexEditor::addDataVisualizer<DataVisualizerFloatingPoint<double>>("hex.builtin.visualizer.floating_point.64bit"); ContentRegistry::HexEditor::addDataVisualizer<DataVisualizerRGBA8>(); ContentRegistry::HexEditor::addDataVisualizer<DataVisualizerHexii>(); ContentRegistry::HexEditor::addDataVisualizer<DataVisualizerBinary>(); } }
14,082
C++
.cpp
248
44.870968
273
0.634336
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
155
views.cpp
WerWolv_ImHex/plugins/builtin/source/content/views.cpp
#include "content/views/view_hex_editor.hpp" #include "content/views/view_pattern_editor.hpp" #include "content/views/view_pattern_data.hpp" #include "content/views/view_information.hpp" #include "content/views/view_about.hpp" #include "content/views/view_tools.hpp" #include "content/views/view_data_inspector.hpp" #include "content/views/view_bookmarks.hpp" #include "content/views/view_patches.hpp" #include "content/views/view_command_palette.hpp" #include "content/views/view_settings.hpp" #include "content/views/view_data_processor.hpp" #include "content/views/view_constants.hpp" #include "content/views/view_store.hpp" #include "content/views/view_provider_settings.hpp" #include "content/views/view_find.hpp" #include "content/views/view_theme_manager.hpp" #include "content/views/view_logs.hpp" #include "content/views/view_achievements.hpp" #include "content/views/view_highlight_rules.hpp" #include "content/views/view_tutorials.hpp" #include <hex/api/layout_manager.hpp> namespace hex::plugin::builtin { void registerViews() { ContentRegistry::Views::add<ViewHexEditor>(); ContentRegistry::Views::add<ViewPatternEditor>(); ContentRegistry::Views::add<ViewPatternData>(); ContentRegistry::Views::add<ViewDataInspector>(); ContentRegistry::Views::add<ViewInformation>(); ContentRegistry::Views::add<ViewBookmarks>(); ContentRegistry::Views::add<ViewPatches>(); ContentRegistry::Views::add<ViewTools>(); ContentRegistry::Views::add<ViewCommandPalette>(); ContentRegistry::Views::add<ViewAbout>(); ContentRegistry::Views::add<ViewSettings>(); ContentRegistry::Views::add<ViewDataProcessor>(); ContentRegistry::Views::add<ViewConstants>(); ContentRegistry::Views::add<ViewStore>(); ContentRegistry::Views::add<ViewProviderSettings>(); ContentRegistry::Views::add<ViewFind>(); ContentRegistry::Views::add<ViewThemeManager>(); ContentRegistry::Views::add<ViewLogs>(); ContentRegistry::Views::add<ViewAchievements>(); ContentRegistry::Views::add<ViewHighlightRules>(); ContentRegistry::Views::add<ViewTutorials>(); LayoutManager::registerLoadCallback([](std::string_view line) { for (auto &[name, view] : ContentRegistry::Views::impl::getEntries()) { if (!view->shouldStoreWindowState()) continue; std::string format = hex::format("{}=%d", view->getUnlocalizedName().get()); sscanf(line.data(), format.c_str(), &view->getWindowOpenState()); } }); LayoutManager::registerStoreCallback([](ImGuiTextBuffer *buffer) { for (auto &[name, view] : ContentRegistry::Views::impl::getEntries()) { if (!view->shouldStoreWindowState()) continue; buffer->appendf("%s=%d\n", name.c_str(), view->getWindowOpenState()); } }); } }
3,003
C++
.cpp
62
41.241935
92
0.684282
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
156
providers.cpp
WerWolv_ImHex/plugins/builtin/source/content/providers.cpp
#include <hex/api/content_registry.hpp> #include "content/providers/gdb_provider.hpp" #include "content/providers/file_provider.hpp" #include "content/providers/null_provider.hpp" #include "content/providers/disk_provider.hpp" #include "content/providers/intel_hex_provider.hpp" #include "content/providers/motorola_srec_provider.hpp" #include "content/providers/memory_file_provider.hpp" #include "content/providers/view_provider.hpp" #include <content/providers/process_memory_provider.hpp> #include <content/providers/base64_provider.hpp> #include <popups/popup_notification.hpp> #include <hex/api/project_file_manager.hpp> #include <hex/api/task_manager.hpp> #include <hex/helpers/fmt.hpp> #include <nlohmann/json.hpp> #include <toasts/toast_notification.hpp> #include <wolv/utils/guards.hpp> namespace hex::plugin::builtin { void registerProviders() { ContentRegistry::Provider::add<FileProvider>(false); ContentRegistry::Provider::add<NullProvider>(false); #if !defined(OS_WEB) ContentRegistry::Provider::add<DiskProvider>(); #endif ContentRegistry::Provider::add<GDBProvider>(); ContentRegistry::Provider::add<IntelHexProvider>(); ContentRegistry::Provider::add<MotorolaSRECProvider>(); ContentRegistry::Provider::add<Base64Provider>(); ContentRegistry::Provider::add<MemoryFileProvider>(false); ContentRegistry::Provider::add<ViewProvider>(false); #if defined(OS_WINDOWS) || defined(OS_MACOS) || (defined(OS_LINUX) && !defined(OS_FREEBSD)) ContentRegistry::Provider::add<ProcessMemoryProvider>(); #endif ProjectFile::registerHandler({ .basePath = "providers", .required = true, .load = [](const std::fs::path &basePath, const Tar &tar) { auto json = nlohmann::json::parse(tar.readString(basePath / "providers.json")); auto providerIds = json.at("providers").get<std::vector<int>>(); bool success = true; std::map<hex::prv::Provider*, std::string> providerWarnings; for (const auto &id : providerIds) { auto providerSettings = nlohmann::json::parse(tar.readString(basePath / hex::format("{}.json", id))); auto providerType = providerSettings.at("type").get<std::string>(); auto newProvider = ImHexApi::Provider::createProvider(providerType, true, false); ON_SCOPE_EXIT { if (!success) { for (auto &task : TaskManager::getRunningTasks()) task->interrupt(); TaskManager::runWhenTasksFinished([]{ for (const auto &provider : ImHexApi::Provider::getProviders()) ImHexApi::Provider::remove(provider, true); }); } }; if (newProvider == nullptr) { // If a provider is not created, it will be overwritten when saving the project, // so we should prevent the project from loading at all ui::ToastError::open( hex::format("hex.builtin.popup.error.project.load"_lang, hex::format("hex.builtin.popup.error.project.load.create_provider"_lang, providerType) ) ); success = false; break; } newProvider->setID(id); bool loaded = false; try { newProvider->loadSettings(providerSettings.at("settings")); loaded = true; } catch (const std::exception &e){ providerWarnings[newProvider] = e.what(); } if (loaded) { if (!newProvider->open() || !newProvider->isAvailable() || !newProvider->isReadable()) { providerWarnings[newProvider] = newProvider->getErrorMessage(); } else { EventProviderOpened::post(newProvider); } } } std::string warningMessage; for (const auto &warning : providerWarnings){ ImHexApi::Provider::remove(warning.first); warningMessage.append( hex::format("\n - {} : {}", warning.first->getName(), warning.second)); } // If no providers were opened, display an error with // the warnings that happened when opening them if (ImHexApi::Provider::getProviders().empty()) { ui::ToastError::open(hex::format("{}{}", "hex.builtin.popup.error.project.load"_lang, "hex.builtin.popup.error.project.load.no_providers"_lang, warningMessage)); return false; } else { // Else, if there are warnings, still display them if (warningMessage.empty()) { return true; } else { ui::ToastWarning::open(hex::format("hex.builtin.popup.error.project.load.some_providers_failed"_lang, warningMessage)); } return success; } }, .store = [](const std::fs::path &basePath, const Tar &tar) { std::vector<int> providerIds; for (const auto &provider : ImHexApi::Provider::getProviders()) { auto id = provider->getID(); providerIds.push_back(id); nlohmann::json json; json["type"] = provider->getTypeName(); json["settings"] = provider->storeSettings({}); tar.writeString(basePath / hex::format("{}.json", id), json.dump(4)); } tar.writeString(basePath / "providers.json", nlohmann::json({ { "providers", providerIds } }).dump(4) ); return true; } }); } }
6,428
C++
.cpp
122
36.114754
181
0.53589
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
157
init_tasks.cpp
WerWolv_ImHex/plugins/builtin/source/content/init_tasks.cpp
#include <hex/api/imhex_api.hpp> #include <hex/api/content_registry.hpp> #include <hex/api/event_manager.hpp> #include <hex/api_urls.hpp> #include <hex/api/task_manager.hpp> #include <hex/helpers/http_requests.hpp> #include <hex/helpers/logger.hpp> #include <wolv/hash/uuid.hpp> namespace hex::plugin::builtin { namespace { using namespace std::literals::string_literals; bool checkForUpdatesSync() { int checkForUpdates = ContentRegistry::Settings::read<int>("hex.builtin.setting.general", "hex.builtin.setting.general.server_contact", 2); // Check if we should check for updates if (checkForUpdates == 1) { HttpRequest request("GET", GitHubApiURL + "/releases/latest"s); // Query the GitHub API for the latest release version auto response = request.execute().get(); if (response.getStatusCode() != 200) return false; nlohmann::json releases; try { releases = nlohmann::json::parse(response.getData()); } catch (const std::exception &) { return false; } // Check if the response is valid if (!releases.contains("tag_name") || !releases["tag_name"].is_string()) return false; // Convert the current version string to a format that can be compared to the latest release auto versionString = ImHexApi::System::getImHexVersion(); size_t versionLength = std::min(versionString.find_first_of('-'), versionString.length()); auto currVersion = "v" + versionString.substr(0, versionLength); // Get the latest release version string auto latestVersion = releases["tag_name"].get<std::string_view>(); // Check if the latest release is different from the current version if (latestVersion != currVersion) ImHexApi::System::impl::addInitArgument("update-available", latestVersion.data()); // Check if there is a telemetry uuid auto uuid = ContentRegistry::Settings::read<std::string>("hex.builtin.setting.general", "hex.builtin.setting.general.uuid", ""); if (uuid.empty()) { // Generate a new uuid uuid = wolv::hash::generateUUID(); // Save ContentRegistry::Settings::write<std::string>("hex.builtin.setting.general", "hex.builtin.setting.general.uuid", uuid); } TaskManager::createBackgroundTask("hex.builtin.task.sending_statistics"_lang, [uuid, versionString](auto&) { // To avoid potentially flooding our database with lots of dead users // from people just visiting the website, don't send telemetry data from // the web version #if defined(OS_WEB) return; #endif // Make telemetry request nlohmann::json telemetry = { { "uuid", uuid }, { "format_version", "1" }, { "imhex_version", versionString }, { "imhex_commit", fmt::format("{}@{}", ImHexApi::System::getCommitHash(true), ImHexApi::System::getCommitBranch()) }, { "install_type", ImHexApi::System::isPortableVersion() ? "Portable" : "Installed" }, { "os", ImHexApi::System::getOSName() }, { "os_version", ImHexApi::System::getOSVersion() }, { "arch", ImHexApi::System::getArchitecture() }, { "gpu_vendor", ImHexApi::System::getGPUVendor() } }; HttpRequest telemetryRequest("POST", ImHexApiURL + "/telemetry"s); telemetryRequest.setTimeout(500); telemetryRequest.setBody(telemetry.dump()); telemetryRequest.addHeader("Content-Type", "application/json"); // Execute request telemetryRequest.execute(); }); } return true; } bool checkForUpdates() { TaskManager::createBackgroundTask("hex.builtin.task.check_updates"_lang, [](auto&) { checkForUpdatesSync(); }); return true; } bool configureUIScale() { EventDPIChanged::subscribe([](float, float newScaling) { int interfaceScaleSetting = int(ContentRegistry::Settings::read<float>("hex.builtin.setting.interface", "hex.builtin.setting.interface.scaling_factor", 0.0F) * 10.0F); float interfaceScaling; if (interfaceScaleSetting == 0) interfaceScaling = newScaling; else interfaceScaling = interfaceScaleSetting / 10.0F; ImHexApi::System::impl::setGlobalScale(interfaceScaling); }); const auto nativeScale = ImHexApi::System::getNativeScale(); EventDPIChanged::post(nativeScale, nativeScale); return true; } bool loadWindowSettings() { bool multiWindowEnabled = ContentRegistry::Settings::read<bool>("hex.builtin.setting.interface", "hex.builtin.setting.interface.multi_windows", false); ImHexApi::System::impl::setMultiWindowMode(multiWindowEnabled); bool restoreWindowPos = ContentRegistry::Settings::read<bool>("hex.builtin.setting.interface", "hex.builtin.setting.interface.restore_window_pos", false); if (restoreWindowPos) { ImHexApi::System::InitialWindowProperties properties = {}; properties.maximized = ContentRegistry::Settings::read<bool>("hex.builtin.setting.interface", "hex.builtin.setting.interface.window.maximized", 0); properties.x = ContentRegistry::Settings::read<int>("hex.builtin.setting.interface", "hex.builtin.setting.interface.window.x", 0); properties.y = ContentRegistry::Settings::read<int>("hex.builtin.setting.interface", "hex.builtin.setting.interface.window.y", 0); properties.width = ContentRegistry::Settings::read<int>("hex.builtin.setting.interface", "hex.builtin.setting.interface.window.width", 0); properties.height = ContentRegistry::Settings::read<int>("hex.builtin.setting.interface", "hex.builtin.setting.interface.window.height", 0); ImHexApi::System::impl::setInitialWindowProperties(properties); } return true; } } void addInitTasks() { ImHexApi::System::addStartupTask("Load Window Settings", false, loadWindowSettings); ImHexApi::System::addStartupTask("Configuring UI scale", false, configureUIScale); ImHexApi::System::addStartupTask("Checking for updates", true, checkForUpdates); } }
7,163
C++
.cpp
115
46.4
183
0.587514
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
158
main_menu_items.cpp
WerWolv_ImHex/plugins/builtin/source/content/main_menu_items.cpp
#include <hex/api/content_registry.hpp> #include <imgui.h> #include <implot.h> #include <hex/ui/view.hpp> #include <hex/api/shortcut_manager.hpp> #include <hex/api/project_file_manager.hpp> #include <hex/api/layout_manager.hpp> #include <hex/api/achievement_manager.hpp> #include <hex/api/tutorial_manager.hpp> #include <hex/helpers/crypto.hpp> #include <hex/helpers/patches.hpp> #include <hex/helpers/debugging.hpp> #include <content/global_actions.hpp> #include <toasts/toast_notification.hpp> #include <popups/popup_text_input.hpp> #include <hex/api/workspace_manager.hpp> #include <wolv/io/file.hpp> #include <wolv/literals.hpp> #include <romfs/romfs.hpp> using namespace std::literals::string_literals; using namespace wolv::literals; namespace hex::plugin::builtin { namespace { bool noRunningTasks() { return TaskManager::getRunningTaskCount() == 0; } bool noRunningTaskAndValidProvider() { return noRunningTasks() && ImHexApi::Provider::isValid(); } bool noRunningTaskAndWritableProvider() { return noRunningTasks() && ImHexApi::Provider::isValid() && ImHexApi::Provider::get()->isWritable(); } } namespace { void handleIPSError(IPSError error) { TaskManager::doLater([error]{ switch (error) { case IPSError::InvalidPatchHeader: ui::ToastError::open("hex.builtin.menu.file.export.ips.popup.invalid_patch_header_error"_lang); break; case IPSError::AddressOutOfRange: ui::ToastError::open("hex.builtin.menu.file.export.ips.popup.address_out_of_range_error"_lang); break; case IPSError::PatchTooLarge: ui::ToastError::open("hex.builtin.menu.file.export.ips.popup.patch_too_large_error"_lang); break; case IPSError::InvalidPatchFormat: ui::ToastError::open("hex.builtin.menu.file.export.ips.popup.invalid_patch_format_error"_lang); break; case IPSError::MissingEOF: ui::ToastError::open("hex.builtin.menu.file.export.ips.popup.missing_eof_error"_lang); break; } }); } } // Import namespace { void importIPSPatch() { fs::openFileBrowser(fs::DialogMode::Open, {}, [](const auto &path) { TaskManager::createTask("hex.ui.common.processing"_lang, TaskManager::NoProgress, [path](auto &task) { auto patchData = wolv::io::File(path, wolv::io::File::Mode::Read).readVector(); auto patch = Patches::fromIPSPatch(patchData); if (!patch.has_value()) { handleIPSError(patch.error()); return; } task.setMaxValue(patch->get().size()); auto provider = ImHexApi::Provider::get(); for (auto &[address, value] : patch->get()) { provider->write(address, &value, sizeof(value)); task.increment(); } provider->getUndoStack().groupOperations(patch->get().size(), "hex.builtin.undo_operation.patches"); }); }); } void importIPS32Patch() { fs::openFileBrowser(fs::DialogMode::Open, {}, [](const auto &path) { TaskManager::createTask("hex.ui.common.processing"_lang, TaskManager::NoProgress, [path](auto &task) { auto patchData = wolv::io::File(path, wolv::io::File::Mode::Read).readVector(); auto patch = Patches::fromIPS32Patch(patchData); if (!patch.has_value()) { handleIPSError(patch.error()); return; } task.setMaxValue(patch->get().size()); auto provider = ImHexApi::Provider::get(); for (auto &[address, value] : patch->get()) { provider->write(address, &value, sizeof(value)); task.increment(); } provider->getUndoStack().groupOperations(patch->get().size(), "hex.builtin.undo_operation.patches"); }); }); } void importModifiedFile() { fs::openFileBrowser(fs::DialogMode::Open, {}, [](const auto &path) { TaskManager::createTask("hex.ui.common.processing"_lang, TaskManager::NoProgress, [path](auto &task) { auto provider = ImHexApi::Provider::get(); auto patchData = wolv::io::File(path, wolv::io::File::Mode::Read).readVector(); if (patchData.size() != provider->getActualSize()) { ui::ToastError::open("hex.builtin.menu.file.import.modified_file.popup.invalid_size"_lang); return; } const auto baseAddress = provider->getBaseAddress(); std::map<u64, u8> patches; for (u64 i = 0; i < patchData.size(); i++) { u8 value = 0; provider->read(baseAddress + i, &value, 1); if (value != patchData[i]) patches[baseAddress + i] = patchData[i]; } task.setMaxValue(patches.size()); for (auto &[address, value] : patches) { provider->write(address, &value, sizeof(value)); task.increment(); } provider->getUndoStack().groupOperations(patches.size(), "hex.builtin.undo_operation.patches"); }); }); } } // Export namespace { void exportBase64() { fs::openFileBrowser(fs::DialogMode::Save, {}, [](const auto &path) { TaskManager::createTask("hex.ui.common.processing"_lang, TaskManager::NoProgress, [path](auto &) { wolv::io::File outputFile(path, wolv::io::File::Mode::Create); if (!outputFile.isValid()) { TaskManager::doLater([] { ui::ToastError::open("hex.builtin.menu.file.export.error.create_file"_lang); }); return; } auto provider = ImHexApi::Provider::get(); std::vector<u8> bytes(5_MiB); for (u64 address = 0; address < provider->getActualSize(); address += bytes.size()) { bytes.resize(std::min<u64>(bytes.size(), provider->getActualSize() - address)); provider->read(provider->getBaseAddress() + address, bytes.data(), bytes.size()); outputFile.writeVector(crypt::encode64(bytes)); } }); }); } void exportSelectionToFile() { fs::openFileBrowser(fs::DialogMode::Save, {}, [](const auto &path) { TaskManager::createTask("hex.ui.common.processing"_lang, TaskManager::NoProgress, [path](auto &task) { wolv::io::File outputFile(path, wolv::io::File::Mode::Create); if (!outputFile.isValid()) { TaskManager::doLater([] { ui::ToastError::open("hex.builtin.menu.file.export.error.create_file"_lang); }); return; } auto provider = ImHexApi::Provider::get(); std::vector<u8> bytes(5_MiB); auto selection = ImHexApi::HexEditor::getSelection(); for (u64 address = selection->getStartAddress(); address <= selection->getEndAddress(); address += bytes.size()) { bytes.resize(std::min<u64>(bytes.size(), selection->getEndAddress() - address + 1)); provider->read(address, bytes.data(), bytes.size()); outputFile.writeVector(bytes); task.update(); } }); }); } void drawExportLanguageMenu() { for (const auto &formatter : ContentRegistry::DataFormatter::impl::getExportMenuEntries()) { if (ImGui::MenuItem(Lang(formatter.unlocalizedName), nullptr, false, ImHexApi::Provider::get()->getActualSize() > 0)) { fs::openFileBrowser(fs::DialogMode::Save, {}, [&formatter](const auto &path) { TaskManager::createTask("hex.builtin.task.exporting_data"_lang, TaskManager::NoProgress, [&formatter, path](auto&){ auto provider = ImHexApi::Provider::get(); auto selection = ImHexApi::HexEditor::getSelection() .value_or( ImHexApi::HexEditor::ProviderRegion { { provider->getBaseAddress(), provider->getSize() }, provider }); auto result = formatter.callback(provider, selection.getStartAddress(), selection.getSize()); wolv::io::File file(path, wolv::io::File::Mode::Create); if (!file.isValid()) { TaskManager::doLater([] { ui::ToastError::open("hex.builtin.menu.file.export.as_language.popup.export_error"_lang); }); return; } file.writeString(result); }); }); } } } void exportReport() { TaskManager::createTask("hex.ui.common.processing"_lang, TaskManager::NoProgress, [](auto &) { std::string data; for (const auto &provider : ImHexApi::Provider::getProviders()) { data += hex::format("# {}", provider->getName()); data += "\n\n"; for (const auto &generator : ContentRegistry::Reports::impl::getGenerators()) { data += generator.callback(provider); data += "\n\n"; } data += "\n\n"; } TaskManager::doLater([data] { fs::openFileBrowser(fs::DialogMode::Save, { { "Markdown File", "md" }}, [&data](const auto &path) { auto file = wolv::io::File(path, wolv::io::File::Mode::Create); if (!file.isValid()) { ui::ToastError::open("hex.builtin.menu.file.export.report.popup.export_error"_lang); return; } file.writeString(data); }); }); }); } void exportIPSPatch() { auto provider = ImHexApi::Provider::get(); auto patches = Patches::fromProvider(provider); if (!patches.has_value()) { handleIPSError(patches.error()); return; } // Make sure there's no patch at address 0x00454F46 because that would cause the patch to contain the sequence "EOF" which signals the end of the patch if (!patches->get().contains(0x00454F45) && patches->get().contains(0x00454F46)) { u8 value = 0; provider->read(0x00454F45, &value, sizeof(u8)); patches->get().at(0x00454F45) = value; } TaskManager::createTask("hex.ui.common.processing"_lang, TaskManager::NoProgress, [patches](auto &) { auto data = patches->toIPSPatch(); TaskManager::doLater([data] { fs::openFileBrowser(fs::DialogMode::Save, {}, [&data](const auto &path) { auto file = wolv::io::File(path, wolv::io::File::Mode::Create); if (!file.isValid()) { ui::ToastError::open("hex.builtin.menu.file.export.ips.popup.export_error"_lang); return; } if (data.has_value()) { file.writeVector(data.value()); } else { handleIPSError(data.error()); } AchievementManager::unlockAchievement("hex.builtin.achievement.hex_editor", "hex.builtin.achievement.hex_editor.create_patch.name"); }); }); }); } void exportIPS32Patch() { auto provider = ImHexApi::Provider::get(); auto patches = Patches::fromProvider(provider); if (!patches.has_value()) { handleIPSError(patches.error()); return; } // Make sure there's no patch at address 0x45454F46 because that would cause the patch to contain the sequence "*EOF" which signals the end of the patch if (!patches->get().contains(0x45454F45) && patches->get().contains(0x45454F46)) { u8 value = 0; provider->read(0x45454F45, &value, sizeof(u8)); patches->get().at(0x45454F45) = value; } TaskManager::createTask("hex.ui.common.processing"_lang, TaskManager::NoProgress, [patches](auto &) { auto data = patches->toIPS32Patch(); TaskManager::doLater([data] { fs::openFileBrowser(fs::DialogMode::Save, {}, [&data](const auto &path) { auto file = wolv::io::File(path, wolv::io::File::Mode::Create); if (!file.isValid()) { ui::ToastError::open("hex.builtin.menu.file.export.ips.popup.export_error"_lang); return; } if (data.has_value()) { file.writeVector(data.value()); } else { handleIPSError(data.error()); } AchievementManager::unlockAchievement("hex.builtin.achievement.hex_editor", "hex.builtin.achievement.hex_editor.create_patch.name"); }); }); }); } } /** * @brief returns true if there is a currently selected provider, and it is possibl to dump data from it */ bool isProviderDumpable() { auto provider = ImHexApi::Provider::get(); return ImHexApi::Provider::isValid() && provider->isDumpable(); } static void createFileMenu() { ContentRegistry::Interface::registerMainMenuItem("hex.builtin.menu.file", 1000); /* Create File */ ContentRegistry::Interface::addMenuItem({ "hex.builtin.menu.file", "hex.builtin.menu.file.create_file" }, ICON_VS_FILE, 1050, CTRLCMD + Keys::N, [] { auto newProvider = hex::ImHexApi::Provider::createProvider("hex.builtin.provider.mem_file", true); if (newProvider != nullptr && !newProvider->open()) hex::ImHexApi::Provider::remove(newProvider); else EventProviderOpened::post(newProvider); }, noRunningTasks); /* Open File */ ContentRegistry::Interface::addMenuItem({ "hex.builtin.menu.file", "hex.builtin.menu.file.open_file" }, ICON_VS_FOLDER_OPENED, 1100, CTRLCMD + Keys::O, [] { RequestOpenWindow::post("Open File"); }, noRunningTasks); /* Open Other */ ContentRegistry::Interface::addMenuItemSubMenu({ "hex.builtin.menu.file", "hex.builtin.menu.file.open_other"}, ICON_VS_TELESCOPE, 1150, [] { for (const auto &unlocalizedProviderName : ContentRegistry::Provider::impl::getEntries()) { if (ImGui::MenuItem(Lang(unlocalizedProviderName))) ImHexApi::Provider::createProvider(unlocalizedProviderName); } }, noRunningTasks); /* Reload Provider */ ContentRegistry::Interface::addMenuItem({ "hex.builtin.menu.file", "hex.builtin.menu.file.reload_provider"}, ICON_VS_ARROW_SWAP, 1250, CTRLCMD + Keys::R, [] { auto provider = ImHexApi::Provider::get(); provider->close(); if (!provider->open()) ImHexApi::Provider::remove(provider, true); EventDataChanged::post(provider); }, noRunningTaskAndValidProvider); /* Project open / save */ ContentRegistry::Interface::addMenuItemSubMenu({ "hex.builtin.menu.file", "hex.builtin.menu.file.project" }, ICON_VS_NOTEBOOK, 1400, []{}, noRunningTasks); ContentRegistry::Interface::addMenuItem({ "hex.builtin.menu.file", "hex.builtin.menu.file.project", "hex.builtin.menu.file.project.open" }, ICON_VS_ROOT_FOLDER_OPENED, 1410, ALT + Keys::O, openProject, noRunningTasks); ContentRegistry::Interface::addMenuItem({ "hex.builtin.menu.file", "hex.builtin.menu.file.project", "hex.builtin.menu.file.project.save" }, ICON_VS_SAVE, 1450, ALT + Keys::S, saveProject, [&] { return noRunningTaskAndValidProvider() && ProjectFile::hasPath(); }); ContentRegistry::Interface::addMenuItem({ "hex.builtin.menu.file", "hex.builtin.menu.file.project", "hex.builtin.menu.file.project.save_as" }, ICON_VS_SAVE_AS, 1500, ALT + SHIFT + Keys::S, saveProjectAs, noRunningTaskAndValidProvider); ContentRegistry::Interface::addMenuItemSeparator({ "hex.builtin.menu.file" }, 2000); /* Import */ { ContentRegistry::Interface::addMenuItemSubMenu({ "hex.builtin.menu.file", "hex.builtin.menu.file.import" }, ICON_VS_SIGN_IN, 2140, []{}, noRunningTaskAndValidProvider); /* IPS */ ContentRegistry::Interface::addMenuItem({ "hex.builtin.menu.file", "hex.builtin.menu.file.import", "hex.builtin.menu.file.import.ips"}, ICON_VS_GIT_PULL_REQUEST_NEW_CHANGES, 2150, Shortcut::None, importIPSPatch, noRunningTaskAndWritableProvider); /* IPS32 */ ContentRegistry::Interface::addMenuItem({ "hex.builtin.menu.file", "hex.builtin.menu.file.import", "hex.builtin.menu.file.import.ips32"}, ICON_VS_GIT_PULL_REQUEST_NEW_CHANGES, 2200, Shortcut::None, importIPS32Patch, noRunningTaskAndWritableProvider); /* Modified File */ ContentRegistry::Interface::addMenuItem({ "hex.builtin.menu.file", "hex.builtin.menu.file.import", "hex.builtin.menu.file.import.modified_file" }, ICON_VS_FILES, 2300, Shortcut::None, importModifiedFile, noRunningTaskAndWritableProvider); } /* Export */ /* Only make them accessible if the current provider is dumpable */ { ContentRegistry::Interface::addMenuItemSubMenu({ "hex.builtin.menu.file", "hex.builtin.menu.file.export" }, ICON_VS_SIGN_OUT, 6000, []{}, isProviderDumpable); /* Selection to File */ ContentRegistry::Interface::addMenuItem({ "hex.builtin.menu.file", "hex.builtin.menu.file.export", "hex.builtin.menu.file.export.selection_to_file" }, ICON_VS_FILE_BINARY, 6010, Shortcut::None, exportSelectionToFile, ImHexApi::HexEditor::isSelectionValid); /* Base 64 */ ContentRegistry::Interface::addMenuItem({ "hex.builtin.menu.file", "hex.builtin.menu.file.export", "hex.builtin.menu.file.export.base64" }, ICON_VS_NOTE, 6020, Shortcut::None, exportBase64, isProviderDumpable); /* Language */ ContentRegistry::Interface::addMenuItemSubMenu({ "hex.builtin.menu.file", "hex.builtin.menu.file.export", "hex.builtin.menu.file.export.as_language" }, ICON_VS_CODE, 6030, drawExportLanguageMenu, isProviderDumpable); /* Report */ ContentRegistry::Interface::addMenuItem({ "hex.builtin.menu.file", "hex.builtin.menu.file.export", "hex.builtin.menu.file.export.report" }, ICON_VS_MARKDOWN, 6040, Shortcut::None, exportReport, ImHexApi::Provider::isValid); ContentRegistry::Interface::addMenuItemSeparator({ "hex.builtin.menu.file", "hex.builtin.menu.file.export" }, 6050); /* IPS */ ContentRegistry::Interface::addMenuItem({ "hex.builtin.menu.file", "hex.builtin.menu.file.export", "hex.builtin.menu.file.export.ips" }, ICON_VS_GIT_PULL_REQUEST_NEW_CHANGES, 6100, Shortcut::None, exportIPSPatch, isProviderDumpable); /* IPS32 */ ContentRegistry::Interface::addMenuItem({ "hex.builtin.menu.file", "hex.builtin.menu.file.export", "hex.builtin.menu.file.export.ips32" }, ICON_VS_GIT_PULL_REQUEST_NEW_CHANGES, 6150, Shortcut::None, exportIPS32Patch, isProviderDumpable); } ContentRegistry::Interface::addMenuItemSeparator({ "hex.builtin.menu.file" }, 10000); /* Close Provider */ ContentRegistry::Interface::addMenuItem({ "hex.builtin.menu.file", "hex.builtin.menu.file.close"}, ICON_VS_CHROME_CLOSE, 10050, CTRLCMD + Keys::W, [] { ImHexApi::Provider::remove(ImHexApi::Provider::get()); }, noRunningTaskAndValidProvider); /* Quit ImHex */ ContentRegistry::Interface::addMenuItem({ "hex.builtin.menu.file", "hex.builtin.menu.file.quit"}, ICON_VS_CLOSE_ALL, 10100, ALT + Keys::F4, [] { ImHexApi::System::closeImHex(); }); } static void createEditMenu() { ContentRegistry::Interface::registerMainMenuItem("hex.builtin.menu.edit", 2000); /* Undo */ ContentRegistry::Interface::addMenuItem({ "hex.builtin.menu.edit", "hex.builtin.menu.edit.undo" }, ICON_VS_DISCARD, 1000, CTRLCMD + Keys::Z, [] { auto provider = ImHexApi::Provider::get(); provider->undo(); }, [&] { return ImHexApi::Provider::isValid() && ImHexApi::Provider::get()->canUndo(); }); /* Redo */ ContentRegistry::Interface::addMenuItem({ "hex.builtin.menu.edit", "hex.builtin.menu.edit.redo" }, ICON_VS_REDO, 1050, CTRLCMD + Keys::Y, [] { auto provider = ImHexApi::Provider::get(); provider->redo(); }, [&] { return ImHexApi::Provider::isValid() && ImHexApi::Provider::get()->canRedo(); }); } static void createViewMenu() { ContentRegistry::Interface::registerMainMenuItem("hex.builtin.menu.view", 3000); #if !defined(OS_WEB) ContentRegistry::Interface::addMenuItem({ "hex.builtin.menu.view", "hex.builtin.menu.view.always_on_top" }, ICON_VS_PINNED, 1000, Keys::F10, [] { static bool state = false; state = !state; glfwSetWindowAttrib(ImHexApi::System::getMainWindowHandle(), GLFW_FLOATING, state); }, []{ return true; }, []{ return glfwGetWindowAttrib(ImHexApi::System::getMainWindowHandle(), GLFW_FLOATING); }); #endif #if !defined(OS_MACOS) && !defined(OS_WEB) ContentRegistry::Interface::addMenuItem({ "hex.builtin.menu.view", "hex.builtin.menu.view.fullscreen" }, ICON_VS_SCREEN_FULL, 2000, Keys::F11, [] { static bool state = false; static ImVec2 position, size; state = !state; const auto window = ImHexApi::System::getMainWindowHandle(); if (state) { position = ImHexApi::System::getMainWindowPosition(); size = ImHexApi::System::getMainWindowSize(); const auto monitor = glfwGetPrimaryMonitor(); const auto videoMode = glfwGetVideoMode(monitor); glfwSetWindowMonitor(window, monitor, 0, 0, videoMode->width, videoMode->height, videoMode->refreshRate); } else { glfwSetWindowMonitor(window, nullptr, position.x, position.y, size.x, size.y, 0); } }, []{ return true; }, []{ return glfwGetWindowMonitor(ImHexApi::System::getMainWindowHandle()) != nullptr; }); #endif #if !defined(OS_WEB) ContentRegistry::Interface::addMenuItemSeparator({ "hex.builtin.menu.view" }, 3000); #endif ContentRegistry::Interface::addMenuItemSubMenu({ "hex.builtin.menu.view" }, 4000, [] { for (auto &[name, view] : ContentRegistry::Views::impl::getEntries()) { if (view->hasViewMenuItemEntry()) { auto &state = view->getWindowOpenState(); if (ImGui::MenuItemEx(Lang(view->getUnlocalizedName()), view->getIcon(), "", state, ImHexApi::Provider::isValid() && !LayoutManager::isLayoutLocked())) state = !state; } } }); } static void createLayoutMenu() { LayoutManager::reload(); ContentRegistry::Interface::addMenuItemSubMenu({ "hex.builtin.menu.workspace", "hex.builtin.menu.workspace.layout" }, ICON_VS_LAYOUT, 1050, []{}, ImHexApi::Provider::isValid); ContentRegistry::Interface::addMenuItem({ "hex.builtin.menu.workspace", "hex.builtin.menu.workspace.layout", "hex.builtin.menu.workspace.layout.save" }, 1100, Shortcut::None, [] { ui::PopupTextInput::open("hex.builtin.popup.save_layout.title", "hex.builtin.popup.save_layout.desc", [](const std::string &name) { LayoutManager::save(name); }); }, ImHexApi::Provider::isValid); ContentRegistry::Interface::addMenuItemSubMenu({ "hex.builtin.menu.workspace", "hex.builtin.menu.workspace.layout" }, ICON_VS_LAYOUT, 1150, [] { bool locked = LayoutManager::isLayoutLocked(); if (ImGui::MenuItemEx("hex.builtin.menu.workspace.layout.lock"_lang, ICON_VS_LOCK, nullptr, locked, ImHexApi::Provider::isValid())) { LayoutManager::lockLayout(!locked); ContentRegistry::Settings::write<bool>("hex.builtin.setting.interface", "hex.builtin.setting.interface.layout_locked", !locked); } }); ContentRegistry::Interface::addMenuItemSeparator({ "hex.builtin.menu.workspace", "hex.builtin.menu.workspace.layout" }, 1200); ContentRegistry::Interface::addMenuItemSubMenu({ "hex.builtin.menu.workspace", "hex.builtin.menu.workspace.layout" }, 2000, [] { for (const auto &path : romfs::list("layouts")) { if (ImGui::MenuItem(wolv::util::capitalizeString(path.stem().string()).c_str(), "", false, ImHexApi::Provider::isValid())) { LayoutManager::loadFromString(std::string(romfs::get(path).string())); } } bool shiftPressed = ImGui::GetIO().KeyShift; for (auto &[name, path] : LayoutManager::getLayouts()) { if (ImGui::MenuItem(hex::format("{}{}", name, shiftPressed ? " " ICON_VS_X : "").c_str(), "", false, ImHexApi::Provider::isValid())) { if (shiftPressed) { LayoutManager::removeLayout(name); break; } else { LayoutManager::load(path); } } } }); } static void createWorkspaceMenu() { ContentRegistry::Interface::registerMainMenuItem("hex.builtin.menu.workspace", 4000); createLayoutMenu(); ContentRegistry::Interface::addMenuItemSeparator({ "hex.builtin.menu.workspace" }, 3000); ContentRegistry::Interface::addMenuItem({ "hex.builtin.menu.workspace", "hex.builtin.menu.workspace.create" }, ICON_VS_REPO_CREATE, 3100, Shortcut::None, [] { ui::PopupTextInput::open("hex.builtin.popup.create_workspace.title", "hex.builtin.popup.create_workspace.desc", [](const std::string &name) { WorkspaceManager::createWorkspace(name); }); }, ImHexApi::Provider::isValid); ContentRegistry::Interface::addMenuItemSubMenu({ "hex.builtin.menu.workspace" }, 3200, [] { const auto &workspaces = WorkspaceManager::getWorkspaces(); bool shiftPressed = ImGui::GetIO().KeyShift; for (auto it = workspaces.begin(); it != workspaces.end(); ++it) { const auto &[name, workspace] = *it; bool canRemove = shiftPressed && !workspace.builtin; if (ImGui::MenuItem(hex::format("{}{}", name, canRemove ? " " ICON_VS_X : "").c_str(), "", it == WorkspaceManager::getCurrentWorkspace(), ImHexApi::Provider::isValid())) { if (canRemove) { WorkspaceManager::removeWorkspace(name); break; } else { WorkspaceManager::switchWorkspace(name); } } } }); } static void createExtrasMenu() { ContentRegistry::Interface::registerMainMenuItem("hex.builtin.menu.extras", 5000); } static void createHelpMenu() { ContentRegistry::Interface::registerMainMenuItem("hex.builtin.menu.help", 6000); } void registerMainMenuEntries() { createFileMenu(); createEditMenu(); createViewMenu(); createWorkspaceMenu(); createExtrasMenu(); createHelpMenu(); } }
31,434
C++
.cpp
522
41.996169
194
0.532883
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
159
window_decoration.cpp
WerWolv_ImHex/plugins/builtin/source/content/window_decoration.cpp
#include <hex/api/content_registry.hpp> #include <hex/api/event_manager.hpp> #include <hex/api/shortcut_manager.hpp> #include <hex/api/task_manager.hpp> #include <hex/api/project_file_manager.hpp> #include <hex/ui/view.hpp> #include <hex/helpers/utils.hpp> #include <imgui.h> #include <imgui_internal.h> #include <hex/ui/imgui_imhex_extensions.h> #include <fonts/codicons_font.h> #include <romfs/romfs.hpp> #include <wolv/utils/guards.hpp> namespace hex::plugin::builtin { // Function that draws the provider popup, defiend in the ui_items.cpp file void drawProviderTooltip(const prv::Provider *provider); namespace { std::string s_windowTitle, s_windowTitleFull; u32 s_searchBarPosition = 0; ImGuiExt::Texture s_logoTexture; bool s_showSearchBar = true; void createNestedMenu(std::span<const UnlocalizedString> menuItems, const char *icon, const Shortcut &shortcut, const ContentRegistry::Interface::impl::MenuCallback &callback, const ContentRegistry::Interface::impl::EnabledCallback &enabledCallback, const ContentRegistry::Interface::impl::SelectedCallback &selectedCallback) { const auto &name = menuItems.front(); if (name.get() == ContentRegistry::Interface::impl::SeparatorValue) { ImGui::Separator(); return; } if (name.get() == ContentRegistry::Interface::impl::SubMenuValue) { callback(); } else if (menuItems.size() == 1) { if (ImGui::MenuItemEx(Lang(name), icon, shortcut.toString().c_str(), selectedCallback(), enabledCallback())) callback(); } else { bool isSubmenu = (menuItems.begin() + 1)->get() == ContentRegistry::Interface::impl::SubMenuValue; if (ImGui::BeginMenuEx(Lang(name), std::next(menuItems.begin())->get() == ContentRegistry::Interface::impl::SubMenuValue ? icon : nullptr, isSubmenu ? enabledCallback() : true)) { createNestedMenu({ std::next(menuItems.begin()), menuItems.end() }, icon, shortcut, callback, enabledCallback, selectedCallback); ImGui::EndMenu(); } } } void drawFooter(ImDrawList *drawList, ImVec2 dockSpaceSize) { auto dockId = ImGui::DockSpace(ImGui::GetID("ImHexMainDock"), dockSpaceSize); ImHexApi::System::impl::setMainDockSpaceId(dockId); ImGui::Separator(); ImGui::SetCursorPosX(8); for (const auto &callback : ContentRegistry::Interface::impl::getFooterItems()) { const auto y = ImGui::GetCursorPosY(); const auto prevIdx = drawList->_VtxCurrentIdx; callback(); const auto currIdx = drawList->_VtxCurrentIdx; ImGui::SetCursorPosY(y); // Only draw separator if something was actually drawn if (prevIdx != currIdx) { ImGui::SameLine(); ImGui::SeparatorEx(ImGuiSeparatorFlags_Vertical); ImGui::SameLine(); } } } void drawSidebar(ImVec2 dockSpaceSize, ImVec2 sidebarPos, float sidebarWidth) { static i32 openWindow = -1; u32 index = 0; u32 drawIndex = 0; ImGui::PushID("SideBarWindows"); for (const auto &[icon, callback, enabledCallback] : ContentRegistry::Interface::impl::getSidebarItems()) { ImGui::SetCursorPosY(sidebarPos.y + sidebarWidth * drawIndex); ImGui::PushStyleColor(ImGuiCol_Button, ImGui::GetColorU32(ImGuiCol_MenuBarBg)); ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImGui::GetColorU32(ImGuiCol_ScrollbarGrabActive)); ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImGui::GetColorU32(ImGuiCol_ScrollbarGrabHovered)); if (enabledCallback()) { drawIndex += 1; ImGui::BeginDisabled(!ImHexApi::Provider::isValid()); { if (ImGui::Button(icon.c_str(), ImVec2(sidebarWidth, sidebarWidth))) { if (static_cast<u32>(openWindow) == index) openWindow = -1; else openWindow = index; } } ImGui::EndDisabled(); } ImGui::PopStyleColor(3); auto sideBarFocused = ImGui::IsWindowFocused(); bool open = static_cast<u32>(openWindow) == index; if (open) { ImGui::SetNextWindowPos(ImGui::GetWindowPos() + sidebarPos + ImVec2(sidebarWidth - 1_scaled, -1_scaled)); ImGui::SetNextWindowSizeConstraints(ImVec2(0, dockSpaceSize.y + 5_scaled), ImVec2(FLT_MAX, dockSpaceSize.y + 5_scaled)); ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 1); ImGui::PushStyleColor(ImGuiCol_WindowShadow, 0x00000000); if (ImGui::Begin("SideBarWindow", &open, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse)) { if (ImGui::BeginChild("##Content", ImGui::GetContentRegionAvail())) { callback(); } ImGui::EndChild(); if (!ImGui::IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows) && !sideBarFocused) { openWindow = -1; } } ImGui::End(); ImGui::PopStyleVar(); ImGui::PopStyleColor(); } ImGui::NewLine(); index += 1; } ImGui::PopID(); } void drawTitleBar() { auto titleBarHeight = ImGui::GetCurrentWindowRead()->MenuBarHeight; #if defined (OS_MACOS) titleBarHeight *= 0.7F; #endif auto buttonSize = ImVec2(titleBarHeight * 1.5F, titleBarHeight - 1); ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0)); ImGui::PushStyleColor(ImGuiCol_Button, ImGui::GetColorU32(ImGuiCol_MenuBarBg)); ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImGui::GetColorU32(ImGuiCol_ScrollbarGrabActive)); ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImGui::GetColorU32(ImGuiCol_ScrollbarGrabHovered)); const auto windowSize = ImGui::GetWindowSize(); auto searchBoxSize = ImVec2(s_showSearchBar ? windowSize.x / 2.5 : ImGui::CalcTextSize(s_windowTitle.c_str()).x, titleBarHeight); auto searchBoxPos = ImVec2((windowSize / 2 - searchBoxSize / 2).x, 0); auto titleBarButtonPosY = 0.0F; #if defined(OS_MACOS) searchBoxPos.y = ImGui::GetStyle().FramePadding.y * 2; titleBarButtonPosY = searchBoxPos.y; #else titleBarButtonPosY = 0; if (s_showSearchBar) { searchBoxPos.y = 3_scaled; searchBoxSize.y -= 3_scaled; } #endif s_searchBarPosition = searchBoxPos.x; // Custom titlebar buttons implementation for borderless window mode auto window = ImHexApi::System::getMainWindowHandle(); bool titleBarButtonsVisible = false; if (ImHexApi::System::isBorderlessWindowModeEnabled() && glfwGetWindowMonitor(window) == nullptr) { #if defined(OS_WINDOWS) titleBarButtonsVisible = true; // Draw minimize, restore and maximize buttons ImGui::SetCursorPosX(ImGui::GetWindowWidth() - buttonSize.x * 3); if (ImGuiExt::TitleBarButton(ICON_VS_CHROME_MINIMIZE, buttonSize)) glfwIconifyWindow(window); if (glfwGetWindowAttrib(window, GLFW_MAXIMIZED)) { if (ImGuiExt::TitleBarButton(ICON_VS_CHROME_RESTORE, buttonSize)) glfwRestoreWindow(window); } else { if (ImGuiExt::TitleBarButton(ICON_VS_CHROME_MAXIMIZE, buttonSize)) glfwMaximizeWindow(window); } ImGui::PushStyleColor(ImGuiCol_ButtonActive, 0xFF7A70F1); ImGui::PushStyleColor(ImGuiCol_ButtonHovered, 0xFF2311E8); // Draw close button if (ImGuiExt::TitleBarButton(ICON_VS_CHROME_CLOSE, buttonSize)) { ImHexApi::System::closeImHex(); } ImGui::PopStyleColor(2); #endif } auto &titleBarButtons = ContentRegistry::Interface::impl::getTitlebarButtons(); // Draw custom title bar buttons if (!titleBarButtons.empty()) { ImGui::SetCursorPosX(ImGui::GetWindowWidth() - 7_scaled - buttonSize.x * float((titleBarButtonsVisible ? 4 : 0) + titleBarButtons.size())); if (ImGui::GetCursorPosX() > (searchBoxPos.x + searchBoxSize.x)) { for (const auto &[icon, tooltip, callback] : titleBarButtons) { ImGui::SetCursorPosY(titleBarButtonPosY); if (ImGuiExt::TitleBarButton(icon.c_str(), buttonSize)) { callback(); } ImGuiExt::InfoTooltip(Lang(tooltip)); } } } ImGui::PopStyleColor(3); ImGui::PopStyleVar(); { ImGui::SetCursorPos(searchBoxPos); if (s_showSearchBar) { const auto buttonColor = [](float alpha) { return ImU32(ImColor(ImGui::GetStyleColorVec4(ImGuiCol_DockingEmptyBg) * ImVec4(1, 1, 1, alpha))); }; ImGui::PushStyleColor(ImGuiCol_Button, buttonColor(0.5F)); ImGui::PushStyleColor(ImGuiCol_ButtonHovered, buttonColor(0.7F)); ImGui::PushStyleColor(ImGuiCol_ButtonActive, buttonColor(0.9F)); ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 1.0_scaled); ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 4_scaled); ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, scaled({ 1, 1 })); if (ImGui::Button(s_windowTitle.c_str(), searchBoxSize)) { EventSearchBoxClicked::post(ImGuiMouseButton_Left); } if (ImGui::IsItemClicked(ImGuiMouseButton_Right)) EventSearchBoxClicked::post(ImGuiMouseButton_Right); ImGui::PushTextWrapPos(300_scaled); if (auto provider = ImHexApi::Provider::get(); provider != nullptr) { drawProviderTooltip(ImHexApi::Provider::get()); } else if (!s_windowTitleFull.empty()) { if (ImGuiExt::InfoTooltip()) { ImGui::BeginTooltip(); ImGui::TextUnformatted(s_windowTitleFull.c_str()); ImGui::EndTooltip(); } } ImGui::PopTextWrapPos(); ImGui::PopStyleVar(3); ImGui::PopStyleColor(3); } else { ImGui::TextUnformatted(s_windowTitle.c_str()); } } } void populateMenu(const UnlocalizedString &menuName) { for (auto &[priority, menuItem] : ContentRegistry::Interface::impl::getMenuItems()) { if (!menuName.empty()) { if (menuItem.unlocalizedNames[0] != menuName) continue; } const auto &[ unlocalizedNames, icon, shortcut, view, callback, enabledCallback, selectedCallack, toolbarIndex ] = menuItem; createNestedMenu(unlocalizedNames | std::views::drop(1), icon.glyph.c_str(), *shortcut, callback, enabledCallback, selectedCallack); } } void defineMenu(const UnlocalizedString &menuName) { if (ImGui::BeginMenu(Lang(menuName))) { populateMenu(menuName); ImGui::EndMenu(); } } void drawMenu() { auto cursorPos = ImGui::GetCursorPosX(); u32 fittingItems = 0; const auto &menuItems = ContentRegistry::Interface::impl::getMainMenuItems(); for (const auto &[priority, menuItem] : menuItems) { auto menuName = Lang(menuItem.unlocalizedName); const auto padding = ImGui::GetStyle().FramePadding.x; bool lastItem = (fittingItems + 1) == menuItems.size(); auto width = ImGui::CalcTextSize(menuName).x + padding * (lastItem ? -3.0F : 4.0F); if ((cursorPos + width) > (s_searchBarPosition - ImGui::CalcTextSize(ICON_VS_ELLIPSIS).x - padding * 2)) break; cursorPos += width; fittingItems += 1; } if (fittingItems <= 2) fittingItems = 0; { u32 count = 0; for (const auto &[priority, menuItem] : menuItems) { if (count >= fittingItems) break; defineMenu(menuItem.unlocalizedName); count += 1; } } if (fittingItems == 0) { if (ImGui::BeginMenu(ICON_VS_MENU)) { for (const auto &[priority, menuItem] : menuItems) { defineMenu(menuItem.unlocalizedName); } ImGui::EndMenu(); } } else if (fittingItems < menuItems.size()) { u32 count = 0; if (ImGui::BeginMenu(ICON_VS_ELLIPSIS)) { for (const auto &[priority, menuItem] : menuItems) { ON_SCOPE_EXIT { count += 1; }; if (count < fittingItems) continue; defineMenu(menuItem.unlocalizedName); } ImGui::EndMenu(); } } } void drawMainMenu([[maybe_unused]] float menuBarHeight) { ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0F); ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 0.0F); ImGui::SetNextWindowScroll(ImVec2(0, 0)); #if defined(OS_MACOS) ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(ImGui::GetStyle().FramePadding.x, 8_scaled)); ON_SCOPE_EXIT { ImGui::PopStyleVar(); }; #endif if (ImGui::BeginMainMenuBar()) { ImGui::Dummy({}); auto window = ImHexApi::System::getMainWindowHandle(); ImGui::PopStyleVar(2); if (ImHexApi::System::isBorderlessWindowModeEnabled()) { #if defined(OS_WINDOWS) ImGui::SetCursorPosX(5_scaled); ImGui::Image(s_logoTexture, ImVec2(menuBarHeight, menuBarHeight)); ImGui::SetCursorPosX(5_scaled); ImGui::InvisibleButton("##logo", ImVec2(menuBarHeight, menuBarHeight)); if (ImGui::IsItemHovered() && ImGui::IsAnyMouseDown()) ImGui::OpenPopup("WindowingMenu"); #elif defined(OS_MACOS) if (!isMacosFullScreenModeEnabled(window)) ImGui::SetCursorPosX(68_scaled); #endif } if (ImGui::BeginPopup("WindowingMenu")) { bool maximized = glfwGetWindowAttrib(window, GLFW_MAXIMIZED); ImGui::BeginDisabled(!maximized); if (ImGui::MenuItem(ICON_VS_CHROME_RESTORE " Restore")) glfwRestoreWindow(window); ImGui::EndDisabled(); if (ImGui::MenuItem(ICON_VS_CHROME_MINIMIZE " Minimize")) glfwIconifyWindow(window); ImGui::BeginDisabled(maximized); if (ImGui::MenuItem(ICON_VS_CHROME_MAXIMIZE " Maximize")) glfwMaximizeWindow(window); ImGui::EndDisabled(); ImGui::Separator(); if (ImGui::MenuItem(ICON_VS_CHROME_CLOSE " Close")) ImHexApi::System::closeImHex(); ImGui::EndPopup(); } drawMenu(); drawTitleBar(); #if defined(OS_MACOS) if (ImHexApi::System::isBorderlessWindowModeEnabled()) { const auto windowSize = ImHexApi::System::getMainWindowSize(); const auto menuUnderlaySize = ImVec2(windowSize.x, ImGui::GetCurrentWindowRead()->MenuBarHeight); ImGui::SetCursorPos(ImVec2()); // Drawing this button late allows widgets rendered before it to grab click events, forming an "input underlay" if (ImGui::InvisibleButton("##mainMenuUnderlay", menuUnderlaySize, ImGuiButtonFlags_PressedOnDoubleClick)) { macosHandleTitlebarDoubleClickGesture(window); } } #endif ImGui::EndMainMenuBar(); } else { ImGui::PopStyleVar(2); } } void drawToolbar() { ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0F); ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 0.0F); if (ImGui::BeginMenuBar()) { for (const auto &callback : ContentRegistry::Interface::impl::getToolbarItems()) { callback(); ImGui::SameLine(); } if (auto provider = ImHexApi::Provider::get(); provider != nullptr) { ImGui::BeginDisabled(TaskManager::getRunningTaskCount() > 0); if (ImGui::CloseButton(ImGui::GetID("ProviderCloseButton"), ImGui::GetCursorScreenPos() + ImVec2(ImGui::GetContentRegionAvail().x - 17_scaled, 3_scaled))) { ImHexApi::Provider::remove(provider); } ImGui::EndDisabled(); } ImGui::EndMenuBar(); } ImGui::PopStyleVar(2); } bool anySidebarItemsAvailable() { if (const auto &items = ContentRegistry::Interface::impl::getSidebarItems(); items.empty()) { return false; } else { return std::any_of(items.begin(), items.end(), [](const auto &item) { return item.enabledCallback(); }); } } bool isAnyViewOpen() { const auto &views = ContentRegistry::Views::impl::getEntries(); return std::any_of(views.begin(), views.end(), [](const auto &entry) { return entry.second->getWindowOpenState(); }); } } void addWindowDecoration() { EventFrameBegin::subscribe([]{ AT_FIRST_TIME { s_logoTexture = ImGuiExt::Texture::fromImage(romfs::get("assets/common/icon.png").span(), ImGuiExt::Texture::Filter::Nearest); }; constexpr static ImGuiWindowFlags windowFlags = ImGuiWindowFlags_MenuBar | ImGuiWindowFlags_NoDocking | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoNavFocus | ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse; 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)); ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 0); // Draw main window decoration if (ImGui::Begin("ImHexDockSpace", nullptr, windowFlags)) { ImGui::PopStyleVar(2); const auto drawList = ImGui::GetWindowDrawList(); const auto shouldDrawSidebar = anySidebarItemsAvailable(); const auto menuBarHeight = ImGui::GetCurrentWindowRead()->MenuBarHeight; const auto sidebarPos = ImGui::GetCursorPos(); const auto sidebarWidth = shouldDrawSidebar ? 20_scaled : 0; auto footerHeight = ImGui::GetTextLineHeightWithSpacing() + 1_scaled; #if defined(OS_MACOS) footerHeight += ImGui::GetStyle().WindowPadding.y * 2; #else footerHeight += ImGui::GetStyle().FramePadding.y * 2; #endif const auto dockSpaceSize = ImHexApi::System::getMainWindowSize() - ImVec2(sidebarWidth, menuBarHeight * 2 + footerHeight); ImGui::SetCursorPosX(sidebarWidth); drawFooter(drawList, dockSpaceSize); if (shouldDrawSidebar) { // Draw sidebar background and separator drawList->AddRectFilled( ImGui::GetWindowPos() - ImVec2(0, ImGui::GetStyle().FramePadding.y + 1_scaled), ImGui::GetWindowPos() + ImGui::GetWindowSize() - ImVec2(dockSpaceSize.x, footerHeight - ImGui::GetStyle().FramePadding.y + 1_scaled), ImGui::GetColorU32(ImGuiCol_MenuBarBg) ); ImGui::SetCursorPos(sidebarPos); drawSidebar(dockSpaceSize, sidebarPos, sidebarWidth); if (ImHexApi::Provider::isValid() && isAnyViewOpen()) { drawList->AddLine( ImGui::GetWindowPos() + sidebarPos + ImVec2(sidebarWidth - 1_scaled, menuBarHeight - 2_scaled), ImGui::GetWindowPos() + sidebarPos + ImGui::GetWindowSize() - ImVec2(dockSpaceSize.x + 1_scaled, footerHeight - ImGui::GetStyle().FramePadding.y + 2_scaled + menuBarHeight), ImGui::GetColorU32(ImGuiCol_Separator)); } } drawMainMenu(menuBarHeight); drawToolbar(); } else { ImGui::PopStyleVar(2); } ImGui::End(); ImGui::PopStyleVar(2); // Draw main menu popups for (auto &[priority, menuItem] : ContentRegistry::Interface::impl::getMenuItems()) { const auto &[unlocalizedNames, icon, shortcut, view, callback, enabledCallback, selectedCallback, toolbarIndex] = menuItem; if (ImGui::BeginPopup(unlocalizedNames.front().get().c_str())) { createNestedMenu({ unlocalizedNames.begin() + 1, unlocalizedNames.end() }, icon.glyph.c_str(), *shortcut, callback, enabledCallback, selectedCallback); ImGui::EndPopup(); } } }); constexpr static auto ImHexTitle = "ImHex"; s_windowTitle = ImHexTitle; // Handle updating the window title RequestUpdateWindowTitle::subscribe([] { std::string prefix, postfix; std::string title = ImHexTitle; if (ProjectFile::hasPath()) { // If a project is open, show the project name instead of the file name prefix = "Project "; title = ProjectFile::getPath().stem().string(); if (ImHexApi::Provider::isDirty()) postfix += " (*)"; } else if (ImHexApi::Provider::isValid()) { auto provider = ImHexApi::Provider::get(); if (provider != nullptr) { title = provider->getName(); if (provider->isDirty()) postfix += " (*)"; if (!provider->isWritable() && provider->getActualSize() != 0) postfix += " (Read Only)"; } } s_windowTitle = prefix + hex::limitStringLength(title, 32) + postfix; s_windowTitleFull = prefix + title + postfix; auto window = ImHexApi::System::getMainWindowHandle(); if (window != nullptr) { if (title != ImHexTitle) title = std::string(ImHexTitle) + " - " + title; glfwSetWindowTitle(window, title.c_str()); } }); ContentRegistry::Settings::onChange("hex.builtin.setting.interface", "hex.builtin.setting.interface.show_header_command_palette", [](const ContentRegistry::Settings::SettingsValue &value) { s_showSearchBar = value.get<bool>(true); }); } }
26,116
C++
.cpp
471
37.887473
367
0.544112
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
160
file_extraction.cpp
WerWolv_ImHex/plugins/builtin/source/content/file_extraction.cpp
#include <hex/helpers/fs.hpp> #include <wolv/io/file.hpp> #include <romfs/romfs.hpp> #include <hex/helpers/logger.hpp> #include <hex/helpers/default_paths.hpp> namespace hex::plugin::builtin { void extractBundledFiles() { constexpr static std::array<std::pair<std::string_view, bool>, 2> Paths = { { { "auto_extract", false }, { "always_auto_extract", true } } }; for (const auto &[extractFolder, alwaysExtract] : Paths) { for (const auto &romfsPath : romfs::list(extractFolder)) { for (const auto &imhexPath : paths::getDataPaths(false)) { const auto path = imhexPath / std::fs::relative(romfsPath, extractFolder); log::info("Extracting {} to {}", romfsPath.string(), path.string()); if (!alwaysExtract && wolv::io::fs::exists(path)) continue; wolv::io::File file(path, wolv::io::File::Mode::Create); if (!file.isValid()) continue; auto data = romfs::get(romfsPath).span<u8>(); file.writeBuffer(data.data(), data.size()); if (file.getSize() == data.size()) break; } } } } }
1,368
C++
.cpp
32
29.46875
94
0.50942
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
161
command_line_interface.cpp
WerWolv_ImHex/plugins/builtin/source/content/command_line_interface.cpp
#include <content/command_line_interface.hpp> #include <content/providers/file_provider.hpp> #include <content/helpers/demangle.hpp> #include <hex/api/content_registry.hpp> #include <hex/api/imhex_api.hpp> #include <hex/api/event_manager.hpp> #include <hex/api/plugin_manager.hpp> #include <hex/api/task_manager.hpp> #include <hex/helpers/fmt.hpp> #include <hex/helpers/magic.hpp> #include <hex/helpers/crypto.hpp> #include <hex/helpers/literals.hpp> #include <hex/helpers/utils.hpp> #include <hex/helpers/default_paths.hpp> #include <hex/subcommands/subcommands.hpp> #include <romfs/romfs.hpp> #include <wolv/utils/string.hpp> #include <wolv/math_eval/math_evaluator.hpp> #include <pl/cli/cli.hpp> #include <llvm/Demangle/Demangle.h> namespace hex::plugin::builtin { using namespace hex::literals; void handleVersionCommand(const std::vector<std::string> &args) { hex::unused(args); hex::log::print(std::string(romfs::get("logo.ans").string()), ImHexApi::System::getImHexVersion(), ImHexApi::System::getCommitBranch(), ImHexApi::System::getCommitHash(), __DATE__, __TIME__, ImHexApi::System::isPortableVersion() ? "Portable" : "Installed"); std::exit(EXIT_SUCCESS); } void handleHelpCommand(const std::vector<std::string> &args) { hex::unused(args); hex::log::print( "ImHex - A Hex Editor for Reverse Engineers, Programmers and people who value their retinas when working at 3 AM.\n" "\n" "usage: imhex [subcommand] [options]\n" "Available subcommands:\n" ); size_t longestLongCommand = 0, longestShortCommand = 0; for (const auto &plugin : PluginManager::getPlugins()) { for (const auto &subCommand : plugin.getSubCommands()) { longestLongCommand = std::max(longestLongCommand, subCommand.commandLong.size()); longestShortCommand = std::max(longestShortCommand, subCommand.commandShort.size()); } } for (const auto &plugin : PluginManager::getPlugins()) { for (const auto &subCommand : plugin.getSubCommands()) { hex::log::println(" " "{}" "{: <{}}" "{}" "{}" "{: <{}}" "{}", subCommand.commandShort.empty() ? " " : "-", subCommand.commandShort, longestShortCommand, subCommand.commandShort.empty() ? " " : ", ", subCommand.commandLong.empty() ? " " : "--", subCommand.commandLong, longestLongCommand + 5, subCommand.commandDescription ); } } std::exit(EXIT_SUCCESS); } void handleOpenCommand(const std::vector<std::string> &args) { if (args.empty()) { hex::log::println("No files provided to open."); std::exit(EXIT_FAILURE); } std::vector<std::string> fullPaths; bool doubleDashFound = false; for (auto &arg : args) { // Skip the first argument named `--` if (arg == "--" && !doubleDashFound) { doubleDashFound = true; } else { try { std::fs::path path; try { path = std::fs::weakly_canonical(arg); } catch(std::fs::filesystem_error &) { path = arg; } if (path.empty()) continue; fullPaths.push_back(wolv::util::toUTF8String(path)); } catch (std::exception &e) { log::error("Failed to open file '{}'\n {}", arg, e.what()); } } } if (!fullPaths.empty()) hex::subcommands::forwardSubCommand("open", fullPaths); } void handleCalcCommand(const std::vector<std::string> &args) { if (args.empty()) { hex::log::println("No expression provided!"); hex::log::println("Example: imhex --calc \"5 * 7\""); std::exit(EXIT_FAILURE); } wolv::math_eval::MathEvaluator<long double> evaluator; auto input = hex::format("{}", fmt::join(args, " ")); auto result = evaluator.evaluate(input); if (!result.has_value()) hex::log::println("{}\n> '{}'", evaluator.getLastError().value(), input); else hex::log::println("{}", result.value()); std::exit(EXIT_SUCCESS); } void handlePluginsCommand(const std::vector<std::string> &args) { if (args.empty()) { hex::log::println("Loaded plugins:"); for (const auto &plugin : PluginManager::getPlugins()) { hex::log::print("- \033[1m{}\033[0m", plugin.getPluginName()); hex::log::println(" by {}", plugin.getPluginAuthor()); hex::log::println(" \033[2;3m{}\033[0m", plugin.getPluginDescription()); } std::exit(EXIT_SUCCESS); } else { for (const auto &arg : args) { PluginManager::addLoadPath(reinterpret_cast<const char8_t*>(arg.c_str())); } } } void handleLanguageCommand(const std::vector<std::string> &args) { if (args.empty()) { hex::log::println("usage: imhex --language <language>"); std::exit(EXIT_FAILURE); } ImHexApi::System::impl::addInitArgument("language", args[0]); } void handleVerboseCommand(const std::vector<std::string> &) { hex::log::enableDebugLogging(); } void handleHashCommand(const std::vector<std::string> &args) { if (args.size() != 2) { hex::log::println("usage: imhex --hash <algorithm> <file>"); hex::log::println("Available algorithms: md5, sha1, sha224, sha256, sha384, sha512"); std::exit(EXIT_FAILURE); } const auto &algorithm = args[0]; const auto &filePath = std::fs::path(args[1]); wolv::io::File file(filePath, wolv::io::File::Mode::Read); if (!file.isValid()) { hex::log::println("Failed to open file: {}", wolv::util::toUTF8String(filePath)); std::exit(EXIT_FAILURE); } constexpr static auto toVector = [](const auto &data) { return std::vector<u8>(data.begin(), data.end()); }; std::vector<u8> result; if (algorithm == "md5") { result = toVector(hex::crypt::md5(file.readVector())); } else if (algorithm == "sha1") { result = toVector(hex::crypt::sha1(file.readVector())); } else if (algorithm == "sha224") { result = toVector(hex::crypt::sha224(file.readVector())); } else if (algorithm == "sha256") { result = toVector(hex::crypt::sha256(file.readVector())); } else if (algorithm == "sha384") { result = toVector(hex::crypt::sha384(file.readVector())); } else if (algorithm == "sha512") { result = toVector(hex::crypt::sha512(file.readVector())); } else { hex::log::println("Unknown algorithm: {}", algorithm); hex::log::println("Available algorithms: md5, sha1, sha224, sha256, sha384, sha512"); std::exit(EXIT_FAILURE); } hex::log::println("{}({}) = {}", algorithm, wolv::util::toUTF8String(filePath.filename()), hex::crypt::encode16(result)); std::exit(EXIT_SUCCESS); } void handleEncodeCommand(const std::vector<std::string> &args) { if (args.size() != 2) { hex::log::println("usage: imhex --encode <algorithm> <string>"); hex::log::println("Available algorithms: base64, hex"); std::exit(EXIT_FAILURE); } const auto &algorithm = args[0]; const auto &data = std::vector<u8>(args[1].begin(), args[1].end()); std::string result; if (algorithm == "base64") { auto base64 = hex::crypt::encode64(data); result = std::string(base64.begin(), base64.end()); } else if (algorithm == "hex") { result = hex::crypt::encode16(data); } else { hex::log::println("Unknown algorithm: {}", algorithm); hex::log::println("Available algorithms: base64, hex"); std::exit(EXIT_FAILURE); } hex::log::println("encode_{}({}) = {}", algorithm, args[1], result); std::exit(EXIT_SUCCESS); } void handleDecodeCommand(const std::vector<std::string> &args) { if (args.size() != 2) { hex::log::println("usage: imhex --decode <algorithm> <string>"); hex::log::println("Available algorithms: base64, hex"); std::exit(EXIT_FAILURE); } const auto &algorithm = args[0]; const auto &data = std::vector<u8>(args[1].begin(), args[1].end()); std::string result; if (algorithm == "base64") { auto base64 = hex::crypt::decode64(data); result = std::string(base64.begin(), base64.end()); } else if (algorithm == "hex") { auto base16 = hex::crypt::decode16(std::string(data.begin(), data.end())); result = std::string(base16.begin(), base16.end()); } else { hex::log::println("Unknown algorithm: {}", algorithm); hex::log::println("Available algorithms: base64, hex"); std::exit(EXIT_FAILURE); } hex::log::print("decode_{}({}) = {}", algorithm, args[1], result); std::exit(EXIT_SUCCESS); } void handleMagicCommand(const std::vector<std::string> &args) { if (args.size() != 2) { hex::log::println("usage: imhex --magic <operation> <file>"); hex::log::println("Available operations: mime, desc"); std::exit(EXIT_FAILURE); } if (!magic::compile()) { hex::log::print("Failed to compile magic database!"); std::exit(EXIT_FAILURE); } const auto &operation = args[0]; const auto &filePath = std::fs::path(args[1]); wolv::io::File file(filePath, wolv::io::File::Mode::Read); if (!file.isValid()) { hex::log::println("Failed to open file: {}", wolv::util::toUTF8String(filePath)); std::exit(EXIT_FAILURE); } auto data = file.readVector(std::min<size_t>(file.getSize(), 100_KiB)); if (operation == "mime") { auto result = magic::getMIMEType(data); hex::log::println("{}", result); } else if (operation == "desc") { auto result = magic::getDescription(data); hex::log::println("{}", result); } else { hex::log::println("Unknown operation: {}", operation); hex::log::println("Available operations: mime, desc"); std::exit(EXIT_FAILURE); } std::exit(EXIT_SUCCESS); } void handlePatternLanguageCommand(const std::vector<std::string> &args) { std::vector<std::string> processedArgs = args; if (processedArgs.empty()) { processedArgs.emplace_back("--help"); } else { for (const auto &path : paths::PatternsInclude.read()) processedArgs.emplace_back(hex::format("--includes={}", wolv::util::toUTF8String(path))); } std::exit(pl::cli::executeCommandLineInterface(processedArgs)); } void handleHexdumpCommand(const std::vector<std::string> &args) { if (args.size() < 1 || args.size() > 3) { log::println("usage: imhex --hexdump <file> <offset> <size>"); std::exit(EXIT_FAILURE); } std::fs::path filePath = reinterpret_cast<const char8_t*>(args[0].data()); FileProvider provider; provider.setPath(filePath); if (!provider.open()) { log::println("Failed to open file '{}'", args[0]); std::exit(EXIT_FAILURE); } u64 startAddress = args.size() >= 2 ? std::stoull(args[1], nullptr, 0) : 0x00; u64 size = args.size() >= 3 ? std::stoull(args[2], nullptr, 0) : provider.getActualSize(); size = std::min<u64>(size, provider.getActualSize()); log::print("{}", hex::generateHexView(startAddress, size - startAddress, &provider)); std::exit(EXIT_SUCCESS); } void handleDemangleCommand(const std::vector<std::string> &args) { if (args.size() != 1) { log::println("usage: imhex --demangle <identifier>"); std::exit(EXIT_FAILURE); } log::println("{}", hex::plugin::builtin::demangle(args[0])); std::exit(EXIT_SUCCESS); } void handleSettingsResetCommand(const std::vector<std::string> &) { constexpr static auto ConfirmationString = "YES I AM ABSOLUTELY SURE"; log::println("You're about to reset all settings back to their default. Are you sure you want to continue?"); log::println("Type \"{}\" to continue.", ConfirmationString); std::string input(128, '\x00'); log::print("> "); if (std::fgets(input.data(), input.size() - 1, stdin) == nullptr) std::exit(EXIT_FAILURE); input = wolv::util::trim(input); if (input == ConfirmationString) { log::println("Resetting all settings!"); ContentRegistry::Settings::impl::clear(); ContentRegistry::Settings::impl::store(); std::exit(EXIT_SUCCESS); } else { log::println("Wrong confirmation string. Settings will not be reset."); std::exit(EXIT_FAILURE); } } void registerCommandForwarders() { hex::subcommands::registerSubCommand("open", [](const std::vector<std::string> &args){ for (auto &arg : args) { RequestOpenFile::post(arg); } }); } }
14,252
C++
.cpp
312
34.608974
132
0.55161
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
162
welcome_screen.cpp
WerWolv_ImHex/plugins/builtin/source/content/welcome_screen.cpp
#include <hex.hpp> #include <hex/api/workspace_manager.hpp> #include <hex/api/event_manager.hpp> #include <hex/api/content_registry.hpp> #include <hex/api/localization_manager.hpp> #include <hex/api/theme_manager.hpp> #include <hex/api/layout_manager.hpp> #include <hex/api/achievement_manager.hpp> #include <hex/api_urls.hpp> #include <hex/ui/view.hpp> #include <toasts/toast_notification.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/project_file_manager.hpp> #include <imgui.h> #include <hex/ui/imgui_imhex_extensions.h> #include <nlohmann/json.hpp> #include <romfs/romfs.hpp> #include <wolv/io/file.hpp> #include <wolv/io/fs.hpp> #include <fonts/codicons_font.h> #include <content/recent.hpp> #include <string> #include <random> namespace hex::plugin::builtin { namespace { ImGuiExt::Texture s_bannerTexture, s_nightlyTexture, s_backdropTexture, s_infoBannerTexture; std::string s_tipOfTheDay; bool s_simplifiedWelcomeScreen = false; class PopupRestoreBackup : public Popup<PopupRestoreBackup> { private: std::fs::path m_logFilePath; std::function<void()> m_restoreCallback; std::function<void()> m_deleteCallback; bool m_reportError = true; public: PopupRestoreBackup(std::fs::path logFilePath, const std::function<void()> &restoreCallback, const std::function<void()> &deleteCallback) : Popup("hex.builtin.popup.safety_backup.title"), m_logFilePath(std::move(logFilePath)), m_restoreCallback(restoreCallback), m_deleteCallback(deleteCallback) { m_reportError = ContentRegistry::Settings::read<bool>("hex.builtin.setting.general", "hex.builtin.setting.general.upload_crash_logs", true); } void drawContent() override { ImGui::TextUnformatted("hex.builtin.popup.safety_backup.desc"_lang); if (!m_logFilePath.empty()) { ImGui::NewLine(); ImGui::TextUnformatted("hex.builtin.popup.safety_backup.log_file"_lang); ImGui::SameLine(0, 2_scaled); if (ImGuiExt::Hyperlink(m_logFilePath.filename().string().c_str())) { fs::openFolderWithSelectionExternal(m_logFilePath); } ImGui::Checkbox("hex.builtin.popup.safety_backup.report_error"_lang, &m_reportError); ImGui::NewLine(); } auto width = ImGui::GetWindowWidth(); ImGui::SetCursorPosX(width / 9); if (ImGui::Button("hex.builtin.popup.safety_backup.restore"_lang, ImVec2(width / 3, 0))) { m_restoreCallback(); m_deleteCallback(); if (m_reportError) { wolv::io::File logFile(m_logFilePath, wolv::io::File::Mode::Read); if (logFile.isValid()) { // Read current log file data auto data = logFile.readString(); // Anonymize the log file { for (const auto &paths : paths::All) { for (auto &folder : paths->all()) { auto parent = wolv::util::toUTF8String(folder.parent_path()); data = wolv::util::replaceStrings(data, parent, "<*****>"); } } } TaskManager::createBackgroundTask("hex.builtin.task.uploading_crash"_lang, [path = m_logFilePath, data](auto&){ HttpRequest request("POST", ImHexApiURL + std::string("/crash_upload")); request.uploadFile(std::vector<u8>(data.begin(), data.end()), "file", path.filename()).wait(); }); } } ContentRegistry::Settings::write<int>("hex.builtin.setting.general", "hex.builtin.setting.general.upload_crash_logs", m_reportError); this->close(); } ImGui::SameLine(); ImGui::SetCursorPosX(width / 9 * 5); if (ImGui::Button("hex.builtin.popup.safety_backup.delete"_lang, ImVec2(width / 3, 0)) || ImGui::IsKeyPressed(ImGuiKey_Escape)) { m_deleteCallback(); this->close(); } } }; class PopupTipOfTheDay : public Popup<PopupTipOfTheDay> { public: PopupTipOfTheDay() : Popup("hex.builtin.popup.tip_of_the_day.title", true, false) { } void drawContent() override { ImGuiExt::Header("hex.builtin.welcome.tip_of_the_day"_lang, true); ImGuiExt::TextFormattedWrapped("{}", s_tipOfTheDay.c_str()); ImGui::NewLine(); static bool dontShowAgain = false; if (ImGui::Checkbox("hex.ui.common.dont_show_again"_lang, &dontShowAgain)) { ContentRegistry::Settings::write<bool>("hex.builtin.setting.general", "hex.builtin.setting.general.show_tips", !dontShowAgain); } ImGui::SameLine((ImGui::GetMainViewport()->Size / 3 - ImGui::CalcTextSize("hex.ui.common.close"_lang) - ImGui::GetStyle().FramePadding).x); if (ImGui::Button("hex.ui.common.close"_lang) || ImGui::IsKeyPressed(ImGuiKey_Escape)) Popup::close(); } }; void loadDefaultLayout() { LayoutManager::loadFromString(std::string(romfs::get("layouts/default.hexlyt").string())); } bool isAnyViewOpen() { const auto &views = ContentRegistry::Views::impl::getEntries(); return std::any_of(views.begin(), views.end(), [](const auto &entry) { return entry.second->getWindowOpenState(); }); } void drawWelcomeScreenBackground() { const auto position = ImGui::GetWindowPos(); const auto size = ImGui::GetWindowSize(); auto drawList = ImGui::GetWindowDrawList(); const auto lineDistance = 20_scaled; const auto lineColor = ImGui::GetColorU32(ImGuiCol_Text, 0.03F); for (auto x = position.x; x < position.x + size.x + lineDistance; x += lineDistance) { drawList->AddLine({ x, position.y }, { x, position.y + size.y }, lineColor); } for (auto y = position.y; y < position.y + size.y + lineDistance; y += lineDistance) { drawList->AddLine({ position.x, y }, { position.x + size.x, y }, lineColor); } } void drawWelcomeScreenContentSimplified() { const ImVec2 backdropSize = scaled({ 350, 350 }); ImGui::SetCursorPos((ImGui::GetContentRegionAvail() - backdropSize) / 2); ImGui::Image(s_backdropTexture, backdropSize); ImGuiExt::TextFormattedCentered("hex.builtin.welcome.drop_file"_lang); } void drawWelcomeScreenContentFull() { const ImVec2 margin = scaled({ 30, 20 }); ImGui::SetCursorPos(margin); if (ImGui::BeginTable("Welcome Outer", 1, ImGuiTableFlags_None, ImGui::GetContentRegionAvail() - margin)) { ImGui::TableNextRow(); ImGui::TableNextColumn(); ImGui::Image(s_bannerTexture, s_bannerTexture.getSize()); if (ImHexApi::System::isNightlyBuild()) { auto cursor = ImGui::GetCursorPos(); ImGui::SameLine(0); ImGui::SetCursorPosX(ImGui::GetCursorPosX() - 15_scaled); ImGui::SetCursorPosY(ImGui::GetCursorPosY() + 5_scaled); ImGui::Image(s_nightlyTexture, s_nightlyTexture.getSize()); ImGuiExt::InfoTooltip("hex.builtin.welcome.nightly_build"_lang); ImGui::SetCursorPos(cursor); } ImGui::NewLine(); ImGui::PushStyleColor(ImGuiCol_ChildBg, ImGui::GetStyleColorVec4(ImGuiCol_PopupBg)); ON_SCOPE_EXIT { ImGui::PopStyleColor(); }; ImGui::TableNextRow(); ImGui::TableNextColumn(); const auto availableSpace = ImGui::GetContentRegionAvail(); if (ImGui::BeginTable("Welcome Left", 1, ImGuiTableFlags_NoBordersInBody, ImVec2(availableSpace.x / 2, 0))) { ImGui::TableNextRow(ImGuiTableRowFlags_None, ImGui::GetTextLineHeightWithSpacing() * 6); ImGui::TableNextColumn(); static bool otherProvidersVisible = false; ImGui::SetCursorPosY(ImGui::GetCursorPosY() + 5_scaled); { auto startPos = ImGui::GetCursorPos(); if (ImGuiExt::BeginSubWindow("hex.builtin.welcome.header.start"_lang, nullptr, ImVec2(), ImGuiChildFlags_AutoResizeX)) { if (ImGuiExt::IconHyperlink(ICON_VS_NEW_FILE, "hex.builtin.welcome.start.create_file"_lang)) { auto newProvider = hex::ImHexApi::Provider::createProvider("hex.builtin.provider.mem_file", true); if (newProvider != nullptr && !newProvider->open()) hex::ImHexApi::Provider::remove(newProvider); else EventProviderOpened::post(newProvider); } if (ImGuiExt::IconHyperlink(ICON_VS_GO_TO_FILE, "hex.builtin.welcome.start.open_file"_lang)) RequestOpenWindow::post("Open File"); if (ImGuiExt::IconHyperlink(ICON_VS_NOTEBOOK, "hex.builtin.welcome.start.open_project"_lang)) RequestOpenWindow::post("Open Project"); if (ImGuiExt::IconHyperlink(ICON_VS_TELESCOPE, "hex.builtin.welcome.start.open_other"_lang)) otherProvidersVisible = !otherProvidersVisible; } ImGuiExt::EndSubWindow(); auto endPos = ImGui::GetCursorPos(); if (otherProvidersVisible) { ImGui::SameLine(0, 2_scaled); ImGui::SetCursorPos(ImGui::GetCursorPos() + ImVec2(0, (endPos - startPos).y / 2)); ImGui::TextUnformatted(ICON_VS_ARROW_RIGHT); ImGui::SameLine(0, 2_scaled); if (ImGuiExt::BeginSubWindow("hex.builtin.welcome.start.open_other"_lang, nullptr, ImVec2(200_scaled, ImGui::GetTextLineHeightWithSpacing() * 6), ImGuiChildFlags_AutoResizeX)) { for (const auto &unlocalizedProviderName : ContentRegistry::Provider::impl::getEntries()) { if (ImGuiExt::Hyperlink(Lang(unlocalizedProviderName))) { ImHexApi::Provider::createProvider(unlocalizedProviderName); otherProvidersVisible = false; } } } ImGuiExt::EndSubWindow(); } } // Draw recent entries ImGui::Dummy({}); recent::draw(); ImGui::TableNextRow(ImGuiTableRowFlags_None, ImGui::GetTextLineHeightWithSpacing() * 6); ImGui::TableNextColumn(); ImGui::SetCursorPosY(ImGui::GetCursorPosY() + 5_scaled); if (ImGuiExt::BeginSubWindow("hex.builtin.welcome.header.help"_lang, nullptr, ImVec2(), ImGuiChildFlags_AutoResizeX)) { if (ImGuiExt::IconHyperlink(ICON_VS_GITHUB, "hex.builtin.welcome.help.repo"_lang)) hex::openWebpage("hex.builtin.welcome.help.repo.link"_lang); if (ImGuiExt::IconHyperlink(ICON_VS_ORGANIZATION, "hex.builtin.welcome.help.gethelp"_lang)) hex::openWebpage("hex.builtin.welcome.help.gethelp.link"_lang); if (ImGuiExt::IconHyperlink(ICON_VS_COMMENT_DISCUSSION, "hex.builtin.welcome.help.discord"_lang)) hex::openWebpage("hex.builtin.welcome.help.discord.link"_lang); } ImGuiExt::EndSubWindow(); if (ImHexApi::System::getInitArguments().contains("update-available")) { ImGui::TableNextRow(); ImGui::TableNextColumn(); if (ImGuiExt::DescriptionButton("hex.builtin.welcome.update.title"_lang, hex::format("hex.builtin.welcome.update.desc"_lang, ImHexApi::System::getInitArgument("update-available")).c_str(), ImVec2(ImGui::GetContentRegionAvail().x * 0.8F, 0))) ImHexApi::System::updateImHex(ImHexApi::System::UpdateType::Stable); } ImGui::EndTable(); } ImGui::SameLine(); if (ImGui::BeginTable("Welcome Right", 1, ImGuiTableFlags_NoBordersInBody, ImVec2(availableSpace.x / 2, 0))) { ImGui::TableNextRow(ImGuiTableRowFlags_None, ImGui::GetTextLineHeightWithSpacing() * 5); ImGui::TableNextColumn(); auto windowPadding = ImGui::GetStyle().WindowPadding.x * 3; if (ImGuiExt::BeginSubWindow("hex.builtin.welcome.header.customize"_lang, nullptr, ImVec2(ImGui::GetContentRegionAvail().x - windowPadding, 0), ImGuiChildFlags_AutoResizeX)) { if (ImGuiExt::DescriptionButton("hex.builtin.welcome.customize.settings.title"_lang, "hex.builtin.welcome.customize.settings.desc"_lang, ImVec2(ImGui::GetContentRegionAvail().x, 0))) RequestOpenWindow::post("Settings"); } ImGuiExt::EndSubWindow(); ImGui::TableNextRow(ImGuiTableRowFlags_None, ImGui::GetTextLineHeightWithSpacing() * 5); ImGui::TableNextColumn(); if (ImGuiExt::BeginSubWindow("hex.builtin.welcome.header.learn"_lang, nullptr, ImVec2(ImGui::GetContentRegionAvail().x - windowPadding, 0), ImGuiChildFlags_AutoResizeX)) { const auto size = ImVec2(ImGui::GetContentRegionAvail().x, 0); if (ImGuiExt::DescriptionButton("hex.builtin.welcome.learn.latest.title"_lang, "hex.builtin.welcome.learn.latest.desc"_lang, size)) hex::openWebpage("hex.builtin.welcome.learn.latest.link"_lang); if (ImGuiExt::DescriptionButton("hex.builtin.welcome.learn.imhex.title"_lang, "hex.builtin.welcome.learn.imhex.desc"_lang, size)) { AchievementManager::unlockAchievement("hex.builtin.achievement.starting_out", "hex.builtin.achievement.starting_out.docs.name"); hex::openWebpage("hex.builtin.welcome.learn.imhex.link"_lang); } if (ImGuiExt::DescriptionButton("hex.builtin.welcome.learn.pattern.title"_lang, "hex.builtin.welcome.learn.pattern.desc"_lang, size)) hex::openWebpage("hex.builtin.welcome.learn.pattern.link"_lang); if (ImGuiExt::DescriptionButton("hex.builtin.welcome.learn.plugins.title"_lang, "hex.builtin.welcome.learn.plugins.desc"_lang, size)) hex::openWebpage("hex.builtin.welcome.learn.plugins.link"_lang); ImGui::SeparatorEx(ImGuiSeparatorFlags_Horizontal, 3_scaled); if (ImGuiExt::DescriptionButton("hex.builtin.welcome.learn.interactive_tutorial.title"_lang, "hex.builtin.welcome.learn.interactive_tutorial.desc"_lang, size)) { RequestOpenWindow::post("Tutorials"); } if (auto [unlocked, total] = AchievementManager::getProgress(); unlocked != total) { if (ImGuiExt::DescriptionButtonProgress("hex.builtin.welcome.learn.achievements.title"_lang, "hex.builtin.welcome.learn.achievements.desc"_lang, float(unlocked) / float(total), size)) { RequestOpenWindow::post("Achievements"); } } } ImGuiExt::EndSubWindow(); auto extraWelcomeScreenEntries = ContentRegistry::Interface::impl::getWelcomeScreenEntries(); if (!extraWelcomeScreenEntries.empty()) { ImGui::TableNextRow(ImGuiTableRowFlags_None, ImGui::GetTextLineHeightWithSpacing() * 5); ImGui::TableNextColumn(); if (ImGuiExt::BeginSubWindow("hex.builtin.welcome.header.various"_lang, nullptr, ImVec2(ImGui::GetContentRegionAvail().x - windowPadding, 0))) { for (const auto &callback : extraWelcomeScreenEntries) callback(); } ImGuiExt::EndSubWindow(); } if (s_infoBannerTexture.isValid()) { static bool hovered = false; ImGui::PushStyleColor(ImGuiCol_Border, ImGui::GetStyleColorVec4(hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Border)); ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0)); if (ImGuiExt::BeginSubWindow("hex.builtin.welcome.header.info"_lang, nullptr, ImVec2(), ImGuiChildFlags_AutoResizeX)) { const auto height = 80_scaled; ImGui::Image(s_infoBannerTexture, ImVec2(height * s_infoBannerTexture.getAspectRatio(), height)); hovered = ImGui::IsItemHovered(); if (ImGui::IsItemClicked()) { hex::openWebpage(ImHexApiURL + hex::format("/info/{}/link", hex::toLower(ImHexApi::System::getOSName()))); } } ImGuiExt::EndSubWindow(); ImGui::PopStyleVar(); ImGui::PopStyleColor(); } ImGui::EndTable(); } ImGui::EndTable(); } ImGui::SetCursorPos(ImVec2(ImGui::GetContentRegionAvail().x - ImGui::GetStyle().FramePadding.x * 2, ImGui::GetStyle().FramePadding.y * 2 - 1)); if (ImGuiExt::DimmedIconButton(ICON_VS_CLOSE, ImGuiExt::GetCustomColorVec4(ImGuiCustomCol_ToolbarRed))) { auto provider = ImHexApi::Provider::createProvider("hex.builtin.provider.null"); if (provider != nullptr) if (provider->open()) EventProviderOpened::post(provider); } } void drawWelcomeScreen() { ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 0); ImGui::PushStyleColor(ImGuiCol_WindowShadow, 0x00); if (ImGui::Begin("ImHexDockSpace", nullptr, ImGuiWindowFlags_NoBringToFrontOnFocus)) { if (!ImHexApi::Provider::isValid()) { static auto title = []{ std::array<char, 256> title = {}; ImFormatString(title.data(), title.size(), "%s/DockSpace_%08X", ImGui::GetCurrentWindowRead()->Name, ImGui::GetID("ImHexMainDock")); return title; }(); if (ImGui::Begin(title.data(), nullptr, ImGuiWindowFlags_NoNav | ImGuiWindowFlags_NoBringToFrontOnFocus)) { ImGui::Dummy({}); ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, scaled({ 10, 10 })); ImGui::SetNextWindowScroll({ 0.0F, -1.0F }); ImGui::SetNextWindowSize(ImGui::GetContentRegionAvail() + scaled({ 0, 10 })); ImGui::SetNextWindowPos(ImGui::GetCursorScreenPos() - ImVec2(0, ImGui::GetStyle().FramePadding.y + 2_scaled)); ImGui::SetNextWindowViewport(ImGui::GetMainViewport()->ID); if (ImGui::Begin("Welcome Screen", nullptr, ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDocking | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove)) { ImGui::BringWindowToDisplayBack(ImGui::GetCurrentWindowRead()); drawWelcomeScreenBackground(); if (s_simplifiedWelcomeScreen) drawWelcomeScreenContentSimplified(); else drawWelcomeScreenContentFull(); static bool hovered = false; ImGui::PushStyleVar(ImGuiStyleVar_Alpha, hovered ? 1.0F : 0.3F); { const ImVec2 windowSize = scaled({ 150, 60 }); ImGui::SetCursorScreenPos(ImGui::GetWindowPos() + ImGui::GetWindowSize() - windowSize - ImGui::GetStyle().WindowPadding); ImGui::PushStyleColor(ImGuiCol_ChildBg, ImGui::GetStyleColorVec4(ImGuiCol_WindowBg)); if (ImGuiExt::BeginSubWindow("hex.builtin.welcome.header.quick_settings"_lang, nullptr, windowSize, ImGuiChildFlags_AutoResizeY)) { if (ImGuiExt::ToggleSwitch("hex.builtin.welcome.quick_settings.simplified"_lang, &s_simplifiedWelcomeScreen)) { ContentRegistry::Settings::write<bool>("hex.builtin.setting.interface", "hex.builtin.setting.interface.simplified_welcome_screen", s_simplifiedWelcomeScreen); WorkspaceManager::switchWorkspace(s_simplifiedWelcomeScreen ? "Minimal" : "Default"); } } ImGuiExt::EndSubWindow(); ImGui::PopStyleColor(); hovered = ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenOverlappedByItem | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem); } ImGui::PopStyleVar(); } ImGui::End(); ImGui::PopStyleVar(); } ImGui::End(); ImGui::BringWindowToDisplayBack(ImGui::GetCurrentWindowRead()); } } ImGui::End(); ImGui::PopStyleColor(); ImGui::PopStyleVar(); } /** * @brief Draw some default background if there are no views available in the current layout */ void drawNoViewsBackground() { ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 0); ImGui::PushStyleColor(ImGuiCol_WindowShadow, 0x00); if (ImGui::Begin("ImHexDockSpace", nullptr, ImGuiWindowFlags_NoBringToFrontOnFocus)) { static std::array<char, 256> title; ImFormatString(title.data(), title.size(), "%s/DockSpace_%08X", ImGui::GetCurrentWindowRead()->Name, ImGui::GetID("ImHexMainDock")); if (ImGui::Begin(title.data())) { ImGui::Dummy({}); ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, scaled({ 10, 10 })); ImGui::SetNextWindowScroll({ 0.0F, -1.0F }); ImGui::SetNextWindowSize(ImGui::GetContentRegionAvail() + scaled({ 0, 10 })); ImGui::SetNextWindowPos(ImGui::GetCursorScreenPos() - ImVec2(0, ImGui::GetStyle().FramePadding.y + 2_scaled)); ImGui::SetNextWindowViewport(ImGui::GetMainViewport()->ID); if (ImGui::Begin("Welcome Screen", nullptr, ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDocking | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove)) { auto imageSize = scaled(ImVec2(350, 350)); auto imagePos = (ImGui::GetContentRegionAvail() - imageSize) / 2; ImGui::SetCursorPos(imagePos); ImGui::Image(s_backdropTexture, imageSize); auto loadDefaultText = "hex.builtin.layouts.none.restore_default"_lang; auto textSize = ImGui::CalcTextSize(loadDefaultText); auto textPos = ImVec2( (ImGui::GetContentRegionAvail().x - textSize.x) / 2, imagePos.y + imageSize.y ); ImGui::SetCursorPos(textPos); if (ImGuiExt::DimmedButton(loadDefaultText)){ loadDefaultLayout(); } } ImGui::End(); ImGui::PopStyleVar(); } ImGui::End(); } ImGui::End(); ImGui::PopStyleColor(); ImGui::PopStyleVar(); } } /** * @brief Registers the event handlers related to the welcome screen * should only be called once, at startup */ void createWelcomeScreen() { recent::registerEventHandlers(); recent::updateRecentEntries(); EventFrameBegin::subscribe(drawWelcomeScreen); // Sets a background when they are no views EventFrameBegin::subscribe([]{ if (ImHexApi::Provider::isValid() && !isAnyViewOpen()) drawNoViewsBackground(); }); ContentRegistry::Settings::onChange("hex.builtin.setting.interface", "hex.builtin.setting.interface.color", [](const ContentRegistry::Settings::SettingsValue &value) { auto theme = value.get<std::string>("Dark"); if (theme != ThemeManager::NativeTheme) { static std::string lastTheme; if (theme != lastTheme) { RequestChangeTheme::post(theme); lastTheme = theme; } } }); ContentRegistry::Settings::onChange("hex.builtin.setting.interface", "hex.builtin.setting.interface.simplified_welcome_screen", [](const ContentRegistry::Settings::SettingsValue &value) { s_simplifiedWelcomeScreen = value.get<bool>(false); }); ContentRegistry::Settings::onChange("hex.builtin.setting.interface", "hex.builtin.setting.interface.language", [](const ContentRegistry::Settings::SettingsValue &value) { auto language = value.get<std::string>("en-US"); if (language != LocalizationManager::getSelectedLanguage()) LocalizationManager::loadLanguage(language); }); ContentRegistry::Settings::onChange("hex.builtin.setting.interface", "hex.builtin.setting.interface.fps", [](const ContentRegistry::Settings::SettingsValue &value) { ImHexApi::System::setTargetFPS(static_cast<float>(value.get<int>(14))); }); RequestChangeTheme::subscribe([](const std::string &theme) { auto changeTexture = [&](const std::string &path) { return ImGuiExt::Texture::fromImage(romfs::get(path).span(), ImGuiExt::Texture::Filter::Nearest); }; auto changeTextureSvg = [&](const std::string &path, float width) { return ImGuiExt::Texture::fromSVG(romfs::get(path).span(), width, 0, ImGuiExt::Texture::Filter::Linear); }; ThemeManager::changeTheme(theme); s_bannerTexture = changeTextureSvg(hex::format("assets/{}/banner.svg", ThemeManager::getImageTheme()), 300_scaled); s_nightlyTexture = changeTextureSvg(hex::format("assets/{}/nightly.svg", "common"), 35_scaled); s_backdropTexture = changeTexture(hex::format("assets/{}/backdrop.png", ThemeManager::getImageTheme())); if (!s_bannerTexture.isValid()) { log::error("Failed to load banner texture!"); } }); // Clear project context if we go back to the welcome screen EventProviderChanged::subscribe([](const hex::prv::Provider *oldProvider, const hex::prv::Provider *newProvider) { hex::unused(oldProvider); if (newProvider == nullptr) { ProjectFile::clearPath(); RequestUpdateWindowTitle::post(); } }); recent::addMenuItems(); // Check for crash backup constexpr static auto CrashFileName = "crash.json"; constexpr static auto BackupFileName = "crash_backup.hexproj"; bool hasCrashed = false; for (const auto &path : paths::Config.read()) { if (auto crashFilePath = std::fs::path(path) / CrashFileName; wolv::io::fs::exists(crashFilePath)) { hasCrashed = true; log::info("Found crash.json file at {}", wolv::util::toUTF8String(crashFilePath)); wolv::io::File crashFile(crashFilePath, wolv::io::File::Mode::Read); nlohmann::json crashFileData; try { crashFileData = nlohmann::json::parse(crashFile.readString()); } catch (nlohmann::json::exception &e) { log::error("Failed to parse crash.json file: {}", e.what()); crashFile.remove(); continue; } bool hasProject = !crashFileData.value("project", "").empty(); auto backupFilePath = path / BackupFileName; auto backupFilePathOld = path / BackupFileName; backupFilePathOld.replace_extension(".hexproj.old"); bool hasBackupFile = wolv::io::fs::exists(backupFilePath); if (!hasProject && !hasBackupFile) { log::warn("No project file or backup file found in crash.json file"); crashFile.close(); // Delete crash.json file wolv::io::fs::remove(crashFilePath); // Delete old backup file wolv::io::fs::remove(backupFilePathOld); // Try to move current backup file to the old backup location if (wolv::io::fs::copyFile(backupFilePath, backupFilePathOld)) { wolv::io::fs::remove(backupFilePath); } continue; } PopupRestoreBackup::open( // Path of log file crashFileData.value("logFile", ""), // Restore callback [crashFileData, backupFilePath, hasProject, hasBackupFile] { if (hasBackupFile) { if (ProjectFile::load(backupFilePath)) { if (hasProject) { ProjectFile::setPath(crashFileData["project"].get<std::string>()); } else { ProjectFile::setPath(""); } RequestUpdateWindowTitle::post(); } else { ui::ToastError::open(hex::format("hex.builtin.popup.error.project.load"_lang, wolv::util::toUTF8String(backupFilePath))); } } else { if (hasProject) { ProjectFile::setPath(crashFileData["project"].get<std::string>()); } } }, // Delete callback (also executed after restore) [crashFilePath, backupFilePath] { wolv::io::fs::remove(crashFilePath); wolv::io::fs::remove(backupFilePath); } ); } } // Tip of the day auto tipsData = romfs::get("tips.json"); if (!hasCrashed && tipsData.valid()) { auto tipsCategories = nlohmann::json::parse(tipsData.string()); auto now = std::chrono::system_clock::now(); auto daysSinceEpoch = std::chrono::duration_cast<std::chrono::days>(now.time_since_epoch()); std::mt19937 random(daysSinceEpoch.count()); auto chosenCategory = tipsCategories[random()%tipsCategories.size()].at("tips"); auto chosenTip = chosenCategory[random()%chosenCategory.size()]; s_tipOfTheDay = chosenTip.get<std::string>(); bool showTipOfTheDay = ContentRegistry::Settings::read<bool>("hex.builtin.setting.general", "hex.builtin.setting.general.show_tips", false); if (showTipOfTheDay) PopupTipOfTheDay::open(); } if (hasCrashed) { TaskManager::doLater([]{ AchievementManager::unlockAchievement("hex.builtin.achievement.starting_out", "hex.builtin.achievement.starting_out.crash.name"); }); } // Load info banner texture either locally or from the server TaskManager::doLater([] { for (const auto &defaultPath : paths::Resources.read()) { const auto infoBannerPath = defaultPath / "info_banner.png"; if (wolv::io::fs::exists(infoBannerPath)) { s_infoBannerTexture = ImGuiExt::Texture::fromImage(infoBannerPath, ImGuiExt::Texture::Filter::Linear); if (s_infoBannerTexture.isValid()) break; } } auto allowNetworking = ContentRegistry::Settings::read<bool>("hex.builtin.setting.general", "hex.builtin.setting.general.network_interface", false) && ContentRegistry::Settings::read<int>("hex.builtin.setting.general", "hex.builtin.setting.general.server_contact", 0) != 0; if (!s_infoBannerTexture.isValid() && allowNetworking) { TaskManager::createBackgroundTask("hex.builtin.task.loading_banner"_lang, [](auto&) { HttpRequest request("GET", ImHexApiURL + hex::format("/info/{}/image", hex::toLower(ImHexApi::System::getOSName()))); auto response = request.downloadFile().get(); if (response.isSuccess()) { const auto &data = response.getData(); if (!data.empty()) { TaskManager::doLater([data] { s_infoBannerTexture = ImGuiExt::Texture::fromImage(data.data(), data.size(), ImGuiExt::Texture::Filter::Linear); }); } } }); } }); } }
35,751
C++
.cpp
560
44.460714
265
0.549192
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
163
data_information_sections.cpp
WerWolv_ImHex/plugins/builtin/source/content/data_information_sections.cpp
#include <hex/api/content_registry.hpp> #include <hex/helpers/magic.hpp> #include <hex/providers/provider.hpp> #include <imgui.h> #include <content/helpers/diagrams.hpp> #include <hex/api/task_manager.hpp> #include <hex/ui/imgui_imhex_extensions.h> #include <wolv/literals.hpp> namespace hex::plugin::builtin { using namespace wolv::literals; class InformationProvider : public ContentRegistry::DataInformation::InformationSection { public: InformationProvider() : InformationSection("hex.builtin.information_section.provider_information") { } ~InformationProvider() override = default; void process(Task &task, prv::Provider *provider, Region region) override { hex::unused(task); m_provider = provider; m_region = region; } void reset() override { m_provider = nullptr; m_region = Region::Invalid(); } void drawContent() override { if (ImGui::BeginTable("information", 2, ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_RowBg | ImGuiTableFlags_NoKeepColumnsVisible)) { ImGui::TableSetupColumn("type"); ImGui::TableSetupColumn("value", ImGuiTableColumnFlags_WidthStretch); ImGui::TableNextRow(); for (auto &[name, value] : m_provider->getDataDescription()) { ImGui::TableNextColumn(); ImGuiExt::TextFormatted("{}", name); ImGui::TableNextColumn(); ImGuiExt::TextFormattedWrapped("{}", value); } ImGui::TableNextColumn(); ImGuiExt::TextFormatted("{}", "hex.ui.common.region"_lang); ImGui::TableNextColumn(); ImGuiExt::TextFormatted("0x{:X} - 0x{:X}", m_region.getStartAddress(), m_region.getEndAddress()); ImGui::EndTable(); } } private: prv::Provider *m_provider = nullptr; Region m_region = Region::Invalid(); }; class InformationMagic : public ContentRegistry::DataInformation::InformationSection { public: InformationMagic() : InformationSection("hex.builtin.information_section.magic") { } ~InformationMagic() override = default; void process(Task &task, prv::Provider *provider, Region region) override { magic::compile(); task.update(); try { std::vector<u8> data(region.getSize()); provider->read(region.getStartAddress(), data.data(), data.size()); m_dataDescription = magic::getDescription(data); m_dataMimeType = magic::getMIMEType(data); m_dataAppleCreatorType = magic::getAppleCreatorType(data); m_dataExtensions = magic::getExtensions(data); } catch (const std::bad_alloc &) { hex::log::error("Failed to allocate enough memory for full file magic analysis!"); // Retry analysis with only the first 100 KiB if (region.getSize() != 100_kiB) { process(task, provider, { region.getStartAddress(), 100_kiB }); } } } void drawContent() override { if (!(m_dataDescription.empty() && m_dataMimeType.empty())) { if (ImGui::BeginTable("magic", 2, ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_RowBg)) { ImGui::TableSetupColumn("type"); ImGui::TableSetupColumn("value", ImGuiTableColumnFlags_WidthStretch); ImGui::TableNextRow(); if (!m_dataDescription.empty()) { ImGui::TableNextColumn(); ImGui::TextUnformatted("hex.builtin.information_section.magic.description"_lang); ImGui::TableNextColumn(); if (m_dataDescription == "data") { ImGuiExt::TextFormattedColored(ImVec4(0.92F, 0.25F, 0.2F, 1.0F), "{} ({})", "hex.builtin.information_section.magic.octet_stream_text"_lang, m_dataDescription); } else { ImGuiExt::TextFormattedWrapped("{}", m_dataDescription); } } if (!m_dataMimeType.empty()) { ImGui::TableNextColumn(); ImGui::TextUnformatted("hex.builtin.information_section.magic.mime"_lang); ImGui::TableNextColumn(); if (m_dataMimeType.contains("application/octet-stream")) { ImGuiExt::TextFormatted("{}", m_dataMimeType); ImGui::SameLine(); ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0)); ImGuiExt::HelpHover("hex.builtin.information_section.magic.octet_stream_warning"_lang); ImGui::PopStyleVar(); } else { ImGuiExt::TextFormatted("{}", m_dataMimeType); } } if (!m_dataAppleCreatorType.empty()) { ImGui::TableNextColumn(); ImGui::TextUnformatted("hex.builtin.information_section.magic.apple_type"_lang); ImGui::TableNextColumn(); ImGuiExt::TextFormatted("{}", m_dataAppleCreatorType); } if (!m_dataExtensions.empty()) { ImGui::TableNextColumn(); ImGui::TextUnformatted("hex.builtin.information_section.magic.extension"_lang); ImGui::TableNextColumn(); ImGuiExt::TextFormatted("{}", m_dataExtensions); } ImGui::EndTable(); } ImGui::NewLine(); } } void reset() override { m_dataDescription.clear(); m_dataMimeType.clear(); m_dataAppleCreatorType.clear(); m_dataExtensions.clear(); } private: std::string m_dataDescription; std::string m_dataMimeType; std::string m_dataAppleCreatorType; std::string m_dataExtensions; }; class InformationByteAnalysis : public ContentRegistry::DataInformation::InformationSection { public: InformationByteAnalysis() : InformationSection("hex.builtin.information_section.info_analysis", "", true) { EventRegionSelected::subscribe(this, [this](const ImHexApi::HexEditor::ProviderRegion &region) { m_byteTypesDistribution.setHandlePosition(region.getStartAddress()); m_chunkBasedEntropy.setHandlePosition(region.getStartAddress()); }); } ~InformationByteAnalysis() override { EventRegionSelected::unsubscribe(this); } void process(Task &task, prv::Provider *provider, Region region) override { if (m_inputChunkSize == 0) m_inputChunkSize = 256; m_blockSize = std::max<u32>(std::ceil(region.getSize() / 2048.0F), 256); m_byteDistribution.reset(); m_byteTypesDistribution.reset(region.getStartAddress(), region.getEndAddress(), provider->getBaseAddress(), provider->getActualSize()); m_chunkBasedEntropy.reset(m_inputChunkSize, region.getStartAddress(), region.getEndAddress(), provider->getBaseAddress(), provider->getActualSize()); m_byteTypesDistribution.enableAnnotations(m_showAnnotations); // Create a handle to the file auto reader = prv::ProviderReader(provider); reader.seek(region.getStartAddress()); reader.setEndAddress(region.getEndAddress()); // Loop over each byte of the selection and update each analysis // one byte at a time to process the file only once for (u8 byte : reader) { m_byteDistribution.update(byte); m_byteTypesDistribution.update(byte); m_chunkBasedEntropy.update(byte); task.update(); } m_averageEntropy = m_chunkBasedEntropy.calculateEntropy(m_byteDistribution.get(), region.getSize()); m_highestBlockEntropy = m_chunkBasedEntropy.getHighestEntropyBlockValue(); m_highestBlockEntropyAddress = m_chunkBasedEntropy.getHighestEntropyBlockAddress(); m_lowestBlockEntropy = m_chunkBasedEntropy.getLowestEntropyBlockValue(); m_lowestBlockEntropyAddress = m_chunkBasedEntropy.getLowestEntropyBlockAddress(); m_plainTextCharacterPercentage = m_byteTypesDistribution.getPlainTextCharacterPercentage(); } void reset() override { m_averageEntropy = -1.0; m_highestBlockEntropy = -1.0; m_plainTextCharacterPercentage = -1.0; } void drawSettings() override { ImGuiExt::SliderBytes("hex.builtin.information_section.info_analysis.block_size"_lang, &m_inputChunkSize, 0, 1_MiB); ImGui::Checkbox("hex.builtin.information_section.info_analysis.show_annotations"_lang, &m_showAnnotations); } void drawContent() override { ImGui::PushStyleColor(ImGuiCol_FrameBg, ImGui::GetColorU32(ImGuiCol_WindowBg)); ImPlot::PushStyleColor(ImPlotCol_FrameBg, ImGui::GetColorU32(ImGuiCol_WindowBg)); // Display byte distribution analysis ImGui::TextUnformatted("hex.builtin.information_section.info_analysis.distribution"_lang); m_byteDistribution.draw( ImVec2(-1, 0), ImPlotFlags_NoLegend | ImPlotFlags_NoMenus | ImPlotFlags_NoBoxSelect ); // Display byte types distribution analysis ImGui::TextUnformatted("hex.builtin.information_section.info_analysis.byte_types"_lang); m_byteTypesDistribution.draw( ImVec2(-1, 0), ImPlotFlags_NoMenus | ImPlotFlags_NoBoxSelect, true ); // Display chunk-based entropy analysis ImGui::TextUnformatted("hex.builtin.information_section.info_analysis.entropy"_lang); m_chunkBasedEntropy.draw( ImVec2(-1, 0), ImPlotFlags_NoLegend | ImPlotFlags_NoMenus | ImPlotFlags_NoBoxSelect, true ); ImPlot::PopStyleColor(); ImGui::PopStyleColor(); // Entropy information if (ImGui::BeginTable("entropy_info", 2, ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_RowBg)) { ImGui::TableSetupColumn("type"); ImGui::TableSetupColumn("value", ImGuiTableColumnFlags_WidthStretch); ImGui::TableNextRow(); ImGui::TableNextColumn(); ImGuiExt::TextFormatted("{}", "hex.builtin.information_section.info_analysis.block_size"_lang); ImGui::TableNextColumn(); ImGuiExt::TextFormatted("hex.builtin.information_section.info_analysis.block_size.desc"_lang, m_chunkBasedEntropy.getSize(), m_chunkBasedEntropy.getChunkSize()); ImGui::TableNextColumn(); ImGuiExt::TextFormatted("{}", "hex.builtin.information_section.info_analysis.file_entropy"_lang); ImGui::TableNextColumn(); if (m_averageEntropy < 0) { ImGui::TextUnformatted("???"); } else { auto entropy = std::abs(m_averageEntropy); ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 0.1F); ImGui::PushStyleColor(ImGuiCol_FrameBg, ImGui::GetColorU32(ImGuiCol_TableRowBgAlt)); ImGui::PushStyleColor(ImGuiCol_PlotHistogram, ImColor::HSV(0.3F - (0.3F * entropy), 0.6F, 0.8F, 1.0F).Value); ImGui::ProgressBar(entropy, ImVec2(200_scaled, ImGui::GetTextLineHeight()), hex::format("{:.5f}", entropy).c_str()); ImGui::PopStyleColor(2); ImGui::PopStyleVar(); } ImGui::TableNextColumn(); ImGuiExt::TextFormatted("{}", "hex.builtin.information_section.info_analysis.highest_entropy"_lang); ImGui::TableNextColumn(); ImGuiExt::TextFormatted("{:.5f} @", m_highestBlockEntropy); ImGui::SameLine(); ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0)); ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0)); if (ImGui::Button(hex::format("0x{:06X}", m_highestBlockEntropyAddress).c_str())) { ImHexApi::HexEditor::setSelection(m_highestBlockEntropyAddress, m_inputChunkSize); } ImGui::PopStyleColor(); ImGui::PopStyleVar(); ImGui::TableNextColumn(); ImGuiExt::TextFormatted("{}", "hex.builtin.information_section.info_analysis.lowest_entropy"_lang); ImGui::TableNextColumn(); ImGuiExt::TextFormatted("{:.5f} @", m_lowestBlockEntropy); ImGui::SameLine(); ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0)); ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0)); if (ImGui::Button(hex::format("0x{:06X}", m_lowestBlockEntropyAddress).c_str())) { ImHexApi::HexEditor::setSelection(m_lowestBlockEntropyAddress, m_inputChunkSize); } ImGui::PopStyleColor(); ImGui::PopStyleVar(); ImGui::TableNextColumn(); ImGuiExt::TextFormatted("{}", "hex.builtin.information_section.info_analysis.plain_text_percentage"_lang); ImGui::TableNextColumn(); if (m_plainTextCharacterPercentage < 0) { ImGui::TextUnformatted("???"); } else { ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 0.1F); ImGui::PushStyleColor(ImGuiCol_FrameBg, ImGui::GetColorU32(ImGuiCol_TableRowBgAlt)); ImGui::PushStyleColor(ImGuiCol_PlotHistogram, ImColor::HSV(0.3F * (m_plainTextCharacterPercentage / 100.0F), 0.8F, 0.6F, 1.0F).Value); ImGui::ProgressBar(m_plainTextCharacterPercentage / 100.0F, ImVec2(200_scaled, ImGui::GetTextLineHeight())); ImGui::PopStyleColor(2); ImGui::PopStyleVar(); } ImGui::EndTable(); } // General information if (ImGui::BeginTable("info", 1, ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_RowBg)) { ImGui::TableSetupColumn("value", ImGuiTableColumnFlags_WidthStretch); ImGui::TableNextRow(); if (m_averageEntropy > 0.83 && m_highestBlockEntropy > 0.9) { ImGui::TableNextColumn(); ImGuiExt::TextFormattedColored(ImVec4(0.92F, 0.25F, 0.2F, 1.0F), "{}", "hex.builtin.information_section.info_analysis.encrypted"_lang); } if (m_plainTextCharacterPercentage > 95) { ImGui::TableNextColumn(); ImGuiExt::TextFormattedColored(ImVec4(0.92F, 0.25F, 0.2F, 1.0F), "{}", "hex.builtin.information_section.info_analysis.plain_text"_lang); } ImGui::EndTable(); } } void load(const nlohmann::json &data) override { InformationSection::load(data); m_inputChunkSize = data.value("block_size", 0); m_showAnnotations = data.value("annotations", true); } nlohmann::json store() override { auto result = InformationSection::store(); result["block_size"] = m_inputChunkSize; result["annotations"] = m_showAnnotations; return result; } private: u64 m_inputChunkSize = 0; u32 m_blockSize = 0; double m_averageEntropy = -1.0; double m_highestBlockEntropy = -1.0; u64 m_highestBlockEntropyAddress = 0x00; double m_lowestBlockEntropy = -1.0; u64 m_lowestBlockEntropyAddress = 0x00; double m_plainTextCharacterPercentage = -1.0; bool m_showAnnotations = true; DiagramByteDistribution m_byteDistribution; DiagramByteTypesDistribution m_byteTypesDistribution; DiagramChunkBasedEntropyAnalysis m_chunkBasedEntropy; }; class InformationByteRelationshipAnalysis : public ContentRegistry::DataInformation::InformationSection { public: InformationByteRelationshipAnalysis() : InformationSection("hex.builtin.information_section.relationship_analysis", "", true) { } void process(Task &task, prv::Provider *provider, Region region) override { updateSettings(); m_digram.reset(region.getSize()); m_layeredDistribution.reset(region.getSize()); // Create a handle to the file auto reader = prv::ProviderReader(provider); reader.seek(region.getStartAddress()); reader.setEndAddress(region.getEndAddress()); // Loop over each byte of the selection and update each analysis // one byte at a time to process the file only once for (u8 byte : reader) { m_digram.update(byte); m_layeredDistribution.update(byte); task.update(); } } void reset() override { m_digram.reset(m_sampleSize); m_layeredDistribution.reset(m_sampleSize); updateSettings(); } void drawSettings() override { if (ImGuiExt::InputHexadecimal("hex.builtin.information_section.relationship_analysis.sample_size"_lang, &m_sampleSize)) { updateSettings(); } if (ImGui::SliderFloat("hex.builtin.information_section.relationship_analysis.brightness"_lang, &m_brightness, 0.0F, 1.0F)) { updateSettings(); } if (ImGui::Combo("hex.builtin.information_section.relationship_analysis.filter"_lang, reinterpret_cast<int*>(&m_filter), "Linear Interpolation\0Nearest Neighbour\0\0")) { updateSettings(); } } void drawContent() override { auto availableWidth = ImGui::GetContentRegionAvail().x; ImGui::TextUnformatted("hex.builtin.information_section.relationship_analysis.digram"_lang); m_digram.draw({ availableWidth, availableWidth }); ImGui::TextUnformatted("hex.builtin.information_section.relationship_analysis.layered_distribution"_lang); m_layeredDistribution.draw({ availableWidth, availableWidth }); } void load(const nlohmann::json &data) override { InformationSection::load(data); m_filter = data.value("filter", ImGuiExt::Texture::Filter::Nearest); m_sampleSize = data.value("sample_size", 0x9000); m_brightness = data.value("brightness", 0.5F); updateSettings(); } nlohmann::json store() override { auto result = InformationSection::store(); result["sample_size"] = m_sampleSize; result["brightness"] = m_brightness; result["filter"] = m_filter; return result; } private: void updateSettings() { m_digram.setFiltering(m_filter); m_digram.setSampleSize(m_sampleSize); m_digram.setBrightness(m_brightness); m_layeredDistribution.setFiltering(m_filter); m_layeredDistribution.setSampleSize(m_sampleSize); m_layeredDistribution.setBrightness(m_brightness); } private: ImGuiExt::Texture::Filter m_filter = ImGuiExt::Texture::Filter::Nearest; u64 m_sampleSize = 0x9000; float m_brightness = 0.5F; DiagramDigram m_digram; DiagramLayeredDistribution m_layeredDistribution; }; void registerDataInformationSections() { ContentRegistry::DataInformation::addInformationSection<InformationProvider>(); ContentRegistry::DataInformation::addInformationSection<InformationMagic>(); ContentRegistry::DataInformation::addInformationSection<InformationByteAnalysis>(); ContentRegistry::DataInformation::addInformationSection<InformationByteRelationshipAnalysis>(); } }
20,893
C++
.cpp
381
40.346457
187
0.594662
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
164
data_processor_nodes.cpp
WerWolv_ImHex/plugins/builtin/source/content/data_processor_nodes.cpp
#include <content/data_processor_nodes.hpp> namespace hex::plugin::builtin { void registerDataProcessorNodes() { registerBasicDataProcessorNodes(); registerVisualDataProcessorNodes(); registerLogicDataProcessorNodes(); registerControlDataProcessorNodes(); registerDecodeDataProcessorNodes(); registerMathDataProcessorNodes(); registerOtherDataProcessorNodes(); } }
435
C++
.cpp
12
29.416667
44
0.743405
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
165
pl_pragmas.cpp
WerWolv_ImHex/plugins/builtin/source/content/pl_pragmas.cpp
#include <hex/api/imhex_api.hpp> #include <hex/api/content_registry.hpp> #include <hex/providers/provider.hpp> #include <hex/helpers/magic.hpp> #include <pl/core/evaluator.hpp> namespace hex::plugin::builtin { void registerPatternLanguagePragmas() { ContentRegistry::PatternLanguage::addPragma("base_address", [](pl::PatternLanguage &runtime, const std::string &value) { auto baseAddress = strtoull(value.c_str(), nullptr, 0); ImHexApi::Provider::get()->setBaseAddress(baseAddress); runtime.setDataBaseAddress(baseAddress); return true; }); ContentRegistry::PatternLanguage::addPragma("MIME", [](pl::PatternLanguage&, const std::string &value) { return magic::isValidMIMEType(value); }); ContentRegistry::PatternLanguage::addPragma("magic", [](pl::PatternLanguage&, const std::string &) { return true; }); } }
947
C++
.cpp
21
37.571429
128
0.667394
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
166
data_formatters.cpp
WerWolv_ImHex/plugins/builtin/source/content/data_formatters.cpp
#include <hex/api/content_registry.hpp> #include <hex/api/achievement_manager.hpp> #include <hex/providers/provider.hpp> #include <hex/providers/buffered_reader.hpp> #include <hex/helpers/fmt.hpp> #include <hex/helpers/crypto.hpp> #include <hex/helpers/utils.hpp> #include <content/export_formatters/export_formatter_csv.hpp> #include <content/export_formatters/export_formatter_tsv.hpp> #include <content/export_formatters/export_formatter_json.hpp> namespace hex::plugin::builtin { static std::string formatLanguageArray(prv::Provider *provider, u64 offset, size_t size, const std::string &start, const std::string &byteFormat, const std::string &end, bool removeFinalDelimiter= false) { constexpr static auto NewLineIndent = "\n "; constexpr static auto LineLength = 16; std::string result; result.reserve(start.size() + hex::format(byteFormat, 0x00).size() * size + + std::string(NewLineIndent).size() / LineLength + end.size()); result += start; auto reader = prv::ProviderReader(provider); reader.seek(offset); reader.setEndAddress(offset + size - 1); u64 index = 0x00; for (u8 byte : reader) { if ((index % LineLength) == 0x00) result += NewLineIndent; result += hex::format(byteFormat, byte); index++; } // Remove trailing delimiter if required if (removeFinalDelimiter && size > 0) { result.pop_back(); result.pop_back(); } result += "\n" + end; return result; } void registerDataFormatters() { ContentRegistry::DataFormatter::addExportMenuEntry("hex.builtin.view.hex_editor.copy.c", [](prv::Provider *provider, u64 offset, size_t size) { return formatLanguageArray(provider, offset, size, hex::format("const uint8_t data[{0}] = {{", size), "0x{0:02X}, ", "};"); }); ContentRegistry::DataFormatter::addExportMenuEntry("hex.builtin.view.hex_editor.copy.cpp", [](prv::Provider *provider, u64 offset, size_t size) { AchievementManager::unlockAchievement("hex.builtin.achievement.hex_editor", "hex.builtin.achievement.hex_editor.copy_as.name"); return formatLanguageArray(provider, offset, size, hex::format("constexpr std::array<uint8_t, {0}> data = {{", size), "0x{0:02X}, ", "};"); }); ContentRegistry::DataFormatter::addExportMenuEntry("hex.builtin.view.hex_editor.copy.java", [](prv::Provider *provider, u64 offset, size_t size) { return formatLanguageArray(provider, offset, size, "final byte[] data = {", "0x{0:02X}, ", "};"); }); ContentRegistry::DataFormatter::addExportMenuEntry("hex.builtin.view.hex_editor.copy.csharp", [](prv::Provider *provider, u64 offset, size_t size) { return formatLanguageArray(provider, offset, size, "const byte[] data = {", "0x{0:02X}, ", "};"); }); ContentRegistry::DataFormatter::addExportMenuEntry("hex.builtin.view.hex_editor.copy.rust", [](prv::Provider *provider, u64 offset, size_t size) { return formatLanguageArray(provider, offset, size, hex::format("let data: [u8; 0x{0:02X}] = [", size), "0x{0:02X}, ", "];"); }); ContentRegistry::DataFormatter::addExportMenuEntry("hex.builtin.view.hex_editor.copy.python", [](prv::Provider *provider, u64 offset, size_t size) { return formatLanguageArray(provider, offset, size, "data = bytes([", "0x{0:02X}, ", "])"); }); ContentRegistry::DataFormatter::addExportMenuEntry("hex.builtin.view.hex_editor.copy.js", [](prv::Provider *provider, u64 offset, size_t size) { return formatLanguageArray(provider, offset, size, "const data = new Uint8Array([", "0x{0:02X}, ", "]);"); }); ContentRegistry::DataFormatter::addExportMenuEntry("hex.builtin.view.hex_editor.copy.lua", [](prv::Provider *provider, u64 offset, size_t size) { return formatLanguageArray(provider, offset, size, "data = {", "0x{0:02X}, ", "}"); }); ContentRegistry::DataFormatter::addExportMenuEntry("hex.builtin.view.hex_editor.copy.go", [](prv::Provider *provider, u64 offset, size_t size) { return formatLanguageArray(provider, offset, size, "data := [...]byte{", "0x{0:02X}, ", "}", false); }); ContentRegistry::DataFormatter::addExportMenuEntry("hex.builtin.view.hex_editor.copy.crystal", [](prv::Provider *provider, u64 offset, size_t size) { return formatLanguageArray(provider, offset, size, "data = [", "0x{0:02X}, ", "] of UInt8"); }); ContentRegistry::DataFormatter::addExportMenuEntry("hex.builtin.view.hex_editor.copy.swift", [](prv::Provider *provider, u64 offset, size_t size) { return formatLanguageArray(provider, offset, size, "let data: [Uint8] = [", "0x{0:02X}, ", "]"); }); ContentRegistry::DataFormatter::addExportMenuEntry("hex.builtin.view.hex_editor.copy.pascal", [](prv::Provider *provider, u64 offset, size_t size) { return formatLanguageArray(provider, offset, size, hex::format("data: array[0..{0}] of Byte = (", size - 1), "${0:02X}, ", ")"); }); ContentRegistry::DataFormatter::addExportMenuEntry("hex.builtin.view.hex_editor.copy.base64", [](prv::Provider *provider, u64 offset, size_t size) { std::vector<u8> data(size, 0x00); provider->read(offset, data.data(), size); auto result = crypt::encode64(data); return std::string(result.begin(), result.end()); }); ContentRegistry::DataFormatter::addExportMenuEntry("hex.builtin.view.hex_editor.copy.hex_view", [](prv::Provider *provider, u64 offset, size_t size) { return hex::generateHexView(offset, size, provider); }); ContentRegistry::DataFormatter::addExportMenuEntry("hex.builtin.view.hex_editor.copy.html", [](prv::Provider *provider, u64 offset, size_t size) { std::string result = "<div>\n" " <style type=\"text/css\">\n" " .offsetheader { color:#0000A0; line-height:200% }\n" " .offsetcolumn { color:#0000A0 }\n" " .hexcolumn { color:#000000 }\n" " .textcolumn { color:#000000 }\n" " .zerobyte { color:#808080 }\n" " </style>\n\n" " <code>\n" " <span class=\"offsetheader\">Hex View&nbsp&nbsp00 01 02 03 04 05 06 07&nbsp 08 09 0A 0B 0C 0D 0E 0F</span>"; auto reader = prv::ProviderReader(provider); reader.seek(offset); reader.setEndAddress((offset + size) - 1); u64 address = offset & ~u64(0x0F); std::string asciiRow; for (u8 byte : reader) { if ((address % 0x10) == 0) { result += hex::format(" {}", asciiRow); result += hex::format("<br>\n <span class=\"offsetcolumn\">{0:08X}</span>&nbsp&nbsp<span class=\"hexcolumn\">", address); asciiRow.clear(); if (address == (offset & ~u64(0x0F))) { for (u64 i = 0; i < (offset - address); i++) { result += "&nbsp&nbsp&nbsp"; asciiRow += "&nbsp"; } address = offset; } result += "</span>"; } std::string tagStart, tagEnd; if (byte == 0x00) { tagStart = "<span class=\"zerobyte\">"; tagEnd = "</span>"; } result += hex::format("{0}{2:02X}{1} ", tagStart, tagEnd, byte); asciiRow += std::isprint(byte) ? char(byte) : '.'; if ((address % 0x10) == 0x07) result += "&nbsp"; address++; } if (address % 0x10 != 0x00) for (u32 i = 0; i < (0x10 - (address % 0x10)); i++) result += "&nbsp&nbsp&nbsp"; result += asciiRow; result += "\n </code>\n" "</div>\n"; return result; }); ContentRegistry::DataFormatter::addFindExportFormatter("csv", "csv", [](const std::vector<ContentRegistry::DataFormatter::impl::FindOccurrence>& occurrences, const auto &transformFunc) { export_fmt::ExportFormatterCsv formatter; return formatter.format(occurrences, transformFunc); }); ContentRegistry::DataFormatter::addFindExportFormatter("tsv", "tsv", [](const std::vector<ContentRegistry::DataFormatter::impl::FindOccurrence>& occurrences, const auto &transformFunc) { export_fmt::ExportFormatterTsv formatter; return formatter.format(occurrences, transformFunc); }); ContentRegistry::DataFormatter::addFindExportFormatter("json", "json", [](const std::vector<ContentRegistry::DataFormatter::impl::FindOccurrence>& occurrences, const auto &transformFunc) { export_fmt::ExportFormatterJson formatter; return formatter.format(occurrences, transformFunc); }); } }
9,356
C++
.cpp
147
51.29932
209
0.590984
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
167
file_handlers.cpp
WerWolv_ImHex/plugins/builtin/source/content/file_handlers.cpp
#include <hex/api/content_registry.hpp> #include <hex/api/project_file_manager.hpp> #include <hex/helpers/default_paths.hpp> #include <toasts/toast_notification.hpp> namespace hex::plugin::builtin { void registerFileHandlers() { ContentRegistry::FileHandler::add({ ".hexproj" }, [](const std::fs::path &path) { return ProjectFile::load(path); }); ContentRegistry::FileHandler::add({ ".hexlyt" }, [](const std::fs::path &path) { for (const auto &folder : paths::Layouts.write()) { if (wolv::io::fs::copyFile(path, folder / path.filename())) return true; } return false; }); ContentRegistry::FileHandler::add({ ".mgc" }, [](const auto &path) { for (const auto &destPath : paths::Magic.write()) { if (wolv::io::fs::copyFile(path, destPath / path.filename(), std::fs::copy_options::overwrite_existing)) { ui::ToastInfo::open("hex.builtin.view.information.magic_db_added"_lang); return true; } } return false; }); } }
1,170
C++
.cpp
27
32.814815
122
0.563492
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
168
data_inspector.cpp
WerWolv_ImHex/plugins/builtin/source/content/data_inspector.cpp
#include <hex/api/imhex_api.hpp> #include <hex/api/content_registry.hpp> #include <hex/helpers/utils.hpp> #include <hex/helpers/crypto.hpp> #include <hex/helpers/fmt.hpp> #include <fmt/chrono.h> #include <hex/providers/provider.hpp> #include <cstring> #include <codecvt> #include <string> #include <imgui_internal.h> #include <hex/ui/imgui_imhex_extensions.h> namespace hex::plugin::builtin { using Style = ContentRegistry::DataInspector::NumberDisplayStyle; struct GUID { u32 data1; u16 data2; u16 data3; u8 data4[8]; }; template<std::unsigned_integral T, size_t Size = sizeof(T)> static std::vector<u8> stringToUnsigned(const std::string &value, std::endian endian) requires(sizeof(T) <= sizeof(u64)) { u64 result = std::strtoull(value.c_str(), nullptr, 0); if (result > std::numeric_limits<T>::max()) return {}; std::vector<u8> bytes(Size, 0x00); std::memcpy(bytes.data(), &result, bytes.size()); if (endian != std::endian::native) std::reverse(bytes.begin(), bytes.end()); return bytes; } template<std::signed_integral T, size_t Size = sizeof(T)> static std::vector<u8> stringToSigned(const std::string &value, std::endian endian) requires(sizeof(T) <= sizeof(u64)) { i64 result = std::strtoll(value.c_str(), nullptr, 0); if (result > std::numeric_limits<T>::max() || result < std::numeric_limits<T>::min()) return {}; std::vector<u8> bytes(Size, 0x00); std::memcpy(bytes.data(), &result, bytes.size()); if (endian != std::endian::native) std::reverse(bytes.begin(), bytes.end()); return bytes; } template<std::floating_point T> static std::vector<u8> stringToFloat(const std::string &value, std::endian endian) requires(sizeof(T) <= sizeof(long double)) { T result = std::strtold(value.c_str(), nullptr); std::vector<u8> bytes(sizeof(T), 0x00); std::memcpy(bytes.data(), &result, bytes.size()); if (endian != std::endian::native) std::reverse(bytes.begin(), bytes.end()); return bytes; } template<std::integral T, size_t Size = sizeof(T)> static std::vector<u8> stringToInteger(const std::string &value, std::endian endian) requires(sizeof(T) <= sizeof(u64)) { if constexpr (std::unsigned_integral<T>) return stringToUnsigned<T, Size>(value, endian); else if constexpr (std::signed_integral<T>) return stringToSigned<T, Size>(value, endian); else return {}; } template<std::integral T, size_t Size = sizeof(T)> static std::string unsignedToString(const std::vector<u8> &buffer, std::endian endian, Style style) requires(sizeof(T) <= sizeof(u64)) { if (buffer.size() < Size) return { }; auto format = (style == Style::Decimal) ? "{0:d}" : ((style == Style::Hexadecimal) ? hex::format("0x{{0:0{}X}}", Size * 2) : hex::format("0o{{0:0{}o}}", Size * 3)); T value = 0x00; std::memcpy(&value, buffer.data(), std::min(sizeof(T), Size)); return hex::format(format, hex::changeEndianness(value, Size, endian)); } template<std::integral T, size_t Size = sizeof(T)> static std::string signedToString(const std::vector<u8> &buffer, std::endian endian, Style style) requires(sizeof(T) <= sizeof(u64)) { if (buffer.size() < Size) return { }; auto format = (style == Style::Decimal) ? "{0:d}" : ((style == Style::Hexadecimal) ? hex::format("0x{{0:0{}X}}", Size * 2) : hex::format("0o{{0:0{}o}}", Size * 3)); T value = 0x00; std::memcpy(&value, buffer.data(), std::min(sizeof(T), Size)); auto number = hex::changeEndianness(value, Size, endian); if (Size != sizeof(T)) number = hex::signExtend(Size * 8, number); return hex::format(format, number); } template<std::integral T, size_t Size = sizeof(T)> static std::string integerToString(const std::vector<u8> &buffer, std::endian endian, Style style) requires(sizeof(T) <= sizeof(u64)) { if constexpr (std::unsigned_integral<T>) return unsignedToString<T, Size>(buffer, endian, style); else if constexpr (std::signed_integral<T>) return signedToString<T, Size>(buffer, endian, style); else return {}; } template<typename T> static hex::ContentRegistry::DataInspector::impl::GeneratorFunction drawString(T func) { return [func](const std::vector<u8> &buffer, std::endian endian, Style style) { return [value = func(buffer, endian, style)]() -> std::string { ImGui::TextUnformatted(value.c_str()); return value; }; }; } // clang-format off void registerDataInspectorEntries() { ContentRegistry::DataInspector::add("hex.builtin.inspector.binary", sizeof(u8), [](auto buffer, auto endian, auto style) { hex::unused(endian, style); std::string binary = hex::format("0b{:08b}", buffer[0]); return [binary] { ImGui::TextUnformatted(binary.c_str()); return binary; }; }, [](const std::string &value, std::endian endian) -> std::vector<u8> { hex::unused(endian); std::string binary = value; if (binary.starts_with("0b")) binary = binary.substr(2); if (binary.size() > 8) return { }; if (auto result = hex::parseBinaryString(binary); result.has_value()) return { result.value() }; else return { }; } ); ContentRegistry::DataInspector::add("hex.builtin.inspector.u8", sizeof(u8), drawString(integerToString<u8>), stringToInteger<u8> ); ContentRegistry::DataInspector::add("hex.builtin.inspector.i8", sizeof(i8), drawString(integerToString<i8>), stringToInteger<i8> ); ContentRegistry::DataInspector::add("hex.builtin.inspector.u16", sizeof(u16), drawString(integerToString<u16>), stringToInteger<u16> ); ContentRegistry::DataInspector::add("hex.builtin.inspector.i16", sizeof(i16), drawString(integerToString<i16>), stringToInteger<i16> ); ContentRegistry::DataInspector::add("hex.builtin.inspector.u24", 3, drawString(integerToString<u32, 3>), stringToInteger<u32, 3> ); ContentRegistry::DataInspector::add("hex.builtin.inspector.i24", 3, drawString(integerToString<i32, 3>), stringToInteger<i32, 3> ); ContentRegistry::DataInspector::add("hex.builtin.inspector.u32", sizeof(u32), drawString(integerToString<u32>), stringToInteger<u32> ); ContentRegistry::DataInspector::add("hex.builtin.inspector.i32", sizeof(i32), drawString(integerToString<i32>), stringToInteger<i32> ); ContentRegistry::DataInspector::add("hex.builtin.inspector.u48", 6, drawString(integerToString<u64, 6>), stringToInteger<u64, 6> ); ContentRegistry::DataInspector::add("hex.builtin.inspector.i48", 6, drawString(integerToString<i64, 6>), stringToInteger<i64, 6> ); ContentRegistry::DataInspector::add("hex.builtin.inspector.u64", sizeof(u64), drawString(integerToString<u64>), stringToInteger<u64> ); ContentRegistry::DataInspector::add("hex.builtin.inspector.i64", sizeof(i64), drawString(integerToString<i64>), stringToInteger<i64> ); ContentRegistry::DataInspector::add("hex.builtin.inspector.float16", sizeof(u16), [](auto buffer, auto endian, auto style) { u16 result = 0; std::memcpy(&result, buffer.data(), sizeof(u16)); const auto formatString = style == Style::Hexadecimal ? "{0:a}" : "{0:G}"; auto value = hex::format(formatString, float16ToFloat32(hex::changeEndianness(result, endian))); return [value] { ImGui::TextUnformatted(value.c_str()); return value; }; } ); ContentRegistry::DataInspector::add("hex.builtin.inspector.float", sizeof(float), [](auto buffer, auto endian, auto style) { float result = 0; std::memcpy(&result, buffer.data(), sizeof(float)); const auto formatString = style == Style::Hexadecimal ? "{0:a}" : "{0:G}"; auto value = hex::format(formatString, hex::changeEndianness(result, endian)); return [value] { ImGui::TextUnformatted(value.c_str()); return value; }; }, stringToFloat<float> ); ContentRegistry::DataInspector::add("hex.builtin.inspector.double", sizeof(double), [](auto buffer, auto endian, auto style) { double result = 0; std::memcpy(&result, buffer.data(), sizeof(double)); const auto formatString = style == Style::Hexadecimal ? "{0:a}" : "{0:G}"; auto value = hex::format(formatString, hex::changeEndianness(result, endian)); return [value] { ImGui::TextUnformatted(value.c_str()); return value; }; }, stringToFloat<double> ); ContentRegistry::DataInspector::add("hex.builtin.inspector.long_double", sizeof(long double), [](auto buffer, auto endian, auto style) { long double result = 0; std::memcpy(&result, buffer.data(), sizeof(long double)); const auto formatString = style == Style::Hexadecimal ? "{0:a}" : "{0:G}"; auto value = hex::format(formatString, hex::changeEndianness(result, endian)); return [value] { ImGui::TextUnformatted(value.c_str()); return value; }; }, stringToFloat<long double> ); ContentRegistry::DataInspector::add("hex.builtin.inspector.sleb128", 1, (sizeof(i128) * 8 / 7) + 1, [](auto buffer, auto endian, auto style) { hex::unused(endian); auto format = (style == Style::Decimal) ? "{0}{1:d}" : ((style == Style::Hexadecimal) ? "{0}0x{1:X}" : "{0}0o{1:o}"); auto number = hex::crypt::decodeSleb128(buffer); bool negative = number < 0; auto value = hex::format(format, negative ? "-" : "", negative ? -number : number); return [value] { ImGui::TextUnformatted(value.c_str()); return value; }; }, [](const std::string &value, std::endian endian) -> std::vector<u8> { hex::unused(endian); return hex::crypt::encodeSleb128(std::strtoll(value.c_str(), nullptr, 0)); } ); ContentRegistry::DataInspector::add("hex.builtin.inspector.uleb128", 1, (sizeof(u128) * 8 / 7) + 1, [](auto buffer, auto endian, auto style) { hex::unused(endian); auto format = (style == Style::Decimal) ? "{0:d}" : ((style == Style::Hexadecimal) ? "0x{0:X}" : "0o{0:o}"); auto value = hex::format(format, hex::crypt::decodeUleb128(buffer)); return [value] { ImGui::TextUnformatted(value.c_str()); return value; }; }, [](const std::string &value, std::endian endian) -> std::vector<u8> { hex::unused(endian); return hex::crypt::encodeUleb128(std::strtoull(value.c_str(), nullptr, 0)); } ); ContentRegistry::DataInspector::add("hex.builtin.inspector.bool", sizeof(bool), [](auto buffer, auto endian, auto style) { hex::unused(endian, style); std::string value = [buffer] { switch (buffer[0]) { case false: return "false"; case true: return "true"; default: return "Invalid"; } }(); return [value] { ImGui::TextUnformatted(value.c_str()); return value; }; } ); ContentRegistry::DataInspector::add("hex.builtin.inspector.ascii", sizeof(char8_t), [](auto buffer, auto endian, auto style) { hex::unused(endian, style); auto value = makePrintable(*reinterpret_cast<char8_t *>(buffer.data())); return [value] { ImGuiExt::TextFormatted("'{0}'", value.c_str()); return value; }; }, [](const std::string &value, std::endian endian) -> std::vector<u8> { hex::unused(endian); if (value.length() > 1) return { }; return { u8(value[0]) }; } ); ContentRegistry::DataInspector::add("hex.builtin.inspector.wide", sizeof(wchar_t), [](auto buffer, auto endian, auto style) { hex::unused(style); wchar_t wideChar = '\x00'; std::memcpy(&wideChar, buffer.data(), std::min(sizeof(wchar_t), buffer.size())); auto c = hex::changeEndianness(wideChar, endian); std::wstring_convert<std::codecvt_utf8<wchar_t>> converter("Invalid"); auto value = hex::format("{0}", c <= 255 ? makePrintable(c) : converter.to_bytes(c)); return [value] { ImGuiExt::TextFormatted("'{0}'", value.c_str()); return value; }; }, [](const std::string &value, std::endian endian) -> std::vector<u8> { std::wstring_convert<std::codecvt_utf8<wchar_t>> converter("Invalid"); std::vector<u8> bytes; auto wideString = converter.from_bytes(value.c_str()); std::copy(wideString.begin(), wideString.end(), std::back_inserter(bytes)); if (endian != std::endian::native) std::reverse(bytes.begin(), bytes.end()); return bytes; } ); ContentRegistry::DataInspector::add("hex.builtin.inspector.utf8", sizeof(char8_t) * 4, [](auto buffer, auto endian, auto style) { hex::unused(endian, style); char utf8Buffer[5] = { 0 }; char codepointString[5] = { 0 }; u32 codepoint = 0; std::memcpy(utf8Buffer, reinterpret_cast<char8_t *>(buffer.data()), 4); u8 codepointSize = ImTextCharFromUtf8(&codepoint, utf8Buffer, utf8Buffer + 4); std::memcpy(codepointString, utf8Buffer, std::min(codepointSize, u8(4))); auto value = hex::format("'{0}' (U+0x{1:04X})", codepoint == 0xFFFD ? "Invalid" : (codepointSize == 1 ? makePrintable(codepointString[0]) : codepointString), codepoint); return [value] { ImGui::TextUnformatted(value.c_str()); return value; }; } ); constexpr static auto MaxStringLength = 32; ContentRegistry::DataInspector::add("hex.builtin.inspector.string", 1, [](auto buffer, auto endian, auto style) { hex::unused(buffer, endian, style); auto currSelection = ImHexApi::HexEditor::getSelection(); std::string value, copyValue; if (currSelection.has_value()) { std::vector<u8> stringBuffer(std::min<size_t>(currSelection->size, 0x1000), 0x00); ImHexApi::Provider::get()->read(currSelection->address, stringBuffer.data(), stringBuffer.size()); value = copyValue = hex::encodeByteString(stringBuffer); if (value.size() > MaxStringLength) { value.resize(MaxStringLength); value += "..."; } } else { value = ""; copyValue = ""; } return [value, copyValue] { ImGuiExt::TextFormatted("\"{0}\"", value.c_str()); return copyValue; }; }, [](const std::string &value, std::endian endian) -> std::vector<u8> { hex::unused(endian); return hex::decodeByteString(value); } ); ContentRegistry::DataInspector::add("hex.builtin.inspector.string16", 2, [](auto buffer, auto endian, auto style) { hex::unused(buffer, endian, style); auto currSelection = ImHexApi::HexEditor::getSelection(); std::string value, copyValue; if (currSelection.has_value()) { std::u16string stringBuffer(std::min<size_t>(currSelection->size, 0x1000), 0x00); ImHexApi::Provider::get()->read(currSelection->address, stringBuffer.data(), stringBuffer.size()); for (auto &c : stringBuffer) c = hex::changeEndianness(c, endian); auto it = std::remove_if(buffer.begin(), buffer.end(), [](auto c) { return c == 0x00; }); buffer.erase(it, buffer.end()); auto string = std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t>("Invalid").to_bytes(stringBuffer.data()); value = copyValue = hex::encodeByteString({ string.begin(), string.end() }); if (value.size() > MaxStringLength) { value.resize(MaxStringLength); value += "..."; } } else { value = ""; copyValue = ""; } return [value, copyValue] { ImGuiExt::TextFormatted("L\"{0}\"", value.c_str()); return copyValue; }; }, [](const std::string &value, std::endian endian) -> std::vector<u8> { hex::unused(endian); return hex::decodeByteString(value); } ); #if defined(OS_WINDOWS) ContentRegistry::DataInspector::add("hex.builtin.inspector.time32", sizeof(u32), [](auto buffer, auto endian, auto style) { hex::unused(style); auto endianAdjustedTime = hex::changeEndianness(*reinterpret_cast<u32 *>(buffer.data()), endian); std::string value; try { value = hex::format("{0:%a, %d.%m.%Y %H:%M:%S}", fmt::localtime(endianAdjustedTime)); } catch (fmt::format_error &) { value = "Invalid"; } return [value] { ImGui::TextUnformatted(value.c_str()); return value; }; }); ContentRegistry::DataInspector::add("hex.builtin.inspector.time64", sizeof(u64), [](auto buffer, auto endian, auto style) { hex::unused(style); auto endianAdjustedTime = hex::changeEndianness(*reinterpret_cast<u64 *>(buffer.data()), endian); std::string value; try { value = hex::format("{0:%a, %d.%m.%Y %H:%M:%S}", fmt::localtime(endianAdjustedTime)); } catch (fmt::format_error &) { value = "Invalid"; } return [value] { ImGui::TextUnformatted(value.c_str()); return value; }; }); #else ContentRegistry::DataInspector::add("hex.builtin.inspector.time", sizeof(time_t), [](auto buffer, auto endian, auto style) { hex::unused(style); auto endianAdjustedTime = hex::changeEndianness(*reinterpret_cast<time_t *>(buffer.data()), endian); std::string value; try { value = hex::format("{0:%a, %d.%m.%Y %H:%M:%S}", fmt::localtime(endianAdjustedTime)); } catch (fmt::format_error &e) { value = "Invalid"; } return [value] { ImGui::TextUnformatted(value.c_str()); return value; }; }); #endif struct DOSDate { unsigned day : 5; unsigned month : 4; unsigned year : 7; }; struct DOSTime { unsigned seconds : 5; unsigned minutes : 6; unsigned hours : 5; }; ContentRegistry::DataInspector::add("hex.builtin.inspector.dos_date", sizeof(DOSDate), [](auto buffer, auto endian, auto style) { hex::unused(style); DOSDate date = { }; std::memcpy(&date, buffer.data(), sizeof(DOSDate)); date = hex::changeEndianness(date, endian); auto value = hex::format("{}/{}/{}", date.day, date.month, date.year + 1980); return [value] { ImGui::TextUnformatted(value.c_str()); return value; }; }); ContentRegistry::DataInspector::add("hex.builtin.inspector.dos_time", sizeof(DOSTime), [](auto buffer, auto endian, auto style) { hex::unused(style); DOSTime time = { }; std::memcpy(&time, buffer.data(), sizeof(DOSTime)); time = hex::changeEndianness(time, endian); auto value = hex::format("{:02}:{:02}:{:02}", time.hours, time.minutes, time.seconds * 2); return [value] { ImGui::TextUnformatted(value.c_str()); return value; }; }); ContentRegistry::DataInspector::add("hex.builtin.inspector.guid", sizeof(GUID), [](auto buffer, auto endian, auto style) { hex::unused(style); GUID guid = { }; std::memcpy(&guid, buffer.data(), sizeof(GUID)); auto value = hex::format("{}{{{:08X}-{:04X}-{:04X}-{:02X}{:02X}-{:02X}{:02X}{:02X}{:02X}{:02X}{:02X}}}", (hex::changeEndianness(guid.data3, endian) >> 12) <= 5 && ((guid.data4[0] >> 4) >= 8 || (guid.data4[0] >> 4) == 0) ? "" : "Invalid ", hex::changeEndianness(guid.data1, endian), hex::changeEndianness(guid.data2, endian), hex::changeEndianness(guid.data3, endian), guid.data4[0], guid.data4[1], guid.data4[2], guid.data4[3], guid.data4[4], guid.data4[5], guid.data4[6], guid.data4[7]); return [value] { ImGui::TextUnformatted(value.c_str()); return value; }; }); ContentRegistry::DataInspector::add("hex.builtin.inspector.rgba8", sizeof(u32), [](auto buffer, auto endian, auto style) { hex::unused(style); ImColor value(hex::changeEndianness(*reinterpret_cast<u32 *>(buffer.data()), endian)); auto copyValue = hex::format("#{:02X}{:02X}{:02X}{:02X}", u8(0xFF * (value.Value.x)), u8(0xFF * (value.Value.y)), u8(0xFF * (value.Value.z)), u8(0xFF * (value.Value.w))); return [value, copyValue] { ImGui::ColorButton("##inspectorColor", value, ImGuiColorEditFlags_None, ImVec2(ImGui::GetColumnWidth(), ImGui::GetTextLineHeight())); return copyValue; }; }); ContentRegistry::DataInspector::add("hex.builtin.inspector.rgb565", sizeof(u16), [](auto buffer, auto endian, auto style) { hex::unused(style); auto value = hex::changeEndianness(*reinterpret_cast<u16 *>(buffer.data()), endian); ImColor color((value & 0x1F) << 3, ((value >> 5) & 0x3F) << 2, ((value >> 11) & 0x1F) << 3, 0xFF); auto copyValue = hex::format("#{:02X}{:02X}{:02X}", u8(0xFF * (color.Value.x)), u8(0xFF * (color.Value.y)), u8(0xFF * (color.Value.z)), 0xFF); return [color, copyValue] { ImGui::ColorButton("##inspectorColor", color, ImGuiColorEditFlags_None, ImVec2(ImGui::GetColumnWidth(), ImGui::GetTextLineHeight())); return copyValue; }; }); } // clang-format on }
24,240
C++
.cpp
450
40.624444
182
0.553939
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
169
tools_entries.cpp
WerWolv_ImHex/plugins/builtin/source/content/tools_entries.cpp
#include <hex/api/content_registry.hpp> #include <hex/api/localization_manager.hpp> #include <content/tools_entries.hpp> #include <imgui.h> namespace hex::plugin::builtin { void drawFileTools() { if (ImGui::BeginTabBar("file_tools_tabs")) { if (ImGui::BeginTabItem("hex.builtin.tools.file_tools.shredder"_lang)) { drawFileToolShredder(); ImGui::EndTabItem(); } if (ImGui::BeginTabItem("hex.builtin.tools.file_tools.splitter"_lang)) { drawFileToolSplitter(); ImGui::EndTabItem(); } if (ImGui::BeginTabItem("hex.builtin.tools.file_tools.combiner"_lang)) { drawFileToolCombiner(); ImGui::EndTabItem(); } ImGui::EndTabBar(); } } void registerToolEntries() { ContentRegistry::Tools::add("hex.builtin.tools.demangler", drawDemangler); ContentRegistry::Tools::add("hex.builtin.tools.ascii_table", drawASCIITable); ContentRegistry::Tools::add("hex.builtin.tools.regex_replacer", drawRegexReplacer); ContentRegistry::Tools::add("hex.builtin.tools.color", drawColorPicker); ContentRegistry::Tools::add("hex.builtin.tools.calc", drawMathEvaluator); ContentRegistry::Tools::add("hex.builtin.tools.graphing", drawGraphingCalculator); ContentRegistry::Tools::add("hex.builtin.tools.base_converter", drawBaseConverter); ContentRegistry::Tools::add("hex.builtin.tools.byte_swapper", drawByteSwapper); ContentRegistry::Tools::add("hex.builtin.tools.permissions", drawPermissionsCalculator); //ContentRegistry::Tools::add("hex.builtin.tools.file_uploader", drawFileUploader); ContentRegistry::Tools::add("hex.builtin.tools.wiki_explain", drawWikiExplainer); ContentRegistry::Tools::add("hex.builtin.tools.file_tools", drawFileTools); ContentRegistry::Tools::add("hex.builtin.tools.ieee754", drawIEEE754Decoder); ContentRegistry::Tools::add("hex.builtin.tools.invariant_multiplication", drawInvariantMultiplicationDecoder); ContentRegistry::Tools::add("hex.builtin.tools.tcp_client_server", drawTCPClientServer); ContentRegistry::Tools::add("hex.builtin.tools.euclidean_algorithm", drawEuclidianAlgorithm); ContentRegistry::Tools::add("hex.builtin.tools.http_requests", drawHTTPRequestMaker); } }
2,676
C++
.cpp
42
54.166667
120
0.624857
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
170
settings_entries.cpp
WerWolv_ImHex/plugins/builtin/source/content/settings_entries.cpp
#include <hex/api/imhex_api.hpp> #include <hex/api/content_registry.hpp> #include <hex/api/localization_manager.hpp> #include <hex/api/theme_manager.hpp> #include <hex/api/shortcut_manager.hpp> #include <hex/api/event_manager.hpp> #include <hex/api/layout_manager.hpp> #include <hex/helpers/http_requests.hpp> #include <hex/helpers/utils.hpp> #include <imgui.h> #include <hex/ui/imgui_imhex_extensions.h> #include <fonts/codicons_font.h> #include <wolv/literals.hpp> #include <wolv/utils/string.hpp> #include <nlohmann/json.hpp> #include <utility> namespace hex::plugin::builtin { using namespace wolv::literals; namespace { bool s_showScalingWarning = true; /* Values of this setting: 0 - do not check for updates on startup 1 - check for updates on startup 2 - default value - ask the user if he wants to check for updates. This value should only be encountered on the first startup. */ class ServerContactWidget : public ContentRegistry::Settings::Widgets::Widget { public: bool draw(const std::string &name) override { bool enabled = m_value == 1; if (ImGui::Checkbox(name.data(), &enabled)) { m_value = enabled ? 1 : 0; return true; } return false; } void load(const nlohmann::json &data) override { if (data.is_number()) m_value = data.get<int>(); } nlohmann::json store() override { return m_value; } private: u32 m_value = 2; }; class FPSWidget : public ContentRegistry::Settings::Widgets::Widget { public: bool draw(const std::string &name) override { auto format = [this] -> std::string { if (m_value > 200) return "hex.builtin.setting.interface.fps.unlocked"_lang; else if (m_value < 15) return "hex.builtin.setting.interface.fps.native"_lang; else return "%d FPS"; }(); if (ImGui::SliderInt(name.data(), &m_value, 14, 201, format.c_str(), ImGuiSliderFlags_AlwaysClamp)) { return true; } return false; } void load(const nlohmann::json &data) override { if (data.is_number()) m_value = data.get<int>(); } nlohmann::json store() override { return m_value; } private: int m_value = 60; }; class UserFolderWidget : public ContentRegistry::Settings::Widgets::Widget { public: bool draw(const std::string &) override { bool result = false; if (!ImGui::BeginListBox("##UserFolders", ImVec2(-40_scaled, 280_scaled))) { return false; } else { for (size_t n = 0; n < m_paths.size(); n++) { const bool isSelected = (m_itemIndex == n); if (ImGui::Selectable(wolv::util::toUTF8String(m_paths[n]).c_str(), isSelected)) { m_itemIndex = n; } if (isSelected) { ImGui::SetItemDefaultFocus(); } } ImGui::EndListBox(); } ImGui::SameLine(); ImGui::BeginGroup(); if (ImGuiExt::IconButton(ICON_VS_NEW_FOLDER, ImGui::GetStyleColorVec4(ImGuiCol_Text), ImVec2(30, 30))) { fs::openFileBrowser(fs::DialogMode::Folder, {}, [&](const std::fs::path &path) { if (std::find(m_paths.begin(), m_paths.end(), path) == m_paths.end()) { m_paths.emplace_back(path); ImHexApi::System::setAdditionalFolderPaths(m_paths); result = true; } }); } ImGuiExt::InfoTooltip("hex.builtin.setting.folders.add_folder"_lang); if (ImGuiExt::IconButton(ICON_VS_REMOVE_CLOSE, ImGui::GetStyleColorVec4(ImGuiCol_Text), ImVec2(30, 30))) { if (!m_paths.empty()) { m_paths.erase(std::next(m_paths.begin(), m_itemIndex)); ImHexApi::System::setAdditionalFolderPaths(m_paths); result = true; } } ImGuiExt::InfoTooltip("hex.builtin.setting.folders.remove_folder"_lang); ImGui::EndGroup(); return result; } void load(const nlohmann::json &data) override { if (data.is_array()) { std::vector<std::string> pathStrings = data; for (const auto &pathString : pathStrings) { m_paths.emplace_back(pathString); } ImHexApi::System::setAdditionalFolderPaths(m_paths); } } nlohmann::json store() override { std::vector<std::string> pathStrings; for (const auto &path : m_paths) { pathStrings.push_back(wolv::io::fs::toNormalizedPathString(path)); } return pathStrings; } private: u32 m_itemIndex = 0; std::vector<std::fs::path> m_paths; }; class ScalingWidget : public ContentRegistry::Settings::Widgets::Widget { public: bool draw(const std::string &name) override { auto format = [this] -> std::string { if (m_value == 0) return hex::format("{} (x{:.1f})", "hex.builtin.setting.interface.scaling.native"_lang, ImHexApi::System::getNativeScale()); else return "x%.1f"; }(); bool changed = ImGui::SliderFloat(name.data(), &m_value, 0, 4, format.c_str()); if (m_value < 0) m_value = 0; else if (m_value > 10) m_value = 10; if (s_showScalingWarning && (u32(m_value * 10) % 10) != 0) { ImGui::SameLine(); ImGuiExt::HelpHover("hex.builtin.setting.interface.scaling.fractional_warning"_lang, ICON_VS_WARNING, ImGuiExt::GetCustomColorU32(ImGuiCustomCol_ToolbarRed)); } return changed; } void load(const nlohmann::json &data) override { if (data.is_number()) m_value = data.get<float>(); } nlohmann::json store() override { return m_value; } float getValue() const { return m_value; } private: float m_value = 0.0F; }; class AutoBackupWidget : public ContentRegistry::Settings::Widgets::Widget { public: bool draw(const std::string &name) override { auto format = [this] -> std::string { auto value = m_value * 30; if (value == 0) return "hex.ui.common.off"_lang; else if (value < 60) return hex::format("hex.builtin.setting.general.auto_backup_time.format.simple"_lang, value); else return hex::format("hex.builtin.setting.general.auto_backup_time.format.extended"_lang, value / 60, value % 60); }(); if (ImGui::SliderInt(name.data(), &m_value, 0, (30 * 60) / 30, format.c_str(), ImGuiSliderFlags_AlwaysClamp | ImGuiSliderFlags_NoInput)) { return true; } return false; } void load(const nlohmann::json &data) override { if (data.is_number()) m_value = data.get<int>(); } nlohmann::json store() override { return m_value; } private: int m_value = 5 * 2; }; class KeybindingWidget : public ContentRegistry::Settings::Widgets::Widget { public: KeybindingWidget(View *view, const Shortcut &shortcut) : m_view(view), m_shortcut(shortcut), m_drawShortcut(shortcut), m_defaultShortcut(shortcut) {} bool draw(const std::string &name) override { std::string label; if (!m_editing) label = m_drawShortcut.toString(); else label = "..."; if (label.empty()) label = "???"; if (m_hasDuplicate) ImGui::PushStyleColor(ImGuiCol_Text, ImGuiExt::GetCustomColorVec4(ImGuiCustomCol_LoggerError)); ImGui::PushID(this); if (ImGui::Button(label.c_str(), ImVec2(250_scaled, 0))) { m_editing = !m_editing; if (m_editing) ShortcutManager::pauseShortcuts(); else ShortcutManager::resumeShortcuts(); } ImGui::SameLine(); if (m_hasDuplicate) ImGui::PopStyleColor(); bool settingChanged = false; ImGui::BeginDisabled(m_drawShortcut == m_defaultShortcut); if (ImGuiExt::IconButton(ICON_VS_X, ImGui::GetStyleColorVec4(ImGuiCol_Text))) { m_hasDuplicate = !ShortcutManager::updateShortcut(m_shortcut, m_defaultShortcut, m_view); m_drawShortcut = m_defaultShortcut; if (!m_hasDuplicate) { m_shortcut = m_defaultShortcut; settingChanged = true; } } ImGui::EndDisabled(); if (!ImGui::IsItemHovered() && ImGui::IsMouseClicked(ImGuiMouseButton_Left)) { m_editing = false; ShortcutManager::resumeShortcuts(); } ImGui::SameLine(); ImGuiExt::TextFormatted("{}", name); ImGui::PopID(); if (m_editing) { if (this->detectShortcut()) { m_editing = false; ShortcutManager::resumeShortcuts(); settingChanged = true; if (!m_hasDuplicate) { } } } return settingChanged; } void load(const nlohmann::json &data) override { std::set<Key> keys; for (const auto &key : data.get<std::vector<u32>>()) keys.insert(Key(Keys(key))); if (keys.empty()) return; auto newShortcut = Shortcut(keys); m_hasDuplicate = !ShortcutManager::updateShortcut(m_shortcut, newShortcut, m_view); m_shortcut = std::move(newShortcut); m_drawShortcut = m_shortcut; } nlohmann::json store() override { std::vector<u32> keys; for (const auto &key : m_shortcut.getKeys()) { if (key != CurrentView) keys.push_back(key.getKeyCode()); } return keys; } private: bool detectShortcut() { if (const auto &shortcut = ShortcutManager::getPreviousShortcut(); shortcut.has_value()) { auto keys = m_shortcut.getKeys(); std::erase_if(keys, [](Key key) { return key != AllowWhileTyping && key != CurrentView; }); for (const auto &key : shortcut->getKeys()) { keys.insert(key); } auto newShortcut = Shortcut(std::move(keys)); m_hasDuplicate = !ShortcutManager::updateShortcut(m_shortcut, newShortcut, m_view); m_drawShortcut = std::move(newShortcut); if (!m_hasDuplicate) { m_shortcut = m_drawShortcut; log::info("Changed shortcut to {}", shortcut->toString()); } else { log::warn("Changing shortcut failed as it overlapped with another one", shortcut->toString()); } return true; } return false; } private: View *m_view = nullptr; Shortcut m_shortcut, m_drawShortcut, m_defaultShortcut; bool m_editing = false; bool m_hasDuplicate = false; }; class ToolbarIconsWidget : public ContentRegistry::Settings::Widgets::Widget { private: struct MenuItemSorter { bool operator()(const auto *a, const auto *b) const { return a->toolbarIndex < b->toolbarIndex; } }; public: bool draw(const std::string &) override { bool changed = false; // Top level layout table if (ImGui::BeginTable("##top_level", 2, ImGuiTableFlags_None, ImGui::GetContentRegionAvail())) { ImGui::TableSetupColumn("##left", ImGuiTableColumnFlags_WidthStretch, 0.3F); ImGui::TableSetupColumn("##right", ImGuiTableColumnFlags_WidthStretch, 0.7F); ImGui::TableNextRow(); ImGui::TableNextColumn(); // Draw list of menu items that can be added to the toolbar if (ImGui::BeginTable("##all_icons", 1, ImGuiTableFlags_BordersOuter | ImGuiTableFlags_RowBg | ImGuiTableFlags_ScrollY, ImVec2(0, 280_scaled))) { ImGui::TableNextRow(); ImGui::TableNextColumn(); // Loop over all available menu items for (auto &[priority, menuItem] : ContentRegistry::Interface::impl::getMenuItems()) { // Filter out items without icon, separators, submenus and items that are already in the toolbar if (menuItem.icon.glyph.empty()) continue; const auto &unlocalizedName = menuItem.unlocalizedNames.back(); if (menuItem.unlocalizedNames.size() > 2) continue; if (unlocalizedName.get() == ContentRegistry::Interface::impl::SeparatorValue) continue; if (unlocalizedName.get() == ContentRegistry::Interface::impl::SubMenuValue) continue; if (menuItem.toolbarIndex != -1) continue; ImGui::TableNextRow(); ImGui::TableNextColumn(); // Draw the menu item ImGui::Selectable(hex::format("{} {}", menuItem.icon.glyph, Lang(unlocalizedName)).c_str(), false, ImGuiSelectableFlags_SpanAllColumns); // Handle draggin the menu item to the toolbar box if (ImGui::BeginDragDropSource()) { auto ptr = &menuItem; ImGui::SetDragDropPayload("MENU_ITEM_PAYLOAD", &ptr, sizeof(void*)); ImGuiExt::TextFormatted("{} {}", menuItem.icon.glyph, Lang(unlocalizedName)); ImGui::EndDragDropSource(); } } ImGui::EndTable(); } // Handle dropping menu items from the toolbar box if (ImGui::BeginDragDropTarget()) { if (auto payload = ImGui::AcceptDragDropPayload("TOOLBAR_ITEM_PAYLOAD"); payload != nullptr) { auto &menuItem = *static_cast<ContentRegistry::Interface::impl::MenuItem **>(payload->Data); menuItem->toolbarIndex = -1; changed = true; } ImGui::EndDragDropTarget(); } ImGui::TableNextColumn(); // Draw toolbar icon box if (ImGuiExt::BeginSubWindow("hex.builtin.setting.toolbar.icons"_lang, nullptr, ImGui::GetContentRegionAvail())) { if (ImGui::BeginTable("##icons", 6, ImGuiTableFlags_SizingStretchSame, ImGui::GetContentRegionAvail())) { ImGui::TableNextRow(); // Find all menu items that are in the toolbar and sort them by their toolbar index std::set<ContentRegistry::Interface::impl::MenuItem*, MenuItemSorter> toolbarItems; for (auto &[priority, menuItem] : ContentRegistry::Interface::impl::getMenuItemsMutable()) { if (menuItem.toolbarIndex == -1) continue; toolbarItems.emplace(&menuItem); } // Loop over all toolbar items for (auto &menuItem : toolbarItems) { // Filter out items without icon, separators, submenus and items that are not in the toolbar if (menuItem->icon.glyph.empty()) continue; const auto &unlocalizedName = menuItem->unlocalizedNames.back(); if (menuItem->unlocalizedNames.size() > 2) continue; if (unlocalizedName.get() == ContentRegistry::Interface::impl::SubMenuValue) continue; if (menuItem->toolbarIndex == -1) continue; ImGui::TableNextColumn(); // Draw the toolbar item ImGui::InvisibleButton(unlocalizedName.get().c_str(), ImVec2(ImGui::GetContentRegionAvail().x, ImGui::GetContentRegionAvail().x)); // Handle dragging the toolbar item around if (ImGui::BeginDragDropSource()) { ImGui::SetDragDropPayload("TOOLBAR_ITEM_PAYLOAD", &menuItem, sizeof(void*)); ImGuiExt::TextFormatted("{} {}", menuItem->icon.glyph, Lang(unlocalizedName)); ImGui::EndDragDropSource(); } // Handle dropping toolbar items onto each other to reorder them if (ImGui::BeginDragDropTarget()) { if (auto payload = ImGui::AcceptDragDropPayload("TOOLBAR_ITEM_PAYLOAD"); payload != nullptr) { auto &otherMenuItem = *static_cast<ContentRegistry::Interface::impl::MenuItem **>(payload->Data); std::swap(menuItem->toolbarIndex, otherMenuItem->toolbarIndex); changed = true; } ImGui::EndDragDropTarget(); } // Handle right clicking toolbar items to open the color selection popup if (ImGui::IsItemClicked(ImGuiMouseButton_Right)) ImGui::OpenPopup(unlocalizedName.get().c_str()); // Draw the color selection popup if (ImGui::BeginPopup(unlocalizedName.get().c_str())) { constexpr static std::array Colors = { ImGuiCustomCol_ToolbarGray, ImGuiCustomCol_ToolbarRed, ImGuiCustomCol_ToolbarYellow, ImGuiCustomCol_ToolbarGreen, ImGuiCustomCol_ToolbarBlue, ImGuiCustomCol_ToolbarPurple, ImGuiCustomCol_ToolbarBrown }; // Draw all the color buttons for (auto color : Colors) { ImGui::PushID(&color); if (ImGui::ColorButton(hex::format("##color{}", u32(color)).c_str(), ImGuiExt::GetCustomColorVec4(color), ImGuiColorEditFlags_NoTooltip | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_NoPicker, ImVec2(20, 20))) { menuItem->icon.color = color; ImGui::CloseCurrentPopup(); changed = true; } ImGui::PopID(); ImGui::SameLine(); } ImGui::EndPopup(); } auto min = ImGui::GetItemRectMin(); auto max = ImGui::GetItemRectMax(); auto iconSize = ImGui::CalcTextSize(menuItem->icon.glyph.c_str()); std::string text = Lang(unlocalizedName); if (text.ends_with("...")) text = text.substr(0, text.size() - 3); auto textSize = ImGui::CalcTextSize(text.c_str()); // Draw icon and text of the toolbar item auto drawList = ImGui::GetWindowDrawList(); drawList->AddText((min + ((max - min) - iconSize) / 2) - ImVec2(0, 10_scaled), ImGuiExt::GetCustomColorU32(ImGuiCustomCol(menuItem->icon.color)), menuItem->icon.glyph.c_str()); drawList->AddText((min + ((max - min)) / 2) + ImVec2(-textSize.x / 2, 5_scaled), ImGui::GetColorU32(ImGuiCol_Text), text.c_str()); } ImGui::EndTable(); } } ImGuiExt::EndSubWindow(); // Handle dropping menu items onto the toolbar box if (ImGui::BeginDragDropTarget()) { if (auto payload = ImGui::AcceptDragDropPayload("MENU_ITEM_PAYLOAD"); payload != nullptr) { auto &menuItem = *static_cast<ContentRegistry::Interface::impl::MenuItem **>(payload->Data); menuItem->toolbarIndex = m_currIndex; m_currIndex += 1; changed = true; } ImGui::EndDragDropTarget(); } ImGui::EndTable(); } if (changed) { ContentRegistry::Interface::updateToolbarItems(); } return changed; } nlohmann::json store() override { std::map<i32, std::pair<std::string, u32>> items; for (const auto &[priority, menuItem] : ContentRegistry::Interface::impl::getMenuItems()) { if (menuItem.toolbarIndex != -1) items.emplace(menuItem.toolbarIndex, std::make_pair(menuItem.unlocalizedNames.back().get(), menuItem.icon.color)); } return items; } void load(const nlohmann::json &data) override { if (data.is_null()) return; for (auto &[priority, menuItem] : ContentRegistry::Interface::impl::getMenuItemsMutable()) menuItem.toolbarIndex = -1; auto toolbarItems = data.get<std::map<i32, std::pair<std::string, u32>>>(); if (toolbarItems.empty()) return; for (auto &[priority, menuItem] : ContentRegistry::Interface::impl::getMenuItemsMutable()) { for (const auto &[index, value] : toolbarItems) { const auto &[name, color] = value; if (menuItem.unlocalizedNames.back().get() == name) { menuItem.toolbarIndex = index; menuItem.icon.color = ImGuiCustomCol(color); break; } } } m_currIndex = toolbarItems.size(); ContentRegistry::Interface::updateToolbarItems(); } private: i32 m_currIndex = 0; }; class FontFilePicker : public ContentRegistry::Settings::Widgets::FilePicker { public: bool draw(const std::string &name) override { bool changed = false; const auto &fonts = hex::getFonts(); bool customFont = false; std::string pathPreview = ""; if (m_path.empty()) { pathPreview = "Default Font"; } else if (fonts.contains(m_path)) { pathPreview = fonts.at(m_path); } else { pathPreview = wolv::util::toUTF8String(m_path.filename()); customFont = true; } if (ImGui::BeginCombo(name.c_str(), pathPreview.c_str())) { if (ImGui::Selectable("Default Font", m_path.empty())) { m_path.clear(); changed = true; } if (ImGui::Selectable("Custom Font", customFont)) { changed = fs::openFileBrowser(fs::DialogMode::Open, { { "TTF Font", "ttf" }, { "OTF Font", "otf" } }, [this](const std::fs::path &path) { m_path = path; }); } for (const auto &[path, fontName] : fonts) { if (ImGui::Selectable(fontName.c_str(), m_path == path)) { m_path = path; changed = true; } } ImGui::EndCombo(); } return changed; } }; bool getDefaultBorderlessWindowMode() { bool result; #if defined (OS_WINDOWS) result = true; // Intel's OpenGL driver is extremely buggy. Its issues can manifest in lots of different ways // such as "colorful snow" appearing on the screen or, the most annoying issue, // it might draw the window content slightly offset to the bottom right as seen in issue #1625 // The latter issue can be circumvented by using the native OS decorations or by using the software renderer. // This code here tries to detect if the user has a problematic Intel GPU and if so, it will default to the native OS decorations. // This doesn't actually solve the issue at all but at least it makes ImHex usable on these GPUs. const bool isIntelGPU = hex::containsIgnoreCase(ImHexApi::System::getGPUVendor(), "Intel"); if (isIntelGPU) { log::warn("Intel GPU detected! Intel's OpenGL GPU drivers are extremely buggy and can cause issues when using ImHex. If you experience any rendering bugs, please enable the Native OS Decoration setting or try the software rendererd -NoGPU release."); // Non-exhaustive list of bad GPUs. // If more GPUs are found to be problematic, they can be added here. constexpr static std::array BadGPUs = { // Sandy Bridge Series, Second Gen HD Graphics "HD Graphics 2000", "HD Graphics 3000" }; const auto &glRenderer = ImHexApi::System::getGLRenderer(); for (const auto &badGPU : BadGPUs) { if (hex::containsIgnoreCase(glRenderer, badGPU)) { result = false; break; } } } #elif defined(OS_MACOS) result = true; #elif defined(OS_LINUX) // On Linux, things like Window snapping and moving is hard to implement // without hacking e.g. libdecor, therefor we default to the native window decorations. result = false; #else result = false; #endif return result; } } void registerSettings() { namespace Widgets = ContentRegistry::Settings::Widgets; /* General */ { ContentRegistry::Settings::add<Widgets::Checkbox>("hex.builtin.setting.general", "", "hex.builtin.setting.general.show_tips", false); ContentRegistry::Settings::add<Widgets::Checkbox>("hex.builtin.setting.general", "", "hex.builtin.setting.general.save_recent_providers", true); ContentRegistry::Settings::add<AutoBackupWidget>("hex.builtin.setting.general", "", "hex.builtin.setting.general.auto_backup_time"); ContentRegistry::Settings::add<Widgets::SliderDataSize>("hex.builtin.setting.general", "", "hex.builtin.setting.general.max_mem_file_size", 128_MiB, 0_bytes, 32_GiB) .setTooltip("hex.builtin.setting.general.max_mem_file_size.desc"); ContentRegistry::Settings::add<Widgets::Checkbox>("hex.builtin.setting.general", "hex.builtin.setting.general.patterns", "hex.builtin.setting.general.auto_load_patterns", true); ContentRegistry::Settings::add<Widgets::Checkbox>("hex.builtin.setting.general", "hex.builtin.setting.general.patterns", "hex.builtin.setting.general.sync_pattern_source", false); ContentRegistry::Settings::add<Widgets::Checkbox>("hex.builtin.setting.general", "hex.builtin.setting.general.network", "hex.builtin.setting.general.network_interface", false); #if !defined(OS_WEB) ContentRegistry::Settings::add<ServerContactWidget>("hex.builtin.setting.general", "hex.builtin.setting.general.network", "hex.builtin.setting.general.server_contact"); ContentRegistry::Settings::add<Widgets::Checkbox>("hex.builtin.setting.general", "hex.builtin.setting.general.network", "hex.builtin.setting.general.upload_crash_logs", true); #endif } /* Interface */ { auto themeNames = ThemeManager::getThemeNames(); std::vector<nlohmann::json> themeJsons = { }; for (const auto &themeName : themeNames) themeJsons.emplace_back(themeName); themeNames.emplace(themeNames.begin(), ThemeManager::NativeTheme); themeJsons.emplace(themeJsons.begin(), ThemeManager::NativeTheme); ContentRegistry::Settings::add<Widgets::DropDown>("hex.builtin.setting.interface", "hex.builtin.setting.interface.style", "hex.builtin.setting.interface.color", themeNames, themeJsons, "Dark").setChangedCallback([](auto &widget) { auto dropDown = static_cast<Widgets::DropDown *>(&widget); if (dropDown->getValue() == ThemeManager::NativeTheme) ImHexApi::System::enableSystemThemeDetection(true); else { ImHexApi::System::enableSystemThemeDetection(false); ThemeManager::changeTheme(dropDown->getValue()); } }); ContentRegistry::Settings::add<ScalingWidget>("hex.builtin.setting.interface", "hex.builtin.setting.interface.style", "hex.builtin.setting.interface.scaling_factor") .requiresRestart(); #if defined (OS_WEB) ContentRegistry::Settings::add<Widgets::Checkbox>("hex.builtin.setting.interface", "hex.builtin.setting.interface.style", "hex.builtin.setting.interface.crisp_scaling", false) .setChangedCallback([](Widgets::Widget &widget) { auto checkBox = static_cast<Widgets::Checkbox *>(&widget); EM_ASM({ var canvas = document.getElementById('canvas'); if ($0) canvas.style.imageRendering = 'pixelated'; else canvas.style.imageRendering = 'smooth'; }, checkBox->isChecked()); }); #endif ContentRegistry::Settings::add<Widgets::Checkbox>("hex.builtin.setting.interface", "hex.builtin.setting.interface.style", "hex.builtin.setting.interface.pattern_data_row_bg", false); ContentRegistry::Settings::add<Widgets::Checkbox>("hex.builtin.setting.interface", "hex.builtin.setting.interface.style", "hex.builtin.setting.interface.always_show_provider_tabs", false); ContentRegistry::Settings::add<Widgets::Checkbox>("hex.builtin.setting.interface", "hex.builtin.setting.interface.style", "hex.builtin.setting.interface.show_header_command_palette", true); std::vector<std::string> languageNames; std::vector<nlohmann::json> languageCodes; for (auto &[languageCode, languageName] : LocalizationManager::getSupportedLanguages()) { languageNames.emplace_back(languageName); languageCodes.emplace_back(languageCode); } ContentRegistry::Settings::add<Widgets::DropDown>("hex.builtin.setting.interface", "hex.builtin.setting.interface.language", "hex.builtin.setting.interface.language", languageNames, languageCodes, "en-US"); ContentRegistry::Settings::add<Widgets::TextBox>("hex.builtin.setting.interface", "hex.builtin.setting.interface.language", "hex.builtin.setting.interface.wiki_explain_language", "en"); ContentRegistry::Settings::add<FPSWidget>("hex.builtin.setting.interface", "hex.builtin.setting.interface.window", "hex.builtin.setting.interface.fps"); #if defined (OS_LINUX) constexpr static auto MultiWindowSupportEnabledDefault = 0; #else constexpr static auto MultiWindowSupportEnabledDefault = 1; #endif ContentRegistry::Settings::add<Widgets::Checkbox>("hex.builtin.setting.interface", "hex.builtin.setting.interface.window", "hex.builtin.setting.interface.multi_windows", MultiWindowSupportEnabledDefault).requiresRestart(); #if !defined(OS_WEB) ContentRegistry::Settings::add<Widgets::Checkbox>("hex.builtin.setting.interface", "hex.builtin.setting.interface.window", "hex.builtin.setting.interface.native_window_decorations", !getDefaultBorderlessWindowMode()).requiresRestart(); #endif ContentRegistry::Settings::add<Widgets::Checkbox>("hex.builtin.setting.interface", "hex.builtin.setting.interface.window", "hex.builtin.setting.interface.restore_window_pos", false); ContentRegistry::Settings::add<Widgets::ColorPicker>("hex.builtin.setting.hex_editor", "", "hex.builtin.setting.hex_editor.highlight_color", ImColor(0x80, 0x80, 0xC0, 0x60)); ContentRegistry::Settings::add<Widgets::Checkbox>("hex.builtin.setting.hex_editor", "", "hex.builtin.setting.hex_editor.sync_scrolling", false); ContentRegistry::Settings::add<Widgets::SliderInteger>("hex.builtin.setting.hex_editor", "", "hex.builtin.setting.hex_editor.byte_padding", 0, 0, 50); ContentRegistry::Settings::add<Widgets::SliderInteger>("hex.builtin.setting.hex_editor", "", "hex.builtin.setting.hex_editor.char_padding", 0, 0, 50); ContentRegistry::Settings::add<Widgets::Checkbox>("hex.builtin.setting.hex_editor", "", "hex.builtin.setting.hex_editor.pattern_parent_highlighting", true); } /* Fonts */ { const auto scaleWarningHandler = [](auto&) { s_showScalingWarning = ImHexApi::Fonts::getCustomFontPath().empty() && ContentRegistry::Settings::read<bool>("hex.builtin.setting.font", "hex.builtin.setting.font.pixel_perfect_default_font", true); }; ContentRegistry::Settings::add<Widgets::Checkbox>("hex.builtin.setting.font", "hex.builtin.setting.font.glyphs", "hex.builtin.setting.font.load_all_unicode_chars", false) .requiresRestart(); auto customFontEnabledSetting = ContentRegistry::Settings::add<Widgets::Checkbox>("hex.builtin.setting.font", "hex.builtin.setting.font.custom_font", "hex.builtin.setting.font.custom_font_enable", false).requiresRestart(); const auto customFontsEnabled = [customFontEnabledSetting] { auto &customFontsEnabled = static_cast<Widgets::Checkbox &>(customFontEnabledSetting.getWidget()); return customFontsEnabled.isChecked(); }; auto customFontPathSetting = ContentRegistry::Settings::add<FontFilePicker>("hex.builtin.setting.font", "hex.builtin.setting.font.custom_font", "hex.builtin.setting.font.font_path") .requiresRestart() .setChangedCallback(scaleWarningHandler) .setEnabledCallback(customFontsEnabled); const auto customFontSettingsEnabled = [customFontEnabledSetting, customFontPathSetting] { auto &customFontsEnabled = static_cast<Widgets::Checkbox &>(customFontEnabledSetting.getWidget()); auto &fontPath = static_cast<Widgets::FilePicker &>(customFontPathSetting.getWidget()); return customFontsEnabled.isChecked() && !fontPath.getPath().empty(); }; ContentRegistry::Settings::add<Widgets::Checkbox>("hex.builtin.setting.font", "hex.builtin.setting.font.custom_font", "hex.builtin.setting.font.pixel_perfect_default_font", true) .setChangedCallback(scaleWarningHandler) .setEnabledCallback([customFontPathSetting, customFontEnabledSetting] { auto &customFontsEnabled = static_cast<Widgets::Checkbox &>(customFontEnabledSetting.getWidget()); auto &fontPath = static_cast<Widgets::FilePicker &>(customFontPathSetting.getWidget()); return customFontsEnabled.isChecked()&& fontPath.getPath().empty(); }) .requiresRestart(); ContentRegistry::Settings::add<Widgets::Label>("hex.builtin.setting.font", "hex.builtin.setting.font.custom_font", "hex.builtin.setting.font.custom_font_info") .setEnabledCallback(customFontsEnabled); ContentRegistry::Settings::add<Widgets::SliderInteger>("hex.builtin.setting.font", "hex.builtin.setting.font.custom_font", "hex.builtin.setting.font.font_size", 13, 0, 100) .requiresRestart() .setEnabledCallback(customFontSettingsEnabled); ContentRegistry::Settings::add<Widgets::Checkbox>("hex.builtin.setting.font", "hex.builtin.setting.font.custom_font", "hex.builtin.setting.font.font_bold", false) .requiresRestart() .setEnabledCallback(customFontSettingsEnabled); ContentRegistry::Settings::add<Widgets::Checkbox>("hex.builtin.setting.font", "hex.builtin.setting.font.custom_font", "hex.builtin.setting.font.font_italic", false) .requiresRestart() .setEnabledCallback(customFontSettingsEnabled); ContentRegistry::Settings::add<Widgets::Checkbox>("hex.builtin.setting.font", "hex.builtin.setting.font.custom_font", "hex.builtin.setting.font.font_antialias", true) .requiresRestart() .setEnabledCallback(customFontSettingsEnabled); } /* Folders */ { ContentRegistry::Settings::setCategoryDescription("hex.builtin.setting.folders", "hex.builtin.setting.folders.description"); ContentRegistry::Settings::add<UserFolderWidget>("hex.builtin.setting.folders", "", "hex.builtin.setting.folders.description"); } /* Proxy */ { HttpRequest::setProxyUrl(ContentRegistry::Settings::read<std::string>("hex.builtin.setting.proxy", "hex.builtin.setting.proxy.url", "")); ContentRegistry::Settings::setCategoryDescription("hex.builtin.setting.proxy", "hex.builtin.setting.proxy.description"); auto proxyEnabledSetting = ContentRegistry::Settings::add<Widgets::Checkbox>("hex.builtin.setting.proxy", "", "hex.builtin.setting.proxy.enable", false) .setChangedCallback([](Widgets::Widget &widget) { auto checkBox = static_cast<Widgets::Checkbox *>(&widget); HttpRequest::setProxyState(checkBox->isChecked()); }); ContentRegistry::Settings::add<Widgets::TextBox>("hex.builtin.setting.proxy", "", "hex.builtin.setting.proxy.url", "") .setEnabledCallback([proxyEnabledSetting] { auto &checkBox = static_cast<Widgets::Checkbox &>(proxyEnabledSetting.getWidget()); return checkBox.isChecked(); }) .setChangedCallback([](Widgets::Widget &widget) { auto textBox = static_cast<Widgets::TextBox *>(&widget); HttpRequest::setProxyUrl(textBox->getValue()); }); } /* Experiments */ { ContentRegistry::Settings::setCategoryDescription("hex.builtin.setting.experiments", "hex.builtin.setting.experiments.description"); EventImHexStartupFinished::subscribe([]{ for (const auto &[name, experiment] : ContentRegistry::Experiments::impl::getExperiments()) { ContentRegistry::Settings::add<Widgets::Checkbox>("hex.builtin.setting.experiments", "", experiment.unlocalizedName, false) .setTooltip(experiment.unlocalizedDescription) .setChangedCallback([name](Widgets::Widget &widget) { auto checkBox = static_cast<Widgets::Checkbox *>(&widget); ContentRegistry::Experiments::enableExperiement(name, checkBox->isChecked()); }); } }); } /* Shorcuts */ { EventImHexStartupFinished::subscribe([]{ for (const auto &shortcutEntry : ShortcutManager::getGlobalShortcuts()) { ContentRegistry::Settings::add<KeybindingWidget>("hex.builtin.setting.shortcuts", "hex.builtin.setting.shortcuts.global", shortcutEntry.unlocalizedName, nullptr, shortcutEntry.shortcut); } for (auto &[viewName, view] : ContentRegistry::Views::impl::getEntries()) { for (const auto &shortcutEntry : ShortcutManager::getViewShortcuts(view.get())) { ContentRegistry::Settings::add<KeybindingWidget>("hex.builtin.setting.shortcuts", viewName, shortcutEntry.unlocalizedName, view.get(), shortcutEntry.shortcut); } } }); } /* Toolbar icons */ { ContentRegistry::Settings::setCategoryDescription("hex.builtin.setting.toolbar", "hex.builtin.setting.toolbar.description"); ContentRegistry::Settings::add<ToolbarIconsWidget>("hex.builtin.setting.toolbar", "", "hex.builtin.setting.toolbar.icons"); } } static void loadLayoutSettings() { const bool locked = ContentRegistry::Settings::read<bool>("hex.builtin.setting.interface", "hex.builtin.setting.interface.layout_locked", false); LayoutManager::lockLayout(locked); } static void loadThemeSettings() { auto theme = ContentRegistry::Settings::read<std::string>("hex.builtin.setting.interface", "hex.builtin.setting.interface.color", ThemeManager::NativeTheme); if (theme == ThemeManager::NativeTheme) { ImHexApi::System::enableSystemThemeDetection(true); } else { ImHexApi::System::enableSystemThemeDetection(false); ThemeManager::changeTheme(theme); } auto borderlessWindowMode = !ContentRegistry::Settings::read<bool>("hex.builtin.setting.interface", "hex.builtin.setting.interface.native_window_decorations", !getDefaultBorderlessWindowMode()); ImHexApi::System::impl::setBorderlessWindowMode(borderlessWindowMode); } static void loadFolderSettings() { auto folderPathStrings = ContentRegistry::Settings::read<std::vector<std::string>>("hex.builtin.setting.folders", "hex.builtin.setting.folders", { }); std::vector<std::fs::path> paths; for (const auto &pathString : folderPathStrings) { paths.emplace_back(pathString); } ImHexApi::System::setAdditionalFolderPaths(paths); } void loadSettings() { loadLayoutSettings(); loadThemeSettings(); loadFolderSettings(); } }
47,114
C++
.cpp
772
41.145078
270
0.531298
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
171
events.cpp
WerWolv_ImHex/plugins/builtin/source/content/events.cpp
#include <hex/api/event_manager.hpp> #include <hex/api/localization_manager.hpp> #include <hex/api/content_registry.hpp> #include <hex/api/project_file_manager.hpp> #include <hex/api/achievement_manager.hpp> #include <hex/api/workspace_manager.hpp> #include <hex/providers/provider.hpp> #include <hex/ui/view.hpp> #include <imgui.h> #include <content/global_actions.hpp> #include <content/providers/file_provider.hpp> #include <wolv/io/fs.hpp> #include <wolv/utils/string.hpp> #include <toasts/toast_notification.hpp> #include <popups/popup_notification.hpp> #include <popups/popup_question.hpp> #include <content/popups/popup_tasks_waiting.hpp> #include <content/popups/popup_unsaved_changes.hpp> #include <content/popups/popup_crash_recovered.hpp> namespace hex::plugin::builtin { static void openFile(const std::fs::path &path) { if (path.extension() == ".hexproj") { if (!ProjectFile::load(path)) { ui::ToastError::open(hex::format("hex.builtin.popup.error.project.load"_lang, wolv::util::toUTF8String(path))); } else { return; } } auto provider = ImHexApi::Provider::createProvider("hex.builtin.provider.file", true); if (auto *fileProvider = dynamic_cast<FileProvider*>(provider); fileProvider != nullptr) { fileProvider->setPath(path); if (!provider->open() || !provider->isAvailable()) { ui::ToastError::open(hex::format("hex.builtin.provider.error.open"_lang, provider->getErrorMessage())); TaskManager::doLater([provider] { ImHexApi::Provider::remove(provider); }); } else { EventProviderOpened::post(fileProvider); AchievementManager::unlockAchievement("hex.builtin.achievement.starting_out", "hex.builtin.achievement.starting_out.open_file.name"); } } } void registerEventHandlers() { static bool imhexClosing = false; EventCrashRecovered::subscribe([](const std::exception &e) { PopupCrashRecovered::open(e); }); EventWindowClosing::subscribe([](GLFWwindow *window) { imhexClosing = false; if (ImHexApi::Provider::isDirty() && !imhexClosing) { glfwSetWindowShouldClose(window, GLFW_FALSE); ui::PopupQuestion::open("hex.builtin.popup.exit_application.desc"_lang, [] { imhexClosing = true; for (const auto &provider : ImHexApi::Provider::getProviders()) ImHexApi::Provider::remove(provider); }, [] { } ); } else if (TaskManager::getRunningTaskCount() > 0 || TaskManager::getRunningBackgroundTaskCount() > 0) { glfwSetWindowShouldClose(window, GLFW_FALSE); TaskManager::doLater([] { for (auto &task : TaskManager::getRunningTasks()) task->interrupt(); PopupTasksWaiting::open(); }); } }); EventProviderClosing::subscribe([](const prv::Provider *provider, bool *shouldClose) { if (provider->isDirty()) { *shouldClose = false; PopupUnsavedChanges::open("hex.builtin.popup.close_provider.desc"_lang, []{ const bool projectSaved = ProjectFile::hasPath() ? saveProject() : saveProjectAs(); if (projectSaved) { for (const auto &provider : ImHexApi::Provider::impl::getClosingProviders()) ImHexApi::Provider::remove(provider, true); if (imhexClosing) ImHexApi::System::closeImHex(true); } else { ImHexApi::Provider::impl::resetClosingProvider(); imhexClosing = false; } }, [] { for (const auto &provider : ImHexApi::Provider::impl::getClosingProviders()) ImHexApi::Provider::remove(provider, true); if (imhexClosing) ImHexApi::System::closeImHex(true); }, [] { ImHexApi::Provider::impl::resetClosingProvider(); imhexClosing = false; } ); } }); EventProviderChanged::subscribe([](hex::prv::Provider *oldProvider, hex::prv::Provider *newProvider) { hex::unused(oldProvider); hex::unused(newProvider); RequestUpdateWindowTitle::post(); }); EventProviderOpened::subscribe([](hex::prv::Provider *provider) { if (provider != nullptr && ImHexApi::Provider::get() == provider) { RequestUpdateWindowTitle::post(); } }); RequestOpenFile::subscribe(openFile); RequestOpenWindow::subscribe([](const std::string &name) { if (name == "Create File") { auto newProvider = hex::ImHexApi::Provider::createProvider("hex.builtin.provider.mem_file", true); if (newProvider != nullptr && !newProvider->open()) hex::ImHexApi::Provider::remove(newProvider); else EventProviderOpened::post(newProvider); } else if (name == "Open File") { fs::openFileBrowser(fs::DialogMode::Open, { }, [](const auto &path) { if (path.extension() == ".hexproj") { if (!ProjectFile::load(path)) { ui::ToastError::open(hex::format("hex.builtin.popup.error.project.load"_lang, wolv::util::toUTF8String(path))); } else { return; } } auto newProvider = static_cast<FileProvider*>( ImHexApi::Provider::createProvider("hex.builtin.provider.file", true) ); if (newProvider == nullptr) return; newProvider->setPath(path); if (!newProvider->open()) { hex::ImHexApi::Provider::remove(newProvider); } else { EventProviderOpened::post(newProvider); AchievementManager::unlockAchievement("hex.builtin.achievement.starting_out", "hex.builtin.achievement.starting_out.open_file.name"); } }, {}, true); } else if (name == "Open Project") { fs::openFileBrowser(fs::DialogMode::Open, { {"Project File", "hexproj"} }, [](const auto &path) { if (!ProjectFile::load(path)) { ui::ToastError::open(hex::format("hex.builtin.popup.error.project.load"_lang, wolv::util::toUTF8String(path))); } }); } }); EventProviderChanged::subscribe([](auto, auto) { EventHighlightingChanged::post(); }); // Handles the provider initialization, and calls EventProviderOpened if successful EventProviderCreated::subscribe([](hex::prv::Provider *provider) { if (provider->shouldSkipLoadInterface()) return; if (provider->hasFilePicker()) { if (!provider->handleFilePicker()) { TaskManager::doLater([provider] { ImHexApi::Provider::remove(provider); }); return; } if (!provider->open()) { ui::ToastError::open(hex::format("hex.builtin.provider.error.open"_lang, provider->getErrorMessage())); TaskManager::doLater([provider] { ImHexApi::Provider::remove(provider); }); return; } EventProviderOpened::post(provider); } else if (!provider->hasLoadInterface()) { if (!provider->open() || !provider->isAvailable()) { ui::ToastError::open(hex::format("hex.builtin.provider.error.open"_lang, provider->getErrorMessage())); TaskManager::doLater([provider] { ImHexApi::Provider::remove(provider); }); return; } EventProviderOpened::post(provider); } }); EventRegionSelected::subscribe([](const ImHexApi::HexEditor::ProviderRegion &region) { ImHexApi::HexEditor::impl::setCurrentSelection(region); }); EventFileDropped::subscribe([](const std::fs::path &path) { // Check if a custom file handler can handle the file bool handled = false; for (const auto &[extensions, handler] : ContentRegistry::FileHandler::impl::getEntries()) { for (const auto &extension : extensions) { if (path.extension() == extension) { // Pass the file to the handler and check if it was successful if (!handler(path)) { log::error("Handler for extensions '{}' failed to process file!", extension); break; } handled = true; } } } // If no custom handler was found, just open the file regularly if (!handled) RequestOpenFile::post(path); }); EventWindowInitialized::subscribe([] { if (ContentRegistry::Settings::read<std::string>("hex.builtin.setting.general", "hex.builtin.setting.general.prev_launch_version", "") == "") { EventFirstLaunch::post(); } ContentRegistry::Settings::write<std::string>("hex.builtin.setting.general", "hex.builtin.setting.general.prev_launch_version", ImHexApi::System::getImHexVersion()); }); EventWindowDeinitializing::subscribe([](GLFWwindow *window) { WorkspaceManager::exportToFile(); if (auto workspace = WorkspaceManager::getCurrentWorkspace(); workspace != WorkspaceManager::getWorkspaces().end()) ContentRegistry::Settings::write<std::string>("hex.builtin.setting.general", "hex.builtin.setting.general.curr_workspace", workspace->first); { int x = 0, y = 0, width = 0, height = 0, maximized = 0; glfwGetWindowPos(window, &x, &y); glfwGetWindowSize(window, &width, &height); maximized = glfwGetWindowAttrib(window, GLFW_MAXIMIZED); ContentRegistry::Settings::write<int>("hex.builtin.setting.interface", "hex.builtin.setting.interface.window.x", x); ContentRegistry::Settings::write<int>("hex.builtin.setting.interface", "hex.builtin.setting.interface.window.y", y); ContentRegistry::Settings::write<int>("hex.builtin.setting.interface", "hex.builtin.setting.interface.window.width", width); ContentRegistry::Settings::write<int>("hex.builtin.setting.interface", "hex.builtin.setting.interface.window.height", height); ContentRegistry::Settings::write<int>("hex.builtin.setting.interface", "hex.builtin.setting.interface.window.maximized", maximized); } }); EventImHexStartupFinished::subscribe([] { const auto &initArgs = ImHexApi::System::getInitArguments(); if (auto it = initArgs.find("language"); it != initArgs.end()) LocalizationManager::loadLanguage(it->second); }); EventWindowFocused::subscribe([](bool focused) { const auto ctx = ImGui::GetCurrentContext(); if (ctx == nullptr) return; if (ImGui::IsPopupOpen("", ImGuiPopupFlags_AnyPopup)) return; if (ImGui::IsAnyItemHovered()) return; static ImGuiWindow *lastFocusedWindow = nullptr; if (focused) { // If the main window gains focus again, restore the last focused window ImGui::FocusWindow(lastFocusedWindow); ImGui::FocusWindow(lastFocusedWindow, ImGuiFocusRequestFlags_RestoreFocusedChild); if (lastFocusedWindow != nullptr) log::debug("Restoring focus on window '{}'", lastFocusedWindow->Name ? lastFocusedWindow->Name : "Unknown Window"); } else { // If the main window loses focus, store the currently focused window // and remove focus from it so it doesn't look like it's focused and // cursor blink animations don't play lastFocusedWindow = ctx->NavWindow; ImGui::FocusWindow(nullptr); if (lastFocusedWindow != nullptr) log::debug("Removing focus from window '{}'", lastFocusedWindow->Name ? lastFocusedWindow->Name : "Unknown Window"); } }); fs::setFileBrowserErrorCallback([](const std::string& errMsg){ #if defined(NFD_PORTAL) ui::PopupError::open(hex::format("hex.builtin.popup.error.file_dialog.portal"_lang, errMsg)); #else ui::PopupError::open(hex::format("hex.builtin.popup.error.file_dialog.common"_lang, errMsg)); #endif }); } }
13,781
C++
.cpp
255
38.333333
177
0.553528
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
172
pl_visualizers.cpp
WerWolv_ImHex/plugins/builtin/source/content/pl_visualizers.cpp
#include <hex/api/imhex_api.hpp> #include <hex/api/content_registry.hpp> #include <pl/core/evaluator.hpp> namespace hex::plugin::builtin { void drawHexVisualizer(pl::ptrn::Pattern &, bool, std::span<const pl::core::Token::Literal> arguments); void drawChunkBasedEntropyVisualizer(pl::ptrn::Pattern &, bool, std::span<const pl::core::Token::Literal> arguments); void registerPatternLanguageVisualizers() { using ParamCount = pl::api::FunctionParameterCount; ContentRegistry::PatternLanguage::addVisualizer("hex_viewer", drawHexVisualizer, ParamCount::exactly(1)); ContentRegistry::PatternLanguage::addVisualizer("chunk_entropy", drawChunkBasedEntropyVisualizer, ParamCount::exactly(2)); } }
741
C++
.cpp
12
57
136
0.751381
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
173
project.cpp
WerWolv_ImHex/plugins/builtin/source/content/project.cpp
#include <filesystem> #include <wolv/utils/guards.hpp> #include <wolv/utils/string.hpp> #include <hex/api/imhex_api.hpp> #include <hex/api/project_file_manager.hpp> #include <hex/api/localization_manager.hpp> #include <hex/api/achievement_manager.hpp> #include <hex/api/content_registry.hpp> #include <hex/api/event_manager.hpp> #include <hex/providers/provider.hpp> #include <hex/helpers/fmt.hpp> #include <hex/helpers/logger.hpp> #include <toasts/toast_notification.hpp> namespace hex::plugin::builtin { constexpr static auto MetadataHeaderMagic = "HEX"; constexpr static auto MetadataPath = "IMHEX_METADATA"; bool load(const std::fs::path &filePath) { if (!wolv::io::fs::exists(filePath) || !wolv::io::fs::isRegularFile(filePath)) { ui::ToastError::open(hex::format("hex.builtin.popup.error.project.load"_lang, hex::format("hex.builtin.popup.error.project.load.file_not_found"_lang, wolv::util::toUTF8String(filePath) ))); return false; } Tar tar(filePath, Tar::Mode::Read); if (!tar.isValid()) { ui::ToastError::open(hex::format("hex.builtin.popup.error.project.load"_lang, hex::format("hex.builtin.popup.error.project.load.invalid_tar"_lang, tar.getOpenErrorString() ))); return false; } if (!tar.contains(MetadataPath)) { ui::ToastError::open(hex::format("hex.builtin.popup.error.project.load"_lang, hex::format("hex.builtin.popup.error.project.load.invalid_magic"_lang) )); return false; } { const auto metadataContent = tar.readVector(MetadataPath); if (!std::string(metadataContent.begin(), metadataContent.end()).starts_with(MetadataHeaderMagic)) { ui::ToastError::open(hex::format("hex.builtin.popup.error.project.load"_lang, hex::format("hex.builtin.popup.error.project.load.invalid_magic"_lang) )); return false; } } for (const auto &provider : ImHexApi::Provider::getProviders()) { ImHexApi::Provider::remove(provider); } auto originalPath = ProjectFile::getPath(); ProjectFile::setPath(filePath); auto resetPath = SCOPE_GUARD { ProjectFile::setPath(originalPath); }; for (const auto &handler : ProjectFile::getHandlers()) { bool result = true; // Handlers are supposed to show the error/warning popup to the user themselves, so we don't show one here try { if (!handler.load(handler.basePath, tar)) { log::warn("Project file handler for {} failed to load {}", filePath.string(), handler.basePath.string()); result = false; } } catch (std::exception &e) { log::warn("Project file handler for {} failed to load {}: {}", filePath.string(), handler.basePath.string(), e.what()); result = false; } if (!result && handler.required) { return false; } } for (const auto &provider : ImHexApi::Provider::getProviders()) { const auto basePath = std::fs::path(std::to_string(provider->getID())); for (const auto &handler: ProjectFile::getProviderHandlers()) { bool result = true; // Handlers are supposed to show the error/warning popup to the user themselves, so we don't show one here try { if (!handler.load(provider, basePath / handler.basePath, tar)) result = false; } catch (std::exception &e) { log::info("{}", e.what()); result = false; } if (!result && handler.required) { return false; } } } resetPath.release(); EventProjectOpened::post(); RequestUpdateWindowTitle::post(); return true; } bool store(std::optional<std::fs::path> filePath = std::nullopt, bool updateLocation = true) { auto originalPath = ProjectFile::getPath(); if (!filePath.has_value()) filePath = originalPath; ProjectFile::setPath(filePath.value()); auto resetPath = SCOPE_GUARD { ProjectFile::setPath(originalPath); }; Tar tar(*filePath, Tar::Mode::Create); if (!tar.isValid()) return false; bool result = true; for (const auto &handler : ProjectFile::getHandlers()) { try { if (!handler.store(handler.basePath, tar) && handler.required) result = false; } catch (std::exception &e) { log::info("{}", e.what()); if (handler.required) result = false; } } for (const auto &provider : ImHexApi::Provider::getProviders()) { const auto basePath = std::fs::path(std::to_string(provider->getID())); for (const auto &handler: ProjectFile::getProviderHandlers()) { try { if (!handler.store(provider, basePath / handler.basePath, tar) && handler.required) result = false; } catch (std::exception &e) { log::info("{}", e.what()); if (handler.required) result = false; } } } { const auto metadataContent = hex::format("{}\n{}", MetadataHeaderMagic, ImHexApi::System::getImHexVersion()); tar.writeString(MetadataPath, metadataContent); } ImHexApi::Provider::resetDirty(); // If saveLocation is false, reset the project path (do not release the lock) if (updateLocation) { resetPath.release(); // Request, as this puts us into a project state RequestUpdateWindowTitle::post(); } AchievementManager::unlockAchievement("hex.builtin.achievement.starting_out", "hex.builtin.achievement.starting_out.save_project.name"); return result; } void registerProjectHandlers() { hex::ProjectFile::setProjectFunctions(load, store); } }
6,520
C++
.cpp
146
32.582192
144
0.565293
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
174
ui_items.cpp
WerWolv_ImHex/plugins/builtin/source/content/ui_items.cpp
#include <hex/api/content_registry.hpp> #include <hex/api/imhex_api.hpp> #include <hex/api/localization_manager.hpp> #include <hex/api/task_manager.hpp> #include <hex/ui/view.hpp> #include <hex/helpers/utils.hpp> #include <hex/helpers/fmt.hpp> #include <hex/helpers/logger.hpp> #include <hex/helpers/debugging.hpp> #include <fonts/codicons_font.h> #include <imgui.h> #include <imgui_internal.h> #include <implot.h> #include <hex/ui/imgui_imhex_extensions.h> #include <toasts/toast_notification.hpp> #include <csignal> namespace hex::plugin::builtin { void addTitleBarButtons() { #if defined(DEBUG) ContentRegistry::Interface::addTitleBarButton(ICON_VS_DEBUG, "hex.builtin.title_bar_button.debug_build", []{ if (ImGui::GetIO().KeyShift) { RequestOpenPopup::post("DebugMenu"); } else { hex::openWebpage("https://imhex.werwolv.net/debug"); } }); #endif ContentRegistry::Interface::addTitleBarButton(ICON_VS_SMILEY, "hex.builtin.title_bar_button.feedback", []{ hex::openWebpage("https://github.com/WerWolv/ImHex/discussions/categories/feedback"); }); } static void drawGlobalPopups() { // Task exception toast for (const auto &task : TaskManager::getRunningTasks()) { if (task->hadException()) { ui::ToastError::open(hex::format("hex.builtin.popup.error.task_exception"_lang, Lang(task->getUnlocalizedName()), task->getExceptionMessage())); task->clearException(); break; } } } #if defined(DEBUG) static void drawDebugPopup() { static bool showImGuiDemo = false; static bool showImPlotDemo = false; ImGui::SetNextWindowSize(scaled({ 300, 150 }), ImGuiCond_Always); if (ImGui::BeginPopup("DebugMenu")) { if (ImGui::BeginTabBar("DebugTabBar")) { if (ImGui::BeginTabItem("ImHex")) { if (ImGui::BeginChild("Scrolling", ImGui::GetContentRegionAvail())) { ImGui::Checkbox("Show Debug Variables", &dbg::impl::getDebugWindowState()); ImGuiExt::Header("Information"); ImGuiExt::TextFormatted("Running Tasks: {0}", TaskManager::getRunningTaskCount()); ImGuiExt::TextFormatted("Running Background Tasks: {0}", TaskManager::getRunningBackgroundTaskCount()); ImGuiExt::TextFormatted("Last Frame Time: {0:.3f}ms", ImHexApi::System::getLastFrameTime() * 1000.0F); } ImGui::EndChild(); ImGui::EndTabItem(); } if (ImGui::BeginTabItem("ImGui")) { if (ImGui::BeginChild("Scrolling", ImGui::GetContentRegionAvail())) { auto ctx = ImGui::GetCurrentContext(); ImGui::Checkbox("Show ImGui Demo", &showImGuiDemo); ImGui::Checkbox("Show ImPlot Demo", &showImPlotDemo); if (ImGui::Button("Trigger Breakpoint in Item") || ctx->DebugItemPickerActive) ImGui::DebugStartItemPicker(); } ImGui::EndChild(); ImGui::EndTabItem(); } if (ImGui::BeginTabItem("Crashes")) { if (ImGui::BeginChild("Scrolling", ImGui::GetContentRegionAvail())) { if (ImGui::Button("Throw Exception")) { TaskManager::doLater([] { throw std::runtime_error("Test exception"); }); } if (ImGui::Button("Access Invalid Memory")) { TaskManager::doLater([] { *reinterpret_cast<u32*>(0x10) = 0x10; std::unreachable(); }); } if (ImGui::Button("Raise SIGSEGV")) { TaskManager::doLater([] { raise(SIGSEGV); }); } if (ImGui::Button("Corrupt Memory")) { TaskManager::doLater([] { auto bytes = new u8[0xFFFFF]; delete[] bytes; delete[] bytes; }); } } ImGui::EndChild(); ImGui::EndTabItem(); } ImGui::EndTabBar(); } ImGui::EndPopup(); } if (showImGuiDemo) ImGui::ShowDemoWindow(&showImGuiDemo); if (showImPlotDemo) ImPlot::ShowDemoWindow(&showImPlotDemo); } #endif static bool s_drawDragDropOverlay = false; static void drawDragNDropOverlay() { if (!s_drawDragDropOverlay) return; auto drawList = ImGui::GetForegroundDrawList(); drawList->PushClipRectFullScreen(); { const auto windowPos = ImHexApi::System::getMainWindowPosition(); const auto windowSize = ImHexApi::System::getMainWindowSize(); const auto center = windowPos + (windowSize / 2.0F) - scaled({ 0, 50 }); // Draw background { const ImVec2 margin = scaled({ 15, 15 }); drawList->AddRectFilled(windowPos, windowPos + windowSize, ImGui::GetColorU32(ImGuiCol_WindowBg, 200.0/255.0)); drawList->AddRect(windowPos + margin, (windowPos + windowSize) - margin, ImGuiExt::GetCustomColorU32(ImGuiCustomCol_Highlight), 10_scaled, ImDrawFlags_None, 7.5_scaled); } // Draw drag n drop icon { const ImVec2 iconSize = scaled({ 64, 64 }); const auto offset = scaled({ 15, 15 }); const auto margin = scaled({ 20, 20 }); const auto text = "hex.builtin.drag_drop.text"_lang; const auto textSize = ImGui::CalcTextSize(text); drawList->AddShadowRect(center - ImVec2(textSize.x, iconSize.y + 40_scaled) / 2.0F - offset - margin, center + ImVec2(textSize.x, iconSize.y + 75_scaled) / 2.0F + offset + ImVec2(0, textSize.y) + margin, ImGui::GetColorU32(ImGuiCol_WindowShadow), 20_scaled, ImVec2(), ImDrawFlags_None, 10_scaled); drawList->AddRectFilled(center - ImVec2(textSize.x, iconSize.y + 40_scaled) / 2.0F - offset - margin, center + ImVec2(textSize.x, iconSize.y + 75_scaled) / 2.0F + offset + ImVec2(0, textSize.y) + margin, ImGui::GetColorU32(ImGuiCol_MenuBarBg, 10), 1_scaled, ImDrawFlags_None); drawList->AddRect(center - iconSize / 2.0F - offset, center + iconSize / 2.0F - offset, ImGui::GetColorU32(ImGuiCol_Text), 5_scaled, ImDrawFlags_None, 7.5_scaled); drawList->AddRect(center - iconSize / 2.0F + offset, center + iconSize / 2.0F + offset, ImGui::GetColorU32(ImGuiCol_Text), 5_scaled, ImDrawFlags_None, 7.5_scaled); drawList->AddText(center + ImVec2(-textSize.x / 2, 85_scaled), ImGui::GetColorU32(ImGuiCol_Text), text); } } drawList->PopClipRect(); } void addGlobalUIItems() { EventFrameEnd::subscribe(drawGlobalPopups); EventFrameEnd::subscribe(drawDragNDropOverlay); #if defined(DEBUG) EventFrameEnd::subscribe(drawDebugPopup); #endif EventFileDragged::subscribe([](bool entered) { s_drawDragDropOverlay = entered; }); } void addFooterItems() { if (hex::isProcessElevated()) { ContentRegistry::Interface::addFooterItem([] { ImGui::PushStyleColor(ImGuiCol_Text, ImGuiExt::GetCustomColorU32(ImGuiCustomCol_Highlight)); ImGui::TextUnformatted(ICON_VS_SHIELD); ImGui::PopStyleColor(); }); } #if defined(DEBUG) ContentRegistry::Interface::addFooterItem([] { static float framerate = 0; if (ImGuiExt::HasSecondPassed()) { framerate = 1.0F / ImGui::GetIO().DeltaTime; } ImGuiExt::TextFormatted("FPS {0:3}.{1:02}", u32(framerate), u32(framerate * 100) % 100); if (ImGui::IsItemHovered()) { ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2()); if (ImGui::BeginTooltip()) { static u32 frameCount = 0; static double largestFrameTime = 0; if (ImPlot::BeginPlot("##frame_time_graph", scaled({ 200, 100 }), ImPlotFlags_CanvasOnly | ImPlotFlags_NoFrame | ImPlotFlags_NoInputs)) { ImPlot::SetupAxes("", "", ImPlotAxisFlags_NoLabel | ImPlotAxisFlags_NoTickLabels, ImPlotAxisFlags_NoLabel | ImPlotAxisFlags_LockMin | ImPlotAxisFlags_AutoFit); ImPlot::SetupAxisLimits(ImAxis_Y1, 0, largestFrameTime * 1.25F, ImPlotCond_Always); ImPlot::SetupAxisFormat(ImAxis_Y1, [](double value, char* buff, int size, void*) -> int { return snprintf(buff, size, "%dms", int(value * 1000.0)); }, nullptr); ImPlot::SetupAxisTicks(ImAxis_Y1, 0, largestFrameTime * 1.25F, 3); static std::vector<double> values(100); values.push_back(ImHexApi::System::getLastFrameTime()); if (values.size() > 100) values.erase(values.begin()); if (frameCount % 100 == 0) largestFrameTime = *std::ranges::max_element(values); frameCount += 1; ImPlot::PlotLine("FPS", values.data(), values.size()); ImPlot::EndPlot(); } ImGui::EndTooltip(); } ImGui::PopStyleVar(); } }); #endif ContentRegistry::Interface::addFooterItem([] { static bool shouldResetProgress = false; auto taskCount = TaskManager::getRunningTaskCount(); if (taskCount > 0) { const auto &tasks = TaskManager::getRunningTasks(); const auto &frontTask = tasks.front(); if (frontTask == nullptr) return; const auto progress = frontTask->getMaxValue() == 0 ? -1 : float(frontTask->getValue()) / float(frontTask->getMaxValue()); ImHexApi::System::setTaskBarProgress(ImHexApi::System::TaskProgressState::Progress, ImHexApi::System::TaskProgressType::Normal, u32(progress * 100)); const auto widgetStart = ImGui::GetCursorPos(); { ImGuiExt::TextSpinner(hex::format("({})", taskCount).c_str()); ImGui::SameLine(); ImGuiExt::SmallProgressBar(progress, (ImGui::GetCurrentWindowRead()->MenuBarHeight - 10_scaled) / 2.0); ImGui::SameLine(); } const auto widgetEnd = ImGui::GetCursorPos(); ImGui::SetCursorPos(widgetStart); ImGui::InvisibleButton("RestTasks", ImVec2(widgetEnd.x - widgetStart.x, ImGui::GetCurrentWindowRead()->MenuBarHeight)); ImGui::SetCursorPos(widgetEnd); std::string progressString; if (progress < 0) progressString = ""; else progressString = hex::format("[ {}/{} ({:.1f}%) ] ", frontTask->getValue(), frontTask->getMaxValue(), std::min(progress, 1.0F) * 100.0F); ImGuiExt::InfoTooltip(hex::format("{}{}", progressString, Lang(frontTask->getUnlocalizedName())).c_str()); if (ImGui::BeginPopupContextItem("RestTasks", ImGuiPopupFlags_MouseButtonLeft)) { for (const auto &task : tasks) { if (task->isBackgroundTask()) continue; ImGui::PushID(&task); ImGuiExt::TextFormatted("{}", Lang(task->getUnlocalizedName())); ImGui::SameLine(); ImGui::SeparatorEx(ImGuiSeparatorFlags_Vertical); ImGui::SameLine(); ImGuiExt::SmallProgressBar(task->getMaxValue() == 0 ? -1 : (float(task->getValue()) / float(task->getMaxValue())), (ImGui::GetTextLineHeightWithSpacing() - 5_scaled) / 2); ImGui::SameLine(); ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0)); if (ImGuiExt::ToolBarButton(ICON_VS_DEBUG_STOP, ImGui::GetStyleColorVec4(ImGuiCol_Text))) task->interrupt(); ImGui::PopStyleVar(); ImGui::PopID(); } ImGui::EndPopup(); } ImGui::SameLine(); ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, scaled(ImVec2(1, 2))); if (ImGuiExt::ToolBarButton(ICON_VS_DEBUG_STOP, ImGui::GetStyleColorVec4(ImGuiCol_Text))) frontTask->interrupt(); ImGui::PopStyleVar(); shouldResetProgress = true; } else { if (shouldResetProgress) { ImHexApi::System::setTaskBarProgress(ImHexApi::System::TaskProgressState::Reset, ImHexApi::System::TaskProgressType::Normal, 0); shouldResetProgress = false; } } }); ContentRegistry::Interface::addFooterItem([] { if (auto selection = ImHexApi::HexEditor::getSelection(); selection.has_value()) { ImGuiExt::TextFormatted("0x{0:02X} - 0x{1:02X} (0x{2:02X} | {2} bytes)", selection->getStartAddress(), selection->getEndAddress(), selection->getSize() ); } }); } static void drawProviderContextMenu(prv::Provider *provider) { for (const auto &menuEntry : provider->getMenuEntries()) { if (ImGui::MenuItem(menuEntry.name.c_str())) { menuEntry.callback(); } } } void drawProviderTooltip(const prv::Provider *provider) { if (ImGuiExt::InfoTooltip()) { ImGui::BeginTooltip(); ImGuiExt::TextFormatted("{}", provider->getName().c_str()); const auto &description = provider->getDataDescription(); if (!description.empty()) { ImGui::Separator(); if (ImGui::GetIO().KeyShift && !description.empty()) { if (ImGui::BeginTable("information", 2, ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_RowBg | ImGuiTableFlags_NoKeepColumnsVisible, ImVec2(400_scaled, 0))) { ImGui::TableSetupColumn("type"); ImGui::TableSetupColumn("value", ImGuiTableColumnFlags_WidthStretch); ImGui::TableNextRow(); for (auto &[name, value] : description) { ImGui::TableNextColumn(); ImGuiExt::TextFormatted("{}", name); ImGui::TableNextColumn(); ImGuiExt::TextFormattedWrapped("{}", value); } ImGui::EndTable(); } } else { ImGuiExt::TextFormattedDisabled("hex.builtin.provider.tooltip.show_more"_lang); } } ImGui::EndTooltip(); } } void addToolbarItems() { ShortcutManager::addGlobalShortcut(AllowWhileTyping + ALT + CTRLCMD + Keys::Left, "hex.builtin.shortcut.prev_provider", []{ auto currIndex = ImHexApi::Provider::getCurrentProviderIndex(); if (currIndex > 0) ImHexApi::Provider::setCurrentProvider(currIndex - 1); }); ShortcutManager::addGlobalShortcut(AllowWhileTyping + ALT + CTRLCMD + Keys::Right, "hex.builtin.shortcut.next_provider", []{ auto currIndex = ImHexApi::Provider::getCurrentProviderIndex(); const auto &providers = ImHexApi::Provider::getProviders(); if (currIndex < i64(providers.size() - 1)) ImHexApi::Provider::setCurrentProvider(currIndex + 1); }); static bool providerJustChanged = true; EventProviderChanged::subscribe([](auto, auto) { providerJustChanged = true; }); static prv::Provider *rightClickedProvider = nullptr; EventSearchBoxClicked::subscribe([](ImGuiMouseButton button){ if (button == ImGuiMouseButton_Right) { rightClickedProvider = ImHexApi::Provider::get(); RequestOpenPopup::post("ProviderMenu"); } }); EventFrameBegin::subscribe([] { if (rightClickedProvider != nullptr && !rightClickedProvider->getMenuEntries().empty()) { if (ImGui::BeginPopup("ProviderMenu")) { drawProviderContextMenu(rightClickedProvider); ImGui::EndPopup(); } } }); EventProviderChanged::subscribe([](auto, auto){ rightClickedProvider = nullptr; }); static bool alwaysShowProviderTabs = false; ContentRegistry::Settings::onChange("hex.builtin.setting.interface", "hex.builtin.setting.interface.always_show_provider_tabs", [](const ContentRegistry::Settings::SettingsValue &value) { alwaysShowProviderTabs = value.get<bool>(false); }); // Toolbar items ContentRegistry::Interface::addToolbarItem([] { for (const auto &menuItem : ContentRegistry::Interface::impl::getToolbarMenuItems()) { const auto &unlocalizedItemName = menuItem->unlocalizedNames.back(); if (unlocalizedItemName.get() == ContentRegistry::Interface::impl::SeparatorValue) { ImGui::SeparatorEx(ImGuiSeparatorFlags_Vertical); continue; } ImGui::BeginDisabled(!menuItem->enabledCallback()); if (ImGuiExt::ToolBarButton(menuItem->icon.glyph.c_str(), ImGuiExt::GetCustomColorVec4(ImGuiCustomCol(menuItem->icon.color)))) { menuItem->callback(); } ImGuiExt::InfoTooltip(Lang(unlocalizedItemName)); ImGui::EndDisabled(); } }); // Provider switcher ContentRegistry::Interface::addToolbarItem([] { const bool providerValid = ImHexApi::Provider::get() != nullptr; const bool tasksRunning = TaskManager::getRunningTaskCount() > 0; ImGui::SeparatorEx(ImGuiSeparatorFlags_Vertical); ImGui::Spacing(); ImGui::Spacing(); ImGui::Spacing(); ImGui::BeginDisabled(!providerValid || tasksRunning); { auto providers = ImHexApi::Provider::getProviders(); ImGui::PushStyleColor(ImGuiCol_TabSelected, ImGui::GetColorU32(ImGuiCol_MenuBarBg)); ImGui::PushStyleColor(ImGuiCol_TabDimmedSelected, ImGui::GetColorU32(ImGuiCol_MenuBarBg)); auto providerSelectorVisible = ImGui::BeginTabBar("provider_switcher", ImGuiTabBarFlags_FittingPolicyScroll | ImGuiTabBarFlags_Reorderable | ImGuiTabBarFlags_AutoSelectNewTabs); ImGui::PopStyleColor(2); if (providerSelectorVisible) { for (size_t i = 0; i < providers.size(); i++) { if (providers.size() == 1 && !alwaysShowProviderTabs) break; auto &tabProvider = providers[i]; const auto selectedProviderIndex = ImHexApi::Provider::getCurrentProviderIndex(); const auto closingProviders = ImHexApi::Provider::impl::getClosingProviders(); if (std::ranges::find(closingProviders, tabProvider) != closingProviders.end()) continue; bool open = true; ImGui::PushID(tabProvider); ImGuiTabItemFlags flags = ImGuiTabItemFlags_NoTooltip; if (tabProvider->isDirty()) flags |= ImGuiTabItemFlags_UnsavedDocument; if (i64(i) == selectedProviderIndex && providerJustChanged) { flags |= ImGuiTabItemFlags_SetSelected; providerJustChanged = false; } static size_t lastSelectedProvider = 0; bool isSelected = false; if (ImGui::BeginTabItem(tabProvider->getName().c_str(), &open, flags)) { isSelected = true; ImGui::EndTabItem(); } if (isSelected && lastSelectedProvider != i) { ImHexApi::Provider::setCurrentProvider(i); lastSelectedProvider = i; } drawProviderTooltip(tabProvider); ImGui::PopID(); if (!open) { ImHexApi::Provider::remove(providers[i]); break; } if (ImGui::IsMouseDown(ImGuiMouseButton_Right) && ImGui::IsItemHovered() && !ImGui::IsMouseDragging(ImGuiMouseButton_Right)) { rightClickedProvider = tabProvider; RequestOpenPopup::post("ProviderMenu"); } } ImGui::EndTabBar(); } } ImGui::EndDisabled(); }); ContentRegistry::Interface::addMenuItemToToolbar("hex.builtin.menu.edit.undo", ImGuiCustomCol_ToolbarBlue); ContentRegistry::Interface::addMenuItemToToolbar("hex.builtin.menu.edit.redo", ImGuiCustomCol_ToolbarBlue); ContentRegistry::Interface::addMenuItemToToolbar("hex.builtin.menu.file.create_file", ImGuiCustomCol_ToolbarGray); ContentRegistry::Interface::addMenuItemToToolbar("hex.builtin.menu.file.open_file", ImGuiCustomCol_ToolbarBrown); ContentRegistry::Interface::addMenuItemToToolbar("hex.builtin.view.hex_editor.menu.file.save", ImGuiCustomCol_ToolbarBlue); ContentRegistry::Interface::addMenuItemToToolbar("hex.builtin.view.hex_editor.menu.file.save_as", ImGuiCustomCol_ToolbarBlue); ContentRegistry::Interface::addMenuItemToToolbar("hex.builtin.menu.edit.bookmark.create", ImGuiCustomCol_ToolbarGreen); } }
23,727
C++
.cpp
417
39.043165
313
0.539827
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
175
themes.cpp
WerWolv_ImHex/plugins/builtin/source/content/themes.cpp
#include <hex/api/theme_manager.hpp> #include <hex/api/event_manager.hpp> #include <hex/ui/imgui_imhex_extensions.h> #include <hex/helpers/default_paths.hpp> #include <imgui.h> #include <imgui_internal.h> #include <implot.h> #include <imnodes.h> #include <TextEditor.h> #include <romfs/romfs.hpp> #include <wolv/io/file.hpp> namespace hex::plugin::builtin { void registerThemeHandlers() { RequestInitThemeHandlers::subscribe([] { { const static ThemeManager::ColorMap ImGuiColorMap = { { "text", ImGuiCol_Text }, { "text-disabled", ImGuiCol_TextDisabled }, { "window-background", ImGuiCol_WindowBg }, { "child-background", ImGuiCol_ChildBg }, { "popup-background", ImGuiCol_PopupBg }, { "border", ImGuiCol_Border }, { "border-shadow", ImGuiCol_BorderShadow }, { "frame-background", ImGuiCol_FrameBg }, { "frame-background-hovered", ImGuiCol_FrameBgHovered }, { "frame-background-active", ImGuiCol_FrameBgActive }, { "title-background", ImGuiCol_TitleBg }, { "title-background-active", ImGuiCol_TitleBgActive }, { "title-background-collapse", ImGuiCol_TitleBgCollapsed }, { "menu-bar-background", ImGuiCol_MenuBarBg }, { "scrollbar-background", ImGuiCol_ScrollbarBg }, { "scrollbar-grab", ImGuiCol_ScrollbarGrab }, { "scrollbar-grab-hovered", ImGuiCol_ScrollbarGrabHovered }, { "scrollbar-grab-active", ImGuiCol_ScrollbarGrabActive }, { "check-mark", ImGuiCol_CheckMark }, { "slider-grab", ImGuiCol_SliderGrab }, { "slider-grab-active", ImGuiCol_SliderGrabActive }, { "button", ImGuiCol_Button }, { "button-hovered", ImGuiCol_ButtonHovered }, { "button-active", ImGuiCol_ButtonActive }, { "header", ImGuiCol_Header }, { "header-hovered", ImGuiCol_HeaderHovered }, { "header-active", ImGuiCol_HeaderActive }, { "separator", ImGuiCol_Separator }, { "separator-hovered", ImGuiCol_SeparatorHovered }, { "separator-active", ImGuiCol_SeparatorActive }, { "resize-grip", ImGuiCol_ResizeGrip }, { "resize-grip-hovered", ImGuiCol_ResizeGripHovered }, { "resize-grip-active", ImGuiCol_ResizeGripActive }, { "tab", ImGuiCol_Tab }, { "tab-hovered", ImGuiCol_TabHovered }, { "tab-active", ImGuiCol_TabSelected }, { "tab-unfocused", ImGuiCol_TabDimmed }, { "tab-unfocused-active", ImGuiCol_TabDimmedSelected }, { "docking-preview", ImGuiCol_DockingPreview }, { "docking-empty-background", ImGuiCol_DockingEmptyBg }, { "plot-lines", ImGuiCol_PlotLines }, { "plot-lines-hovered", ImGuiCol_PlotLinesHovered }, { "plot-histogram", ImGuiCol_PlotHistogram }, { "plot-histogram-hovered", ImGuiCol_PlotHistogramHovered }, { "table-header-background", ImGuiCol_TableHeaderBg }, { "table-border-strong", ImGuiCol_TableBorderStrong }, { "table-border-light", ImGuiCol_TableBorderLight }, { "table-row-background", ImGuiCol_TableRowBg }, { "table-row-background-alt", ImGuiCol_TableRowBgAlt }, { "text-selected-background", ImGuiCol_TextSelectedBg }, { "drag-drop-target", ImGuiCol_DragDropTarget }, { "nav-highlight", ImGuiCol_NavHighlight }, { "nav-windowing-highlight", ImGuiCol_NavWindowingHighlight }, { "nav-windowing-background", ImGuiCol_NavWindowingDimBg }, { "modal-window-dim-background", ImGuiCol_ModalWindowDimBg }, { "window-shadow", ImGuiCol_WindowShadow } }; ThemeManager::addThemeHandler("imgui", ImGuiColorMap, [](u32 colorId) -> ImColor { return ImGui::GetStyle().Colors[colorId]; }, [](u32 colorId, ImColor color) { ImGui::GetStyle().Colors[colorId] = color; } ); } { const static ThemeManager::ColorMap ImPlotColorMap = { { "line", ImPlotCol_Line }, { "fill", ImPlotCol_Fill }, { "marker-outline", ImPlotCol_MarkerOutline }, { "marker-fill", ImPlotCol_MarkerFill }, { "error-bar", ImPlotCol_ErrorBar }, { "frame-bg", ImPlotCol_FrameBg }, { "plot-bg", ImPlotCol_PlotBg }, { "plot-border", ImPlotCol_PlotBorder }, { "legend-bg", ImPlotCol_LegendBg }, { "legend-border", ImPlotCol_LegendBorder }, { "legend-text", ImPlotCol_LegendText }, { "title-text", ImPlotCol_TitleText }, { "inlay-text", ImPlotCol_InlayText }, { "axis-text", ImPlotCol_AxisText }, { "axis-grid", ImPlotCol_AxisGrid }, { "axis-tick", ImPlotCol_AxisTick }, { "axis-bg", ImPlotCol_AxisBg }, { "axis-bg-hovered", ImPlotCol_AxisBgHovered }, { "axis-bg-active", ImPlotCol_AxisBgActive }, { "selection", ImPlotCol_Selection }, { "crosshairs", ImPlotCol_Crosshairs } }; ThemeManager::addThemeHandler("implot", ImPlotColorMap, [](u32 colorId) -> ImColor { return ImPlot::GetStyle().Colors[colorId]; }, [](u32 colorId, ImColor color) { ImPlot::GetStyle().Colors[colorId] = color; } ); } { const static ThemeManager::ColorMap ImNodesColorMap = { { "node-background", ImNodesCol_NodeBackground }, { "node-background-hovered", ImNodesCol_NodeBackgroundHovered }, { "node-background-selected", ImNodesCol_NodeBackgroundSelected }, { "node-outline", ImNodesCol_NodeOutline }, { "title-bar", ImNodesCol_TitleBar }, { "title-bar-hovered", ImNodesCol_TitleBarHovered }, { "title-bar-selected", ImNodesCol_TitleBarSelected }, { "link", ImNodesCol_Link }, { "link-hovered", ImNodesCol_LinkHovered }, { "link-selected", ImNodesCol_LinkSelected }, { "pin", ImNodesCol_Pin }, { "pin-hovered", ImNodesCol_PinHovered }, { "box-selector", ImNodesCol_BoxSelector }, { "box-selector-outline", ImNodesCol_BoxSelectorOutline }, { "grid-background", ImNodesCol_GridBackground }, { "grid-line", ImNodesCol_GridLine }, { "grid-line-primary", ImNodesCol_GridLinePrimary }, { "mini-map-background", ImNodesCol_MiniMapBackground }, { "mini-map-background-hovered", ImNodesCol_MiniMapBackgroundHovered }, { "mini-map-outline", ImNodesCol_MiniMapOutline }, { "mini-map-outline-hovered", ImNodesCol_MiniMapOutlineHovered }, { "mini-map-node-background", ImNodesCol_MiniMapNodeBackground }, { "mini-map-node-background-hovered", ImNodesCol_MiniMapNodeBackgroundHovered }, { "mini-map-node-background-selected", ImNodesCol_MiniMapNodeBackgroundSelected }, { "mini-map-node-outline", ImNodesCol_MiniMapNodeOutline }, { "mini-map-link", ImNodesCol_MiniMapLink }, { "mini-map-link-selected", ImNodesCol_MiniMapLinkSelected }, { "mini-map-canvas", ImNodesCol_MiniMapCanvas }, { "mini-map-canvas-outline", ImNodesCol_MiniMapCanvasOutline }, }; ThemeManager::addThemeHandler("imnodes", ImNodesColorMap, [](u32 colorId) -> ImColor { return ImNodes::GetStyle().Colors[colorId]; }, [](u32 colorId, ImColor color) { ImNodes::GetStyle().Colors[colorId] = color; } ); } { const static ThemeManager::ColorMap ImHexColorMap = { { "desc-button", ImGuiCustomCol_DescButton }, { "desc-button-hovered", ImGuiCustomCol_DescButtonHovered }, { "desc-button-active", ImGuiCustomCol_DescButtonActive }, { "toolbar-gray", ImGuiCustomCol_ToolbarGray }, { "toolbar-red", ImGuiCustomCol_ToolbarRed }, { "toolbar-yellow", ImGuiCustomCol_ToolbarYellow }, { "toolbar-green", ImGuiCustomCol_ToolbarGreen }, { "toolbar-blue", ImGuiCustomCol_ToolbarBlue }, { "toolbar-purple", ImGuiCustomCol_ToolbarPurple }, { "toolbar-brown", ImGuiCustomCol_ToolbarBrown }, { "logger-debug", ImGuiCustomCol_LoggerDebug }, { "logger-info", ImGuiCustomCol_LoggerInfo }, { "logger-warning", ImGuiCustomCol_LoggerWarning }, { "logger-error", ImGuiCustomCol_LoggerError }, { "logger-fatal", ImGuiCustomCol_LoggerFatal }, { "achievement-unlocked", ImGuiCustomCol_AchievementUnlocked }, { "find-highlight", ImGuiCustomCol_FindHighlight }, { "highlight", ImGuiCustomCol_Highlight }, { "diff-added", ImGuiCustomCol_DiffAdded }, { "diff-removed", ImGuiCustomCol_DiffRemoved }, { "diff-changed", ImGuiCustomCol_DiffChanged }, { "advanced-encoding-ascii", ImGuiCustomCol_AdvancedEncodingASCII }, { "advanced-encoding-single", ImGuiCustomCol_AdvancedEncodingSingleChar }, { "advanced-encoding-multi", ImGuiCustomCol_AdvancedEncodingMultiChar }, { "advanced-encoding-unknown", ImGuiCustomCol_AdvancedEncodingUnknown }, { "patches", ImGuiCustomCol_Patches }, { "pattern-selected", ImGuiCustomCol_PatternSelected }, { "IEEE-tool-sign", ImGuiCustomCol_IEEEToolSign }, { "IEEE-tool-exp", ImGuiCustomCol_IEEEToolExp }, { "IEEE-tool-mantissa", ImGuiCustomCol_IEEEToolMantissa }, { "blur-background", ImGuiCustomCol_BlurBackground } }; ThemeManager::addThemeHandler("imhex", ImHexColorMap, [](u32 colorId) -> ImColor { return static_cast<ImGuiExt::ImHexCustomData *>(GImGui->IO.UserData)->Colors[colorId]; }, [](u32 colorId, ImColor color) { static_cast<ImGuiExt::ImHexCustomData *>(GImGui->IO.UserData)->Colors[colorId] = color; } ); } { const static ThemeManager::ColorMap TextEditorColorMap = { { "default", u32(TextEditor::PaletteIndex::Default) }, { "keyword", u32(TextEditor::PaletteIndex::Keyword) }, { "number", u32(TextEditor::PaletteIndex::Number) }, { "string", u32(TextEditor::PaletteIndex::String) }, { "char-literal", u32(TextEditor::PaletteIndex::CharLiteral) }, { "punctuation", u32(TextEditor::PaletteIndex::Punctuation) }, { "preprocessor", u32(TextEditor::PaletteIndex::Preprocessor) }, { "identifier", u32(TextEditor::PaletteIndex::Identifier) }, { "known-identifier", u32(TextEditor::PaletteIndex::KnownIdentifier) }, { "preproc-identifier", u32(TextEditor::PaletteIndex::PreprocIdentifier) }, { "global-doc-comment", u32(TextEditor::PaletteIndex::GlobalDocComment) }, { "doc-comment", u32(TextEditor::PaletteIndex::DocComment) }, { "comment", u32(TextEditor::PaletteIndex::Comment) }, { "multi-line-comment", u32(TextEditor::PaletteIndex::MultiLineComment) }, { "preprocessor-deactivated", u32(TextEditor::PaletteIndex::PreprocessorDeactivated) }, { "background", u32(TextEditor::PaletteIndex::Background) }, { "cursor", u32(TextEditor::PaletteIndex::Cursor) }, { "selection", u32(TextEditor::PaletteIndex::Selection) }, { "error-marker", u32(TextEditor::PaletteIndex::ErrorMarker) }, { "breakpoint", u32(TextEditor::PaletteIndex::Breakpoint) }, { "line-number", u32(TextEditor::PaletteIndex::LineNumber) }, { "current-line-fill", u32(TextEditor::PaletteIndex::CurrentLineFill) }, { "current-line-fill-inactive", u32(TextEditor::PaletteIndex::CurrentLineFillInactive) }, { "current-line-edge", u32(TextEditor::PaletteIndex::CurrentLineEdge) } }; ThemeManager::addThemeHandler("text-editor", TextEditorColorMap, [](u32 colorId) -> ImColor { return TextEditor::GetPalette()[colorId]; }, [](u32 colorId, ImColor color) { auto palette = TextEditor::GetPalette(); palette[colorId] = color; TextEditor::SetPalette(palette); } ); } }); } void registerStyleHandlers() { RequestInitThemeHandlers::subscribe([] { { auto &style = ImGui::GetStyle(); const static ThemeManager::StyleMap ImGuiStyleMap = { { "alpha", { &style.Alpha, 0.1F, 1.0F, false } }, { "disabled-alpha", { &style.DisabledAlpha, 0.0F, 1.0F, false } }, { "window-padding", { &style.WindowPadding, 0.0F, 20.0F, true } }, { "window-rounding", { &style.WindowRounding, 0.0F, 12.0F, true } }, { "window-border-size", { &style.WindowBorderSize, 0.0F, 1.0F, true } }, { "window-min-size", { &style.WindowMinSize, 0.0F, 1000.0F, true } }, { "window-title-align", { &style.WindowTitleAlign, 0.0F, 1.0F , false } }, { "child-rounding", { &style.ChildRounding, 0.0F, 12.0F, true } }, { "child-border-size", { &style.ChildBorderSize, 0.0F, 1.0F , true } }, { "popup-rounding", { &style.PopupRounding, 0.0F, 12.0F, true } }, { "popup-border-size", { &style.PopupBorderSize, 0.0F, 1.0F, true } }, { "frame-padding", { &style.FramePadding, 0.0F, 20.0F, true } }, { "frame-rounding", { &style.FrameRounding, 0.0F, 12.0F, true } }, { "frame-border-size", { &style.FrameBorderSize, 0.0F, 1.0F, true } }, { "item-spacing", { &style.ItemSpacing, 0.0F, 20.0F, true } }, { "item-inner-spacing", { &style.ItemInnerSpacing, 0.0F, 20.0F, true } }, { "indent-spacing", { &style.IndentSpacing, 0.0F, 30.0F, true } }, { "cell-padding", { &style.CellPadding, 0.0F, 20.0F, true } }, { "scrollbar-size", { &style.ScrollbarSize, 0.0F, 20.0F, true } }, { "scrollbar-rounding", { &style.ScrollbarRounding, 0.0F, 12.0F, true } }, { "grab-min-size", { &style.GrabMinSize, 0.0F, 20.0F, true } }, { "grab-rounding", { &style.GrabRounding, 0.0F, 12.0F, true } }, { "tab-rounding", { &style.TabRounding, 0.0F, 12.0F, true } }, { "button-text-align", { &style.ButtonTextAlign, 0.0F, 1.0F, false } }, { "selectable-text-align", { &style.SelectableTextAlign, 0.0F, 1.0F, false } }, { "window-shadow-size", { &style.WindowShadowSize, 0.0F, 100.0F, true } }, { "window-shadow-offset", { &style.WindowShadowOffsetDist, 0.0F, 100.0F, true } }, { "window-shadow-angle", { &style.WindowShadowOffsetAngle, 0.0F, 10.0F, false } }, }; ThemeManager::addStyleHandler("imgui", ImGuiStyleMap); } { auto &style = ImPlot::GetStyle(); const static ThemeManager::StyleMap ImPlotStyleMap = { { "line-weight", { &style.LineWeight, 0.0F, 5.0F, true } }, { "marker-size", { &style.MarkerSize, 2.0F, 10.0F, true } }, { "marker-weight", { &style.MarkerWeight, 0.0F, 5.0F, true } }, { "fill-alpha", { &style.FillAlpha, 0.0F, 1.0F, false } }, { "error-bar-size", { &style.ErrorBarSize, 0.0F, 10.0F, true } }, { "error-bar-weight", { &style.ErrorBarWeight, 0.0F, 5.0F, true } }, { "digital-bit-height", { &style.DigitalBitHeight, 0.0F, 20.0F, true } }, { "digital-bit-gap", { &style.DigitalBitGap, 0.0F, 20.0F, true } }, { "plot-border-size", { &style.PlotBorderSize, 0.0F, 2.0F, true } }, { "minor-alpha", { &style.MinorAlpha, 0.0F, 1.0F, false } }, { "major-tick-len", { &style.MajorTickLen, 0.0F, 20.0F, true } }, { "minor-tick-len", { &style.MinorTickLen, 0.0F, 20.0F, true } }, { "major-tick-size", { &style.MajorTickSize, 0.0F, 2.0F, true } }, { "minor-tick-size", { &style.MinorTickSize, 0.0F, 2.0F, true } }, { "major-grid-size", { &style.MajorGridSize, 0.0F, 2.0F, true } }, { "minor-grid-size", { &style.MinorGridSize, 0.0F, 2.0F, true } }, { "plot-padding", { &style.PlotPadding, 0.0F, 20.0F, true } }, { "label-padding", { &style.LabelPadding, 0.0F, 20.0F, true } }, { "legend-padding", { &style.LegendPadding, 0.0F, 20.0F, true } }, { "legend-inner-padding", { &style.LegendInnerPadding, 0.0F, 10.0F, true } }, { "legend-spacing", { &style.LegendSpacing, 0.0F, 5.0F, true } }, { "mouse-pos-padding", { &style.MousePosPadding, 0.0F, 20.0F, true } }, { "annotation-padding", { &style.AnnotationPadding, 0.0F, 5.0F, true } }, { "fit-padding", { &style.FitPadding, 0.0F, 0.2F, true } }, { "plot-default-size", { &style.PlotDefaultSize, 0.0F, 1000.0F, true } }, { "plot-min-size", { &style.PlotMinSize, 0.0F, 300.0F, true } }, }; ThemeManager::addStyleHandler("implot", ImPlotStyleMap); } { auto &style = ImNodes::GetStyle(); const static ThemeManager::StyleMap ImNodesStyleMap = { { "grid-spacing", { &style.GridSpacing, 0.0F, 100.0F, true } }, { "node-corner-rounding", { &style.NodeCornerRounding, 0.0F, 12.0F, true } }, { "node-padding", { &style.NodePadding, 0.0F, 20.0F, true } }, { "node-border-thickness", { &style.NodeBorderThickness, 0.0F, 1.0F, true } }, { "link-thickness", { &style.LinkThickness, 0.0F, 10.0F, true } }, { "link-line-segments-per-length", { &style.LinkLineSegmentsPerLength, 0.0F, 2.0F, true } }, { "link-hover-distance", { &style.LinkHoverDistance, 0.0F, 20.0F, true } }, { "pin-circle-radius", { &style.PinCircleRadius, 0.0F, 20.0F, true } }, { "pin-quad-side-length", { &style.PinQuadSideLength, 0.0F, 20.0F, true } }, { "pin-triangle-side-length", { &style.PinTriangleSideLength, 0.0F, 20.0F, true } }, { "pin-line-thickness", { &style.PinLineThickness, 0.0F, 5.0F, true } }, { "pin-hover-radius", { &style.PinHoverRadius, 0.0F, 20.0F, true } }, { "pin-offset", { &style.PinOffset, -10.0F, 10.0F, true } }, { "mini-map-padding", { &style.MiniMapPadding, 0.0F, 20.0F, true } }, { "mini-map-offset", { &style.MiniMapOffset, -10.0F, 10.0F, true } }, }; ThemeManager::addStyleHandler("imnodes", ImNodesStyleMap); } { auto &style = ImGuiExt::GetCustomStyle(); const static ThemeManager::StyleMap ImHexStyleMap = { { "window-blur", { &style.WindowBlur, 0.0F, 1.0F, true } }, { "popup-alpha", { &style.PopupWindowAlpha, 0.0F, 1.0F, false } }, }; ThemeManager::addStyleHandler("imhex", ImHexStyleMap); } }); } void registerThemes() { // Load built-in themes for (const auto &theme : romfs::list("themes")) { ThemeManager::addTheme(std::string(romfs::get(theme).string())); } // Load user themes for (const auto &themeFolder : paths::Themes.read()) { for (const auto &theme : std::fs::directory_iterator(themeFolder)) { if (theme.is_regular_file()) ThemeManager::addTheme(wolv::io::File(theme.path(), wolv::io::File::Mode::Read).readString()); } } } }
28,200
C++
.cpp
352
60.71875
121
0.412947
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
176
background_services.cpp
WerWolv_ImHex/plugins/builtin/source/content/background_services.cpp
#include <hex/api/content_registry.hpp> #include <hex/api/localization_manager.hpp> #include <hex/api/event_manager.hpp> #include <hex/api/project_file_manager.hpp> #include <hex/helpers/fmt.hpp> #include <hex/helpers/default_paths.hpp> #include <hex/helpers/logger.hpp> #include <hex/providers/provider.hpp> #include <wolv/utils/guards.hpp> #include <wolv/utils/string.hpp> #include <wolv/net/socket_server.hpp> #include <fmt/chrono.h> #include <nlohmann/json.hpp> namespace hex::plugin::builtin { static bool s_networkInterfaceServiceEnabled = false; static int s_autoBackupTime = 0; namespace { void handleNetworkInterfaceService() { if (!s_networkInterfaceServiceEnabled) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); return; } static wolv::net::SocketServer networkInterfaceServer(31337); AT_FIRST_TIME { EventImHexClosing::subscribe([]{ networkInterfaceServer.shutdown(); }); }; networkInterfaceServer.accept([](auto, const std::vector<u8> &data) -> std::vector<u8> { nlohmann::json result; try { auto json = nlohmann::json::parse(data.begin(), data.end()); const auto &endpoints = ContentRegistry::CommunicationInterface::impl::getNetworkEndpoints(); if (auto callback = endpoints.find(json.at("endpoint").get<std::string>()); callback != endpoints.end()) { log::info("Network endpoint {} called with arguments '{}'", json.at("endpoint").get<std::string>(), json.contains("data") ? json.at("data").dump() : ""); auto responseData = callback->second(json.contains("data") ? json.at("data") : nlohmann::json::object()); result["status"] = "success"; result["data"] = responseData; } else { throw std::runtime_error("Endpoint not found"); } } catch (const std::exception &e) { log::warn("Network interface service error: {}", e.what()); result["status"] = "error"; result["data"]["error"] = e.what(); } auto resultString = result.dump(); return { resultString.begin(), resultString.end() }; }); } bool s_dataDirty = false; void handleAutoBackup() { auto now = std::chrono::steady_clock::now(); static std::chrono::time_point<std::chrono::steady_clock> lastBackupTime = now; if (s_autoBackupTime > 0 && (now - lastBackupTime) > std::chrono::seconds(s_autoBackupTime)) { lastBackupTime = now; if (ImHexApi::Provider::isValid() && s_dataDirty) { s_dataDirty = false; std::vector<prv::Provider *> dirtyProviders; for (const auto &provider : ImHexApi::Provider::getProviders()) { if (provider->isDirty()) { dirtyProviders.push_back(provider); } } for (const auto &path : paths::Backups.write()) { const auto backupPath = path / hex::format("auto_backup.{:%y%m%d_%H%M%S}.hexproj", fmt::gmtime(std::chrono::system_clock::now())); if (ProjectFile::store(backupPath, false)) { log::info("Created auto-backup file '{}'", wolv::util::toUTF8String(backupPath)); break; } } for (const auto &provider : dirtyProviders) { provider->markDirty(); } } } std::this_thread::sleep_for(std::chrono::seconds(1)); } } void registerBackgroundServices() { ContentRegistry::Settings::onChange("hex.builtin.setting.general", "hex.builtin.setting.general.network_interface", [](const ContentRegistry::Settings::SettingsValue &value) { s_networkInterfaceServiceEnabled = value.get<bool>(false); }); ContentRegistry::Settings::onChange("hex.builtin.setting.general", "hex.builtin.setting.general.auto_backup_time", [](const ContentRegistry::Settings::SettingsValue &value) { s_autoBackupTime = value.get<int>(0) * 30; }); ContentRegistry::BackgroundServices::registerService("hex.builtin.background_service.network_interface", handleNetworkInterfaceService); ContentRegistry::BackgroundServices::registerService("hex.builtin.background_service.auto_backup", handleAutoBackup); EventProviderDirtied::subscribe([](prv::Provider *) { s_dataDirty = true; }); } }
4,972
C++
.cpp
93
39.311828
183
0.566804
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
177
recent.cpp
WerWolv_ImHex/plugins/builtin/source/content/recent.cpp
#include <imgui.h> #include <imgui_internal.h> #include <hex/api/event_manager.hpp> #include <hex/api/content_registry.hpp> #include <hex/api/project_file_manager.hpp> #include <hex/api/task_manager.hpp> #include <hex/providers/provider.hpp> #include <hex/helpers/default_paths.hpp> #include <hex/helpers/fmt.hpp> #include <fmt/chrono.h> #include <wolv/utils/guards.hpp> #include <wolv/utils/string.hpp> #include <content/recent.hpp> #include <toasts/toast_notification.hpp> #include <fonts/codicons_font.h> #include <ranges> #include <unordered_set> namespace hex::plugin::builtin::recent { constexpr static auto MaxRecentEntries = 5; constexpr static auto BackupFileName = "crash_backup.hexproj"; namespace { std::atomic_bool s_recentEntriesUpdating = false; std::list<RecentEntry> s_recentEntries; std::atomic_bool s_autoBackupsFound = false; class PopupAutoBackups : public Popup<PopupAutoBackups> { private: struct BackupEntry { std::string displayName; std::fs::path path; }; public: PopupAutoBackups() : Popup("hex.builtin.welcome.start.recent.auto_backups", true, true) { for (const auto &backupPath : paths::Backups.read()) { for (const auto &entry : std::fs::directory_iterator(backupPath)) { if (entry.is_regular_file() && entry.path().extension() == ".hexproj") { wolv::io::File backupFile(entry.path(), wolv::io::File::Mode::Read); m_backups.emplace_back( hex::format("hex.builtin.welcome.start.recent.auto_backups.backup"_lang, fmt::gmtime(backupFile.getFileInfo()->st_ctime)), entry.path() ); } } } } void drawContent() override { if (ImGui::BeginTable("AutoBackups", 1, ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersInnerV, ImVec2(0, ImGui::GetTextLineHeightWithSpacing() * 5))) { for (const auto &backup : m_backups | std::views::reverse | std::views::take(10)) { ImGui::TableNextRow(); ImGui::TableNextColumn(); if (ImGui::Selectable(backup.displayName.c_str())) { ProjectFile::load(backup.path); Popup::close(); } } ImGui::EndTable(); } if (ImGui::IsKeyPressed(ImGuiKey_Escape)) this->close(); } [[nodiscard]] ImGuiWindowFlags getFlags() const override { return ImGuiWindowFlags_AlwaysAutoResize; } private: std::vector<BackupEntry> m_backups; }; } void registerEventHandlers() { // Save every opened provider as a "recent" shortcut (void)EventProviderOpened::subscribe([](const prv::Provider *provider) { if (ContentRegistry::Settings::read<bool>("hex.builtin.setting.general", "hex.builtin.setting.general.save_recent_providers", true)) { auto fileName = hex::format("{:%y%m%d_%H%M%S}.json", fmt::gmtime(std::chrono::system_clock::now())); // Do not save to recents if the provider is part of a project if (ProjectFile::hasPath()) return; // Do not save to recents if the provider doesn't want it if (!provider->isSavableAsRecent()) return; // The recent provider is saved to every "recent" directory for (const auto &recentPath : paths::Recent.write()) { wolv::io::File recentFile(recentPath / fileName, wolv::io::File::Mode::Create); if (!recentFile.isValid()) continue; { auto path = ProjectFile::getPath(); ProjectFile::clearPath(); if (auto settings = provider->storeSettings({}); !settings.is_null()) recentFile.writeString(settings.dump(4)); ProjectFile::setPath(path); } } } updateRecentEntries(); }); // Save opened projects as a "recent" shortcut (void)EventProjectOpened::subscribe([] { if (ContentRegistry::Settings::read<bool>("hex.builtin.setting.general", "hex.builtin.setting.general.save_recent_providers", true)) { auto fileName = hex::format("{:%y%m%d_%H%M%S}.json", fmt::gmtime(std::chrono::system_clock::now())); auto projectFileName = ProjectFile::getPath().filename(); if (projectFileName == BackupFileName) return; // The recent provider is saved to every "recent" directory for (const auto &recentPath : paths::Recent.write()) { wolv::io::File recentFile(recentPath / fileName, wolv::io::File::Mode::Create); if (!recentFile.isValid()) continue; nlohmann::json recentEntry { { "type", "project" }, { "displayName", wolv::util::toUTF8String(projectFileName) }, { "path", wolv::util::toUTF8String(ProjectFile::getPath()) } }; recentFile.writeString(recentEntry.dump(4)); } } updateRecentEntries(); }); } void updateRecentEntries() { TaskManager::createBackgroundTask("hex.builtin.task.updating_recents"_lang, [](auto&) { if (s_recentEntriesUpdating) return; s_recentEntriesUpdating = true; ON_SCOPE_EXIT { s_recentEntriesUpdating = false; }; s_recentEntries.clear(); // Query all recent providers std::vector<std::fs::path> recentFilePaths; for (const auto &folder : paths::Recent.read()) { for (const auto &entry : std::fs::directory_iterator(folder)) { if (entry.is_regular_file()) recentFilePaths.push_back(entry.path()); } } // Sort recent provider files by last modified time std::sort(recentFilePaths.begin(), recentFilePaths.end(), [](const auto &a, const auto &b) { return std::fs::last_write_time(a) > std::fs::last_write_time(b); }); std::unordered_set<RecentEntry, RecentEntry::HashFunction> uniqueProviders; for (const auto &path : recentFilePaths) { if (uniqueProviders.size() >= MaxRecentEntries) break; try { wolv::io::File recentFile(path, wolv::io::File::Mode::Read); if (!recentFile.isValid()) { continue; } auto content = recentFile.readString(); if (content.empty()) { continue; } auto jsonData = nlohmann::json::parse(content); uniqueProviders.insert(RecentEntry { .displayName = jsonData.at("displayName"), .type = jsonData.at("type"), .entryFilePath = path, .data = jsonData }); } catch (const std::exception &e) { log::error("Failed to parse recent file: {}", e.what()); } } // Delete all recent provider files that are not in the list for (const auto &path : recentFilePaths) { bool found = false; for (const auto &provider : uniqueProviders) { if (path == provider.entryFilePath) { found = true; break; } } if (!found) wolv::io::fs::remove(path); } std::copy(uniqueProviders.begin(), uniqueProviders.end(), std::front_inserter(s_recentEntries)); s_autoBackupsFound = false; for (const auto &backupPath : paths::Backups.read()) { for (const auto &entry : std::fs::directory_iterator(backupPath)) { if (entry.is_regular_file() && entry.path().extension() == ".hexproj") { s_autoBackupsFound = true; break; } } } }); } void loadRecentEntry(const RecentEntry &recentEntry) { if (recentEntry.type == "project") { std::fs::path projectPath = recentEntry.data["path"].get<std::string>(); if (!ProjectFile::load(projectPath)) { ui::ToastError::open(hex::format("hex.builtin.popup.error.project.load"_lang, wolv::util::toUTF8String(projectPath))); } return; } auto *provider = ImHexApi::Provider::createProvider(recentEntry.type, true); if (provider != nullptr) { provider->loadSettings(recentEntry.data); if (!provider->open() || !provider->isAvailable()) { ui::ToastError::open(hex::format("hex.builtin.provider.error.open"_lang, provider->getErrorMessage())); TaskManager::doLater([provider] { ImHexApi::Provider::remove(provider); }); return; } EventProviderOpened::post(provider); updateRecentEntries(); } } void draw() { if (s_recentEntries.empty() && !s_autoBackupsFound) return; static bool collapsed = false; if (ImGuiExt::BeginSubWindow("hex.builtin.welcome.start.recent"_lang, &collapsed, ImVec2(), ImGuiChildFlags_AutoResizeX)) { if (!s_recentEntriesUpdating) { for (auto it = s_recentEntries.begin(); it != s_recentEntries.end();) { const auto &recentEntry = *it; bool shouldRemove = false; const bool isProject = recentEntry.type == "project"; ImGui::PushID(&recentEntry); ON_SCOPE_EXIT { ImGui::PopID(); }; const char* icon; if (isProject) { icon = ICON_VS_PROJECT; } else { icon = ICON_VS_FILE_BINARY; } if (ImGuiExt::Hyperlink(hex::format("{} {}", icon, hex::limitStringLength(recentEntry.displayName, 32)).c_str())) { loadRecentEntry(recentEntry); break; } if (ImGui::IsItemHovered() && ImGui::GetIO().KeyShift) { if (ImGui::BeginTooltip()) { if (ImGui::BeginTable("##RecentEntryTooltip", 2, ImGuiTableFlags_RowBg)) { ImGui::TableNextRow(); ImGui::TableNextColumn(); ImGui::TextUnformatted("hex.ui.common.name"_lang); ImGui::TableNextColumn(); ImGui::TextUnformatted(recentEntry.displayName.c_str()); ImGui::TableNextRow(); ImGui::TableNextColumn(); ImGui::TextUnformatted("hex.ui.common.type"_lang); ImGui::TableNextColumn(); if (isProject) { ImGui::TextUnformatted("hex.ui.common.project"_lang); ImGui::TableNextRow(); ImGui::TableNextColumn(); ImGui::TextUnformatted("hex.ui.common.path"_lang); ImGui::TableNextColumn(); ImGui::TextUnformatted(recentEntry.data["path"].get<std::string>().c_str()); } else { ImGui::TextUnformatted(Lang(recentEntry.type)); } ImGui::EndTable(); } ImGui::EndTooltip(); } } // Detect right click on recent provider std::string popupID = hex::format("RecentEntryMenu.{}", recentEntry.getHash()); if (ImGui::IsMouseReleased(1) && ImGui::IsItemHovered()) { ImGui::OpenPopup(popupID.c_str()); } if (ImGui::BeginPopup(popupID.c_str())) { if (ImGui::MenuItem("hex.ui.common.remove"_lang)) { shouldRemove = true; } ImGui::EndPopup(); } // Handle deletion from vector and on disk if (shouldRemove) { wolv::io::fs::remove(recentEntry.entryFilePath); it = s_recentEntries.erase(it); } else { ++it; } } if (s_autoBackupsFound) { ImGui::Separator(); if (ImGuiExt::Hyperlink(hex::format("{} {}", ICON_VS_ARCHIVE, "hex.builtin.welcome.start.recent.auto_backups"_lang).c_str())) PopupAutoBackups::open(); } } } ImGuiExt::EndSubWindow(); } void addMenuItems() { ContentRegistry::Interface::addMenuItemSubMenu({ "hex.builtin.menu.file" }, 1200, [] { if (ImGui::BeginMenuEx("hex.builtin.menu.file.open_recent"_lang, ICON_VS_ARCHIVE, !recent::s_recentEntriesUpdating && !s_recentEntries.empty())) { // Copy to avoid changing list while iteration auto recentEntries = s_recentEntries; for (auto &recentEntry : recentEntries) { if (ImGui::MenuItem(recentEntry.displayName.c_str())) { loadRecentEntry(recentEntry); } } ImGui::Separator(); if (ImGui::MenuItem("hex.builtin.menu.file.clear_recent"_lang)) { s_recentEntries.clear(); // Remove all recent files for (const auto &recentPath : paths::Recent.write()) { for (const auto &entry : std::fs::directory_iterator(recentPath)) std::fs::remove(entry.path()); } } ImGui::EndMenu(); } }); } }
15,336
C++
.cpp
304
32.404605
167
0.493102
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
178
out_of_box_experience.cpp
WerWolv_ImHex/plugins/builtin/source/content/out_of_box_experience.cpp
#include <imgui.h> #include <imgui_internal.h> #include <fonts/codicons_font.h> #include <hex/ui/imgui_imhex_extensions.h> #include <hex/api/content_registry.hpp> #include <hex/api/event_manager.hpp> #include <hex/api/task_manager.hpp> #include <hex/api/theme_manager.hpp> #include <hex/api/tutorial_manager.hpp> #include <hex/helpers/utils.hpp> #include <romfs/romfs.hpp> #include <wolv/hash/uuid.hpp> #include <wolv/utils/guards.hpp> #include <list> #include <numbers> #include <ranges> #include <string> namespace hex::plugin::builtin { namespace { ImGuiExt::Texture s_imhexBanner; ImGuiExt::Texture s_compassTexture, s_globeTexture; std::list<std::pair<std::fs::path, ImGuiExt::Texture>> s_screenshots; nlohmann::json s_screenshotDescriptions; std::string s_uuid; class Blend { public: Blend(float start, float end) : m_time(0), m_start(start), m_end(end) {} [[nodiscard]] operator float() { m_time += ImGui::GetIO().DeltaTime; float t = m_time; t -= m_start; t /= (m_end - m_start); t = std::clamp(t, 0.0F, 1.0F); float square = t * t; return square / (2.0F * (square - t) + 1.0F); } void reset() { m_time = 0; } private: float m_time; float m_start, m_end; }; EventManager::EventList::iterator s_drawEvent; void drawOutOfBoxExperience() { static float windowAlpha = 1.0F; static bool oobeDone = false; static bool tutorialEnabled = false; ImGui::SetNextWindowPos(ImHexApi::System::getMainWindowPosition()); ImGui::SetNextWindowSize(ImHexApi::System::getMainWindowSize()); ImGui::PushStyleVar(ImGuiStyleVar_Alpha, windowAlpha); ON_SCOPE_EXIT { ImGui::PopStyleVar(); }; if (ImGui::Begin("##oobe", nullptr, ImGuiWindowFlags_NoDocking | ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize)) { ImGui::BringWindowToFocusFront(ImGui::GetCurrentWindowRead()); static Blend bannerSlideIn(-0.2F, 1.5F); static Blend bannerFadeIn(-0.2F, 1.5F); // Draw banner ImGui::SetCursorPos(scaled({ 25 * bannerSlideIn, 25 })); const auto bannerSize = s_imhexBanner.getSize() / (3.0F * (1.0F / ImHexApi::System::getGlobalScale())); ImGui::Image( s_imhexBanner, bannerSize, { 0, 0 }, { 1, 1 }, { 1, 1, 1, (bannerFadeIn - 0.5F) * 2.0F } ); static u32 page = 0; switch (page) { // Landing page case 0: { static Blend textFadeIn(2.0F, 2.5F); static Blend buttonFadeIn(2.5F, 3.0F); // Draw welcome text ImGui::PushStyleVar(ImGuiStyleVar_Alpha, textFadeIn); ImGui::SameLine(); if (ImGui::BeginChild("Text", ImVec2(ImGui::GetContentRegionAvail().x, bannerSize.y))) { ImGuiExt::TextFormattedCentered("Welcome to ImHex!\n\nA powerful data analysis and visualization suite for Reverse Engineers, Hackers and Security Researchers."); } ImGui::EndChild(); if (!s_screenshots.empty()) { const auto imageSize = s_screenshots.front().second.getSize() * ImHexApi::System::getGlobalScale(); const auto padding = ImGui::GetStyle().CellPadding.x; const auto stride = imageSize.x + padding * 2; static bool imageHovered = false; static std::string clickedImage; // Move last screenshot to the front of the list when the last screenshot is out of view static float position = 0; if (position >= stride) { position = 0; s_screenshots.splice(s_screenshots.begin(), s_screenshots, std::prev(s_screenshots.end()), s_screenshots.end()); } if (!imageHovered && clickedImage.empty()) position += (ImGui::GetIO().DeltaTime) * 40; imageHovered = false; auto drawList = ImGui::GetWindowDrawList(); const auto drawImage = [&](const std::fs::path &fileName, const ImGuiExt::Texture &screenshot) { auto pos = ImGui::GetCursorScreenPos(); // Draw image ImGui::Image(screenshot, imageSize); imageHovered = imageHovered || ImGui::IsItemHovered(); auto currentHovered = ImGui::IsItemHovered(); if (ImGui::IsItemClicked()) { clickedImage = fileName.string(); ImGui::OpenPopup("FeatureDescription"); } // Draw shadow auto &style = ImGui::GetStyle(); float shadowSize = style.WindowShadowSize * (currentHovered ? 3.0F : 1.0F); ImU32 shadowCol = ImGui::GetColorU32(ImGuiCol_WindowShadow, currentHovered ? 2.0F : 1.0F); ImVec2 shadowOffset = ImVec2(ImCos(style.WindowShadowOffsetAngle), ImSin(style.WindowShadowOffsetAngle)) * style.WindowShadowOffsetDist; drawList->AddShadowRect(pos, pos + imageSize, shadowCol, shadowSize, shadowOffset, ImDrawFlags_ShadowCutOutShapeBackground); ImGui::SameLine(); }; ImGui::NewLine(); u32 repeatCount = std::ceil(std::ceil(ImHexApi::System::getMainWindowSize().x / stride) / s_screenshots.size()); if (repeatCount == 0) repeatCount = 1; // Draw top screenshot row ImGui::SetCursorPosX(-position); for (u32 i = 0; i < repeatCount; i += 1) { for (const auto &[fileName, screenshot] : s_screenshots | std::views::reverse) { drawImage(fileName, screenshot); } } ImGui::NewLine(); // Draw bottom screenshot row ImGui::SetCursorPosX(-stride + position); for (u32 i = 0; i < repeatCount; i += 1) { for (const auto &[fileName, screenshot] : s_screenshots) { drawImage(fileName, screenshot); } } ImGui::SetNextWindowPos(ImGui::GetWindowPos() + (ImGui::GetWindowSize() / 2), ImGuiCond_Always, ImVec2(0.5F, 0.5F)); ImGui::SetNextWindowSize(ImVec2(400_scaled, 0), ImGuiCond_Always); if (ImGui::BeginPopup("FeatureDescription")) { const auto &description = s_screenshotDescriptions[clickedImage]; ImGuiExt::Header(description["title"].get<std::string>().c_str(), true); ImGuiExt::TextFormattedWrapped("{}", description["description"].get<std::string>().c_str()); ImGui::EndPopup(); } else { clickedImage.clear(); } // Continue button const auto buttonSize = scaled({ 100, 50 }); ImGui::SetCursorPos(ImHexApi::System::getMainWindowSize() - buttonSize - scaled({ 10, 10 })); ImGui::PushStyleVar(ImGuiStyleVar_Alpha, buttonFadeIn); if (ImGuiExt::DimmedButton(hex::format("{} {}", "hex.ui.common.continue"_lang, ICON_VS_ARROW_RIGHT).c_str(), buttonSize)) page += 1; ImGui::PopStyleVar(); } ImGui::PopStyleVar(); break; } // Language selection page case 1: { static const auto &languages = LocalizationManager::getSupportedLanguages(); static auto currLanguage = languages.begin(); static float prevTime = 0; ImGui::NewLine(); ImGui::NewLine(); ImGui::NewLine(); ImGui::NewLine(); static Blend textFadeOut(2.5F, 2.9F); static Blend textFadeIn(0.1F, 0.5F); auto currTime = ImGui::GetTime(); if ((currTime - prevTime) > 3) { prevTime = currTime; ++currLanguage; textFadeIn.reset(); textFadeOut.reset(); } if (currLanguage == languages.end()) currLanguage = languages.begin(); // Draw globe image const auto imageSize = s_compassTexture.getSize() / (1.5F * (1.0F / ImHexApi::System::getGlobalScale())); ImGui::SetCursorPos((ImGui::GetWindowSize() / 2 - imageSize / 2) - ImVec2(0, 50_scaled)); ImGui::Image(s_globeTexture, imageSize); ImGui::NewLine(); ImGui::NewLine(); // Draw information text ImGui::SetCursorPosX(0); const auto availableWidth = ImGui::GetContentRegionAvail().x; if (ImGui::BeginChild("##language_text", ImVec2(availableWidth, 30_scaled))) { ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetColorU32(ImGuiCol_Text, textFadeIn - textFadeOut)); ImGuiExt::TextFormattedCentered("{}", LocalizationManager::getLocalizedString("hex.builtin.setting.interface.language", currLanguage->first)); ImGui::PopStyleColor(); } ImGui::EndChild(); ImGui::NewLine(); // Draw language selection list ImGui::SetCursorPosX(availableWidth / 3); if (ImGui::BeginListBox("##language", ImVec2(availableWidth / 3, 0))) { for (const auto &[langId, language] : LocalizationManager::getSupportedLanguages()) { if (ImGui::Selectable(language.c_str(), langId == LocalizationManager::getSelectedLanguage())) { LocalizationManager::loadLanguage(langId); } } ImGui::EndListBox(); } // Continue button const auto buttonSize = scaled({ 100, 50 }); ImGui::SetCursorPos(ImHexApi::System::getMainWindowSize() - buttonSize - scaled({ 10, 10 })); if (ImGuiExt::DimmedButton(hex::format("{} {}", "hex.ui.common.continue"_lang, ICON_VS_ARROW_RIGHT).c_str(), buttonSize)) page += 1; break; } // Server contact page case 2: { static ImVec2 subWindowSize = { 0, 0 }; const auto windowSize = ImHexApi::System::getMainWindowSize(); // Draw telemetry subwindow ImGui::SetCursorPos((windowSize - subWindowSize) / 2); if (ImGuiExt::BeginSubWindow("hex.builtin.oobe.server_contact"_lang, nullptr, subWindowSize, ImGuiChildFlags_AutoResizeY)) { // Draw telemetry information auto yBegin = ImGui::GetCursorPosY(); std::string message = "hex.builtin.oobe.server_contact.text"_lang; ImGuiExt::TextFormattedWrapped("{}", message.c_str()); ImGui::NewLine(); // Draw table containing everything that's being reported if (ImGui::CollapsingHeader("hex.builtin.oobe.server_contact.data_collected_title"_lang)) { if (ImGui::BeginTable("hex.builtin.oobe.server_contact.data_collected_table", 2, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_ScrollY | ImGuiTableFlags_NoHostExtendY, ImVec2(ImGui::GetContentRegionAvail().x, 150_scaled))) { ImGui::TableSetupColumn("hex.builtin.oobe.server_contact.data_collected_table.key"_lang); ImGui::TableSetupColumn("hex.builtin.oobe.server_contact.data_collected_table.value"_lang, ImGuiTableColumnFlags_WidthStretch); ImGui::TableSetupScrollFreeze(0, 1); ImGui::TableHeadersRow(); ImGui::TableNextRow(); ImGui::TableNextColumn(); ImGui::TextUnformatted("hex.builtin.oobe.server_contact.data_collected.uuid"_lang); ImGui::TableNextColumn(); ImGui::TextWrapped("%s", s_uuid.c_str()); ImGui::TableNextRow(); ImGui::TableNextColumn(); ImGui::TextUnformatted("hex.builtin.oobe.server_contact.data_collected.version"_lang); ImGui::TableNextColumn(); ImGuiExt::TextFormattedWrapped("{}\n{}@{}\n{}", ImHexApi::System::getImHexVersion(), ImHexApi::System::getCommitHash(true), ImHexApi::System::getCommitBranch(), ImHexApi::System::isPortableVersion() ? "Portable" : "Installed" ); ImGui::TableNextRow(); ImGui::TableNextColumn(); ImGui::TextUnformatted("hex.builtin.oobe.server_contact.data_collected.os"_lang); ImGui::TableNextColumn(); ImGuiExt::TextFormattedWrapped("{}\n{}\n{}\n{}", ImHexApi::System::getOSName(), ImHexApi::System::getOSVersion(), ImHexApi::System::getArchitecture(), ImHexApi::System::getGPUVendor()); ImGui::EndTable(); } } ImGui::NewLine(); const auto width = ImGui::GetWindowWidth(); const auto buttonSize = ImVec2(width / 3 - ImGui::GetStyle().FramePadding.x * 3, 0); const auto buttonPos = [&](u8 index) { return ImGui::GetStyle().FramePadding.x + (buttonSize.x + ImGui::GetStyle().FramePadding.x * 3) * index; }; // Draw allow button ImGui::SetCursorPosX(buttonPos(0)); if (ImGui::Button("hex.ui.common.allow"_lang, buttonSize)) { ContentRegistry::Settings::write<int>("hex.builtin.setting.general", "hex.builtin.setting.general.server_contact", 1); ContentRegistry::Settings::write<int>("hex.builtin.setting.general", "hex.builtin.setting.general.upload_crash_logs", 1); page += 1; } ImGui::SameLine(); // Draw crash logs only button ImGui::SetCursorPosX(buttonPos(1)); if (ImGui::Button("hex.builtin.oobe.server_contact.crash_logs_only"_lang, buttonSize)) { ContentRegistry::Settings::write<int>("hex.builtin.setting.general", "hex.builtin.setting.general.server_contact", 0); ContentRegistry::Settings::write<int>("hex.builtin.setting.general", "hex.builtin.setting.general.upload_crash_logs", 1); page += 1; } ImGui::SameLine(); // Draw deny button ImGui::SetCursorPosX(buttonPos(2)); if (ImGui::Button("hex.ui.common.deny"_lang, buttonSize)) { ContentRegistry::Settings::write<int>("hex.builtin.setting.general", "hex.builtin.setting.general.server_contact", 0); ContentRegistry::Settings::write<int>("hex.builtin.setting.general", "hex.builtin.setting.general.upload_crash_logs", 0); page += 1; } auto yEnd = ImGui::GetCursorPosY(); subWindowSize = ImGui::GetWindowSize(); subWindowSize.y = (yEnd - yBegin) + 35_scaled; } ImGuiExt::EndSubWindow(); break; } // Tutorial page case 3: { ImGui::NewLine(); ImGui::NewLine(); ImGui::NewLine(); ImGui::NewLine(); // Draw compass image const auto imageSize = s_compassTexture.getSize() / (1.5F * (1.0F / ImHexApi::System::getGlobalScale())); ImGui::SetCursorPos((ImGui::GetWindowSize() / 2 - imageSize / 2) - ImVec2(0, 50_scaled)); ImGui::Image(s_compassTexture, imageSize); // Draw information text about playing the tutorial ImGui::SetCursorPosX(0); ImGuiExt::TextFormattedCentered("hex.builtin.oobe.tutorial_question"_lang); // Draw no button const auto buttonSize = scaled({ 100, 50 }); ImGui::SetCursorPos(ImHexApi::System::getMainWindowSize() - ImVec2(buttonSize.x * 2 + 20, buttonSize.y + 10)); if (ImGuiExt::DimmedButton("hex.ui.common.no"_lang, buttonSize)) { oobeDone = true; } // Draw yes button ImGui::SetCursorPos(ImHexApi::System::getMainWindowSize() - ImVec2(buttonSize.x + 10, buttonSize.y + 10)); if (ImGuiExt::DimmedButton("hex.ui.common.yes"_lang, buttonSize)) { tutorialEnabled = true; oobeDone = true; } break; } default: page = 0; } } ImGui::End(); // Handle finishing the out of box experience if (oobeDone) { static Blend backgroundFadeOut(0.0F, 1.0F); windowAlpha = 1.0F - backgroundFadeOut; if (backgroundFadeOut >= 1.0F) { if (tutorialEnabled) { TutorialManager::startTutorial("hex.builtin.tutorial.introduction"); } else { ContentRegistry::Settings::write<bool>("hex.builtin.setting.interface", "hex.builtin.setting.interface.achievement_popup", false); } TaskManager::doLater([] { ImHexApi::System::setWindowResizable(true); EventFrameBegin::unsubscribe(s_drawEvent); }); } } } } void setupOutOfBoxExperience() { // Don't show the out of box experience in the web version #if defined(OS_WEB) return; #endif // Check if there is a telemetry uuid s_uuid = ContentRegistry::Settings::read<std::string>("hex.builtin.setting.general", "hex.builtin.setting.general.uuid", ""); if (s_uuid.empty()) { // Generate a new UUID s_uuid = wolv::hash::generateUUID(); // Save UUID to settings ContentRegistry::Settings::write<std::string>("hex.builtin.setting.general", "hex.builtin.setting.general.uuid", s_uuid); } EventFirstLaunch::subscribe([] { ImHexApi::System::setWindowResizable(false); const auto imageTheme = ThemeManager::getImageTheme(); s_imhexBanner = ImGuiExt::Texture::fromSVG(romfs::get(hex::format("assets/{}/banner.svg", imageTheme)).span<std::byte>()); s_compassTexture = ImGuiExt::Texture::fromImage(romfs::get("assets/common/compass.png").span<std::byte>()); s_globeTexture = ImGuiExt::Texture::fromImage(romfs::get("assets/common/globe.png").span<std::byte>()); s_screenshotDescriptions = nlohmann::json::parse(romfs::get("assets/screenshot_descriptions.json").string()); for (const auto &path : romfs::list("assets/screenshots")) { s_screenshots.emplace_back(path.filename(), ImGuiExt::Texture::fromImage(romfs::get(path).span<std::byte>(), ImGuiExt::Texture::Filter::Linear)); } s_drawEvent = EventFrameBegin::subscribe(drawOutOfBoxExperience); }); } }
23,322
C++
.cpp
364
39.398352
204
0.475201
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
179
command_palette_commands.cpp
WerWolv_ImHex/plugins/builtin/source/content/command_palette_commands.cpp
#include <hex/api/content_registry.hpp> #include <hex/api/imhex_api.hpp> #include <hex/api/localization_manager.hpp> #include <hex/api/shortcut_manager.hpp> #include <hex/helpers/utils.hpp> #include <hex/helpers/fmt.hpp> #include <hex/providers/provider.hpp> #include <wolv/math_eval/math_evaluator.hpp> #include <wolv/utils/guards.hpp> #include <wolv/utils/string.hpp> namespace hex::plugin::builtin { namespace { class Value { public: enum class Unit { Unitless, Decimal, Hexadecimal, Binary, Octal, Bits, Bytes, Invalid }; explicit Value(std::string value) { if (!value.starts_with("0x") && !value.starts_with("0b")) { auto index = value.find_first_not_of("0123456789.,"); if (index == std::string::npos) { m_unit = Unit::Unitless; } else { std::tie(m_unit, m_multiplier) = parseUnit(value.substr(index)); value = value.substr(0, index); } } else { m_unit = Unit::Unitless; } try { if (!value.contains('.')) { m_value = i128(std::stoull(value, nullptr, 0) * static_cast<long double>(m_multiplier)); } else { m_value = std::stod(value) * m_multiplier; } } catch (const std::exception &) { m_value = i128(0); m_unit = Unit::Invalid; m_unitString.clear(); m_multiplier = 1; } } std::string formatAs(Value other) { return std::visit([&, this]<typename T>(T value) -> std::string { auto unit = other.getUnit(); auto multipler = other.getMultiplier(); bool isInteger = std::integral<T> && multipler == 1; switch (m_unit) { case Unit::Invalid: if (this->getUnitString() != other.getUnitString()) return "hex.builtin.command.convert.invalid_conversion"_lang; unit = Unit::Decimal; [[fallthrough]]; case Unit::Unitless: { switch (unit) { case Unit::Unitless: case Unit::Decimal: if (isInteger) return hex::format("{0}", value / multipler); else return hex::format("{0:.3f}", value / multipler); case Unit::Hexadecimal: return hex::format("0x{0:x}", u128(value / multipler)); case Unit::Binary: return hex::format("0b{0:b}", u128(value / multipler)); case Unit::Octal: return hex::format("0o{0:o}", u128(value / multipler)); case Unit::Bytes: return hex::format("{0}", u128(value / multipler)); default: return "hex.builtin.command.convert.invalid_conversion"_lang; } break; } case Unit::Bits: { switch (unit) { case Unit::Bits: case Unit::Decimal: if (isInteger) return hex::format("{0}", value / multipler); else return hex::format("{0:.3f}", value / multipler); case Unit::Hexadecimal: return hex::format("0x{0:x}", u128(value / multipler)); case Unit::Binary: return hex::format("0b{0:b}", u128(value / multipler)); case Unit::Octal: return hex::format("0o{0:o}", u128(value / multipler)); case Unit::Bytes: return hex::format("{0}", u128((value / multipler) / 8)); default: return "hex.builtin.command.convert.invalid_conversion"_lang; } break; } case Unit::Bytes: { switch (unit) { case Unit::Bytes: case Unit::Decimal: if (isInteger) return hex::format("{0}", value / multipler); else return hex::format("{0:.3f}", value / multipler); case Unit::Hexadecimal: return hex::format("0x{0:x}", u128(value / multipler)); case Unit::Binary: return hex::format("0b{0:b}", u128(value / multipler)); case Unit::Octal: return hex::format("0o{0:o}", u128(value / multipler)); case Unit::Bits: return hex::format("{0}", u128((value / multipler) * 8)); default: return "hex.builtin.command.convert.invalid_conversion"_lang; } break; } default: return "hex.builtin.command.convert.invalid_input"_lang; } }, m_value); } [[nodiscard]] Unit getUnit() const { return m_unit; } [[nodiscard]] double getMultiplier() const { return m_multiplier; } [[nodiscard]] const std::string& getUnitString() const { return m_unitString; } private: std::pair<Unit, double> parseUnit(std::string unitString, bool parseMultiplier = true) { auto unitStringCopy = unitString; unitString = wolv::util::trim(unitString); double multiplier = 1; if (parseMultiplier && !unitString.starts_with("dec") && !unitString.starts_with("hex") && !unitString.starts_with("bin") && !unitString.starts_with("oct")) { if (unitString.starts_with("Ki")) { multiplier = 1024ULL; unitString = unitString.substr(2); } else if (unitString.starts_with("Mi")) { multiplier = 1024ULL * 1024ULL; unitString = unitString.substr(2); } else if (unitString.starts_with("Gi")) { multiplier = 1024ULL * 1024ULL * 1024ULL; unitString = unitString.substr(2); } else if (unitString.starts_with("Ti")) { multiplier = 1024ULL * 1024ULL * 1024ULL * 1024ULL; unitString = unitString.substr(2); } else if (unitString.starts_with("Pi")) { multiplier = 1024ULL * 1024ULL * 1024ULL * 1024ULL * 1024ULL; unitString = unitString.substr(2); } else if (unitString.starts_with("k")) { multiplier = 1E3; unitString = unitString.substr(1); } else if (unitString.starts_with("M")) { multiplier = 1E6; unitString = unitString.substr(1); } else if (unitString.starts_with("G")) { multiplier = 1E9; unitString = unitString.substr(1); } else if (unitString.starts_with("T")) { multiplier = 1E12; unitString = unitString.substr(1); } else if (unitString.starts_with("P")) { multiplier = 1E15; unitString = unitString.substr(1); } else if (unitString.starts_with("E")) { multiplier = 1E18; unitString = unitString.substr(1); } else if (unitString.starts_with("Z")) { multiplier = 1E21; unitString = unitString.substr(1); } else if (unitString.starts_with("Y")) { multiplier = 1E24; unitString = unitString.substr(1); } else if (unitString.starts_with("d")) { multiplier = 1E-1; unitString = unitString.substr(1); } else if (unitString.starts_with("c")) { multiplier = 1E-2; unitString = unitString.substr(1); } else if (unitString.starts_with("m")) { multiplier = 1E-3; unitString = unitString.substr(1); } else if (unitString.starts_with("u")) { multiplier = 1E-6; unitString = unitString.substr(1); } else if (unitString.starts_with("n")) { multiplier = 1E-9; unitString = unitString.substr(1); } else if (unitString.starts_with("p")) { multiplier = 1E-12; unitString = unitString.substr(1); } else if (unitString.starts_with("f")) { multiplier = 1E-15; unitString = unitString.substr(1); } else if (unitString.starts_with("a")) { multiplier = 1E-18; unitString = unitString.substr(1); } else if (unitString.starts_with("z")) { multiplier = 1E-21; unitString = unitString.substr(1); } else if (unitString.starts_with("y")) { multiplier = 1E-24; unitString = unitString.substr(1); } else { return parseUnit(unitString, false); } } unitString = wolv::util::trim(unitString); m_unitString = unitString; if (unitString.empty()) { if (multiplier == 1) { return { Unit::Unitless, 1 }; } else { m_unitString = unitStringCopy; return { Unit::Unitless, 1 }; } } else if (unitString == "bit" || unitString == "bits" || unitString == "b") { return { Unit::Bits, multiplier }; } else if (unitString == "byte" || unitString == "bytes" || unitString == "B") { return { Unit::Bytes, multiplier }; } else if (unitString == "hex" || unitString == "hex.builtin.command.convert.hexadecimal"_lang.get()) { return { Unit::Hexadecimal, multiplier }; } else if (unitString == "bin" || unitString == "hex.builtin.command.convert.binary"_lang.get()) { return { Unit::Binary, multiplier }; } else if (unitString == "oct" || unitString == "hex.builtin.command.convert.octal"_lang.get()) { return { Unit::Octal, multiplier }; } else if (unitString == "dec" || unitString == "hex.builtin.command.convert.decimal"_lang.get()) { return { Unit::Decimal, multiplier }; } else { return { Unit::Invalid, multiplier }; } } private: Unit m_unit; std::string m_unitString; double m_multiplier = 1; std::variant<i128, double> m_value; }; std::vector<std::string> splitConversionCommandInput(const std::string &input) { std::vector<std::string> parts = wolv::util::splitString(input, " ", true); std::erase_if(parts, [](auto &part) { return part.empty(); }); return parts; } bool verifyConversionInput(const std::vector<std::string> &parts) { if (parts.size() == 3) { return parts[1] == "hex.builtin.command.convert.to"_lang.get() || parts[1] == "hex.builtin.command.convert.in"_lang.get() || parts[1] == "hex.builtin.command.convert.as"_lang.get(); } else { return false; } } std::string handleConversionCommand(const std::string &input) { auto parts = splitConversionCommandInput(input); if (!verifyConversionInput(parts)) return "hex.builtin.command.convert.invalid_input"_lang; auto from = Value(parts[0]); auto to = Value("1" + parts[2]); return fmt::format("% {}", from.formatAs(to)); } } void registerCommandPaletteCommands() { ContentRegistry::CommandPaletteCommands::add( ContentRegistry::CommandPaletteCommands::Type::SymbolCommand, "=", "hex.builtin.command.calc.desc", [](auto input) { wolv::math_eval::MathEvaluator<long double> evaluator; evaluator.registerStandardVariables(); evaluator.registerStandardFunctions(); std::optional<long double> result = evaluator.evaluate(input); if (result.has_value()) return hex::format("{0} = {1}", input.data(), result.value()); else if (evaluator.hasError()) return hex::format("Error: {}", *evaluator.getLastError()); else return std::string("???"); }); ContentRegistry::CommandPaletteCommands::add( ContentRegistry::CommandPaletteCommands::Type::KeywordCommand, "/web", "hex.builtin.command.web.desc", [](auto input) { return hex::format("hex.builtin.command.web.result"_lang, input.data()); }, [](auto input) { hex::openWebpage(input); }); ContentRegistry::CommandPaletteCommands::add( ContentRegistry::CommandPaletteCommands::Type::SymbolCommand, "$", "hex.builtin.command.cmd.desc", [](auto input) { return hex::format("hex.builtin.command.cmd.result"_lang, input.data()); }, [](auto input) { hex::executeCommand(input); }); ContentRegistry::CommandPaletteCommands::addHandler( ContentRegistry::CommandPaletteCommands::Type::SymbolCommand, ">", [](const auto &input) { std::vector<ContentRegistry::CommandPaletteCommands::impl::QueryResult> result; for (const auto &[priority, entry] : ContentRegistry::Interface::impl::getMenuItems()) { if (!entry.enabledCallback()) continue; std::vector<std::string> names; std::transform(entry.unlocalizedNames.begin(), entry.unlocalizedNames.end(), std::back_inserter(names), [](auto &name) { return Lang(name); }); if (auto combined = wolv::util::combineStrings(names, " -> "); hex::containsIgnoreCase(combined, input) && !combined.contains(ContentRegistry::Interface::impl::SeparatorValue) && !combined.contains(ContentRegistry::Interface::impl::SubMenuValue)) { result.emplace_back(ContentRegistry::CommandPaletteCommands::impl::QueryResult { std::move(combined), [&entry](const auto&) { entry.callback(); } }); } } return result; }, [](auto input) { return hex::format("Menu Item: {}", input.data()); }); ContentRegistry::CommandPaletteCommands::addHandler( ContentRegistry::CommandPaletteCommands::Type::SymbolCommand, ".", [](const auto &input) { std::vector<ContentRegistry::CommandPaletteCommands::impl::QueryResult> result; u32 index = 0; for (const auto &provider : ImHexApi::Provider::getProviders()) { ON_SCOPE_EXIT { index += 1; }; auto name = provider->getName(); if (!hex::containsIgnoreCase(name, input)) continue; result.emplace_back(ContentRegistry::CommandPaletteCommands::impl::QueryResult { provider->getName(), [index](const auto&) { ImHexApi::Provider::setCurrentProvider(index); } }); } return result; }, [](auto input) { return hex::format("Provider: {}", input.data()); }); ContentRegistry::CommandPaletteCommands::add( ContentRegistry::CommandPaletteCommands::Type::SymbolCommand, "%", "hex.builtin.command.convert.desc", handleConversionCommand); } }
17,395
C++
.cpp
301
37.488372
272
0.476414
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
180
workspaces.cpp
WerWolv_ImHex/plugins/builtin/source/content/workspaces.cpp
#include <hex/api/content_registry.hpp> #include <hex/api/task_manager.hpp> #include <hex/api/workspace_manager.hpp> #include <hex/helpers/fs.hpp> namespace hex::plugin::builtin { void loadWorkspaces() { WorkspaceManager::reload(); auto currentWorkspace = ContentRegistry::Settings::read<std::string>("hex.builtin.setting.general", "hex.builtin.setting.general.curr_workspace", "Default"); TaskManager::doLater([currentWorkspace] { WorkspaceManager::switchWorkspace(currentWorkspace); }); } }
550
C++
.cpp
13
36.923077
165
0.718045
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
181
communication_interface.cpp
WerWolv_ImHex/plugins/builtin/source/content/communication_interface.cpp
#include <hex/api/content_registry.hpp> #include <hex/api/event_manager.hpp> #include <nlohmann/json.hpp> namespace hex::plugin::builtin { void registerNetworkEndpoints() { ContentRegistry::CommunicationInterface::registerNetworkEndpoint("pattern_editor/set_code", [](const nlohmann::json &data) -> nlohmann::json { auto code = data.at("code").get<std::string>(); RequestSetPatternLanguageCode::post(code); return { }; }); ContentRegistry::CommunicationInterface::registerNetworkEndpoint("imhex/capabilities", [](const nlohmann::json &) -> nlohmann::json { nlohmann::json result; result["build"] = { { "version", ImHexApi::System::getImHexVersion() }, { "commit", ImHexApi::System::getCommitHash(true) }, { "branch", ImHexApi::System::getCommitBranch() } }; std::vector<std::string> commands; for (const auto&[command, callback] : ContentRegistry::CommunicationInterface::impl::getNetworkEndpoints()) commands.emplace_back(command); result["commands"] = commands; return result; }); } }
1,227
C++
.cpp
25
38.72
150
0.61745
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
182
report_generators.cpp
WerWolv_ImHex/plugins/builtin/source/content/report_generators.cpp
#include <hex/api/content_registry.hpp> #include <hex/helpers/fmt.hpp> #include <hex/helpers/utils.hpp> #include <hex/providers/provider.hpp> namespace hex::plugin::builtin { namespace { } void registerReportGenerators() { // Generate provider data description report ContentRegistry::Reports::addReportProvider([](const prv::Provider *provider) -> std::string { std::string result; result += "## Data description\n\n"; result += "| Type | Value |\n"; result += "| ---- | ----- |\n"; for (const auto &[type, value] : provider->getDataDescription()) result += hex::format("| {} | {} |\n", type, value); return result; }); // Generate provider overlays report ContentRegistry::Reports::addReportProvider([](prv::Provider *provider) -> std::string { std::string result; const auto &overlays = provider->getOverlays(); if (overlays.empty()) return ""; result += "## Overlays\n\n"; for (const auto &overlay : overlays) { result += hex::format("### Overlay 0x{:04X} - 0x{:04X}", overlay->getAddress(), overlay->getAddress() + overlay->getSize() - 1); result += "\n\n"; result += "```\n"; result += hex::generateHexView(overlay->getAddress(), overlay->getSize(), provider); result += "\n```\n\n"; } return result; }); } }
1,562
C++
.cpp
36
32.75
144
0.540702
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
183
minimap_visualizers.cpp
WerWolv_ImHex/plugins/builtin/source/content/minimap_visualizers.cpp
#include <hex/api/content_registry.hpp> #include <imgui.h> #include <imgui_internal.h> #include <hex/api/imhex_api.hpp> #include <hex/ui/imgui_imhex_extensions.h> #include <hex/helpers/utils.hpp> #include <pl/patterns/pattern.hpp> #include <wolv/utils/lock.hpp> #include <wolv/utils/string.hpp> namespace hex::plugin::builtin { namespace { void entropyMiniMapVisualizer(u64, std::span<const u8> data, std::vector<ImColor> &output) { std::array<u8, 256> frequencies = { 0 }; for (u8 byte : data) frequencies[byte] += 1; double entropy = 0.0; for (u32 frequency : frequencies) { if (frequency == 0) continue; double probability = static_cast<double>(frequency) / data.size(); entropy -= probability * std::log2(probability); } // Calculate color ImColor color = ImColor::HSV(0.0F, 0.0F, 1.0F); if (entropy > 0.0) { double hue = std::clamp(entropy / 8.0, 0.0, 1.0); color = ImColor::HSV(static_cast<float>(hue) / 0.75F, 0.8F, 1.0F); } output.push_back(color); } void zerosCountMiniMapVisualizer(u64, std::span<const u8> data, std::vector<ImColor> &output) { u32 zerosCount = 0; for (u8 byte : data) { if (byte == 0x00) zerosCount += 1; } output.push_back(ImColor::HSV(0.0F, 0.0F, 1.0F - (double(zerosCount) / data.size()))); } void zerosMiniMapVisualizer(u64, std::span<const u8> data, std::vector<ImColor> &output) { for (u8 byte : data) { if (byte == 0x00) output.push_back(ImColor(1.0F, 1.0F, 1.0F, 1.0F)); else output.push_back(ImColor(0.0F, 0.0F, 0.0F, 1.0F)); } } void byteTypeMiniMapVisualizer(u64, std::span<const u8> data, std::vector<ImColor> &output) { for (u8 byte : data) { if (std::isalpha(byte)) output.emplace_back(1.0F, 0.0F, 0.0F, 1.0F); else if (std::isdigit(byte)) output.emplace_back(0.0F, 1.0F, 0.0F, 1.0F); else if (std::isspace(byte)) output.emplace_back(0.0F, 0.0F, 1.0F, 1.0F); else if (std::iscntrl(byte)) output.emplace_back(0.5F, 0.5F, 0.5F, 1.0F); else output.emplace_back(0.0F, 0.0F, 0.0F, 1.0F); } } void asciiCountMiniMapVisualizer(u64, std::span<const u8> data, std::vector<ImColor> &output) { u8 asciiCount = 0; for (u8 byte : data) { if (std::isprint(byte)) asciiCount += 1; } output.push_back(ImColor::HSV(0.5F, 0.5F, (double(asciiCount) / data.size()))); } void byteMagnitudeMiniMapVisualizer(u64, std::span<const u8> data, std::vector<ImColor> &output) { for (u8 byte : data) { output.push_back(ImColor::HSV(0.0F, 0.0F, static_cast<float>(byte) / 255.0F)); } } void highlightsMiniMapVisualizer(u64 address, std::span<const u8> data, std::vector<ImColor> &output) { for (size_t i = 0; i < data.size(); i += 1) { std::optional<ImColor> result; for (const auto &[id, callback] : ImHexApi::HexEditor::impl::getBackgroundHighlightingFunctions()) { if (auto color = callback(address + i, data.data() + i, 1, 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, 1 })) { result = highlighting.getColor(); break; } } } if (result.has_value()) { result->Value.w = 1.0F; } else { if (auto region = ImHexApi::HexEditor::getSelection(); region.has_value()) { if (region->overlaps({ address + i, 1 })) result = 0x60C08080; } } output.push_back(result.value_or(ImColor())); } } } void registerMiniMapVisualizers() { ContentRegistry::HexEditor::addMiniMapVisualizer("hex.builtin.minimap_visualizer.highlights", highlightsMiniMapVisualizer); ContentRegistry::HexEditor::addMiniMapVisualizer("hex.builtin.minimap_visualizer.entropy", entropyMiniMapVisualizer); ContentRegistry::HexEditor::addMiniMapVisualizer("hex.builtin.minimap_visualizer.zero_count", zerosCountMiniMapVisualizer); ContentRegistry::HexEditor::addMiniMapVisualizer("hex.builtin.minimap_visualizer.zeros", zerosMiniMapVisualizer); ContentRegistry::HexEditor::addMiniMapVisualizer("hex.builtin.minimap_visualizer.ascii_count", asciiCountMiniMapVisualizer); ContentRegistry::HexEditor::addMiniMapVisualizer("hex.builtin.minimap_visualizer.byte_type", byteTypeMiniMapVisualizer); ContentRegistry::HexEditor::addMiniMapVisualizer("hex.builtin.minimap_visualizer.byte_magnitude", byteMagnitudeMiniMapVisualizer); } }
5,640
C++
.cpp
110
37.354545
140
0.548955
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
184
global_actions.cpp
WerWolv_ImHex/plugins/builtin/source/content/global_actions.cpp
#include <content/global_actions.hpp> #include <hex/ui/view.hpp> #include <hex/api/project_file_manager.hpp> #include <hex/helpers/logger.hpp> #include <toasts/toast_notification.hpp> #include <wolv/utils/string.hpp> namespace hex::plugin::builtin { void openProject() { fs::openFileBrowser(fs::DialogMode::Open, { {"Project File", "hexproj"} }, [](const auto &path) { if (!ProjectFile::load(path)) { ui::ToastError::open(hex::format("hex.builtin.popup.error.project.load"_lang, wolv::util::toUTF8String(path))); } }); } bool saveProject() { if (!ImHexApi::Provider::isValid()) return false; if (ProjectFile::hasPath()) { if (!ProjectFile::store()) { ui::ToastError::open("hex.builtin.popup.error.project.save"_lang); return false; } else { log::debug("Project saved"); return true; } } else { return saveProjectAs(); } } bool saveProjectAs() { return fs::openFileBrowser(fs::DialogMode::Save, { {"Project File", "hexproj"} }, [](std::fs::path path) { if (path.extension() != ".hexproj") { path.replace_extension(".hexproj"); } if (!ProjectFile::store(path)) { ui::ToastError::open("hex.builtin.popup.error.project.save"_lang); } }); } }
1,755
C++
.cpp
42
26.095238
147
0.465376
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
185
pl_builtin_functions.cpp
WerWolv_ImHex/plugins/builtin/source/content/pl_builtin_functions.cpp
#include <hex/api/imhex_api.hpp> #include <hex/api/content_registry.hpp> #include <hex/providers/provider.hpp> #include <hex/helpers/http_requests.hpp> #include <pl/core/token.hpp> #include <pl/core/evaluator.hpp> #include <content/helpers/demangle.hpp> #include <pl/patterns/pattern.hpp> namespace hex::plugin::builtin { void registerPatternLanguageFunctions() { using namespace pl::core; using FunctionParameterCount = pl::api::FunctionParameterCount; { const pl::api::Namespace nsHexCore = { "builtin", "hex", "core" }; /* get_selection() */ ContentRegistry::PatternLanguage::addFunction(nsHexCore, "get_selection", FunctionParameterCount::none(), [](Evaluator *, auto) -> std::optional<Token::Literal> { if (!ImHexApi::HexEditor::isSelectionValid()) return std::numeric_limits<u128>::max(); auto selection = ImHexApi::HexEditor::getSelection(); return u128(u128(selection->getStartAddress()) << 64 | u128(selection->getSize())); }); /* add_virtual_file(path, pattern) */ ContentRegistry::PatternLanguage::addFunction(nsHexCore, "add_virtual_file", FunctionParameterCount::exactly(2), [](Evaluator *, auto params) -> std::optional<Token::Literal> { auto path = params[0].toString(false); auto pattern = params[1].toPattern(); Region region = Region::Invalid(); if (pattern->getSection() == pl::ptrn::Pattern::MainSectionId) region = Region(pattern->getOffset(), pattern->getSize()); ImHexApi::HexEditor::addVirtualFile(path, pattern->getBytes(), region); return std::nullopt; }); } { const pl::api::Namespace nsHexPrv = { "builtin", "hex", "prv" }; /* get_information() */ ContentRegistry::PatternLanguage::addFunction(nsHexPrv, "get_information", FunctionParameterCount::between(1, 2), [](Evaluator *, auto params) -> std::optional<Token::Literal> { std::string category = params[0].toString(false); std::string argument = params.size() == 2 ? params[1].toString(false) : ""; if (!ImHexApi::Provider::isValid()) return u128(0); auto provider = ImHexApi::Provider::get(); if (!provider->isAvailable()) return u128(0); return std::visit( [](auto &&value) -> Token::Literal { return value; }, provider->queryInformation(category, argument) ); }); } { const pl::api::Namespace nsHexDec = { "builtin", "hex", "dec" }; /* demangle(mangled_string) */ ContentRegistry::PatternLanguage::addFunction(nsHexDec, "demangle", FunctionParameterCount::exactly(1), [](Evaluator *, auto params) -> std::optional<Token::Literal> { const auto mangledString = params[0].toString(false); return hex::plugin::builtin::demangle(mangledString); }); } { const pl::api::Namespace nsHexHttp = { "builtin", "hex", "http" }; /* get(url) */ ContentRegistry::PatternLanguage::addDangerousFunction(nsHexHttp, "get", FunctionParameterCount::exactly(1), [](Evaluator *, auto params) -> std::optional<Token::Literal> { const auto url = params[0].toString(false); hex::HttpRequest request("GET", url); return request.execute().get().getData(); }); } } }
3,761
C++
.cpp
70
40.728571
189
0.574584
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
186
achievements.cpp
WerWolv_ImHex/plugins/builtin/source/content/achievements.cpp
#include <hex/api/achievement_manager.hpp> #include <hex/api/project_file_manager.hpp> #include <hex/api/event_manager.hpp> #include <hex/helpers/crypto.hpp> #include <toasts/toast_notification.hpp> #include <popups/popup_notification.hpp> #include <popups/popup_text_input.hpp> #include <nlohmann/json.hpp> #include <romfs/romfs.hpp> namespace hex::plugin::builtin { namespace { class AchievementStartingOut : public Achievement { public: explicit AchievementStartingOut(UnlocalizedString unlocalizedName) : Achievement("hex.builtin.achievement.starting_out", std::move(unlocalizedName)) { } }; class AchievementHexEditor : public Achievement { public: explicit AchievementHexEditor(UnlocalizedString unlocalizedName) : Achievement("hex.builtin.achievement.hex_editor", std::move(unlocalizedName)) { } }; class AchievementPatterns : public Achievement { public: explicit AchievementPatterns(UnlocalizedString unlocalizedName) : Achievement("hex.builtin.achievement.patterns", std::move(unlocalizedName)) { } }; class AchievementDataProcessor : public Achievement { public: explicit AchievementDataProcessor(UnlocalizedString unlocalizedName) : Achievement("hex.builtin.achievement.data_processor", std::move(unlocalizedName)) { } }; class AchievementFind : public Achievement { public: explicit AchievementFind(UnlocalizedString unlocalizedName) : Achievement("hex.builtin.achievement.find", std::move(unlocalizedName)) { } }; class AchievementMisc : public Achievement { public: explicit AchievementMisc(UnlocalizedString unlocalizedName) : Achievement("hex.builtin.achievement.misc", std::move(unlocalizedName)) { } }; void registerGettingStartedAchievements() { AchievementManager::addAchievement<AchievementStartingOut>("hex.builtin.achievement.starting_out.docs.name") .setDescription("hex.builtin.achievement.starting_out.docs.desc") .setIcon(romfs::get("assets/achievements/open-book.png").span()); AchievementManager::addAchievement<AchievementStartingOut>("hex.builtin.achievement.starting_out.open_file.name") .setDescription("hex.builtin.achievement.starting_out.open_file.desc") .setIcon(romfs::get("assets/achievements/page-facing-up.png").span()); AchievementManager::addAchievement<AchievementStartingOut>("hex.builtin.achievement.starting_out.save_project.name") .setDescription("hex.builtin.achievement.starting_out.save_project.desc") .setIcon(romfs::get("assets/achievements/card-index-dividers.png").span()) .addRequirement("hex.builtin.achievement.starting_out.open_file.name"); AchievementManager::addAchievement<AchievementStartingOut>("hex.builtin.achievement.starting_out.crash.name") .setDescription("hex.builtin.achievement.starting_out.crash.desc") .setIcon(romfs::get("assets/achievements/collision-symbol.png").span()) .setInvisible(); } void registerHexEditorAchievements() { AchievementManager::addAchievement<AchievementHexEditor>("hex.builtin.achievement.hex_editor.select_byte.name") .setDescription("hex.builtin.achievement.hex_editor.select_byte.desc") .setIcon(romfs::get("assets/achievements/bookmark-tabs.png").span()) .addRequirement("hex.builtin.achievement.starting_out.open_file.name"); AchievementManager::addAchievement<AchievementHexEditor>("hex.builtin.achievement.hex_editor.open_new_view.name") .setDescription("hex.builtin.achievement.hex_editor.open_new_view.desc") .setIcon(romfs::get("assets/achievements/frame-with-picture.png").span()) .addRequirement("hex.builtin.achievement.hex_editor.create_bookmark.name"); AchievementManager::addAchievement<AchievementHexEditor>("hex.builtin.achievement.hex_editor.modify_byte.name") .setDescription("hex.builtin.achievement.hex_editor.modify_byte.desc") .setIcon(romfs::get("assets/achievements/pencil.png").span()) .addRequirement("hex.builtin.achievement.hex_editor.select_byte.name") .addVisibilityRequirement("hex.builtin.achievement.hex_editor.select_byte.name"); AchievementManager::addAchievement<AchievementHexEditor>("hex.builtin.achievement.hex_editor.copy_as.name") .setDescription("hex.builtin.achievement.hex_editor.copy_as.desc") .setIcon(romfs::get("assets/achievements/copy.png").span()) .addRequirement("hex.builtin.achievement.hex_editor.modify_byte.name"); AchievementManager::addAchievement<AchievementHexEditor>("hex.builtin.achievement.hex_editor.create_patch.name") .setDescription("hex.builtin.achievement.hex_editor.create_patch.desc") .setIcon(romfs::get("assets/achievements/adhesive-bandage.png").span()) .addRequirement("hex.builtin.achievement.hex_editor.modify_byte.name"); AchievementManager::addAchievement<AchievementHexEditor>("hex.builtin.achievement.hex_editor.fill.name") .setDescription("hex.builtin.achievement.hex_editor.fill.desc") .setIcon(romfs::get("assets/achievements/water-wave.png").span()) .addRequirement("hex.builtin.achievement.hex_editor.select_byte.name") .addVisibilityRequirement("hex.builtin.achievement.hex_editor.select_byte.name"); AchievementManager::addAchievement<AchievementHexEditor>("hex.builtin.achievement.hex_editor.create_bookmark.name") .setDescription("hex.builtin.achievement.hex_editor.create_bookmark.desc") .setIcon(romfs::get("assets/achievements/bookmark.png").span()) .addRequirement("hex.builtin.achievement.hex_editor.select_byte.name") .addVisibilityRequirement("hex.builtin.achievement.hex_editor.select_byte.name"); } void registerPatternsAchievements() { AchievementManager::addAchievement<AchievementPatterns>("hex.builtin.achievement.patterns.place_menu.name") .setDescription("hex.builtin.achievement.patterns.place_menu.desc") .setIcon(romfs::get("assets/achievements/clipboard.png").span()) .addRequirement("hex.builtin.achievement.hex_editor.select_byte.name"); AchievementManager::addAchievement<AchievementPatterns>("hex.builtin.achievement.patterns.load_existing.name") .setDescription("hex.builtin.achievement.patterns.load_existing.desc") .setIcon(romfs::get("assets/achievements/hourglass.png").span()) .addRequirement("hex.builtin.achievement.patterns.place_menu.name"); AchievementManager::addAchievement<AchievementPatterns>("hex.builtin.achievement.patterns.modify_data.name") .setDescription("hex.builtin.achievement.patterns.modify_data.desc") .setIcon(romfs::get("assets/achievements/hammer.png").span()) .addRequirement("hex.builtin.achievement.patterns.place_menu.name"); AchievementManager::addAchievement<AchievementPatterns>("hex.builtin.achievement.patterns.data_inspector.name") .setDescription("hex.builtin.achievement.patterns.data_inspector.desc") .setIcon(romfs::get("assets/achievements/eye-in-speech-bubble.png").span()) .addRequirement("hex.builtin.achievement.hex_editor.select_byte.name"); } void registerFindAchievements() { AchievementManager::addAchievement<AchievementFind>("hex.builtin.achievement.find.find_strings.name") .setDescription("hex.builtin.achievement.find.find_strings.desc") .setIcon(romfs::get("assets/achievements/ring.png").span()) .addRequirement("hex.builtin.achievement.starting_out.open_file.name"); AchievementManager::addAchievement<AchievementFind>("hex.builtin.achievement.find.find_specific_string.name") .setDescription("hex.builtin.achievement.find.find_specific_string.desc") .setIcon(romfs::get("assets/achievements/right-pointing-magnifying-glass.png").span()) .addRequirement("hex.builtin.achievement.find.find_strings.name"); AchievementManager::addAchievement<AchievementFind>("hex.builtin.achievement.find.find_numeric.name") .setDescription("hex.builtin.achievement.find.find_numeric.desc") .setIcon(romfs::get("assets/achievements/abacus.png").span()) .addRequirement("hex.builtin.achievement.find.find_strings.name"); } void registerDataProcessorAchievements() { AchievementManager::addAchievement<AchievementDataProcessor>("hex.builtin.achievement.data_processor.place_node.name") .setDescription("hex.builtin.achievement.data_processor.place_node.desc") .setIcon(romfs::get("assets/achievements/cloud.png").span()) .addRequirement("hex.builtin.achievement.starting_out.open_file.name"); AchievementManager::addAchievement<AchievementDataProcessor>("hex.builtin.achievement.data_processor.create_connection.name") .setDescription("hex.builtin.achievement.data_processor.create_connection.desc") .setIcon(romfs::get("assets/achievements/linked-paperclips.png").span()) .addRequirement("hex.builtin.achievement.data_processor.place_node.name"); AchievementManager::addAchievement<AchievementDataProcessor>("hex.builtin.achievement.data_processor.modify_data.name") .setDescription("hex.builtin.achievement.data_processor.modify_data.desc") .setIcon(romfs::get("assets/achievements/hammer-and-pick.png").span()) .addRequirement("hex.builtin.achievement.data_processor.create_connection.name"); AchievementManager::addAchievement<AchievementDataProcessor>("hex.builtin.achievement.data_processor.custom_node.name") .setDescription("hex.builtin.achievement.data_processor.custom_node.desc") .setIcon(romfs::get("assets/achievements/wrench.png").span()) .addRequirement("hex.builtin.achievement.data_processor.create_connection.name"); } void registerMiscAchievements() { AchievementManager::addAchievement<AchievementMisc>("hex.builtin.achievement.misc.analyze_file.name") .setDescription("hex.builtin.achievement.misc.analyze_file.desc") .setIcon(romfs::get("assets/achievements/brain.png").span()) .addRequirement("hex.builtin.achievement.starting_out.open_file.name"); AchievementManager::addAchievement<AchievementMisc>("hex.builtin.achievement.misc.download_from_store.name") .setDescription("hex.builtin.achievement.misc.download_from_store.desc") .setIcon(romfs::get("assets/achievements/package.png").span()) .addRequirement("hex.builtin.achievement.starting_out.open_file.name"); } void registerEvents() { EventRegionSelected::subscribe([](const auto &region) { if (region.getSize() > 1) AchievementManager::unlockAchievement("hex.builtin.achievement.hex_editor", "hex.builtin.achievement.hex_editor.select_byte.name"); }); EventBookmarkCreated::subscribe([](const auto&) { AchievementManager::unlockAchievement("hex.builtin.achievement.hex_editor", "hex.builtin.achievement.hex_editor.create_bookmark.name"); }); EventPatchCreated::subscribe([](u64, u8, u8) { AchievementManager::unlockAchievement("hex.builtin.achievement.hex_editor", "hex.builtin.achievement.hex_editor.modify_byte.name"); }); EventImHexStartupFinished::subscribe(AchievementManager::loadProgress); EventAchievementUnlocked::subscribe([](const Achievement &) { AchievementManager::storeProgress(); }); // Clear temporary achievements when the last provider is closed EventProviderChanged::subscribe([](hex::prv::Provider *oldProvider, const hex::prv::Provider *newProvider) { hex::unused(oldProvider); if (newProvider == nullptr) { AchievementManager::clearTemporary(); } }); } void registerChallengeAchievementHandlers() { static std::string challengeAchievement; static std::string challengeDescription; static std::map<std::string, std::vector<u8>> icons; ProjectFile::registerHandler({ .basePath = "challenge", .required = false, .load = [](const std::fs::path &basePath, const Tar &tar) { if (!tar.contains(basePath / "achievements.json") || !tar.contains(basePath / "description.txt")) return true; challengeAchievement = tar.readString(basePath / "achievements.json"); challengeDescription = tar.readString(basePath / "description.txt"); nlohmann::json unlockedJson; if (tar.contains(basePath / "unlocked.json")) { unlockedJson = nlohmann::json::parse(tar.readString(basePath / "unlocked.json")); } try { auto json = nlohmann::json::parse(challengeAchievement); if (json.contains("achievements")) { for (const auto &achievement : json["achievements"]) { auto &newAchievement = AchievementManager::addTemporaryAchievement<Achievement>("hex.builtin.achievement.challenge", achievement["name"].get<std::string>()) .setDescription(achievement["description"]); if (achievement.contains("icon")) { if (const auto &icon = achievement["icon"]; icon.is_string() && !icon.is_null()) { auto iconPath = icon.get<std::string>(); auto data = tar.readVector(basePath / iconPath); newAchievement.setIcon(data); icons[iconPath] = std::move(data); } } if (achievement.contains("requirements")) { if (const auto &requirements = achievement["requirements"]; requirements.is_array()) { for (const auto &requirement : requirements) { newAchievement.addRequirement(requirement.get<std::string>()); } } } if (achievement.contains("visibility_requirements")) { if (const auto &requirements = achievement["visibility_requirements"]; requirements.is_array()) { for (const auto &requirement : requirements) { newAchievement.addVisibilityRequirement(requirement.get<std::string>()); } } } if (achievement.contains("password")) { if (const auto &password = achievement["password"]; password.is_string() && !password.is_null()) { newAchievement.setClickCallback([password = password.get<std::string>()](Achievement &achievement) { if (password.empty()) achievement.setUnlocked(true); else ui::PopupTextInput::open("Enter Password", "Enter the password to unlock this achievement", [password, &achievement](const std::string &input) { if (input == password) achievement.setUnlocked(true); else ui::ToastWarning::open("The password you entered was incorrect."); }); }); if (unlockedJson.contains("achievements") && unlockedJson["achievements"].is_array()) { for (const auto &unlockedAchievement : unlockedJson["achievements"]) { if (unlockedAchievement.is_string() && unlockedAchievement.get<std::string>() == achievement["name"].get<std::string>()) { newAchievement.setUnlocked(true); break; } } } } } } } } catch (const nlohmann::json::exception &e) { log::error("Failed to load challenge project: {}", e.what()); return false; } ui::PopupInfo::open(challengeDescription); return true; }, .store = [](const std::fs::path &basePath, const Tar &tar) { if (!challengeAchievement.empty()) tar.writeString(basePath / "achievements.json", challengeAchievement); if (!challengeDescription.empty()) tar.writeString(basePath / "description.txt", challengeDescription); for (const auto &[iconPath, data] : icons) { tar.writeVector(basePath / iconPath, data); } nlohmann::json unlockedJson; unlockedJson["achievements"] = nlohmann::json::array(); for (const auto &[categoryName, achievements] : AchievementManager::getAchievements()) { for (const auto &[achievementName, achievement] : achievements) { if (achievement->isTemporary() && achievement->isUnlocked()) { unlockedJson["achievements"].push_back(achievementName); } } } tar.writeString(basePath / "unlocked.json", unlockedJson.dump(4)); return true; } }); } } void registerAchievements() { registerGettingStartedAchievements(); registerHexEditorAchievements(); registerPatternsAchievements(); registerFindAchievements(); registerDataProcessorAchievements(); registerMiscAchievements(); registerEvents(); registerChallengeAchievementHandlers(); } }
20,273
C++
.cpp
277
52.458484
192
0.590355
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
187
visual_nodes.cpp
WerWolv_ImHex/plugins/builtin/source/content/data_processor_nodes/visual_nodes.cpp
#include <imgui_internal.h> #include <hex/api/content_registry.hpp> #include <hex/helpers/utils.hpp> #include <hex/data_processor/node.hpp> #include <hex/ui/imgui_imhex_extensions.h> namespace hex::plugin::builtin { class NodeDisplayInteger : public dp::Node { public: NodeDisplayInteger() : Node("hex.builtin.nodes.display.int.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.common.input") }) { } void drawNode() override { ImGui::PushItemWidth(150_scaled); if (m_value.has_value()) { ImGuiExt::TextFormattedSelectable("{0:d}", m_value.value()); ImGuiExt::TextFormattedSelectable("0x{0:02X}", m_value.value()); ImGuiExt::TextFormattedSelectable("0o{0:03o}", m_value.value()); ImGuiExt::TextFormattedSelectable("0b{0:08b}", m_value.value()); } else { ImGui::TextUnformatted("???"); ImGui::TextUnformatted("???"); ImGui::TextUnformatted("???"); ImGui::TextUnformatted("???"); } ImGui::PopItemWidth(); } void process() override { m_value = this->getIntegerOnInput(0); } private: std::optional<u64> m_value; }; class NodeDisplayFloat : public dp::Node { public: NodeDisplayFloat() : Node("hex.builtin.nodes.display.float.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Float, "hex.builtin.nodes.common.input") }) { } void drawNode() override { ImGui::PushItemWidth(150_scaled); if (m_value.has_value()) ImGuiExt::TextFormattedSelectable("{0}", m_value.value()); else ImGui::TextUnformatted("???"); ImGui::PopItemWidth(); } void process() override { m_value.reset(); const auto &input = this->getFloatOnInput(0); m_value = input; } private: std::optional<float> m_value; }; class NodeDisplayBuffer : public dp::Node { public: NodeDisplayBuffer() : Node("hex.builtin.nodes.display.buffer.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.common.input") }) { } void drawNode() override { static const std::string Header = " Address 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F "; if (ImGui::BeginChild("##hex_view", ImVec2(ImGui::CalcTextSize(Header.c_str()).x, 200_scaled), true)) { ImGui::TextUnformatted(Header.c_str()); auto size = m_buffer.size(); ImGuiListClipper clipper; clipper.Begin((size + 0x0F) / 0x10); while (clipper.Step()) { for (auto y = clipper.DisplayStart; y < clipper.DisplayEnd; y++) { auto lineSize = ((size - y * 0x10) < 0x10) ? size % 0x10 : 0x10; std::string line = hex::format(" {:08X}: ", y * 0x10); for (u32 x = 0; x < 0x10; x++) { if (x < lineSize) line += hex::format("{:02X} ", m_buffer[y * 0x10 + x]); else line += " "; if (x == 7) line += " "; } line += " "; for (u32 x = 0; x < lineSize; x++) { auto c = char(m_buffer[y * 0x10 + x]); if (std::isprint(c)) line += c; else line += "."; } ImGuiExt::TextFormattedSelectable("{}", line.c_str()); } } clipper.End(); } ImGui::EndChild(); } void process() override { m_buffer = this->getBufferOnInput(0); } private: std::vector<u8> m_buffer; }; class NodeDisplayString : public dp::Node { public: NodeDisplayString() : Node("hex.builtin.nodes.display.string.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.common.input") }) { } void drawNode() override { constexpr static auto LineLength = 50; if (ImGui::BeginChild("##string_view", scaled(ImVec2(ImGui::CalcTextSize(" ").x * (LineLength + 4), 150)), true)) { std::string_view string = m_value; ImGuiListClipper clipper; clipper.Begin((string.length() + (LineLength - 1)) / LineLength); while (clipper.Step()) { for (auto i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) { auto line = string.substr(i * LineLength, LineLength); ImGui::TextUnformatted(""); ImGui::SameLine(); ImGuiExt::TextFormattedSelectable("{}", line); } } clipper.End(); } ImGui::EndChild(); } void process() override { const auto &input = this->getBufferOnInput(0); m_value = hex::encodeByteString(input); } private: std::string m_value; }; class NodeDisplayBits : public dp::Node { public: NodeDisplayBits() : Node("hex.builtin.nodes.display.bits.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.common.input") }) { } void drawNode() override { ImGui::PushItemWidth(100_scaled); ImGuiExt::TextFormattedSelectable("{}", m_display); ImGui::PopItemWidth(); } void process() override { const auto &buffer = this->getBufferOnInput(0); // Display bits in groups of 4 bits std::string display; display.reserve(buffer.size() * 9 + 2); // 8 bits + 1 space at beginning + 1 space every 4 bits for (const auto &byte : buffer) { for (size_t i = 0; i < 8; i++) { if (i % 4 == 0) { display += ' '; } display += (byte & (1 << i)) != 0 ? '1' : '0'; } } m_display = wolv::util::trim(display); } private: std::string m_display = "???"; }; void registerVisualDataProcessorNodes() { ContentRegistry::DataProcessorNode::add<NodeDisplayInteger>("hex.builtin.nodes.display", "hex.builtin.nodes.display.int"); ContentRegistry::DataProcessorNode::add<NodeDisplayFloat>("hex.builtin.nodes.display", "hex.builtin.nodes.display.float"); ContentRegistry::DataProcessorNode::add<NodeDisplayBuffer>("hex.builtin.nodes.display", "hex.builtin.nodes.display.buffer"); ContentRegistry::DataProcessorNode::add<NodeDisplayString>("hex.builtin.nodes.display", "hex.builtin.nodes.display.string"); ContentRegistry::DataProcessorNode::add<NodeDisplayBits>("hex.builtin.nodes.display", "hex.builtin.nodes.display.bits"); } }
7,412
C++
.cpp
153
34.620915
190
0.52375
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
188
other_nodes.cpp
WerWolv_ImHex/plugins/builtin/source/content/data_processor_nodes/other_nodes.cpp
#include <hex/api/imhex_api.hpp> #include <hex/api/content_registry.hpp> #include <hex/api/achievement_manager.hpp> #include <hex/api/event_manager.hpp> #include <hex/providers/provider.hpp> #include <hex/data_processor/node.hpp> #include <hex/helpers/utils.hpp> #include <wolv/utils/core.hpp> #include <content/helpers/diagrams.hpp> #include <pl/patterns/pattern.hpp> namespace hex::plugin::builtin { class NodeReadData : public dp::Node { public: NodeReadData() : Node("hex.builtin.nodes.data_access.read.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.data_access.read.address"), dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.data_access.read.size"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "hex.builtin.nodes.data_access.read.data") }) { } void process() override { const auto &address = this->getIntegerOnInput(0); const auto &size = this->getIntegerOnInput(1); std::vector<u8> data; data.resize(size); ImHexApi::Provider::get()->readRaw(address, data.data(), size); this->setBufferOnOutput(2, data); } }; class NodeWriteData : public dp::Node { public: NodeWriteData() : Node("hex.builtin.nodes.data_access.write.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.data_access.write.address"), dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.data_access.write.data") }) { } void process() override { const auto &address = this->getIntegerOnInput(0); const auto &data = this->getBufferOnInput(1); if (!data.empty()) { AchievementManager::unlockAchievement("hex.builtin.achievement.data_processor", "hex.builtin.achievement.data_processor.modify_data.name"); } this->setOverlayData(address, data); } }; class NodeDataSize : public dp::Node { public: NodeDataSize() : Node("hex.builtin.nodes.data_access.size.header", { dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.data_access.size.size") }) { } void process() override { auto size = ImHexApi::Provider::get()->getActualSize(); this->setIntegerOnOutput(0, size); } }; class NodeDataSelection : public dp::Node { public: NodeDataSelection() : Node("hex.builtin.nodes.data_access.selection.header", { dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.data_access.selection.address"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.data_access.selection.size") }) { EventRegionSelected::subscribe(this, [this](const auto &region) { m_address = region.address; m_size = region.size; }); } ~NodeDataSelection() override { EventRegionSelected::unsubscribe(this); } void process() override { this->setIntegerOnOutput(0, m_address); this->setIntegerOnOutput(1, m_size); } private: u64 m_address = 0; size_t m_size = 0; }; class NodeCastIntegerToBuffer : public dp::Node { public: NodeCastIntegerToBuffer() : Node("hex.builtin.nodes.casting.int_to_buffer.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.common.input"), dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.buffer.size"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "hex.builtin.nodes.common.output") }) { } void process() override { const auto &input = this->getIntegerOnInput(0); auto size = this->getIntegerOnInput(1); if (size == 0) { for (u32 i = 0; i < sizeof(input); i++) { if ((input >> (i * 8)) == 0) { size = i; break; } } if (size == 0) size = 1; } else if (size > sizeof(input)) { throwNodeError("Integers cannot hold more than 16 bytes"); } std::vector<u8> output(size, 0x00); std::memcpy(output.data(), &input, size); this->setBufferOnOutput(2, output); } }; class NodeCastBufferToInteger : public dp::Node { public: NodeCastBufferToInteger() : Node("hex.builtin.nodes.casting.buffer_to_int.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.common.input"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.common.output") }) { } void process() override { const auto &input = this->getBufferOnInput(0); i128 output = 0; if (input.empty() || input.size() > sizeof(output)) throwNodeError("Buffer is empty or bigger than 128 bits"); std::memcpy(&output, input.data(), input.size()); this->setIntegerOnOutput(1, output); } }; class NodeCastFloatToBuffer : public dp::Node { public: NodeCastFloatToBuffer() : Node("hex.builtin.nodes.casting.float_to_buffer.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Float, "hex.builtin.nodes.common.input"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "hex.builtin.nodes.common.output") }) { } void process() override { const auto &input = this->getFloatOnInput(0); std::vector<u8> output(sizeof(input), 0x00); std::memcpy(output.data(), &input, sizeof(input)); this->setBufferOnOutput(1, output); } }; class NodeCastBufferToFloat : public dp::Node { public: NodeCastBufferToFloat() : Node("hex.builtin.nodes.casting.buffer_to_float.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.common.input"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Float, "hex.builtin.nodes.common.output") }) { } void process() override { const auto &input = this->getBufferOnInput(0); double output = 0; if (input.empty() || input.size() != sizeof(output)) throwNodeError("Buffer is empty or not the right size to fit a float"); std::memcpy(&output, input.data(), input.size()); this->setFloatOnOutput(1, output); } }; class NodeBufferCombine : public dp::Node { public: NodeBufferCombine() : Node("hex.builtin.nodes.buffer.combine.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.common.input.a"), dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.common.input.b"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "hex.builtin.nodes.common.output") }) { } void process() override { const auto &inputA = this->getBufferOnInput(0); const auto &inputB = this->getBufferOnInput(1); auto output = inputA; std::copy(inputB.begin(), inputB.end(), std::back_inserter(output)); this->setBufferOnOutput(2, output); } }; class NodeBufferSlice : public dp::Node { public: NodeBufferSlice() : Node("hex.builtin.nodes.buffer.slice.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.buffer.slice.input.buffer"), dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.buffer.slice.input.from"), dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.buffer.slice.input.to"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "hex.builtin.nodes.common.output") }) { } void process() override { const auto &input = this->getBufferOnInput(0); const auto &from = this->getIntegerOnInput(1); const auto &to = this->getIntegerOnInput(2); if (from < 0 || static_cast<u128>(from) >= input.size()) throwNodeError("'from' input out of range"); if (to < 0 || static_cast<u128>(to) >= input.size()) throwNodeError("'to' input out of range"); if (to <= from) throwNodeError("'to' input needs to be greater than 'from' input"); this->setBufferOnOutput(3, std::vector(input.begin() + u64(from), input.begin() + u64(to))); } }; class NodeBufferRepeat : public dp::Node { public: NodeBufferRepeat() : Node("hex.builtin.nodes.buffer.repeat.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.buffer.repeat.input.buffer"), dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.buffer.repeat.input.count"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "hex.builtin.nodes.common.output") }) { } void process() override { const auto &buffer = this->getBufferOnInput(0); const auto &count = this->getIntegerOnInput(1); std::vector<u8> output; output.resize(buffer.size() * count); for (u32 i = 0; i < count; i++) std::copy(buffer.begin(), buffer.end(), output.begin() + buffer.size() * i); this->setBufferOnOutput(2, output); } }; class NodeBufferPatch : public dp::Node { public: NodeBufferPatch() : Node("hex.builtin.nodes.buffer.patch.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.common.input"), dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.buffer.patch.input.patch"), dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.ui.common.address"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "hex.builtin.nodes.common.output") }) { } void process() override { auto buffer = this->getBufferOnInput(0); const auto &patch = this->getBufferOnInput(1); const auto &address = this->getIntegerOnInput(2); if (address < 0 || static_cast<u128>(address) >= buffer.size()) throwNodeError("Address out of range"); if (address + patch.size() > buffer.size()) buffer.resize(address + patch.size()); std::copy(patch.begin(), patch.end(), buffer.begin() + address); this->setBufferOnOutput(3, buffer); } }; class NodeBufferSize : public dp::Node { public: NodeBufferSize() : Node("hex.builtin.nodes.buffer.size.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.common.input"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.buffer.size.output") }) { } void process() override { const auto &buffer = this->getBufferOnInput(0); this->setIntegerOnOutput(1, buffer.size()); } }; class NodeVisualizerDigram : public dp::Node { public: NodeVisualizerDigram() : Node("hex.builtin.nodes.visualizer.digram.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.common.input") }) { } void drawNode() override { m_digram.draw(scaled({ 200, 200 })); if (ImGui::IsItemHovered() && ImGui::IsKeyDown(ImGuiKey_LeftShift)) { ImGui::BeginTooltip(); m_digram.draw(scaled({ 600, 600 })); ImGui::EndTooltip(); } } void process() override { m_digram.process(this->getBufferOnInput(0)); } private: DiagramDigram m_digram; }; class NodeVisualizerLayeredDistribution : public dp::Node { public: NodeVisualizerLayeredDistribution() : Node("hex.builtin.nodes.visualizer.layered_dist.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.common.input") }) { } void drawNode() override { m_layeredDistribution.draw(scaled({ 200, 200 })); if (ImGui::IsItemHovered() && ImGui::IsKeyDown(ImGuiKey_LeftShift)) { ImGui::BeginTooltip(); m_layeredDistribution.draw(scaled({ 600, 600 })); ImGui::EndTooltip(); } } void process() override { m_layeredDistribution.process(this->getBufferOnInput(0)); } private: DiagramLayeredDistribution m_layeredDistribution; }; class NodeVisualizerImage : public dp::Node { public: NodeVisualizerImage() : Node("hex.builtin.nodes.visualizer.image.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.common.input") }) { } void drawNode() override { ImGui::Image(m_texture, scaled(ImVec2(m_texture.getAspectRatio() * 200, 200))); if (ImGui::IsItemHovered() && ImGui::IsKeyDown(ImGuiKey_LeftShift)) { ImGui::BeginTooltip(); ImGui::Image(m_texture, scaled(ImVec2(m_texture.getAspectRatio() * 600, 600))); ImGui::EndTooltip(); } } void process() override { const auto &rawData = this->getBufferOnInput(0); m_texture = ImGuiExt::Texture::fromImage(rawData.data(), rawData.size(), ImGuiExt::Texture::Filter::Nearest); } private: ImGuiExt::Texture m_texture; }; class NodeVisualizerImageRGBA : public dp::Node { public: NodeVisualizerImageRGBA() : Node("hex.builtin.nodes.visualizer.image_rgba.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.common.input"), dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.common.width"), dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.common.height") }) { } void drawNode() override { ImGui::Image(m_texture, scaled(ImVec2(m_texture.getAspectRatio() * 200, 200))); if (ImGui::IsItemHovered() && ImGui::IsKeyDown(ImGuiKey_LeftShift)) { ImGui::BeginTooltip(); ImGui::Image(m_texture, scaled(ImVec2(m_texture.getAspectRatio() * 600, 600))); ImGui::EndTooltip(); } } void process() override { m_texture = { }; const auto &rawData = this->getBufferOnInput(0); const auto &width = this->getIntegerOnInput(1); const auto &height = this->getIntegerOnInput(2); const size_t requiredBytes = width * height * 4; if (requiredBytes > rawData.size()) throwNodeError(hex::format("Image requires at least {} bytes of data, but only {} bytes are available", requiredBytes, rawData.size())); m_texture = ImGuiExt::Texture::fromBitmap(rawData.data(), rawData.size(), width, height, ImGuiExt::Texture::Filter::Nearest); } private: ImGuiExt::Texture m_texture; }; class NodeVisualizerByteDistribution : public dp::Node { public: NodeVisualizerByteDistribution() : Node("hex.builtin.nodes.visualizer.byte_distribution.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.common.input") }) { } void drawNode() override { drawPlot(scaled({ 400, 300 })); if (ImGui::IsItemHovered() && ImGui::IsKeyDown(ImGuiKey_LeftShift)) { ImGui::BeginTooltip(); drawPlot(scaled({ 700, 550 })); ImGui::EndTooltip(); } } void drawPlot(const ImVec2 &viewSize) { if (ImPlot::BeginPlot("##distribution", viewSize, ImPlotFlags_NoLegend | ImPlotFlags_NoMenus | ImPlotFlags_NoBoxSelect)) { ImPlot::SetupAxes("Address", "Count", ImPlotAxisFlags_Lock, ImPlotAxisFlags_Lock); ImPlot::SetupAxisScale(ImAxis_Y1, ImPlotScale_Log10); ImPlot::SetupAxesLimits(0, 256, 1, double(*std::max_element(m_counts.begin(), m_counts.end())) * 1.1F, ImGuiCond_Always); static auto x = [] { std::array<ImU64, 256> result { 0 }; std::iota(result.begin(), result.end(), 0); return result; }(); ImPlot::PlotBars<ImU64>("##bytes", x.data(), m_counts.data(), x.size(), 1); ImPlot::EndPlot(); } } void process() override { const auto &buffer = this->getBufferOnInput(0); m_counts.fill(0x00); for (const auto &byte : buffer) { m_counts[byte]++; } } private: std::array<ImU64, 256> m_counts = { 0 }; }; class NodePatternLanguageOutVariable : public dp::Node { public: NodePatternLanguageOutVariable() : Node("hex.builtin.nodes.pattern_language.out_var.header", { dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "hex.builtin.nodes.common.output") }) { } void drawNode() override { ImGui::PushItemWidth(100_scaled); ImGui::InputText("##name", m_name); ImGui::PopItemWidth(); } void process() override { auto lock = std::scoped_lock(ContentRegistry::PatternLanguage::getRuntimeLock()); auto &runtime = ContentRegistry::PatternLanguage::getRuntime(); const auto &outVars = runtime.getOutVariables(); if (outVars.contains(m_name)) { std::visit(wolv::util::overloaded { [](const std::string &) {}, [](const std::shared_ptr<pl::ptrn::Pattern> &) {}, [this](auto &&value) { std::vector<u8> buffer(std::min<size_t>(sizeof(value), 8)); std::memcpy(buffer.data(), &value, buffer.size()); this->setBufferOnOutput(0, buffer); } }, outVars.at(m_name)); } else { throwNodeError(hex::format("Out variable '{}' has not been defined!", m_name)); } } void store(nlohmann::json &j) const override { j = nlohmann::json::object(); j["name"] = m_name; } void load(const nlohmann::json &j) override { m_name = j["name"].get<std::string>(); } private: std::string m_name; }; class NodeBufferByteSwap : public dp::Node { public: NodeBufferByteSwap() : Node("hex.builtin.nodes.buffer.byte_swap.header", {dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.common.input"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "hex.builtin.nodes.common.output") }) { } void process() override { auto data = this->getBufferOnInput(0); std::reverse(data.begin(), data.end()); this->setBufferOnOutput(1, data); } }; void registerOtherDataProcessorNodes() { ContentRegistry::DataProcessorNode::add<NodeReadData>("hex.builtin.nodes.data_access", "hex.builtin.nodes.data_access.read"); ContentRegistry::DataProcessorNode::add<NodeWriteData>("hex.builtin.nodes.data_access", "hex.builtin.nodes.data_access.write"); ContentRegistry::DataProcessorNode::add<NodeDataSize>("hex.builtin.nodes.data_access", "hex.builtin.nodes.data_access.size"); ContentRegistry::DataProcessorNode::add<NodeDataSelection>("hex.builtin.nodes.data_access", "hex.builtin.nodes.data_access.selection"); ContentRegistry::DataProcessorNode::add<NodeCastIntegerToBuffer>("hex.builtin.nodes.casting", "hex.builtin.nodes.casting.int_to_buffer"); ContentRegistry::DataProcessorNode::add<NodeCastBufferToInteger>("hex.builtin.nodes.casting", "hex.builtin.nodes.casting.buffer_to_int"); ContentRegistry::DataProcessorNode::add<NodeCastFloatToBuffer>("hex.builtin.nodes.casting", "hex.builtin.nodes.casting.float_to_buffer"); ContentRegistry::DataProcessorNode::add<NodeCastBufferToFloat>("hex.builtin.nodes.casting", "hex.builtin.nodes.casting.buffer_to_float"); ContentRegistry::DataProcessorNode::add<NodeBufferCombine>("hex.builtin.nodes.buffer", "hex.builtin.nodes.buffer.combine"); ContentRegistry::DataProcessorNode::add<NodeBufferSlice>("hex.builtin.nodes.buffer", "hex.builtin.nodes.buffer.slice"); ContentRegistry::DataProcessorNode::add<NodeBufferRepeat>("hex.builtin.nodes.buffer", "hex.builtin.nodes.buffer.repeat"); ContentRegistry::DataProcessorNode::add<NodeBufferPatch>("hex.builtin.nodes.buffer", "hex.builtin.nodes.buffer.patch"); ContentRegistry::DataProcessorNode::add<NodeBufferSize>("hex.builtin.nodes.buffer", "hex.builtin.nodes.buffer.size"); ContentRegistry::DataProcessorNode::add<NodeBufferByteSwap>("hex.builtin.nodes.buffer", "hex.builtin.nodes.buffer.byte_swap"); ContentRegistry::DataProcessorNode::add<NodeVisualizerDigram>("hex.builtin.nodes.visualizer", "hex.builtin.nodes.visualizer.digram"); ContentRegistry::DataProcessorNode::add<NodeVisualizerLayeredDistribution>("hex.builtin.nodes.visualizer", "hex.builtin.nodes.visualizer.layered_dist"); ContentRegistry::DataProcessorNode::add<NodeVisualizerImage>("hex.builtin.nodes.visualizer", "hex.builtin.nodes.visualizer.image"); ContentRegistry::DataProcessorNode::add<NodeVisualizerImageRGBA>("hex.builtin.nodes.visualizer", "hex.builtin.nodes.visualizer.image_rgba"); ContentRegistry::DataProcessorNode::add<NodeVisualizerByteDistribution>("hex.builtin.nodes.visualizer", "hex.builtin.nodes.visualizer.byte_distribution"); ContentRegistry::DataProcessorNode::add<NodePatternLanguageOutVariable>("hex.builtin.nodes.pattern_language", "hex.builtin.nodes.pattern_language.out_var"); } }
22,662
C++
.cpp
361
51.742382
538
0.630594
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
189
basic_nodes.cpp
WerWolv_ImHex/plugins/builtin/source/content/data_processor_nodes/basic_nodes.cpp
#include <hex/api/content_registry.hpp> #include <hex/api/localization_manager.hpp> #include <hex/helpers/utils.hpp> #include <hex/ui/imgui_imhex_extensions.h> #include <hex/data_processor/node.hpp> #include <wolv/utils/core.hpp> #include <nlohmann/json.hpp> #include <imgui.h> #include <fonts/codicons_font.h> #include <wolv/math_eval/math_evaluator.hpp> namespace hex::plugin::builtin { class NodeNullptr : public dp::Node { public: NodeNullptr() : Node("hex.builtin.nodes.constants.nullptr.header", { dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "") }) { } void process() override { this->setBufferOnOutput(0, {}); } }; class NodeBuffer : public dp::Node { public: NodeBuffer() : Node("hex.builtin.nodes.constants.buffer.header", { dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "") }) { } void drawNode() override { constexpr static int StepSize = 1, FastStepSize = 10; ImGui::PushItemWidth(100_scaled); ImGui::InputScalar("hex.builtin.nodes.constants.buffer.size"_lang, ImGuiDataType_U32, &m_size, &StepSize, &FastStepSize); ImGui::PopItemWidth(); } void process() override { if (m_buffer.size() != m_size) m_buffer.resize(m_size, 0x00); this->setBufferOnOutput(0, m_buffer); } void store(nlohmann::json &j) const override { j = nlohmann::json::object(); j["size"] = m_size; j["data"] = m_buffer; } void load(const nlohmann::json &j) override { m_size = j.at("size"); m_buffer = j.at("data").get<std::vector<u8>>(); } private: u32 m_size = 1; std::vector<u8> m_buffer; }; class NodeString : public dp::Node { public: NodeString() : Node("hex.builtin.nodes.constants.string.header", { dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "") }) { } void drawNode() override { ImGui::InputTextMultiline("##string", m_value, ImVec2(150_scaled, 0), ImGuiInputTextFlags_AllowTabInput); } void process() override { this->setBufferOnOutput(0, hex::decodeByteString(m_value)); } void store(nlohmann::json &j) const override { j = nlohmann::json::object(); j["data"] = m_value; } void load(const nlohmann::json &j) override { m_value = j.at("data").get<std::string>(); } private: std::string m_value; }; class NodeInteger : public dp::Node { public: NodeInteger() : Node("hex.builtin.nodes.constants.int.header", { dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "") }) { } void drawNode() override { ImGui::PushItemWidth(100_scaled); ImGuiExt::InputTextIcon("##integer_value", ICON_VS_SYMBOL_OPERATOR, m_input, ImGuiInputTextFlags_AutoSelectAll); ImGui::PopItemWidth(); } void process() override { wolv::math_eval::MathEvaluator<i128> evaluator; if (auto result = evaluator.evaluate(m_input); result.has_value()) this->setIntegerOnOutput(0, *result); else throwNodeError(evaluator.getLastError().value_or("Unknown math evaluator error")); } void store(nlohmann::json &j) const override { j = nlohmann::json::object(); j["input"] = m_input; } void load(const nlohmann::json &j) override { if (j.contains("input")) m_input = j.at("input"); else if (j.contains("data")) m_input = std::to_string(j.at("data").get<i64>()); } private: std::string m_input = "0x00"; }; class NodeFloat : public dp::Node { public: NodeFloat() : Node("hex.builtin.nodes.constants.float.header", { dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Float, "") }) { } void drawNode() override { ImGui::PushItemWidth(100_scaled); ImGui::InputScalar("##floatValue", ImGuiDataType_Float, &m_value, nullptr, nullptr, "%f", ImGuiInputTextFlags_CharsDecimal); ImGui::PopItemWidth(); } void process() override { this->setFloatOnOutput(0, m_value); } void store(nlohmann::json &j) const override { j = nlohmann::json::object(); j["data"] = m_value; } void load(const nlohmann::json &j) override { m_value = j.at("data"); } private: float m_value = 0; }; class NodeRGBA8 : public dp::Node { public: NodeRGBA8() : Node("hex.builtin.nodes.constants.rgba8.header", { dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.constants.rgba8.output.r"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.constants.rgba8.output.g"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.constants.rgba8.output.b"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.constants.rgba8.output.a"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "hex.builtin.nodes.constants.rgba8.output.color"), }) { } void drawNode() override { ImGui::PushItemWidth(200_scaled); ImGui::ColorPicker4("##colorPicker", &m_color.Value.x, ImGuiColorEditFlags_AlphaBar); ImGui::PopItemWidth(); } void process() override { this->setIntegerOnOutput(0, u8(m_color.Value.x * 0xFF)); this->setIntegerOnOutput(1, u8(m_color.Value.y * 0xFF)); this->setIntegerOnOutput(2, u8(m_color.Value.z * 0xFF)); this->setIntegerOnOutput(3, u8(m_color.Value.w * 0xFF)); std::array buffer = { u8(m_color.Value.x * 0xFF), u8(m_color.Value.y * 0xFF), u8(m_color.Value.z * 0xFF), u8(m_color.Value.w * 0xFF) }; this->setBufferOnOutput(4, buffer); } void store(nlohmann::json &j) const override { j = nlohmann::json::object(); j["data"] = nlohmann::json::object(); j["data"]["r"] = m_color.Value.x; j["data"]["g"] = m_color.Value.y; j["data"]["b"] = m_color.Value.z; j["data"]["a"] = m_color.Value.w; } void load(const nlohmann::json &j) override { const auto &color = j.at("data"); m_color = ImVec4(color.at("r"), color.at("g"), color.at("b"), color.at("a")); } private: ImColor m_color; }; class NodeComment : public dp::Node { public: NodeComment() : Node("hex.builtin.nodes.constants.comment.header", {}) { } void drawNode() override { ImGui::InputTextMultiline("##string", m_comment, scaled(ImVec2(150, 100))); } void process() override { } void store(nlohmann::json &j) const override { j = nlohmann::json::object(); j["comment"] = m_comment; } void load(const nlohmann::json &j) override { m_comment = j["comment"].get<std::string>(); } private: std::string m_comment; }; void registerBasicDataProcessorNodes() { ContentRegistry::DataProcessorNode::add<NodeInteger>("hex.builtin.nodes.constants", "hex.builtin.nodes.constants.int"); ContentRegistry::DataProcessorNode::add<NodeFloat>("hex.builtin.nodes.constants", "hex.builtin.nodes.constants.float"); ContentRegistry::DataProcessorNode::add<NodeNullptr>("hex.builtin.nodes.constants", "hex.builtin.nodes.constants.nullptr"); ContentRegistry::DataProcessorNode::add<NodeBuffer>("hex.builtin.nodes.constants", "hex.builtin.nodes.constants.buffer"); ContentRegistry::DataProcessorNode::add<NodeString>("hex.builtin.nodes.constants", "hex.builtin.nodes.constants.string"); ContentRegistry::DataProcessorNode::add<NodeRGBA8>("hex.builtin.nodes.constants", "hex.builtin.nodes.constants.rgba8"); ContentRegistry::DataProcessorNode::add<NodeComment>("hex.builtin.nodes.constants", "hex.builtin.nodes.constants.comment"); } }
8,741
C++
.cpp
186
36.456989
158
0.586893
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
190
math_nodes.cpp
WerWolv_ImHex/plugins/builtin/source/content/data_processor_nodes/math_nodes.cpp
#include <hex/api/content_registry.hpp> #include <hex/data_processor/node.hpp> #include <numeric> #include <algorithm> #include <cmath> namespace hex::plugin::builtin { class NodeArithmeticAdd : public dp::Node { public: NodeArithmeticAdd() : Node("hex.builtin.nodes.arithmetic.add.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.common.input.a"), dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.common.input.b"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.common.output") }) { } void process() override { const auto &inputA = this->getIntegerOnInput(0); const auto &inputB = this->getIntegerOnInput(1); auto output = inputA + inputB; this->setIntegerOnOutput(2, output); } }; class NodeArithmeticSubtract : public dp::Node { public: NodeArithmeticSubtract() : Node("hex.builtin.nodes.arithmetic.sub.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.common.input.a"), dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.common.input.b"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.common.output") }) { } void process() override { const auto &inputA = this->getIntegerOnInput(0); const auto &inputB = this->getIntegerOnInput(1); auto output = inputA - inputB; this->setIntegerOnOutput(2, output); } }; class NodeArithmeticMultiply : public dp::Node { public: NodeArithmeticMultiply() : Node("hex.builtin.nodes.arithmetic.mul.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.common.input.a"), dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.common.input.b"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.common.output") }) { } void process() override { const auto &inputA = this->getIntegerOnInput(0); const auto &inputB = this->getIntegerOnInput(1); auto output = inputA * inputB; this->setIntegerOnOutput(2, output); } }; class NodeArithmeticDivide : public dp::Node { public: NodeArithmeticDivide() : Node("hex.builtin.nodes.arithmetic.div.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.common.input.a"), dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.common.input.b"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.common.output") }) { } void process() override { const auto &inputA = this->getIntegerOnInput(0); const auto &inputB = this->getIntegerOnInput(1); if (inputB == 0) throwNodeError("Division by zero"); auto output = inputA / inputB; this->setIntegerOnOutput(2, output); } }; class NodeArithmeticModulus : public dp::Node { public: NodeArithmeticModulus() : Node("hex.builtin.nodes.arithmetic.mod.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.common.input.a"), dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.common.input.b"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.common.output") }) { } void process() override { const auto &inputA = this->getIntegerOnInput(0); const auto &inputB = this->getIntegerOnInput(1); if (inputB == 0) throwNodeError("Division by zero"); auto output = inputA % inputB; this->setIntegerOnOutput(2, output); } }; class NodeArithmeticAverage : public dp::Node { public: NodeArithmeticAverage() : Node("hex.builtin.nodes.arithmetic.average.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.common.input"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Float, "hex.builtin.nodes.common.output") }) { } void process() override { const auto &input = this->getBufferOnInput(0); double output = std::reduce(input.begin(), input.end(), double(0)) / double(input.size()); this->setFloatOnOutput(1, output); } }; class NodeArithmeticMedian : public dp::Node { public: NodeArithmeticMedian() : Node("hex.builtin.nodes.arithmetic.median.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.common.input"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Float, "hex.builtin.nodes.common.output") }) { } void process() override { auto input = this->getBufferOnInput(0); u64 medianIndex = input.size() / 2; std::nth_element(input.begin(), input.begin() + medianIndex, input.end()); i128 median = 0; if (input.size() % 2 == 0) { std::nth_element(input.begin(), input.begin() + medianIndex - 1, input.end()); median = (input[medianIndex] + input[medianIndex - 1]) / 2; } else { median = input[medianIndex]; } this->setFloatOnOutput(1, median); } }; class NodeArithmeticCeil : public dp::Node { public: NodeArithmeticCeil() : Node("hex.builtin.nodes.arithmetic.ceil.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Float, "hex.builtin.nodes.common.input"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Float, "hex.builtin.nodes.common.output") }) { } void process() override { const auto &input = this->getFloatOnInput(0); this->setFloatOnOutput(1, std::ceil(input)); } }; class NodeArithmeticFloor : public dp::Node { public: NodeArithmeticFloor() : Node("hex.builtin.nodes.arithmetic.floor.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Float, "hex.builtin.nodes.common.input"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Float, "hex.builtin.nodes.common.output") }) { } void process() override { const auto &input = this->getFloatOnInput(0); this->setFloatOnOutput(1, std::floor(input)); } }; class NodeArithmeticRound : public dp::Node { public: NodeArithmeticRound() : Node("hex.builtin.nodes.arithmetic.round.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Float, "hex.builtin.nodes.common.input"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Float, "hex.builtin.nodes.common.output") }) { } void process() override { const auto &input = this->getFloatOnInput(0); this->setFloatOnOutput(1, std::round(input)); } }; void registerMathDataProcessorNodes() { ContentRegistry::DataProcessorNode::add<NodeArithmeticAdd>("hex.builtin.nodes.arithmetic", "hex.builtin.nodes.arithmetic.add"); ContentRegistry::DataProcessorNode::add<NodeArithmeticSubtract>("hex.builtin.nodes.arithmetic", "hex.builtin.nodes.arithmetic.sub"); ContentRegistry::DataProcessorNode::add<NodeArithmeticMultiply>("hex.builtin.nodes.arithmetic", "hex.builtin.nodes.arithmetic.mul"); ContentRegistry::DataProcessorNode::add<NodeArithmeticDivide>("hex.builtin.nodes.arithmetic", "hex.builtin.nodes.arithmetic.div"); ContentRegistry::DataProcessorNode::add<NodeArithmeticModulus>("hex.builtin.nodes.arithmetic", "hex.builtin.nodes.arithmetic.mod"); ContentRegistry::DataProcessorNode::add<NodeArithmeticAverage>("hex.builtin.nodes.arithmetic", "hex.builtin.nodes.arithmetic.average"); ContentRegistry::DataProcessorNode::add<NodeArithmeticMedian>("hex.builtin.nodes.arithmetic", "hex.builtin.nodes.arithmetic.median"); ContentRegistry::DataProcessorNode::add<NodeArithmeticCeil>("hex.builtin.nodes.arithmetic", "hex.builtin.nodes.arithmetic.ceil"); ContentRegistry::DataProcessorNode::add<NodeArithmeticFloor>("hex.builtin.nodes.arithmetic", "hex.builtin.nodes.arithmetic.floor"); ContentRegistry::DataProcessorNode::add<NodeArithmeticRound>("hex.builtin.nodes.arithmetic", "hex.builtin.nodes.arithmetic.round"); } }
8,728
C++
.cpp
123
61.447154
414
0.669394
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
191
control_nodes.cpp
WerWolv_ImHex/plugins/builtin/source/content/data_processor_nodes/control_nodes.cpp
#include <hex/api/content_registry.hpp> #include <hex/data_processor/node.hpp> namespace hex::plugin::builtin { class NodeIf : public dp::Node { public: NodeIf() : Node("hex.builtin.nodes.control_flow.if.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.if.condition"), dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.control_flow.if.true"), dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.control_flow.if.false"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "hex.builtin.nodes.common.output") }) { } void process() override { const auto &cond = this->getIntegerOnInput(0); const auto &trueData = this->getBufferOnInput(1); const auto &falseData = this->getBufferOnInput(2); if (cond != 0) this->setBufferOnOutput(3, trueData); else this->setBufferOnOutput(3, falseData); } }; class NodeEquals : public dp::Node { public: NodeEquals() : Node("hex.builtin.nodes.control_flow.equals.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.common.input.a"), dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.common.input.b"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.common.output") }) { } void process() override { const auto &inputA = this->getIntegerOnInput(0); const auto &inputB = this->getIntegerOnInput(1); this->setIntegerOnOutput(2, inputA == inputB); } }; class NodeNot : public dp::Node { public: NodeNot() : Node("hex.builtin.nodes.control_flow.not.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.common.input"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.common.output") }) { } void process() override { const auto &input = this->getIntegerOnInput(0); this->setIntegerOnOutput(1, !input); } }; class NodeGreaterThan : public dp::Node { public: NodeGreaterThan() : Node("hex.builtin.nodes.control_flow.gt.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.common.input.a"), dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.common.input.b"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.common.output") }) { } void process() override { const auto &inputA = this->getIntegerOnInput(0); const auto &inputB = this->getIntegerOnInput(1); this->setIntegerOnOutput(2, inputA > inputB); } }; class NodeLessThan : public dp::Node { public: NodeLessThan() : Node("hex.builtin.nodes.control_flow.lt.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.common.input.a"), dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.common.input.b"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.common.output") }) { } void process() override { const auto &inputA = this->getIntegerOnInput(0); const auto &inputB = this->getIntegerOnInput(1); this->setIntegerOnOutput(2, inputA < inputB); } }; class NodeBoolAND : public dp::Node { public: NodeBoolAND() : Node("hex.builtin.nodes.control_flow.and.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.common.input.a"), dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.common.input.b"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.common.output") }) { } void process() override { const auto &inputA = this->getIntegerOnInput(0); const auto &inputB = this->getIntegerOnInput(1); this->setIntegerOnOutput(2, inputA && inputB); } }; class NodeBoolOR : public dp::Node { public: NodeBoolOR() : Node("hex.builtin.nodes.control_flow.or.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.common.input.a"), dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.common.input.b"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.common.output") }) { } void process() override { const auto &inputA = this->getIntegerOnInput(0); const auto &inputB = this->getIntegerOnInput(1); this->setIntegerOnOutput(2, inputA || inputB); } }; class NodeLoop : public dp::Node { public: NodeLoop() : Node("hex.builtin.nodes.control_flow.loop.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.loop.start"), dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.loop.end"), dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.loop.init"), dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.loop.in"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Integer, "hex.builtin.nodes.control_flow.loop.out") }) {} void process() override { if (!m_started) { m_started = true; auto start = this->getIntegerOnInput(0); auto end = this->getIntegerOnInput(1); m_value = this->getIntegerOnInput(2); for (auto value = start; value < end; value += 1) { this->resetProcessedInputs(); m_value = this->getIntegerOnInput(3); } m_started = false; } this->setIntegerOnOutput(4, m_value); } void reset() override { m_started = false; } private: bool m_started = false; i128 m_value = 0; }; void registerControlDataProcessorNodes() { ContentRegistry::DataProcessorNode::add<NodeIf>("hex.builtin.nodes.control_flow", "hex.builtin.nodes.control_flow.if"); ContentRegistry::DataProcessorNode::add<NodeEquals>("hex.builtin.nodes.control_flow", "hex.builtin.nodes.control_flow.equals"); ContentRegistry::DataProcessorNode::add<NodeNot>("hex.builtin.nodes.control_flow", "hex.builtin.nodes.control_flow.not"); ContentRegistry::DataProcessorNode::add<NodeGreaterThan>("hex.builtin.nodes.control_flow", "hex.builtin.nodes.control_flow.gt"); ContentRegistry::DataProcessorNode::add<NodeLessThan>("hex.builtin.nodes.control_flow", "hex.builtin.nodes.control_flow.lt"); ContentRegistry::DataProcessorNode::add<NodeBoolAND>("hex.builtin.nodes.control_flow", "hex.builtin.nodes.control_flow.and"); ContentRegistry::DataProcessorNode::add<NodeBoolOR>("hex.builtin.nodes.control_flow", "hex.builtin.nodes.control_flow.or"); ContentRegistry::DataProcessorNode::add<NodeLoop>("hex.builtin.nodes.control_flow", "hex.builtin.nodes.control_flow.loop"); } }
8,485
C++
.cpp
130
50.569231
167
0.592504
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
192
decode_nodes.cpp
WerWolv_ImHex/plugins/builtin/source/content/data_processor_nodes/decode_nodes.cpp
#include <hex/api/content_registry.hpp> #include <hex/api/localization_manager.hpp> #include <hex/helpers/utils.hpp> #include <hex/helpers/crypto.hpp> #include <hex/data_processor/node.hpp> #include <nlohmann/json.hpp> namespace hex::plugin::builtin { class NodeCryptoAESDecrypt : public dp::Node { public: NodeCryptoAESDecrypt() : Node("hex.builtin.nodes.crypto.aes.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.crypto.aes.key"), dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.crypto.aes.iv"), dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.crypto.aes.nonce"), dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.common.input"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "hex.builtin.nodes.common.output") }) { } void drawNode() override { ImGui::PushItemWidth(100_scaled); ImGui::Combo("hex.builtin.nodes.crypto.aes.mode"_lang, &m_mode, "ECB\0CBC\0CFB128\0CTR\0GCM\0CCM\0OFB\0"); ImGui::Combo("hex.builtin.nodes.crypto.aes.key_length"_lang, &m_keyLength, "128 Bits\000192 Bits\000256 Bits\000"); ImGui::PopItemWidth(); } void process() override { const auto &key = this->getBufferOnInput(0); const auto &iv = this->getBufferOnInput(1); const auto &nonce = this->getBufferOnInput(2); const auto &input = this->getBufferOnInput(3); if (key.empty()) throwNodeError("Key cannot be empty"); if (input.empty()) throwNodeError("Input cannot be empty"); std::array<u8, 8> ivData = { 0 }, nonceData = { 0 }; std::copy(iv.begin(), iv.end(), ivData.begin()); std::copy(nonce.begin(), nonce.end(), nonceData.begin()); auto output = crypt::aesDecrypt(static_cast<crypt::AESMode>(m_mode), static_cast<crypt::KeyLength>(m_keyLength), key, nonceData, ivData, input); this->setBufferOnOutput(4, output); } void store(nlohmann::json &j) const override { j = nlohmann::json::object(); j["data"] = nlohmann::json::object(); j["data"]["mode"] = m_mode; j["data"]["key_length"] = m_keyLength; } void load(const nlohmann::json &j) override { m_mode = j["data"]["mode"]; m_keyLength = j["data"]["key_length"]; } private: int m_mode = 0; int m_keyLength = 0; }; class NodeDecodingBase64 : public dp::Node { public: NodeDecodingBase64() : Node("hex.builtin.nodes.decoding.base64.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.common.input"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "hex.builtin.nodes.common.output") }) { } void process() override { const auto &input = this->getBufferOnInput(0); auto output = crypt::decode64(input); this->setBufferOnOutput(1, output); } }; class NodeDecodingHex : public dp::Node { public: NodeDecodingHex() : Node("hex.builtin.nodes.decoding.hex.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.common.input"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "hex.builtin.nodes.common.output") }) { } void process() override { auto input = this->getBufferOnInput(0); std::erase_if(input, [](u8 c) { return std::isspace(c); }); if (input.size() % 2 != 0) throwNodeError("Can't decode odd number of hex characters"); std::vector<u8> output; for (u32 i = 0; i < input.size(); i += 2) { char c1 = static_cast<char>(std::tolower(input[i])); char c2 = static_cast<char>(std::tolower(input[i + 1])); if (!std::isxdigit(c1) || !isxdigit(c2)) throwNodeError("Can't decode non-hexadecimal character"); u8 value; if (std::isdigit(c1)) value = (c1 - '0') << 4; else value = ((c1 - 'a') + 0x0A) << 4; if (std::isdigit(c2)) value |= c2 - '0'; else value |= (c2 - 'a') + 0x0A; output.push_back(value); } this->setBufferOnOutput(1, output); } }; void registerDecodeDataProcessorNodes() { ContentRegistry::DataProcessorNode::add<NodeDecodingBase64>("hex.builtin.nodes.decoding", "hex.builtin.nodes.decoding.base64"); ContentRegistry::DataProcessorNode::add<NodeDecodingHex>("hex.builtin.nodes.decoding", "hex.builtin.nodes.decoding.hex"); ContentRegistry::DataProcessorNode::add<NodeCryptoAESDecrypt>("hex.builtin.nodes.crypto", "hex.builtin.nodes.crypto.aes"); } }
5,363
C++
.cpp
93
44.795699
299
0.574155
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
193
logic_nodes.cpp
WerWolv_ImHex/plugins/builtin/source/content/data_processor_nodes/logic_nodes.cpp
#include <hex/api/content_registry.hpp> #include <hex/data_processor/node.hpp> #include <ranges> namespace hex::plugin::builtin { class NodeBitwiseNOT : public dp::Node { public: NodeBitwiseNOT() : Node("hex.builtin.nodes.bitwise.not.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.common.input"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "hex.builtin.nodes.common.output") }) { } void process() override { const auto &input = this->getBufferOnInput(0); std::vector<u8> output = input; for (auto &byte : output) byte = ~byte; this->setBufferOnOutput(1, output); } }; class NodeBitwiseShiftLeft : public dp::Node { public: NodeBitwiseShiftLeft() : Node("hex.builtin.nodes.bitwise.shift_left.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.common.input"), dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.common.amount"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "hex.builtin.nodes.common.output") }) { } void process() override { const auto &input = this->getBufferOnInput(0); const auto &amount = this->getIntegerOnInput(1); std::vector<u8> output = input; for (u32 i = 0; i < amount; i += 1) { u8 prevByte = 0x00; for (auto &byte : output) { auto startValue = byte; byte <<= 1; byte |= (prevByte & 0x80) >> 7; prevByte = startValue; } } this->setBufferOnOutput(2, output); } }; class NodeBitwiseShiftRight : public dp::Node { public: NodeBitwiseShiftRight() : Node("hex.builtin.nodes.bitwise.shift_right.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.common.input"), dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Integer, "hex.builtin.nodes.common.amount"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "hex.builtin.nodes.common.output") }) { } void process() override { const auto &input = this->getBufferOnInput(0); const auto &amount = this->getIntegerOnInput(1); std::vector<u8> output = input; for (u32 i = 0; i < amount; i += 1) { u8 prevByte = 0x00; for (auto &byte : output | std::views::reverse) { auto startValue = byte; byte >>= 1; byte |= (prevByte & 0x01) << 7; prevByte = startValue; } } this->setBufferOnOutput(2, output); } }; class NodeBitwiseADD : public dp::Node { public: NodeBitwiseADD() : Node("hex.builtin.nodes.bitwise.add.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.common.input.a"), dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.common.input.b"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "hex.builtin.nodes.common.output") }) { } void process() override { const auto &inputA = this->getBufferOnInput(0); const auto &inputB = this->getBufferOnInput(1); std::vector<u8> output(std::min(inputA.size(), inputB.size()), 0x00); for (u32 i = 0; i < output.size(); i++) output[i] = inputA[i] + inputB[i]; this->setBufferOnOutput(2, output); } }; class NodeBitwiseAND : public dp::Node { public: NodeBitwiseAND() : Node("hex.builtin.nodes.bitwise.and.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.common.input.a"), dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.common.input.b"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "hex.builtin.nodes.common.output") }) { } void process() override { const auto &inputA = this->getBufferOnInput(0); const auto &inputB = this->getBufferOnInput(1); std::vector<u8> output(std::min(inputA.size(), inputB.size()), 0x00); for (u32 i = 0; i < output.size(); i++) output[i] = inputA[i] & inputB[i]; this->setBufferOnOutput(2, output); } }; class NodeBitwiseOR : public dp::Node { public: NodeBitwiseOR() : Node("hex.builtin.nodes.bitwise.or.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.common.input.a"), dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.common.input.b"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "hex.builtin.nodes.common.output") }) { } void process() override { const auto &inputA = this->getBufferOnInput(0); const auto &inputB = this->getBufferOnInput(1); std::vector<u8> output(std::min(inputA.size(), inputB.size()), 0x00); for (u32 i = 0; i < output.size(); i++) output[i] = inputA[i] | inputB[i]; this->setBufferOnOutput(2, output); } }; class NodeBitwiseXOR : public dp::Node { public: NodeBitwiseXOR() : Node("hex.builtin.nodes.bitwise.xor.header", { dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.common.input.a"), dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.common.input.b"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "hex.builtin.nodes.common.output") }) { } void process() override { const auto &inputA = this->getBufferOnInput(0); const auto &inputB = this->getBufferOnInput(1); std::vector<u8> output(std::min(inputA.size(), inputB.size()), 0x00); for (u32 i = 0; i < output.size(); i++) output[i] = inputA[i] ^ inputB[i]; this->setBufferOnOutput(2, output); } }; class NodeBitwiseSwap : public dp::Node { public: NodeBitwiseSwap() : Node("hex.builtin.nodes.bitwise.swap.header", {dp::Attribute(dp::Attribute::IOType::In, dp::Attribute::Type::Buffer, "hex.builtin.nodes.common.input"), dp::Attribute(dp::Attribute::IOType::Out, dp::Attribute::Type::Buffer, "hex.builtin.nodes.common.output") }) { } void process() override { // Table contains reversed nibble entries static constexpr std::array<u8, 16> BitFlipLookup = { 0x0, 0x8, 0x4, 0xC, 0x2, 0xA, 0x6, 0xE, 0x1, 0x9, 0x5, 0xD, 0x3, 0xB, 0x7, 0xF, }; auto data = this->getBufferOnInput(0); for (u8 &b : data) b = BitFlipLookup[b & 0xf] << 4 | BitFlipLookup[b >> 4]; std::reverse(data.begin(), data.end()); this->setBufferOnOutput(1, data); } }; void registerLogicDataProcessorNodes() { ContentRegistry::DataProcessorNode::add<NodeBitwiseADD>("hex.builtin.nodes.bitwise", "hex.builtin.nodes.bitwise.add"); ContentRegistry::DataProcessorNode::add<NodeBitwiseAND>("hex.builtin.nodes.bitwise", "hex.builtin.nodes.bitwise.and"); ContentRegistry::DataProcessorNode::add<NodeBitwiseOR>("hex.builtin.nodes.bitwise", "hex.builtin.nodes.bitwise.or"); ContentRegistry::DataProcessorNode::add<NodeBitwiseXOR>("hex.builtin.nodes.bitwise", "hex.builtin.nodes.bitwise.xor"); ContentRegistry::DataProcessorNode::add<NodeBitwiseNOT>("hex.builtin.nodes.bitwise", "hex.builtin.nodes.bitwise.not"); ContentRegistry::DataProcessorNode::add<NodeBitwiseShiftLeft>("hex.builtin.nodes.bitwise", "hex.builtin.nodes.bitwise.shift_left"); ContentRegistry::DataProcessorNode::add<NodeBitwiseShiftRight>("hex.builtin.nodes.bitwise", "hex.builtin.nodes.bitwise.shift_right"); ContentRegistry::DataProcessorNode::add<NodeBitwiseSwap>("hex.builtin.nodes.bitwise", "hex.builtin.nodes.bitwise.swap"); } }
8,520
C++
.cpp
135
51.607407
400
0.612737
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
194
hex_viewer.cpp
WerWolv_ImHex/plugins/builtin/source/content/pl_visualizers/hex_viewer.cpp
#include <hex/helpers/utils.hpp> #include <hex/providers/memory_provider.hpp> #include <imgui.h> #include <pl/pattern_language.hpp> #include <pl/patterns/pattern.hpp> #include <hex/ui/imgui_imhex_extensions.h> #include <ui/hex_editor.hpp> namespace hex::plugin::builtin { void drawHexVisualizer(pl::ptrn::Pattern &, bool shouldReset, std::span<const pl::core::Token::Literal> arguments) { static ui::HexEditor editor; static prv::MemoryProvider dataProvider; if (shouldReset) { auto pattern = arguments[0].toPattern(); std::vector<u8> data; try { data = pattern->getBytes(); } catch (const std::exception &) { dataProvider.resize(0); throw; } dataProvider.resize(data.size()); dataProvider.writeRaw(0x00, data.data(), data.size()); editor.setProvider(&dataProvider); } if (ImGui::BeginChild("##editor", scaled(ImVec2(600, 400)), false, ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse)) { editor.draw(); ImGui::EndChild(); } } }
1,182
C++
.cpp
30
30.533333
144
0.616667
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
195
chunk_entropy.cpp
WerWolv_ImHex/plugins/builtin/source/content/pl_visualizers/chunk_entropy.cpp
#include <implot.h> #include <imgui.h> #include <content/helpers/diagrams.hpp> #include <hex/ui/imgui_imhex_extensions.h> #include <pl/patterns/pattern.hpp> namespace hex::plugin::builtin { void drawChunkBasedEntropyVisualizer(pl::ptrn::Pattern &, bool shouldReset, std::span<const pl::core::Token::Literal> arguments) { // Variable used to store the result to avoid having to recalculate the result at each frame static DiagramChunkBasedEntropyAnalysis analyzer; // Compute data if (shouldReset) { auto pattern = arguments[0].toPattern(); auto chunkSize = arguments[1].toUnsigned(); analyzer.process(pattern->getBytes(), chunkSize); } // Show results analyzer.draw(ImVec2(400, 250), ImPlotFlags_CanvasOnly); } }
821
C++
.cpp
19
36.631579
134
0.688442
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
196
intel_hex_provider.cpp
WerWolv_ImHex/plugins/builtin/source/content/providers/intel_hex_provider.cpp
#include "content/providers/intel_hex_provider.hpp" #include <cstring> #include <hex/api/localization_manager.hpp> #include <hex/helpers/utils.hpp> #include <hex/helpers/fmt.hpp> #include <nlohmann/json.hpp> #include <wolv/io/file.hpp> #include <wolv/utils/expected.hpp> #include <wolv/utils/string.hpp> namespace hex::plugin::builtin { namespace intel_hex { u8 parseHexDigit(char c) { if (c >= '0' && c <= '9') return c - '0'; else if (c >= 'A' && c <= 'F') return c - 'A' + 10; else if (c >= 'a' && c <= 'f') return c - 'a' + 10; else throw std::runtime_error("Failed to parse hex digit"); } wolv::util::Expected<std::map<u64, std::vector<u8>>, std::string> parseIntelHex(const std::string &string) { std::map<u64, std::vector<u8>> result; u8 checksum = 0x00; u64 offset = 0x00; u8 byteCount = 0x00; u32 segmentAddress = 0x0000'0000; u32 extendedLinearAddress = 0x0000'0000; u16 address = 0x0000; std::vector<u8> data; enum class RecordType { Data = 0x00, EndOfFile = 0x01, ExtendedSegmentAddress = 0x02, StartSegmentAddress = 0x03, ExtendedLinearAddress = 0x04, StartLinearAddress = 0x05 } recordType; auto c = [&] { while (offset < string.length() && std::isspace(string[offset])) offset++; if (offset >= string.length()) throw std::runtime_error("Unexpected end of file"); return string[offset++]; }; auto parseValue = [&](u8 count) { u64 value = 0x00; for (u8 i = 0; i < count; i++) { u8 byte = (parseHexDigit(c()) << 4) | parseHexDigit(c()); value <<= 8; value |= byte; checksum += byte; } return value; }; bool endOfFile = false; try { while (offset < string.length()) { // Parse start code if (c() != ':') return { }; checksum = 0x00; if (endOfFile) throw std::runtime_error("Unexpected end of file"); // Parse byte count byteCount = parseValue(1); // Parse address address = parseValue(2); // Parse record type recordType = static_cast<RecordType>(parseValue(1)); data.clear(); for (u32 i = 0; i < byteCount; i++) { data.push_back(parseValue(1)); } parseValue(1); if (!data.empty() && checksum != 0x00) throw std::runtime_error("Checksum mismatch"); while (std::isspace(string[offset]) && offset < string.length()) offset++; // Construct region switch (recordType) { case RecordType::Data: { result[extendedLinearAddress | (segmentAddress + address)] = data; break; } case RecordType::EndOfFile: { endOfFile = true; break; } case RecordType::ExtendedSegmentAddress: { if (byteCount != 2) throw std::runtime_error("Unexpected byte count"); segmentAddress = (data[0] << 8 | data[1]) * 16; break; } case RecordType::StartSegmentAddress: { if (byteCount != 4) throw std::runtime_error("Unexpected byte count"); // Can be safely ignored break; } case RecordType::ExtendedLinearAddress: { if (byteCount != 2) throw std::runtime_error("Unexpected byte count"); extendedLinearAddress = (data[0] << 8 | data[1]) << 16; break; } case RecordType::StartLinearAddress: { if (byteCount != 4) throw std::runtime_error("Unexpected byte count"); // Can be safely ignored break; } } while (std::isspace(string[offset]) && offset < string.length()) offset++; } } catch (const std::runtime_error &e) { return wolv::util::Unexpected<std::string>(e.what()); } return result; } } void IntelHexProvider::setBaseAddress(u64 address) { auto oldBase = this->getBaseAddress(); auto regions = m_data.overlapping({ oldBase, oldBase + this->getActualSize() }); decltype(m_data) newIntervals; for (auto &[interval, data] : regions) { newIntervals.insert({ interval.start - oldBase + address, interval.end - oldBase + address }, *data); } m_data = newIntervals; Provider::setBaseAddress(address); } void IntelHexProvider::readRaw(u64 offset, void *buffer, size_t size) { auto intervals = m_data.overlapping({ offset, (offset + size) - 1 }); std::memset(buffer, 0x00, size); auto bytes = static_cast<u8*>(buffer); for (const auto &[interval, data] : intervals) { for (u32 i = std::max(interval.start, offset); i <= interval.end && (i - offset) < size; i++) { bytes[i - offset] = (*data)[i - interval.start]; } } } void IntelHexProvider::writeRaw(u64 offset, const void *buffer, size_t size) { hex::unused(offset, buffer, size); } u64 IntelHexProvider::getActualSize() const { return m_dataSize; } bool IntelHexProvider::open() { auto file = wolv::io::File(m_sourceFilePath, wolv::io::File::Mode::Read); if (!file.isValid()) { this->setErrorMessage(hex::format("hex.builtin.provider.file.error.open"_lang, m_sourceFilePath.string(), ::strerror(errno))); return false; } auto data = intel_hex::parseIntelHex(file.readString()); if (!data.has_value()) { this->setErrorMessage(data.error()); return false; } u64 maxAddress = 0x00; for (auto &[address, bytes] : data.value()) { auto endAddress = (address + bytes.size()) - 1; m_data.emplace({ address, endAddress }, std::move(bytes)); if (endAddress > maxAddress) maxAddress = endAddress; } m_dataSize = maxAddress + 1; m_dataValid = true; return true; } void IntelHexProvider::close() { } [[nodiscard]] std::string IntelHexProvider::getName() const { return hex::format("hex.builtin.provider.intel_hex.name"_lang, wolv::util::toUTF8String(m_sourceFilePath.filename())); } [[nodiscard]] std::vector<IntelHexProvider::Description> IntelHexProvider::getDataDescription() const { std::vector<Description> result; result.emplace_back("hex.builtin.provider.file.path"_lang, wolv::util::toUTF8String(m_sourceFilePath)); result.emplace_back("hex.builtin.provider.file.size"_lang, hex::toByteString(this->getActualSize())); return result; } bool IntelHexProvider::handleFilePicker() { auto picked = fs::openFileBrowser(fs::DialogMode::Open, { { "Intel Hex File", "hex" }, { "Intel Hex File", "h86" }, { "Intel Hex File", "hxl" }, { "Intel Hex File", "hxh" }, { "Intel Hex File", "obl" }, { "Intel Hex File", "obh" }, { "Intel Hex File", "mcs" }, { "Intel Hex File", "ihex" }, { "Intel Hex File", "ihe" }, { "Intel Hex File", "ihx" }, { "Intel Hex File", "a43" }, { "Intel Hex File", "a90" } }, [this](const std::fs::path &path) { m_sourceFilePath = path; } ); if (!picked) return false; if (!wolv::io::fs::isRegularFile(m_sourceFilePath)) return false; return true; } std::pair<Region, bool> IntelHexProvider::getRegionValidity(u64 address) const { auto intervals = m_data.overlapping({ address, address }); if (intervals.empty()) { return Provider::getRegionValidity(address); } decltype(m_data)::Interval closestInterval = { 0, 0 }; for (const auto &[interval, data] : intervals) { if (interval.start <= closestInterval.end) closestInterval = interval; } return { Region { closestInterval.start, (closestInterval.end - closestInterval.start) + 1}, true }; } void IntelHexProvider::loadSettings(const nlohmann::json &settings) { Provider::loadSettings(settings); auto path = settings.at("path").get<std::string>(); m_sourceFilePath = std::u8string(path.begin(), path.end()); } nlohmann::json IntelHexProvider::storeSettings(nlohmann::json settings) const { settings["path"] = wolv::io::fs::toNormalizedPathString(m_sourceFilePath); return Provider::storeSettings(settings); } }
10,197
C++
.cpp
228
29.868421
138
0.494446
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
197
view_provider.cpp
WerWolv_ImHex/plugins/builtin/source/content/providers/view_provider.cpp
#include <content/providers/view_provider.hpp> #include <hex/helpers/fmt.hpp> #include <hex/api/event_manager.hpp> #include <popups/popup_text_input.hpp> #include <nlohmann/json.hpp> namespace hex::plugin::builtin { [[nodiscard]] bool ViewProvider::isAvailable() const { if (m_provider == nullptr) return false; else return m_provider->isAvailable(); } [[nodiscard]] bool ViewProvider::isReadable() const { if (m_provider == nullptr) return false; else return m_provider->isReadable(); } [[nodiscard]] bool ViewProvider::isWritable() const { if (m_provider == nullptr) return false; else return m_provider->isWritable(); } [[nodiscard]] bool ViewProvider::isResizable() const { return true; } [[nodiscard]] bool ViewProvider::isSavable() const { if (m_provider == nullptr) return false; else return m_provider->isSavable(); } [[nodiscard]] bool ViewProvider::isSavableAsRecent() const { return false; } void ViewProvider::save() { m_provider->save(); } [[nodiscard]] bool ViewProvider::open() { if (m_provider == this) return false; EventProviderClosing::subscribe(this, [this](const prv::Provider *provider, bool*) { if (m_provider == provider) ImHexApi::Provider::remove(this, false); }); return true; } void ViewProvider::close() { EventProviderClosing::unsubscribe(this); } void ViewProvider::resizeRaw(u64 newSize) { m_size = newSize; } void ViewProvider::insertRaw(u64 offset, u64 size) { if (m_provider == nullptr) return; m_size += size; m_provider->insert(offset + m_startAddress, size); } void ViewProvider::removeRaw(u64 offset, u64 size) { if (m_provider == nullptr) return; m_size -= size; m_provider->remove(offset + m_startAddress, size); } void ViewProvider::readRaw(u64 offset, void *buffer, size_t size) { if (m_provider == nullptr) return; m_provider->read(offset + m_startAddress, buffer, size); } void ViewProvider::writeRaw(u64 offset, const void *buffer, size_t size) { if (m_provider == nullptr) return; m_provider->write(offset + m_startAddress, buffer, size); } [[nodiscard]] u64 ViewProvider::getActualSize() const { return m_size; } [[nodiscard]] std::string ViewProvider::getName() const { if (!m_name.empty()) return m_name; if (m_provider == nullptr) return "View"; else return hex::format("{} View", m_provider->getName()); } [[nodiscard]] std::vector<ViewProvider::Description> ViewProvider::getDataDescription() const { if (m_provider == nullptr) return { }; return m_provider->getDataDescription(); } void ViewProvider::loadSettings(const nlohmann::json &settings) { Provider::loadSettings(settings); auto id = settings.at("id").get<u64>(); m_startAddress = settings.at("start_address").get<u64>(); m_size = settings.at("size").get<size_t>(); const auto &providers = ImHexApi::Provider::getProviders(); auto provider = std::ranges::find_if(providers, [id](const prv::Provider *provider) { return provider->getID() == id; }); if (provider == providers.end()) return; m_provider = *provider; } [[nodiscard]] nlohmann::json ViewProvider::storeSettings(nlohmann::json settings) const { settings["id"] = m_provider->getID(); settings["start_address"] = m_startAddress; settings["size"] = m_size; return Provider::storeSettings(settings); } [[nodiscard]] std::string ViewProvider::getTypeName() const { return "hex.builtin.provider.view"; } void ViewProvider::setProvider(u64 startAddress, size_t size, hex::prv::Provider *provider) { m_startAddress = startAddress; m_size = size; m_provider = provider; } void ViewProvider::setName(const std::string& name) { m_name = name; } [[nodiscard]] std::pair<Region, bool> ViewProvider::getRegionValidity(u64 address) const { address -= this->getBaseAddress(); if (address < this->getActualSize()) return { Region { this->getBaseAddress() + address, this->getActualSize() - address }, true }; else return { Region::Invalid(), false }; } std::vector<prv::Provider::MenuEntry> ViewProvider::getMenuEntries() { return { MenuEntry { Lang("hex.builtin.provider.rename"), [this] { this->renameFile(); } } }; } void ViewProvider::renameFile() { ui::PopupTextInput::open("hex.builtin.provider.rename", "hex.builtin.provider.rename.desc", [this](const std::string &name) { m_name = name; RequestUpdateWindowTitle::post(); }); } }
5,210
C++
.cpp
141
28.730496
133
0.601868
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
198
gdb_provider.cpp
WerWolv_ImHex/plugins/builtin/source/content/providers/gdb_provider.cpp
#include "content/providers/gdb_provider.hpp" #include <cstring> #include <thread> #include <chrono> #include <imgui.h> #include <hex/ui/imgui_imhex_extensions.h> #include <hex/helpers/fmt.hpp> #include <hex/helpers/crypto.hpp> #include <hex/api/localization_manager.hpp> #include <nlohmann/json.hpp> namespace hex::plugin::builtin { using namespace std::chrono_literals; namespace gdb { namespace { u8 calculateChecksum(const std::string &data) { u64 checksum = 0; for (const auto &c : data) checksum += c; return checksum & 0xFF; } std::string createPacket(const std::string &data) { return hex::format("${}#{:02x}", data, calculateChecksum(data)); } std::optional<std::string> parsePacket(const std::string &packet) { if (packet.length() < 4) return std::nullopt; if (!packet.starts_with('$')) return std::nullopt; if (packet[packet.length() - 3] != '#') return std::nullopt; std::string data = packet.substr(1, packet.length() - 4); std::string checksum = packet.substr(packet.length() - 2, 2); auto decodedChecksum = crypt::decode16(checksum); if (checksum.length() != 2 || decodedChecksum.empty() || decodedChecksum[0] != calculateChecksum(data)) return std::nullopt; return data; } } void sendAck(const wolv::net::SocketClient &socket) { socket.writeString("+"); } void continueExecution(const wolv::net::SocketClient &socket) { socket.writeString(createPacket("vCont;c")); } std::vector<u8> readMemory(const wolv::net::SocketClient &socket, u64 address, size_t size) { std::string packet = createPacket(hex::format("m{:X},{:X}", address, size)); socket.writeString(packet); auto receivedPacket = socket.readString(size * 2 + 4); if (receivedPacket.empty()) return {}; auto receivedData = parsePacket(receivedPacket); if (!receivedData.has_value()) return {}; if (receivedData->size() == 3 && receivedData->starts_with("E")) return {}; auto data = crypt::decode16(receivedData.value()); data.resize(size); return data; } void writeMemory(const wolv::net::SocketClient &socket, u64 address, const void *buffer, size_t size) { std::vector<u8> bytes(size); std::memcpy(bytes.data(), buffer, size); std::string byteString = crypt::encode16(bytes); std::string packet = createPacket(hex::format("M{:X},{:X}:{}", address, size, byteString)); socket.writeString(packet); auto receivedPacket = socket.readString(6); } bool enableNoAckMode(const wolv::net::SocketClient &socket) { socket.writeString(createPacket("QStartNoAckMode")); auto ack = socket.readString(1); if (ack.empty() || ack[0] != '+') return false; auto receivedPacket = socket.readString(6); auto receivedData = parsePacket(receivedPacket); if (receivedData && *receivedData == "OK") { sendAck(socket); return true; } else { return false; } } } GDBProvider::GDBProvider() : m_size(0xFFFF'FFFF) { } bool GDBProvider::isAvailable() const { return m_socket.isConnected(); } bool GDBProvider::isReadable() const { return m_socket.isConnected(); } bool GDBProvider::isWritable() const { return true; } bool GDBProvider::isResizable() const { return false; } bool GDBProvider::isSavable() const { return false; } void GDBProvider::readRaw(u64 offset, void *buffer, size_t size) { if ((offset - this->getBaseAddress()) > (this->getActualSize() - size) || buffer == nullptr || size == 0) return; offset -= this->getBaseAddress(); u64 alignedOffset = offset - (offset % CacheLineSize); if (size <= CacheLineSize) { std::scoped_lock lock(m_cacheLock); const auto &cacheLine = std::find_if(m_cache.begin(), m_cache.end(), [&](auto &line) { return line.address == alignedOffset; }); if (cacheLine != m_cache.end()) { // Cache hit } else { // Cache miss m_cache.push_back({ alignedOffset, { 0 } }); } if (cacheLine != m_cache.end()) std::memcpy(buffer, &cacheLine->data[0] + (offset % CacheLineSize), std::min<u64>(size, cacheLine->data.size())); } else { while (size > 0) { size_t readSize = std::min<u64>(size, CacheLineSize); auto data = gdb::readMemory(m_socket, offset, size); if (!data.empty()) std::memcpy(buffer, &data[0], data.size()); size -= readSize; offset += readSize; } } } void GDBProvider::writeRaw(u64 offset, const void *buffer, size_t size) { if ((offset - this->getBaseAddress()) > (this->getActualSize() - size) || buffer == nullptr || size == 0) return; offset -= this->getBaseAddress(); gdb::writeMemory(m_socket, offset, buffer, size); } void GDBProvider::save() { Provider::save(); } u64 GDBProvider::getActualSize() const { return m_size; } std::string GDBProvider::getName() const { std::string address = "-"; std::string port = "-"; if (this->isConnected()) { address = m_ipAddress; port = std::to_string(m_port); } return hex::format("hex.builtin.provider.gdb.name"_lang, address, port); } std::vector<GDBProvider::Description> GDBProvider::getDataDescription() const { return { {"hex.builtin.provider.gdb.server"_lang, hex::format("{}:{}", m_ipAddress, m_port)}, }; } bool GDBProvider::open() { m_socket = wolv::net::SocketClient(wolv::net::SocketClient::Type::TCP); m_socket.connect(m_ipAddress, m_port); if (!gdb::enableNoAckMode(m_socket)) { m_socket.disconnect(); return false; } if (m_socket.isConnected()) { gdb::continueExecution(m_socket); m_cacheUpdateThread = std::thread([this] { auto cacheLine = m_cache.begin(); while (this->isConnected()) { { std::scoped_lock lock(m_cacheLock); if (m_resetCache) { m_cache.clear(); m_resetCache = false; cacheLine = m_cache.begin(); } if (cacheLine != m_cache.end()) { std::vector<u8> data = gdb::readMemory(m_socket, cacheLine->address, CacheLineSize); while (std::count_if(m_cache.begin(), m_cache.end(), [&](auto &line) { return !line.data.empty(); }) > 100) { m_cache.pop_front(); cacheLine = m_cache.begin(); } std::memcpy(cacheLine->data.data(), data.data(), data.size()); } if (cacheLine == m_cache.end()) cacheLine = m_cache.begin(); else ++cacheLine; } std::this_thread::sleep_for(10ms); } }); return true; } else { return false; } } void GDBProvider::close() { m_socket.disconnect(); if (m_cacheUpdateThread.joinable()) { m_cacheUpdateThread.join(); } } bool GDBProvider::isConnected() const { return m_socket.isConnected(); } bool GDBProvider::drawLoadInterface() { ImGui::InputText("hex.builtin.provider.gdb.ip"_lang, m_ipAddress); ImGui::InputInt("hex.builtin.provider.gdb.port"_lang, &m_port, 0, 0); ImGui::Separator(); ImGuiExt::InputHexadecimal("hex.ui.common.size"_lang, &m_size, ImGuiInputTextFlags_CharsHexadecimal); if (m_port < 0) m_port = 0; else if (m_port > 0xFFFF) m_port = 0xFFFF; return !m_ipAddress.empty() && m_port != 0; } void GDBProvider::loadSettings(const nlohmann::json &settings) { Provider::loadSettings(settings); m_ipAddress = settings.at("ip").get<std::string>(); m_port = settings.at("port").get<int>(); m_size = settings.at("size").get<size_t>(); } nlohmann::json GDBProvider::storeSettings(nlohmann::json settings) const { settings["ip"] = m_ipAddress; settings["port"] = m_port; settings["size"] = m_size; return Provider::storeSettings(settings); } std::pair<Region, bool> GDBProvider::getRegionValidity(u64 address) const { address -= this->getBaseAddress(); if (address < this->getActualSize()) return { Region { this->getBaseAddress() + address, this->getActualSize() - address }, true }; else return { Region::Invalid(), false }; } std::variant<std::string, i128> GDBProvider::queryInformation(const std::string &category, const std::string &argument) { if (category == "ip") return m_ipAddress; else if (category == "port") return m_port; else return Provider::queryInformation(category, argument); } }
10,212
C++
.cpp
242
30.004132
137
0.533968
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
199
file_provider.cpp
WerWolv_ImHex/plugins/builtin/source/content/providers/file_provider.cpp
#include "content/providers/file_provider.hpp" #include "content/providers/memory_file_provider.hpp" #include <hex/api/content_registry.hpp> #include <hex/api/imhex_api.hpp> #include <hex/api/localization_manager.hpp> #include <hex/api/project_file_manager.hpp> #include <hex/api/task_manager.hpp> #include <popups/popup_question.hpp> #include <toasts/toast_notification.hpp> #include <hex/helpers/utils.hpp> #include <hex/helpers/fmt.hpp> #include <fmt/chrono.h> #include <wolv/utils/string.hpp> #include <wolv/literals.hpp> #include <nlohmann/json.hpp> #include <cstring> #if defined(OS_WINDOWS) #include <windows.h> #endif namespace hex::plugin::builtin { static std::mutex s_openCloseMutex; using namespace wolv::literals; std::set<FileProvider*> FileProvider::s_openedFiles; bool FileProvider::isAvailable() const { return true; } bool FileProvider::isReadable() const { return isAvailable() && m_readable; } bool FileProvider::isWritable() const { return isAvailable() && m_writable; } bool FileProvider::isResizable() const { return isAvailable() && isWritable(); } bool FileProvider::isSavable() const { return m_loadedIntoMemory; } void FileProvider::readRaw(u64 offset, void *buffer, size_t size) { if (m_fileSize == 0 || (offset + size) > m_fileSize || buffer == nullptr || size == 0) return; if (m_loadedIntoMemory) std::memcpy(buffer, m_data.data() + offset, size); else m_file.readBufferAtomic(offset, static_cast<u8*>(buffer), size); } void FileProvider::writeRaw(u64 offset, const void *buffer, size_t size) { if ((offset + size) > this->getActualSize() || buffer == nullptr || size == 0) return; if (m_loadedIntoMemory) std::memcpy(m_data.data() + offset, buffer, size); else m_file.writeBufferAtomic(offset, static_cast<const u8*>(buffer), size); } void FileProvider::save() { if (m_loadedIntoMemory) { m_ignoreNextChangeEvent = true; m_file.open(); m_file.writeVectorAtomic(0x00, m_data); m_file.setSize(m_data.size()); } else { m_file.flush(); } #if defined(OS_WINDOWS) FILETIME ft; SYSTEMTIME st; if (m_file.isValid()) { GetSystemTime(&st); if (SystemTimeToFileTime(&st, &ft)) { auto fileHandle = HANDLE(_get_osfhandle(_fileno(m_file.getHandle()))); SetFileTime(fileHandle, nullptr, nullptr, &ft); } } #endif if (m_loadedIntoMemory) m_file.close(); Provider::save(); } void FileProvider::saveAs(const std::fs::path &path) { if (path == m_path) this->save(); else Provider::saveAs(path); } void FileProvider::resizeRaw(u64 newSize) { if (m_loadedIntoMemory) m_data.resize(newSize); else m_file.setSize(newSize); m_fileSize = newSize; } u64 FileProvider::getActualSize() const { return m_fileSize; } std::string FileProvider::getName() const { return wolv::util::toUTF8String(m_path.filename()); } std::vector<FileProvider::Description> FileProvider::getDataDescription() const { std::vector<Description> result; result.emplace_back("hex.builtin.provider.file.path"_lang, wolv::util::toUTF8String(m_path)); result.emplace_back("hex.builtin.provider.file.size"_lang, hex::toByteString(this->getActualSize())); if (m_fileStats.has_value()) { std::string creationTime, accessTime, modificationTime; try { creationTime = hex::format("{:%Y-%m-%d %H:%M:%S}", fmt::localtime(m_fileStats->st_ctime)); } catch (const std::exception&) { creationTime = "???"; } try { accessTime = hex::format("{:%Y-%m-%d %H:%M:%S}", fmt::localtime(m_fileStats->st_atime)); } catch (const std::exception&) { accessTime = "???"; } try { modificationTime = hex::format("{:%Y-%m-%d %H:%M:%S}", fmt::localtime(m_fileStats->st_mtime)); } catch (const std::exception&) { modificationTime = "???"; } result.emplace_back("hex.builtin.provider.file.creation"_lang, creationTime); result.emplace_back("hex.builtin.provider.file.access"_lang, accessTime); result.emplace_back("hex.builtin.provider.file.modification"_lang, modificationTime); } return result; } std::variant<std::string, i128> FileProvider::queryInformation(const std::string &category, const std::string &argument) { if (category == "file_path") return wolv::io::fs::toNormalizedPathString(m_path); else if (category == "file_name") return wolv::io::fs::toNormalizedPathString(m_path.filename()); else if (category == "file_extension") return wolv::io::fs::toNormalizedPathString(m_path.extension()); else if (category == "creation_time") return m_fileStats->st_ctime; else if (category == "access_time") return m_fileStats->st_atime; else if (category == "modification_time") return m_fileStats->st_mtime; else if (category == "permissions") return m_fileStats->st_mode & 0777; else return Provider::queryInformation(category, argument); } bool FileProvider::handleFilePicker() { return fs::openFileBrowser(fs::DialogMode::Open, {}, [this](const auto &path) { this->setPath(path); }); } std::vector<FileProvider::MenuEntry> FileProvider::getMenuEntries() { FileProvider::MenuEntry loadMenuItem; if (m_loadedIntoMemory) loadMenuItem = { "hex.builtin.provider.file.menu.direct_access"_lang, [this] { this->convertToDirectAccess(); } }; else loadMenuItem = { "hex.builtin.provider.file.menu.into_memory"_lang, [this] { this->convertToMemoryFile(); } }; return { { "hex.builtin.provider.file.menu.open_folder"_lang, [this] { fs::openFolderWithSelectionExternal(m_path); } }, { "hex.builtin.provider.file.menu.open_file"_lang, [this] { fs::openFileExternal(m_path); } }, loadMenuItem }; } void FileProvider::setPath(const std::fs::path &path) { m_path = path; m_path.make_preferred(); } bool FileProvider::open() { const size_t maxMemoryFileSize = ContentRegistry::Settings::read<u64>("hex.builtin.setting.general", "hex.builtin.setting.general.max_mem_file_size", 128_MiB); size_t fileSize = 0x00; { wolv::io::File file(m_path, wolv::io::File::Mode::Read); if (!file.isValid()) return false; fileSize = file.getSize(); } const bool directAccess = fileSize >= maxMemoryFileSize; const bool result = open(directAccess); if (result && directAccess) { m_writable = false; ui::PopupQuestion::open("hex.builtin.provider.file.too_large"_lang, [this] { m_writable = false; }, [this] { m_writable = true; RequestUpdateWindowTitle::post(); }); } return result; } bool FileProvider::open(bool directAccess) { m_readable = true; m_writable = true; if (!wolv::io::fs::exists(m_path)) { this->setErrorMessage(hex::format("hex.builtin.provider.file.error.open"_lang, m_path.string(), ::strerror(ENOENT))); return false; } wolv::io::File file(m_path, wolv::io::File::Mode::Write); if (!file.isValid()) { m_writable = false; file = wolv::io::File(m_path, wolv::io::File::Mode::Read); if (!file.isValid()) { m_readable = false; this->setErrorMessage(hex::format("hex.builtin.provider.file.error.open"_lang, m_path.string(), ::strerror(errno))); return false; } ui::ToastInfo::open("hex.builtin.popup.error.read_only"_lang); } std::scoped_lock lock(s_openCloseMutex); m_file = std::move(file); m_fileStats = m_file.getFileInfo(); m_fileSize = m_file.getSize(); // Make sure the current file is not already opened { auto alreadyOpenedFileProvider = std::ranges::find_if(s_openedFiles, [this](const FileProvider *provider) { return provider->m_path == m_path; }); if (alreadyOpenedFileProvider != s_openedFiles.end()) { ImHexApi::Provider::setCurrentProvider(*alreadyOpenedFileProvider); return false; } else { s_openedFiles.insert(this); } } if (m_writable) { if (directAccess) { m_loadedIntoMemory = false; } else { m_data = m_file.readVectorAtomic(0x00, m_fileSize); if (!m_data.empty()) { m_changeTracker = wolv::io::ChangeTracker(m_file); m_changeTracker.startTracking([this]{ this->handleFileChange(); }); m_file.close(); m_loadedIntoMemory = true; } } } return true; } void FileProvider::close() { std::scoped_lock lock(s_openCloseMutex); m_file.close(); m_data.clear(); s_openedFiles.erase(this); m_changeTracker.stopTracking(); } void FileProvider::loadSettings(const nlohmann::json &settings) { Provider::loadSettings(settings); auto pathString = settings.at("path").get<std::string>(); std::fs::path path = std::u8string(pathString.begin(), pathString.end()); if (auto projectPath = ProjectFile::getPath(); !projectPath.empty()) { std::fs::path fullPath; try { fullPath = std::fs::weakly_canonical(projectPath.parent_path() / path); } catch (const std::fs::filesystem_error &) { fullPath = projectPath.parent_path() / path; } if (!wolv::io::fs::exists(fullPath)) fullPath = path; if (!wolv::io::fs::exists(fullPath)) { this->setErrorMessage(hex::format("hex.builtin.provider.file.error.open"_lang, m_path.string(), ::strerror(ENOENT))); } path = std::move(fullPath); } this->setPath(path); } nlohmann::json FileProvider::storeSettings(nlohmann::json settings) const { std::fs::path path; if (m_path.u8string().starts_with(u8"//")) { path = m_path; } else { if (auto projectPath = ProjectFile::getPath(); !projectPath.empty()) path = std::fs::proximate(m_path, projectPath.parent_path()); if (path.empty()) path = m_path; } settings["path"] = wolv::io::fs::toNormalizedPathString(path); return Provider::storeSettings(settings); } std::pair<Region, bool> FileProvider::getRegionValidity(u64 address) const { address -= this->getBaseAddress(); if (address < this->getActualSize()) return { Region { this->getBaseAddress() + address, this->getActualSize() - address }, true }; else return { Region::Invalid(), false }; } void FileProvider::convertToMemoryFile() { this->close(); this->open(false); } void FileProvider::convertToDirectAccess() { this->close(); this->open(true); } void FileProvider::handleFileChange() { if (m_ignoreNextChangeEvent) { m_ignoreNextChangeEvent = false; return; } if (m_changeEventAcknowledgementPending) { return; } m_changeEventAcknowledgementPending = true; ui::PopupQuestion::open("hex.builtin.provider.file.reload_changes"_lang, [this] { this->close(); (void)this->open(!m_loadedIntoMemory); getUndoStack().reapply(); m_changeEventAcknowledgementPending = false; }, [this]{ m_changeEventAcknowledgementPending = false; }); } }
12,651
C++
.cpp
302
31.827815
167
0.583986
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
200
disk_provider.cpp
WerWolv_ImHex/plugins/builtin/source/content/providers/disk_provider.cpp
#if !defined(OS_WEB) #include "content/providers/disk_provider.hpp" #include <hex/api/localization_manager.hpp> #include <hex/helpers/logger.hpp> #include <hex/helpers/fmt.hpp> #include <hex/helpers/utils.hpp> #include <hex/ui/imgui_imhex_extensions.h> #include <wolv/utils/string.hpp> #include <bitset> #include <filesystem> #include <imgui.h> #include <fonts/codicons_font.h> #include <nlohmann/json.hpp> #if defined(OS_WINDOWS) #include <windows.h> #include <winioctl.h> #include <setupapi.h> #include <cfgmgr32.h> #elif defined(OS_LINUX) #include <fcntl.h> #include <unistd.h> #if !defined(OS_FREEBSD) #include <linux/fs.h> #endif #include <sys/stat.h> #include <sys/ioctl.h> #include <sys/types.h> #elif defined(OS_MACOS) #include <fcntl.h> #include <unistd.h> #include <sys/stat.h> #include <sys/ioctl.h> #include <sys/types.h> #include <sys/disk.h> #endif #if defined(OS_LINUX) && !defined(OS_FREEBSD) #define lseek lseek64 #elif defined(OS_FREEBSD) #include <sys/disk.h> #define DEFAULT_SECTOR_SIZE 512 #endif namespace hex::plugin::builtin { bool DiskProvider::isAvailable() const { #if defined(OS_WINDOWS) return m_diskHandle != INVALID_HANDLE_VALUE; #else return m_diskHandle != -1; #endif } bool DiskProvider::isReadable() const { return m_readable; } bool DiskProvider::isWritable() const { return m_writable; } bool DiskProvider::isResizable() const { return false; } bool DiskProvider::isSavable() const { return false; } void DiskProvider::setPath(const std::fs::path &path) { m_path = path; } #if defined (OS_LINUX) #ifdef BLKSSZGET int blkdev_get_sector_size(int fd, int *sector_size) { if (ioctl(fd, BLKSSZGET, sector_size) < 0) return -1; return 0; } #elif defined(OS_FREEBSD) && defined(DIOCGSECTORSIZE) int blkdev_get_sector_size(int fd, int *sector_size) { if (ioctl(fd, DIOCGSECTORSIZE, sector_size) < 0) return -1; return 0; } #else int blkdev_get_sector_size(int fd, int *sector_size) { (void)fd; *sector_size = DEFAULT_SECTOR_SIZE; return 0; } #endif #ifdef BLKGETSIZE64 int blkdev_get_size(int fd, u64 *bytes) { if (ioctl(fd, BLKGETSIZE64, bytes) < 0) return -1; return 0; } #elif defined(OS_FREEBSD) && defined(DIOCGMEDIASIZE) int blkdev_get_size(int fd, u64 *bytes) { if (ioctl(fd, DIOCGMEDIASIZE, bytes) < 0) return -1; return 0; } #else int blkdev_get_size(int fd, u64 *bytes) { struct stat st; if (fstat(fd, &st) < 0) return -1; if (st.st_size == 0) { // Try BLKGETSIZE unsigned long long bytes64; if (ioctl(fd, BLKGETSIZE, &bytes64) >= 0) { *bytes = bytes64; return 0; } } *bytes = st.st_size; return 0; } #endif #elif defined(OS_MACOS) int blkdev_get_sector_size(int fd, int *sector_size) { if (ioctl(fd, DKIOCGETBLOCKSIZE, sector_size) >= 0) return 0; return -1; } int blkdev_get_size(int fd, u64 *bytes) { int sectorSize = 0; if (blkdev_get_sector_size(fd, &sectorSize) < 0) return -1; if (ioctl(fd, DKIOCGETBLOCKCOUNT, bytes) < 0) return -1; *bytes *= sectorSize; return 0; } #endif bool DiskProvider::open() { m_readable = true; m_writable = true; #if defined(OS_WINDOWS) const auto &path = m_path.native(); m_diskHandle = CreateFileW(path.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); if (m_diskHandle == INVALID_HANDLE_VALUE) { m_diskHandle = CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); m_writable = false; if (m_diskHandle == INVALID_HANDLE_VALUE) { this->setErrorMessage(hex::formatSystemError(::GetLastError())); return false; } } { DISK_GEOMETRY_EX diskGeometry = { }; DWORD bytesRead = 0; if (DeviceIoControl( m_diskHandle, IOCTL_DISK_GET_DRIVE_GEOMETRY_EX, nullptr, 0, &diskGeometry, sizeof(DISK_GEOMETRY_EX), &bytesRead, nullptr)) { m_diskSize = diskGeometry.DiskSize.QuadPart; m_sectorSize = diskGeometry.Geometry.BytesPerSector; m_sectorBuffer.resize(m_sectorSize); } } if (m_diskHandle == nullptr || m_diskHandle == INVALID_HANDLE_VALUE) { this->setErrorMessage(hex::formatSystemError(::GetLastError())); m_readable = false; m_diskHandle = nullptr; CloseHandle(m_diskHandle); return false; } #else const auto &path = m_path.native(); m_diskHandle = ::open(path.c_str(), O_RDWR); if (m_diskHandle == -1) { this->setErrorMessage(hex::format("hex.builtin.provider.disk.error.read_rw"_lang, path, ::strerror(errno))); log::warn(this->getErrorMessage()); m_diskHandle = ::open(path.c_str(), O_RDONLY); m_writable = false; } if (m_diskHandle == -1) { this->setErrorMessage(hex::format("hex.builtin.provider.disk.error.read_ro"_lang, path, ::strerror(errno))); log::warn(this->getErrorMessage()); m_readable = false; return false; } u64 diskSize = 0; blkdev_get_size(m_diskHandle, &diskSize); m_diskSize = diskSize; blkdev_get_sector_size(m_diskHandle, reinterpret_cast<int *>(&m_sectorSize)); m_sectorBuffer.resize(m_sectorSize); #endif return true; } void DiskProvider::close() { #if defined(OS_WINDOWS) if (m_diskHandle != INVALID_HANDLE_VALUE) ::CloseHandle(m_diskHandle); m_diskHandle = INVALID_HANDLE_VALUE; #else if (m_diskHandle != -1) ::close(m_diskHandle); m_diskHandle = -1; #endif } void DiskProvider::readRaw(u64 offset, void *buffer, size_t size) { #if defined(OS_WINDOWS) DWORD bytesRead = 0; u64 startOffset = offset; while (size > 0) { LARGE_INTEGER seekPosition; seekPosition.LowPart = (offset & 0xFFFF'FFFF) - (offset % m_sectorSize); seekPosition.HighPart = LONG(offset >> 32); if (m_sectorBufferAddress != static_cast<u64>(seekPosition.QuadPart)) { ::SetFilePointer(m_diskHandle, seekPosition.LowPart, &seekPosition.HighPart, FILE_BEGIN); ::ReadFile(m_diskHandle, m_sectorBuffer.data(), m_sectorBuffer.size(), &bytesRead, nullptr); m_sectorBufferAddress = seekPosition.QuadPart; } std::memcpy(static_cast<u8 *>(buffer) + (offset - startOffset), m_sectorBuffer.data() + (offset & (m_sectorSize - 1)), std::min<u64>(m_sectorSize, size)); size = std::max<ssize_t>(static_cast<ssize_t>(size) - m_sectorSize, 0); offset += m_sectorSize; } #else u64 startOffset = offset; while (size > 0) { u64 seekPosition = offset - (offset % m_sectorSize); if (m_sectorBufferAddress != seekPosition || m_sectorBufferAddress == 0) { ::lseek(m_diskHandle, seekPosition, SEEK_SET); if (::read(m_diskHandle, m_sectorBuffer.data(), m_sectorBuffer.size()) == -1) break; m_sectorBufferAddress = seekPosition; } std::memcpy(reinterpret_cast<u8 *>(buffer) + (offset - startOffset), m_sectorBuffer.data() + (offset & (m_sectorSize - 1)), std::min<u64>(m_sectorSize, size)); size = std::max<ssize_t>(static_cast<ssize_t>(size) - m_sectorSize, 0); offset += m_sectorSize; } #endif } void DiskProvider::writeRaw(u64 offset, const void *buffer, size_t size) { #if defined(OS_WINDOWS) DWORD bytesWritten = 0; u64 startOffset = offset; std::vector<u8> modifiedSectorBuffer; modifiedSectorBuffer.resize(m_sectorSize); while (size > 0) { u64 sectorBase = offset - (offset % m_sectorSize); size_t currSize = std::min<u64>(size, m_sectorSize); this->readRaw(sectorBase, modifiedSectorBuffer.data(), modifiedSectorBuffer.size()); std::memcpy(modifiedSectorBuffer.data() + ((offset - sectorBase) % m_sectorSize), static_cast<const u8 *>(buffer) + (startOffset - offset), currSize); LARGE_INTEGER seekPosition; seekPosition.LowPart = (offset & 0xFFFF'FFFF) - (offset % m_sectorSize); seekPosition.HighPart = offset >> 32; ::SetFilePointer(m_diskHandle, seekPosition.LowPart, &seekPosition.HighPart, FILE_BEGIN); ::WriteFile(m_diskHandle, modifiedSectorBuffer.data(), modifiedSectorBuffer.size(), &bytesWritten, nullptr); //Print last error log::error("{}", hex::formatSystemError(::GetLastError())); offset += currSize; size -= currSize; } #else u64 startOffset = offset; std::vector<u8> modifiedSectorBuffer; modifiedSectorBuffer.resize(m_sectorSize); while (size > 0) { u64 sectorBase = offset - (offset % m_sectorSize); size_t currSize = std::min<u64>(size, m_sectorSize); this->readRaw(sectorBase, modifiedSectorBuffer.data(), modifiedSectorBuffer.size()); std::memcpy(modifiedSectorBuffer.data() + ((offset - sectorBase) % m_sectorSize), reinterpret_cast<const u8 *>(buffer) + (startOffset - offset), currSize); ::lseek(m_diskHandle, sectorBase, SEEK_SET); if (::write(m_diskHandle, modifiedSectorBuffer.data(), modifiedSectorBuffer.size()) < 0) break; offset += currSize; size -= currSize; } #endif } u64 DiskProvider::getActualSize() const { return m_diskSize; } std::string DiskProvider::getName() const { if (m_friendlyName.empty()) return wolv::util::toUTF8String(m_path); else return m_friendlyName; } std::vector<DiskProvider::Description> DiskProvider::getDataDescription() const { return { { "hex.builtin.provider.disk.selected_disk"_lang, wolv::util::toUTF8String(m_path) }, { "hex.builtin.provider.disk.disk_size"_lang, hex::toByteString(m_diskSize) }, { "hex.builtin.provider.disk.sector_size"_lang, hex::toByteString(m_sectorSize) } }; } void DiskProvider::reloadDrives() { #if defined(OS_WINDOWS) m_availableDrives.clear(); std::array<WCHAR, MAX_DEVICE_ID_LEN> deviceInstanceId = {}; std::array<WCHAR, 1024> description = {}; const GUID hddClass = GUID_DEVINTERFACE_DISK; HDEVINFO hDevInfo = SetupDiGetClassDevs(&hddClass, nullptr, nullptr, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE); if (hDevInfo == INVALID_HANDLE_VALUE) return; // Add all physical drives for (u32 i = 0; ; i++) { SP_DEVINFO_DATA deviceInfoData; deviceInfoData.cbSize = sizeof(deviceInfoData); if (SetupDiEnumDeviceInfo(hDevInfo, i, &deviceInfoData) == FALSE) break; SP_DEVICE_INTERFACE_DATA interfaceData; interfaceData.cbSize = sizeof(SP_INTERFACE_DEVICE_DATA); if (!SetupDiEnumInterfaceDevice(hDevInfo, nullptr, &hddClass, i, &interfaceData)) break; if (CM_Get_Device_IDW(deviceInfoData.DevInst, deviceInstanceId.data(), MAX_PATH, 0) != CR_SUCCESS) continue; // Get the required size of the device path DWORD requiredSize = 0; SetupDiGetDeviceInterfaceDetail(hDevInfo, &interfaceData, nullptr, 0, &requiredSize, nullptr); // Query the device path std::vector<u8> dataBuffer(requiredSize); auto data = reinterpret_cast<SP_INTERFACE_DEVICE_DETAIL_DATA*>(dataBuffer.data()); data->cbSize = sizeof(SP_INTERFACE_DEVICE_DETAIL_DATA); if (!SetupDiGetDeviceInterfaceDetail(hDevInfo, &interfaceData, data, requiredSize, nullptr, nullptr)) continue; auto path = reinterpret_cast<const WCHAR*>(data->DevicePath); // Query the friendly name of the device DWORD size = 0; DWORD propertyRegDataType = SPDRP_PHYSICAL_DEVICE_OBJECT_NAME; SetupDiGetDeviceRegistryPropertyW(hDevInfo, &deviceInfoData, SPDRP_FRIENDLYNAME, &propertyRegDataType, reinterpret_cast<BYTE*>(description.data()), sizeof(description), &size); auto friendlyName = description.data(); m_availableDrives.insert({ utf16ToUtf8(path), utf16ToUtf8(friendlyName) }); } // Add all logical drives std::bitset<32> drives = ::GetLogicalDrives(); for (char i = 0; i < 26; i++) { if (drives[i]) { char letter = 'A' + i; m_availableDrives.insert({ hex::format(R"(\\.\{:c}:)", letter), hex::format(R"({:c}:/)", letter) }); } } #endif } bool DiskProvider::drawLoadInterface() { #if defined(OS_WINDOWS) if (m_availableDrives.empty()) { this->reloadDrives(); m_elevated = hex::isProcessElevated(); } if (!m_elevated) { ImGui::PushTextWrapPos(0); ImGuiExt::TextFormattedColored(ImGuiExt::GetCustomColorU32(ImGuiCustomCol_LoggerError), ICON_VS_SHIELD "{}", "hex.builtin.provider.disk.elevation"_lang); ImGui::PopTextWrapPos(); ImGui::NewLine(); } ImGui::PushItemWidth(300_scaled); if (ImGui::BeginListBox("hex.builtin.provider.disk.selected_disk"_lang)) { ImGui::PushID(1); for (const auto &[path, friendlyName] : m_availableDrives) { if (ImGui::Selectable(friendlyName.c_str(), m_path == path)) { m_path = path; m_friendlyName = friendlyName; } ImGuiExt::InfoTooltip(path.c_str()); } ImGui::PopID(); ImGui::EndListBox(); } ImGui::PopItemWidth(); ImGui::SameLine(); if (ImGui::Button("hex.builtin.provider.disk.reload"_lang)) { this->reloadDrives(); } #else if (ImGui::InputText("hex.builtin.provider.disk.selected_disk"_lang, m_pathBuffer.data(), m_pathBuffer.size(), ImGuiInputTextFlags_CallbackResize, ImGuiExt::UpdateStringSizeCallback, &m_pathBuffer)) { m_path = m_pathBuffer; m_friendlyName = m_pathBuffer; } #endif return !m_path.empty(); } nlohmann::json DiskProvider::storeSettings(nlohmann::json settings) const { settings["path"] = wolv::io::fs::toNormalizedPathString(m_path); settings["friendly_name"] = m_friendlyName; return Provider::storeSettings(settings); } void DiskProvider::loadSettings(const nlohmann::json &settings) { Provider::loadSettings(settings); auto path = settings.at("path").get<std::string>(); if (settings.contains("friendly_name")) m_friendlyName = settings.at("friendly_name").get<std::string>(); this->setPath(std::u8string(path.begin(), path.end())); this->reloadDrives(); } std::pair<Region, bool> DiskProvider::getRegionValidity(u64 address) const { address -= this->getBaseAddress(); if (address < this->getActualSize()) return { Region { this->getBaseAddress() + address, this->getActualSize() - address }, true }; else return { Region::Invalid(), false }; } std::variant<std::string, i128> DiskProvider::queryInformation(const std::string &category, const std::string &argument) { if (category == "file_path") return wolv::io::fs::toNormalizedPathString(m_path); else if (category == "sector_size") return m_sectorSize; else if (category == "friendly_name") return m_friendlyName; else return Provider::queryInformation(category, argument); } } #endif
18,005
C++
.cpp
411
31.647202
212
0.561262
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
201
motorola_srec_provider.cpp
WerWolv_ImHex/plugins/builtin/source/content/providers/motorola_srec_provider.cpp
#include "content/providers/motorola_srec_provider.hpp" #include <hex/api/localization_manager.hpp> #include <hex/helpers/utils.hpp> #include <hex/helpers/fmt.hpp> #include <wolv/io/file.hpp> #include <wolv/io/fs.hpp> #include <wolv/utils/expected.hpp> #include <wolv/utils/string.hpp> namespace hex::plugin::builtin { namespace motorola_srec { u8 parseHexDigit(char c) { if (c >= '0' && c <= '9') return c - '0'; else if (c >= 'A' && c <= 'F') return c - 'A' + 10; else if (c >= 'a' && c <= 'f') return c - 'a' + 10; else throw std::runtime_error("Failed to parse hex digit"); } wolv::util::Expected<std::map<u64, std::vector<u8>>, std::string> parseMotorolaSREC(const std::string &string) { std::map<u64, std::vector<u8>> result; u64 offset = 0x00; u8 checksum = 0x00; u8 byteCount = 0x00; u32 address = 0x0000'0000; std::vector<u8> data; auto c = [&] { while (offset < string.length() && std::isspace(string[offset])) offset++; if (offset >= string.length()) throw std::runtime_error("Unexpected end of file"); return string[offset++]; }; auto parseValue = [&](u8 count) { u64 value = 0x00; for (u8 i = 0; i < count; i++) { u8 byte = (parseHexDigit(c()) << 4) | parseHexDigit(c()); value <<= 8; value |= byte; checksum += byte; } return value; }; enum class RecordType { Header = 0x00, Data16 = 0x01, Data24 = 0x02, Data32 = 0x03, Reserved = 0x04, Count16 = 0x05, Count24 = 0x06, StartAddress32 = 0x07, StartAddress24 = 0x08, StartAddress16 = 0x09, } recordType; bool endOfFile = false; try { while (offset < string.length()) { // Parse record start if (c() != 'S') return { }; if (endOfFile) throw std::runtime_error("Unexpected end of file"); // Parse record type { char typeCharacter = c(); if (typeCharacter < '0' || typeCharacter > '9') throw std::runtime_error("Invalid record type"); recordType = static_cast<RecordType>(typeCharacter - '0'); } checksum = 0x00; // Parse byte count byteCount = parseValue(1); // Parse address switch (recordType) { case RecordType::Reserved: break; case RecordType::Header: case RecordType::Data16: case RecordType::Count16: case RecordType::StartAddress16: byteCount -= 2; address = parseValue(2); break; case RecordType::Data24: case RecordType::Count24: case RecordType::StartAddress24: byteCount -= 3; address = parseValue(3); break; case RecordType::Data32: case RecordType::StartAddress32: byteCount -= 4; address = parseValue(4); break; } byteCount -= 1; auto readData = [&byteCount, &parseValue] { std::vector<u8> bytes; bytes.resize(byteCount); for (u8 i = 0; i < byteCount; i++) { bytes[i] = parseValue(1); } return bytes; }; // Parse data data = readData(); // Parse checksum { auto value = parseValue(1); if (((checksum - value) ^ 0xFF) != value) throw std::runtime_error("Invalid checksum"); } // Construct region switch (recordType) { case RecordType::Data16: case RecordType::Data24: case RecordType::Data32: result[address] = data; break; case RecordType::Header: case RecordType::Reserved: break; case RecordType::Count16: case RecordType::Count24: break; case RecordType::StartAddress32: case RecordType::StartAddress24: case RecordType::StartAddress16: endOfFile = true; break; } while (std::isspace(string[offset]) && offset < string.length()) offset++; } } catch (const std::runtime_error &e) { return wolv::util::Unexpected<std::string>(e.what()); } return result; } } bool MotorolaSRECProvider::open() { auto file = wolv::io::File(m_sourceFilePath, wolv::io::File::Mode::Read); if (!file.isValid()) { this->setErrorMessage(hex::format("hex.builtin.provider.file.error.open"_lang, m_sourceFilePath.string(), ::strerror(errno))); return false; } auto data = motorola_srec::parseMotorolaSREC(file.readString()); if (!data.has_value()) { this->setErrorMessage(data.error()); return false; } u64 maxAddress = 0x00; for (auto &[address, bytes] : data.value()) { auto endAddress = (address + bytes.size()) - 1; m_data.emplace({ address, endAddress }, std::move(bytes)); if (endAddress > maxAddress) maxAddress = endAddress; } m_dataSize = maxAddress + 1; m_dataValid = true; return true; } void MotorolaSRECProvider::close() { } [[nodiscard]] std::string MotorolaSRECProvider::getName() const { return hex::format("hex.builtin.provider.motorola_srec.name"_lang, wolv::util::toUTF8String(m_sourceFilePath.filename())); } [[nodiscard]] std::vector<MotorolaSRECProvider::Description> MotorolaSRECProvider::getDataDescription() const { std::vector<Description> result; result.emplace_back("hex.builtin.provider.file.path"_lang, wolv::util::toUTF8String(m_sourceFilePath)); result.emplace_back("hex.builtin.provider.file.size"_lang, hex::toByteString(this->getActualSize())); return result; } bool MotorolaSRECProvider::handleFilePicker() { auto picked = fs::openFileBrowser(fs::DialogMode::Open, { { "Motorola SREC File", "s19" }, { "Motorola SREC File", "s28" }, { "Motorola SREC File", "s37" }, { "Motorola SREC File", "s" }, { "Motorola SREC File", "s1" }, { "Motorola SREC File", "s2" }, { "Motorola SREC File", "s3" }, { "Motorola SREC File", "sx" }, { "Motorola SREC File", "srec" }, { "Motorola SREC File", "exo" }, { "Motorola SREC File", "mot" }, { "Motorola SREC File", "mxt" } }, [this](const std::fs::path &path) { m_sourceFilePath = path; } ); if (!picked) return false; if (!wolv::io::fs::isRegularFile(m_sourceFilePath)) return false; return true; } }
8,615
C++
.cpp
201
25.78607
138
0.444484
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
202
base64_provider.cpp
WerWolv_ImHex/plugins/builtin/source/content/providers/base64_provider.cpp
#include <content/providers/base64_provider.hpp> #include <hex/helpers/crypto.hpp> #include <hex/helpers/utils.hpp> namespace hex::plugin::builtin { void Base64Provider::readRaw(u64 offset, void *buffer, size_t size) { const u64 base64Offset = 4 * (offset / 3); const u64 base64Size = std::min<u64>(hex::alignTo<u64>(4 * (size / 3), 4) + 4, m_fileSize); std::vector<u8> bytes(base64Size); FileProvider::readRaw(base64Offset, bytes.data(), bytes.size()); auto decoded = crypt::decode64(bytes); if (decoded.empty()) return; u64 startOffset = offset % 3; std::memcpy(buffer, decoded.data() + startOffset, std::min<size_t>(decoded.size() - startOffset, size)); } void Base64Provider::writeRaw(u64 offset, const void *buffer, size_t size) { const u64 base64Offset = 4 * (offset / 3); const u64 base64Size = hex::alignTo<u64>(4 * (size / 3), 4) + 4; std::vector<u8> bytes(base64Size); FileProvider::readRaw(base64Offset, bytes.data(), bytes.size()); auto decoded = crypt::decode64(bytes); if (decoded.empty()) return; u64 startOffset = offset % 3; std::memcpy(decoded.data() + startOffset, buffer, std::min<size_t>(decoded.size() - startOffset, size)); auto encoded = crypt::encode64(decoded); if (encoded.empty()) return; FileProvider::writeRaw(base64Offset, encoded.data(), encoded.size()); } void Base64Provider::resizeRaw(u64 newSize) { u64 newFileLength = 4 * (newSize / 3); FileProvider::resizeRaw(newFileLength); } void Base64Provider::insertRaw(u64 offset, u64 size) { u64 newFileLength = 4 * ((getActualSize() + size) / 3); FileProvider::insertRaw(4 * (offset / 3), newFileLength); constexpr static auto NullByte = 0x00; for (u64 i = 0; i < size; i++) writeRaw(offset + i, &NullByte, 1); } void Base64Provider::removeRaw(u64 offset, u64 size) { u64 newFileLength = 4 * ((getActualSize() - size) / 3); FileProvider::removeRaw(4 * (offset / 3), newFileLength); } }
2,189
C++
.cpp
46
39.565217
112
0.625235
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
203
process_memory_provider.cpp
WerWolv_ImHex/plugins/builtin/source/content/providers/process_memory_provider.cpp
#if defined(OS_WINDOWS) || defined(OS_MACOS) || (defined(OS_LINUX) && !defined(OS_FREEBSD)) #include <content/providers/process_memory_provider.hpp> #if defined(OS_WINDOWS) #include <windows.h> #include <psapi.h> #include <shellapi.h> #elif defined(OS_MACOS) #include <mach/mach_types.h> #include <mach/message.h> #include <mach/arm/kern_return.h> #include <mach/arm/vm_types.h> #include <mach/vm_map.h> #include <mach-o/dyld_images.h> #include <libproc.h> #elif defined(OS_LINUX) #include <sys/uio.h> #endif #include <imgui.h> #include <hex/ui/imgui_imhex_extensions.h> #include <hex/helpers/utils.hpp> #include <hex/helpers/fmt.hpp> #include <hex/ui/view.hpp> #include <toasts/toast_notification.hpp> #include <wolv/io/fs.hpp> #include <wolv/io/file.hpp> #include <wolv/utils/guards.hpp> namespace hex::plugin::builtin { bool ProcessMemoryProvider::open() { #if defined(OS_WINDOWS) m_processHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, m_selectedProcess->id); if (m_processHandle == nullptr) return false; #else m_processId = pid_t(m_selectedProcess->id); #endif this->reloadProcessModules(); return true; } void ProcessMemoryProvider::close() { #if defined(OS_WINDOWS) CloseHandle(m_processHandle); m_processHandle = nullptr; #else m_processId = -1; #endif } void ProcessMemoryProvider::readRaw(u64 address, void *buffer, size_t size) { #if defined(OS_WINDOWS) ReadProcessMemory(m_processHandle, reinterpret_cast<LPCVOID>(address), buffer, size, nullptr); #elif defined(OS_MACOS) task_t t; task_for_pid(mach_task_self(), m_processId, &t); vm_size_t dataSize = 0; vm_read_overwrite(t, address, size, reinterpret_cast<vm_address_t>(buffer), &dataSize ); #elif defined(OS_LINUX) const iovec local { .iov_base = buffer, .iov_len = size, }; const iovec remote = { .iov_base = reinterpret_cast<void*>(address), .iov_len = size, }; auto read = process_vm_readv(m_processId, &local, 1, &remote, 1, 0); hex::unused(read); #endif } void ProcessMemoryProvider::writeRaw(u64 address, const void *buffer, size_t size) { #if defined(OS_WINDOWS) WriteProcessMemory(m_processHandle, reinterpret_cast<LPVOID>(address), buffer, size, nullptr); #elif defined(OS_MACOS) task_t t; task_for_pid(mach_task_self(), m_processId, &t); vm_write(t, address, reinterpret_cast<vm_address_t>(buffer), size ); #elif defined(OS_LINUX) const iovec local { .iov_base = const_cast<void*>(buffer), .iov_len = size, }; const iovec remote = { .iov_base = reinterpret_cast<void*>(address), .iov_len = size, }; auto write = process_vm_writev(m_processId, &local, 1, &remote, 1, 0); hex::unused(write); #endif } std::pair<Region, bool> ProcessMemoryProvider::getRegionValidity(u64 address) const { for (const auto &memoryRegion : m_memoryRegions) { if (memoryRegion.region.overlaps({ address, 1LLU })) return { memoryRegion.region, true }; } Region lastRegion = Region::Invalid(); for (const auto &memoryRegion : m_memoryRegions) { if (address < memoryRegion.region.getStartAddress()) return { Region { lastRegion.getEndAddress() + 1LLU, memoryRegion.region.getStartAddress() - lastRegion.getEndAddress() }, false }; lastRegion = memoryRegion.region; } return { Region::Invalid(), false }; } bool ProcessMemoryProvider::drawLoadInterface() { if (m_processes.empty() && !m_enumerationFailed) { #if defined(OS_WINDOWS) DWORD numProcesses = 0; std::vector<DWORD> processIds; do { processIds.resize(processIds.size() + 1024); if (EnumProcesses(processIds.data(), processIds.size() * sizeof(DWORD), &numProcesses) == FALSE) { processIds.clear(); m_enumerationFailed = true; break; } } while (numProcesses == processIds.size() * sizeof(DWORD)); processIds.resize(numProcesses / sizeof(DWORD)); auto dc = GetDC(nullptr); ON_SCOPE_EXIT { ReleaseDC(nullptr, dc); }; for (auto processId : processIds) { HANDLE processHandle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processId); if (processHandle == nullptr) continue; ON_SCOPE_EXIT { CloseHandle(processHandle); }; char processName[MAX_PATH]; if (GetModuleBaseNameA(processHandle, nullptr, processName, MAX_PATH) == 0) continue; ImGuiExt::Texture texture; { HMODULE moduleHandle = nullptr; DWORD numModules = 0; if (EnumProcessModules(processHandle, &moduleHandle, sizeof(HMODULE), &numModules) != FALSE) { char modulePath[MAX_PATH]; if (GetModuleFileNameExA(processHandle, moduleHandle, modulePath, MAX_PATH) != FALSE) { SHFILEINFOA fileInfo; if (SHGetFileInfoA(modulePath, 0, &fileInfo, sizeof(SHFILEINFOA), SHGFI_ICON | SHGFI_SMALLICON) > 0) { ON_SCOPE_EXIT { DestroyIcon(fileInfo.hIcon); }; ICONINFO iconInfo; if (GetIconInfo(fileInfo.hIcon, &iconInfo) != FALSE) { ON_SCOPE_EXIT { DeleteObject(iconInfo.hbmColor); DeleteObject(iconInfo.hbmMask); }; BITMAP bitmap; if (GetObject(iconInfo.hbmColor, sizeof(BITMAP), &bitmap) > 0) { BITMAPINFO bitmapInfo = { }; bitmapInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bitmapInfo.bmiHeader.biWidth = bitmap.bmWidth; bitmapInfo.bmiHeader.biHeight = -bitmap.bmHeight; bitmapInfo.bmiHeader.biPlanes = 1; bitmapInfo.bmiHeader.biBitCount = 32; bitmapInfo.bmiHeader.biCompression = BI_RGB; std::vector<u32> pixels(bitmap.bmWidth * bitmap.bmHeight * 4); if (GetDIBits(dc, iconInfo.hbmColor, 0, bitmap.bmHeight, pixels.data(), &bitmapInfo, DIB_RGB_COLORS) > 0) { for (auto &pixel : pixels) pixel = (pixel & 0xFF00FF00) | ((pixel & 0xFF) << 16) | ((pixel & 0xFF0000) >> 16); texture = ImGuiExt::Texture::fromBitmap(reinterpret_cast<const u8*>(pixels.data()), pixels.size(), bitmap.bmWidth, bitmap.bmHeight, ImGuiExt::Texture::Filter::Nearest); } } } } } } } m_processes.push_back({ u32(processId), processName, std::move(texture) }); } #elif defined(OS_MACOS) std::array<pid_t, 2048> pids; const auto bytes = proc_listpids(PROC_ALL_PIDS, 0, pids.data(), sizeof(pids)); const auto processCount = bytes / sizeof(pid_t); for (u32 i = 0; i < processCount; i += 1) { proc_bsdinfo proc; const auto result = proc_pidinfo(pids[i], PROC_PIDTBSDINFO, 0, &proc, PROC_PIDTBSDINFO_SIZE); if (result == PROC_PIDTBSDINFO_SIZE) { m_processes.emplace_back(pids[i], proc.pbi_name, ImGuiExt::Texture()); } } #elif defined(OS_LINUX) for (const auto& entry : std::fs::directory_iterator("/proc")) { if (!std::fs::is_directory(entry)) continue; const auto &path = entry.path(); u32 processId = 0; try { processId = std::stoi(path.filename()); } catch (...) { continue; // not a PID } wolv::io::File file(path /"cmdline", wolv::io::File::Mode::Read); if (!file.isValid()) continue; std::string processName = file.readString(0xF'FFFF); m_processes.emplace_back(processId, processName, ImGuiExt::Texture()); } #endif } if (m_enumerationFailed) { ImGui::TextUnformatted("hex.builtin.provider.process_memory.enumeration_failed"_lang); } else { #if defined(OS_MACOS) ImGuiExt::TextFormattedWrapped("{}", "hex.builtin.provider.process_memory.macos_limitations"_lang); ImGui::NewLine(); #endif ImGui::PushItemWidth(500_scaled); const auto &filtered = m_processSearchWidget.draw(m_processes); ImGui::PopItemWidth(); if (ImGui::BeginTable("##process_table", 3, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_ScrollY, ImVec2(500_scaled, 500_scaled))) { ImGui::TableSetupColumn("##icon"); ImGui::TableSetupColumn("hex.builtin.provider.process_memory.process_id"_lang); ImGui::TableSetupColumn("hex.builtin.provider.process_memory.process_name"_lang); ImGui::TableSetupScrollFreeze(0, 1); ImGui::TableHeadersRow(); for (auto &process : filtered) { ImGui::PushID(process); ImGui::TableNextRow(); ImGui::TableNextColumn(); ImGui::Image(process->icon, process->icon.getSize()); ImGui::TableNextColumn(); ImGuiExt::TextFormatted("{}", process->id); ImGui::TableNextColumn(); if (ImGui::Selectable(process->name.c_str(), m_selectedProcess != nullptr && process->id == m_selectedProcess->id, ImGuiSelectableFlags_SpanAllColumns, ImVec2(0, process->icon.getSize().y))) m_selectedProcess = process; ImGui::PopID(); } ImGui::EndTable(); } } return m_selectedProcess != nullptr; } void ProcessMemoryProvider::drawInterface() { ImGuiExt::Header("hex.builtin.provider.process_memory.memory_regions"_lang, true); auto availableX = ImGui::GetContentRegionAvail().x; ImGui::PushItemWidth(availableX); const auto &filtered = m_regionSearchWidget.draw(m_memoryRegions); ImGui::PopItemWidth(); #if defined(OS_WINDOWS) auto availableY = 400_scaled; #else // Take up full height on Linux since there are no DLL injection controls auto availableY = ImGui::GetContentRegionAvail().y; #endif if (ImGui::BeginTable("##module_table", 3, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_ScrollY, ImVec2(availableX, availableY))) { ImGui::TableSetupColumn("hex.ui.common.region"_lang); ImGui::TableSetupColumn("hex.ui.common.size"_lang); ImGui::TableSetupColumn("hex.ui.common.name"_lang); ImGui::TableSetupScrollFreeze(0, 1); ImGui::TableHeadersRow(); for (const auto &memoryRegion : filtered) { ImGui::PushID(&memoryRegion); ImGui::TableNextRow(); ImGui::TableNextColumn(); ImGuiExt::TextFormatted("0x{0:016X} - 0x{1:016X}", memoryRegion->region.getStartAddress(), memoryRegion->region.getEndAddress()); ImGui::TableNextColumn(); ImGui::TextUnformatted(hex::toByteString(memoryRegion->region.getSize()).c_str()); ImGui::TableNextColumn(); if (ImGui::Selectable(memoryRegion->name.c_str(), false, ImGuiSelectableFlags_SpanAllColumns)) ImHexApi::HexEditor::setSelection(memoryRegion->region); ImGui::PopID(); } ImGui::EndTable(); } #if defined(OS_WINDOWS) ImGuiExt::Header("hex.builtin.provider.process_memory.utils"_lang); if (ImGui::Button("hex.builtin.provider.process_memory.utils.inject_dll"_lang)) { hex::fs::openFileBrowser(fs::DialogMode::Open, { { "DLL File", "dll" } }, [this](const std::fs::path &path) { const auto &dllPath = path.native(); const auto dllPathLength = (dllPath.length() + 1) * sizeof(std::fs::path::value_type); if (auto pathAddress = VirtualAllocEx(m_processHandle, nullptr, dllPathLength, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); pathAddress != nullptr) { if (WriteProcessMemory(m_processHandle, pathAddress, dllPath.c_str(), dllPathLength, nullptr) != FALSE) { auto loadLibraryW = reinterpret_cast<LPTHREAD_START_ROUTINE>(reinterpret_cast<void*>(GetProcAddress(GetModuleHandleA("kernel32.dll"), "LoadLibraryW"))); if (loadLibraryW != nullptr) { if (auto threadHandle = CreateRemoteThread(m_processHandle, nullptr, 0, loadLibraryW, pathAddress, 0, nullptr); threadHandle != nullptr) { WaitForSingleObject(threadHandle, INFINITE); ui::ToastInfo::open(hex::format("hex.builtin.provider.process_memory.utils.inject_dll.success"_lang, path.filename().string())); this->reloadProcessModules(); CloseHandle(threadHandle); return; } } } } ui::ToastError::open(hex::format("hex.builtin.provider.process_memory.utils.inject_dll.failure"_lang, path.filename().string())); }); } #endif } void ProcessMemoryProvider::reloadProcessModules() { m_memoryRegions.clear(); #if defined(OS_WINDOWS) DWORD numModules = 0; std::vector<HMODULE> modules; do { modules.resize(modules.size() + 1024); if (EnumProcessModules(m_processHandle, modules.data(), modules.size() * sizeof(HMODULE), &numModules) == FALSE) { modules.clear(); break; } } while (numModules == modules.size() * sizeof(HMODULE)); modules.resize(numModules / sizeof(HMODULE)); for (auto &module : modules) { MODULEINFO moduleInfo; if (GetModuleInformation(m_processHandle, module, &moduleInfo, sizeof(MODULEINFO)) == FALSE) continue; char moduleName[MAX_PATH]; if (GetModuleFileNameExA(m_processHandle, module, moduleName, MAX_PATH) == FALSE) continue; m_memoryRegions.insert({ { u64(moduleInfo.lpBaseOfDll), size_t(moduleInfo.SizeOfImage) }, std::fs::path(moduleName).filename().string() }); } MEMORY_BASIC_INFORMATION memoryInfo; for (u64 address = 0; address < this->getActualSize(); address += memoryInfo.RegionSize) { if (VirtualQueryEx(m_processHandle, reinterpret_cast<LPCVOID>(address), &memoryInfo, sizeof(MEMORY_BASIC_INFORMATION)) == 0) break; std::string name; if (memoryInfo.State & MEM_IMAGE) continue; if (memoryInfo.State & MEM_FREE) continue; if (memoryInfo.State & MEM_COMMIT) name += hex::format("{} ", "hex.builtin.provider.process_memory.region.commit"_lang); if (memoryInfo.State & MEM_RESERVE) name += hex::format("{} ", "hex.builtin.provider.process_memory.region.reserve"_lang); if (memoryInfo.State & MEM_PRIVATE) name += hex::format("{} ", "hex.builtin.provider.process_memory.region.private"_lang); if (memoryInfo.State & MEM_MAPPED) name += hex::format("{} ", "hex.builtin.provider.process_memory.region.mapped"_lang); m_memoryRegions.insert({ { reinterpret_cast<u64>(memoryInfo.BaseAddress), reinterpret_cast<u64>(memoryInfo.BaseAddress) + memoryInfo.RegionSize }, name }); } #elif defined(OS_MACOS) vm_region_submap_info_64 info; mach_msg_type_number_t count = VM_REGION_SUBMAP_INFO_COUNT_64; vm_address_t address = 0; vm_size_t size = 0; natural_t depth = 0; while (true) { if (vm_region_recurse_64(mach_task_self(), &address, &size, &depth, reinterpret_cast<vm_region_info_64_t>(&info), &count) != KERN_SUCCESS) break; // Get region name std::array<char, 1024> name; if (proc_regionfilename(m_processId, address, name.data(), name.size()) != 0) { std::strcpy(name.data(), "???"); } m_memoryRegions.insert({ { address, size }, name.data() }); address += size; } #elif defined(OS_LINUX) wolv::io::File file(std::fs::path("/proc") / std::to_string(m_processId) / "maps", wolv::io::File::Mode::Read); if (!file.isValid()) return; // procfs files don't have a defined size, so we have to just keep reading until we stop getting data std::string data; while (true) { auto chunk = file.readString(0xFFFF); if (chunk.empty()) break; data.append(chunk); } for (const auto &line : wolv::util::splitString(data, "\n")) { const auto &split = splitString(line, " "); if (split.size() < 5) continue; const u64 start = std::stoull(split[0].substr(0, split[0].find('-')), nullptr, 16); const u64 end = std::stoull(split[0].substr(split[0].find('-') + 1), nullptr, 16); std::string name; if (split.size() > 5) name = wolv::util::trim(combineStrings(std::vector(split.begin() + 5, split.end()), " ")); m_memoryRegions.insert({ { start, end - start }, name }); } #endif } std::variant<std::string, i128> ProcessMemoryProvider::queryInformation(const std::string &category, const std::string &argument) { auto findRegionByName = [this](const std::string &name) { return std::find_if(m_memoryRegions.begin(), m_memoryRegions.end(), [name](const auto &region) { return region.name == name; }); }; if (category == "region_address") { if (auto iter = findRegionByName(argument); iter != m_memoryRegions.end()) return iter->region.getStartAddress(); else return 0; } else if (category == "region_size") { if (auto iter = findRegionByName(argument); iter != m_memoryRegions.end()) return iter->region.getSize(); else return 0; } else if (category == "process_id") { return m_selectedProcess->id; } else if (category == "process_name") { return m_selectedProcess->name; } else { return Provider::queryInformation(category, argument); } } } #endif
21,174
C++
.cpp
393
37.282443
216
0.533443
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
204
memory_file_provider.cpp
WerWolv_ImHex/plugins/builtin/source/content/providers/memory_file_provider.cpp
#include "content/providers/memory_file_provider.hpp" #include "content/providers/file_provider.hpp" #include <popups/popup_text_input.hpp> #include <cstring> #include <hex/api/imhex_api.hpp> #include <hex/api/localization_manager.hpp> #include <hex/api/event_manager.hpp> #include <wolv/io/file.hpp> #include <nlohmann/json.hpp> namespace hex::plugin::builtin { bool MemoryFileProvider::open() { if (m_data.empty()) { m_data.resize(1); } return true; } void MemoryFileProvider::readRaw(u64 offset, void *buffer, size_t size) { auto actualSize = this->getActualSize(); if (actualSize == 0 || (offset + size) > actualSize || buffer == nullptr || size == 0) return; std::memcpy(buffer, &m_data.front() + offset, size); } void MemoryFileProvider::writeRaw(u64 offset, const void *buffer, size_t size) { if ((offset + size) > this->getActualSize() || buffer == nullptr || size == 0) return; std::memcpy(&m_data.front() + offset, buffer, size); } void MemoryFileProvider::save() { if (!m_name.empty()) return; fs::openFileBrowser(fs::DialogMode::Save, { }, [this](const std::fs::path &path) { if (path.empty()) return; this->saveAs(path); auto newProvider = hex::ImHexApi::Provider::createProvider("hex.builtin.provider.file", true); if (auto fileProvider = dynamic_cast<FileProvider*>(newProvider); fileProvider != nullptr) { fileProvider->setPath(path); if (!fileProvider->open()) { ImHexApi::Provider::remove(newProvider); } else { MovePerProviderData::post(this, fileProvider); fileProvider->markDirty(false); EventProviderOpened::post(newProvider); ImHexApi::Provider::remove(this, true); } } }); } void MemoryFileProvider::resizeRaw(u64 newSize) { m_data.resize(newSize); } [[nodiscard]] std::string MemoryFileProvider::getName() const { if (m_name.empty()) return Lang("hex.builtin.provider.mem_file.unsaved"); else return m_name; } std::vector<MemoryFileProvider::MenuEntry> MemoryFileProvider::getMenuEntries() { return { MenuEntry { Lang("hex.builtin.provider.mem_file.rename"), [this] { this->renameFile(); } } }; } std::pair<Region, bool> MemoryFileProvider::getRegionValidity(u64 address) const { address -= this->getBaseAddress(); if (address < this->getActualSize()) return { Region { this->getBaseAddress() + address, this->getActualSize() - address }, true }; else return { Region::Invalid(), false }; } void MemoryFileProvider::loadSettings(const nlohmann::json &settings) { Provider::loadSettings(settings); m_data = settings["data"].get<std::vector<u8>>(); m_name = settings["name"].get<std::string>(); m_readOnly = settings["readOnly"].get<bool>(); } [[nodiscard]] nlohmann::json MemoryFileProvider::storeSettings(nlohmann::json settings) const { settings["data"] = m_data; settings["name"] = m_name; settings["readOnly"] = m_readOnly; return Provider::storeSettings(settings); } void MemoryFileProvider::renameFile() { ui::PopupTextInput::open("hex.builtin.provider.rename", "hex.builtin.provider.rename.desc", [this](const std::string &name) { m_name = name; RequestUpdateWindowTitle::post(); }); } }
3,740
C++
.cpp
88
33.306818
133
0.604195
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
205
demangler.cpp
WerWolv_ImHex/plugins/builtin/source/content/tools/demangler.cpp
#include <hex/helpers/utils.hpp> #include <hex/api/localization_manager.hpp> #include <content/helpers/demangle.hpp> #include <imgui.h> #include <hex/ui/imgui_imhex_extensions.h> #include <TextEditor.h> namespace hex::plugin::builtin { void drawDemangler() { static std::string mangledName, demangledName, wrappedDemangledName; static TextEditor outputField = []{ TextEditor editor; editor.SetReadOnly(true); editor.SetShowLineNumbers(false); editor.SetShowWhitespaces(false); editor.SetShowCursor(false); editor.SetImGuiChildIgnored(true); auto languageDef = TextEditor::LanguageDefinition::CPlusPlus(); for (auto &[name, identifier] : languageDef.mIdentifiers) identifier.mDeclaration = ""; editor.SetLanguageDefinition(languageDef); return editor; }(); static float prevWindowWidth; if (ImGui::InputTextWithHint("hex.builtin.tools.demangler.mangled"_lang, "Itanium, MSVC, Dlang & Rust", mangledName)) { demangledName = hex::plugin::builtin::demangle(mangledName); if (demangledName == mangledName) { demangledName = "???"; } prevWindowWidth = 0; } const auto windowWidth = ImGui::GetContentRegionAvail().x; if (prevWindowWidth != windowWidth) { wrappedDemangledName = wolv::util::wrapMonospacedString( demangledName, ImGui::CalcTextSize("M").x, ImGui::GetContentRegionAvail().x - ImGui::GetStyle().ScrollbarSize - ImGui::GetStyle().FrameBorderSize ); outputField.SetText(wrappedDemangledName); prevWindowWidth = windowWidth; } ImGuiExt::Header("hex.builtin.tools.demangler.demangled"_lang); if (ImGui::BeginChild("Demangled", ImVec2(ImGui::GetContentRegionAvail().x, 150_scaled), true, ImGuiWindowFlags_NoMove)) { outputField.Render("Demangled", ImVec2(ImGui::GetContentRegionAvail().x, 150_scaled), true); } ImGui::EndChild(); } }
2,171
C++
.cpp
47
35.914894
130
0.640417
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
206
base_converter.cpp
WerWolv_ImHex/plugins/builtin/source/content/tools/base_converter.cpp
#include <hex/helpers/utils.hpp> #include <hex/helpers/fmt.hpp> #include <hex/api/localization_manager.hpp> #include <hex/ui/imgui_imhex_extensions.h> #include <fonts/codicons_font.h> namespace hex::plugin::builtin { void drawBaseConverter() { static std::array<std::string, 4> buffers; static auto ConvertBases = [](u8 base) { u64 number; switch (base) { case 16: number = std::strtoull(buffers[1].c_str(), nullptr, base); break; case 10: number = std::strtoull(buffers[0].c_str(), nullptr, base); break; case 8: number = std::strtoull(buffers[2].c_str(), nullptr, base); break; case 2: number = std::strtoull(buffers[3].c_str(), nullptr, base); break; default: return; } buffers[0] = std::to_string(number); buffers[1] = hex::format("0x{0:X}", number); buffers[2] = hex::format("{0:#o}", number); buffers[3] = hex::toBinaryString(number); }; if (ImGuiExt::InputTextIcon("hex.builtin.tools.base_converter.dec"_lang, ICON_VS_SYMBOL_NUMERIC, buffers[0])) ConvertBases(10); if (ImGuiExt::InputTextIcon("hex.builtin.tools.base_converter.hex"_lang, ICON_VS_SYMBOL_NUMERIC, buffers[1])) ConvertBases(16); if (ImGuiExt::InputTextIcon("hex.builtin.tools.base_converter.oct"_lang, ICON_VS_SYMBOL_NUMERIC, buffers[2])) ConvertBases(8); if (ImGuiExt::InputTextIcon("hex.builtin.tools.base_converter.bin"_lang, ICON_VS_SYMBOL_NUMERIC, buffers[3])) ConvertBases(2); } }
1,827
C++
.cpp
41
32.170732
117
0.553239
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
207
perms_calc.cpp
WerWolv_ImHex/plugins/builtin/source/content/tools/perms_calc.cpp
#include <hex/helpers/fmt.hpp> #include <hex/api/localization_manager.hpp> #include <imgui.h> #include <hex/ui/imgui_imhex_extensions.h> namespace hex::plugin::builtin { void drawPermissionsCalculator() { static bool setuid, setgid, sticky; static bool r[3], w[3], x[3]; ImGuiExt::Header("hex.builtin.tools.permissions.perm_bits"_lang, true); if (ImGui::BeginTable("Permissions", 4, ImGuiTableFlags_Borders)) { ImGui::TableSetupColumn("Special", ImGuiTableColumnFlags_NoSort); ImGui::TableSetupColumn("User", ImGuiTableColumnFlags_NoSort); ImGui::TableSetupColumn("Group", ImGuiTableColumnFlags_NoSort); ImGui::TableSetupColumn("Other", ImGuiTableColumnFlags_NoSort); ImGui::TableSetupScrollFreeze(0, 1); ImGui::TableHeadersRow(); ImGui::TableNextRow(); ImGui::TableNextColumn(); ImGui::Checkbox("setuid", &setuid); ImGui::Checkbox("setgid", &setgid); ImGui::Checkbox("Sticky bit", &sticky); for (u8 i = 0; i < 3; i++) { ImGui::TableNextColumn(); ImGui::PushID(i); ImGui::Checkbox("Read", &r[i]); ImGui::Checkbox("Write", &w[i]); ImGui::Checkbox("Execute", &x[i]); ImGui::PopID(); } ImGui::EndTable(); } ImGuiExt::Header("hex.builtin.tools.permissions.absolute"_lang); auto result = hex::format("{}{}{}{}", (setuid << 2) | (setgid << 1) | (sticky << 0), (r[0] << 2) | (w[0] << 1) | (x[0] << 0), (r[1] << 2) | (w[1] << 1) | (x[1] << 0), (r[2] << 2) | (w[2] << 1) | (x[2] << 0)); ImGui::InputText("##permissions_absolute", result.data(), result.size(), ImGuiInputTextFlags_ReadOnly); ImGui::NewLine(); constexpr static auto WarningColor = ImColor(0.92F, 0.25F, 0.2F, 1.0F); if (setuid && !x[0]) ImGuiExt::TextFormattedColored(WarningColor, "{}", "hex.builtin.tools.permissions.setuid_error"_lang); if (setgid && !x[1]) ImGuiExt::TextFormattedColored(WarningColor, "{}", "hex.builtin.tools.permissions.setgid_error"_lang); if (sticky && !x[2]) ImGuiExt::TextFormattedColored(WarningColor, "{}", "hex.builtin.tools.permissions.sticky_error"_lang); } }
2,424
C++
.cpp
48
39.583333
114
0.571186
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
208
tcp_client_server.cpp
WerWolv_ImHex/plugins/builtin/source/content/tools/tcp_client_server.cpp
#include <hex/api/localization_manager.hpp> #include <hex/helpers/utils.hpp> #include <wolv/net/socket_client.hpp> #include <wolv/net/socket_server.hpp> #include <fonts/codicons_font.h> #include <imgui.h> #include <hex/ui/imgui_imhex_extensions.h> #include <jthread.hpp> #include <string> #include <vector> namespace hex::plugin::builtin { using namespace std::literals::chrono_literals; void drawTCPClientServer() { if (ImGui::BeginTabBar("##tcpTransceiver", ImGuiTabBarFlags_None)) { if (ImGui::BeginTabItem("hex.builtin.tools.tcp_client_server.client"_lang)) { static wolv::net::SocketClient client; static std::string ipAddress; static int port; static std::vector<std::string> messages; static std::string input; static std::jthread receiverThread; static std::mutex receiverMutex; ImGuiExt::Header("hex.builtin.tools.tcp_client_server.settings"_lang, true); ImGui::BeginDisabled(client.isConnected()); { ImGui::PushItemWidth(ImGui::GetContentRegionAvail().x * 0.3F); ImGui::InputText("##ipAddress", ipAddress); ImGui::PopItemWidth(); ImGui::SameLine(0, 0); ImGui::TextUnformatted(":"); ImGui::SameLine(0, 0); ImGui::PushItemWidth(ImGui::GetContentRegionAvail().x * 0.2F); ImGui::InputInt("##port", &port, 0, 0); ImGui::PopItemWidth(); } ImGui::EndDisabled(); ImGui::SameLine(); ImGui::PushItemWidth(ImGui::GetContentRegionAvail().x * 0.2F); if (client.isConnected()) { if (ImGuiExt::IconButton(ICON_VS_DEBUG_DISCONNECT, ImGuiExt::GetCustomColorVec4(ImGuiCustomCol_ToolbarRed))) { client.disconnect(); receiverThread.request_stop(); receiverThread.join(); } } else { if (ImGuiExt::IconButton(ICON_VS_PLAY, ImGuiExt::GetCustomColorVec4(ImGuiCustomCol_ToolbarGreen))) { client.connect(ipAddress, port); receiverThread = std::jthread([](const std::stop_token& stopToken) { while (!stopToken.stop_requested()) { auto message = client.readString(); if (!message.empty()) { std::scoped_lock lock(receiverMutex); messages.push_back(message); } } }); } } ImGui::PopItemWidth(); if (port < 1) port = 1; else if (port > 65535) port = 65535; ImGuiExt::Header("hex.builtin.tools.tcp_client_server.messages"_lang); if (ImGui::BeginTable("##response", 1, ImGuiTableFlags_ScrollY | ImGuiTableFlags_RowBg | ImGuiTableFlags_Borders, ImVec2(0, 200_scaled))) { { std::scoped_lock lock(receiverMutex); for (const auto &message : messages) { ImGui::TableNextRow(); ImGui::TableNextColumn(); ImGuiExt::TextFormattedSelectable("{}", message.c_str()); } } ImGui::EndTable(); } ImGui::BeginDisabled(!client.isConnected()); { ImGui::PushItemWidth(-(50_scaled)); bool pressedEnter = ImGui::InputText("##input", input, ImGuiInputTextFlags_EnterReturnsTrue); ImGui::PopItemWidth(); ImGui::SameLine(); if (pressedEnter) ImGui::SetKeyboardFocusHere(-1); if (ImGuiExt::IconButton(ICON_VS_DEBUG_STACKFRAME, ImGui::GetStyleColorVec4(ImGuiCol_Text)) || pressedEnter) { client.writeString(input); input.clear(); } } ImGui::EndDisabled(); ImGui::EndTabItem(); } if (ImGui::BeginTabItem("hex.builtin.tools.tcp_client_server.server"_lang)) { static wolv::net::SocketServer server; static int port; static std::vector<std::string> messages; static std::mutex receiverMutex; static std::jthread receiverThread; ImGuiExt::Header("hex.builtin.tools.tcp_client_server.settings"_lang, true); ImGui::BeginDisabled(server.isActive()); { ImGui::PushItemWidth(ImGui::GetContentRegionAvail().x * 0.2F); ImGui::InputInt("##port", &port, 0, 0); ImGui::PopItemWidth(); } ImGui::EndDisabled(); ImGui::SameLine(); if (port < 1) port = 1; else if (port > 65535) port = 65535; ImGui::PushItemWidth(ImGui::GetContentRegionAvail().x * 0.2F); if (server.isActive()) { if (ImGuiExt::IconButton(ICON_VS_DEBUG_DISCONNECT, ImGuiExt::GetCustomColorVec4(ImGuiCustomCol_ToolbarRed))) { server.shutdown(); receiverThread.request_stop(); receiverThread.join(); } } else { if (ImGuiExt::IconButton(ICON_VS_PLAY, ImGuiExt::GetCustomColorVec4(ImGuiCustomCol_ToolbarGreen))) { receiverThread = std::jthread([](const std::stop_token& stopToken){ server = wolv::net::SocketServer(port); while (!stopToken.stop_requested()) { server.accept([](wolv::net::SocketHandle, const std::vector<u8> &data) -> std::vector<u8> { std::scoped_lock lock(receiverMutex); messages.emplace_back(data.begin(), data.end()); return {}; }, nullptr, true); std::this_thread::sleep_for(100ms); } }); } } ImGui::PopItemWidth(); ImGuiExt::Header("hex.builtin.tools.tcp_client_server.messages"_lang); if (ImGui::BeginTable("##response", 1, ImGuiTableFlags_ScrollY | ImGuiTableFlags_RowBg | ImGuiTableFlags_Borders, ImVec2(0, 200_scaled))) { { std::scoped_lock lock(receiverMutex); u32 index = 0; for (const auto &message : messages) { ImGui::TableNextRow(); ImGui::TableNextColumn(); ImGui::PushID(index); ImGuiExt::TextFormattedSelectable("{}", message.c_str()); ImGui::PopID(); index += 1; } } ImGui::EndTable(); } ImGui::EndTabItem(); } ImGui::EndTabBar(); } } }
7,804
C++
.cpp
155
30.412903
155
0.472405
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
209
ascii_table.cpp
WerWolv_ImHex/plugins/builtin/source/content/tools/ascii_table.cpp
#include <hex/helpers/utils.hpp> #include <hex/api/localization_manager.hpp> #include <imgui.h> #include <hex/ui/imgui_imhex_extensions.h> namespace hex::plugin::builtin { void drawASCIITable() { static bool asciiTableShowOctal = false; ImGui::BeginTable("##asciitable", 4); ImGui::TableSetupColumn(""); ImGui::TableSetupColumn(""); ImGui::TableSetupColumn(""); ImGui::TableSetupColumn(""); ImGui::TableNextColumn(); for (u8 tablePart = 0; tablePart < 4; tablePart++) { ImGui::BeginTable("##asciitablepart", asciiTableShowOctal ? 4 : 3, ImGuiTableFlags_BordersInnerV | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_RowBg); ImGui::TableSetupColumn("dec"); if (asciiTableShowOctal) ImGui::TableSetupColumn("oct"); ImGui::TableSetupColumn("hex"); ImGui::TableSetupColumn("char"); ImGui::TableHeadersRow(); for (u8 i = 0; i < 0x80 / 4; i++) { ImGui::TableNextRow(); ImGui::TableNextColumn(); ImGuiExt::TextFormatted("{0:03d}", i + 32 * tablePart); if (asciiTableShowOctal) { ImGui::TableNextColumn(); ImGuiExt::TextFormatted("0o{0:03o}", i + 32 * tablePart); } ImGui::TableNextColumn(); ImGuiExt::TextFormatted("0x{0:02X}", i + 32 * tablePart); ImGui::TableNextColumn(); ImGuiExt::TextFormatted("{0}", hex::makePrintable(i + 32 * tablePart)); } ImGui::EndTable(); ImGui::TableNextColumn(); } ImGui::EndTable(); ImGui::Checkbox("hex.builtin.tools.ascii_table.octal"_lang, &asciiTableShowOctal); } }
1,828
C++
.cpp
41
33.02439
165
0.575706
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
210
file_tool_splitter.cpp
WerWolv_ImHex/plugins/builtin/source/content/tools/file_tool_splitter.cpp
#include <hex/helpers/http_requests.hpp> #include <hex/helpers/fmt.hpp> #include <hex/helpers/literals.hpp> #include <hex/helpers/fs.hpp> #include <hex/api/localization_manager.hpp> #include <hex/api/task_manager.hpp> #include <algorithm> #include <imgui.h> #include <hex/ui/imgui_imhex_extensions.h> #include <toasts/toast_notification.hpp> #include <wolv/io/file.hpp> #include <wolv/utils/guards.hpp> namespace hex::plugin::builtin { using namespace hex::literals; void drawFileToolSplitter() { std::array sizeText = { static_cast<const char*>("hex.builtin.tools.file_tools.splitter.sizes.5_75_floppy"_lang), static_cast<const char*>("hex.builtin.tools.file_tools.splitter.sizes.3_5_floppy"_lang), static_cast<const char*>("hex.builtin.tools.file_tools.splitter.sizes.zip100"_lang), static_cast<const char*>("hex.builtin.tools.file_tools.splitter.sizes.zip200"_lang), static_cast<const char*>("hex.builtin.tools.file_tools.splitter.sizes.cdrom650"_lang), static_cast<const char*>("hex.builtin.tools.file_tools.splitter.sizes.cdrom700"_lang), static_cast<const char*>("hex.builtin.tools.file_tools.splitter.sizes.fat32"_lang), static_cast<const char*>("hex.builtin.tools.file_tools.splitter.sizes.custom"_lang) }; std::array<u64, sizeText.size()> sizes = { 1200_KiB, 1400_KiB, 100_MiB, 200_MiB, 650_MiB, 700_MiB, 4_GiB, 1 }; static std::u8string selectedFile; static std::u8string baseOutputPath; static u64 splitSize = sizes[0]; static int selectedItem = 0; static TaskHolder splitterTask; if (ImGui::BeginChild("split_settings", { 0, ImGui::GetTextLineHeightWithSpacing() * 7 }, true, ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse)) { ImGui::BeginDisabled(splitterTask.isRunning()); { ImGui::InputText("##path", selectedFile); ImGui::SameLine(); if (ImGui::Button("...##input")) { fs::openFileBrowser(fs::DialogMode::Open, {}, [](const auto &path) { selectedFile = path.u8string(); }); } ImGui::SameLine(); ImGui::TextUnformatted("hex.builtin.tools.file_tools.splitter.input"_lang); ImGui::InputText("##base_path", baseOutputPath); ImGui::SameLine(); if (ImGui::Button("...##output")) { fs::openFileBrowser(fs::DialogMode::Save, {}, [](const auto &path) { baseOutputPath = path.u8string(); }); } ImGui::SameLine(); ImGui::TextUnformatted("hex.builtin.tools.file_tools.splitter.output"_lang); ImGui::Separator(); if (ImGui::Combo("###part_size", &selectedItem, sizeText.data(), sizeText.size())) { splitSize = sizes[selectedItem]; } } ImGui::EndDisabled(); ImGui::BeginDisabled(splitterTask.isRunning() || selectedItem != sizes.size() - 1); { ImGui::InputScalar("###custom_size", ImGuiDataType_U64, &splitSize); ImGui::SameLine(); ImGui::TextUnformatted("Bytes"); } ImGui::EndDisabled(); } ImGui::EndChild(); ImGui::BeginDisabled(selectedFile.empty() || baseOutputPath.empty() || splitSize == 0); { if (splitterTask.isRunning()) { ImGuiExt::TextSpinner("hex.builtin.tools.file_tools.splitter.picker.splitting"_lang); } else { if (ImGui::Button("hex.builtin.tools.file_tools.splitter.picker.split"_lang)) { splitterTask = TaskManager::createTask("hex.builtin.tools.file_tools.splitter.picker.splitting"_lang, 0, [](auto &task) { ON_SCOPE_EXIT { selectedFile.clear(); baseOutputPath.clear(); }; wolv::io::File file(selectedFile, wolv::io::File::Mode::Read); if (!file.isValid()) { ui::ToastError::open("hex.builtin.tools.file_tools.splitter.picker.error.open"_lang); return; } if (file.getSize() < splitSize) { ui::ToastError::open("hex.builtin.tools.file_tools.splitter.picker.error.size"_lang); return; } task.setMaxValue(file.getSize()); u32 index = 1; for (u64 offset = 0; offset < file.getSize(); offset += splitSize) { task.update(offset); std::fs::path path = baseOutputPath; path += hex::format(".{:05}", index); wolv::io::File partFile(path, wolv::io::File::Mode::Create); if (!partFile.isValid()) { ui::ToastError::open(hex::format("hex.builtin.tools.file_tools.splitter.picker.error.create"_lang, index)); return; } constexpr static auto BufferSize = 0xFF'FFFF; for (u64 partOffset = 0; partOffset < splitSize; partOffset += BufferSize) { partFile.writeVector(file.readVector(std::min<u64>(BufferSize, splitSize - partOffset))); partFile.flush(); } index++; } ui::ToastInfo::open("hex.builtin.tools.file_tools.splitter.picker.success"_lang); }); } } } ImGui::EndDisabled(); } }
6,186
C++
.cpp
122
34.319672
173
0.522603
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
211
regex_replacer.cpp
WerWolv_ImHex/plugins/builtin/source/content/tools/regex_replacer.cpp
#include <hex/helpers/http_requests.hpp> #include <hex/helpers/utils.hpp> #include <hex/api/localization_manager.hpp> #include <boost/regex.hpp> #include <imgui.h> #include <hex/ui/imgui_imhex_extensions.h> #include <fonts/codicons_font.h> namespace hex::plugin::builtin { void drawRegexReplacer() { static std::string inputString; static std::string regexPattern; static std::string replacePattern; static std::string outputString; ImGui::PushItemWidth(-150_scaled); bool changed1 = ImGuiExt::InputTextIcon("hex.builtin.tools.regex_replacer.pattern"_lang, ICON_VS_REGEX, regexPattern); bool changed2 = ImGuiExt::InputTextIcon("hex.builtin.tools.regex_replacer.replace"_lang, ICON_VS_REGEX, replacePattern); bool changed3 = ImGui::InputTextMultiline("hex.builtin.tools.regex_replacer.input"_lang, inputString, ImVec2(0, 0)); if (changed1 || changed2 || changed3) { try { const auto regex = boost::regex(regexPattern); outputString = boost::regex_replace(inputString, regex, replacePattern); } catch (boost::regex_error &) { } } ImGui::InputTextMultiline("hex.builtin.tools.regex_replacer.output"_lang, outputString.data(), outputString.size(), ImVec2(0, 0), ImGuiInputTextFlags_ReadOnly); ImGui::PopItemWidth(); } }
1,386
C++
.cpp
27
44.037037
168
0.694589
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
212
http_requests.cpp
WerWolv_ImHex/plugins/builtin/source/content/tools/http_requests.cpp
#include <hex/api/localization_manager.hpp> #include <imgui.h> #include <TextEditor.h> #include <hex/ui/imgui_imhex_extensions.h> #include <hex/helpers/http_requests.hpp> #include <hex/helpers/utils.hpp> #include <chrono> #include <fonts/codicons_font.h> namespace hex::plugin::builtin { using namespace std::literals::chrono_literals; void drawHTTPRequestMaker() { static std::string url, body, output; static std::vector<std::pair<std::string, std::string>> headers; static int method = 0; static TextEditor responseEditor, bodyEditor; static HttpRequest request("", ""); static std::future<HttpRequest::Result<std::string>> response; AT_FIRST_TIME { responseEditor.SetReadOnly(true); responseEditor.SetShowLineNumbers(false); responseEditor.SetShowWhitespaces(true); responseEditor.SetShowCursor(false); auto languageDef = TextEditor::LanguageDefinition(); for (auto &[name, identifier] : languageDef.mIdentifiers) identifier.mDeclaration = ""; languageDef.mCaseSensitive = false; languageDef.mAutoIndentation = false; languageDef.mCommentStart = ""; languageDef.mCommentEnd = ""; languageDef.mSingleLineComment = ""; languageDef.mDocComment = ""; languageDef.mGlobalDocComment = ""; responseEditor.SetLanguageDefinition(languageDef); bodyEditor.SetShowLineNumbers(true); bodyEditor.SetShowWhitespaces(true); bodyEditor.SetShowCursor(true); bodyEditor.SetLanguageDefinition(languageDef); }; constexpr static auto Methods = std::array{ "GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS", "CONNECT", "TRACE" }; ImGui::SetNextItemWidth(100_scaled); ImGui::Combo("##method", &method, Methods.data(), Methods.size()); ImGui::SameLine(); ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x - 75_scaled); if (ImGui::InputTextWithHint("##url", "hex.builtin.tools.http_requests.enter_url"_lang, url)) { output.clear(); } ImGui::SameLine(); ImGui::SetNextItemWidth(75_scaled); if (ImGui::Button("hex.builtin.tools.http_requests.send"_lang)) { request.setMethod(Methods[method]); request.setUrl(url); request.setBody(body); for (const auto &[key, value] : headers) request.addHeader(key, value); response = request.execute<std::string>(); } if (ImGui::BeginChild("Settings", ImVec2(ImGui::GetContentRegionAvail().x, 200_scaled), ImGuiChildFlags_None, ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse)) { if (ImGui::BeginTabBar("SettingsTabs")) { if (ImGui::BeginTabItem("hex.builtin.tools.http_requests.headers"_lang)) { if (ImGui::BeginTable("Headers", 3, ImGuiTableFlags_Borders, ImGui::GetContentRegionAvail() - ImVec2(0, ImGui::GetTextLineHeightWithSpacing() + ImGui::GetStyle().ItemSpacing.y * 2))) { ImGui::TableSetupColumn("hex.ui.common.key"_lang, ImGuiTableColumnFlags_NoSort); ImGui::TableSetupColumn("hex.ui.common.value"_lang, ImGuiTableColumnFlags_NoSort); ImGui::TableSetupColumn("##remove", ImGuiTableColumnFlags_NoSort | ImGuiTableColumnFlags_WidthFixed, 20_scaled); ImGui::TableSetupScrollFreeze(0, 1); ImGui::TableHeadersRow(); auto elementToRemove = headers.end(); for (auto it = headers.begin(); it != headers.end(); ++it) { auto &[key, value] = *it; ImGui::TableNextRow(); ImGui::PushID(&key); ImGui::TableNextColumn(); ImGui::SetNextItemWidth(-1); ImGui::InputTextWithHint("##key", "hex.ui.common.key"_lang, key); ImGui::TableNextColumn(); ImGui::SetNextItemWidth(-1); ImGui::InputTextWithHint("##value", "hex.ui.common.value"_lang, value); ImGui::TableNextColumn(); if (ImGuiExt::IconButton(ICON_VS_REMOVE, ImGui::GetStyleColorVec4(ImGuiCol_Text))) elementToRemove = it; ImGui::PopID(); } if (elementToRemove != headers.end()) headers.erase(elementToRemove); ImGui::TableNextColumn(); ImGui::Dummy(ImVec2(0, 0)); ImGui::EndTable(); } if (ImGuiExt::DimmedButton("hex.ui.common.add"_lang)) headers.emplace_back(); ImGui::EndTabItem(); } if (ImGui::BeginTabItem("hex.builtin.tools.http_requests.body"_lang)) { bodyEditor.Render("Body", ImGui::GetContentRegionAvail(), true); ImGui::EndTabItem(); } ImGui::EndTabBar(); } } ImGui::EndChild(); ImGuiExt::Header("hex.builtin.tools.http_requests.response"_lang); responseEditor.Render("Response", ImVec2(ImGui::GetContentRegionAvail().x, 150_scaled), true); if (response.valid() && response.wait_for(0s) != std::future_status::timeout) { const auto result = response.get(); const auto data = result.getData(); if (const auto status = result.getStatusCode(); status != 0) responseEditor.SetText("Status: " + std::to_string(result.getStatusCode()) + "\n\n" + data); else responseEditor.SetText("Status: No Response"); } } }
6,192
C++
.cpp
120
36.591667
204
0.563049
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
213
multiplication_decoder.cpp
WerWolv_ImHex/plugins/builtin/source/content/tools/multiplication_decoder.cpp
#include <hex/helpers/utils.hpp> #include <hex/api/localization_manager.hpp> #include <imgui.h> #include <hex/ui/imgui_imhex_extensions.h> namespace hex::plugin::builtin { void drawInvariantMultiplicationDecoder() { static u64 divisor = 1; static u64 multiplier = 1; static u64 numBits = 32; ImGuiExt::TextFormattedWrapped("{}", "hex.builtin.tools.invariant_multiplication.description"_lang); ImGui::NewLine(); if (ImGui::BeginChild("##calculator", ImVec2(0, ImGui::GetTextLineHeightWithSpacing() * 5), true)) { constexpr static u64 min = 1, max = 64; ImGui::SliderScalar("hex.builtin.tools.invariant_multiplication.num_bits"_lang, ImGuiDataType_U64, &numBits, &min, &max); ImGui::NewLine(); ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0)); ImGui::PushStyleColor(ImGuiCol_ChildBg, ImGui::GetStyleColorVec4(ImGuiCol_TableRowBgAlt)); if (ImGui::BeginChild("##calculator", ImVec2(0, ImGui::GetTextLineHeightWithSpacing() + 12_scaled), true)) { ImGui::PushItemWidth(100_scaled); ImGui::TextUnformatted("X /"); ImGui::SameLine(); if (ImGui::InputScalar("##divisor", ImGuiDataType_U64, &divisor)) { if (divisor == 0) divisor = 1; multiplier = ((1LLU << (numBits + 1)) / divisor) + 1; } ImGui::SameLine(); ImGui::TextUnformatted(" <=> "); ImGui::SameLine(); ImGui::TextUnformatted("( X *"); ImGui::SameLine(); if (ImGuiExt::InputHexadecimal("##multiplier", &multiplier)) { if (multiplier == 0) multiplier = 1; divisor = ((1LLU << (numBits + 1)) / multiplier) + 1; } ImGui::SameLine(); ImGuiExt::TextFormatted(") >> {}", numBits + 1); ImGui::PopItemWidth(); } ImGui::EndChild(); ImGui::PopStyleColor(); ImGui::PopStyleVar(); } ImGui::EndChild(); } }
2,231
C++
.cpp
47
34.234043
133
0.546335
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
214
file_tool_shredder.cpp
WerWolv_ImHex/plugins/builtin/source/content/tools/file_tool_shredder.cpp
#include <hex/helpers/fs.hpp> #include <hex/api/localization_manager.hpp> #include <hex/api/task_manager.hpp> #include <algorithm> #include <random> #include <imgui.h> #include <hex/ui/imgui_imhex_extensions.h> #include <toasts/toast_notification.hpp> #include <wolv/io/file.hpp> #include <wolv/utils/guards.hpp> namespace hex::plugin::builtin { void drawFileToolShredder() { static std::u8string selectedFile; static bool fastMode = false; static TaskHolder shredderTask; ImGui::TextUnformatted("hex.builtin.tools.file_tools.shredder.warning"_lang); ImGui::NewLine(); if (ImGui::BeginChild("settings", { 0, ImGui::GetTextLineHeightWithSpacing() * 4 }, true, ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse)) { ImGui::BeginDisabled(shredderTask.isRunning()); { ImGui::TextUnformatted("hex.builtin.tools.file_tools.shredder.input"_lang); ImGui::SameLine(); ImGui::InputText("##path", selectedFile); ImGui::SameLine(); if (ImGui::Button("...")) { fs::openFileBrowser(fs::DialogMode::Open, {}, [](const auto &path) { selectedFile = path.u8string(); }); } ImGui::Checkbox("hex.builtin.tools.file_tools.shredder.fast"_lang, &fastMode); } ImGui::EndDisabled(); } ImGui::EndChild(); if (shredderTask.isRunning()) { ImGuiExt::TextSpinner("hex.builtin.tools.file_tools.shredder.shredding"_lang); } else { ImGui::BeginDisabled(selectedFile.empty()); { if (ImGui::Button("hex.builtin.tools.file_tools.shredder.shred"_lang)) { shredderTask = TaskManager::createTask("hex.builtin.tools.file_tools.shredder.shredding"_lang, 0, [](auto &task) { ON_SCOPE_EXIT { selectedFile.clear(); }; wolv::io::File file(selectedFile, wolv::io::File::Mode::Write); if (!file.isValid()) { ui::ToastError::open("hex.builtin.tools.file_tools.shredder.error.open"_lang); return; } task.setMaxValue(file.getSize()); std::vector<std::array<u8, 3>> overwritePattern; if (fastMode) { /* Should be sufficient for modern disks */ overwritePattern.push_back({ 0x00, 0x00, 0x00 }); overwritePattern.push_back({ 0xFF, 0xFF, 0xFF }); } else { /* Gutmann's method. Secure for magnetic storage */ std::random_device rd; std::uniform_int_distribution<u8> dist(0x00, 0xFF); /* Fill fixed patterns */ overwritePattern = { { }, { }, {}, {}, { 0x55, 0x55, 0x55 }, { 0xAA, 0xAA, 0xAA }, { 0x92, 0x49, 0x24 }, { 0x49, 0x24, 0x92 }, { 0x24, 0x92, 0x49 }, { 0x00, 0x00, 0x00 }, { 0x11, 0x11, 0x11 }, { 0x22, 0x22, 0x22 }, { 0x33, 0x33, 0x44 }, { 0x55, 0x55, 0x55 }, { 0x66, 0x66, 0x66 }, { 0x77, 0x77, 0x77 }, { 0x88, 0x88, 0x88 }, { 0x99, 0x99, 0x99 }, { 0xAA, 0xAA, 0xAA }, { 0xBB, 0xBB, 0xBB }, { 0xCC, 0xCC, 0xCC }, { 0xDD, 0xDD, 0xDD }, { 0xEE, 0xEE, 0xEE }, { 0xFF, 0xFF, 0xFF }, { 0x92, 0x49, 0x24 }, { 0x49, 0x24, 0x92 }, { 0x24, 0x92, 0x49 }, { 0x6D, 0xB6, 0xDB }, { 0xB6, 0xDB, 0x6D }, { 0xBD, 0x6D, 0xB6 }, {}, {}, {}, {} }; /* Fill random patterns */ for (u8 i = 0; i < 4; i++) overwritePattern[i] = { dist(rd), dist(rd), dist(rd) }; for (u8 i = 0; i < 4; i++) overwritePattern[overwritePattern.size() - 1 - i] = { dist(rd), dist(rd), dist(rd) }; } size_t fileSize = file.getSize(); for (const auto &pattern : overwritePattern) { for (u64 offset = 0; offset < fileSize; offset += 3) { file.writeBuffer(pattern.data(), std::min<u64>(pattern.size(), fileSize - offset)); task.update(offset); } file.flush(); } file.remove(); ui::ToastInfo::open("hex.builtin.tools.file_tools.shredder.success"_lang); }); } } ImGui::EndDisabled(); } } }
6,108
C++
.cpp
119
27.731092
167
0.38941
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
215
file_tool_combiner.cpp
WerWolv_ImHex/plugins/builtin/source/content/tools/file_tool_combiner.cpp
#include <hex/helpers/http_requests.hpp> #include <hex/helpers/fmt.hpp> #include <hex/helpers/fs.hpp> #include <hex/api/localization_manager.hpp> #include <hex/api/task_manager.hpp> #include <algorithm> #include <random> #include <imgui.h> #include <hex/ui/imgui_imhex_extensions.h> #include <toasts/toast_notification.hpp> #include <wolv/io/file.hpp> namespace hex::plugin::builtin { void drawFileToolCombiner() { static std::vector<std::fs::path> files; static std::u8string outputPath; static u32 selectedIndex; static TaskHolder combinerTask; if (ImGui::BeginTable("files_table", 2, ImGuiTableFlags_SizingStretchProp)) { ImGui::TableSetupColumn("file list", ImGuiTableColumnFlags_NoHeaderLabel, 10); ImGui::TableSetupColumn("buttons", ImGuiTableColumnFlags_NoHeaderLabel, 1); ImGui::TableNextRow(); ImGui::TableNextColumn(); if (ImGui::BeginListBox("##files", { -FLT_MIN, 10 * ImGui::GetTextLineHeightWithSpacing() })) { u32 index = 0; for (auto &file : files) { if (ImGui::Selectable(wolv::util::toUTF8String(file).c_str(), index == selectedIndex)) selectedIndex = index; index++; } ImGui::EndListBox(); } ImGui::TableNextColumn(); ImGui::BeginDisabled(selectedIndex <= 0); { if (ImGui::ArrowButton("move_up", ImGuiDir_Up)) { std::iter_swap(files.begin() + selectedIndex, files.begin() + selectedIndex - 1); selectedIndex--; } } ImGui::EndDisabled(); ImGui::BeginDisabled(files.empty() || selectedIndex >= files.size() - 1); { if (ImGui::ArrowButton("move_down", ImGuiDir_Down)) { std::iter_swap(files.begin() + selectedIndex, files.begin() + selectedIndex + 1); selectedIndex++; } } ImGui::EndDisabled(); ImGui::TableNextRow(); ImGui::TableNextColumn(); ImGui::BeginDisabled(combinerTask.isRunning()); { if (ImGui::Button("hex.builtin.tools.file_tools.combiner.add"_lang)) { fs::openFileBrowser(fs::DialogMode::Open, {}, [](const auto &path) { files.push_back(path); }, "", true); } ImGui::SameLine(); ImGui::BeginDisabled(files.empty() || selectedIndex >= files.size()); if (ImGui::Button("hex.builtin.tools.file_tools.combiner.delete"_lang)) { files.erase(files.begin() + selectedIndex); if (selectedIndex > 0) selectedIndex--; } ImGui::EndDisabled(); ImGui::SameLine(); ImGui::BeginDisabled(files.empty()); if (ImGui::Button("hex.builtin.tools.file_tools.combiner.clear"_lang)) { files.clear(); } ImGui::EndDisabled(); } ImGui::EndDisabled(); ImGui::EndTable(); } ImGui::BeginDisabled(combinerTask.isRunning()); { ImGui::InputText("##output_path", outputPath); ImGui::SameLine(); if (ImGui::Button("...")) { fs::openFileBrowser(fs::DialogMode::Save, {}, [](const auto &path) { outputPath = path.u8string(); }); } ImGui::SameLine(); ImGui::TextUnformatted("hex.builtin.tools.file_tools.combiner.output"_lang); } ImGui::EndDisabled(); ImGui::BeginDisabled(files.empty() || outputPath.empty()); { if (combinerTask.isRunning()) { ImGuiExt::TextSpinner("hex.builtin.tools.file_tools.combiner.combining"_lang); } else { if (ImGui::Button("hex.builtin.tools.file_tools.combiner.combine"_lang)) { combinerTask = TaskManager::createTask("hex.builtin.tools.file_tools.combiner.combining"_lang, 0, [](auto &task) { wolv::io::File output(outputPath, wolv::io::File::Mode::Create); if (!output.isValid()) { ui::ToastError::open("hex.builtin.tools.file_tools.combiner.error.open_output"_lang); return; } task.setMaxValue(files.size()); for (const auto &file : files) { task.increment(); wolv::io::File input(file, wolv::io::File::Mode::Read); if (!input.isValid()) { ui::ToastError::open(hex::format("hex.builtin.tools.file_tools.combiner.open_input"_lang, wolv::util::toUTF8String(file))); return; } constexpr static auto BufferSize = 0xFF'FFFF; auto inputSize = input.getSize(); for (u64 inputOffset = 0; inputOffset < inputSize; inputOffset += BufferSize) { output.writeVector(input.readVector(std::min<u64>(BufferSize, inputSize - inputOffset))); output.flush(); } } files.clear(); selectedIndex = 0; outputPath.clear(); ui::ToastInfo::open("hex.builtin.tools.file_tools.combiner.success"_lang); }); } } } ImGui::EndDisabled(); } }
5,948
C++
.cpp
126
30.992063
155
0.504054
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
216
ieee_decoder.cpp
WerWolv_ImHex/plugins/builtin/source/content/tools/ieee_decoder.cpp
#include <hex/api/content_registry.hpp> #include <hex/api/localization_manager.hpp> #include <hex/helpers/utils.hpp> #include <imgui.h> #include <hex/ui/imgui_imhex_extensions.h> namespace hex::plugin::builtin { // Tool for converting between different number formats. // There are three places where input can be changed; the bit checkboxes, the hex input, and the decimal input. // The bit checkboxes and the hex input are directly related and can be converted between each other easily. // The decimal input is a bit more complicated. IEEE 754 floating point numbers are represented as a sign bit, // an exponent and a mantissa. For details see https://en.wikipedia.org/wiki/IEEE_754. // Workflow is as follows: // From the bit checkboxes determine the integer hex value. This is straightforward. // From the hex value determine the binary floating point value by extracting the sign, exponent, and mantissa. // From the binary floating point value determine the decimal floating point value using a third party library. // From the decimal floating point we reconstruct the binary floating point value using internal hardware. // If the format is non-standard, the reconstruction is done using properties of the format. void drawIEEE754Decoder() { constexpr static auto flags = ImGuiInputTextFlags_EnterReturnsTrue; class IEEE754STATICS { public: IEEE754STATICS() : value(0), exponentBitCount(8), mantissaBitCount(23), resultFloat(0) {} u128 value; i32 exponentBitCount; i32 mantissaBitCount; long double resultFloat; }; static IEEE754STATICS ieee754statics; enum class NumberType { Normal, Zero, Denormal, Infinity, NaN, }; enum class InputType { Infinity, NotANumber, QuietNotANumber, SignalingNotANumber, Regular, Invalid }; enum class ValueType { Regular, SignalingNaN, QuietNaN, NegativeInfinity, PositiveInfinity, }; class IEEE754 { public: ValueType valueType; NumberType numberType; i64 exponentBias; long double signValue; long double exponentValue; long double mantissaValue; i64 signBits; i64 exponentBits; i64 mantissaBits; i64 precision; } ieee754 = {}; std::string specialNumbers[] = { "inf" , "Inf", "INF" , "nan" , "Nan" , "NAN", "qnan","Qnan", "QNAN", "snan", "Snan", "SNAN" }; const auto totalBitCount = ieee754statics.exponentBitCount + ieee754statics.mantissaBitCount; const auto signBitPosition = totalBitCount - 0; const auto exponentBitPosition = totalBitCount - 1; const auto mantissaBitPosition = totalBitCount - 1 - ieee754statics.exponentBitCount; const static auto ExtractBits = [](u32 startBit, u32 count) { return hex::extract(startBit, startBit - (count - 1), ieee754statics.value); }; ieee754.signBits = ExtractBits(signBitPosition, 1); ieee754.exponentBits = ExtractBits(exponentBitPosition, ieee754statics.exponentBitCount); ieee754.mantissaBits = ExtractBits(mantissaBitPosition, ieee754statics.mantissaBitCount); static i64 inputFieldWidth = 0; ImGuiExt::TextFormattedWrapped("{}", "hex.builtin.tools.ieee754.description"_lang); ImGui::NewLine(); static i64 displayMode = ContentRegistry::Settings::read<int>("hex.builtin.tools.ieee754.settings", "display_mode", 0); i64 displayModeTemp = displayMode; ImGui::RadioButton("hex.builtin.tools.ieee754.settings.display_mode.detailed"_lang, reinterpret_cast<int *>(&displayMode), 0); ImGui::SameLine(); ImGui::RadioButton("hex.builtin.tools.ieee754.settings.display_mode.simplified"_lang, reinterpret_cast<int *>(&displayMode), 1); if (displayModeTemp != displayMode) { ContentRegistry::Settings::write<int>("hex.builtin.tools.ieee754.settings", "display_mode", displayMode); displayModeTemp = displayMode; } auto tableFlags = ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_NoKeepColumnsVisible | ImGuiTableFlags_ScrollX | ImGuiTableFlags_NoPadInnerX; const static auto IndentBoxOrLabel = [](u32 startBit, u32 bitIndex, u32 count, bool isLabel) { auto checkBoxWidth = ImGui::CalcTextSize("0").x + ImGui::GetStyle().FramePadding.x * 2.0F; auto columnWidth = ImGui::GetColumnWidth(); float boxesPerColumn=columnWidth/checkBoxWidth; float result; if (isLabel) { std::string labelString = fmt::format("{}", bitIndex); auto labelWidth = ImGui::CalcTextSize(labelString.c_str()).x; auto leadingBoxes = (boxesPerColumn-count) / 2.0F; if (leadingBoxes < 0.0F) leadingBoxes = 0.0F; result = checkBoxWidth*(leadingBoxes + startBit - bitIndex + 0.5F) - labelWidth / 2.0F; } else { if (count < boxesPerColumn) result = (columnWidth - count * checkBoxWidth) / 2.0F; else result = 0.0F; } if (result <= 0.0F) result = 0.05F; return result; }; const static auto DisplayBitLabels = [](int startBit, int count) { static i32 lastLabelAdded = -1; i32 labelIndex; if (lastLabelAdded == -1 || count < 4) labelIndex = startBit - (count >> 1); else labelIndex = lastLabelAdded - 4; while (labelIndex + count > startBit) { auto indentSize = IndentBoxOrLabel(startBit, labelIndex, count, true); ImGui::Indent(indentSize ); ImGuiExt::TextFormatted("{}", labelIndex); lastLabelAdded = labelIndex; ImGui::Unindent(indentSize ); labelIndex -= 4; ImGui::SameLine(); } }; const static auto FormatBitLabels = [](i32 totalBitCount, i32 exponentBitPosition, i32 mantissaBitPosition) { // Row for bit labels. Due to font size constrains each bit cannot have its own label. // Instead, we label each 4 bits and then use the bit position to determine the bit label. // Result. ImGui::TableNextColumn(); // Equals. ImGui::TableNextColumn(); // Sign bit label is always shown. ImGui::TableNextColumn(); DisplayBitLabels(totalBitCount + 1, 1); // Times. ImGui::TableNextColumn(); // Exponent. ImGui::TableNextColumn(); DisplayBitLabels(exponentBitPosition + 1, ieee754statics.exponentBitCount); // Times. ImGui::TableNextColumn(); // Mantissa. ImGui::TableNextColumn(); DisplayBitLabels(mantissaBitPosition + 1, ieee754statics.mantissaBitCount); }; const static auto BitCheckbox = [](u8 bit) { bool checkbox = false; ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 1.0F); checkbox = (ieee754statics.value & (u128(1) << bit)) != 0; ImGuiExt::BitCheckbox("##checkbox", &checkbox); ieee754statics.value = (ieee754statics.value & ~(u128(1) << bit)) | (u128(checkbox) << bit); ImGui::PopStyleVar(); }; const static auto BitCheckboxes = [](u32 startBit, u32 count) { for (u32 i = 0; i < count; i++) { ImGui::PushID(startBit - i); BitCheckbox(startBit - i); ImGui::SameLine(0, 0); ImGui::PopID(); } }; const static auto FormatBits = [](i32 signBitPosition, i32 exponentBitPosition, i32 mantissaBitPosition) { // Sign. ImGui::TableNextColumn(); ImVec4 signColor = ImGuiExt::GetCustomColorVec4(ImGuiCustomCol_IEEEToolSign); ImVec4 expColor = ImGuiExt::GetCustomColorVec4(ImGuiCustomCol_IEEEToolExp); ImVec4 mantColor = ImGuiExt::GetCustomColorVec4(ImGuiCustomCol_IEEEToolMantissa); ImVec4 black = ImVec4(0.0, 0.0, 0.0, 1.0); float indent = IndentBoxOrLabel(signBitPosition,signBitPosition, 1, false); ImGui::Indent(indent); ImGui::PushStyleColor(ImGuiCol_FrameBg, signColor); ImGui::PushStyleColor(ImGuiCol_Border, black); BitCheckboxes(signBitPosition, 1); ImGui::PopStyleColor(); ImGui::PopStyleColor(); ImGui::Unindent(indent); // Times. ImGui::TableNextColumn(); // Exponent. ImGui::TableNextColumn(); indent = IndentBoxOrLabel(exponentBitPosition,exponentBitPosition, ieee754statics.exponentBitCount, false); ImGui::Indent(indent); ImGui::PushStyleColor(ImGuiCol_FrameBg, expColor); ImGui::PushStyleColor(ImGuiCol_Border, black); BitCheckboxes(exponentBitPosition, ieee754statics.exponentBitCount); ImGui::PopStyleColor(); ImGui::PopStyleColor(); ImGui::Unindent(indent); // Times. ImGui::TableNextColumn(); // Mantissa. ImGui::TableNextColumn(); indent = IndentBoxOrLabel(mantissaBitPosition,mantissaBitPosition, ieee754statics.mantissaBitCount, false); ImGui::Indent(indent); ImGui::PushStyleColor(ImGuiCol_FrameBg, mantColor); ImGui::PushStyleColor(ImGuiCol_Border, black); BitCheckboxes(mantissaBitPosition, ieee754statics.mantissaBitCount); ImGui::PopStyleColor(); ImGui::PopStyleColor(); ImGui::Unindent(indent); }; const static auto BitsToFloat = [](IEEE754 &ieee754) { // Zero or denormal. if (ieee754.exponentBits == 0) { // Result doesn't fit in 128 bits. if ((ieee754.exponentBias - 1) > 128) { ieee754.exponentValue = std::pow(2.0L, static_cast<long double>(-ieee754.exponentBias + 1)); } else { if (ieee754.exponentBias == 0) { // Exponent is zero. if (ieee754.mantissaBits == 0) ieee754.exponentValue = 1.0; else // Exponent is one. ieee754.exponentValue = 2.0; } else { ieee754.exponentValue = 1.0 / static_cast<long double>(u128(1) << (ieee754.exponentBias - 1)); } } } // Normal. else { // Result doesn't fit in 128 bits. if (std::abs(ieee754.exponentBits - ieee754.exponentBias) > 128) { ieee754.exponentValue = std::pow(2.0L, static_cast<long double>(ieee754.exponentBits - ieee754.exponentBias)); } //Result fits in 128 bits. else { // Exponent is positive. if (ieee754.exponentBits > ieee754.exponentBias) ieee754.exponentValue = static_cast<long double>(u128(1) << (ieee754.exponentBits - ieee754.exponentBias)); // Exponent is negative. else if (ieee754.exponentBits < ieee754.exponentBias) ieee754.exponentValue = 1.0 / static_cast<long double>(u128(1) << (ieee754.exponentBias - ieee754.exponentBits)); // Exponent is zero. else ieee754.exponentValue = 1.0; } } ieee754.mantissaValue = static_cast<long double>(ieee754.mantissaBits) / static_cast<long double>(u128(1) << (ieee754statics.mantissaBitCount)); if (ieee754.exponentBits != 0) ieee754.mantissaValue += 1.0; // Check if all exponent bits are set. if (std::popcount(static_cast<u64>(ieee754.exponentBits)) == static_cast<i64>(ieee754statics.exponentBitCount)) { // If fraction is zero number is infinity, if (ieee754.mantissaBits == 0) { if (ieee754.signBits == 0) { ieee754.valueType = ValueType::PositiveInfinity; ieee754statics.resultFloat = std::numeric_limits<long double>::infinity(); } else { ieee754.valueType = ValueType::NegativeInfinity; ieee754statics.resultFloat = -std::numeric_limits<long double>::infinity(); } ieee754.numberType = NumberType::Infinity; // otherwise number is NaN. } else { if (ieee754.mantissaBits & (u128(1) << (ieee754statics.mantissaBitCount - 1))) { ieee754.valueType = ValueType::QuietNaN; ieee754statics.resultFloat = std::numeric_limits<long double>::quiet_NaN(); } else { ieee754.valueType = ValueType::SignalingNaN; ieee754statics.resultFloat = std::numeric_limits<long double>::signaling_NaN(); } ieee754.numberType = NumberType::NaN; } // If all exponent bits are zero, but we have a non-zero fraction // then the number is denormal which are smaller than regular numbers // but not as precise. } else if (ieee754.exponentBits == 0 && ieee754.mantissaBits != 0) { ieee754.numberType = NumberType::Denormal; ieee754.valueType = ValueType::Regular; ieee754statics.resultFloat = ieee754.signValue * ieee754.exponentValue * ieee754.mantissaValue; } else { ieee754.numberType = NumberType::Normal; ieee754.valueType = ValueType::Regular; ieee754statics.resultFloat = ieee754.signValue * ieee754.exponentValue * ieee754.mantissaValue; } }; const static auto FloatToBits = [&specialNumbers](IEEE754 &ieee754, std::string decimalFloatingPointNumberString, int totalBitCount) { // Always obtain sign first. if (decimalFloatingPointNumberString[0] == '-') { // And remove it from the string. ieee754.signBits = 1; decimalFloatingPointNumberString.erase(0, 1); } else { // Important to switch from - to +. ieee754.signBits = 0; } InputType inputType = InputType::Regular; bool matchFound = false; // Detect and use special numbers. for (u32 i = 0; i < 12; i++) { if (decimalFloatingPointNumberString == specialNumbers[i]) { inputType = InputType(i/3); matchFound = true; break; } } if (!matchFound) inputType = InputType::Regular; if (inputType == InputType::Regular) { try { ieee754statics.resultFloat = stod(decimalFloatingPointNumberString); } catch(const std::invalid_argument& _) { inputType = InputType::Invalid; } } else if (inputType == InputType::Infinity) { ieee754statics.resultFloat = std::numeric_limits<long double>::infinity(); ieee754statics.resultFloat *= (ieee754.signBits == 1 ? -1 : 1); } else if (inputType == InputType::NotANumber) { ieee754statics.resultFloat = std::numeric_limits<long double>::quiet_NaN(); } else if (inputType == InputType::QuietNotANumber) { ieee754statics.resultFloat = std::numeric_limits<long double>::quiet_NaN(); } else if (inputType == InputType::SignalingNotANumber) { ieee754statics.resultFloat = std::numeric_limits<long double>::signaling_NaN(); } if (inputType != InputType::Invalid) { // Deal with zero first so we can use log2. if (ieee754statics.resultFloat == 0.0) { if (ieee754.signBits == 1) ieee754statics.resultFloat = -0.0; else ieee754statics.resultFloat = 0.0; ieee754.numberType = NumberType::Zero; ieee754.valueType = ValueType::Regular; ieee754.exponentBits = 0; ieee754.mantissaBits = 0; } else { long double log2Result = std::log2(ieee754statics.resultFloat); // 2^(bias+1)-2^(bias-prec) is the largest number that can be represented. // If the number entered is larger than this then the input is set to infinity. if (ieee754statics.resultFloat > (std::pow(2.0L, ieee754.exponentBias + 1) - std::pow(2.0L, ieee754.exponentBias - ieee754statics.mantissaBitCount)) || inputType == InputType::Infinity ) { ieee754statics.resultFloat = std::numeric_limits<long double>::infinity(); ieee754.numberType = NumberType::Infinity; ieee754.valueType = ieee754.signBits == 1 ? ValueType::NegativeInfinity : ValueType::PositiveInfinity; ieee754.exponentBits = (u128(1) << ieee754statics.exponentBitCount) - 1; ieee754.mantissaBits = 0; } else if (-std::rint(log2Result) > ieee754.exponentBias + ieee754statics.mantissaBitCount - 1) { // 1/2^(bias-1+prec) is the smallest number that can be represented. // If the number entered is smaller than this then the input is set to zero. if (ieee754.signBits == 1) ieee754statics.resultFloat = -0.0; else ieee754statics.resultFloat = 0.0; ieee754.numberType = NumberType::Zero; ieee754.valueType = ValueType::Regular; ieee754.exponentBits = 0; ieee754.mantissaBits = 0; } else if (inputType == InputType::SignalingNotANumber) { ieee754statics.resultFloat = std::numeric_limits<long double>::signaling_NaN(); ieee754.valueType = ValueType::SignalingNaN; ieee754.numberType = NumberType::NaN; ieee754.exponentBits = (u128(1) << ieee754statics.exponentBitCount) - 1; ieee754.mantissaBits = 1; } else if (inputType == InputType::QuietNotANumber || inputType == InputType::NotANumber ) { ieee754statics.resultFloat = std::numeric_limits<long double>::quiet_NaN(); ieee754.valueType = ValueType::QuietNaN; ieee754.numberType = NumberType::NaN; ieee754.exponentBits = (u128(1) << ieee754statics.exponentBitCount) - 1; ieee754.mantissaBits = (u128(1) << (ieee754statics.mantissaBitCount - 1)); } else if (static_cast<i64>(std::floor(log2Result)) + ieee754.exponentBias <= 0) { ieee754.numberType = NumberType::Denormal; ieee754.valueType = ValueType::Regular; ieee754.exponentBits = 0; auto mantissaExp = log2Result + ieee754.exponentBias + ieee754statics.mantissaBitCount - 1; ieee754.mantissaBits = static_cast<i64>(std::round(std::pow(2.0L, mantissaExp))); } else { ieee754.valueType = ValueType::Regular; ieee754.numberType = NumberType::Normal; i64 unBiasedExponent = static_cast<i64>(std::floor(log2Result)); ieee754.exponentBits = unBiasedExponent + ieee754.exponentBias; ieee754.mantissaValue = ieee754statics.resultFloat * std::pow(2.0L, -unBiasedExponent) - 1; ieee754.mantissaBits = static_cast<i64>(std::round( static_cast<long double>(u128(1) << (ieee754statics.mantissaBitCount)) * ieee754.mantissaValue)); } } // Put the bits together. ieee754statics.value = (ieee754.signBits << (totalBitCount)) | (ieee754.exponentBits << (totalBitCount - ieee754statics.exponentBitCount)) | ieee754.mantissaBits; } }; const static auto DisplayDecimal = [](IEEE754 &ieee754) { unsigned signColorU32 = ImGuiExt::GetCustomColorU32(ImGuiCustomCol_IEEEToolSign); unsigned expColorU32 = ImGuiExt::GetCustomColorU32(ImGuiCustomCol_IEEEToolExp); unsigned mantColorU32 = ImGuiExt::GetCustomColorU32(ImGuiCustomCol_IEEEToolMantissa); ImGui::TableNextColumn(); ImGui::TextUnformatted("="); // Sign. ImGui::TableNextColumn(); // This has the effect of dimming the color of the numbers so user doesn't try // to interact with them. ImVec4 textColor = ImGui::GetStyleColorVec4(ImGuiCol_Text); ImGui::BeginDisabled(); ImGui::PushStyleColor(ImGuiCol_Text, textColor); ImGui::Indent(10_scaled); ImGui::TableSetBgColor(ImGuiTableBgTarget_CellBg, signColorU32); if (ieee754.signBits == 1) ImGui::TextUnformatted("-1"); else ImGui::TextUnformatted("+1"); ImGui::Unindent(10_scaled); // Times. ImGui::TableNextColumn(); ImGui::TextUnformatted("x"); ImGui::TableNextColumn(); // Exponent. ImGui::TableSetBgColor(ImGuiTableBgTarget_CellBg, expColorU32); ImGui::Indent(20_scaled); if (ieee754.numberType == NumberType::NaN) { if (ieee754.valueType == ValueType::QuietNaN) ImGui::TextUnformatted("qNaN"); else ImGui::TextUnformatted("sNaN"); } else if (ieee754.numberType == NumberType::Infinity) { ImGui::TextUnformatted("Inf"); } else if (ieee754.numberType == NumberType::Zero) { ImGui::TextUnformatted("0"); } else if (ieee754.numberType == NumberType::Denormal) { ImGuiExt::TextFormatted("2^{0}", 1 - ieee754.exponentBias); } else { ImGuiExt::TextFormatted("2^{0}", ieee754.exponentBits - ieee754.exponentBias); } ImGui::Unindent(20_scaled); // Times. ImGui::TableNextColumn(); ImGui::TextUnformatted("x"); ImGui::TableNextColumn(); // Mantissa. ImGui::TableSetBgColor(ImGuiTableBgTarget_CellBg, mantColorU32); ImGui::Indent(20_scaled); ImGuiExt::TextFormatted("{:.{}}", ieee754.mantissaValue,ieee754.precision); ImGui::Unindent(20_scaled); ImGui::PopStyleColor(); ImGui::EndDisabled(); }; const static auto ToolMenu = [](i64 &inputFieldWidth) { // If precision and exponent match one of the IEEE 754 formats the format is highlighted // and remains highlighted until user changes to a different format. Matching formats occur when // the user clicks on one of the selections or if the slider values match the format in question. // When a new format is selected, it may have a smaller number of digits than // the previous selection. Since the largest of the hexadecimal and the decimal // representation widths set both field widths to the same value, we need to // reset it here when a new choice is set. auto exponentBitCount = ieee754statics.exponentBitCount; auto mantissaBitCount = ieee754statics.mantissaBitCount; if (ImGui::SliderInt("hex.builtin.tools.ieee754.exponent_size"_lang, &exponentBitCount, 1, 63 - mantissaBitCount)) { inputFieldWidth = 0; ieee754statics.exponentBitCount = exponentBitCount; } if (ImGui::SliderInt("hex.builtin.tools.ieee754.mantissa_size"_lang, &mantissaBitCount, 1, 63 - exponentBitCount)) { inputFieldWidth = 0; ieee754statics.mantissaBitCount = mantissaBitCount; } ImGui::Separator(); auto color = ImGui::GetColorU32(ImGuiCol_ButtonActive); bool needsPop = false; if (ieee754statics.exponentBitCount == 3 && ieee754statics.mantissaBitCount == 4) { ImGui::PushStyleColor(ImGuiCol_Button, color); needsPop = true; } if (ImGui::Button("hex.builtin.tools.ieee754.quarter_precision"_lang)) { ieee754statics.exponentBitCount = 3; ieee754statics.mantissaBitCount = 4; inputFieldWidth = 0; } if (needsPop) ImGui::PopStyleColor(); ImGui::SameLine(); needsPop = false; if (ieee754statics.exponentBitCount == 5 && ieee754statics.mantissaBitCount == 10) { ImGui::PushStyleColor(ImGuiCol_Button, color); needsPop = true; } if (ImGui::Button("hex.builtin.tools.ieee754.half_precision"_lang)) { ieee754statics.exponentBitCount = 5; ieee754statics.mantissaBitCount = 10; inputFieldWidth = 0; } if (needsPop) ImGui::PopStyleColor(); ImGui::SameLine(); needsPop = false; if (ieee754statics.exponentBitCount == 8 && ieee754statics.mantissaBitCount == 23) { ImGui::PushStyleColor(ImGuiCol_Button, color); needsPop = true; } if (ImGui::Button("hex.builtin.tools.ieee754.single_precision"_lang)) { ieee754statics.exponentBitCount = 8; ieee754statics.mantissaBitCount = 23; inputFieldWidth = 0; } if (needsPop) ImGui::PopStyleColor(); ImGui::SameLine(); needsPop = false; if (ieee754statics.exponentBitCount == 11 && ieee754statics.mantissaBitCount == 52) { ImGui::PushStyleColor(ImGuiCol_Button, color); needsPop = true; } if (ImGui::Button("hex.builtin.tools.ieee754.double_precision"_lang)) { ieee754statics.exponentBitCount = 11; ieee754statics.mantissaBitCount = 52; inputFieldWidth = 0; } if (needsPop) ImGui::PopStyleColor(); ImGui::SameLine(); needsPop = false; if (ImGui::Button("hex.builtin.tools.ieee754.clear"_lang)) // This will reset all interactive widgets to zero. ieee754statics.value = 0; ImGui::Separator(); ImGui::NewLine(); }; if (ImGui::BeginTable("##outer", 7, tableFlags, ImVec2(0, ImGui::GetTextLineHeightWithSpacing() * 5.5 ))) { ImGui::TableSetupColumn("hex.builtin.tools.ieee754.result.title"_lang); ImGui::TableSetupColumn("##equals"); ImGui::TableSetupColumn("hex.builtin.tools.ieee754.sign"_lang); ImGui::TableSetupColumn("##times"); ImGui::TableSetupColumn("hex.builtin.tools.ieee754.exponent"_lang); ImGui::TableSetupColumn("##times"); ImGui::TableSetupColumn("hex.builtin.tools.ieee754.mantissa"_lang); ImGui::TableHeadersRow(); ImGui::TableNextRow(); FormatBitLabels(totalBitCount, exponentBitPosition, mantissaBitPosition); ImGui::TableNextRow(); // Row for bit checkboxes // Result. ImGui::TableNextColumn(); u64 mask = hex::bitmask(totalBitCount+1); std::string maskString = hex::format("0x{:X} ", mask); auto style = ImGui::GetStyle(); inputFieldWidth = std::fmax(inputFieldWidth, ImGui::CalcTextSize(maskString.c_str()).x + style.FramePadding.x * 2.0F); ImGui::PushItemWidth(inputFieldWidth); u64 newValue = ieee754statics.value & mask; if (ImGuiExt::InputHexadecimal("##hex", &newValue, flags)) ieee754statics.value = newValue; ImGui::PopItemWidth(); // Equals. ImGui::TableNextColumn(); ImGui::TextUnformatted("="); FormatBits(signBitPosition, exponentBitPosition, mantissaBitPosition); ImGui::TableNextRow(); ImGui::TableNextColumn(); ieee754.exponentBias = (u128(1) << (ieee754statics.exponentBitCount - 1)) - 1; ieee754.signValue = ieee754.signBits == 0 ? 1.0 : -1.0; BitsToFloat(ieee754); if (ieee754.numberType == NumberType::Denormal) ieee754.precision = std::ceil(1+ieee754statics.mantissaBitCount * std::log10(2.0L)); else ieee754.precision = std::ceil(1+(ieee754statics.mantissaBitCount + 1) * std::log10(2.0L)); // For C++ from_chars is better than strtold. // The main problem is that from_chars will not process special numbers // like inf and nan, so we handle them manually. static std::string decimalFloatingPointNumberString; // Use qnan for quiet NaN and snan for signaling NaN. if (ieee754.numberType == NumberType::NaN) { if (ieee754.valueType == ValueType::QuietNaN) decimalFloatingPointNumberString = "qnan"; else decimalFloatingPointNumberString = "snan"; } else { decimalFloatingPointNumberString = fmt::format("{:.{}}", ieee754statics.resultFloat, ieee754.precision); } auto style1 = ImGui::GetStyle(); inputFieldWidth = std::fmax(inputFieldWidth, ImGui::CalcTextSize(decimalFloatingPointNumberString.c_str()).x + 2 * style1.FramePadding.x); ImGui::PushItemWidth(inputFieldWidth); // We allow any input in order to accept infinities and NaNs, all invalid entries // are detected catching exceptions. You can also enter -0 or -inf. if (ImGui::InputText("##resultFloat", decimalFloatingPointNumberString, flags)) { FloatToBits(ieee754, decimalFloatingPointNumberString, totalBitCount); } ImGui::PopItemWidth(); if (displayMode == 0) DisplayDecimal(ieee754); ImGui::EndTable(); } ToolMenu(inputFieldWidth); } }
31,877
C++
.cpp
580
39.748276
208
0.578375
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
217
graphing_calc.cpp
WerWolv_ImHex/plugins/builtin/source/content/tools/graphing_calc.cpp
#include <hex/helpers/http_requests.hpp> #include <wolv/math_eval/math_evaluator.hpp> #include <imgui.h> #include <implot.h> #include <hex/ui/imgui_imhex_extensions.h> #include <fonts/codicons_font.h> namespace hex::plugin::builtin { void drawGraphingCalculator() { static std::array<long double, 1000> x, y; static std::string mathInput; static ImPlotRect limits; static double prevPos = 0; static long double stepSize = 0.1; if (ImPlot::BeginPlot("Function", ImVec2(-1, 0), ImPlotFlags_NoTitle | ImPlotFlags_NoMenus | ImPlotFlags_NoBoxSelect | ImPlotFlags_NoMouseText | ImPlotFlags_NoFrame)) { ImPlot::SetupAxesLimits(-10, 10, -5, 5, ImPlotCond_Once); limits = ImPlot::GetPlotLimits(ImAxis_X1, ImAxis_Y1); ImPlot::PlotLine("f(x)", x.data(), y.data(), x.size()); ImPlot::EndPlot(); } ImGui::PushItemWidth(-1); ImGuiExt::InputTextIcon("##graphing_math_input", ICON_VS_SYMBOL_OPERATOR, mathInput, ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_AutoSelectAll); ImGui::PopItemWidth(); if ((prevPos != limits.X.Min && (ImGui::IsMouseReleased(ImGuiMouseButton_Left) || ImGui::GetIO().MouseWheel != 0)) || (ImGui::IsItemFocused() && ImGui::IsKeyPressed(ImGuiKey_Enter))) { wolv::math_eval::MathEvaluator<long double> evaluator; y = {}; u32 i = 0; evaluator.setFunction("y", [&](auto args) -> std::optional<long double> { i32 index = i + args[0]; if (index < 0 || u32(index) >= y.size()) return 0; else return y[index]; }, 1, 1); evaluator.registerStandardVariables(); evaluator.registerStandardFunctions(); stepSize = (limits.X.Size()) / x.size(); for (i = 0; i < x.size(); i++) { evaluator.setVariable("x", limits.X.Min + i * stepSize); x[i] = limits.X.Min + i * stepSize; y[i] = evaluator.evaluate(mathInput).value_or(0); if (y[i] < limits.Y.Min) limits.Y.Min = y[i]; if (y[i] > limits.Y.Max) limits.X.Max = y[i]; } limits.X.Max = limits.X.Min + x.size() * stepSize; prevPos = limits.X.Min; } } }
2,428
C++
.cpp
50
37.1
192
0.569309
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
218
byte_swapper.cpp
WerWolv_ImHex/plugins/builtin/source/content/tools/byte_swapper.cpp
#include <hex/api/localization_manager.hpp> #include <algorithm> #include <imgui.h> #include <hex/ui/imgui_imhex_extensions.h> #include <fonts/codicons_font.h> namespace hex::plugin::builtin { void drawByteSwapper() { static std::string input, buffer, output; if (ImGuiExt::InputTextIcon("hex.builtin.tools.input"_lang, ICON_VS_SYMBOL_NUMERIC, input, ImGuiInputTextFlags_CharsHexadecimal)) { auto nextAlignedSize = std::max<size_t>(2, std::bit_ceil(input.size())); buffer.clear(); buffer.resize(nextAlignedSize - input.size(), '0'); buffer += input; output.clear(); for (u32 i = 0; i < buffer.size(); i += 2) { output += buffer[buffer.size() - i - 2]; output += buffer[buffer.size() - i - 1]; } } ImGui::PushStyleVar(ImGuiStyleVar_Alpha, ImGui::GetStyle().DisabledAlpha); ImGuiExt::InputTextIcon("hex.builtin.tools.output"_lang, ICON_VS_SYMBOL_NUMERIC, output, ImGuiInputTextFlags_ReadOnly); ImGui::PopStyleVar(); } }
1,100
C++
.cpp
24
37.25
139
0.626642
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
219
math_eval.cpp
WerWolv_ImHex/plugins/builtin/source/content/tools/math_eval.cpp
#include <hex/api/localization_manager.hpp> #include <hex/api/imhex_api.hpp> #include <hex/providers/provider.hpp> #include <hex/helpers/utils.hpp> #include <wolv/math_eval/math_evaluator.hpp> #include <imgui.h> #include <hex/ui/imgui_imhex_extensions.h> #include <fonts/codicons_font.h> #include <vector> #include <string> namespace hex::plugin::builtin { void drawMathEvaluator() { static std::vector<long double> mathHistory; static std::string lastMathError; static std::string mathInput; bool evaluate = false; static wolv::math_eval::MathEvaluator<long double> mathEvaluator = [&] { wolv::math_eval::MathEvaluator<long double> evaluator; evaluator.registerStandardVariables(); evaluator.registerStandardFunctions(); evaluator.setFunction( "clear", [&](auto args) -> std::optional<long double> { hex::unused(args); mathHistory.clear(); lastMathError.clear(); mathEvaluator.getVariables().clear(); mathEvaluator.registerStandardVariables(); mathInput.clear(); return std::nullopt; }, 0, 0); evaluator.setFunction( "read", [](auto args) -> std::optional<long double> { u8 value = 0; auto provider = ImHexApi::Provider::get(); if (!ImHexApi::Provider::isValid() || !provider->isReadable() || args[0] >= provider->getActualSize()) return std::nullopt; provider->read(args[0], &value, sizeof(u8)); return value; }, 1, 1); evaluator.setFunction( "write", [](auto args) -> std::optional<long double> { auto provider = ImHexApi::Provider::get(); if (!ImHexApi::Provider::isValid() || !provider->isWritable() || args[0] >= provider->getActualSize()) return std::nullopt; if (args[1] > 0xFF) return std::nullopt; u8 value = args[1]; provider->write(args[0], &value, sizeof(u8)); return std::nullopt; }, 2, 2); return evaluator; }(); enum class MathDisplayType : u8 { Standard, Scientific, Engineering, Programmer } mathDisplayType = MathDisplayType::Standard; if (ImGui::BeginTabBar("##mathFormatTabBar")) { if (ImGui::BeginTabItem("hex.builtin.tools.format.standard"_lang)) { mathDisplayType = MathDisplayType::Standard; ImGui::EndTabItem(); } if (ImGui::BeginTabItem("hex.builtin.tools.format.scientific"_lang)) { mathDisplayType = MathDisplayType::Scientific; ImGui::EndTabItem(); } if (ImGui::BeginTabItem("hex.builtin.tools.format.engineering"_lang)) { mathDisplayType = MathDisplayType::Engineering; ImGui::EndTabItem(); } if (ImGui::BeginTabItem("hex.builtin.tools.format.programmer"_lang)) { mathDisplayType = MathDisplayType::Programmer; ImGui::EndTabItem(); } ImGui::EndTabBar(); } if (ImGui::BeginTable("##mathWrapper", 3)) { ImGui::TableSetupColumn("##keypad", ImGuiTableColumnFlags_WidthFixed | ImGuiTableColumnFlags_NoResize); ImGui::TableSetupColumn("##results", ImGuiTableColumnFlags_WidthStretch, 0.666); ImGui::TableSetupColumn("##variables", ImGuiTableColumnFlags_WidthStretch, 0.666); ImGui::TableNextRow(); ImGui::TableNextColumn(); auto buttonSize = ImVec2(3, 2) * ImGui::GetTextLineHeightWithSpacing(); if (ImGui::Button("Ans", buttonSize)) mathInput += "ans"; ImGui::SameLine(); if (ImGui::Button("Pi", buttonSize)) mathInput += "pi"; ImGui::SameLine(); if (ImGui::Button("e", buttonSize)) mathInput += "e"; ImGui::SameLine(); if (ImGui::Button("CE", buttonSize)) mathInput.clear(); ImGui::SameLine(); if (ImGui::Button(ICON_VS_DISCARD, buttonSize)) mathInput.clear(); ImGui::SameLine(); ImGui::NewLine(); switch (mathDisplayType) { case MathDisplayType::Standard: case MathDisplayType::Scientific: case MathDisplayType::Engineering: if (ImGui::Button("x²", buttonSize)) mathInput += "** 2"; ImGui::SameLine(); if (ImGui::Button("1/x", buttonSize)) mathInput += "1/"; ImGui::SameLine(); if (ImGui::Button("|x|", buttonSize)) mathInput += "abs"; ImGui::SameLine(); if (ImGui::Button("exp", buttonSize)) mathInput += "e ** "; ImGui::SameLine(); if (ImGui::Button("%", buttonSize)) mathInput += "%"; ImGui::SameLine(); break; case MathDisplayType::Programmer: if (ImGui::Button("<<", buttonSize)) mathInput += "<<"; ImGui::SameLine(); if (ImGui::Button(">>", buttonSize)) mathInput += ">>"; ImGui::SameLine(); if (ImGui::Button("&", buttonSize)) mathInput += "&"; ImGui::SameLine(); if (ImGui::Button("|", buttonSize)) mathInput += "|"; ImGui::SameLine(); if (ImGui::Button("^", buttonSize)) mathInput += "^"; ImGui::SameLine(); break; } ImGui::NewLine(); if (ImGui::Button("sqrt", buttonSize)) mathInput += "sqrt"; ImGui::SameLine(); if (ImGui::Button("(", buttonSize)) mathInput += "("; ImGui::SameLine(); if (ImGui::Button(")", buttonSize)) mathInput += ")"; ImGui::SameLine(); if (ImGui::Button("sign", buttonSize)) mathInput += "sign"; ImGui::SameLine(); if (ImGui::Button("÷", buttonSize)) mathInput += "/"; ImGui::SameLine(); ImGui::NewLine(); if (ImGui::Button("xª", buttonSize)) mathInput += "**"; ImGui::SameLine(); if (ImGui::Button("7", buttonSize)) mathInput += "7"; ImGui::SameLine(); if (ImGui::Button("8", buttonSize)) mathInput += "8"; ImGui::SameLine(); if (ImGui::Button("9", buttonSize)) mathInput += "9"; ImGui::SameLine(); if (ImGui::Button("×", buttonSize)) mathInput += "*"; ImGui::SameLine(); ImGui::NewLine(); if (ImGui::Button("log", buttonSize)) mathInput += "log"; ImGui::SameLine(); if (ImGui::Button("4", buttonSize)) mathInput += "4"; ImGui::SameLine(); if (ImGui::Button("5", buttonSize)) mathInput += "5"; ImGui::SameLine(); if (ImGui::Button("6", buttonSize)) mathInput += "6"; ImGui::SameLine(); if (ImGui::Button("-", buttonSize)) mathInput += "-"; ImGui::SameLine(); ImGui::NewLine(); if (ImGui::Button("ln", buttonSize)) mathInput += "ln"; ImGui::SameLine(); if (ImGui::Button("1", buttonSize)) mathInput += "1"; ImGui::SameLine(); if (ImGui::Button("2", buttonSize)) mathInput += "2"; ImGui::SameLine(); if (ImGui::Button("3", buttonSize)) mathInput += "3"; ImGui::SameLine(); if (ImGui::Button("+", buttonSize)) mathInput += "+"; ImGui::SameLine(); ImGui::NewLine(); if (ImGui::Button("lb", buttonSize)) mathInput += "lb"; ImGui::SameLine(); if (ImGui::Button("x=", buttonSize)) mathInput += "="; ImGui::SameLine(); if (ImGui::Button("0", buttonSize)) mathInput += "0"; ImGui::SameLine(); if (ImGui::Button(".", buttonSize)) mathInput += "."; ImGui::SameLine(); ImGui::PushStyleColor(ImGuiCol_Button, ImGuiExt::GetCustomColorVec4(ImGuiCustomCol_DescButtonHovered)); ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImGuiExt::GetCustomColorVec4(ImGuiCustomCol_DescButton)); ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImGuiExt::GetCustomColorVec4(ImGuiCustomCol_DescButtonActive)); if (ImGui::Button("=", buttonSize)) evaluate = true; ImGui::SameLine(); ImGui::PopStyleColor(3); ImGui::NewLine(); ImGui::TableNextColumn(); if (ImGui::BeginTable("##mathHistory", 1, ImGuiTableFlags_ScrollY | ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg, ImVec2(0, 300))) { ImGui::TableSetupColumn("hex.builtin.tools.history"_lang); ImGui::TableSetupScrollFreeze(0, 1); ImGuiListClipper clipper; clipper.Begin(mathHistory.size()); ImGui::TableHeadersRow(); while (clipper.Step()) { for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) { if (i == 0) ImGui::PushStyleColor(ImGuiCol_Text, ImU32(ImColor(0xA5, 0x45, 0x45))); ImGui::TableNextRow(); ImGui::TableNextColumn(); switch (mathDisplayType) { case MathDisplayType::Standard: ImGuiExt::TextFormatted("{0:.3Lf}", mathHistory[(mathHistory.size() - 1) - i]); break; case MathDisplayType::Scientific: ImGuiExt::TextFormatted("{0:.6Lg}", mathHistory[(mathHistory.size() - 1) - i]); break; case MathDisplayType::Engineering: ImGuiExt::TextFormatted("{0}", hex::toEngineeringString(mathHistory[(mathHistory.size() - 1) - i]).c_str()); break; case MathDisplayType::Programmer: ImGuiExt::TextFormatted("0x{0:X} ({1})", u64(mathHistory[(mathHistory.size() - 1) - i]), u64(mathHistory[(mathHistory.size() - 1) - i])); break; } if (i == 0) ImGui::PopStyleColor(); } } clipper.End(); ImGui::EndTable(); } ImGui::TableNextColumn(); if (ImGui::BeginTable("##mathVariables", 2, ImGuiTableFlags_ScrollY | ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg, ImVec2(0, 300))) { ImGui::TableSetupColumn("hex.builtin.tools.name"_lang); ImGui::TableSetupColumn("hex.builtin.tools.value"_lang); ImGui::TableSetupScrollFreeze(0, 1); ImGui::TableHeadersRow(); for (const auto &[name, variable] : mathEvaluator.getVariables()) { const auto &[value, constant] = variable; if (constant) continue; ImGui::TableNextRow(); ImGui::TableNextColumn(); ImGui::TextUnformatted(name.c_str()); ImGui::TableNextColumn(); switch (mathDisplayType) { case MathDisplayType::Standard: ImGuiExt::TextFormatted("{0:.3Lf}", value); break; case MathDisplayType::Scientific: ImGuiExt::TextFormatted("{0:.6Lg}", value); break; case MathDisplayType::Engineering: ImGuiExt::TextFormatted("{}", hex::toEngineeringString(value)); break; case MathDisplayType::Programmer: ImGuiExt::TextFormatted("0x{0:X} ({1})", u64(value), u64(value)); break; } } ImGui::EndTable(); } ImGui::EndTable(); } ImGui::PushItemWidth(ImGui::GetContentRegionAvail().x); if (ImGuiExt::InputTextIcon("##input", ICON_VS_SYMBOL_OPERATOR, mathInput, ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_AutoSelectAll)) { ImGui::SetKeyboardFocusHere(); evaluate = true; } ImGui::PopItemWidth(); if (!lastMathError.empty()) ImGuiExt::TextFormattedColored(ImColor(0xA00040FF), "hex.builtin.tools.error"_lang, lastMathError); else ImGui::NewLine(); if (evaluate) { try { auto result = mathEvaluator.evaluate(mathInput); mathInput.clear(); if (result.has_value()) { mathHistory.push_back(result.value()); lastMathError.clear(); } else { lastMathError = mathEvaluator.getLastError().value_or(""); } } catch (std::invalid_argument &e) { lastMathError = e.what(); } } } }
14,016
C++
.cpp
284
32.757042
159
0.500804
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
220
euclidean_alg.cpp
WerWolv_ImHex/plugins/builtin/source/content/tools/euclidean_alg.cpp
#include <hex/api/localization_manager.hpp> #include <imgui.h> #include <hex/ui/imgui_imhex_extensions.h> #include <fonts/codicons_font.h> #include <numeric> namespace hex::plugin::builtin { void drawEuclidianAlgorithm() { static u64 a, b; static i64 gcdResult = 0; static i64 lcmResult = 0; static i64 p = 0, q = 0; static bool overflow = false; constexpr static auto extendedGcd = []<typename T>(T a, T b) -> std::pair<T, T> { T x = 1, y = 0; T xLast = 0, yLast = 1; while (b > 0) { T quotient = a / b; std::tie(x, xLast) = std::tuple { xLast, x - quotient * xLast }; std::tie(y, yLast) = std::tuple { yLast, y - quotient * yLast }; std::tie(a, b) = std::tuple { b, a - quotient * b }; } return { x, y }; }; ImGuiExt::TextFormattedWrapped("{}", "hex.builtin.tools.euclidean_algorithm.description"_lang); ImGui::NewLine(); if (ImGuiExt::BeginBox()) { bool hasChanged = false; hasChanged = ImGui::InputScalar("A", ImGuiDataType_U64, &a) || hasChanged; hasChanged = ImGui::InputScalar("B", ImGuiDataType_U64, &b) || hasChanged; // Update results when input changed if (hasChanged) { // Detect overflow const u64 multiplicationResult = a * b; if (a != 0 && multiplicationResult / a != b) { gcdResult = 0; lcmResult = 0; p = 0; q = 0; overflow = true; } else { gcdResult = std::gcd<i128, i128>(a, b); lcmResult = std::lcm<i128, i128>(a, b); std::tie(p, q) = extendedGcd(a, b); overflow = false; } } ImGui::Separator(); ImGui::PushStyleVar(ImGuiStyleVar_Alpha, ImGui::GetStyle().DisabledAlpha); ImGui::InputScalar("gcd(A, B)", ImGuiDataType_S64, &gcdResult, nullptr, nullptr, "%llu", ImGuiInputTextFlags_ReadOnly); ImGui::Indent(); ImGuiExt::TextFormatted(ICON_VS_ARROW_RIGHT " a \u00D7 p + b \u00D7 q = ({0}) \u00D7 ({1}) + ({2}) \u00D7 ({3})", a, p, b, q); ImGui::Unindent(); ImGui::InputScalar("lcm(A, B)", ImGuiDataType_S64, &lcmResult, nullptr, nullptr, "%llu", ImGuiInputTextFlags_ReadOnly); ImGui::PopStyleVar(); ImGuiExt::EndBox(); } if (overflow) ImGuiExt::TextFormattedColored(ImGuiExt::GetCustomColorVec4(ImGuiCustomCol_ToolbarRed), "{}", "hex.builtin.tools.euclidean_algorithm.overflow"_lang); else ImGui::NewLine(); } }
2,880
C++
.cpp
62
33.758065
161
0.519871
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
221
color_picker.cpp
WerWolv_ImHex/plugins/builtin/source/content/tools/color_picker.cpp
#include <hex/helpers/utils.hpp> #include <hex/helpers/fmt.hpp> #include <hex/api/localization_manager.hpp> #include <imgui.h> #include <hex/ui/imgui_imhex_extensions.h> #include <nlohmann/json.hpp> #include <romfs/romfs.hpp> namespace hex::plugin::builtin { void drawColorPicker() { static std::array<float, 4> pickedColor = { 0 }; static std::string rgba8; struct BitValue { int bits; float color; float saturationMultiplier; const char *name; u8 index; }; static std::array bitValues = { BitValue{ 8, 0.00F, 1.0F, "R", 0 }, BitValue{ 8, 0.33F, 1.0F, "G", 1 }, BitValue{ 8, 0.66F, 1.0F, "B", 2 }, BitValue{ 8, 0.00F, 0.0F, "A", 3 } }; if (ImGui::BeginTable("##color_picker_table", 3, ImGuiTableFlags_BordersInnerV)) { ImGui::TableSetupColumn(hex::format(" {}", "hex.builtin.tools.color"_lang).c_str(), ImGuiTableColumnFlags_WidthFixed | ImGuiTableColumnFlags_NoResize, 300_scaled); ImGui::TableSetupColumn(hex::format(" {}", "hex.builtin.tools.color.components"_lang).c_str(), ImGuiTableColumnFlags_WidthFixed | ImGuiTableColumnFlags_NoResize, 105_scaled); ImGui::TableSetupColumn(hex::format(" {}", "hex.builtin.tools.color.formats"_lang).c_str(), ImGuiTableColumnFlags_WidthStretch | ImGuiTableColumnFlags_NoResize); ImGui::TableHeadersRow(); ImGui::TableNextRow(); ImGui::TableNextColumn(); // Draw main color picker widget { ImGui::PushItemWidth(-1); ImGui::ColorPicker4("hex.builtin.tools.color"_lang, pickedColor.data(), ImGuiColorEditFlags_Uint8 | ImGuiColorEditFlags_AlphaBar | ImGuiColorEditFlags_NoSidePreview | ImGuiColorEditFlags_NoSmallPreview | ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_DisplayHSV | ImGuiColorEditFlags_DisplayHex); ImGui::ColorButton("##color_button", ImColor(pickedColor[0], pickedColor[1], pickedColor[2], pickedColor[3]), ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_NoDragDrop | ImGuiColorEditFlags_AlphaPreviewHalf, ImVec2(300_scaled, 0)); ImGui::PopItemWidth(); } ImGui::TableNextColumn(); const auto colorFormatName = hex::format("{}{}{}{}", bitValues[0].bits > 0 ? bitValues[0].name : "", bitValues[1].bits > 0 ? bitValues[1].name : "", bitValues[2].bits > 0 ? bitValues[2].name : "", bitValues[3].bits > 0 ? bitValues[3].name : "" ); // Draw color bit count sliders { ImGui::Indent(); static auto drawBitsSlider = [&](BitValue *bitValue) { // Change slider color ImGui::PushStyleColor(ImGuiCol_FrameBg, ImColor::HSV(bitValue->color, 0.5F * bitValue->saturationMultiplier, 0.5F).Value); ImGui::PushStyleColor(ImGuiCol_FrameBgHovered, ImColor::HSV(bitValue->color, 0.6F * bitValue->saturationMultiplier, 0.5F).Value); ImGui::PushStyleColor(ImGuiCol_FrameBgActive, ImColor::HSV(bitValue->color, 0.7F * bitValue->saturationMultiplier, 0.5F).Value); ImGui::PushStyleColor(ImGuiCol_SliderGrab, ImColor::HSV(bitValue->color, 0.9F * bitValue->saturationMultiplier, 0.9F).Value); // Draw slider ImGui::PushID(&bitValue->bits); auto format = hex::format("%d\n{}", bitValue->name); ImGui::VSliderInt("##slider", ImVec2(18_scaled, 350_scaled), &bitValue->bits, 0, 16, format.c_str(), ImGuiSliderFlags_AlwaysClamp); ImGui::PopID(); ImGui::PopStyleColor(4); }; // Force sliders closer together ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(4, 4)); // Draw a slider for each color component for (u32 index = 0; auto &bitValue : bitValues) { // Draw slider drawBitsSlider(&bitValue); // Configure drag and drop source and target if (ImGui::BeginDragDropSource(ImGuiDragDropFlags_SourceNoPreviewTooltip)) { // Set the current slider index as the payload ImGui::SetDragDropPayload("BIT_VALUE", &index, sizeof(u32)); // Draw a color button to show the color being dragged ImGui::ColorButton("##color_button", ImColor::HSV(bitValue.color, 0.5F * bitValue.saturationMultiplier, 0.5F).Value); ImGui::EndDragDropSource(); } if (ImGui::BeginDragDropTarget()) { if (const ImGuiPayload *payload = ImGui::AcceptDragDropPayload("BIT_VALUE"); payload != nullptr) { auto otherIndex = *static_cast<const u32 *>(payload->Data); // Swap the currently hovered slider with the one being dragged std::swap(bitValues[index], bitValues[otherIndex]); } ImGui::EndDragDropTarget(); } ImGui::SameLine(); index += 1; } ImGui::NewLine(); // Draw color name below sliders ImGuiExt::TextFormatted("{}", colorFormatName); ImGui::PopStyleVar(); ImGui::Unindent(); } ImGui::TableNextColumn(); // Draw encoded color values { // Calculate int and float representations of the selected color std::array<u32, 4> intColor = {}; std::array<float, 4> floatColor = {}; for (u32 index = 0; auto &bitValue : bitValues) { intColor[index] = u64(std::round(static_cast<long double>(pickedColor[bitValue.index]) * std::numeric_limits<u32>::max())) >> (32 - bitValue.bits); floatColor[index] = pickedColor[bitValue.index]; index += 1; } // Draw a table with the color values if (ImGui::BeginTable("##value_table", 2, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_NoHostExtendX , ImVec2(230_scaled, 0))) { ImGui::TableSetupColumn("name", ImGuiTableColumnFlags_WidthFixed); ImGui::TableSetupColumn("value", ImGuiTableColumnFlags_WidthStretch); const static auto drawValue = [](const char *name, auto formatter) { ImGui::TableNextRow(); ImGui::TableNextColumn(); // Draw name of the formatting ImGui::TextUnformatted(name); ImGui::TableNextColumn(); // Draw value ImGui::PushID(name); ImGuiExt::TextFormattedSelectable("{}", formatter()); ImGui::PopID(); }; const u32 bitCount = bitValues[0].bits + bitValues[1].bits + bitValues[2].bits + bitValues[3].bits; // Draw the different representations drawValue("hex.builtin.tools.color.formats.hex"_lang, [&] { u64 hexValue = 0; for (u32 index = 0; auto &bitValue : bitValues) { hexValue <<= bitValue.bits; hexValue |= u64(intColor[index]) & hex::bitmask(bitValue.bits); index += 1; } return hex::format("#{0:0{1}X}", hexValue, bitCount / 4); }); drawValue(colorFormatName.c_str(), [&] { return hex::format("{}({}, {}, {}, {})", colorFormatName, intColor[0], intColor[1], intColor[2], intColor[3]); }); drawValue("hex.builtin.tools.color.formats.vec4"_lang, [&] { return hex::format("{{ {:.2}F, {:.2}F, {:.2}F, {:.2}F }}", floatColor[0], floatColor[1], floatColor[2], floatColor[3]); }); drawValue("hex.builtin.tools.color.formats.percent"_lang, [&] { return hex::format("{{ {}%, {}%, {}%, {}% }}", u32(floatColor[0] * 100), u32(floatColor[1] * 100), u32(floatColor[2] * 100), u32(floatColor[3] * 100)); }); drawValue("hex.builtin.tools.color.formats.color_name"_lang, [&] -> std::string { const static auto ColorTable = [] { auto colorMap = nlohmann::json::parse(romfs::get("assets/common/color_names.json").string()).get<std::map<std::string, std::string>>(); std::map<u8, std::map<u8, std::map<u8, std::string>>> result; for (const auto &[colorValue, colorName] : colorMap) { result [hex::parseHexString(colorValue.substr(0, 2))[0]] [hex::parseHexString(colorValue.substr(2, 2))[0]] [hex::parseHexString(colorValue.substr(4, 2))[0]] = colorName; } return result; }(); const auto r = pickedColor[0] * 0xFF; const auto g = pickedColor[1] * 0xFF; const auto b = pickedColor[2] * 0xFF; auto gTable = ColorTable.lower_bound(r); if (gTable == ColorTable.end()) return "???"; auto bTable = gTable->second.lower_bound(g); if (bTable == gTable->second.end()) return "???"; auto name = bTable->second.lower_bound(b); if (name == bTable->second.end()) return "???"; return name->second; }); ImGui::EndTable(); } } ImGui::EndTable(); } } }
10,566
C++
.cpp
171
42.532164
318
0.514747
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
222
file_uploader.cpp
WerWolv_ImHex/plugins/builtin/source/content/tools/file_uploader.cpp
namespace hex::plugin::builtin { /*void drawFileUploader() { struct UploadedFile { std::string fileName, link, size; }; static HttpRequest request("POST", "https://api.anonfiles.com/upload"); static std::future<HttpRequest::Result<std::string>> uploadProcess; static std::fs::path currFile; static std::vector<UploadedFile> links; bool uploading = uploadProcess.valid() && uploadProcess.wait_for(0s) != std::future_status::ready; ImGuiExt::Header("hex.builtin.tools.file_uploader.control"_lang, true); if (!uploading) { if (ImGui::Button("hex.builtin.tools.file_uploader.upload"_lang)) { fs::openFileBrowser(fs::DialogMode::Open, {}, [&](auto path) { uploadProcess = request.uploadFile(path); currFile = path; }); } } else { if (ImGui::Button("hex.ui.common.cancel"_lang)) { request.cancel(); } } ImGui::SameLine(); ImGui::ProgressBar(request.getProgress(), ImVec2(0, 0), uploading ? nullptr : "Done!"); ImGuiExt::Header("hex.builtin.tools.file_uploader.recent"_lang); if (ImGui::BeginTable("##links", 3, ImGuiTableFlags_ScrollY | ImGuiTableFlags_Borders | ImGuiTableFlags_Resizable | ImGuiTableFlags_RowBg, ImVec2(0, 200))) { ImGui::TableSetupColumn("hex.ui.common.file"_lang); ImGui::TableSetupColumn("hex.ui.common.link"_lang); ImGui::TableSetupColumn("hex.ui.common.size"_lang); ImGui::TableSetupScrollFreeze(0, 1); ImGui::TableHeadersRow(); ImGuiListClipper clipper; clipper.Begin(links.size()); while (clipper.Step()) { for (i32 i = clipper.DisplayEnd - 1; i >= clipper.DisplayStart; i--) { auto &[fileName, link, size] = links[i]; ImGui::TableNextRow(); ImGui::TableNextColumn(); ImGui::TextUnformatted(fileName.c_str()); ImGui::TableNextColumn(); if (ImGuiExt::Hyperlink(link.c_str())) { if (ImGui::IsKeyDown(ImGuiKey_LeftCtrl)) hex::openWebpage(link); else ImGui::SetClipboardText(link.c_str()); } ImGuiExt::InfoTooltip("hex.builtin.tools.file_uploader.tooltip"_lang); ImGui::TableNextColumn(); ImGui::TextUnformatted(size.c_str()); } } clipper.End(); ImGui::EndTable(); } if (uploadProcess.valid() && uploadProcess.wait_for(0s) == std::future_status::ready) { auto response = uploadProcess.get(); if (response.getStatusCode() == 200) { try { auto json = nlohmann::json::parse(response.getData()); links.push_back({ wolv::util::toUTF8String(currFile.filename()), json.at("data").at("file").at("url").at("short"), json.at("data").at("file").at("metadata").at("size").at("readable") }); } catch (...) { ui::PopupError::open("hex.builtin.tools.file_uploader.invalid_response"_lang); } } else if (response.getStatusCode() == 0) { // Canceled by user, no action needed } else ui::PopupError::open(hex::format("hex.builtin.tools.file_uploader.error"_lang, response.getStatusCode())); uploadProcess = {}; currFile.clear(); } }*/ }
3,813
C++
.cpp
76
35.026316
165
0.529048
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