// SPDX-License-Identifier: GPL-3.0-only #include "modern/ui/ui_preferences.hpp" #include namespace bmh::modern_ui { namespace { bool keys(const Json &v, std::initializer_list names) { if (!v.is_object() || v.size() != names.size()) return false; for (const auto *n : names) if (!v.contains(n)) return false; return true; } bool choice(const Json &v, std::initializer_list names) { if (!v.is_string()) return false; for (const auto *n : names) if (v == n) return true; return false; } } // namespace Json default_ui_preferences() { return {{"theme", "midnight"}, {"display", {{"mode", "window"}, {"resolution", "1920x1080"}, {"scale", "auto"}, {"language", "de"}}}, {"sound", {{"volume", 80}, {"effects", true}, {"style", "classic"}}}}; } bool valid_ui_preferences(const Json &v) { try { if (!keys(v, {"theme", "display", "sound"}) || !choice(v.at("theme"), {"midnight", "silver", "matchday"})) return false; const auto &d = v.at("display"), &s = v.at("sound"); return keys(d, {"mode", "resolution", "scale", "language"}) && keys(s, {"volume", "effects", "style"}) && choice(d.at("mode"), {"window", "fullscreen"}) && choice(d.at("resolution"), {"1280x720", "1600x900", "1920x1080", "2560x1440", "3840x2160"}) && choice(d.at("scale"), {"auto", "1", "1.5", "2"}) && d.at("language") == "de" && s.at("volume").is_number_integer() && s.at("volume") >= 0 && s.at("volume") <= 100 && s.at("effects").is_boolean() && choice(s.at("style"), {"classic", "modern"}); } catch (const Json::exception &) { return false; } } Json legacy_ui_preferences(const Json &legacy) { auto next = default_ui_preferences(); if (!legacy.is_object()) return next; if (legacy.contains("theme")) next["theme"] = legacy["theme"]; for (const auto *key : {"mode", "resolution", "scale"}) if (legacy.contains(key)) next["display"][key] = legacy[key]; for (const auto *key : {"volume", "effects"}) if (legacy.contains(key)) next["sound"][key] = legacy[key]; if (legacy.contains("sound-style")) next["sound"]["style"] = legacy["sound-style"]; return valid_ui_preferences(next) ? next : default_ui_preferences(); } Json load_ui_preferences(const fs::path &path) { if (!fs::exists(path)) return default_ui_preferences(); const auto envelope = Json::parse(editor::read_file(path)); if (!keys(envelope, {"schema", "preferences"}) || envelope.at("schema") != "openbmh-ui-preferences@1" || !valid_ui_preferences(envelope.at("preferences"))) throw editor::Error("invalid_ui_preferences"); return envelope.at("preferences"); } void save_ui_preferences(const fs::path &path, const Json &v) { if (!valid_ui_preferences(v)) throw editor::Error("invalid_ui_preferences"); if (!path.parent_path().empty()) fs::create_directories(path.parent_path()); editor::write_atomic( path, Json{{"schema", "openbmh-ui-preferences@1"}, {"preferences", v}}.dump(2)); } } // namespace bmh::modern_ui