1
0
mirror of synced 2024-12-04 20:17:57 +01:00
ImHex/main/gui/source/init/tasks.cpp

335 lines
12 KiB
C++
Raw Normal View History

#include "init/tasks.hpp"
#include "misc/freetype/imgui_freetype.h"
2021-08-31 15:22:00 +02:00
#include <imgui.h>
#include <romfs/romfs.hpp>
2021-08-31 15:22:00 +02:00
2023-05-11 23:21:52 +02:00
#include <hex/helpers/http_requests.hpp>
#include <hex/helpers/fs.hpp>
#include <hex/helpers/logger.hpp>
#include <hex/api/content_registry.hpp>
2022-08-20 13:43:26 +02:00
#include <hex/api/project_file_manager.hpp>
2023-01-05 09:29:16 +01:00
#include <hex/api/theme_manager.hpp>
2023-05-11 23:21:52 +02:00
#include <hex/api/plugin_manager.hpp>
#include <hex/api/layout_manager.hpp>
#include <hex/api/achievement_manager.hpp>
2023-05-11 23:21:52 +02:00
#include <hex/ui/view.hpp>
#include <hex/ui/popup.hpp>
#include <nlohmann/json.hpp>
#include <wolv/io/fs.hpp>
#include <wolv/io/file.hpp>
namespace hex::init {
using namespace std::literals::string_literals;
bool setupEnvironment() {
hex::log::debug("Using romfs: '{}'", romfs::name());
return true;
}
bool createDirectories() {
bool result = true;
using enum fs::ImHexPath;
// Try to create all default directories
for (u32 path = 0; path < u32(fs::ImHexPath::END); path++) {
for (auto &folder : fs::getDefaultPaths(static_cast<fs::ImHexPath>(path), true)) {
try {
wolv::io::fs::createDirectories(folder);
} catch (...) {
2023-03-12 18:43:05 +01:00
log::error("Failed to create folder {}!", wolv::util::toUTF8String(folder));
result = false;
}
}
}
if (!result)
ImHexApi::System::impl::addInitArgument("folder-creation-error");
return result;
}
bool deleteSharedData() {
// This function is called when ImHex is closed. It deletes all shared data that was created by plugins
// This is a bit of a hack but necessary because when ImHex gets closed, all plugins are unloaded in order for
// destructors to be called correctly. To prevent crashes when ImHex exits, we need to delete all shared data
EventImHexClosing::post();
EventManager::clear();
2023-12-06 11:04:35 +01:00
// Terminate all asynchronous tasks
TaskManager::exit();
2022-06-27 17:01:21 +02:00
while (ImHexApi::Provider::isValid())
ImHexApi::Provider::remove(ImHexApi::Provider::get());
ContentRegistry::Provider::impl::getEntries().clear();
2022-06-27 17:01:21 +02:00
2022-02-04 00:47:39 +01:00
ImHexApi::System::getInitArguments().clear();
ui/ux: Rewrite of the entire hex editor view to make it more flexible (#512) * ui/ux: Initial recreation of the hex editor view * ui/ux: Added back support for editing cells * ux: Make scrolling and selecting bytes feel nice again * ui/ux: Improved byte selecting, added footer * sys: Make math evaluator more generic to support integer only calculations * patterns: Moved value formatting into pattern language * ui/ux: Added Goto and Search popups, improved selection * ui: Added better tooltips for bookmarks and patterns * sys: Use worse hex search algorithm on macOS Sadly it still doesn't support `std::boyer_moore_horsepool_searcher` * ui: Added back missing events, menu items and shortcuts * fix: Bookmark highlighting being rendered off by one * fix: Various macOS build errors * fix: size_t is not u64 on macos * fix: std::fmod and std::pow not working with integer types on macos * fix: Missing semicolons * sys: Added proper integer pow function * ui: Added back support for custom encodings * fix: Editor not jumping to selection when selection gets changed * ui: Turn Hexii setting into a data visualizer * sys: Added back remaining shortcuts * sys: Remove old hex editor files * sys: Moved more legacy things away from the hex editor view, updated localization * fix: Hex editor scrolling behaving weirdly and inconsistently * sys: Cleaned up Hex editor code * sys: Added selection color setting, localized all new settings * fix: Search feature not working correctly * ui: Replace custom ImGui::Disabled function with native ImGui ones * ui: Fix bookmark tooltip rendering issues * fix: Another size_t not being 64 bit issue on MacOS
2022-05-27 20:42:07 +02:00
ImHexApi::HexEditor::impl::getBackgroundHighlights().clear();
ImHexApi::HexEditor::impl::getForegroundHighlights().clear();
ImHexApi::HexEditor::impl::getBackgroundHighlightingFunctions().clear();
ImHexApi::HexEditor::impl::getForegroundHighlightingFunctions().clear();
ImHexApi::HexEditor::impl::getTooltips().clear();
ImHexApi::HexEditor::impl::getTooltipFunctions().clear();
ImHexApi::System::getAdditionalFolderPaths().clear();
ImHexApi::Messaging::impl::getHandlers().clear();
ImHexApi::Fonts::getCustomFontPath().clear();
2023-11-28 09:49:38 +01:00
ImHexApi::Fonts::impl::getFonts().clear();
ContentRegistry::Settings::impl::getSettings().clear();
ContentRegistry::Settings::impl::getSettingsData().clear();
ContentRegistry::CommandPaletteCommands::impl::getEntries().clear();
ContentRegistry::CommandPaletteCommands::impl::getHandlers().clear();
ContentRegistry::PatternLanguage::impl::getFunctions().clear();
ContentRegistry::PatternLanguage::impl::getPragmas().clear();
ContentRegistry::PatternLanguage::impl::getVisualizers().clear();
ContentRegistry::PatternLanguage::impl::getInlineVisualizers().clear();
ContentRegistry::Views::impl::getEntries().clear();
impl::PopupBase::getOpenPopups().clear();
ContentRegistry::Tools::impl::getEntries().clear();
ContentRegistry::DataInspector::impl::getEntries().clear();
ContentRegistry::Language::impl::getLanguages().clear();
ContentRegistry::Language::impl::getLanguageDefinitions().clear();
LocalizationManager::impl::resetLanguageStrings();
ContentRegistry::Interface::impl::getWelcomeScreenEntries().clear();
ContentRegistry::Interface::impl::getFooterItems().clear();
ContentRegistry::Interface::impl::getToolbarItems().clear();
ContentRegistry::Interface::impl::getMainMenuItems().clear();
ContentRegistry::Interface::impl::getMenuItems().clear();
ContentRegistry::Interface::impl::getSidebarItems().clear();
ContentRegistry::Interface::impl::getTitleBarButtons().clear();
ShortcutManager::clearShortcuts();
ContentRegistry::DataProcessorNode::impl::getEntries().clear();
ContentRegistry::DataFormatter::impl::getEntries().clear();
ContentRegistry::FileHandler::impl::getEntries().clear();
ContentRegistry::Hashes::impl::getHashes().clear();
ContentRegistry::HexEditor::impl::getVisualizers().clear();
ContentRegistry::BackgroundServices::impl::stopServices();
ContentRegistry::BackgroundServices::impl::getServices().clear();
ContentRegistry::CommunicationInterface::impl::getNetworkEndpoints().clear();
ContentRegistry::Experiments::impl::getExperiments().clear();
ContentRegistry::Reports::impl::getGenerators().clear();
2023-05-11 23:21:52 +02:00
LayoutManager::reset();
ThemeManager::reset();
2023-01-05 09:29:16 +01:00
AchievementManager::getAchievements().clear();
2022-08-20 13:43:26 +02:00
ProjectFile::getHandlers().clear();
ProjectFile::getProviderHandlers().clear();
2023-06-23 21:39:22 +02:00
ProjectFile::setProjectFunctions(nullptr, nullptr);
2022-08-20 13:43:26 +02:00
fs::setFileBrowserErrorCallback(nullptr);
2023-12-02 11:09:32 +01:00
// Unlock font atlas so it can be deleted in case of a crash
if (ImGui::GetCurrentContext() != nullptr)
ImGui::GetIO().Fonts->Locked = false;
return true;
}
bool loadPlugins() {
// Load all plugins
for (const auto &dir : fs::getDefaultPaths(fs::ImHexPath::Plugins)) {
PluginManager::load(dir);
}
// Get loaded plugins
auto &plugins = PluginManager::getPlugins();
// If no plugins were loaded, ImHex wasn't installed properly. This will trigger an error popup later on
if (plugins.empty()) {
2022-01-13 14:34:27 +01:00
log::error("No plugins found!");
ImHexApi::System::impl::addInitArgument("no-plugins");
return false;
}
const auto shouldLoadPlugin = [executablePath = wolv::io::fs::getExecutablePath()](const Plugin &plugin) {
// In debug builds, ignore all plugins that are not part of the executable directory
#if !defined(DEBUG)
return true;
#endif
if (!executablePath.has_value())
return true;
// Check if the plugin is somewhere in the same directory tree as the executable
return !std::fs::relative(plugin.getPath(), executablePath->parent_path()).string().starts_with("..");
};
u32 builtinPlugins = 0;
2022-02-01 22:09:44 +01:00
u32 loadErrors = 0;
// Load the builtin plugin first, so it can initialize everything that's necessary for ImHex to work
for (const auto &plugin : plugins) {
if (!plugin.isBuiltinPlugin()) continue;
if (!shouldLoadPlugin(plugin)) {
log::debug("Skipping built-in plugin {}", plugin.getPath().string());
continue;
}
// Make sure there's only one built-in plugin
if (builtinPlugins > 1) continue;
// Initialize the plugin
if (!plugin.initializePlugin()) {
2023-03-12 18:43:05 +01:00
log::error("Failed to initialize plugin {}", wolv::util::toUTF8String(plugin.getPath().filename()));
loadErrors++;
} else {
builtinPlugins++;
}
}
// Load all other plugins
for (const auto &plugin : plugins) {
if (plugin.isBuiltinPlugin()) continue;
if (!shouldLoadPlugin(plugin)) {
log::debug("Skipping plugin {}", plugin.getPath().string());
continue;
}
// Initialize the plugin
if (!plugin.initializePlugin()) {
2023-03-12 18:43:05 +01:00
log::error("Failed to initialize plugin {}", wolv::util::toUTF8String(plugin.getPath().filename()));
loadErrors++;
}
}
// If no plugins were loaded successfully, ImHex wasn't installed properly. This will trigger an error popup later on
if (loadErrors == plugins.size()) {
log::error("No plugins loaded successfully!");
ImHexApi::System::impl::addInitArgument("no-plugins");
return false;
}
// ImHex requires exactly one built-in plugin
// If no built-in plugin or more than one was found, something's wrong and we can't continue
#if !defined(EMSCRIPTEN)
if (builtinPlugins == 0) {
log::error("Built-in plugin not found!");
ImHexApi::System::impl::addInitArgument("no-builtin-plugin");
return false;
} else if (builtinPlugins > 1) {
log::error("Found more than one built-in plugin!");
ImHexApi::System::impl::addInitArgument("multiple-builtin-plugins");
return false;
}
#endif
return true;
}
bool clearOldLogs() {
2023-11-30 11:23:12 +01:00
bool result = true;
for (const auto &path : fs::getDefaultPaths(fs::ImHexPath::Logs)) {
try {
2023-11-10 20:47:08 +01:00
std::vector<std::filesystem::directory_entry> files;
for (const auto& file : std::filesystem::directory_iterator(path))
files.push_back(file);
if (files.size() <= 10)
return true;
std::sort(files.begin(), files.end(), [](const auto& a, const auto& b) {
return std::filesystem::last_write_time(a) > std::filesystem::last_write_time(b);
});
2023-11-10 20:47:08 +01:00
for (auto it = files.begin() + 10; it != files.end(); it += 1)
std::filesystem::remove(it->path());
} catch (std::filesystem::filesystem_error &e) {
log::error("Failed to clear old log! {}", e.what());
2023-11-30 11:23:12 +01:00
result = false;
}
}
2023-11-30 11:23:12 +01:00
return result;
}
bool unloadPlugins() {
PluginManager::unload();
return true;
}
bool loadSettings() {
try {
// Try to load settings from file
ContentRegistry::Settings::impl::load();
2022-01-13 14:34:27 +01:00
} catch (std::exception &e) {
// If that fails, create a new settings file
2022-01-13 14:34:27 +01:00
log::error("Failed to load configuration! {}", e.what());
ContentRegistry::Settings::impl::clear();
ContentRegistry::Settings::impl::store();
return false;
}
return true;
}
bool storeSettings() {
try {
ContentRegistry::Settings::impl::store();
2022-01-13 14:34:27 +01:00
} catch (std::exception &e) {
log::error("Failed to store configuration! {}", e.what());
return false;
}
return true;
}
// Run all exit tasks, and print to console
void runExitTasks() {
for (const auto &[name, task, async] : init::getExitTasks()) {
2023-11-10 20:47:08 +01:00
bool result = task();
2023-11-11 00:54:16 +01:00
log::info("Exit task '{0}' finished {1}", name, result ? "successfully" : "unsuccessfully");
}
}
std::vector<Task> getInitTasks() {
return {
{ "Setting up environment", setupEnvironment, false },
{ "Creating directories", createDirectories, false },
{ "Loading settings", loadSettings, false },
2023-11-28 00:47:03 +01:00
{ "Loading plugins", loadPlugins, false },
};
}
std::vector<Task> getExitTasks() {
return {
2023-11-10 23:25:02 +01:00
{ "Saving settings", storeSettings, false },
{ "Cleaning up shared data", deleteSharedData, false },
{ "Unloading plugins", unloadPlugins, false },
{ "Clearing old logs", clearOldLogs, false },
};
}
}