#pragma once #include #include #include #include #include #include #include #include #include #include #include "save_bridge.h" #include "../modules/module_manager.h" #include "../gui/notifications.h" #include "../gui/hud_editor.h" namespace config { namespace fs = std::filesystem; struct value { int type = 0; double numbers[4]{}; std::string mode; }; struct module_state { bool enabled = false; int key = 0; float x = 10, y = 10; std::map settings; }; using snapshot = std::map; inline snapshot capture(module_manager& manager) { snapshot result; for (auto& m : manager.all()) { auto& state = result[m->name()]; state.enabled = m->enabled(); state.key = m->toggle_key(); state.x = m->hud_pos.x; state.y = m->hud_pos.y; for (auto& s : m->settings()) { if (s.type == setting_type::action) continue; auto& v = state.settings[s.name]; v.type = int(s.type); if (s.type == setting_type::toggle) v.numbers[0] = s.bool_value; else if (s.type == setting_type::slider_float) v.numbers[0] = s.float_value; else if (s.type == setting_type::color) std::copy(s.color, s.color + 4, v.numbers); else if (s.type != setting_type::text) v.numbers[0] = s.int_value; if (s.type == setting_type::text) v.mode = s.text_value; if (s.type == setting_type::mode && s.int_value >= 0 && s.int_value < int(s.modes.size())) v.mode = s.modes[s.int_value]; } } auto& editor=result["[hud editor]"]; editor.settings["snap to grid"]={int(setting_type::toggle),{double(hud_editor::options.snap)}}; editor.settings["show grid"]={int(setting_type::toggle),{double(hud_editor::options.show_grid)}}; editor.settings["grid size"]={int(setting_type::slider_int),{double(hud_editor::options.grid_size)}}; return result; } inline std::string encode(const snapshot& data) { std::ostringstream out; out.imbue(std::locale::classic()); out << "AMNESIA_PROFILE 1\n" << std::setprecision(9); for (auto& entry : data) { const auto& m = entry.second; out << "module " << std::quoted(entry.first) << ' ' << m.enabled << ' ' << m.key << ' ' << m.x << ' ' << m.y << '\n'; for (auto& setting : m.settings) { const auto& v = setting.second; out << "setting " << std::quoted(entry.first) << ' ' << std::quoted(setting.first) << ' ' << v.type; for (double number : v.numbers) out << ' ' << number; out << ' ' << std::quoted(v.mode) << '\n'; } } out << "end\n"; return out.str(); } inline bool decode(const std::string& text, snapshot& result) { if (text.size() > 2 * 1024 * 1024) return false; std::istringstream in(text); in.imbue(std::locale::classic()); std::string line; if (!std::getline(in, line) || line != "AMNESIA_PROFILE 1") return false; snapshot parsed; bool ended = false; while (std::getline(in, line)) { if (line == "end") { ended = true; break; } std::istringstream row(line); row.imbue(std::locale::classic()); std::string kind, name; if (!(row >> kind >> std::quoted(name)) || name.empty() || name.size() > 256) return false; if (kind == "module") { module_state state; int enabled; if (!(row >> enabled >> state.key >> state.x >> state.y) || (enabled != 0 && enabled != 1) || state.key < 0 || state.key > 255 || !std::isfinite(state.x) || !std::isfinite(state.y) || std::abs(state.x) > 100000 || std::abs(state.y) > 100000 || parsed.count(name)) return false; state.enabled = enabled != 0; parsed.emplace(name, state); } else if (kind == "setting") { std::string key; value v; if (!(row >> std::quoted(key) >> v.type) || key.empty() || key.size() > 256 || !parsed.count(name) || v.type < 0 || v.type > int(setting_type::text) || v.type == int(setting_type::action)) return false; for (auto& number : v.numbers) if (!(row >> number) || !std::isfinite(number) || std::abs(number) > 1e9) return false; if (!(row >> std::quoted(v.mode)) || v.mode.size() > 256 || parsed[name].settings.count(key)) return false; if ((v.type == int(setting_type::toggle) && v.numbers[0] != 0 && v.numbers[0] != 1) || ((v.type == int(setting_type::slider_int) || v.type == int(setting_type::mode) || v.type == int(setting_type::keybind)) && v.numbers[0] != std::floor(v.numbers[0]))) return false; parsed[name].settings.emplace(key, v); } else return false; row >> std::ws; if (!row.eof()) return false; } in >> std::ws; if (!ended || !in.eof()) return false; result = std::move(parsed); return true; } inline void apply(module_manager& manager, const snapshot& defaults, const snapshot& data) { hud_editor::options={}; auto editor=defaults.find("[hud editor]"); auto loaded_editor=data.find("[hud editor]"); std::map editor_values; if(editor!=defaults.end())editor_values=editor->second.settings; if(loaded_editor!=data.end())for(auto& entry:loaded_editor->second.settings)editor_values[entry.first]=entry.second; auto toggle=[&](const char* name,bool& target) { auto found=editor_values.find(name); if(found!=editor_values.end() && found->second.type==int(setting_type::toggle))target=found->second.numbers[0]!=0; }; toggle("snap to grid",hud_editor::options.snap);toggle("show grid",hud_editor::options.show_grid); auto spacing=editor_values.find("grid size"); if(spacing!=editor_values.end() && spacing->second.type==int(setting_type::slider_int)) hud_editor::options.grid_size=int(std::clamp(spacing->second.numbers[0],4.0,64.0)); // Disabling first releases injected input and cancels macro countdowns/runs. for (auto& m : manager.all()) m->set_enabled(false); for (auto& m : manager.all()) { auto original = defaults.find(m->name()); if (original == defaults.end()) continue; module_state state = original->second; auto loaded = data.find(m->name()); if (loaded != data.end()) { state.enabled = loaded->second.enabled; state.key = loaded->second.key; state.x = loaded->second.x; state.y = loaded->second.y; for (auto& entry : loaded->second.settings) state.settings[entry.first] = entry.second; if(m->name()=="atmosphere")for(const auto& alias:{std::pair{"screen rain","rain density"},{"screen snow","snow density"}}) { auto old=loaded->second.settings.find(alias.first); if(old!=loaded->second.settings.end() && !loaded->second.settings.count(alias.second))state.settings[alias.second]=old->second; } } m->set_toggle_key(state.key); m->hud_pos = ImVec2(state.x, state.y); m->ui.binding = false; for (auto& s : m->settings()) { s.binding = false; auto found = state.settings.find(s.name); if (found == state.settings.end() || found->second.type != int(s.type)) continue; const auto& v = found->second; switch (s.type) { case setting_type::text: s.text_value = v.mode.substr(0, s.int_max); break; case setting_type::toggle: s.bool_value = v.numbers[0] != 0; break; case setting_type::slider_float: s.float_value = std::clamp(float(v.numbers[0]), s.float_min, s.float_max); break; case setting_type::slider_int: s.int_value = std::clamp(int(v.numbers[0]), s.int_min, s.int_max); break; case setting_type::keybind: s.int_value = std::clamp(int(v.numbers[0]), 0, 255); break; case setting_type::color: for (int i = 0; i < 4; ++i) s.color[i] = std::clamp(float(v.numbers[i]), 0.f, 1.f); break; case setting_type::mode: { const auto mode = std::find(s.modes.begin(), s.modes.end(), v.mode); s.int_value = mode != s.modes.end() ? int(mode - s.modes.begin()) : 0; break; } default: break; } } } for (auto& m : manager.all()) { auto loaded = data.find(m->name()), original = defaults.find(m->name()); if (loaded != data.end()) m->set_enabled(loaded->second.enabled); else if (original != defaults.end()) m->set_enabled(original->second.enabled); } } inline std::string folded(std::string name) { for (char& c : name) if (c >= 'A' && c <= 'Z') c += 'a' - 'A'; return name; } inline bool valid_name(const std::string& name) { if (name.empty() || name.size() > 48 || name.front() == ' ' || name.back() == ' ') return false; for (unsigned char c : name) if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == ' ' || c == '_' || c == '-')) return false; const auto lower = folded(name); if (lower == "con" || lower == "prn" || lower == "aux" || lower == "nul") return false; if (lower.size() == 4 && (lower.substr(0, 3) == "com" || lower.substr(0, 3) == "lpt") && lower[3] >= '0' && lower[3] <= '9') return false; return true; } inline fs::path directory() { HMODULE dll = nullptr; wchar_t name[32768]{}; if (!GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, reinterpret_cast(&directory), &dll)) return {}; DWORD size = GetModuleFileNameW(dll, name, 32768); return size && size < 32768 ? fs::path(std::wstring(name, size)).parent_path() / L"profiles" : fs::path{}; } inline bool atomic_write(const fs::path& path, const std::string& text) { auto temporary = path; temporary += L".tmp"; HANDLE file = CreateFileW(temporary.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); if (file == INVALID_HANDLE_VALUE) return false; DWORD written = 0; bool ok = WriteFile(file, text.data(), DWORD(text.size()), &written, nullptr) && written == text.size(); if (ok) ok = FlushFileBuffers(file) != FALSE; if (!CloseHandle(file)) ok = false; if (ok) ok = MoveFileExW(temporary.c_str(), path.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH) != FALSE; if (!ok) DeleteFileW(temporary.c_str()); return ok; } inline bool read(const fs::path& path, snapshot& result) { std::error_code ec; auto size = fs::file_size(path, ec); if (ec || size > 2 * 1024 * 1024) return false; std::ifstream file(path, std::ios::binary); std::string text((std::istreambuf_iterator(file)), {}); return file && decode(text, result); } class profile_manager { public: ~profile_manager() { if (owns_bridge_) config_save::request = {}; } void initialize(module_manager& manager, fs::path root = directory(), bool bridge = true) { if (ready_) return; manager_ = &manager; root_ = std::move(root); defaults_ = capture(manager); ready_ = true; if (bridge) { config_save::request = [this] { return applying_ || closing_ ? true : writable_ && save(false); }; owns_bridge_ = true; } std::error_code ec; if (root_.empty()) { error("Could not find the client profile folder."); writable_ = false; return; } fs::create_directories(root_, ec); if (ec) { error("Cannot create the profiles folder beside the DLL."); writable_ = false; return; } std::ifstream index(root_ / L"active.txt"); std::string requested; if (std::getline(index, requested) && valid_name(requested)) active_ = requested; refresh(); snapshot loaded; // A removed last-used profile must not overwrite an existing Default. if (!fs::exists(file(active_), ec)) active_ = "Default"; if (fs::exists(file(active_), ec)) { if (read(file(active_), loaded)) { applying_ = true; apply(manager, defaults_, loaded); applying_ = false; baseline_ = encode(capture(manager)); observed_ = baseline_; } else { writable_ = false; error("Profile is damaged. Choose another profile or create a new one; the damaged file has been preserved."); } } else { active_ = "Default"; save(false); } write_index(); refresh(); } bool ready() const { return ready_; } const std::string& active() const { return active_; } const std::vector& names() const { return names_; } const std::string& last_error() const { return error_; } bool dirty() const { return manager_ && encode(capture(*manager_)) != baseline_; } bool blocked() const { return !writable_; } bool save(bool report = true) { if (!manager_ || root_.empty() || applying_ || closing_) return false; const auto current = encode(capture(*manager_)); if (!atomic_write(file(active_), current)) { error("Could not save the profile. Check that the client folder is writable."); return false; } writable_ = true; baseline_ = observed_ = current; error_.clear(); refresh(); if (report) message("Profile saved", active_); return true; } void tick(double time) { if (!ready_ || !manager_ || closing_) return; const auto current = encode(capture(*manager_)); if (current != observed_) { if (observed_ == baseline_) first_change_ = time; observed_ = current; changed_at_ = time; } if (writable_ && current != baseline_ && time >= retry_at_ && (time - changed_at_ >= 0.75 || time - first_change_ >= 5.0)) { if (!save(false)) retry_at_ = time + 5.0; } } void shutdown() { if (manager_ && writable_ && dirty()) save(false); // Module shutdown must not fall back to the legacy macro INI. closing_ = true; } bool create(const std::string& name) { if (!check_new(name)) return false; const auto state = encode(capture(*manager_)); if (writable_ && dirty() && !save(false)) return false; if (!atomic_write(file(name), state)) { error("Could not create the profile."); return false; } const auto current = capture(*manager_); applying_ = true; apply(*manager_, defaults_, current); applying_ = false; active_ = name; writable_ = true; baseline_ = observed_ = state; error_.clear(); write_index(); refresh(); message("Profile created", name); return true; } bool switch_to(const std::string& name) { if (!valid_name(name) || name == active_) return name == active_; snapshot loaded; if (!read(file(name), loaded)) { error("Could not load this profile. Its file has been preserved."); return false; } if (writable_ && dirty() && !save(false)) return false; applying_ = true; apply(*manager_, defaults_, loaded); applying_ = false; active_ = name; writable_ = true; baseline_ = observed_ = encode(capture(*manager_)); error_.clear(); write_index(); message("Profile loaded", name); return true; } bool rename(const std::string& name) { if (folded(active_) == "default") { error("The Default profile cannot be renamed."); return false; } if (!check_new(name) || !save(false)) return false; if (!MoveFileExW(file(active_).c_str(), file(name).c_str(), MOVEFILE_WRITE_THROUGH)) { error("Could not rename the profile."); return false; } active_ = name; error_.clear(); write_index(); refresh(); message("Profile renamed", name); return true; } bool remove_active() { if (folded(active_) == "default" || names_.size() < 2) { error("Keep at least one profile. Default cannot be deleted."); return false; } const auto old = active_; const auto choices = names_; for (const auto& name : choices) { if (name != old && switch_to(name)) { if (!DeleteFileW(file(old).c_str())) { error("Could not delete the profile."); return false; } refresh(); message("Profile deleted", old); return true; } } return false; } void refresh() { names_.clear(); std::error_code ec; fs::directory_iterator it(root_, ec), end; while (!ec && it != end) { const auto& path = it->path(); if (it->is_regular_file(ec) && path.extension() == L".profile") { const auto native = path.stem().wstring(); if (std::all_of(native.begin(), native.end(), [](wchar_t c) { return c > 0 && c < 128; })) { std::string name; for (wchar_t c : native) name.push_back(static_cast(c)); if (valid_name(name)) names_.push_back(name); } } it.increment(ec); } std::sort(names_.begin(), names_.end(), [](const auto& a, const auto& b) { return folded(a) < folded(b); }); } private: module_manager* manager_ = nullptr; fs::path root_; snapshot defaults_; std::string active_ = "Default", baseline_, observed_, error_; std::vector names_; double first_change_ = 0, changed_at_ = 0, retry_at_ = 0; bool ready_ = false, writable_ = true, applying_ = false, closing_ = false, owns_bridge_ = false; fs::path file(const std::string& name) const { return root_ / fs::path(name + ".profile"); } bool check_new(const std::string& name) { if (!manager_ || root_.empty()) { error("No profile folder is available."); return false; } if (!valid_name(name)) { error("Use 1-48 letters, numbers, spaces, underscores or hyphens. Reserved Windows names are unavailable."); return false; } refresh(); for (auto& existing : names_) if (folded(existing) == folded(name)) { error("A profile with that name already exists."); return false; } return true; } void write_index() { if (!atomic_write(root_ / L"active.txt", active_ + "\n")) error("Profile works now, but the active profile could not be remembered for next launch."); } void error(const std::string& text) { if (error_ != text) notifications::push("Profile error", text, notifications::kind::error, 6, "profiles"); error_ = text; } static void message(const std::string& title, const std::string& body) { notifications::push(title, body, notifications::kind::success, 3, "profiles"); } }; } inline config::profile_manager& profiles() { static config::profile_manager instance; return instance; }