Add opt-in native Modern UI foundation and first desktop flow (by Codex)

This commit is contained in:
Codex committed 2026-10-23 18:51:02 +02:00
1 parent a4a37f1cb2
commit 11a6356c1e
42 files changed
+5333 -9

No files matched your search

+54 -3
View File
@@ -32,6 +32,9 @@
#include "launch/game_data.hpp"
#include "launch/launcher.hpp"
#include "launch/startup_error.hpp"
#ifdef OPENBMH_MODERN_UI
#include "modern/ui/view.hpp"
#endif
#include "content/package.hpp"
#include "version.hpp"
#include "app/live_matchday_events.hpp"
@@ -95,6 +98,10 @@ int main(int argc, char** argv) {
rml::attach_parent_console();
const std::vector<std::string> args = launch::utf8_arguments(argc, argv); // (file names beyond the code page)
fs::path data, save_directory;
#ifdef OPENBMH_MODERN_UI
modern_ui::Config modern_ui;
bool modern_demo = false;
#endif
uint32_t seed = uint32_t(std::chrono::system_clock::now().time_since_epoch().count());
bool muted = false, music_enabled = true;
int live_frame_ms = 0;
@@ -104,9 +111,37 @@ int main(int argc, char** argv) {
live_frame_ms_explicit = true;
}
float volume = 1.0F;
try {
for (size_t i = 1; i < args.size(); ++i) {
const auto is = [&](const char* name) { return args[i] == name; };
const bool value = i + 1 < args.size();
#ifdef OPENBMH_MODERN_UI
if (is("--modern-ui-demo")) {
modern_demo = true;
} else if (is("--gui-assets") && value) {
modern_ui.gui_assets = launch::path_from_utf8(args[++i]);
} else if (is("--ui-scene") && value) {
modern_ui.scene = args[++i];
} else if (is("--ui-theme") && value) {
modern_ui.theme = args[++i];
} else if (is("--ui-screenshot") && value) {
modern_ui.screenshot = launch::path_from_utf8(args[++i]);
modern_demo = true;
} else if (is("--ui-script") && value) {
modern_ui.commands = launch::path_from_utf8(args[++i]);
modern_demo = true;
} else if (is("--ui-state") && value) {
modern_ui.state = launch::path_from_utf8(args[++i]);
} else if (is("--ui-size") && value) {
const auto size = args[++i];
const auto separator = size.find('x');
if (separator == std::string::npos) throw std::runtime_error("--ui-size requires WIDTHxHEIGHT");
modern_ui.width = std::stoi(size.substr(0, separator));
modern_ui.height = std::stoi(size.substr(separator + 1));
if (modern_ui.width < 960 || modern_ui.width > 7680 || modern_ui.height < 540 || modern_ui.height > 4320)
throw std::runtime_error("Unsupported Modern UI preview size");
} else
#endif
if (is("--mute")) {
muted = true;
} else if (is("--music")) {
@@ -131,6 +166,11 @@ int main(int argc, char** argv) {
std::printf("usage: OpenBMH [--mod <mods/name/content.obw>] [--seed <Watcom seed>] "
"[--save-directory <directory>] [--mute] [--volume <0..1>] [--no-music] "
"[--live-frame-ms <0..1000>]\n");
#ifdef OPENBMH_MODERN_UI
std::printf("Modern UI preview: --modern-ui-demo --gui-assets <directory> "
"[--ui-scene main|desktop|camp|manager|newgame|tables] "
"[--ui-theme midnight|silver|matchday] [--ui-size WIDTHxHEIGHT]\n");
#endif
return 0;
} else if (args[i].rfind("--", 0) != 0 && data.empty()) {
data = launch::path_from_utf8(args[i]);
@@ -139,6 +179,7 @@ int main(int argc, char** argv) {
return 1;
}
}
}catch(const std::exception &e){show_start_error(e.what());return 1;}
std::filesystem::path executable;
if (char *base = SDL_GetBasePath()) {
executable = launch::path_from_utf8(base);
@@ -150,9 +191,13 @@ int main(int argc, char** argv) {
#endif
} else
executable = fs::absolute(launch::path_from_utf8(args.front()));
if (data.empty()) {
if (data.empty()
#ifdef OPENBMH_MODERN_UI
|| modern_demo || modern_ui::is_modern_world(data)
#endif
) {
try {
return launch::run_launcher(executable, [](const fs::path &package, const fs::path &source,
const launch::SaveMigrator migrate = [](const fs::path &package, const fs::path &source,
const fs::path &destination) {
const auto content = content::open(package);
content::Mount mount(package, content);
@@ -164,7 +209,13 @@ int main(int argc, char** argv) {
if (!migrated.save_game(destination, migrated.state().memory.u8(::bmh::layout::ActiveManager),
false, error))
throw FormatError("Spielstand konnte nicht übernommen werden: " + error);
});
};
#ifdef OPENBMH_MODERN_UI
modern_ui.world = data;
return modern_ui::run(executable, migrate, modern_ui);
#else
return launch::run_launcher(executable, migrate);
#endif
} catch (const std::exception &e) {
show_start_error(e.what());
return 1;
+14 -2
View File
@@ -61,10 +61,22 @@ foreach(component editor_json editor_http editor_images editor_svg editor_xml)
endforeach()
file(APPEND "${CMAKE_BINARY_DIR}/editor-dependencies.json" "}\n")
add_library(bmh_editor_core STATIC archive.cpp world.cpp session.cpp comparison.cpp regulations.cpp images.cpp options.cpp mcp.cpp)
add_library(bmh_asset_io STATIC archive.cpp images.cpp)
target_include_directories(bmh_asset_io PUBLIC ..)
target_link_libraries(bmh_asset_io PUBLIC nlohmann_json::nlohmann_json bmh_content
PRIVATE bmh_miniz ${BMH_SDL_TARGET} SDL2_image::SDL2_image-static lunasvg::lunasvg pugixml::pugixml)
if(MSVC)
target_compile_options(bmh_asset_io PRIVATE /W4 /utf-8)
else()
target_compile_options(bmh_asset_io PRIVATE -Wall -Wextra -Wpedantic)
endif()
if(NOT OPENBMH_BUILD_EDITOR)
return()
endif()
add_library(bmh_editor_core STATIC world.cpp session.cpp comparison.cpp regulations.cpp options.cpp mcp.cpp)
target_compile_definitions(bmh_editor_core PUBLIC OPENBMH_EDITOR_VERSION="${OPENBMH_EDITOR_VERSION}")
target_include_directories(bmh_editor_core PUBLIC .. ${editor_http_SOURCE_DIR})
target_link_libraries(bmh_editor_core PUBLIC nlohmann_json::nlohmann_json bmh_content
target_link_libraries(bmh_editor_core PUBLIC bmh_asset_io nlohmann_json::nlohmann_json bmh_content
PRIVATE bmh_miniz ${BMH_SDL_TARGET} SDL2_image::SDL2_image-static lunasvg::lunasvg pugixml::pugixml)
find_package(Threads REQUIRED)
target_link_libraries(bmh_editor_core PUBLIC Threads::Threads)
+46
View File
@@ -0,0 +1,46 @@
# SPDX-License-Identifier: GPL-3.0-only
add_library(bmh_modern_ui_core STATIC catalog.cpp model.cpp gui_assets.cpp desktop.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)
target_link_libraries(bmh_modern_ui PUBLIC bmh_modern_ui_core PRIVATE bmh_rmlui bmh_launcher nfd::nfd ${BMH_SDL_TARGET})
if(MSVC)
target_compile_options(bmh_modern_ui_core PRIVATE /W4 /utf-8)
target_compile_options(bmh_modern_ui PRIVATE /W4 /utf-8)
else()
target_compile_options(bmh_modern_ui_core PRIVATE -Wall -Wextra -Wpedantic)
target_compile_options(bmh_modern_ui PRIVATE -Wall -Wextra -Wpedantic)
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)
configure_file("${CMAKE_SOURCE_DIR}/assets/modern/${asset}" "${modern_assets}/${asset}" COPYONLY)
endforeach()
file(COPY "${CMAKE_SOURCE_DIR}/assets/modern/icons" DESTINATION "${modern_assets}")
foreach(weight Regular Bold)
configure_file("${rmlui_SOURCE_DIR}/Samples/assets/LatoLatin-${weight}.ttf"
"${modern_assets}/LatoLatin-${weight}.ttf" COPYONLY)
endforeach()
set(BMH_MODERN_GUI_ASSETS "" CACHE PATH "Optional externally supplied Modern GUI resource directory")
if(BMH_MODERN_GUI_ASSETS)
if(NOT EXISTS "${BMH_MODERN_GUI_ASSETS}/gui-assets.json")
message(FATAL_ERROR "BMH_MODERN_GUI_ASSETS does not contain gui-assets.json")
endif()
file(COPY "${BMH_MODERN_GUI_ASSETS}/" DESTINATION "${modern_assets}/gui")
endif()
install(DIRECTORY "${modern_assets}/" DESTINATION assets/modern COMPONENT Runtime)
add_executable(modern_ui_core_tests ../../../tests/modern_ui_core_tests.cpp)
target_link_libraries(modern_ui_core_tests PRIVATE bmh_modern_ui_core)
if(MSVC)
target_compile_options(modern_ui_core_tests PRIVATE /utf-8)
endif()
add_test(NAME modern_ui_core_tests COMMAND modern_ui_core_tests)
add_executable(modern_ticket_document_tests ../../../tests/modern_ticket_document_tests.cpp ticket_popover.cpp)
target_link_libraries(modern_ticket_document_tests PRIVATE bmh_modern_ui_core RmlUi::Core)
if(MSVC)
target_compile_options(modern_ticket_document_tests PRIVATE /utf-8)
endif()
foreach(theme midnight silver matchday)
add_test(NAME modern_ticket_${theme} COMMAND modern_ticket_document_tests "${modern_assets}" ${theme})
endforeach()
+216
View File
@@ -0,0 +1,216 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "modern/ui/catalog.hpp"
#include <algorithm>
#include <array>
#include <limits>
namespace bmh::modern_ui {
std::string localized(const Json &v, const std::string &language) {
if (v.is_string())
return v.get<std::string>();
if (!v.is_object())
return {};
for (const auto &key : {language, std::string("default"), std::string("en")})
if (auto i = v.find(key); i != v.end() && i->is_string() &&
!i->get_ref<const std::string &>().empty())
return i->get<std::string>();
if (v.contains("first") || v.contains("last")) {
const auto first = localized(v.value("first", Json())),
last = localized(v.value("last", Json()));
return first + (first.empty() || last.empty() ? "" : " ") + last;
}
return {};
}
std::string number(int64_t n) {
const auto raw = std::to_string(n);
std::string out;
for (size_t i = 0; i < raw.size(); ++i) {
if (i && raw[i - 1] != '-' && (raw.size() - i) % 3 == 0)
out += '.';
out += raw[i];
}
return out;
}
std::string money(int64_t n, const Json &currency) {
const int units = currency.value("minor_units", 0);
const auto code = currency.value("code", std::string("EUR"));
const auto suffix = code == "EUR" ? " €" : " " + code;
if (!units)
return number(n) + suffix;
if (units != 2)
throw editor::Error("unsupported_currency_precision");
const auto remainder = int(n % 100 < 0 ? -(n % 100) : n % 100);
return (n < 0 && n > -100 ? "-" : "") + number(n / 100) + "," +
(remainder < 10 ? "0" : "") + std::to_string(remainder) + suffix;
}
bool Catalog::modern_manifest(const Json &m) {
if (!m.is_object() || m.value("format", "") != "openbmh-world" ||
m.value("kind", "") != "world")
return false;
const auto required = m.value("requires", Json::array());
if (!required.is_array())
return false;
if (std::find(required.begin(), required.end(), "runtime:modern-v1") !=
required.end())
return true;
return std::find(required.begin(), required.end(), "editor:world-v1") !=
required.end() &&
m.value("x-editor", Json::object()).value("profile", "") ==
"editor-world-v1";
}
std::shared_ptr<const Catalog> Catalog::open(const fs::path &input) {
auto c = std::shared_ptr<Catalog>(new Catalog);
c->source_ = fs::absolute(input).lexically_normal();
c->store_ = editor::ArchiveStore::open(c->source_);
c->manifest_ = Json::parse(c->store_->read("manifest.json"));
if (!modern_manifest(c->manifest_))
throw editor::Error("modern_world_required");
if (!c->manifest_.value("format_version", std::string()).starts_with("1."))
throw editor::Error("unsupported_version");
for (const char *table :
{"nations", "clubs", "players", "competitions", "contracts", "finance",
"staff", "stadiums", "rules", "calendar", "assets"}) {
const auto file = std::string(table) == "assets"
? "assets/index.json"
: std::string("world/") + table + ".json";
Json items = Json::array();
if (c->store_->contains(file)) {
const auto doc = Json::parse(c->store_->read(file));
if (!doc.is_object() || !doc.contains("items") ||
!doc["items"].is_array())
throw editor::Error("invalid_table", {{"file", file}});
items = doc["items"];
} else if (std::string(table) == "clubs" ||
std::string(table) == "players" ||
std::string(table) == "competitions")
throw editor::Error("missing_table", {{"file", file}});
auto &index = c->indices_[table];
for (size_t i = 0; i < items.size(); ++i) {
if (!items[i].is_object())
throw editor::Error("invalid_record", {{"file", file}});
const auto id = items[i].value(
std::string(table) == "assets" ? "key" : "id", std::string());
if (id.empty() || !index.emplace(id, i).second)
throw editor::Error("duplicate_or_missing_id", {{"file", file}});
}
c->tables_[table] = std::move(items);
}
if (const auto file = c->manifest_.value("presentation", std::string());
!file.empty())
c->presentation_ = Json::parse(c->store_->read(file));
for (const auto *league : c->leagues()) {
const auto id = league->value("id", "");
for (const auto *club : c->clubs(id))
if (!c->find("nations", club->value("nation", "")))
throw editor::Error("unknown_nation");
}
return c;
}
const Json &Catalog::rows(const std::string &table) const {
return tables_.at(table);
}
const Json *Catalog::find(const std::string &table,
const std::string &id) const {
const auto t = indices_.find(table);
if (t == indices_.end())
return nullptr;
const auto i = t->second.find(id);
return i == t->second.end() ? nullptr : &tables_.at(table).at(i->second);
}
std::string Catalog::title() const {
return localized(manifest_.value("title", Json()));
}
std::string Catalog::name(const Json &row) const {
return localized(row.value("name", Json()));
}
std::string Catalog::nation_name(const std::string &id) const {
const auto *n = find("nations", id);
return n ? name(*n) : id;
}
std::vector<const Json *> Catalog::leagues(const std::string &nation) const {
std::vector<const Json *> out;
for (const auto &r : rows("competitions"))
if (r.value("type", "") == "league" &&
(nation.empty() || r.value("nation", "") == nation))
out.push_back(&r);
return out;
}
std::vector<const Json *> Catalog::clubs(const std::string &league) const {
std::vector<const Json *> out;
for (const auto &r : rows("clubs"))
if (r.value("type", "club") == "club" &&
(league.empty() || r.value("competition", "") == league))
out.push_back(&r);
return out;
}
std::vector<const Json *> Catalog::squad(const std::string &club) const {
std::vector<const Json *> out;
for (const auto &r : rows("players"))
if (r.value("team", "") == club)
out.push_back(&r);
std::stable_sort(out.begin(), out.end(), [](auto a, auto b) {
return a->value("squad_order", 999) < b->value("squad_order", 999);
});
return out;
}
bool Catalog::manageable(const std::string &club) const {
const auto *r = find("clubs", club);
const auto *league =
r ? find("competitions", r->value("competition", "")) : nullptr;
return r && r->value("type", "club") == "club" &&
r->value("nation", "") == "nation:de" && league &&
league->value("nation", "") == "nation:de" &&
league->value("type", "") == "league";
}
std::pair<std::string, std::string> Catalog::asset(const std::string &key,
int pixels) const {
const auto *a = find("assets", key);
if (!a && !presentation_.is_null() && key.find("/photo") != std::string::npos)
a = find("assets", presentation_.value("player_photo_fallback", ""));
if (!a)
return {};
const auto files = a->value("files", Json::object());
std::string file;
if (files.contains("svg") && files["svg"].is_string())
file = files["svg"].get<std::string>();
if (file.empty()) {
std::vector<std::pair<int, std::string>> candidates;
for (const auto &[size, value] : files.items()) {
if (!value.is_string() || size == "native" || size == "svg")
continue;
try {
candidates.emplace_back(std::stoi(size), value.get<std::string>());
} catch (const std::exception &) {
if (file.empty())
file = value.get<std::string>();
}
}
if (!candidates.empty()) {
std::sort(candidates.begin(), candidates.end());
file = candidates.back().second;
for (const auto &[size, name] : candidates)
if (size >= pixels) {
file = name;
break;
}
}
}
if (file.empty())
file = files.value("native", "");
if (file.empty() || !store_->contains(file))
return {};
return {store_->read(file), fs::path(file).extension().string()};
}
Json Catalog::summary() const {
Json leagues_json = Json::array();
for (auto *r : leagues())
leagues_json.push_back({{"id", r->value("id", "")},
{"name", name(*r)},
{"clubs", clubs(r->value("id", "")).size()}});
return {{"title", title()},
{"leagues", leagues_json},
{"clubs", rows("clubs").size()},
{"players", rows("players").size()},
{"engine", false}};
}
} // namespace bmh::modern_ui
+40
View File
@@ -0,0 +1,40 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "editor/archive.hpp"
#include <unordered_map>
namespace bmh::modern_ui {
using Json = editor::Json;
namespace fs = std::filesystem;
// Immutable presentation data. This reader does not construct a game state.
class Catalog {
public:
static std::shared_ptr<const Catalog> open(const fs::path &);
static bool modern_manifest(const Json &);
const Json &manifest() const { return manifest_; }
const Json &rows(const std::string &) const;
const Json *find(const std::string &, const std::string &) const;
std::string title() const;
std::string name(const Json &) const;
std::string nation_name(const std::string &) const;
std::vector<const Json *> leagues(const std::string &nation = {}) const;
std::vector<const Json *> clubs(const std::string &league = {}) const;
std::vector<const Json *> squad(const std::string &) const;
bool manageable(const std::string &) const;
std::pair<std::string, std::string> asset(const std::string &,
int pixels = 512) const;
Json summary() const;
const fs::path &source() const { return source_; }
private:
fs::path source_;
std::shared_ptr<editor::ArchiveStore> store_;
Json manifest_, presentation_;
std::map<std::string, Json> tables_;
std::map<std::string, std::unordered_map<std::string, size_t>> indices_;
};
std::string localized(const Json &, const std::string &language = "de");
std::string number(int64_t);
std::string money(int64_t, const Json &currency);
} // namespace bmh::modern_ui
File diff suppressed because it is too large. Load diff
+239
View File
@@ -0,0 +1,239 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "modern/ui/desktop.hpp"
#include <algorithm>
#include <cmath>
#include <limits>
namespace bmh::modern_ui {
namespace {
constexpr int pitch = 248, gap = 24, cell = 224, left = 64, top = 224;
bool overlaps(const Json &a, const Json &b, int spacing) {
const int x = a.at("x"), y = a.at("y"), bx = b.at("x"), by = b.at("y");
return x < bx + b.at("w").get<int>() + spacing &&
x + a.at("w").get<int>() + spacing > bx &&
y < by + b.at("h").get<int>() + spacing &&
y + a.at("h").get<int>() + spacing > by;
}
bool find_space(Json &layout, const std::string &id, int near_x, int near_y,
bool nearest) {
auto &object = layout.at("objects").at(id);
const int width = object.at("w"), height = object.at("h");
const bool grid = layout.value("grid", true);
const int step = grid ? pitch : 32;
double best = std::numeric_limits<double>::max();
int found_x = -1, found_y = -1;
for (int y = top; y + height <= 2160 - gap; y += step) {
for (int x = left; x + width <= 3840 - gap; x += step) {
Json candidate = object;
candidate["x"] = x;
candidate["y"] = y;
bool collision = false;
for (const auto &[other_id, other] : layout.at("objects").items()) {
if (other_id != id && other.value("visible", false) &&
overlaps(candidate, other, grid ? gap : 20)) {
collision = true;
break;
}
}
if (collision)
continue;
const double distance = nearest ? std::hypot(x - near_x, y - near_y) : 0;
if (distance < best) {
best = distance;
found_x = x;
found_y = y;
}
if (!nearest)
break;
}
if (!nearest && found_x >= 0)
break;
}
if (found_x < 0)
return false;
object["x"] = found_x;
object["y"] = found_y;
return true;
}
Json object(int column, int row, int columns, int rows, bool widget,
bool visible) {
return {{"x", left + column * pitch},
{"y", top + row * pitch},
{"w", columns * pitch - gap},
{"h", rows * pitch - gap},
{"pinned", true},
{"visible", visible},
{"widget", widget}};
}
} // namespace
const std::vector<std::string> &desktop_routes() {
static const std::vector<std::string> value = {
"tables", "league", "strengths", "lineup", "achievements",
"other", "friendlies", "postpone", "calendar", "indoor",
"load", "save", "kickoff", "toto", "bank",
"camp", "training", "transfer", "tactics", "settings",
"scorers", "advertising", "stadium", "statistics", "environment",
"fairplay", "highscore", "contracts", "balance", "newplayer",
"news"};
return value;
}
const std::vector<WidgetDefinition> &widget_definitions() {
static const std::vector<WidgetDefinition> value = {
{"calendar", "Kalender", {{2, 2}, {2, 3}, {3, 3}}},
{"account", "Konto & Eintritt", {{4, 1}, {2, 2}, {4, 2}, {4, 3}}},
{"competition", "Wettbewerb & Gegner", {{2, 2}, {4, 2}, {4, 3}}},
{"portrait", "Managerporträt", {{2, 2}, {3, 3}}},
{"crest", "Vereinswappen", {{2, 2}, {3, 3}}},
{"opponent-crest", "Gegnerwappen", {{2, 2}, {3, 3}}},
{"warnings", "Warnlampen", {{4, 1}, {2, 2}, {4, 2}, {4, 3}}},
{"fans", "Fan-Stimmung", {{2, 1}, {4, 1}}},
{"own-curve",
"Tabellenplatz · eigener Verein",
{{2, 2}, {3, 3}, {4, 2}, {4, 4}}},
{"opponent-curve",
"Tabellenplatz · Gegner",
{{2, 2}, {3, 3}, {4, 2}, {4, 4}}},
{"comparison-curve",
"Tabellenplätze · Vergleich",
{{3, 3}, {4, 2}, {4, 4}}},
{"results", "Letzte sechs Spiele", {{4, 1}, {2, 2}, {4, 2}, {4, 4}}},
{"duels", "Direkter Vergleich", {{2, 2}, {4, 2}}},
{"own-summary", "Platz & Stärke · eigener Verein", {{2, 1}, {4, 1}}},
{"opponent-summary", "Platz & Stärke · Gegner", {{2, 1}, {4, 1}}},
{"news", "Nachrichten", {{2, 2}, {4, 2}, {4, 4}}},
{"trash", "Papierkorb", {{1, 1}, {2, 2}}}};
return value;
}
Json default_desktop() {
Json layout = {{"schema", "openbmh-modern-desktop@1"},
{"grid", true},
{"objects", Json::object()}};
for (const auto &definition : widget_definitions()) {
const auto [w, h] = definition.sizes.front();
layout["objects"][definition.id] = object(0, 0, w, h, true, false);
}
auto &objects = layout["objects"];
objects["calendar"] = object(0, 0, 2, 3, true, true);
objects["account"] = object(2, 0, 4, 2, true, true);
objects["competition"] = object(2, 2, 4, 2, true, true);
objects["portrait"] = object(6, 0, 2, 2, true, true);
objects["crest"] = object(8, 0, 2, 2, true, true);
objects["opponent-crest"] = object(10, 0, 2, 2, true, true);
objects["warnings"] = object(6, 2, 4, 2, true, true);
objects["trash"] = object(14, 6, 1, 1, true, true);
for (const auto &route : desktop_routes()) {
const auto id = "app-" + route;
objects[id] = object(0, 0, 1, 1, false, false);
if (!find_space(layout, id, left, top, false))
throw editor::Error("default_desktop_full");
objects[id]["visible"] = true;
}
return layout;
}
bool valid_desktop(const Json &layout) {
try {
if (layout.at("schema") != "openbmh-modern-desktop@1" ||
!layout.at("grid").is_boolean())
return false;
const auto &objects = layout.at("objects");
if (!objects.is_object() ||
objects.size() != widget_definitions().size() + desktop_routes().size())
return false;
const auto check = [&](const std::string &id, bool widget) {
const auto &o = objects.at(id);
for (const auto *key : {"x", "y", "w", "h"})
if (!o.at(key).is_number_integer() || o.at(key) < 0 || o.at(key) > 3840)
return false;
if (!o.at("visible").is_boolean() || !o.at("pinned").is_boolean() ||
o.at("widget") != widget)
return false;
const int x = o.at("x"), y = o.at("y"), w = o.at("w"), h = o.at("h");
return w > 0 && h > 0 && w <= 3840 && h <= 2160 - top && x >= 0 &&
y >= top && x <= 3840 - w && y <= 2160 - h &&
(widget || (w == cell && h == cell && o.at("visible") == true));
};
for (const auto &d : widget_definitions()) {
if (!check(d.id, true))
return false;
const auto &o = objects.at(d.id);
if (std::none_of(d.sizes.begin(), d.sizes.end(), [&](auto s) {
return o.at("w") == s.first * pitch - gap &&
o.at("h") == s.second * pitch - gap;
}))
return false;
}
for (const auto &route : desktop_routes())
if (!check("app-" + route, false))
return false;
return true;
} catch (const Json::exception &) {
return false;
}
}
bool place_desktop_object(Json &layout, const std::string &id, int x, int y,
bool nearest) {
if (!valid_desktop(layout) || !layout["objects"].contains(id))
return false;
auto next = layout;
auto &o = next["objects"][id];
if (o.at("pinned") == true)
return false;
if (!next.at("grid").get<bool>()) {
o["x"] = std::clamp(x, 0, 3840 - o.at("w").get<int>());
o["y"] = std::clamp(y, top, 2160 - o.at("h").get<int>());
} else if (!find_space(next, id, x, y, nearest))
return false;
o["visible"] = true;
layout = std::move(next);
return true;
}
bool resize_desktop_widget(Json &layout, const std::string &id, int columns,
int rows) {
if (!valid_desktop(layout))
return false;
const auto found =
std::find_if(widget_definitions().begin(), widget_definitions().end(),
[&](const auto &d) { return d.id == id; });
if (found == widget_definitions().end() ||
std::find(found->sizes.begin(), found->sizes.end(),
std::pair{columns, rows}) == found->sizes.end())
return false;
auto next = layout;
auto &o = next["objects"][id];
if (o.at("pinned") == true)
return false;
o["w"] = columns * pitch - gap;
o["h"] = rows * pitch - gap;
if (!find_space(next, id, o.at("x"), o.at("y"), true))
return false;
o["visible"] = true;
layout = std::move(next);
return true;
}
bool arrange_desktop(Json &layout) {
if (!valid_desktop(layout))
return false;
auto next = layout;
next["grid"] = true;
std::vector<std::string> loose;
for (auto &[id, o] : next["objects"].items())
if (o.at("visible") == true && o.at("pinned") == false) {
loose.push_back(id);
o["visible"] = false;
}
std::stable_sort(
loose.begin(), loose.end(), [&](const auto &a, const auto &b) {
const auto &x = next["objects"][a], &y = next["objects"][b];
return x.at("w").template get<int>() * x.at("h").template get<int>() >
y.at("w").template get<int>() * y.at("h").template get<int>();
});
for (const auto &id : loose) {
auto &o = next["objects"][id];
if (!find_space(next, id, o.at("x"), o.at("y"), false))
return false;
o["visible"] = true;
}
layout = std::move(next);
return true;
}
} // namespace bmh::modern_ui
+20
View File
@@ -0,0 +1,20 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "modern/ui/catalog.hpp"
namespace bmh::modern_ui {
struct WidgetDefinition {
std::string id, name;
std::vector<std::pair<int, int>> sizes;
};
const std::vector<WidgetDefinition> &widget_definitions();
const std::vector<std::string> &desktop_routes();
// These operations stage the whole layout. Failed placement leaves it
// untouched.
Json default_desktop();
bool valid_desktop(const Json &);
bool place_desktop_object(Json &, const std::string &, int x, int y,
bool nearest = true);
bool resize_desktop_widget(Json &, const std::string &, int columns, int rows);
bool arrange_desktop(Json &);
} // namespace bmh::modern_ui
+92
View File
@@ -0,0 +1,92 @@
// SPDX-License-Identifier: GPL-3.0-only
std::string App::render_desktop_tools(const std::string &key) {
init_desktop();
if (key == "background")
return "<div class=\"center\" style=\"padding:90dp;\">" +
img("background", 2200, 1240, false, true, 1800) +
"<h2 style=\"margin-top:45dp;\">Stadion bei Nacht</h2><p "
"class=\"muted\" style=\"margin-top:20dp;\">Aktueller "
"Hintergrund</p></div>";
if (key == "widgets") {
std::string body =
"<div class=\"list\" "
"style=\"position:absolute;left:0;right:0;top:0;bottom:0;\">";
size_t i = 0;
for (const auto &definition : widget_definitions()) {
const auto &o = desktop_["objects"].at(definition.id);
body += "<div class=\"gallery-card panel\" style=\"left:" +
std::to_string((i % 3) * 870) +
"dp;top:" + std::to_string((i / 3) * 480) + "dp;\"><h2>" +
esc(definition.name) + "</h2><p>";
for (auto [w, h] : definition.sizes)
body += std::to_string(w) + " × " + std::to_string(h) + " &nbsp; ";
body += "</p>" +
btn("widget-add",
o.value("visible", false) ? "Bereits auf dem Desktop"
: "Hinzufügen",
{},
"data-id=\"" + definition.id +
"\" "
"style=\"position:absolute;left:30dp;right:30dp;bottom:"
"30dp;\" " +
(o.value("visible", false) ? "disabled" : "")) +
"</div>";
++i;
}
return body + "</div>";
}
const bool saving = key == "view-save";
const auto directory = user_dir() / "layouts";
std::vector<std::string> names;
if (fs::exists(directory))
for (const auto &entry : fs::directory_iterator(directory))
if (entry.is_regular_file() && entry.path().extension() == ".json")
names.push_back(editor::utf8(entry.path().stem()));
std::sort(names.begin(), names.end());
std::string body = "<div class=\"panel list\" "
"style=\"position:absolute;left:0;top:0;width:1000dp;"
"bottom:150dp;padding:24dp;\">";
if (!saving)
body += btn("view-default", "Standardansicht · fixiert", "choice",
"style=\"width:100%;height:120dp;text-align:left;margin-bottom:"
"18dp;\"");
for (const auto &name : names)
body += btn("view-select", esc(name),
std::string("choice ") +
(name == selections_["view"] ? "selected" : ""),
"data-id=\"" + esc(name) +
"\" "
"style=\"width:100%;height:120dp;text-align:left;margin-"
"bottom:18dp;\"");
body +=
"</div><div class=\"panel\" "
"style=\"position:absolute;left:1040dp;right:0;top:0;bottom:150dp;"
"padding:50dp;\"><h2>" +
std::string(saving ? "Aktuelle Ansicht speichern"
: selections_["view"].empty() ? "Ansicht auswählen"
: esc(selections_["view"])) +
"</h2>";
if (!selections_["view"].empty()) {
launch::ModLibrary::validate_name(selections_["view"]);
auto preview = directory / editor::path(selections_["view"] + ".png");
if (fs::is_regular_file(preview))
body += "<img src=\"" + renderer_.local_image(preview, 1400).token +
"\" style=\"width:1400dp;height:787.5dp;margin-top:70dp;\"/>";
}
if (saving)
body += "<div class=\"field-row\" "
"style=\"margin-top:70dp;\"><label>Bezeichnung</label><input "
"id=\"view-name\" value=\"" +
esc(selections_["view"].empty() ? "Meine Ansicht"
: selections_["view"]) +
"\"/></div>";
body += "</div><div class=\"bottom-controls\">" +
btn("view-delete", "Löschen", {},
selections_["view"].empty() ? "disabled" : "") +
btn("close", "Abbrechen") +
btn(saving ? "view-save-confirm" : "view-load-confirm",
saving ? "Speichern" : "Laden", "primary",
!saving && selections_["view"].empty() ? "disabled" : "") +
"</div>";
return body;
}
+62
View File
@@ -0,0 +1,62 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "modern/ui/gui_assets.hpp"
#include <algorithm>
#include <cmath>
namespace bmh::modern_ui {
GuiAssets::GuiAssets(fs::path root) : root_(std::move(root)) {
if (root_.empty() || !fs::exists(root_ / "gui-assets.json"))
return;
root_ = fs::weakly_canonical(root_);
auto document = Json::parse(editor::read_file(root_ / "gui-assets.json"));
if (document.value("schema", "") != "openbmh-gui-assets@1" ||
!document.at("items").is_object())
throw editor::Error("invalid_gui_catalog");
items_ = document.at("items");
for (const auto &[key, item] : items_.items()) {
const auto relative = editor::path(item.at("file").get<std::string>());
const auto full = fs::weakly_canonical(root_ / relative);
const auto inside = full.lexically_relative(root_);
if (relative.is_absolute() || inside.empty() || *inside.begin() == ".." ||
!fs::is_regular_file(full))
throw editor::Error("missing_or_unsafe_gui_asset", {{"key", key}});
}
}
editor::images::Raster GuiAssets::decode(const std::string &key,
int pixels) const {
if (!items_.contains(key))
throw editor::Error("missing_gui_asset", {{"key", key}});
const auto item = items_.at(key);
const auto file = root_ / editor::path(item.at("file").get<std::string>());
auto image = editor::images::decode(editor::read_file(file),
file.extension().string(), pixels);
if (!item.contains("crop"))
return image;
const auto crop = item.at("crop");
if (!crop.is_array() || crop.size() != 4)
throw editor::Error("invalid_gui_crop");
for (const auto &n : crop)
if (!n.is_number() || !std::isfinite(n.get<double>()) || n < 0 || n > 1)
throw editor::Error("invalid_gui_crop");
if (crop[2] <= 0 || crop[3] <= 0 ||
crop[0].get<double>() + crop[2].get<double>() > 1.000001 ||
crop[1].get<double>() + crop[3].get<double>() > 1.000001)
throw editor::Error("invalid_gui_crop");
const auto x = std::clamp(
int(std::round(crop[0].get<double>() * image.width)), 0, image.width - 1);
const auto y =
std::clamp(int(std::round(crop[1].get<double>() * image.height)), 0,
image.height - 1);
const auto width = std::clamp(
int(std::round(crop[2].get<double>() * image.width)), 1, image.width - x);
const auto height =
std::clamp(int(std::round(crop[3].get<double>() * image.height)), 1,
image.height - y);
editor::images::Raster out{width, height,
std::vector<uint8_t>(size_t(width) * height * 4)};
for (int row = 0; row < height; ++row)
std::copy_n(image.pixels.data() + (size_t(y + row) * image.width + x) * 4,
size_t(width) * 4, out.pixels.data() + size_t(row) * width * 4);
return out;
}
} // namespace bmh::modern_ui
+20
View File
@@ -0,0 +1,20 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "editor/images.hpp"
#include "modern/ui/catalog.hpp"
namespace bmh::modern_ui {
class GuiAssets {
public:
explicit GuiAssets(fs::path root = {});
bool available() const { return !items_.empty(); }
editor::images::Raster decode(const std::string &, int pixels = 1024) const;
bool contains(const std::string &key) const { return items_.contains(key); }
const Json &items() const { return items_; }
const fs::path &root() const { return root_; }
private:
fs::path root_;
Json items_ = Json::object();
};
} // namespace bmh::modern_ui
+184
View File
@@ -0,0 +1,184 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "modern/ui/model.hpp"
#include "modern/ui/desktop.hpp"
#include <algorithm>
#include <chrono>
namespace bmh::modern_ui {
namespace {
bool valid_date(const Json &value) {
if (!value.is_string())
return false;
const auto text = value.get<std::string>();
if (text.size() != 10 || text[4] != '-' || text[7] != '-')
return false;
for (size_t i = 0; i < text.size(); ++i)
if (i != 4 && i != 7 && (text[i] < '0' || text[i] > '9'))
return false;
const int year = std::stoi(text.substr(0, 4)),
month = std::stoi(text.substr(5, 2)),
day = std::stoi(text.substr(8, 2));
return year > 0 &&
std::chrono::year_month_day{std::chrono::year{year},
std::chrono::month{unsigned(month)},
std::chrono::day{unsigned(day)}}
.ok();
}
bool camp_id(const Json &value) {
if (!value.is_string())
return false;
const auto id = value.get<std::string>();
for (int i = 0; i < 18; ++i)
if (id == "resort:" + std::to_string(i))
return true;
return false;
}
bool preferences(const Json &value) {
if (!value.is_object())
return false;
const auto theme = value.value("theme", std::string("midnight"));
return (theme == "midnight" || theme == "silver" || theme == "matchday") &&
(!value.contains("volume") ||
(value["volume"].is_number_integer() && value["volume"] >= 0 &&
value["volume"] <= 100)) &&
(!value.contains("effects") || value["effects"].is_boolean());
}
} // namespace
DemoSource::DemoSource(std::shared_ptr<const Catalog> catalog)
: catalog_(std::move(catalog)) {
std::string club;
for (const auto *c : catalog_->clubs()) {
if (!catalog_->manageable(c->value("id", "")))
continue;
club = c->value("id", "");
break;
}
if (club.empty())
throw editor::Error("no_manageable_demo_club");
state_ = {
{"schema", "openbmh-ui-demo@1"},
{"world", catalog_->manifest().value("id", "")},
{"date", catalog_->manifest().value("start_date", "2026-07-01")},
{"managers",
Json::array(
{{{"name", "Alex Berger"}, {"club", club}, {"portrait", 0}}})},
{"cash", 12450000},
{"deposit", 600000},
{"debt", 0},
{"ticket", 13},
{"fans", 67},
{"camp",
{{"selected", "resort:4"}, {"confirmed", ""}, {"focus", {5, 4, 6}}}},
{"opening", "complete"},
{"preferences",
{{"theme", "midnight"}, {"volume", 80}, {"effects", true}}},
{"edits", Json::object()}};
saved_ = state_;
if (!valid_date(state_.at("date")))
throw editor::Error("invalid_demo_date");
}
Snapshot DemoSource::snapshot() const { return {revision_, catalog_, state_}; }
ActionResult DemoSource::apply(const Action &action) {
if (action.revision != revision_)
return {false, revision_, "stale_revision"};
auto next = state_;
try {
if (action.kind == "ticket") {
if (!action.value.is_number_integer() || action.value < 0 ||
action.value > 25)
return {false, revision_, "invalid_demo_ticket"};
next["ticket"] = action.value;
} else if (action.kind == "managers") {
if (!action.value.is_array() || action.value.empty() ||
action.value.size() > 4)
return {false, revision_, "invalid_managers"};
std::set<std::string> clubs;
std::set<int> portraits;
for (const auto &m : action.value) {
const auto club = m.at("club").get<std::string>();
const auto name = m.at("name").get<std::string>();
if (!catalog_->manageable(club))
return {false, revision_, "club_locked"};
const auto portrait = m.value("portrait", 0);
if (name.find_first_not_of(" \t\r\n") == name.npos ||
name.size() > 160 || portrait < 0 || portrait > 11 ||
!clubs.insert(club).second || !portraits.insert(portrait).second)
return {false, revision_, "invalid_manager"};
}
next["managers"] = action.value;
} else if (action.kind == "camp.select") {
if (!camp_id(action.value))
return {false, revision_, "camp_unknown"};
next["camp"]["selected"] = action.value;
} else if (action.kind == "camp.focus") {
if (!action.value.is_array() || action.value.size() != 3)
return {false, revision_, "invalid_focus"};
for (const auto &v : action.value)
if (!v.is_number_integer() || v < 0 || v > 15)
return {false, revision_, "invalid_focus"};
next["camp"]["focus"] = action.value;
} else if (action.kind == "camp.remember")
next["camp"]["confirmed"] = next["camp"]["selected"];
else if (action.kind == "opening")
next["opening"] = action.value;
else if (action.kind == "preferences") {
if (!preferences(action.value))
return {false, revision_, "invalid_preferences"};
next["preferences"] = action.value;
} else if (action.kind == "edit") {
const auto key = action.value.at("key").get<std::string>();
if (key.empty() || key.size() > 100)
return {false, revision_, "invalid_edit"};
next["edits"][key] = action.value.at("value");
} else
return {false, revision_, "unsupported_demo_action"};
} catch (const Json::exception &) {
return {false, revision_, "invalid_action"};
}
state_ = std::move(next);
return {true, ++revision_, {}};
}
void DemoSource::save(const fs::path &file, const Json &desktop) {
if (!valid_desktop(desktop))
throw editor::Error("invalid_demo_desktop");
auto out = state_;
out["desktop"] = desktop;
editor::write_atomic(file, out.dump(2));
saved_ = state_;
}
Json DemoSource::load(const fs::path &file) {
const auto data = Json::parse(editor::read_file(file));
if (data.value("schema", "") != "openbmh-ui-demo@1" ||
data.value("world", "") != catalog_->manifest().value("id", ""))
throw editor::Error("wrong_demo_world");
auto validation = DemoSource(catalog_);
const auto result = validation.apply({0, "managers", data.at("managers")});
if (!result.ok)
throw editor::Error(result.error);
if (!data.at("ticket").is_number_integer() || data.at("ticket") < 0 ||
data.at("ticket") > 25)
throw editor::Error("invalid_demo_ticket");
for (const auto *key : {"cash", "deposit", "debt", "fans"})
if (!data.at(key).is_number_integer())
throw editor::Error("invalid_demo_number");
if (!valid_date(data.at("date")) || !preferences(data.at("preferences")) ||
!data.at("edits").is_object() || !data.at("opening").is_string() ||
!camp_id(data.at("camp").at("selected")))
throw editor::Error("invalid_demo_state");
const auto &focus = data.at("camp").at("focus");
if (!focus.is_array() || focus.size() != 3)
throw editor::Error("invalid_focus");
for (const auto &v : focus)
if (!v.is_number_integer() || v < 0 || v > 15)
throw editor::Error("invalid_focus");
auto next = data;
const auto desktop = next.value("desktop", Json::object());
if (!valid_desktop(desktop))
throw editor::Error("invalid_demo_desktop");
next.erase("desktop");
state_ = std::move(next);
saved_ = state_;
++revision_;
return desktop;
}
} // namespace bmh::modern_ui
+42
View File
@@ -0,0 +1,42 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "modern/ui/catalog.hpp"
namespace bmh::modern_ui {
struct Snapshot {
uint64_t revision = 0;
std::shared_ptr<const Catalog> world;
Json state;
};
struct Action {
uint64_t revision = 0;
std::string kind;
Json value;
};
struct ActionResult {
bool ok = false;
uint64_t revision = 0;
std::string error;
};
// The native view depends on this presentation boundary, never on GameState.
class DataSource {
public:
virtual ~DataSource() = default;
virtual Snapshot snapshot() const = 0;
virtual ActionResult apply(const Action &) = 0;
};
class DemoSource final : public DataSource {
public:
explicit DemoSource(std::shared_ptr<const Catalog>);
Snapshot snapshot() const override;
ActionResult apply(const Action &) override;
void save(const fs::path &, const Json &desktop);
Json load(const fs::path &);
bool dirty() const { return state_ != saved_; }
private:
std::shared_ptr<const Catalog> catalog_;
Json state_, saved_;
uint64_t revision_ = 0;
};
} // namespace bmh::modern_ui
+958
View File
@@ -0,0 +1,958 @@
// SPDX-License-Identifier: GPL-3.0-only
// Included in the native UI implementation's anonymous namespace.
void App::init_desktop() {
if (!desktop_.contains("objects")) {
desktop_ = default_desktop();
saved_desktop_ = desktop_;
}
}
std::string App::widget(const std::string &id, const Json &o) {
const auto s = snap();
const auto *own = club(s);
const auto w = o.value("w", 472), h = o.value("h", 472);
const auto row = world_->clubs(own ? own->value("competition", "") : league_);
const auto *opponent =
row.size() > 1 ? (row[0] == own ? row[1] : row[0]) : own;
auto heading = [&](const std::string &name) {
return "<div class=\"card-heading\">" + esc(name) + "</div>";
};
if (id == "calendar") {
const auto date = s.state.value("date", std::string("2026-07-01"));
const auto year = date.substr(0, 4), day = date.substr(8, 2);
const int month = std::stoi(date.substr(5, 2));
const std::array<const char *, 12> months = {
"Januar", "Februar", "März", "April", "Mai", "Juni",
"Juli", "August", "September", "Oktober", "November", "Dezember"};
return "<div "
"style=\"height:116dp;background-color:#a45254;color:white;text-"
"align:center;padding-top:30dp;font-size:38dp;\">" +
std::string(months[size_t(std::clamp(month, 1, 12) - 1)]) + " " +
year +
"</div><div class=\"center\" style=\"padding-top:66dp;\"><p "
"class=\"muted\" style=\"font-size:38dp;\">Saisonvorbereitung</p><p "
"style=\"font-size:240dp;line-height:1.1;\">" +
std::to_string(std::stoi(day)) + "</p><p class=\"small\">" +
esc(date) + "</p></div>" +
btn("open:calendar", "Kalender öffnen ↗", "card-button",
"style=\"left:0;bottom:0;width:100%;height:90dp;border-top:2dp "
"var(--border);font-size:25dp;color:var(--muted);\"");
}
if (id == "account") {
if (h < 300)
return "<div style=\"padding:18dp 28dp;\"><span "
"class=\"small\">Konto</span><p "
"style=\"font-size:46dp;color:var(--accent);\">" +
cash(s.state.value("cash", int64_t(0))) + "</p></div>" +
btn("ticket",
"Eintritt &nbsp; " +
std::to_string(s.state.value("ticket", 13)) + " €",
"card-button",
"id=\"desktop-ticket\" data-interactive=\"true\" "
"style=\"right:20dp;top:45dp;font-size:32dp;\"");
return heading("Vereinskasse") +
"<div style=\"position:absolute;left:34dp;top:90dp;\"><p "
"class=\"small\">Guthaben</p><p style=\"font-size:" +
std::to_string(w < 600 ? 48 : 65) +
"dp;letter-spacing:-2dp;color:var(--accent);margin-top:10dp;\">" +
cash(s.state.value("cash", int64_t(0))) +
"</p></div><div "
"style=\"position:absolute;left:0;right:0;bottom:0;height:132dp;"
"border-top:2dp var(--border);padding:22dp 34dp;\"><span "
"class=\"small\">Sparbuch</span><p style=\"font-size:34dp;\">" +
cash(s.state.value("deposit", int64_t(0))) + "</p></div>" +
btn("ticket",
"<span class=\"small\">Eintritt</span><br/>" +
std::to_string(s.state.value("ticket", 13)) + " € &nbsp; ›",
"card-button",
"id=\"desktop-ticket\" data-interactive=\"true\" "
"style=\"right:30dp;bottom:20dp;min-width:200dp;padding:12dp "
"24dp;font-size:34dp;background-color:var(--soft);border-radius:"
"18dp;\"");
}
if (id == "portrait")
return img(std::string(manager(s).value("portrait_style", "photo") ==
"painted"
? "manager-painted."
: "manager.") +
std::to_string(manager(s).value("portrait", 0)),
w, h, false, true, 800) +
"<div "
"style=\"position:absolute;left:0;right:0;bottom:0;padding:50dp "
"30dp "
"28dp;decorator:linear-gradient(0deg,#0d1928ed,#0d192800);color:#"
"eff4f8;\"><small>Manager</small><p style=\"font-size:34dp;\">" +
esc(manager(s).value("name", "")) + "</p></div>";
if (id == "crest" || id == "opponent-crest")
return "<div class=\"center\" style=\"padding:35dp 30dp;\">" +
crest(id == "crest" ? own : opponent, std::min(w - 60, h - 150)) +
"</div><div "
"style=\"position:absolute;left:15dp;right:15dp;bottom:28dp;text-"
"align:center;font-size:28dp;\"><p class=\"small\">" +
(id == "crest" ? "Dein Verein" : "Nächster Gegner") + "</p><p>" +
esc(world_->name(*(id == "crest" ? own : opponent))) + "</p></div>";
if (id == "competition")
return heading("Nächste Begegnung") +
"<div class=\"row\" "
"style=\"position:absolute;left:30dp;right:30dp;top:180dp;justify-"
"content:space-around;text-align:center;\"><div>" +
crest(own, 80) + "<p style=\"font-size:23dp;margin-top:14dp;\">" +
esc(own ? world_->name(*own) : "") +
"</p></div><div><p class=\"small\">Freundschaftsspiel</p><p "
"style=\"font-size:54dp;\">19:00</p><p class=\"small\">Heim · "
"Samstag</p></div><div>" +
crest(opponent, 80) +
"<p style=\"font-size:23dp;margin-top:14dp;\">" +
esc(opponent ? world_->name(*opponent) : "") + "</p></div></div>";
if (id == "warnings") {
const std::array<const char *, 10> names = {
"Aktiengewinn", "Kontostand", "Freie Werbeflächen",
"Sondertraining", "Erschöpfung", "Startaufstellung",
"Ersatzspieler", "Taktischer Einsatz", "Auslaufende Verträge",
"Lizenz"};
const std::array<const char *, 10> icons = {
"chart", "coins", "shirt", "star", "heart",
"person", "person", "chart", "save", "check"};
const std::array<int, 8> wide_members = {0, 1, 2, 3, 5, 7, 8, 9};
const bool wide = h < 300;
const int columns = wide ? 8 : 5, count = wide ? 8 : 10;
std::string out = heading("Vereinsstatus");
for (int i = 0; i < count; ++i) {
const int member = wide ? wide_members[size_t(i)] : i;
const int cell_w = (w - 52) / columns;
const int x = 26 + cell_w * (i % columns),
y = wide ? 90 : 95 + (i / columns) * 175;
out += "<div style=\"position:absolute;" +
rect(x, y, cell_w, wide ? 110 : 160) +
"\"><div style=\"position:absolute;left:" +
std::to_string((cell_w - 64) / 2) +
"dp;top:0;width:64dp;height:64dp;border:2dp "
"#9ddbc653;border-radius:32dp;padding:12dp;background-color:" +
std::string(member == 2 ? "#c57c67" : "#65a58d") + ";\">" +
glyph(icons[size_t(member)], 36) + "</div>" +
(wide ? ""
: "<p class=\"center\" "
"style=\"position:absolute;left:0;right:0;top:80dp;font-"
"size:18dp;line-height:1.15;\">" +
std::string(names[size_t(member)]) + "</p>") +
"</div>";
}
return out;
}
if (id == "trash")
return "<div class=\"center\" style=\"padding-top:35dp;\">" +
glyph("trash", 100) +
"</div><p class=\"center small\">Papierkorb</p>";
if (id == "fans")
return heading("Fan-Stimmung") +
"<p class=\"center accent\" "
"style=\"font-size:80dp;padding-top:85dp;\">" +
std::to_string(s.state.value("fans", 67)) + " %</p>";
if (id == "news")
return heading("Nachrichten") +
"<p style=\"padding:90dp 30dp;font-size:34dp;\">Willkommen zur "
"neuen Saison.</p>";
if (id == "results")
return heading("Letzte sechs Spiele") +
"<div class=\"row\" style=\"padding:100dp "
"30dp;justify-content:space-around;font-size:40dp;\"><span>–</"
"span><span>–</span><span>–</span><span>–</span><span>–</"
"span><span>–</span></div>";
if (id == "own-summary" || id == "opponent-summary")
return heading(id == "own-summary" ? "Platz &amp; Stärke · eigener Verein"
: "Platz &amp; Stärke · Gegner") +
"<div class=\"row\" style=\"padding:80dp "
"30dp;justify-content:space-around;font-size:56dp;\"><span>–</"
"span><span>–</span></div>";
const auto caption = id == "duels" ? "Direkter Vergleich"
: id == "comparison-curve" ? "Tabellenplätze · Vergleich"
: id == "own-curve" ? "Tabellenplatz · eigener Verein"
: "Tabellenplatz · Gegner";
return heading(caption) +
"<div "
"style=\"position:absolute;left:50dp;right:30dp;top:95dp;bottom:45dp;"
"border-left:2dp var(--muted);border-bottom:2dp var(--muted);\"><p "
"class=\"center muted\" "
"style=\"padding-top:80dp;\">Saisonvorbereitung</p></div>";
}
std::string App::render_desktop() {
init_desktop();
const auto s = snap();
const auto *c = club(s);
std::string out =
"<div class=\"info-bar\">" +
btn("desktop-context",
crest(c, 82) + "<span><strong>" + esc(c ? world_->name(*c) : "") +
"</strong><small>" + esc(manager(s).value("name", "")) +
"</small></span>",
"identity") +
"<div class=\"info-date\">Saisonvorbereitung<small>" +
esc(s.state.value("date", std::string())) +
"</small></div><div class=\"info-cash\"><small>Guthaben</small><strong>" +
cash(s.state.value("cash", int64_t(0))) + "</strong></div></div>";
for (const auto &[id, o] : desktop_["objects"].items()) {
if (!o.value("visible", false))
continue;
const auto style = rect(o.value("x", 0), o.value("y", 0), o.value("w", 224),
o.value("h", 224));
if (o.value("widget", false))
out += "<div id=\"object-" + esc(id) + "\" data-object=\"" + esc(id) +
"\" class=\"desktop-card\" style=\"" + style + "\">" +
widget(id, o) +
(o.value("pinned", true) ? "<div class=\"pin-dot\"></div>" : "") +
"</div>";
else {
const auto route = id.substr(4);
out += "<button id=\"object-" + esc(id) + "\" data-object=\"" + esc(id) +
"\" data-action=\"open:" + route +
"\" class=\"desktop-app\" style=\"" + style +
"\"><div class=\"app-tile\">" +
img("button." + route, 146, 146, false, false, 256) +
"</div><span class=\"app-name\">" + esc(title(route)) + "</span>" +
(o.value("pinned", true) ? "<div class=\"pin-dot\"></div>" : "") +
"</button>";
}
}
return out;
}
std::string App::render_newgame() {
std::string body = "<h2>Grundeinstellungen</h2><p class=\"small\" "
"style=\"position:absolute;right:0;top:10dp;\">Zuerst die "
"Partie, dann die Manager.</p>";
const std::array<const char *, 4> keys = {"duration", "difficulty", "players",
"mode"};
const std::array<const char *, 4> names = {"Spieldauer", "Schwierigkeit",
"Mitspieler", "Modus"};
const std::array<int, 4> limits = {
5, 10, start_options_.value("league", true) ? 4 : 1, 3};
for (int i = 0; i < 4; ++i) {
const auto key = std::string(keys[size_t(i)]);
const int value = start_options_.value(key, 1), x = (i % 2) * 1320,
y = 120 + (i / 2) * 716;
std::string symbols, caption;
if (i == 0) {
symbols = "<strong style=\"font-size:210dp;color:var(--accent);\">" +
std::string(value == 5 ? "∞" : std::to_string(value)) +
"</strong>";
caption = value == 5 ? "Unbegrenzt" : value == 1 ? "Saison" : "Saisons";
} else if (i == 1) {
symbols = "<div style=\"position:relative;width:500dp;height:200dp;\">";
const int cols = std::min(value, 5);
for (int n = 0; n < value; ++n)
symbols += "<div style=\"position:absolute;" +
rect((n % cols) * 100,
(n / cols) * 100 + (value <= 5 ? 50 : 0), 92, 92) +
"\">" + glyph("ball", 92) + "</div>";
symbols += "</div>";
caption = "Spielstärke " + std::to_string(value) + " von 10";
} else if (i == 2) {
symbols =
"<div class=\"row\" style=\"height:200dp;justify-content:center;\">";
for (int n = 0; n < value; ++n)
symbols += glyph("person", 110);
symbols += "</div>";
caption = std::to_string(value) + " Mitspieler";
} else {
symbols = "<strong style=\"font-size:174dp;color:#dfcb91;\">" +
std::string(value == 1 ? "I"
: value == 2 ? "II"
: "III") +
"</strong>";
caption = value == 1 ? "Grundfunktionen"
: value == 2 ? "Erweiterte Funktionen"
: "Alle Funktionen";
}
body += "<div class=\"panel\" style=\"position:absolute;" +
rect(x, y, 1288, 688) +
"padding:40dp 30dp;\"><h2 class=\"center\">" + names[size_t(i)] +
"</h2><div class=\"row\" "
"style=\"position:absolute;left:30dp;right:30dp;top:190dp;justify-"
"content:space-between;\">";
body +=
btn("setup-step", "−", {},
"data-id=\"" + key +
"\" data-step=\"-1\" "
"style=\"width:94dp;height:124dp;padding:0;font-size:72dp;\" " +
(value == 1 ? "disabled" : ""));
body += "<div class=\"column center\" "
"style=\"width:800dp;align-items:center;gap:20dp;\">" +
symbols + "<p>" + caption + "</p></div>";
body +=
btn("setup-step", "+", {},
"data-id=\"" + key +
"\" data-step=\"1\" "
"style=\"width:94dp;height:124dp;padding:0;font-size:72dp;\" " +
(value == limits[size_t(i)] ? "disabled" : "")) +
"</div></div>";
}
body += "<div class=\"row\" "
"style=\"position:absolute;left:0;right:0;bottom:205dp;\">";
for (const auto *key : {"league", "world"}) {
const bool league = std::string(key) == "league",
active = start_options_.value(key, true),
locked = active &&
(league ? (start_options_.value("players", 1) > 1 ||
!start_options_.value("world", true))
: !start_options_.value("league", true));
body +=
btn("setup-competition",
glyph(league ? "pitch" : "world", 70) + "<span>" +
(league ? "Ligaspiel" : "WM / EM") + " &nbsp; " +
(active ? "Aktiv" : "Aus") + "</span>",
active ? "primary row" : "row",
"data-id=\"" + std::string(key) +
"\" style=\"flex:1;height:126dp;justify-content:center;\" " +
(locked ? "disabled" : ""));
}
body += "</div><p class=\"small center\" "
"style=\"position:absolute;left:0;right:0;bottom:155dp;\">Mindestens "
"ein Wettbewerb bleibt aktiv.</p><div class=\"bottom-controls\">" +
btn("close", "Abbrechen") + btn("setup-next", "Weiter", "primary") +
"</div>";
return window("Neues Spiel", body);
}
std::string App::render_manager() {
const int limit = adding_manager_ ? 4 : start_options_.value("players", 1);
const auto used_club = [&](const std::string &id) {
return std::any_of(
managers_draft_.begin(), managers_draft_.end(),
[&](const auto &m) { return m.value("club", "") == id; });
};
const auto used_portrait = [&](int id) {
return std::any_of(
managers_draft_.begin(), managers_draft_.end(),
[&](const auto &m) { return m.value("portrait", 0) == id; });
};
const int portrait =
selections_["portrait"].empty() ? 0 : std::stoi(selections_["portrait"]);
const auto style = selections_["portrait-style"] == "painted"
? "manager-painted."
: "manager.";
if (!world_->manageable(selected_club_) || used_club(selected_club_))
for (auto *c : world_->clubs())
if (world_->manageable(c->value("id", "")) &&
!used_club(c->value("id", ""))) {
selected_club_ = c->value("id", "");
break;
}
std::string body;
std::vector<std::pair<std::string, std::string>> countries;
std::set<std::string> seen;
for (auto *r : world_->leagues()) {
const auto id = r->value("nation", "");
if (seen.insert(id).second)
countries.emplace_back(id, world_->nation_name(id));
}
auto leagues = world_->leagues(country_);
if (std::none_of(leagues.begin(), leagues.end(),
[&](auto *r) { return r->value("id", "") == league_; }))
league_ = leagues.empty() ? "" : leagues.front()->value("id", "");
std::vector<std::pair<std::string, std::string>> choices;
for (auto *r : leagues)
choices.emplace_back(r->value("id", ""), world_->name(*r));
if (manager_picker_) {
body =
"<div class=\"row\" "
"style=\"justify-content:space-between;\"><h2>Verein auswählen</h2>" +
btn("manager-clubs-back", "Zurück") +
"</div><div class=\"toolbar\" style=\"margin-top:35dp;\">" +
select("manager-country", countries, country_, "manager-country") +
select("manager-league", choices, league_, "manager-league") +
"</div><div class=\"list\" "
"style=\"position:absolute;left:0;right:0;top:240dp;bottom:0;\">";
const auto clubs = world_->clubs(league_);
for (size_t i = 0; i < clubs.size(); ++i) {
const auto *c = clubs[i];
const auto id = c->value("id", "");
const bool locked = !world_->manageable(id), used = used_club(id);
const auto x = (i % 4) * 650, y = (i / 4) * 340;
body +=
"<button data-action=\"manager-club\" data-id=\"" + esc(id) +
"\" class=\"choice " +
(locked ? "locked"
: id == selected_club_ ? "selected"
: "") +
"\" style=\"position:absolute;" + rect(x, y, 618, 310) +
"padding:25dp;\" " + (locked || used ? "disabled" : "") +
"><div class=\"center\">" + crest(c, 150) +
"</div><p style=\"font-size:30dp;margin-top:15dp;\">" +
esc(world_->name(*c)) + "</p>" +
(locked ? "<div style=\"position:absolute;right:24dp;top:24dp;\">" +
glyph("lock", 40) + "</div>"
: "") +
"<p class=\"small\" style=\"margin-top:12dp;\">" +
(locked ? "Nicht spielbar"
: used ? "Bereits vergeben"
: id == selected_club_
? "Ausgewählt"
: esc(world_->name(*world_->find("competitions", league_)))) +
"</p></button>";
}
return window("Neuer Spieler", body + "</div>");
}
const auto *c = world_->find("clubs", selected_club_);
body = "<h2>Mitspieler " + std::to_string(manager_index_ + 1) + " von " +
std::to_string(limit) +
"</h2><p class=\"small\" "
"style=\"position:absolute;right:0;top:10dp;\">Dein Name. Dein "
"Verein. Dein Porträt.</p>";
body +=
"<div class=\"panel\" style=\"position:absolute;" +
rect(0, 90, 1288, 330) +
"padding:32dp;\"><div "
"style=\"position:absolute;left:32dp;top:32dp;width:970dp;\"><label "
"class=\"small\">Managername</label><input id=\"manager-name\" "
"maxlength=\"24\" value=\"" +
esc(selections_["manager-name"]) +
"\" style=\"width:100%;font-size:38dp;height:86dp;margin-top:20dp;\"/><p "
"class=\"small\" style=\"margin-top:20dp;\">So wirst du im Spiel "
"angesprochen.</p><p class=\"small accent\" "
"style=\"margin-top:16dp;\">Porträt " +
std::to_string(portrait + 1) +
"</p></div><div "
"style=\"position:absolute;right:32dp;top:45dp;border-radius:12dp;"
"overflow:hidden;\">" +
img(style + std::to_string(portrait), 174, 232, false, true, 320) +
"</div></div>";
body += "<div class=\"panel\" style=\"position:absolute;" +
rect(1320, 90, 1288, 330) +
"padding:30dp;\"><p class=\"small\">Verein</p>" +
btn("manager-clubs",
crest(c, 176) +
"<div class=\"column\" style=\"gap:20dp;\"><strong "
"style=\"font-size:38dp;\">" +
esc(c ? world_->name(*c) : "") +
"</strong><small class=\"small\">" +
esc(c ? world_->name(*world_->find(
"competitions", c->value("competition", "")))
: "") +
"</small><span class=\"accent\">Verein wählen ›</span></div>",
"row",
"style=\"margin-top:10dp;width:100%;height:230dp;background-"
"color:transparent;border-width:0;padding:0;text-align:left;\"") +
"</div>";
body +=
"<div style=\"position:absolute;" + rect(0, 460, 1288, 170) +
"\"><h3>Startliga</h3><div class=\"row\" style=\"margin-top:20dp;\">" +
select("manager-country", countries, country_, "manager-country") +
select("manager-league", choices, league_, "manager-league") +
"</div></div><div style=\"position:absolute;" +
rect(1320, 460, 1288, 170) +
"\"><h3>Vereinsstärke</h3><div style=\"margin-top:20dp;\">" +
select("manager-strength",
{{"0", "Unteres Drittel"},
{"1", "Mittelfeld"},
{"2", "Oberes Drittel"}},
selections_["manager-strength"].empty()
? "1"
: selections_["manager-strength"],
"manager-strength") +
"</div></div>";
body += "<div class=\"panel\" "
"style=\"position:absolute;left:0;top:670dp;width:1978dp;bottom:"
"145dp;padding:26dp;\"><h3>Managerporträt</h3><div class=\"row\" "
"style=\"position:absolute;right:26dp;top:16dp;\">" +
btn("portrait-style", "Foto",
selections_["portrait-style"] != "painted" ? "primary" : "",
"data-id=\"photo\"") +
btn("portrait-style", "Illustration",
selections_["portrait-style"] == "painted" ? "primary" : "",
"data-id=\"painted\"") +
"</div>";
for (int i = 0; i < 12; ++i) {
const int x = 26 + (i % 6) * 320, y = 100 + (i / 6) * 440;
const bool used = used_portrait(i);
body += "<button data-action=\"portrait\" data-id=\"" + std::to_string(i) +
"\" class=\"choice " + (i == portrait ? "selected" : "") +
"\" style=\"position:absolute;" + rect(x, y, 300, 412) +
"padding:18dp 30dp;\" " + (used ? "disabled" : "") + ">" +
img(style + std::to_string(i), 230, 306, false, true, 350) +
"<p style=\"font-size:24dp;margin-top:18dp;\">" +
(used ? "Vergeben"
: i == portrait ? "Ausgewählt"
: "Porträt " + std::to_string(i + 1)) +
"</p></button>";
}
body += "</div><div class=\"panel\" "
"style=\"position:absolute;left:2010dp;right:0;top:670dp;bottom:"
"145dp;padding:28dp;\"><h3>Mitspieler dieser Partie</h3>";
for (size_t i = 0; i < managers_draft_.size(); ++i) {
const auto &m = managers_draft_[i];
body += "<div class=\"row\" style=\"margin-top:40dp;\">" +
img("manager." + std::to_string(m.value("portrait", 0)), 90, 120,
false, true, 180) +
"<div><small class=\"small\">Spieler " + std::to_string(i + 1) +
"</small><p style=\"margin-top:10dp;\">" +
esc(m.value("name", "")) + "</p><small class=\"small\">" +
esc(world_->name(*world_->find("clubs", m.value("club", "")))) +
"</small></div></div>";
}
body += "<p class=\"small\" "
"style=\"position:absolute;left:28dp;right:28dp;bottom:28dp;\">" +
std::to_string(limit - int(managers_draft_.size())) +
" weitere Plätze frei</p></div><div class=\"bottom-controls\">" +
btn("manager-back", adding_manager_ ? "Abbrechen" : "Zurück") +
btn("manager-next",
adding_manager_ ? "Mitspieler hinzufügen"
: manager_index_ + 1 == limit ? "Spiel starten"
: "Mitspieler bestätigen",
"primary",
world_->manageable(selected_club_) && manager_index_ < limit
? ""
: "disabled") +
"</div>";
return window("Neuer Spieler", body);
}
std::string App::render_opening() {
const std::array<const char *, 3> names = {"UEFA-Cup", "Champions League",
"Europapokal der Pokalsieger"};
const auto german = world_->clubs("comp:de-1");
std::vector<const Json *> pool;
for (auto *l : world_->leagues("nation:de"))
for (auto *c : world_->clubs(l->value("id", "")))
if (pool.size() < 64)
pool.push_back(c);
std::string body;
if (opening_page_ < 3) {
body = "<h2 style=\"font-size:46dp;\">" +
std::string(names[size_t(opening_page_)]) +
"</h2><p class=\"small\" style=\"margin-top:16dp;\">Deutsche Teams "
"· Saison " +
esc(snap().state.value("date", std::string()).substr(0, 4)) + "</p>";
const int count = opening_page_ == 0 ? 4 : 1;
for (int i = 0; i < count && size_t(i) < german.size(); ++i) {
const auto *c = german[size_t((i + opening_page_) % int(german.size()))];
const bool single = count == 1;
const int x = single ? 704 : 150 + (i % 2) * 1178,
y = single ? 360 : 180 + (i / 2) * 730;
body += "<div class=\"panel center\" style=\"position:absolute;" +
rect(x, y, single ? 1200 : 1128, single ? 1000 : 680) +
"padding:65dp;\">" + crest(c, single ? 620 : 360) +
"<h3 style=\"margin-top:26dp;font-size:" +
std::to_string(single ? 64 : 50) + "dp;font-weight:normal;\">" +
esc(world_->name(*c)) + "</h3></div>";
}
body +=
"<div class=\"bottom-controls\" style=\"justify-content:flex-end;\">" +
btn("opening-next", "Weiter", "primary",
"style=\"flex:none;width:390dp;\"") +
"</div>";
} else {
const auto pair = [&](int index, int known, int size) {
const size_t a = size_t(index * 2), b = a + 1;
if (b >= pool.size())
return std::string();
const auto label_for = [&](const Json *c, bool home) {
return "<span class=\"club-label\" style=\"flex:1;justify-content:" +
std::string(home ? "flex-end" : "flex-start") + ";\">" +
(home ? "<span>" + esc(world_->name(*c)) + "</span>" +
crest(c, size)
: crest(c, size) + "<span>" + esc(world_->name(*c)) +
"</span>") +
"</span>";
};
return "<div class=\"row\" style=\"height:100%;gap:18dp;\"><span "
"class=\"small\" style=\"width:40dp;text-align:right;\">" +
std::to_string(index + 1) + "</span>" +
(known > 0 ? label_for(pool[a], true)
: "<span class=\"muted\" "
"style=\"flex:1;text-align:right;\">Heim</span>") +
"<span class=\"muted\" "
"style=\"width:30dp;text-align:center;\">–</span>" +
(known > 1 ? label_for(pool[b], false)
: "<span class=\"muted\" style=\"flex:1;\">Noch nicht "
"gezogen</span>") +
"</div>";
};
body = "<h2 style=\"font-size:46dp;\">" +
std::string(opening_page_ == 3 ? "1. Runde" : "DFB-Pokal") +
"</h2><p class=\"small\" style=\"margin-top:16dp;\">" +
(opening_page_ == 3 ? "DFB-Pokal · Saison " : "1. Runde · Saison ") +
esc(snap().state.value("date", std::string()).substr(0, 4)) + "</p>";
if (opening_page_ == 3) {
body += "<span class=\"small\" "
"style=\"position:absolute;right:0;top:20dp;\">" +
std::to_string(draw_revealed_) +
" / 64 Mannschaften</span><div style=\"position:absolute;" +
rect(0, 138, 2608, 850) + "\">" +
img("art.cup-draw-v1.png", 2608, 850, false, false, 1800) +
"</div>";
const int current = std::max(0, (draw_revealed_ - 1) / 2),
known = draw_revealed_ ? draw_revealed_ - current * 2 : 0;
body += "<div class=\"panel\" style=\"position:absolute;" +
rect(130, 1026, 2348, 126) +
"padding:10dp 28dp;font-size:38dp;\">" +
pair(current, known, 66) + "</div>";
for (int i = std::max(0, current - 3); i < current; ++i)
body +=
"<div style=\"position:absolute;" +
rect(158, 1190 + (i - std::max(0, current - 3)) * 155, 2292, 145) +
"border-bottom:2dp var(--border);\">" + pair(i, 2, 42) + "</div>";
body += "<div class=\"bottom-controls\" "
"style=\"justify-content:flex-end;\">" +
btn("opening-play", draw_playing_ ? "Pause" : "Fortsetzen", {},
"style=\"flex:none;width:390dp;\"") +
btn("opening-all", "Alle Paarungen anzeigen", {},
"style=\"flex:none;width:600dp;\"") +
"</div>";
} else {
for (int column = 0; column < 2; ++column) {
body += "<div class=\"panel\" style=\"position:absolute;" +
rect(column * 1321, 154, 1287, 1500) + "padding:12dp 18dp;\">";
for (int row = 0; row < 16; ++row)
body += "<div style=\"height:92dp;font-size:27dp;border-bottom:1dp "
"var(--border);\">" +
pair(column * 16 + row, 2, 36) + "</div>";
body += "</div>";
}
body += "<div class=\"bottom-controls\" "
"style=\"justify-content:flex-end;\">" +
btn("opening-finish", "Weiter zum Desktop", "primary",
"style=\"flex:none;width:550dp;\"") +
"</div>";
}
}
return window(opening_page_ < 3 ? "Deutsche Teams" : "DFB-Pokal", body,
false);
}
std::string App::render_table(bool strengths, bool indoor) {
auto leagues = world_->leagues(country_);
if (std::none_of(leagues.begin(), leagues.end(),
[&](auto *r) { return r->value("id", "") == league_; }))
league_ = leagues.empty() ? "" : leagues.front()->value("id", "");
const auto clubs = world_->clubs(league_);
std::string body = "<div class=\"list\" "
"style=\"position:absolute;left:0;right:0;top:0;bottom:"
"160dp;\"><div class=\"table\"><div class=\"tr\"><div "
"class=\"th\" style=\"width:42%;\">" +
btn("table-sort", "Pl. / Verein", {}, "data-id=\"rank\"") +
"</div>";
const std::vector<std::string> headers =
strengths ? std::vector<std::string>{"Tor", "Abwehr", "Mittelfeld",
"Sturm", "Gesamt"}
: std::vector<std::string>{"Sp.", "S", "U", "N",
"Punkte", "Tore", "Diff."};
for (const auto &h : headers)
body += "<div class=\"th center\">" +
btn("table-sort", esc(h), {}, "data-id=\"" + esc(h) + "\"") +
"</div>";
body += "</div>";
for (size_t i = 0; i < clubs.size(); ++i) {
auto *c = clubs[i];
body += "<div class=\"tr " + std::string(i % 2 ? "" : "odd") +
"\"><div class=\"td\">" +
btn("club-detail",
"<span class=\"club-label\"><span class=\"rank\">" +
std::to_string(i + 1) + ".</span>" + crest(c, 40) +
"<span>" + esc(world_->name(*c)) + "</span></span>",
{}, "data-id=\"" + esc(c->value("id", "")) + "\"") +
"</div>";
if (strengths) {
const auto players = world_->squad(c->value("id", ""));
for (const auto &position : {"gk", "df", "mf", "fw", "all"}) {
int sum = 0, n = 0;
for (auto *p : players) {
const auto positions = p->value("positions", Json::array());
if (std::string(position) == "all" ||
std::find(positions.begin(), positions.end(), position) !=
positions.end()) {
sum += p->value("attributes", Json::object()).value("strength", 0);
++n;
}
}
body += "<div class=\"td center\">" +
(n ? std::to_string(sum / n) : "–") + "</div>";
}
} else
for (int n = 0; n < 7; ++n)
body += "<div class=\"td center\">" +
std::string(n == 5 ? "0:0" : "0") + "</div>";
body += "</div>";
}
body += "</div></div><div class=\"bottom-controls\">";
if (!strengths && !indoor)
body += btn("table-overall", "Gesamt") + select("table-scope",
{{"all", "Alle Spiele"},
{"first", "Hinrunde"},
{"second", "Rückrunde"},
{"home", "Heim"},
{"away", "Auswärts"}},
selections_["table-scope"],
"table-scope");
std::vector<std::pair<std::string, std::string>> countries, league_rows;
std::set<std::string> seen;
for (auto *l : world_->leagues()) {
const auto id = l->value("nation", "");
if (seen.insert(id).second)
countries.emplace_back(id, world_->nation_name(id));
if (id == country_)
league_rows.emplace_back(l->value("id", ""), world_->name(*l));
}
body += select("table-country", countries, country_, "table-country") +
select("table-league", league_rows, league_, "table-league") +
"</div>";
return body;
}
std::string App::render_camp() {
const auto index_file =
Json::parse(editor::read_file(gui_.root() / "gui-assets.json"));
const auto demo = index_file.at("demo"), camps = demo.at("training_camps");
const auto s = snap();
const auto id = s.state.at("camp").value("selected", std::string("resort:4"));
const Json *chosen = nullptr;
for (const auto &c : camps)
if (c.value("id", "") == id)
chosen = &c;
if (!chosen)
chosen = &camps.at(0);
auto region = selections_["camp-region"];
if (region.empty())
region = chosen->value("map", "map:eu");
std::string body = "<div "
"style=\"position:absolute;left:0;top:0;width:1440dp;"
"bottom:0;\"><div class=\"toolbar\">";
for (const auto &m : demo.at("maps"))
body += btn("camp-region", esc(m.value("name", "")),
m.value("id", "") == region ? "primary" : "",
"data-id=\"" + esc(m.value("id", "")) + "\"");
body += "</div><div "
"style=\"position:absolute;left:0;top:120dp;width:1440dp;height:1603."
"2dp;overflow:hidden;border-radius:22dp;\">" +
img("map." + region.substr(4), 1440, 1603.2, false, false, 1600);
for (const auto &c : camps)
if (c.value("map", "") == region) {
const double x = c.value("x", 0) * 1.2, y = c.value("y", 0) * 1.2;
body += btn("camp-select",
"<span "
"style=\"display:block;width:18dp;height:18dp;background-"
"color:#dfb668;border-radius:9dp;\"></span>",
c.value("id", "") == id ? "primary" : "",
"data-id=\"" + esc(c.value("id", "")) +
"\" style=\"position:absolute;" +
rect(x - 34, y - 34, 68, 68) +
"padding:23dp;border-radius:34dp;\"");
}
body += "</div></div><div "
"style=\"position:absolute;left:1500dp;right:0;top:0;bottom:0;\"><"
"div style=\"height:570dp;overflow:hidden;border-radius:24dp;\">" +
img(chosen->value("gui_image", ""), 1100, 570, false, true, 1400) +
"</div><h2 style=\"margin-top:22dp;\">" +
esc(chosen->value("name", "")) +
"</h2><p class=\"small\" style=\"margin-top:14dp;\">" +
esc(chosen->value("place", "")) + "</p>";
const std::array<const char *, 4> qualities = {
"Platzqualität", "Fitnessgeräte", "Verpflegung", "Unterkunft"};
for (size_t i = 0; i < 4; ++i) {
const int q = chosen->at("quality")[i].get<int>();
std::string stars;
for (int j = 0; j < q; ++j)
stars += glyph("star", 32);
body += "<div class=\"field-row\" style=\"min-height:78dp;padding:12dp "
"0;\"><span>" +
std::string(qualities[i]) +
"</span><span class=\"row\" style=\"gap:5dp;color:#d9b96f;\">" +
stars + "</span></div>";
}
body += "<div class=\"field-row\"><strong>Preis</strong><strong "
"class=\"accent\">" +
cash(chosen->value("price", int64_t(0))) + "</strong></div>";
const std::array<const char *, 4> focus = {"Kondition", "Technik", "Spiel",
"Erholung"};
const auto values = s.state.at("camp").at("focus");
int sum = 0;
for (const auto &v : values)
sum += v.get<int>();
for (int i = 0; i < 4; ++i) {
const int value = i == 3 ? 15 - sum / 3 : values[size_t(i)].get<int>();
body += "<div class=\"field-row\" style=\"min-height:100dp;padding:8dp "
"0;\"><label>" +
std::string(focus[size_t(i)]) +
"</label><input type=\"range\" id=\"camp-focus-" +
std::to_string(i) + "\" data-input=\"camp-focus\" data-id=\"" +
std::to_string(i) + "\" min=\"0\" max=\"15\" step=\"1\" value=\"" +
std::to_string(value) + "\" style=\"width:400dp;\" " +
(i == 3 ? "disabled" : "") + "/><span id=\"camp-value-" +
std::to_string(i) +
"\" style=\"width:145dp;flex-shrink:0;text-align:right;\">" +
std::to_string(value) + " / 15</span></div>";
}
body += "<div class=\"row\" "
"style=\"margin-top:26dp;justify-content:flex-end;\">" +
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:block;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\" "
"style=\"position:absolute;left:0;top:0;width:1120dp;"
"bottom:145dp;padding:24dp;\">";
if (save)
body += btn("save-new", "Neuer Speicherstand", "choice",
"style=\"width:100%;text-align:left;min-height:100dp;margin-"
"bottom:14dp;\"");
if (fs::exists(directory))
for (const auto &file : fs::directory_iterator(directory))
if (file.path().extension() == ".json") {
const auto name = editor::utf8(file.path().stem());
body += btn("save-select", esc(name),
std::string("choice ") +
(selections_["save"] == name ? "selected" : ""),
"data-id=\"" + esc(name) +
"\" "
"style=\"width:100%;min-height:110dp;text-align:left;"
"margin-bottom:14dp;\"");
}
body += "</div><div class=\"panel\" "
"style=\"position:absolute;left:1160dp;right:0;top:0;bottom:145dp;"
"padding:50dp;\"><h2>" +
esc(selections_["save"].empty() ? "Speicherstand auswählen"
: selections_["save"]) +
"</h2>";
const auto s = snap();
body +=
"<div style=\"margin:40dp 0;\">" + crest(club(s), 340) +
"</div><div class=\"field-row\"><span>Saison</span><strong>" +
esc(s.state.value("date", std::string()).substr(0, 4)) +
"</strong></div><div "
"class=\"field-row\"><span>Spieltag</span><strong>Saisonvorbereitung</"
"strong></div><div class=\"field-row\"><span>Datum</span><strong>" +
esc(s.state.value("date", std::string())) +
"</strong></div><div "
"class=\"field-row\"><span>Mitspieler</span><strong>" +
std::to_string(s.state.at("managers").size()) + "</strong></div>";
if (save && selections_["save"].empty())
body += "<div class=\"field-row\"><label>Bezeichnung</label><input "
"id=\"save-name\" value=\"Meine Karriere\"/></div>";
return body + "</div><div class=\"bottom-controls\">" +
btn("save-delete", "Löschen") + btn("save-rename", "Umbenennen") +
btn("close", "Abbrechen") +
btn(save ? "save-confirm" : "load-confirm",
save ? "Speichern" : "Laden", "primary") +
"</div>";
}
std::string App::render_menu(const std::string &key) {
std::string body;
if (key == "tables" || key == "strengths")
body = render_table(key == "strengths", false);
else if (key == "camp")
body = render_camp();
else if (key == "settings")
body = render_settings();
else if (key == "save" || key == "load")
body = render_save(key == "save");
else if (key == "widgets" || key == "view-save" || key == "view-load" ||
key == "background")
body = render_desktop_tools(key);
else
throw editor::Error("Diese native Ansicht ist noch nicht verfügbar.");
return "<div class=\"fill\" style=\"z-index:100;\">" +
window(title(key), body) + "</div>";
}
+392
View File
@@ -0,0 +1,392 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "modern/ui/ticket_popover.hpp"
#include <RmlUi/Core.h>
#include <RmlUi/Core/Elements/ElementFormControl.h>
#include <algorithm>
#include <cmath>
#include <limits>
#include <optional>
#include <sstream>
namespace bmh::modern_ui {
namespace {
std::string escaped(const std::string &value) {
std::string out;
for (char c : value) {
if (c == '&')
out += "&amp;";
else if (c == '<')
out += "&lt;";
else if (c == '>')
out += "&gt;";
else if (c == '"')
out += "&quot;";
else
out += c;
}
return out;
}
std::string px(float value) {
std::ostringstream out;
out.imbue(std::locale::classic());
out << value << "px";
return out.str();
}
std::optional<int> price(const Snapshot &snapshot) {
const auto it = snapshot.state.find("ticket");
if (it == snapshot.state.end() || !it->is_number_integer())
return {};
const auto n = it->get<int64_t>();
if (n < std::numeric_limits<int>::min() ||
n > std::numeric_limits<int>::max())
return {};
return int(n);
}
std::string button(const char *action, const char *label, bool primary = false,
bool disabled = false) {
return "<button data-ticket-action=\"" + std::string(action) + "\" class=\"" +
(primary ? "native-ticket-primary" : "") + "\"" +
(disabled ? " disabled=\"disabled\"" : "") + ">" + label + "</button>";
}
bool inside(Rml::Element *node, Rml::Element *root) {
for (; node; node = node->GetParentNode())
if (node == root)
return true;
return false;
}
} // namespace
TicketPopover::TicketPopover(Rml::Context &context,
Rml::ElementDocument &document, DataSource &source,
std::function<void()> on_commit)
: context_(context), document_(document), source_(source),
on_commit_(std::move(on_commit)) {
auto layer = document_.CreateElement("div");
layer->SetId("native-ticket-layer");
layer->SetProperty("display", "none");
layer_ = document_.AppendChild(std::move(layer));
for (const char *type : {"click", "change", "input", "mousedown", "mouseup",
"mousemove", "contextmenu"})
layer_->AddEventListener(type, this);
// Capture before the range widget's default key handler to avoid double
// steps.
layer_->AddEventListener("keydown", this, true);
}
TicketPopover::~TicketPopover() {
// The owner must destroy this editor before closing its document/context.
close(false);
if (layer_)
document_.RemoveChild(layer_);
}
bool TicketPopover::open(Rml::Element *anchor, float device_pixel_ratio,
int min, int max, int step) {
close(false);
const auto snapshot = source_.snapshot();
const auto current = price(snapshot);
const auto interval = int64_t(max) - min;
if (!anchor || anchor->GetOwnerDocument() != &document_ ||
anchor->GetId().empty() || !anchor->IsVisible(true) ||
!std::isfinite(device_pixel_ratio) || device_pixel_ratio <= 0 ||
min > max || step <= 0 || interval % step != 0 || !current ||
*current < min || *current > max || (int64_t(*current) - min) % step != 0)
return false;
anchor_id_ = anchor->GetId();
revision_ = snapshot.revision;
world_ = snapshot.world;
original_ = value_ = *current;
min_ = min;
max_ = max;
step_ = step;
ratio_ = device_pixel_ratio;
review_ = false;
error_.clear();
open_ = true;
layer_->SetProperty("display", "block");
layer_->SetProperty("font-size", px(14.f * ratio_));
render();
return open_;
}
void TicketPopover::focus_opener() {
if (auto *anchor = document_.GetElementById(anchor_id_);
anchor && anchor->IsVisible(true))
anchor->Focus(true);
}
void TicketPopover::close(bool restore_focus) {
if (!open_)
return;
open_ = false;
layer_->SetProperty("display", "none");
layer_->SetInnerRML("");
world_.reset();
error_.clear();
if (restore_focus)
focus_opener();
}
bool TicketPopover::fresh() const {
const auto snapshot = source_.snapshot();
return snapshot.revision == revision_ && snapshot.world == world_ &&
price(snapshot) == original_;
}
void TicketPopover::resize(float device_pixel_ratio) {
if (!open_)
return;
if (!std::isfinite(device_pixel_ratio) || device_pixel_ratio <= 0) {
close(false);
return;
}
ratio_ = device_pixel_ratio;
layer_->SetProperty("font-size", px(14.f * ratio_));
position();
}
void TicketPopover::update() {
if (!open_)
return;
if (!fresh()) {
close(false);
return;
}
position();
if (open_ && !inside(context_.GetFocusElement(), layer_)) {
if (auto *control = layer_->GetElementById(review_ ? "native-ticket-back"
: "native-ticket-range"))
control->Focus(true);
}
}
void TicketPopover::position() {
if (!open_)
return;
auto *anchor = document_.GetElementById(anchor_id_);
auto *panel = layer_->GetElementById("native-ticket-panel");
if (!anchor || !anchor->IsVisible(true) || !panel) {
close(false);
return;
}
const auto viewport = context_.GetDimensions();
const float margin = 8.f * ratio_, gap = 8.f * ratio_;
const float available_width = float(viewport.x) - 2 * margin;
const float available_height = float(viewport.y) - 2 * margin;
if (available_width <= 0 || available_height <= 0) {
close(false);
return;
}
panel->SetProperty("width", px(std::min(330.f * ratio_, available_width)));
panel->SetProperty("max-height", px(available_height));
document_.UpdateDocument();
const auto at = anchor->GetAbsoluteOffset(Rml::BoxArea::Border);
const auto size = anchor->GetBox().GetSize(Rml::BoxArea::Border);
const auto popup = panel->GetBox().GetSize(Rml::BoxArea::Border);
if (size.x <= 0 || size.y <= 0) {
close(false);
return;
}
const float below = float(viewport.y) - at.y - size.y - gap;
const float above = at.y - gap;
const bool down = below >= popup.y || below >= above;
const float left =
std::clamp(at.x + size.x - popup.x, margin,
std::max(margin, float(viewport.x) - popup.x - margin));
const float top =
std::clamp(down ? at.y + size.y + gap : at.y - gap - popup.y, margin,
std::max(margin, float(viewport.y) - popup.y - margin));
panel->SetProperty("left", px(left));
panel->SetProperty("top", px(top));
panel->SetAttribute("data-side", down ? "below" : "above");
}
void TicketPopover::render(bool focus_range) {
const auto amount = std::to_string(value_);
std::string content =
"<section id=\"native-ticket-panel\" role=\"dialog\" aria-modal=\"true\" "
"aria-labelledby=\"native-ticket-title\">"
"<div class=\"native-ticket-heading\"><h2 "
"id=\"native-ticket-title\">Eintrittspreis</h2><span>Aktuell: " +
std::to_string(original_) + " €</span></div>";
if (review_) {
content +=
"<div class=\"native-ticket-editor native-ticket-review\"><strong "
"aria-label=\"Bisheriger und neuer Eintrittspreis\">" +
std::to_string(original_) +
" € <span class=\"native-ticket-arrow\" aria-hidden=\"true\"><span "
"class=\"native-ticket-arrow-line\"></span><span "
"class=\"native-ticket-arrow-head\"></span></span> " +
amount + " €</strong></div>";
} else {
content += "<div class=\"native-ticket-editor\"><div "
"id=\"native-ticket-amount\">" +
amount +
" €</div>"
"<input id=\"native-ticket-range\" type=\"range\" min=\"" +
std::to_string(min_) + "\" max=\"" + std::to_string(max_) +
"\" step=\"" + std::to_string(step_) + "\" value=\"" + amount +
"\" aria-label=\"Eintrittspreis in Euro\" aria-valuetext=\"" +
amount + " Euro\"/><div class=\"native-ticket-limits\"><span>" +
std::to_string(min_) + " €</span><span>" + std::to_string(max_) +
" €</span></div></div>";
}
if (!error_.empty())
content += "<p id=\"native-ticket-error\" role=\"status\">" +
escaped(error_) + "</p>";
content +=
"<div class=\"native-ticket-actions\">" + button("cancel", "Abbrechen");
if (review_)
content += "<button id=\"native-ticket-back\" "
"data-ticket-action=\"back\">Ändern</button>" +
button("confirm", "Bestätigen", true);
else
content += button("review", "Übernehmen", true, value_ == original_);
content += "</div></section>";
layer_->SetInnerRML(content);
position();
if (open_ && focus_range) {
if (auto *control = layer_->GetElementById(review_ ? "native-ticket-back"
: "native-ticket-range"))
control->Focus(true);
}
}
void TicketPopover::draft(int value) {
if (review_ || value < min_ || value > max_ ||
(int64_t(value) - min_) % step_ != 0 || value == value_)
return;
value_ = value;
layer_->GetElementById("native-ticket-amount")
->SetInnerRML(std::to_string(value_) + " €");
auto *range = layer_->GetElementById("native-ticket-range");
range->SetAttribute("aria-valuetext", std::to_string(value_) + " Euro");
if (range->GetAttribute<int>("value", value_) != value_)
range->SetAttribute("value", value_);
Rml::ElementList buttons;
layer_->GetElementsByTagName(buttons, "button");
for (auto *node : buttons)
if (node->GetAttribute<Rml::String>("data-ticket-action", "") == "review")
if (auto *control = dynamic_cast<Rml::ElementFormControl *>(node))
control->SetDisabled(value_ == original_);
}
void TicketPopover::confirm() {
if (!fresh()) {
close(false);
return;
}
const auto result = source_.apply({revision_, "ticket", value_});
if (!result.ok) {
if (!fresh()) {
close(false);
return;
}
error_ = result.error.empty()
? "Der Eintrittspreis konnte nicht übernommen werden."
: result.error;
render();
return;
}
close();
if (on_commit_)
on_commit_();
}
void TicketPopover::ProcessEvent(Rml::Event &event) {
if (!open_)
return;
const auto &type = event.GetType();
auto *target = event.GetTargetElement();
if (type == "keydown") {
const auto key =
Rml::Input::KeyIdentifier(event.GetParameter<int>("key_identifier", 0));
event.StopImmediatePropagation();
if (key == Rml::Input::KI_ESCAPE) {
close();
return;
}
if (key == Rml::Input::KI_TAB) {
Rml::ElementList controls;
layer_->QuerySelectorAll(controls, "input,button");
controls.erase(
std::remove_if(controls.begin(), controls.end(),
[](auto *node) {
auto *control =
dynamic_cast<Rml::ElementFormControl *>(node);
return !node->IsVisible(true) ||
(control && control->IsDisabled());
}),
controls.end());
if (controls.empty())
return;
const auto current = std::find(controls.begin(), controls.end(),
context_.GetFocusElement());
const bool backwards = event.GetParameter<int>("shift_key", 0) != 0;
const int n = int(controls.size()),
old = current == controls.end()
? (backwards ? 0 : -1)
: int(current - controls.begin());
controls[size_t((old + (backwards ? -1 : 1) + n) % n)]->Focus(true);
return;
}
if (!review_ && target->GetId() == "native-ticket-range") {
const int64_t delta =
(key == Rml::Input::KI_LEFT || key == Rml::Input::KI_DOWN)
? -int64_t(step_)
: int64_t(step_);
if (key == Rml::Input::KI_HOME)
draft(min_);
else if (key == Rml::Input::KI_END)
draft(max_);
else if (key == Rml::Input::KI_LEFT || key == Rml::Input::KI_RIGHT ||
key == Rml::Input::KI_UP || key == Rml::Input::KI_DOWN)
draft(int(
std::clamp(int64_t(value_) + delta, int64_t(min_), int64_t(max_))));
return;
}
if (key != Rml::Input::KI_RETURN && key != Rml::Input::KI_NUMPADENTER &&
key != Rml::Input::KI_SPACE)
return;
} else {
// Leave slider default mouse handling intact, but never bubble into desktop
// drag/actions.
event.StopPropagation();
if (type == "change" || type == "input") {
if (!review_ && target->GetId() == "native-ticket-range") {
const auto raw = event.GetParameter<float>(
"value", std::numeric_limits<float>::quiet_NaN());
if (std::isfinite(raw) && raw >= min_ && raw <= max_) {
const auto n = std::llround(raw);
if (std::abs(raw - double(n)) < 1e-4)
draft(int(n));
}
}
return;
}
if (type != "click")
return;
if (target == layer_) {
close();
return;
}
}
if (!fresh()) {
close(false);
return;
}
for (auto *node = target; node && node != layer_;
node = node->GetParentNode()) {
const auto action =
node->GetAttribute<Rml::String>("data-ticket-action", "");
if (action.empty())
continue;
if (auto *control = dynamic_cast<Rml::ElementFormControl *>(node);
control && control->IsDisabled())
return;
if (action == "cancel")
close();
else if (action == "back") {
review_ = false;
error_.clear();
render();
} else if (action == "review" && value_ != original_) {
review_ = true;
error_.clear();
render();
} else if (action == "confirm" && review_)
confirm();
return;
}
}
} // namespace bmh::modern_ui
+56
View File
@@ -0,0 +1,56 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "modern/ui/model.hpp"
#include <RmlUi/Core/EventListener.h>
#include <cstdint>
#include <functional>
#include <memory>
#include <string>
namespace Rml {
class Context;
class Element;
class ElementDocument;
} // namespace Rml
namespace bmh::modern_ui {
// A presentation-only editor. Default bounds describe the demo, not engine
// rules.
class TicketPopover final : public Rml::EventListener {
public:
TicketPopover(Rml::Context &, Rml::ElementDocument &, DataSource &,
std::function<void()> on_commit);
~TicketPopover() override;
TicketPopover(const TicketPopover &) = delete;
TicketPopover &operator=(const TicketPopover &) = delete;
bool open(Rml::Element *anchor, float device_pixel_ratio, int min = 0,
int max = 25, int step = 1);
void close(bool restore_focus = true);
void resize(float device_pixel_ratio);
void update();
bool is_open() const { return open_; }
void ProcessEvent(Rml::Event &) override;
private:
void render(bool focus_range = true);
void position();
void draft(int value);
void confirm();
void focus_opener();
bool fresh() const;
Rml::Context &context_;
Rml::ElementDocument &document_;
DataSource &source_;
std::function<void()> on_commit_;
Rml::Element *layer_ = nullptr;
std::string anchor_id_, error_;
std::shared_ptr<const Catalog> world_;
uint64_t revision_ = 0;
float ratio_ = 1.f;
int original_ = 0, value_ = 0, min_ = 0, max_ = 25, step_ = 1;
bool open_ = false, review_ = false;
};
} // namespace bmh::modern_ui
+859
View File
@@ -0,0 +1,859 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "modern/ui/view.hpp"
#include "content/package.hpp"
#include "launch/game_data.hpp"
#include "launch/process.hpp"
#include "launch/rml_path.hpp"
#include "launch/rml_video.hpp"
#include "modern/ui/desktop.hpp"
#include "modern/ui/gui_assets.hpp"
#include "modern/ui/model.hpp"
#include "modern/ui/ticket_popover.hpp"
#include "version.hpp"
#include <RmlUi/Core.h>
#include <RmlUi/Core/Elements/ElementFormControl.h>
#include <RmlUi_Platform_SDL.h>
#include <SDL.h>
#include <algorithm>
#include <array>
#include <cmath>
#include <fstream>
#include <functional>
#include <iomanip>
#include <nfd.hpp>
#include <sstream>
namespace bmh::modern_ui {
namespace {
std::string esc(std::string_view value) { return editor::escaped(value); }
std::string scalar(double n) {
std::ostringstream s;
s.imbue(std::locale::classic());
s << n;
return s.str();
}
std::string rect(double x, double y, double w, double h) {
return "left:" + scalar(x) + "dp;top:" + scalar(y) + "dp;width:" + scalar(w) +
"dp;height:" + scalar(h) + "dp;";
}
std::string btn(const std::string &action, const std::string &label,
const std::string &css = {}, const std::string &attrs = {}) {
return "<button data-action=\"" + esc(action) + "\" class=\"" + css + "\" " +
attrs + ">" + label + "</button>";
}
const std::array<std::string, 31> routes = {
"tables", "league", "strengths", "lineup", "achievements",
"other", "friendlies", "postpone", "calendar", "indoor",
"load", "save", "kickoff", "toto", "bank",
"camp", "training", "transfer", "tactics", "settings",
"scorers", "advertising", "stadium", "statistics", "environment",
"fairplay", "highscore", "contracts", "balance", "newplayer",
"news"};
const std::array<std::string, 31> titles = {"Tabellen",
"Ligaspiele",
"Stärken",
"Aufstellung",
"Erfolge",
"Übrige Spiele",
"Freundschaftsspiele",
"Verlegen",
"Kalender",
"Hallentabellen",
"Laden",
"Speichern",
"Anstoß",
"TOTO",
"Bank",
"Trainingslager",
"Training",
"Transfermarkt",
"Taktik",
"Einstellungen",
"Spielerstatistiken",
"Werbung",
"Stadion",
"Statistiken",
"Umfeld",
"Fairplay",
"Highscore",
"Verträge",
"Bilanz",
"Neuer Spieler",
"Nachrichten"};
std::string title(const std::string &route) {
const auto i = std::find(routes.begin(), routes.end(), route);
if (i != routes.end())
return titles[size_t(i - routes.begin())];
if (route == "newgame")
return "Neues Spiel";
if (route == "mods")
return "Mod";
if (route == "opening")
return "Saisonvorbereitung";
return "OpenBMH";
}
struct Picture {
std::string token;
int width = 1, height = 1;
};
class Renderer final : public rml::Renderer {
GuiAssets &gui_;
fs::path assets_;
std::shared_ptr<const Catalog> world_;
struct Entry {
std::string key;
bool world;
int pixels;
editor::images::Raster raster;
};
std::map<std::string, Entry> entries_;
std::map<std::string, std::string> keys_;
size_t serial_ = 0;
public:
Renderer(rml::Video &video, GuiAssets &gui, fs::path assets)
: rml::Renderer(video), gui_(gui), assets_(std::move(assets)) {}
Picture local_image(const fs::path &file, int pixels) {
const auto identity =
editor::utf8(file) + ":" +
std::to_string(fs::last_write_time(file).time_since_epoch().count());
if (!keys_.contains(identity)) {
auto raster = editor::images::decode(
editor::read_file(file), editor::utf8(file.extension()), pixels);
const auto token = "modern-image-" + std::to_string(serial_++) + ".png";
entries_[token] = {identity, false, pixels, std::move(raster)};
keys_[identity] = token;
}
const auto token = keys_.at(identity);
const auto &r = entries_.at(token).raster;
return {token, r.width, r.height};
}
void world(std::shared_ptr<const Catalog> value) {
Rml::ReleaseTextures(this);
entries_.clear();
keys_.clear();
world_ = std::move(value);
}
Picture image(const std::string &key, bool world = false, int pixels = 512) {
const auto identity =
(world ? "world:" : "gui:") + key + ":" + std::to_string(pixels);
auto found = keys_.find(identity);
if (found == keys_.end()) {
auto token = "modern-image-" + std::to_string(serial_++) + ".png";
editor::images::Raster raster;
if (world) {
if (!world_)
return {};
const auto bytes = world_->asset(key, pixels);
if (bytes.first.empty())
return {};
raster = editor::images::decode(bytes.first, bytes.second, pixels);
} else if (key.starts_with("icon.")) {
const auto name = key.substr(5);
if (name.empty() ||
name.find_first_not_of("abcdefghijklmnopqrstuvwxyz-") != name.npos)
return {};
raster = editor::images::decode(
editor::read_file(assets_ / "icons" / (name + ".svg")), ".svg",
pixels);
} else if (gui_.contains(key))
raster = gui_.decode(key, pixels);
else if (key == "background")
raster = editor::images::decode(
editor::read_file(assets_.parent_path() / "launcher" /
"stadium.tga"),
".tga", pixels);
else
return {};
// Decode at source fidelity, then bound GPU storage to the requested
// display detail.
const auto largest = std::max(raster.width, raster.height);
if (largest > pixels) {
const double scale = double(pixels) / largest;
editor::images::Raster small{
std::max(1, int(std::round(raster.width * scale))),
std::max(1, int(std::round(raster.height * scale))),
{}};
small.pixels.resize(size_t(small.width) * small.height * 4);
SDL_Surface *source = SDL_CreateRGBSurfaceWithFormatFrom(
raster.pixels.data(), raster.width, raster.height, 32,
raster.width * 4, SDL_PIXELFORMAT_RGBA32);
SDL_Surface *destination = SDL_CreateRGBSurfaceWithFormatFrom(
small.pixels.data(), small.width, small.height, 32, small.width * 4,
SDL_PIXELFORMAT_RGBA32);
if (!source || !destination) {
if (source)
SDL_FreeSurface(source);
if (destination)
SDL_FreeSurface(destination);
throw std::runtime_error(SDL_GetError());
}
SDL_SetSurfaceBlendMode(source, SDL_BLENDMODE_NONE);
SDL_BlitScaled(source, nullptr, destination, nullptr);
SDL_FreeSurface(source);
SDL_FreeSurface(destination);
raster = std::move(small);
}
entries_[token] = {key, world, pixels, std::move(raster)};
keys_[identity] = token;
found = keys_.find(identity);
}
const auto &r = entries_.at(found->second).raster;
return {found->second, r.width, r.height};
}
Rml::TextureHandle LoadTexture(Rml::Vector2i &dimensions,
const Rml::String &source) override {
const auto token = editor::utf8(editor::path(source).filename());
auto found = entries_.find(token);
if (found == entries_.end())
return rml::Renderer::LoadTexture(dimensions, source);
auto pixels = found->second.raster.pixels;
for (size_t i = 0; i < pixels.size(); i += 4)
for (int c = 0; c < 3; ++c)
pixels[i + c] =
uint8_t((unsigned(pixels[i + c]) * pixels[i + 3] + 127) / 255);
dimensions = {found->second.raster.width, found->second.raster.height};
return GenerateTexture(pixels, dimensions);
}
};
struct Mod {
std::string name, type, error;
fs::path file;
Json manifest;
};
class App final : public Rml::EventListener {
fs::path executable_, root_, assets_, gui_root_;
launch::SaveMigrator migrate_;
Config config_;
GuiAssets gui_;
rml::Video video_;
rml::AssetFiles files_;
SystemInterface_SDL system_;
Renderer renderer_;
TextInputMethodEditor_SDL ime_;
Rml::Context *context_ = nullptr;
Rml::ElementDocument *doc_ = nullptr;
bool initialized_ = false, closed_ = false, dirty_ = true,
needs_render_ = true;
double scale_ = 1, canvas_left_ = 0, canvas_top_ = 0;
std::string scene_ = "main", menu_, theme_ = "midnight", active_mod_,
selected_mod_, notice_, country_ = "nation:de", league_,
selected_club_;
std::vector<Mod> mods_;
std::shared_ptr<const Catalog> world_;
std::unique_ptr<DemoSource> source_;
std::unique_ptr<TicketPopover> ticket_;
bool focus_ticket_ = false;
float device_ratio_ = 1.f;
Json desktop_ = Json::object(), saved_desktop_ = Json::object(),
options_ = Json::object();
Json managers_draft_ = Json::array(),
start_options_ = {{"duration", 5}, {"difficulty", 3}, {"players", 1},
{"mode", 3}, {"league", true}, {"world", true}};
int manager_index_ = 0;
bool manager_picker_ = false, adding_manager_ = false;
struct Drag {
bool active = false, moved = false;
std::string id;
float x = 0, y = 0;
double left = 0, top = 0;
};
Drag drag_;
bool suppress_click_ = false;
std::vector<Json> undo_;
std::function<void()> confirm_;
std::string popup_, rendered_popup_;
bool rendered_confirm_ = false;
std::string popup_input_, popup_extra_, popup_accept_ = "Bestätigen";
bool popup_has_input_ = false, quit_after_save_ = false;
std::function<void(const std::string &)> text_accept_;
bool context_open_ = false, context_dirty_ = false;
std::string context_id_;
int context_x_ = 0, context_y_ = 0;
int opening_page_ = 0, draw_revealed_ = 0;
bool draw_playing_ = true;
uint64_t draw_at_ = 0;
std::string settings_category_ = "display";
Json draft_preferences_;
std::map<std::string, std::string> selections_;
Rml::Element *element(const std::string &id) const {
return doc_->GetElementById(id);
}
std::string field(const std::string &id) const {
auto *p = dynamic_cast<Rml::ElementFormControl *>(element(id));
return p ? p->GetValue() : "";
}
Snapshot snap() const { return source_->snapshot(); }
const Json &manager(const Snapshot &s) const {
return s.state.at("managers").at(0);
}
const Json *club(const Snapshot &s) const {
return s.world->find("clubs", manager(s).value("club", ""));
}
std::string cash(int64_t value) const {
return money(value,
world_ ? world_->manifest().value("currency", Json::object())
: Json::object());
}
fs::path user_dir() const {
const auto id = world_ ? world_->manifest().value("id", std::string("none"))
: std::string("none");
return root_ / "userdata" / "ui-demo" / content::sha256(id);
}
std::string img(const std::string &key, double w, double h,
bool world = false, bool cover = false, int pixels = 512) {
const auto p = renderer_.image(key, world, pixels);
if (p.token.empty())
return "<div style=\"width:" + scalar(w) + "dp;height:" + scalar(h) +
"dp;\"></div>";
double iw = w, ih = h;
std::string crop;
if (cover) {
const auto a = double(p.width) / p.height, b = w / h;
double x = 0, y = 0, sw = p.width, sh = p.height;
if (a > b) {
sw = sh * b;
x = (p.width - sw) / 2;
} else {
sh = sw / b;
y = (p.height - sh) / 2;
}
crop = " rect=\"" + scalar(x) + " " + scalar(y) + " " + scalar(sw) + " " +
scalar(sh) + "\"";
} else {
const auto factor = std::min(w / p.width, h / p.height);
iw = p.width * factor;
ih = p.height * factor;
}
return "<div class=\"image-frame\" style=\"width:" + scalar(w) +
"dp;height:" + scalar(h) + "dp;\"><img src=\"" + p.token + "\"" +
crop + " style=\"width:" + scalar(iw) + "dp;height:" + scalar(ih) +
"dp;\"/></div>";
}
std::string crest(const Json *c, double size) {
return c ? img(c->value("crest", ""), size, size, true) : "";
}
std::string glyph(const std::string &name, double size) {
return img("icon." + name, size, size, false, false, int(size));
}
std::string label(const Json *c, double size = 40) {
return c ? "<span class=\"club-label\">" + crest(c, size) + "<span>" +
esc(world_->name(*c)) + "</span></span>"
: "";
}
std::string window(const std::string &heading, const std::string &content,
bool close = true) {
return "<div class=\"window\"><div class=\"titlebar\">" +
(close ? btn("close", "<span>×</span>", "close")
: "<span style=\"width:76dp;\"></span>") +
"<h1>" + esc(heading) + "</h1></div><div class=\"content\">" +
content + "</div></div>";
}
std::string
select(const std::string &id,
const std::vector<std::pair<std::string, std::string>> &rows,
const std::string &value, const std::string &action = {}) {
std::string out =
"<select id=\"" + id + "\" data-change=\"" + action + "\">";
for (const auto &[key, name] : rows)
out += "<option value=\"" + esc(key) + "\" " +
(key == value ? "selected" : "") + ">" + esc(name) + "</option>";
return out + "</select>";
}
bool apply(const std::string &kind, const Json &value) {
const auto r = source_->apply({source_->snapshot().revision, kind, value});
if (!r.ok) {
message("Die Eingabe konnte nicht übernommen werden: " + r.error);
return false;
}
return true;
}
void reset_popup() {
popup_has_input_ = false;
popup_input_.clear();
popup_extra_.clear();
popup_accept_ = "Bestätigen";
text_accept_ = {};
rendered_popup_.clear();
}
void message(const std::string &text) {
reset_popup();
popup_ = text;
confirm_ = {};
dirty_ = true;
}
void confirmation(const std::string &text, std::function<void()> accepted) {
reset_popup();
popup_ = text;
confirm_ = std::move(accepted);
dirty_ = true;
}
void text_dialog(const std::string &text, const std::string &initial,
std::function<void(const std::string &)> accepted) {
confirmation(text, {});
popup_has_input_ = true;
popup_input_ = initial;
text_accept_ = std::move(accepted);
dirty_ = true;
}
void refresh() {
needs_render_ = true;
dirty_ = true;
}
void collect_mods() {
mods_.clear();
const auto folder = root_ / "mods";
if (!fs::exists(folder))
return;
for (const auto &entry : fs::directory_iterator(folder)) {
if (!entry.is_directory() || entry.is_symlink() ||
editor::utf8(entry.path().filename()).starts_with('.'))
continue;
Mod m{editor::utf8(entry.path().filename()),
"",
{},
entry.path() / "content.obw",
{}};
try {
auto store = editor::ArchiveStore::open(m.file);
m.manifest = Json::parse(store->read("manifest.json"));
m.type = Catalog::modern_manifest(m.manifest) ? "Modern" : "Classic";
} catch (const std::exception &e) {
m.error = e.what();
m.type = "Unbekannt";
}
mods_.push_back(std::move(m));
}
std::sort(mods_.begin(), mods_.end(),
[](const auto &a, const auto &b) { return a.name < b.name; });
}
Mod *mod(const std::string &name) {
for (auto &m : mods_)
if (m.name == name)
return &m;
return nullptr;
}
void load_world(const fs::path &file) {
auto next = Catalog::open(file);
auto demo = std::make_unique<DemoSource>(next);
ticket_.reset();
renderer_.world(next);
world_ = std::move(next);
source_ = std::move(demo);
desktop_ = Json::object();
ticket_ =
std::make_unique<TicketPopover>(*context_, *doc_, *source_, [this] {
focus_ticket_ = true;
refresh();
});
league_ = world_->leagues("nation:de").empty()
? ""
: world_->leagues("nation:de").front()->value("id", "");
selected_club_ = manager(snap()).value("club", "");
}
std::string main_menu() {
const auto *m = mod(active_mod_);
std::string out =
"<div class=\"fill front-shade\"></div><div "
"class=\"brand\"><p>FUSSBALLMANAGER</p><h1>Open<span>BMH</span></h1></"
"div><div class=\"main-options\">";
const std::array<std::pair<std::string, std::string>, 6> actions = {
{{"new", "Neues Spiel"},
{"load", "Spiel laden"},
{"network", "Netzwerk"},
{"mods", "Mod"},
{"settings", "Einstellungen"},
{"exit", "Beenden"}}};
for (const auto &[key, name] : actions)
out += btn(
key, esc(name) + (key == "network" ? "<small>Demnächst</small>" : ""),
{},
key == "network" || (key == "new" && !m && !world_) ? "disabled"
: "");
out +=
"</div><div class=\"front-footer\"><div><small>Aktive Mod</small><p>" +
esc(m ? m->name
: world_ ? world_->title()
: "Keine Mod aktiviert") +
"</p></div><small>v" + std::string(kOpenBmhVersion) +
(m && m->type == "Classic" ? "" : " · Modern UI Demo") +
"</small></div>";
return out;
}
std::string mods_page() {
if (selected_mod_.empty() && !mods_.empty())
selected_mod_ = mods_.front().name;
std::string left = "<h3 style=\"padding:28dp;\">Installierte Mods</h3><div "
"class=\"list\" style=\"height:1310dp;\">";
for (const auto &m : mods_)
left += btn(
"mod-select",
"<span class=\"grow\">" + esc(m.name) + "</span><span>" +
esc(m.type) + "</span>",
std::string("row choice ") +
(m.name == selected_mod_ ? "selected" : ""),
"data-id=\"" + esc(m.name) +
"\" style=\"width:100%;margin-bottom:12dp;min-height:120dp;\"");
left += "</div>";
std::string right;
if (auto *m = mod(selected_mod_))
right =
"<div class=\"column\" style=\"padding:38dp;\">" +
img("background", 1300, 400, false, true, 1600) + "<h2>" +
esc(m->name) + "</h2><p class=\"muted\">" + esc(m->type) +
(m->type == "Modern" ? " · Oberfläche bis zum Anstoß" : "") +
"</p><p>" + esc(m->error) + "</p>" +
btn("mod-activate", m->name == active_mod_ ? "Aktiv" : "Aktivieren",
"primary", m->name == active_mod_ ? "disabled" : "") +
"</div>";
return window(
"Mod",
"<div class=\"row\" style=\"height:1560dp;align-items:stretch;\"><div "
"class=\"panel\" style=\"width:1120dp;\">" +
left + "</div><div class=\"panel grow\">" + right +
"</div></div><div class=\"bottom-controls\">" +
btn("import-modern", "OBW-Paket hinzufügen") +
btn("import-classic", "BMH / Football Limited") +
btn("mod-rename", "Umbenennen") + btn("mod-remove", "Löschen") +
"</div>");
}
std::string render_desktop();
void init_desktop();
std::string widget(const std::string &, const Json &);
std::string render_table(bool strengths = false, bool indoor = false);
std::string render_camp();
std::string render_settings();
std::string render_save(bool save);
std::string render_desktop_tools(const std::string &);
void render_context();
void context_menu(const std::string &id, int x, int y);
void drag_event(Rml::Event &);
std::string render_newgame();
std::string render_manager();
std::string render_opening();
std::string render_menu(const std::string &);
void dispatch(const std::string &, Rml::Element *);
void change(Rml::Element *);
void input(Rml::Element *);
void resize() {
int w, h, pw, ph;
SDL_GetWindowSize(video_.window, &w, &h);
video_.drawable_size(pw, ph);
if (w <= 0 || h <= 0 || pw <= 0 || ph <= 0)
return;
scale_ = std::min(double(pw) / 3840, double(ph) / 2160);
canvas_left_ = (pw - 3840 * scale_) / 2;
canvas_top_ = (ph - 2160 * scale_) / 2;
device_ratio_ = float(pw) / w;
renderer_.SetViewport(pw, ph);
context_->SetDimensions({pw, ph});
context_->SetDensityIndependentPixelRatio(float(scale_));
element("canvas")->SetProperty("left", scalar(canvas_left_) + "px");
element("canvas")->SetProperty("top", scalar(canvas_top_) + "px");
if (ticket_)
ticket_->resize(device_ratio_);
dirty_ = true;
}
void render() {
if (ticket_)
ticket_->close(false);
context_open_ = false;
context_dirty_ = true;
doc_->SetClassNames(theme_);
std::string markup;
if (scene_ == "main")
markup = main_menu();
else if (scene_ == "mods")
markup = mods_page();
else if (scene_ == "newgame")
markup = render_newgame();
else if (scene_ == "manager")
markup = render_manager();
else if (scene_ == "opening")
markup = render_opening();
else if (source_)
markup = render_desktop();
if (!menu_.empty())
markup += render_menu(menu_);
element("canvas")->SetInnerRML(markup);
const auto size = context_->GetDimensions();
const auto background =
img("background", size.x / scale_, size.y / scale_, false, true, 2048);
element("background")->SetInnerRML(background);
element("background")
->SetProperty("filter", scene_ == "main" ? "none"
: theme_ == "silver"
? "saturate(0.2) brightness(0.9)"
: theme_ == "matchday"
? "saturate(0.13) brightness(0.56)"
: "saturate(0.34) brightness(0.70)");
needs_render_ = false;
dirty_ = true;
if (focus_ticket_) {
if (auto *n = element("desktop-ticket"))
n->Focus();
focus_ticket_ = false;
}
}
void render_popup() {
if (popup_.empty()) {
element("popup")->SetClass("visible", false);
rendered_popup_.clear();
return;
}
element("popup")->SetClass("visible", true);
if (popup_ == rendered_popup_ && bool(confirm_) == rendered_confirm_)
return;
element("popup")->SetInnerRML(
"<div class=\"fill popup-backdrop\"></div><div "
"class=\"popup-box\"><h2>OpenBMH</h2><p>" +
esc(popup_) + "</p>" +
(popup_has_input_
? "<input id=\"popup-text\" value=\"" + esc(popup_input_) +
"\" style=\"width:100%;margin-bottom:38dp;\"/>"
: "") +
"<footer>" +
btn("popup-close",
confirm_ || text_accept_ ? "Abbrechen" : "Verstanden") +
popup_extra_ +
((confirm_ || text_accept_)
? btn("popup-confirm", popup_accept_, "primary")
: "") +
"</footer></div>");
rendered_popup_ = popup_;
rendered_confirm_ = bool(confirm_);
if (auto *button = element("popup")->QuerySelector("button"))
button->Focus();
}
void frame() {
if (ticket_)
ticket_->update();
if (needs_render_)
render();
render_popup();
render_context();
context_->Update();
renderer_.Clear();
renderer_.BeginFrame();
context_->Render();
renderer_.EndFrame();
video_.present();
dirty_ = false;
}
void screenshot(const fs::path &file) {
frame();
int w, h;
auto bytes = video_.capture(w, h);
fs::create_directories(file.parent_path());
editor::write_atomic(file,
editor::images::encode_png({w, h, std::move(bytes)}));
}
void load_fonts() {
bool regular = false, bold = false;
#ifdef _WIN32
const char *base = std::getenv("WINDIR");
if (base) {
const auto folder = fs::path(base) / "Fonts";
regular = Rml::LoadFontFace(rml::asset_path(folder / "segoeui.ttf"),
"Modern", Rml::Style::FontStyle::Normal,
Rml::Style::FontWeight::Normal);
bold = Rml::LoadFontFace(rml::asset_path(folder / "segoeuib.ttf"),
"Modern", Rml::Style::FontStyle::Normal,
Rml::Style::FontWeight::Bold);
}
#elif defined(__APPLE__)
const fs::path system = "/System/Library/Fonts/SFNS.ttf";
if (fs::exists(system)) {
regular = Rml::LoadFontFace(rml::asset_path(system), "Modern",
Rml::Style::FontStyle::Normal,
Rml::Style::FontWeight::Normal);
bold = Rml::LoadFontFace(rml::asset_path(system), "Modern",
Rml::Style::FontStyle::Normal,
Rml::Style::FontWeight::Bold);
}
#else
const fs::path fonts = fs::exists("/usr/share/fonts/truetype/liberation2")
? "/usr/share/fonts/truetype/liberation2"
: "/usr/share/fonts/truetype/liberation";
if (fs::exists(fonts)) {
regular = Rml::LoadFontFace(
rml::asset_path(fonts / "LiberationSans-Regular.ttf"), "Modern",
Rml::Style::FontStyle::Normal, Rml::Style::FontWeight::Normal);
bold = Rml::LoadFontFace(
rml::asset_path(fonts / "LiberationSans-Bold.ttf"), "Modern",
Rml::Style::FontStyle::Normal, Rml::Style::FontWeight::Bold);
}
#endif
if (!regular)
regular = Rml::LoadFontFace(
rml::asset_path(assets_ / "LatoLatin-Regular.ttf"), "Modern",
Rml::Style::FontStyle::Normal, Rml::Style::FontWeight::Normal);
if (!bold)
bold = Rml::LoadFontFace(rml::asset_path(assets_ / "LatoLatin-Bold.ttf"),
"Modern", Rml::Style::FontStyle::Normal,
Rml::Style::FontWeight::Bold);
if (!regular || !bold)
throw std::runtime_error(
"GUI-Schriften fehlen. Bitte das vollständige Paket entpacken.");
}
void script();
public:
App(fs::path executable, launch::SaveMigrator migrate, Config config)
: executable_(std::move(executable)), root_(executable_.parent_path()),
assets_(root_ / "assets" / "modern"),
gui_root_(config.gui_assets.empty() ? assets_ / "gui"
: config.gui_assets),
migrate_(std::move(migrate)), config_(std::move(config)),
gui_(gui_root_),
video_("OpenBMH", config_.width, config_.height, 960, 540),
system_(video_.window), renderer_(video_, gui_, assets_) {
try {
Rml::SetSystemInterface(&system_);
Rml::SetFileInterface(&files_);
Rml::SetRenderInterface(&renderer_);
Rml::SetTextInputHandler(&ime_);
initialized_ = Rml::Initialise();
if (!initialized_)
throw std::runtime_error("RmlUI initialization failed");
load_fonts();
context_ =
Rml::CreateContext("modern-ui", {config_.width, config_.height});
if (!context_)
throw std::runtime_error("Modern UI context failed");
doc_ = context_->LoadDocument(rml::asset_path(assets_ / "modern.rml"));
if (!doc_)
throw std::runtime_error("Modern UI layout missing");
for (const char *event :
{"click", "dblclick", "change", "input", "keydown", "mousedown",
"mouseup", "mousemove", "contextmenu"})
doc_->AddEventListener(event, this);
if(!config_.theme.empty())theme_ = config_.theme;
if(theme_!="midnight"&&theme_!="silver"&&theme_!="matchday")throw editor::Error("Unbekanntes Modern-Theme.");
collect_mods();
if (!mods_.empty())
active_mod_ = mods_.front().name;
if (!config_.world.empty()) {
load_world(config_.world);
scene_ = config_.scene;
if (scene_ != "main" && scene_ != "newgame" && scene_ != "manager" &&
scene_ != "opening" && scene_ != "desktop") {
menu_ = scene_;
scene_ = "desktop";
}
}
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(source_&&!config_.theme.empty()){
auto preferences=snap().state.at("preferences");preferences["theme"]=theme_;apply("preferences",preferences);
}
if (scene_ == "manager" && selections_["manager-name"].empty())
selections_["manager-name"] = "Alex Berger";
doc_->Show();
resize();
render();
SDL_ShowWindow(video_.window);
frame();
} catch (...) {
shutdown();
throw;
}
}
void shutdown() {
ticket_.reset();
if (doc_) {
doc_->Close();
doc_ = nullptr;
}
if (context_) {
const auto name = context_->GetName();
context_ = nullptr;
Rml::RemoveContext(name);
}
if (initialized_) {
Rml::Shutdown();
initialized_ = false;
}
}
~App() { shutdown(); }
void ProcessEvent(Rml::Event &event) override;
int run() {
if (!config_.commands.empty())
script();
if (!config_.screenshot.empty()) {
screenshot(config_.screenshot);
return 0;
}
while (!closed_) {
if (scene_ == "opening" && opening_page_ == 3 && draw_revealed_ < 64 &&
draw_playing_ && SDL_GetTicks64() >= draw_at_ &&
(SDL_GetWindowFlags(video_.window) & SDL_WINDOW_INPUT_FOCUS)) {
++draw_revealed_;
draw_at_ = SDL_GetTicks64() + 900;
if (draw_revealed_ == 64)
opening_page_ = 4;
refresh();
}
if (needs_render_ || dirty_)
frame();
SDL_Event event;
const auto timeout =
int(std::clamp(context_->GetNextUpdateDelay(), 0.0, .2) * 1000);
bool got = SDL_WaitEventTimeout(&event, timeout) != 0;
while (got) {
if (event.type == SDL_QUIT) {
if (source_ && scene_ != "main") {
dispatch("context-quit", nullptr);
} else
closed_ = true;
} else {
if (event.type == SDL_WINDOWEVENT)
resize();
int w, h, pw, ph;
SDL_GetWindowSize(video_.window, &w, &h);
video_.drawable_size(pw, ph);
if (w > 0 && h > 0) {
if (event.type == SDL_MOUSEMOTION) {
event.motion.x = int(double(event.motion.x) * pw / w);
event.motion.y = int(double(event.motion.y) * ph / h);
}
if (event.type == SDL_MOUSEBUTTONDOWN ||
event.type == SDL_MOUSEBUTTONUP) {
event.button.x = int(double(event.button.x) * pw / w);
event.button.y = int(double(event.button.y) * ph / h);
context_->ProcessMouseMove(event.button.x, event.button.y,
RmlSDL::GetKeyModifierState());
}
}
RmlSDL::InputEventHandler(context_, video_.window, event);
dirty_ = true;
}
got = SDL_PollEvent(&event) != 0;
}
if (context_->GetNextUpdateDelay() <= 0)
dirty_ = true;
}
return 0;
}
};
#include "modern/ui/controls.inc"
#include "modern/ui/desktop_screens.inc"
#include "modern/ui/screens.inc"
} // namespace
bool is_modern_world(const fs::path &file) {
try {
auto store = editor::ArchiveStore::open(file);
return Catalog::modern_manifest(Json::parse(store->read("manifest.json")));
} catch (const std::exception &) {
return false;
}
}
int run(const fs::path &executable, const launch::SaveMigrator &migrate,
const Config &config) {
App app(executable, migrate, config);
return app.run();
}
} // namespace bmh::modern_ui
+16
View File
@@ -0,0 +1,16 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "launch/mods.hpp"
namespace bmh::modern_ui {
struct Config {
std::filesystem::path world, gui_assets, screenshot, commands, state;
std::string scene = "main", theme;
int width = 1280, height = 720;
};
// Returns before Classic initialization. The demonstration never starts a
// match.
int run(const std::filesystem::path &executable, const launch::SaveMigrator &,
const Config &);
bool is_modern_world(const std::filesystem::path &);
} // namespace bmh::modern_ui