Port settings and automation to the Modern UI (by Codex)

This commit is contained in:
Codex committed 2026-10-25 21:36:18 +01:00
1 parent 8222926d9c
commit adb4166a80
26 files changed
+2734 -179

No files matched your search

+2
View File
@@ -132,6 +132,8 @@ int main(int argc, char** argv) {
modern_demo = true;
} else if (is("--ui-state") && value) {
modern_config.state = launch::path_from_utf8(args[++i]);
} else if (is("--ui-preferences") && value) {
modern_config.preferences = launch::path_from_utf8(args[++i]);
} else if (is("--ui-size") && value) {
const auto size = args[++i];
const auto separator = size.find('x');
+3 -3
View File
@@ -1,5 +1,5 @@
# SPDX-License-Identifier: GPL-3.0-only
add_library(bmh_modern_ui_core STATIC catalog.cpp model.cpp gui_assets.cpp desktop.cpp demo_sports.cpp demo_calendar.cpp demo_reports.cpp demo_almanac.cpp demo_finance.cpp demo_environment.cpp demo_advertising.cpp demo_toto.cpp demo_lineup.cpp demo_transfer.cpp demo_career_reports.cpp demo_rankings.cpp demo_stadium.cpp demo_statistics.cpp demo_news.cpp)
add_library(bmh_modern_ui_core STATIC catalog.cpp model.cpp gui_assets.cpp desktop.cpp demo_sports.cpp demo_calendar.cpp demo_reports.cpp demo_almanac.cpp demo_finance.cpp demo_environment.cpp demo_advertising.cpp demo_toto.cpp demo_lineup.cpp demo_transfer.cpp demo_career_reports.cpp demo_rankings.cpp demo_stadium.cpp demo_statistics.cpp demo_news.cpp demo_settings.cpp ui_preferences.cpp)
target_include_directories(bmh_modern_ui_core PUBLIC ../..)
target_link_libraries(bmh_modern_ui_core PUBLIC bmh_asset_io)
add_library(bmh_modern_ui STATIC view.cpp ticket_popover.cpp)
@@ -14,7 +14,7 @@ endif()
set(modern_assets "${CMAKE_BINARY_DIR}/assets/modern")
FetchContent_GetProperties(rmlui)
file(MAKE_DIRECTORY "${modern_assets}")
foreach(asset modern.rml theme.rcss ticket.rcss sports.rcss calendar.rcss reports.rcss report_details.rcss report_pickers.rcss indoor.rcss planning.rcss almanac.rcss finance.rcss bank.rcss contracts.rcss amount.rcss environment.rcss advertising.rcss toto.rcss lineup.rcss transfer.rcss career_reports.rcss rankings.rcss stadium.rcss statistics.rcss news.rcss)
foreach(asset modern.rml theme.rcss ticket.rcss sports.rcss calendar.rcss reports.rcss report_details.rcss report_pickers.rcss indoor.rcss planning.rcss almanac.rcss finance.rcss bank.rcss contracts.rcss amount.rcss environment.rcss advertising.rcss toto.rcss lineup.rcss transfer.rcss career_reports.rcss rankings.rcss stadium.rcss statistics.rcss news.rcss settings.rcss)
configure_file("${CMAKE_SOURCE_DIR}/assets/modern/${asset}" "${modern_assets}/${asset}" COPYONLY)
endforeach()
@@ -100,7 +100,7 @@ foreach(component environment advertising toto lineup transfer stadium)
add_test(NAME modern_${component}_ui_tests COMMAND modern_${component}_ui_tests)
endforeach()
foreach(component statistics news)
foreach(component statistics news settings)
add_executable(modern_${component}_ui_tests ../../../tests/modern_${component}_ui_tests.cpp)
target_link_libraries(modern_${component}_ui_tests PRIVATE bmh_modern_ui_core)
if(MSVC)
+13 -44
View File
@@ -133,7 +133,7 @@ void App::ProcessEvent(Rml::Event &event) try {
const auto type = event.GetType();
// Native widgets can emit intermediate selected values while their options
// are being constructed. Opening a squad menu must stay read-only.
if (setting_menu_markup_ && (menu_ == "lineup" || menu_ == "transfer" || menu_ == "news") &&
if (setting_menu_markup_ && (menu_ == "lineup" || menu_ == "transfer" || menu_ == "news" || menu_ == "settings") &&
(type == "change" || type == "input")) return;
if (type == "keydown")
keyboard_navigation_ = true;
@@ -154,6 +154,7 @@ void App::ProcessEvent(Rml::Event &event) try {
if (n->GetId() == "native-ticket-layer")
return;
if (amount_event(event)) return;
if (popup_.empty() && settings_event(event)) return;
if ((menu_ == "lineup" || menu_ == "transfer") && (type == "change" || type == "input")) {
if (auto *select = dynamic_cast<Rml::ElementFormControlSelect *>(event.GetTargetElement());
select && select->IsSelectBoxVisible()) {
@@ -246,7 +247,7 @@ void App::ProcessEvent(Rml::Event &event) try {
if (type == "mouseup" && event.GetParameter<int>("button", 0) == 1) {
if (scene_ == "desktop" && !menu_.empty() && popup_.empty()) {
menu_.clear();
draft_preferences_ = nullptr;
reset_settings();
refresh();
} else if (scene_ == "desktop" && menu_.empty() && popup_.empty()) {
std::string id;
@@ -363,7 +364,7 @@ void App::ProcessEvent(Rml::Event &event) try {
dirty_ = true;
} else if (!menu_.empty()) {
menu_.clear();
draft_preferences_ = nullptr;
reset_settings();
refresh();
} else if (scene_ == "manager") {
scene_ = "newgame";
@@ -459,6 +460,7 @@ void App::ProcessEvent(Rml::Event &event) try {
void App::dispatch(const std::string &action, Rml::Element *target) {
const auto id =
target ? target->GetAttribute<Rml::String>("data-id", "") : std::string();
if (settings_action(action,target)) return;
if (lineup_action(action, target) || transfer_action(action, target)) return;
if (career_report_action(action, target) || rankings_action(action, target)) return;
if (statistics_action(action, target) || dispatch_news(action, target)) return;
@@ -678,7 +680,7 @@ void App::dispatch(const std::string &action, Rml::Element *target) {
}
if (action == "close") {
menu_.clear();
draft_preferences_ = nullptr;
reset_settings();
if (scene_ != "desktop")
scene_ = "main";
refresh();
@@ -692,7 +694,7 @@ void App::dispatch(const std::string &action, Rml::Element *target) {
}
if (action == "settings") {
settings_category_ = "display";
draft_preferences_ = nullptr;
reset_settings();
menu_ = "settings";
refresh();
return;
@@ -1088,7 +1090,7 @@ void App::dispatch(const std::string &action, Rml::Element *target) {
planning_dialog_.clear();
if (route == "settings") {
settings_category_ = "display";
draft_preferences_ = nullptr;
reset_settings();
}
refresh();
return;
@@ -1155,37 +1157,6 @@ void App::dispatch(const std::string &action, Rml::Element *target) {
message("Trainingslager für die Demo vorgemerkt.");
return;
}
if (action == "settings-category") {
settings_category_ = id;
refresh();
return;
}
if (action == "settings-theme") {
draft_preferences_["theme"] = id;
refresh();
return;
}
if (action == "settings-apply") {
if (settings_category_ == "display") {
for (const auto *key : {"mode", "resolution", "scale"}) {
const auto value = field(std::string("display-") + key);
if (!value.empty())
draft_preferences_[key] = value;
}
}
if (settings_category_ == "sound") {
draft_preferences_["effects"] =
element("sound-effects")->HasAttribute("checked");
draft_preferences_["sound-style"] = field("sound-style");
}
if (source_ && !apply("preferences", draft_preferences_))
return;
theme_ = draft_preferences_.value("theme", theme_);
draft_preferences_ = nullptr;
menu_.clear();
refresh();
return;
}
if (action == "save-select") {
selections_["save"] = id;
refresh();
@@ -1230,7 +1201,7 @@ void App::dispatch(const std::string &action, Rml::Element *target) {
desktop_ =
source_->load(user_dir() / "saves" / editor::path(name + ".json"));
saved_desktop_ = desktop_;
theme_ = snap().state.at("preferences").value("theme", theme_);
if(!ui_preferences_loaded_){ui_preferences_=legacy_ui_preferences(snap().state.at("preferences"));theme_=ui_preferences_.at("theme").get<std::string>();}
menu_.clear();
scene_ = "desktop";
refresh();
@@ -1279,6 +1250,7 @@ void App::dispatch(const std::string &action, Rml::Element *target) {
}
}
void App::change(Rml::Element *target) {
if(settings_change(target))return;
const auto kind = target->GetAttribute<Rml::String>("data-change", "");
auto *control = dynamic_cast<Rml::ElementFormControl *>(target);
if (!control)
@@ -1342,6 +1314,7 @@ void App::change(Rml::Element *target) {
}
}
void App::input(Rml::Element *target) {
if(settings_change(target))return;
const auto kind = target->GetAttribute<Rml::String>("data-input", "");
auto *control = dynamic_cast<Rml::ElementFormControl *>(target);
if (!control)
@@ -1359,12 +1332,7 @@ void App::input(Rml::Element *target) {
}
return;
}
if (kind == "sound-volume") {
const int n = std::stoi(value);
draft_preferences_["volume"] = n;
element("volume-value")->SetInnerRML(std::to_string(n) + " %");
dirty_ = true;
}
if (kind == "camp-focus") {
const auto i = std::stoi(target->GetAttribute<Rml::String>("data-id", "0"));
if (i < 0 || i > 2)
@@ -1469,6 +1437,7 @@ void App::script() {
{"transfer_view", transfer_view_}, {"transfer_dialog", transfer_dialog_}, {"transfer_draft", transfer_draft_},
{"career_view", career_view_}, {"rankings_view", rankings_view_},
{"stadium_view", stadium_view_},
{"ui_preferences",ui_preferences_}, {"settings_draft",settings_draft_}, {"settings_category",settings_category_}, {"settings_query",settings_query_}, {"settings_notice",settings_notice_},
{"statistics_view", statistics_view_}, {"statistics_trophy", statistics_trophy_},
{"statistics_scrolls", statistics_scrolls_},
{"news_view", news_view_}, {"news_dialog", news_dialog_},
File diff suppressed because it is too large. Load diff
+15
View File
@@ -0,0 +1,15 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "modern/ui/catalog.hpp"
namespace bmh::modern_ui {
// Presentation preferences only. Codes preserve the handbook's UI addresses;
// they neither change Modern rules nor start any automatic game operation.
const Json &settings_catalogue();
int settings_index(const std::string &code);
Json default_demo_settings(const Json &full_state);
bool valid_demo_settings(const Json &full_state);
bool migrate_demo_settings(Json &full_state);
void sync_demo_settings_training(Json &full_state);
std::string edit_demo_settings(Json &full_state, const Json &settings);
std::string settings_search_key(std::string);
} // namespace bmh::modern_ui
+10 -1
View File
@@ -13,6 +13,7 @@
#include "modern/ui/demo_stadium.hpp"
#include "modern/ui/demo_statistics.hpp"
#include "modern/ui/demo_news.hpp"
#include "modern/ui/demo_settings.hpp"
#include "modern/ui/desktop.hpp"
#include <algorithm>
#include <chrono>
@@ -103,6 +104,8 @@ DemoSource::DemoSource(std::shared_ptr<const Catalog> catalog)
throw editor::Error("invalid_demo_stadium");
if (!migrate_demo_news(state_, *catalog_))
throw editor::Error("invalid_demo_news");
if (!migrate_demo_settings(state_))
throw editor::Error("invalid_demo_settings");
saved_ = state_;
}
Snapshot DemoSource::snapshot() const { return {revision_, catalog_, state_}; }
@@ -117,7 +120,10 @@ ActionResult DemoSource::apply(const Action &action) {
return {false, revision_, "stale_revision"};
auto next = state_;
try {
if (action.kind == "news") {
if (action.kind == "settings") {
const auto error = edit_demo_settings(next, action.value);
if (!error.empty()) return {false, revision_, error};
} else if (action.kind == "news") {
const auto error = edit_demo_news(next, action.value, *catalog_);
if (!error.empty())
return {false, revision_, error};
@@ -231,6 +237,7 @@ ActionResult DemoSource::apply(const Action &action) {
} catch (const Json::exception &) {
return {false, revision_, "invalid_action"};
}
sync_demo_settings_training(next);
state_ = std::move(next);
return {true, ++revision_, {}};
}
@@ -302,6 +309,8 @@ Json DemoSource::load(const fs::path &file) {
throw editor::Error("invalid_demo_stadium");
if (!migrate_demo_news(data, *catalog_))
throw editor::Error("invalid_demo_news");
if (!migrate_demo_settings(data))
throw editor::Error("invalid_demo_settings");
auto next = data;
auto desktop = next.value("desktop", Json::object());
if (!migrate_desktop(desktop))
-109
View File
@@ -711,115 +711,6 @@ std::string App::render_camp() {
btn("camp-remember", "Vormerken", "primary") + "</div></div>";
return body;
}
std::string App::render_settings() {
if (draft_preferences_.is_null())
draft_preferences_ =
source_ ? snap().state.at("preferences")
: Json{{"theme", theme_}, {"volume", 80}, {"effects", true}};
std::string nav;
for (const auto &[key, label] :
std::vector<std::pair<std::string, std::string>>{
{"display", "Anzeige"},
{"sound", "Sound"},
{"game", "Spiel"},
{"automation", "Automatik"}}) {
if (scene_ == "main" && (key == "game" || key == "automation"))
continue;
nav += btn("settings-category", label,
settings_category_ == key ? "primary" : "",
"data-id=\"" + key +
"\" "
"style=\"display:flex;justify-content:flex-start;width:100%;"
"height:100dp;margin-"
"bottom:14dp;text-align:left;\"");
}
std::string pane = "<h2>" +
std::string(settings_category_ == "display" ? "Anzeige"
: settings_category_ == "sound" ? "Sound"
: settings_category_ == "game" ? "Spiel"
: "Automatik") +
"</h2>";
if (settings_category_ == "display") {
pane +=
"<h3 style=\"margin:40dp 0 24dp;\">Gestaltung</h3><div class=\"row\">";
for (const auto &[id, name] :
std::vector<std::pair<std::string, std::string>>{
{"midnight", "Midnight Glass"},
{"silver", "Silver Glass"},
{"matchday", "Matchday"}})
pane +=
btn("settings-theme",
img("background", 520, 270, false, true, 650) +
"<p style=\"margin-top:20dp;\">" + name + "</p>",
std::string("choice ") +
(draft_preferences_.value("theme", theme_) == id ? "selected"
: ""),
"data-id=\"" + id + "\" style=\"width:570dp;padding:20dp;\"");
pane +=
"</div><h3 style=\"margin-top:50dp;\">Bildschirm</h3><div "
"class=\"field-row\"><label>Modus</label>" +
select("display-mode",
{{"window", "Fenster"}, {"fullscreen", "Vollbild"}},
draft_preferences_.value("mode", "window")) +
"</div><div class=\"field-row\"><label>Auflösung</label>" +
select("display-resolution",
{{"1280x720", "1280 × 720"},
{"1920x1080", "1920 × 1080"},
{"2560x1440", "2560 × 1440"},
{"3840x2160", "3840 × 2160"}},
draft_preferences_.value("resolution", "1920x1080")) +
"</div><div class=\"field-row\"><label>Skalierung</label>" +
select("display-scale",
{{"auto", "Auto"}, {"1", "1×"}, {"1.5", "1,5×"}, {"2", "2×"}},
draft_preferences_.value("scale", "auto")) +
"</div><div class=\"field-row\"><label>Sprache</label><select "
"id=\"display-language\"><option value=\"de\" "
"selected>Deutsch</option><option "
"disabled>Englisch</option></select></div>";
} else if (settings_category_ == "sound")
pane +=
"<div class=\"field-row\"><label>Lautstärke</label><input "
"type=\"range\" min=\"0\" max=\"100\" value=\"" +
std::to_string(draft_preferences_.value("volume", 80)) +
"\" id=\"sound-volume\" data-input=\"sound-volume\"/><span "
"id=\"volume-value\">" +
std::to_string(draft_preferences_.value("volume", 80)) +
" %</span></div><div class=\"field-row\"><label>Effekte</label><input "
"type=\"checkbox\" id=\"sound-effects\" " +
(draft_preferences_.value("effects", true) ? "checked" : "") +
"/></div><div class=\"field-row\"><label>Effektstil</label>" +
select("sound-style", {{"classic", "Klassisch"}, {"modern", "Modern"}},
draft_preferences_.value("sound-style", "classic")) +
"</div>";
else if (settings_category_ == "automation") {
pane += "<div class=\"field-row\"><label>Alles automatisch</label><input "
"type=\"checkbox\" data-change=\"automation-all\"/></div>";
for (const auto *name :
{"Aufstellung", "Auswechslungen", "Taktik", "Manndeckung", "Training"})
pane += "<div class=\"field-row\"><label>" + std::string(name) +
"</label><input type=\"checkbox\"/></div>";
} else
pane +=
std::string(
"<div class=\"field-row\"><label>Spieloption suchen</label><input "
"type=\"text\" id=\"settings-search\"/></div><div "
"class=\"field-row\"><label>Reality-Modus</label><input "
"type=\"checkbox\"/></div><div "
"class=\"field-row\"><label>Spielszenen anzeigen</label><input "
"type=\"checkbox\"/></div><div class=\"field-row\"><label>Desktop "
"am Raster ausrichten</label><input type=\"checkbox\" ") +
(desktop_.value("grid", true) ? "checked" : "") + "/></div>";
return "<div class=\"panel\" "
"style=\"position:absolute;left:0;top:0;width:370dp;bottom:150dp;"
"padding:24dp 20dp;\">" +
nav +
"</div><div class=\"panel list\" "
"style=\"position:absolute;left:410dp;right:0;top:0;bottom:150dp;"
"padding:36dp;\">" +
pane + "</div><div class=\"bottom-controls\">" +
btn("close", "Abbrechen") +
btn("settings-apply", "Anwenden", "primary") + "</div>";
}
std::string App::render_save(bool save) {
const auto directory = user_dir() / "saves";
std::string body = "<div class=\"panel list\" "
+460
View File
@@ -0,0 +1,460 @@
// SPDX-License-Identifier: GPL-3.0-only
void App::settings_remember_scroll() {
if (menu_ == "settings" && last_rendered_menu_ == "settings")
if (auto *pane = element("settings-options"))
settings_scrolls_[settings_rendered_category_.empty()
? settings_category_
: settings_rendered_category_] =
pane->GetScrollTop();
}
void App::settings_after_render() {
if (menu_ != "settings")
return;
settings_sync();
settings_rendered_category_ = settings_category_;
if (settings_category_ == "game") {
int count = 0;
render_settings_groups(&count);
if (auto *label = element("settings-search-count"))
label->SetInnerRML(std::to_string(count) + (settings_query_.empty()
? " Optionen"
: " von 142 Optionen"));
}
if (settings_restore_scroll_) {
context_->Update();
if (auto *pane = element("settings-options"))
pane->SetScrollTop(settings_scrolls_.value(settings_category_, 0.f));
settings_restore_scroll_ = false;
}
context_->Update();
}
void App::settings_sync() {
if (menu_ != "settings" || !settings_draft_.is_object())
return;
const bool valid = settings_valid(), changed = settings_dirty();
if (auto *button = element("settings-apply")) {
if (valid && changed)
button->RemoveAttribute("disabled");
else
button->SetAttribute("disabled", true);
}
if (auto *status = element("settings-draft-status"))
status->SetInnerRML(esc(!valid ? "Bitte die Spielwerte prüfen."
: !settings_notice_.empty() ? settings_notice_
: changed ? "Nicht angewendete Änderungen"
: "Keine Änderungen"));
if (auto *style = element("preference-style")) {
if (settings_draft_.at("global").at("sound").at("effects") == true)
style->RemoveAttribute("disabled");
else
style->SetAttribute("disabled", true);
}
Rml::ElementList toggles;
doc_->QuerySelectorAll(toggles, ".settings-switch");
for (auto *toggle : toggles) {
const auto scope = toggle->GetAttribute<Rml::String>("data-scope", ""),
key = toggle->GetAttribute<Rml::String>("data-key", "");
bool on = false, mixed = false;
if (scope == "sound")
on = settings_draft_["global"]["sound"].at(key).get<bool>();
else if (scope == "cell")
on = settings_draft_["local"]["cells"][size_t(settings_index(key))] == 1;
else if (scope == "automation") {
const auto &a = settings_draft_["local"]["automation"];
if (key == "all") {
int n = 0;
for (const auto &[k, v] : a.items())
if (v == true)
++n;
on = n == 5;
mixed = n > 0 && n < 5;
} else
on = a.at(key).get<bool>();
}
toggle->SetClass("checked", on);
toggle->SetClass("mixed", mixed);
toggle->SetAttribute("aria-checked", mixed ? "mixed"
: on ? "true"
: "false");
if (auto *knob = toggle->QuerySelector(".settings-switch-knob"))
knob->SetProperty("left", std::string(mixed ? "25"
: on ? "45"
: "5") +
"dp");
}
for (const auto *theme : {"midnight", "silver", "matchday"})
if (auto *button = element(std::string("settings-theme-") + theme))
button->SetAttribute(
"aria-pressed",
settings_draft_["global"]["theme"] == theme ? "true" : "false");
if (auto *clear = element("settings-search-clear")) {
if (settings_query_.empty())
clear->SetAttribute("disabled", true);
else
clear->RemoveAttribute("disabled");
}
dirty_ = true;
}
void App::settings_filter() {
if (menu_ != "settings" || settings_category_ != "game")
return;
int count = 0;
const auto html = render_settings_groups(&count);
setting_menu_markup_ = true;
if (auto *groups = element("settings-groups"))
groups->SetInnerRML(html);
setting_menu_markup_ = false;
if (auto *label = element("settings-search-count"))
label->SetInnerRML(std::to_string(count) + (settings_query_.empty()
? " Optionen"
: " von 142 Optionen"));
if (auto *select = dynamic_cast<Rml::ElementFormControlSelect *>(
element("settings-jump"))) {
std::string choices;
std::string first;
for (const auto &g : settings_catalogue().at("groups")) {
const auto id = g.at("id").get<std::string>();
const bool shown = element("settings-group-" + id) != nullptr;
if (shown && first.empty())
first = id;
choices += "<option value=\"" + id + "\" " + (shown ? "" : "disabled") +
">" + esc(g.at("title").get<std::string>()) + "</option>";
}
if (!element("settings-group-" + settings_jump_))
settings_jump_ = first;
setting_menu_markup_ = true;
select->SetInnerRML(choices);
select->SetValue(settings_jump_);
setting_menu_markup_ = false;
if (count)
select->RemoveAttribute("disabled");
else
select->SetAttribute("disabled", true);
}
settings_scrolls_["game"] = 0.f;
context_->Update();
if (auto *pane = element("settings-options"))
pane->SetScrollTop(0);
center_selects(*doc_);
settings_sync();
}
bool App::settings_change(Rml::Element *target) {
if (menu_ != "settings" || !target || !settings_draft_.is_object())
return false;
const auto id = target->GetId();
if (id == "settings-search") {
settings_query_ = field(id);
settings_filter();
return true;
}
if (id == "preference-volume") {
try {
settings_draft_["global"]["sound"]["volume"] =
std::clamp(int(std::lround(std::stod(field(id)))), 0, 100);
} catch (const std::exception &) {
return true;
}
if (auto *label = element("settings-volume-value"))
label->SetInnerRML(
std::to_string(
settings_draft_["global"]["sound"]["volume"].get<int>()) +
" %");
settings_notice_.clear();
settings_sync();
return true;
}
const auto scope =
target->GetAttribute<Rml::String>("data-settings-scope", "");
if (scope.empty())
return false;
const auto key = target->GetAttribute<Rml::String>("data-settings-key", ""),
section =
target->GetAttribute<Rml::String>("data-settings-section", "");
const auto value = field(id);
if (scope == "jump") {
if (auto *group = element("settings-group-" + value)) {
settings_jump_ = value;
if (auto *pane = element("settings-options")) {
const auto offset =
group->GetAbsoluteOffset().y - pane->GetAbsoluteOffset().y;
pane->SetScrollTop(pane->GetScrollTop() + offset);
settings_scrolls_["game"] = pane->GetScrollTop();
}
}
dirty_ = true;
return true;
}
if (scope == "global")
settings_draft_["global"][section][key] = value;
else if (scope == "number" || scope == "cell") {
const int index = settings_index(key);
if (index < 0)
return true;
const bool digits = !value.empty() && value.size() <= 2 &&
std::all_of(value.begin(), value.end(), [](char c) {
return c >= '0' && c <= '9';
});
settings_draft_["local"]["cells"][size_t(index)] =
digits ? Json(std::stoi(value)) : Json();
}
settings_notice_.clear();
settings_sync();
return true;
}
void App::settings_commit() {
if (!settings_dirty() || !settings_valid())
return;
const bool local = !settings_global_only();
if (local &&
(settings_source_ != source_.get() || settings_world_ != world_ ||
settings_revision_ != snap().revision)) {
settings_notice_ =
"Die Anzeige ist veraltet. Bitte schließen und erneut öffnen.";
settings_sync();
return;
}
const auto global = settings_draft_.at("global");
const bool changed_global = global != settings_base_.at("global");
const bool changed_local =
local && settings_draft_.at("local") != settings_base_.at("local");
const auto file = ui_preferences_file();
const bool had_file = fs::exists(file);
std::string previous;
try {
if (changed_global) {
if (had_file)
previous = editor::read_file(file);
save_ui_preferences(file, global);
}
if (changed_local) {
const auto result = source_->apply(
{settings_revision_, "settings", settings_draft_.at("local")});
if (!result.ok) {
if (changed_global) {
if (had_file)
editor::write_atomic(file, previous);
else
fs::remove(file);
}
settings_notice_ =
"Änderungen konnten nicht übernommen werden. Bitte erneut öffnen.";
settings_sync();
return;
}
}
} catch (const std::exception &) {
settings_notice_ = "Änderungen konnten nicht gespeichert werden.";
settings_sync();
return;
}
ui_preferences_ = global;
theme_ = global.at("theme").get<std::string>();
if (changed_global)
ui_preferences_loaded_ = true;
reset_settings();
menu_.clear();
refresh();
}
bool App::settings_action(const std::string &action, Rml::Element *target) {
if (!action.starts_with("settings-"))
return false;
if (menu_ != "settings")
return false;
begin_settings();
if (action == "settings-apply") {
settings_commit();
return true;
}
if (action == "settings-cancel") {
reset_settings();
menu_.clear();
refresh();
return true;
}
const auto id =
target ? target->GetAttribute<Rml::String>("data-id", "") : std::string();
if (action == "settings-category") {
if (id != "display" && id != "sound" &&
(settings_global_only() || (id != "game" && id != "automation")))
return true;
settings_remember_scroll();
settings_category_ = id;
focus_after_render_ = "settings-tab-" + id;
refresh();
return true;
}
if (action == "settings-theme") {
if (id == "midnight" || id == "silver" || id == "matchday")
settings_draft_["global"]["theme"] = id;
settings_notice_.clear();
settings_sync();
return true;
}
if (action == "settings-search-clear") {
settings_query_.clear();
if (auto *input =
dynamic_cast<Rml::ElementFormControl *>(element("settings-search")))
input->SetValue("");
settings_filter();
if (auto *input = element("settings-search"))
input->Focus(true);
return true;
}
if (!target)
return true;
if (action == "settings-toggle") {
const auto scope = target->GetAttribute<Rml::String>("data-scope", ""),
key = target->GetAttribute<Rml::String>("data-key", "");
if (scope == "sound" && key == "effects")
settings_draft_["global"]["sound"][key] =
!settings_draft_["global"]["sound"][key].get<bool>();
else if (!settings_global_only() && scope == "cell" &&
settings_index(key) >= 0) {
auto &value =
settings_draft_["local"]["cells"][size_t(settings_index(key))];
value = value == 1 ? 0 : 1;
} else if (!settings_global_only() && scope == "automation") {
auto &a = settings_draft_["local"]["automation"];
if (key == "all") {
const bool on = !std::all_of(a.begin(), a.end(),
[](const Json &v) { return v == true; });
for (auto &[k, v] : a.items())
v = on;
} else if (a.contains(key))
a[key] = !a[key].get<bool>();
}
settings_notice_.clear();
settings_sync();
return true;
}
return false;
}
bool App::settings_event(Rml::Event &event) {
if (menu_ != "settings" || !popup_.empty() || amount_)
return false;
begin_settings();
const auto type = event.GetType();
auto *target = event.GetTargetElement();
if (type == "input" || type == "change") {
if (auto *select = dynamic_cast<Rml::ElementFormControlSelect *>(target);
select && select->IsSelectBoxVisible()) {
pending_selects_.insert(select->GetId());
dirty_ = true;
return true;
}
if (settings_change(target))
return true;
}
const auto pressed_key =
type == "keydown" ? Rml::Input::KeyIdentifier(
event.GetParameter<int>("key_identifier", 0))
: Rml::Input::KI_UNKNOWN;
const int digit =
pressed_key >= Rml::Input::KI_0 && pressed_key <= Rml::Input::KI_9
? pressed_key - Rml::Input::KI_0
: pressed_key >= Rml::Input::KI_NUMPAD0 &&
pressed_key <= Rml::Input::KI_NUMPAD9
? pressed_key - Rml::Input::KI_NUMPAD0
: -1;
const bool numeric_key =
type == "keydown" && !event.GetParameter<int>("ctrl_key", 0) &&
!event.GetParameter<int>("meta_key", 0) &&
!event.GetParameter<int>("alt_key", 0) &&
(digit >= 0 || pressed_key == Rml::Input::KI_RETURN ||
pressed_key == Rml::Input::KI_NUMPADENTER ||
pressed_key == Rml::Input::KI_SPACE ||
pressed_key == Rml::Input::KI_F4 || pressed_key == Rml::Input::KI_UP ||
pressed_key == Rml::Input::KI_DOWN ||
pressed_key == Rml::Input::KI_BACK ||
pressed_key == Rml::Input::KI_DELETE);
if (((type == "mousedown" && event.GetParameter<int>("button", 0) == 0) ||
numeric_key) &&
target->HasAttribute("data-settings-max")) {
const auto key = target->GetAttribute<Rml::String>("data-settings-key", "");
const int index = settings_index(key),
maximum = target->GetAttribute<int>("data-settings-max", 9);
if (index >= 0) {
const auto &old = settings_draft_["local"]["cells"][size_t(index)];
AmountRequest request;
request.title = target->GetAttribute<Rml::String>("data-settings-title",
"Spieloption " + key);
request.return_focus = target->GetId();
request.value = old.is_number_integer() ? old.get<int>() : 0;
request.max = maximum;
request.step = request.suggestion_step = 1;
request.review = false;
request.accept = [this, index](int64_t value) {
if (menu_ != "settings" || !settings_draft_.is_object())
return false;
settings_draft_["local"]["cells"][size_t(index)] = value;
settings_notice_.clear();
return true;
};
open_amount(std::move(request));
if (amount_ && digit >= 0) {
amount_->raw = std::to_string(digit);
amount_select_all_ = false;
amount_caret_end_ = true;
}
event.StopImmediatePropagation();
return true;
}
}
if (type != "keydown")
return false;
const auto key =
Rml::Input::KeyIdentifier(event.GetParameter<int>("key_identifier", 0));
if (auto *select = dynamic_cast<Rml::ElementFormControlSelect *>(target);
select && select->IsSelectBoxVisible())
return false;
if (key == Rml::Input::KI_ESCAPE && target->GetId() == "settings-search" &&
!settings_query_.empty()) {
settings_action("settings-search-clear", nullptr);
event.StopImmediatePropagation();
return true;
}
if (key == Rml::Input::KI_TAB) {
Rml::ElementList controls;
if (auto *canvas = element("canvas"))
canvas->QuerySelectorAll(
controls,
".window button,.window input,.window select,#settings-options");
std::erase_if(controls, [](auto *node) {
return !node->IsVisible(true) || node->HasAttribute("disabled");
});
if (!controls.empty()) {
const auto it = std::find(controls.begin(), controls.end(),
context_->GetFocusElement());
const int pos = it == controls.end() ? -1 : int(it - controls.begin()),
n = int(controls.size());
const bool back = event.GetParameter<int>("shift_key", 0) != 0;
const int next =
pos < 0 ? (back ? n - 1 : 0) : (pos + (back ? -1 : 1) + n) % n;
controls[size_t(next)]->Focus(true);
controls[size_t(next)]->ScrollIntoView(
Rml::ScrollIntoViewOptions(Rml::ScrollAlignment::Nearest));
}
event.StopImmediatePropagation();
return true;
}
if (target->GetId().starts_with("settings-tab-") &&
(key == Rml::Input::KI_UP || key == Rml::Input::KI_DOWN ||
key == Rml::Input::KI_HOME || key == Rml::Input::KI_END)) {
const std::vector<std::string> tabs =
settings_global_only() ? std::vector<std::string>{"display", "sound"}
: std::vector<std::string>{"display", "sound",
"game", "automation"};
const auto it = std::find(tabs.begin(), tabs.end(), settings_category_);
int pos = int(it - tabs.begin());
pos = key == Rml::Input::KI_HOME ? 0
: key == Rml::Input::KI_END
? int(tabs.size() - 1)
: (pos + (key == Rml::Input::KI_UP ? -1 : 1) + int(tabs.size())) %
int(tabs.size());
if (auto *button = element("settings-tab-" + tabs[size_t(pos)]))
settings_action("settings-category", button);
event.StopImmediatePropagation();
return true;
}
return false;
}
+353
View File
@@ -0,0 +1,353 @@
// SPDX-License-Identifier: GPL-3.0-only
bool App::settings_global_only() const { return scene_ == "main" || !source_; }
fs::path App::ui_preferences_file() const {
return config_.preferences.empty()
? root_ / "userdata" / "modern-ui-preferences.json"
: config_.preferences;
}
void App::reset_settings() {
settings_draft_ = Json();
settings_base_ = Json();
settings_notice_.clear();
settings_query_.clear();
settings_jump_ = "rules";
settings_category_ = "display";
settings_scrolls_ = Json::object();
settings_restore_scroll_ = false;
settings_rendered_category_.clear();
settings_world_.reset();
settings_source_ = nullptr;
settings_revision_ = 0;
}
void App::begin_settings() {
if (!settings_draft_.is_null())
return;
settings_draft_ = {{"global", ui_preferences_}};
if (!settings_global_only()) {
const auto s = snap();
settings_draft_["local"] = s.state.at("settings");
settings_revision_ = s.revision;
settings_world_ = s.world;
settings_source_ = source_.get();
}
settings_base_ = settings_draft_;
}
bool App::settings_dirty() const {
return settings_draft_.is_object() && settings_draft_ != settings_base_;
}
bool App::settings_valid() const {
if (!settings_draft_.is_object() ||
!valid_ui_preferences(settings_draft_.at("global")))
return false;
if (settings_global_only())
return true;
auto copy = snap().state;
return edit_demo_settings(copy, settings_draft_.at("local")).empty();
}
std::string App::settings_row(const std::string &id, const std::string &label,
const std::string &help,
const std::string &control) const {
return "<div class=\"settings-row\"><label for=\"" + esc(id) + "\"><span>" +
esc(label) + "</span>" +
(help.empty() ? "" : "<small>" + esc(help) + "</small>") + "</label>" +
control + "</div>";
}
std::string App::settings_switch(const std::string &id,
const std::string &scope,
const std::string &key, bool on,
bool mixed) const {
return btn("settings-toggle",
"<span class=\"settings-switch-knob\" style=\"left:" +
std::string(mixed ? "25"
: on ? "45"
: "5") +
"dp;\"></span>",
"settings-switch " + std::string(on ? "checked " : "") +
(mixed ? "mixed" : ""),
"id=\"" + esc(id) + "\" role=\"switch\" aria-checked=\"" +
(mixed ? "mixed"
: on ? "true"
: "false") +
"\" data-scope=\"" + scope + "\" data-key=\"" + key + "\"");
}
std::string App::settings_select(
const std::string &id,
const std::vector<std::pair<std::string, std::string>> &rows,
const std::string &value, const std::string &scope,
const std::string &section, const std::string &key) const {
std::string out = "<select class=\"settings-select\" id=\"" + id +
"\" data-settings-scope=\"" + scope +
"\" data-settings-section=\"" + section +
"\" data-settings-key=\"" + key + "\">";
for (const auto &[v, label] : rows)
out += "<option value=\"" + esc(v) + "\" " +
(v == value ? "selected " : "") +
(id == "preference-language" && v == "en" ? "disabled " : "") + ">" +
esc(label) + "</option>";
return out + "</select>";
}
std::string App::settings_option(const Json &option) const {
const auto code = option.at("code").get<std::string>(),
id = "game-setting-" + code;
const auto &value =
settings_draft_.at("local").at("cells")[size_t(settings_index(code))];
const auto type = option.at("type").get<std::string>();
std::string control;
if (type == "toggle")
control = settings_switch(id, "cell", code, value == 1);
else if (type == "choice") {
std::vector<std::pair<std::string, std::string>> rows;
for (const auto &choice : option.at("choices"))
rows.emplace_back(std::to_string(choice[0].get<int>()),
choice[1].get<std::string>());
control = settings_select(
id, rows,
value.is_number_integer() ? std::to_string(value.get<int>()) : "",
"cell", "", code);
} else
control =
"<input class=\"settings-number\" type=\"text\" id=\"" + id +
"\" data-settings-scope=\"number\" data-settings-key=\"" + code +
"\" data-settings-title=\"" +
esc(option.at("label").get<std::string>()) + "\" data-settings-max=\"" +
std::to_string(option.at("max").get<int>()) +
"\" maxlength=\"2\" value=\"" +
(value.is_number_integer() ? std::to_string(value.get<int>()) : "") +
"\"/>";
return settings_row(id, option.at("label").get<std::string>(),
option.value("help", ""), control);
}
std::string App::render_settings_groups(int *count) const {
std::istringstream words(settings_search_key(settings_query_));
std::vector<std::string> terms;
for (std::string word; words >> word;)
terms.push_back(word);
int found = 0;
std::string out;
for (const auto &group : settings_catalogue().at("groups")) {
std::string rows;
const auto matches = [&](const Json &o, const std::string &competition) {
const auto text = settings_search_key(
group.at("title").get<std::string>() + " " + competition + " " +
o.at("label").get<std::string>() + " " + o.value("help", ""));
return std::all_of(terms.begin(), terms.end(), [&](const auto &w) {
return text.find(w) != text.npos;
});
};
if (group.contains("options")) {
for (const auto &o : group.at("options"))
if (matches(o, "")) {
rows += settings_option(o);
++found;
}
} else
for (const auto &competition : group.at("competitions")) {
std::string entries;
for (const auto &o : competition.at("options"))
if (matches(o, competition.at("title").get<std::string>())) {
entries += settings_option(o);
++found;
}
if (!entries.empty())
rows += "<div class=\"settings-competition\"><h4>" +
esc(competition.at("title").get<std::string>()) + "</h4>" +
entries + "</div>";
}
if (!rows.empty())
out += "<div id=\"settings-group-" + group.at("id").get<std::string>() +
"\" class=\"settings-group\"><h3>" +
esc(group.at("title").get<std::string>()) + "</h3>" +
(group.contains("help")
? "<p class=\"settings-group-help\">" +
esc(group.at("help").get<std::string>()) + "</p>"
: "") +
rows + "</div>";
}
if (count)
*count = found;
if (!found)
out = "<p class=\"settings-search-empty\"><span>Keine Einstellungen "
"gefunden.</span><small>Versuche einen anderen "
"Suchbegriff.</small></p>";
return out;
}
std::string App::render_settings() {
begin_settings();
settings_remember_scroll();
const auto &p = settings_draft_.at("global");
std::string nav, pane;
const std::array<std::pair<const char *, const char *>, 4> categories{
{{"display", "Anzeige"},
{"sound", "Sound"},
{"game", "Spiel"},
{"automation", "Automatik"}}};
for (const auto &[id, label] : categories)
if (!settings_global_only() || std::string(id) == "display" ||
std::string(id) == "sound")
nav += btn("settings-category", "<span>" + std::string(label) + "</span>",
settings_category_ == id ? "active" : "",
"id=\"settings-tab-" + std::string(id) +
"\" role=\"tab\" aria-selected=\"" +
(settings_category_ == id ? "true" : "false") +
"\" data-id=\"" + id + "\"");
const std::map<std::string, std::pair<std::string, std::string>> captions = {
{"display", {"Anzeige", "Bildschirm und Sprache"}},
{"sound", {"Sound", "Lautstärke, Effekte und Spielton"}},
{"game", {"Spiel", "Spielablauf und Darstellung nach dem Handbuch"}},
{"automation",
{"Automatik",
"Aufstellung, Wechsel, Taktik, Manndeckung und Training"}}};
std::string head = "<div><h2>" + captions.at(settings_category_).first +
"</h2><p>" + captions.at(settings_category_).second +
"</p></div>";
if (settings_category_ == "display") {
pane =
"<div class=\"settings-group\"><h3>Gestaltung</h3><p "
"class=\"settings-group-help\">Wähle deinen Look. Die Gestaltung wird "
"mit „Anwenden“ übernommen.</p><div class=\"settings-theme-options\">";
const std::array<std::array<const char *, 3>, 3> themes{
{{{"midnight", "Midnight Glass",
"Dunkles Glas · ruhige Blautöne · Mint"}},
{{"silver", "Silver Glass",
"Helles Glas · klare Schrift · Silberblau"}},
{{"matchday", "Matchday", "Graphit · klare Flächen · Vereinsrot"}}}};
for (const auto &t : themes) {
const std::string type = t[0];
const auto mini =
"<div class=\"settings-theme-preview preview-" + type +
"\"><div class=\"preview-background\">" +
img("background", 647.333333, 404.583333, false, true, 650) +
"</div><div class=\"preview-bar\"><span></span></div><div "
"class=\"preview-widget one\"></div><div class=\"preview-widget "
"two\"></div><div class=\"preview-app app-one\"></div><div "
"class=\"preview-app app-two\"></div><div class=\"preview-app "
"app-three\"></div><div class=\"preview-window\"><div "
"class=\"preview-title\"><span></span></div><div "
"class=\"preview-line line-one\"></div><div class=\"preview-line "
"line-two\"></div><div class=\"preview-line "
"line-three\"></div></div></div>";
pane +=
btn("settings-theme",
mini + "<strong>" + t[1] + "</strong><small>" + t[2] + "</small>",
"settings-theme-choice",
"id=\"settings-theme-" + type + "\" data-id=\"" + type +
"\" aria-pressed=\"" +
(p.at("theme") == type ? "true" : "false") + "\"");
}
pane += "</div></div><div class=\"settings-group\"><h3>Bildschirm</h3>";
const auto pref =
[&](const char *key, const char *label,
const std::vector<std::pair<std::string, std::string>> &rows,
const char *help = "") {
return settings_row(
std::string("preference-") + key, label, help,
settings_select(std::string("preference-") + key, rows,
p.at("display").at(key).get<std::string>(),
"global", "display", key));
};
pane += pref("mode", "Modus",
{{"fullscreen", "Vollbild"}, {"window", "Fenster"}});
pane += pref("resolution", "Auflösung",
{{"1280x720", "1280 × 720"},
{"1600x900", "1600 × 900"},
{"1920x1080", "1920 × 1080"},
{"2560x1440", "2560 × 1440"},
{"3840x2160", "3840 × 2160"}},
"Beispielauflösungen für den POC.");
pane +=
pref("scale", "Skalierung",
{{"auto", "Auto"}, {"1", "1×"}, {"1.5", "1,5×"}, {"2", "2×"}}) +
"</div><div class=\"settings-group\"><h3>Sprache</h3>" +
pref("language", "Sprache", {{"de", "Deutsch"}, {"en", "Englisch"}}) +
"</div>";
} else if (settings_category_ == "sound") {
const auto &s = p.at("sound");
pane = "<div class=\"settings-group\"><h3>Lautstärke und Effekte</h3>";
pane += settings_row(
"preference-volume", "Lautstärke", "",
"<div class=\"settings-volume\"><input type=\"range\" "
"id=\"preference-volume\" min=\"0\" max=\"100\" step=\"1\" value=\"" +
std::to_string(s.at("volume").get<int>()) +
"\"/><span id=\"settings-volume-value\">" +
std::to_string(s.at("volume").get<int>()) + " %</span></div>");
pane +=
settings_row("preference-effects", "Effekte", "",
settings_switch("preference-effects", "sound", "effects",
s.at("effects").get<bool>()));
pane += settings_row("preference-style", "Effektstil", "",
settings_select(
"preference-style",
{{"classic", "Klassisch"}, {"modern", "Modern"}},
s.at("style").get<std::string>(), "global",
"sound", "style")) +
"</div>";
if (!settings_global_only()) {
pane += "<div class=\"settings-group\"><h3>Ton im Spiel</h3>";
for (const auto &o : settings_catalogue().at("sound"))
pane += settings_option(o);
pane += "</div>";
}
} else if (settings_category_ == "automation") {
const auto &a = settings_draft_.at("local").at("automation");
int on = 0;
for (const auto &[k, v] : a.items())
if (v == true)
++on;
pane = "<div class=\"settings-automation-master\">" +
settings_row("automation-all", "Alles automatisch",
"Alle fünf Bereiche gemeinsam ein- oder ausschalten.",
settings_switch("automation-all", "automation", "all",
on == 5, on > 0 && on < 5)) +
"</div><div class=\"settings-group\"><h3>Aufgaben an den Co-Trainer "
"abgeben</h3><p class=\"settings-group-help\">Die fünf "
"Automatikfunktionen des Originals. Änderungen werden erst mit "
"„Anwenden“ übernommen.</p>";
for (const auto &o : settings_catalogue().at("automation")) {
const auto key = o[0].get<std::string>();
pane += settings_row("automation-" + key, o[1].get<std::string>(),
o[2].get<std::string>(),
settings_switch("automation-" + key, "automation",
key, a.at(key).get<bool>()));
}
pane += "</div>";
} else {
std::vector<std::pair<std::string, std::string>> groups;
for (const auto &g : settings_catalogue().at("groups"))
groups.emplace_back(g.at("id").get<std::string>(),
g.at("title").get<std::string>());
head += "<div class=\"settings-jump-label\"><span>Zum Abschnitt</span>" +
settings_select("settings-jump", groups, settings_jump_, "jump", "",
"") +
"</div>";
pane = "<div id=\"settings-groups\">" + render_settings_groups() + "</div>";
}
const std::string search =
settings_category_ == "game"
? "<div class=\"settings-searchbar\"><div "
"class=\"settings-search-field\">" +
glyph("search", 30) +
"<input type=\"text\" id=\"settings-search\" maxlength=\"120\" "
"value=\"" +
esc(settings_query_) +
"\" placeholder=\"Spieloption suchen …\"/>" +
btn("settings-search-clear", "×", "",
"id=\"settings-search-clear\" aria-label=\"Suche "
"leeren\"") +
"</div><span id=\"settings-search-count\"></span></div>"
: "";
settings_restore_scroll_ = true;
return "<section class=\"settings-layout\"><nav "
"class=\"settings-categories\" role=\"tablist\" "
"aria-orientation=\"vertical\">" +
nav + "</nav><div class=\"settings-pane\" data-category=\"" +
settings_category_ + "\"><header class=\"settings-pane-header\">" +
head + "</header>" + search +
"<div id=\"settings-options\" class=\"settings-scroll\" "
"tabindex=\"0\">" +
pane +
"</div></div></section><div class=\"settings-actions\"><p "
"id=\"settings-draft-status\"></p>" +
btn("settings-cancel", "Abbrechen", "", "id=\"settings-cancel\"") +
btn("settings-apply", "Anwenden", "", "id=\"settings-apply\"") +
"</div>";
}
+37
View File
@@ -0,0 +1,37 @@
// SPDX-License-Identifier: GPL-3.0-only
Json ui_preferences_ = default_ui_preferences();
bool ui_preferences_loaded_ = false;
std::string ui_preferences_error_;
std::string settings_category_ = "display", settings_query_,
settings_jump_ = "rules", settings_notice_,
settings_rendered_category_;
Json settings_draft_, settings_base_, settings_scrolls_ = Json::object();
uint64_t settings_revision_ = 0;
std::shared_ptr<const Catalog> settings_world_;
const DataSource *settings_source_ = nullptr;
bool settings_restore_scroll_ = false;
fs::path ui_preferences_file() const;
void reset_settings();
void begin_settings();
bool settings_global_only() const;
bool settings_dirty() const;
bool settings_valid() const;
std::string render_settings_groups(int *count = nullptr) const;
std::string settings_row(const std::string &, const std::string &,
const std::string &, const std::string &) const;
std::string settings_switch(const std::string &, const std::string &,
const std::string &, bool, bool = false) const;
std::string settings_option(const Json &) const;
std::string
settings_select(const std::string &,
const std::vector<std::pair<std::string, std::string>> &,
const std::string &, const std::string &, const std::string &,
const std::string &) const;
bool settings_action(const std::string &, Rml::Element *);
bool settings_event(Rml::Event &);
bool settings_change(Rml::Element *);
void settings_filter();
void settings_sync();
void settings_remember_scroll();
void settings_after_render();
void settings_commit();
+87
View File
@@ -0,0 +1,87 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "modern/ui/ui_preferences.hpp"
#include <set>
namespace bmh::modern_ui {
namespace {
bool keys(const Json &v, std::initializer_list<const char *> 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<const char *> 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
+12
View File
@@ -0,0 +1,12 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "modern/ui/catalog.hpp"
namespace bmh::modern_ui {
Json default_ui_preferences();
bool valid_ui_preferences(const Json &);
Json legacy_ui_preferences(const Json &);
// A missing file is a normal first launch. Malformed files are reported and
// left intact; callers decide how to present the error without hiding it.
Json load_ui_preferences(const fs::path &);
void save_ui_preferences(const fs::path &, const Json &);
} // namespace bmh::modern_ui
+26 -11
View File
@@ -19,6 +19,8 @@
#include "modern/ui/demo_stadium.hpp"
#include "modern/ui/demo_statistics.hpp"
#include "modern/ui/demo_news.hpp"
#include "modern/ui/demo_settings.hpp"
#include "modern/ui/ui_preferences.hpp"
#include "modern/ui/desktop.hpp"
#include "modern/ui/gui_assets.hpp"
#include "modern/ui/model.hpp"
@@ -408,8 +410,7 @@ class App final : public Rml::EventListener {
int last_tactic_ = 0;
bool draw_playing_ = true;
uint64_t draw_at_ = 0;
std::string settings_category_ = "display";
Json draft_preferences_;
#include "modern/ui/settings_state.inc"
std::map<std::string, std::string> selections_;
Rml::Element *element(const std::string &id) const {
return doc_->GetElementById(id);
@@ -585,6 +586,7 @@ class App final : public Rml::EventListener {
return nullptr;
}
void load_world(const fs::path &file) {
reset_settings();
auto next = Catalog::open(file);
auto demo = std::make_unique<DemoSource>(next);
ticket_.reset();
@@ -807,7 +809,7 @@ class App final : public Rml::EventListener {
pending_selects_.erase(id);
if (auto *select = element(id)) {
// Menu-local select handlers receive only a committed/cancelled value.
if ((menu_ == "lineup" && id.starts_with("lineup-")) ||
if (menu_ == "settings" || (menu_ == "lineup" && id.starts_with("lineup-")) ||
(menu_ == "transfer" && id.starts_with("transfer-")))
select->DispatchEvent("change", {});
else change(select);
@@ -853,6 +855,7 @@ class App final : public Rml::EventListener {
// A window-close save prompt can leave a menu while its local dialog is
// open. Never keep that menu's modal/input gate in the destination view.
if (menu_ != last_rendered_menu_) {
if(last_rendered_menu_=="settings")reset_settings();
statistics_trophy_ = Json::object();
planning_dialog_.clear();
career_view_["dialog"] = ""; career_view_["return_focus"] = "";
@@ -1072,6 +1075,7 @@ class App final : public Rml::EventListener {
if (menu_ == "transfer") transfer_restore_scroll();
if (menu_ == "scorers" || menu_ == "fairplay") rankings_restore_scroll();
if (menu_ == "statistics") statistics_restore_scroll();
if (menu_ == "settings") settings_after_render();
if (!report_option_to_scroll_.empty()) {
if (auto *node = element(report_option_to_scroll_))
node->ScrollIntoView(Rml::ScrollIntoViewOptions(Rml::ScrollAlignment::Nearest));
@@ -1223,8 +1227,15 @@ public:
"mouseup", "mousemove", "contextmenu", "focus"})
doc_->AddEventListener(event, this, Rml::String(event) == "keydown" ||
Rml::String(event) == "blur" || Rml::String(event) == "focus");
if (!config_.theme.empty())
theme_ = config_.theme;
try {
ui_preferences_loaded_=fs::exists(ui_preferences_file());
ui_preferences_=load_ui_preferences(ui_preferences_file());
} catch(const std::exception &) {
ui_preferences_error_="Die gespeicherten UI-Einstellungen konnten nicht geladen werden. Die Standardwerte werden verwendet.";
ui_preferences_=default_ui_preferences();ui_preferences_loaded_=false;
}
theme_=ui_preferences_.at("theme").get<std::string>();
if (!config_.theme.empty()) theme_ = config_.theme;
if (theme_ != "midnight" && theme_ != "silver" && theme_ != "matchday")
throw editor::Error("Unbekanntes Modern-Theme.");
collect_mods();
@@ -1243,19 +1254,21 @@ public:
if (!config_.state.empty() && source_) {
desktop_ = source_->load(config_.state);
saved_desktop_ = desktop_;
if (config_.theme.empty())
theme_ = snap().state.at("preferences").value("theme", theme_);
if (config_.theme.empty() && !ui_preferences_loaded_) {
ui_preferences_=legacy_ui_preferences(snap().state.at("preferences"));
theme_=ui_preferences_.at("theme").get<std::string>();
}
}
if (source_ && !config_.theme.empty()) {
auto preferences = snap().state.at("preferences");
preferences["theme"] = theme_;
apply("preferences", preferences);
if (!config_.theme.empty()) {
// A capture/CLI override is visual only and never edits a career.
ui_preferences_["theme"]=theme_;
}
if (scene_ == "manager" && selections_["manager-name"].empty())
selections_["manager-name"] = "Alex Berger";
doc_->Show();
resize();
render();
if (!ui_preferences_error_.empty()) message(ui_preferences_error_);
SDL_ShowWindow(video_.window);
frame();
} catch (...) {
@@ -1381,6 +1394,8 @@ public:
#include "modern/ui/statistics_controls.inc"
#include "modern/ui/news_screens.inc"
#include "modern/ui/news_controls.inc"
#include "modern/ui/settings_screens.inc"
#include "modern/ui/settings_controls.inc"
} // namespace
bool is_modern_world(const fs::path &file) {
try {
+1 -1
View File
@@ -4,7 +4,7 @@
namespace bmh::modern_ui {
struct Config {
std::filesystem::path world, gui_assets, screenshot, commands, state;
std::filesystem::path world, gui_assets, screenshot, commands, state, preferences;
std::string scene = "main", theme;
int width = 1280, height = 720;
};