fix: Don't unload background .NET scripts

This commit is contained in:
WerWolv
2024-06-07 21:27:01 +02:00
parent af59b9d2ca
commit 8531a67519
3 changed files with 34 additions and 10 deletions

View File

@@ -15,6 +15,7 @@ namespace hex::script::loader {
bool initialize() override;
bool loadAll() override;
void clearScripts() override;
private:
std::function<int(const std::string &, bool, const std::fs::path&)> m_runMethod;

View File

@@ -17,6 +17,8 @@ namespace hex::script::loader {
struct Script {
std::string name;
std::fs::path path;
bool background;
std::function<void()> entryPoint;
const ScriptLoader *loader;
@@ -29,9 +31,10 @@ namespace hex::script::loader {
virtual bool initialize() = 0;
virtual bool loadAll() = 0;
virtual void clearScripts() = 0;
void addScript(std::string name, bool background, std::function<void()> entryPoint) {
m_scripts.emplace_back(std::move(name), background, std::move(entryPoint), this);
void addScript(std::string name, std::fs::path path, bool background, std::function<void()> entryPoint) {
m_scripts.emplace_back(std::move(name), std::move(path), background, std::move(entryPoint), this);
}
const auto& getScripts() const {
@@ -43,8 +46,8 @@ namespace hex::script::loader {
}
protected:
void clearScripts() {
m_scripts.clear();
auto& getScripts() {
return m_scripts;
}
private:

View File

@@ -235,22 +235,36 @@ namespace hex::script::loader {
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, false, [this, scriptPath] {
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, true, [] {});
}
if (hasOnLoad) {
this->addScript(scriptName, scriptPath, true, [] {});
auto result = m_runMethod("OnLoad", true, scriptPath);
if (result != 0) {
TaskManager::doLater([=] {
@@ -258,11 +272,17 @@ namespace hex::script::loader {
});
}
}
}
}
return true;
}
void DotNetLoader::clearScripts() {
std::erase_if(getScripts(), [](const Script *script) {
return !script->background;
});
}
}