Files
Dreierpack-Manager/src/modern/ui/view.cpp
T

1535 lines
66 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// SPDX-License-Identifier: GPL-3.0-only
#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/controls.hpp"
#include "modern/ui/engine_bridge.hpp"
#include "modern/ui/live_match_info.hpp"
#include "modern/ui/script_locator.hpp"
#include "modern/ui/select_menu.hpp"
#include "modern/ui/demo_calendar.hpp"
#include "modern/ui/demo_finance.hpp"
#include "modern/ui/demo_environment.hpp"
#include "modern/ui/demo_advertising.hpp"
#include "modern/ui/demo_toto.hpp"
#include "modern/ui/demo_reports.hpp"
#include "modern/ui/demo_opening.hpp"
#include "modern/ui/demo_sports.hpp"
#include "modern/ui/demo_lineup.hpp"
#include "modern/ui/demo_live.hpp"
#include "modern/ui/demo_post_match.hpp"
#include "modern/ui/postmatch_eleven_markup.hpp"
#include "modern/ui/demo_career.hpp"
#include "modern/ui/demo_national_ui.hpp"
#include "modern/ui/demo_transfer.hpp"
#include "modern/ui/demo_career_reports.hpp"
#include "modern/ui/demo_rankings.hpp"
#include "modern/ui/demo_stadium.hpp"
#include "modern/ui/demo_statistics.hpp"
#include "modern/ui/demo_news.hpp"
#include "modern/ui/demo_settings.hpp"
#include "modern/ui/settings_presentation.hpp"
#include "modern/ui/ui_preferences.hpp"
#include "modern/ui/desktop.hpp"
#include "modern/ui/demo_widgets.hpp"
#include "modern/ui/demo_files.hpp"
#include "modern/ui/gui_assets.hpp"
#include "modern/ui/model.hpp"
#include "modern/ui/mod_library.hpp"
#include <future>
#include <mutex>
#include "modern/ui/ticket_popover.hpp"
#include "modern/ui/view.hpp"
#include "version.hpp"
#include <RmlUi/Core.h>
#include <cstring>
#include <tuple>
#include <RmlUi/Core/Elements/ElementFormControl.h>
#include <RmlUi/Core/Elements/ElementFormControlInput.h>
#include <RmlUi/Core/Elements/ElementFormControlSelect.h>
#include <RmlUi_Platform_SDL.h>
#include <SDL.h>
#include <algorithm>
#include <array>
#include <chrono>
#include <cmath>
#include <fstream>
#include <functional>
#include <iomanip>
#include <nfd.hpp>
#include <optional>
#include <RmlUi/Core/ScrollTypes.h>
#include <sstream>
namespace bmh::modern_ui {
namespace {
std::string esc(std::string_view value) { return editor::escaped(value); }
std::string money_classes(int64_t value) { return value < 0 ? "money-amount is-negative" : "money-amount"; }
std::string scalar(double n) {
std::ostringstream s;
s.imbue(std::locale::classic());
s << n;
return s.str();
}
std::string mixed_color(const std::string &first, const std::string &second,
double amount) {
std::ostringstream out;
out << '#' << std::hex << std::setfill('0');
for (size_t i = 1; i < 7; i += 2) {
const int a = std::stoi(first.substr(i, 2), nullptr, 16),
b = std::stoi(second.substr(i, 2), nullptr, 16);
out << std::setw(2) << int(std::round(a * (1 - amount) + b * amount));
}
return out.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_markup(action, label, css, attrs);
}
const std::array<std::string, 32> 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", "almanac"};
const std::array<std::string, 32> 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",
"Fairplaywertung",
"Highscore",
"Verträge",
"Bilanz",
"Neuer Spieler",
"Nachrichten", "Almanach"};
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 == "widgets")
return "Widget hinzufügen";
if (route == "view-save")
return "Ansicht speichern";
if (route == "view-load")
return "Ansicht laden";
if (route == "background")
return "Hintergrundbild ändern";
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_;
std::map<std::string, std::string> loaded_sources_;
size_t serial_ = 0;
public:
Renderer(rml::Video &video, GuiAssets &gui, fs::path assets)
: rml::Renderer(video), gui_(gui), assets_(std::move(assets)) {}
Picture diagram(const std::string &slot, const std::string &svg,
int pixels = 2400) {
const auto token = "modern-dynamic-" + slot + ".png",
digest = content::sha256(svg);
auto found = entries_.find(token);
if (found == entries_.end() || found->second.key != digest) {
auto raster = editor::images::decode(svg, ".svg", pixels);
if (const auto loaded = loaded_sources_.find(token);
loaded != loaded_sources_.end()) {
Rml::ReleaseTexture(loaded->second, this);
loaded_sources_.erase(loaded);
}
entries_[token] = {digest, false, pixels, std::move(raster)};
}
const auto &r = entries_.at(token).raster;
return {token, r.width, r.height};
}
Picture generated_png(const std::string &slot,const std::string &png){
const auto token="modern-generated-"+slot+".png",digest=content::sha256(png);
auto found=entries_.find(token);
if(found==entries_.end()||found->second.key!=digest){
if(auto loaded=loaded_sources_.find(token);loaded!=loaded_sources_.end()){Rml::ReleaseTexture(loaded->second,this);loaded_sources_.erase(loaded);}
entries_[token]={digest,false,1280,editor::images::decode(png,".png")};
}
const auto &r=entries_.at(token).raster;return {token,r.width,r.height};
}
Picture local_image(const fs::path &file, int pixels) {
const auto identity =
editor::utf8(file) + ":" +
std::to_string(std::chrono::duration_cast<std::chrono::nanoseconds>(
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();
loaded_sources_.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.")) {
auto name = key.substr(5);
const bool ink = name.ends_with("-ink");
if (ink)
name.resize(name.size() - 4);
if (name.empty() ||
name.find_first_not_of("abcdefghijklmnopqrstuvwxyz-") != name.npos)
return {};
auto svg = editor::read_file(assets_ / "icons" / (name + ".svg"));
if (ink) {
size_t at = 0;
while ((at = svg.find("#dceae7", at)) != std::string::npos) {
svg.replace(at, 7, "#426071");
at += 7;
}
}
raster = editor::images::decode(svg, ".svg", pixels);
} else if (key == "button.almanac" && !gui_.contains(key)) {
raster = editor::images::decode(editor::read_file(assets_ / "icons" / "almanac.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 thumbnail{
std::max(1, int(std::round(raster.width * scale))),
std::max(1, int(std::round(raster.height * scale))),
{}};
thumbnail.pixels.resize(size_t(thumbnail.width) * thumbnail.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(
thumbnail.pixels.data(), thumbnail.width, thumbnail.height, 32,
thumbnail.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(thumbnail);
}
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);
loaded_sources_[token] = 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;
};
struct AmountRequest {
std::string title, unit, return_focus;
int64_t value = 0, min = 0, max = 99999999, step = 1, suggestion_step = 100000;
bool review = true;
std::function<std::string(int64_t)> review_text;
std::function<bool(int64_t)> accept;
};
struct AmountDraft {
AmountRequest request;
std::string raw, error, menu;
bool review = false;
uint64_t revision = 0;
std::shared_ptr<const Catalog> world;
};
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_;
std::unique_ptr<SelectMenu> select_menu_;
bool select_text_input_owned_ = false;
struct SelectCapture final : Rml::EventListener {
std::function<void(Rml::Event &)> handler;
void ProcessEvent(Rml::Event &event) override {
if (handler) handler(event);
}
} select_capture_;
static constexpr std::array<const char *, 9> select_capture_events_ = {
"mousedown", "mouseup", "click", "keydown", "textinput", "blur", "scroll", "mousemove", "contextmenu"};
bool focus_ticket_ = false;
std::set<std::string> pending_selects_;
std::string focus_after_render_;
uint64_t document_generation_ = 0;
bool keyboard_navigation_ = false, setting_menu_markup_ = false;
std::string last_rendered_menu_;
std::optional<float> training_scroll_;
std::optional<float> report_scroll_;
float fixture_half_width_ = -1.f;
float almanac_list_width_ = -1.f;
std::string last_report_state_, report_picker_, report_detail_kind_,
report_detail_club_, report_detail_player_, report_detail_return_focus_,
report_option_to_scroll_;
std::string planning_dialog_, planning_notice_, planning_return_focus_;
int almanac_year_ = 0;
std::string almanac_day_, almanac_match_, almanac_tab_ = "lineups";
std::optional<AmountDraft> amount_;
bool amount_select_all_ = false, amount_caret_end_ = false;
std::string bank_view_ = "entrance", bank_hint_;
int bank_property_ = 0, bank_owned_ = 0, bank_stock_ = 11;
bool balance_future_ = false;
Json contract_draft_;
std::string contracts_player_, contracts_dialog_, contracts_return_focus_, contracts_notice_;
int contracts_tab_ = 2;
uint64_t contracts_revision_ = 0;
std::shared_ptr<const Catalog> contracts_world_;
int advertising_selected_ = -1, advertising_offer_ = 0;
uint64_t advertising_revision_ = 0;
std::shared_ptr<const Catalog> advertising_world_;
int toto_column_ = 0;
std::array<std::pair<int, int>, 6> toto_focus_{{{0,1},{0,1},{0,1},{0,1},{0,1},{0,1}}};
std::string toto_dialog_, toto_return_focus_;
bool lineup_pitch_ = true;
int lineup_data_ = 0, lineup_page_ = 0;
std::string lineup_side_ = "formations", lineup_selected_;
Json lineup_drag_;
uint64_t lineup_drag_revision_ = 0;
std::shared_ptr<const Catalog> lineup_drag_world_;
bool lineup_ignore_click_ = false, lineup_reset_scroll_ = false;
std::optional<float> lineup_roster_scroll_;
Json transfer_view_ = Json::object(), transfer_draft_, transfer_search_draft_;
std::string transfer_dialog_, transfer_return_focus_, transfer_notice_, transfer_poach_league_, transfer_poach_club_, transfer_picker_;
uint64_t transfer_revision_ = 0;
std::shared_ptr<const Catalog> transfer_world_;
Json career_view_ = Json::object(), rankings_view_ = Json::object();
Json stadium_view_ = Json::object();
uint64_t stadium_revision_ = 0;
std::shared_ptr<const Catalog> stadium_world_;
const DataSource *stadium_source_ = nullptr;
#include "modern/ui/statistics_state.inc"
#include "modern/ui/news_state.inc"
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}};
std::shared_ptr<const Catalog> entry_catalog_;
const DataSource *entry_source_ = nullptr;
uint64_t entry_revision_ = 0;
std::string club_search_, entry_return_scene_ = "main",
entry_picker_country_, entry_picker_league_;
bool manager_confirm_ = false, manager_success_ = false;
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;
bool pinned=false;
};
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;
uint64_t opening_due_ = 0;
bool opening_io_blocked_ = false;
int last_tactic_ = 0;
#include "modern/ui/engine_state.inc"
#include "modern/ui/settings_state.inc"
#include "modern/ui/widgets_state.inc"
#include "modern/ui/files_state.inc"
#include "modern/ui/front_state.inc"
#include "modern/ui/live_state.inc"
#include "modern/ui/postmatch_state.inc"
#include "modern/ui/national_state.inc"
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(); }
uint64_t input_revision() const { return engine_mode_ ? std::stoull(engine_data_.at("desktop").at("meta").at("stateRevision").get<std::string>()) : snap().revision; }
const Json &manager(const Snapshot &s) const {
return demo_career_manager(s.state);
}
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());
}
std::string money_unit() const {
const auto code = world_ ? world_->manifest().value("currency", Json::object()).value("code", std::string("EUR")) : "EUR";
return code == "EUR" ? "€" : code;
}
fs::path user_dir() const {
const auto id = world_ ? world_->manifest().value("id", std::string("none"))
: std::string("none");
return (config_.userdata.empty() ? root_ / "userdata" : config_.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) {
return picture(renderer_.image(key, world, pixels), w, h, cover);
}
std::string picture(const Picture &p, double w, double h,
bool cover = false) {
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 + (theme_ == "silver" ? "-ink" : ""), 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", "id=\"window-close\" aria-label=\"" + std::string(menu_ == "bank" && bank_view_ != "entrance" ? "Zurück zur Bankhalle" : "Fenster schließen") + "\"")
: "<span style=\"width:76dp;\"></span>") +
"<h1>" + esc(heading) + "</h1></div><div class=\"content\">" +
content + "</div>" + (amount_ ? render_amount() : "") + "</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) {
if (kind == "training" && r.error == "training_preview_budget") {
const int limit = value.value("group", "") == "type" ? 8
: value.value("index", 0) < 2 ? 4
: 18;
message("Für diesen Trainingsbereich stehen höchstens " +
std::to_string(limit) + " Bälle zur Verfügung.");
return false;
}
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() {
front_snapshot_=UiModLibrary(front_library_root()).snapshot();mods_.clear();
for(const auto &entry:front_snapshot_.entries)mods_.push_back({entry.name,entry.type,entry.error,entry.path/"content.obw",Json::object()});
active_mod_=front_external_override_?"":front_snapshot_.active.value_or("");
if(!front_selected())selected_mod_=front_snapshot_.entries.empty()?"":front_snapshot_.entries.front().id;
}
Mod *mod(const std::string &name) {
for (auto &m : mods_)
if (m.name == name)
return &m;
return nullptr;
}
void bind_world(std::shared_ptr<const Catalog> next) {
renderer_.world(std::move(next));
files_default_key_.clear();
files_default_picture_ = Picture();
files_default_pending_ = false;
}
void load_world(const fs::path &file) {
auto next = Catalog::open(file);
auto demo = std::make_unique<DemoSource>(next);
publish_world(std::move(next), std::move(demo));
}
void publish_world(std::shared_ptr<const Catalog> next,
std::unique_ptr<DemoSource> demo) {
live_.close(); live_drafts_ = Json::object(); live_dialog_.clear();
live_dialog_draft_ = Json(); live_world_.reset(); live_source_ = nullptr;
live_last_tick_ = 0; live_speed_dragging_ = false; live_review_ = false;
reset_settings();
reset_files();
ticket_.reset();
bind_world(next);
world_ = std::move(next);
source_ = std::move(demo);
opening_due_ = 0;
opening_io_blocked_ = false;
lineup_drag_ = Json(); lineup_drag_world_.reset(); lineup_selected_.clear(); lineup_ignore_click_ = false;
lineup_pitch_ = true; lineup_data_ = lineup_page_ = 0; lineup_side_ = "formations";
transfer_view_ = Json::object(); transfer_draft_ = transfer_search_draft_ = Json();
transfer_dialog_.clear(); transfer_picker_.clear(); transfer_notice_.clear(); transfer_return_focus_.clear();
transfer_poach_league_.clear(); transfer_poach_club_.clear(); transfer_world_.reset(); transfer_revision_ = 0;
career_view_ = Json::object(); rankings_view_ = Json::object();
statistics_view_ = Json::object(); statistics_trophy_ = Json::object();
statistics_scrolls_ = Json::object();
reset_news();
stadium_view_ = Json::object(); stadium_revision_ = 0;
stadium_world_.reset(); stadium_source_ = nullptr;
advertising_selected_ = -1; advertising_offer_ = 0; advertising_revision_ = 0; advertising_world_.reset();
toto_column_ = 0; toto_dialog_.clear();
for (auto &focus : toto_focus_) focus = {0, 1};
amount_.reset();
amount_select_all_ = amount_caret_end_ = false;
contracts_dialog_.clear();
contracts_player_.clear();
contract_draft_ = Json();
contracts_world_.reset();
bank_view_ = "entrance";
bank_hint_.clear();
balance_future_ = false;
almanac_year_ = 0;
almanac_day_.clear();
almanac_match_.clear();
almanac_tab_ = "lineups";
desktop_ = Json::object();
working_desktop_initialized_=false;working_desktop_base_=Json();
files_default_key_.clear();files_default_picture_=Picture();files_default_pending_=false;
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();
std::string mods_page();
std::string render_desktop();
std::string desktop_button(const std::string &, const Json &, const std::string &, bool enabled = true);
void init_desktop();
std::string widget(const std::string &, const Json &);
std::string render_reports(const std::string &);
std::string report_club_button(const std::string &, bool name_first = false);
std::string render_report_detail();
bool report_detail_action(const std::string &, Rml::Element *);
std::string report_picker(const std::string &, double, double);
std::vector<std::pair<std::string, std::string>>
report_picker_items(const std::string &) const;
std::string report_picker_value(const std::string &) const;
bool report_picker_event(Rml::Event &);
bool report_picker_action(const std::string &, Rml::Element *);
void close_report_picker(bool focus = false);
std::string render_camp();
std::string render_training();
std::string render_tactics();
std::string render_calendar();
Json planning_calendar() const;
std::string calendar_day_info(const Json &) const;
std::string calendar_grid(const Json &, double, double, double, double, bool, bool);
std::string render_postpone();
std::string render_friendlies();
std::string render_planning_dialog();
std::string planning_progress(bool, bool);
bool planning_action(const std::string &, Rml::Element *);
std::string render_amount();
void open_amount(AmountRequest);
void close_amount(bool restore = true);
void update_amount(bool focus = false, bool select_all = false);
bool amount_action(const std::string &, Rml::Element *);
bool amount_event(Rml::Event &);
bool amount_trigger_event(Rml::Event &);
std::optional<int64_t> amount_value() const;
std::string amount_error() const;
bool commit_finance(const Json &, uint64_t);
std::string render_bank();
bool bank_action(const std::string &, Rml::Element *);
bool bank_event(Rml::Event &);
std::string render_balance();
bool finance_action(const std::string &, Rml::Element *);
bool finance_event(Rml::Event &);
std::string render_contracts();
bool contracts_action(const std::string &, Rml::Element *);
bool contracts_event(Rml::Event &);
void close_contracts(bool restore = true);
std::string render_environment();
bool environment_action(const std::string &, Rml::Element *);
std::string render_advertising();
bool advertising_action(const std::string &, Rml::Element *);
bool advertising_event(Rml::Event &);
std::string render_toto();
bool toto_action(const std::string &, Rml::Element *);
bool toto_event(Rml::Event &);
std::string render_lineup();
bool lineup_action(const std::string &, Rml::Element *);
bool lineup_event(Rml::Event &);
void cancel_lineup_drag(bool refresh_view = true);
std::string render_transfer();
std::string render_transfer_dialog();
bool transfer_action(const std::string &, Rml::Element *);
bool transfer_event(Rml::Event &);
void close_transfer(bool restore = true);
void transfer_remember_scroll();
void transfer_restore_scroll();
std::string render_achievements();
std::string render_highscore();
bool career_report_action(const std::string &, Rml::Element *);
bool career_report_event(Rml::Event &);
std::string render_scorers();
std::string render_fairplay();
bool rankings_action(const std::string &, Rml::Element *);
bool rankings_event(Rml::Event &);
void rankings_remember_scroll();
void rankings_restore_scroll();
std::string render_stadium();
std::string render_stadium_dialog();
void sync_stadium_draft();
bool stadium_action(const std::string &, Rml::Element *);
bool stadium_event(Rml::Event &);
std::string render_almanac();
bool almanac_action(const std::string &, Rml::Element *);
std::string render_indoor();
bool indoor_action(const std::string &, Rml::Element *);
std::string training_balls(const std::string &, int, int, bool,
const std::string &player = {}, int size = 56,
int gap = 10, bool overtraining = false);
std::string render_settings();
void render_context();
void context_menu(const std::string &id, int x, int y);
void drag_event(Rml::Event &);
std::shared_ptr<const Catalog> entry_world() const {
return entry_catalog_ ? entry_catalog_ : world_;
}
bool entry_name_valid() const;
bool entry_used_club(const std::string &) const;
bool entry_used_portrait(int) const;
bool entry_full() const { return adding_manager_ && managers_draft_.size() >= size_t(career_national_entry()?1:4); }
void entry_begin();
void entry_add();
void entry_cancel();
void entry_choose_defaults();
void entry_sync_club();
void entry_confirm();
bool entry_action(const std::string &, Rml::Element *);
bool entry_change(Rml::Element *, bool user_reselected = false);
bool entry_input(Rml::Element *);
bool entry_event(Rml::Event &);
Json entry_snapshot() const;
bool career_resign_open_=false,career_game_end_=false;
int career_resign_portrait_=0;
uint64_t career_resign_revision_=0;
const DataSource *career_resign_source_=nullptr;
bool career_national_entry() const {return adding_manager_?source_&&!snap().state.at("edits").at("setup").value("league",true):!start_options_.value("league",true);}
std::string render_career();
bool career_action(const std::string &,Rml::Element *);
bool career_event(Rml::Event &);
std::string render_newgame();
std::string render_manager();
std::string render_opening();
fs::path opening_progress_path(const Catalog &) const;
void opening_write(const Catalog &, const Json &, const Json &);
void opening_restore_startup();
bool opening_pending() const;
bool opening_change(const std::string &);
bool opening_action(const std::string &, Rml::Element *);
bool opening_event(Rml::Event &);
void opening_tick();
void handle_event(SDL_Event &);
void pump_events();
std::string render_menu(const std::string &);
void dispatch(const std::string &, Rml::Element *);
void change(Rml::Element *);
void flush_selects() {
std::vector<std::string> ready;
for (const auto &id : pending_selects_) {
auto *select = dynamic_cast<Rml::ElementFormControlSelect *>(element(id));
if (!select || !select->IsSelectBoxVisible())
ready.push_back(id);
}
for (const auto &id : ready) {
pending_selects_.erase(id);
if (auto *select = element(id)) {
// Menu-local select handlers receive only a committed/cancelled value.
if (menu_ == "settings" || (menu_ == "lineup" && id.starts_with("lineup-")) ||
(menu_ == "transfer" && id.starts_with("transfer-")))
select->DispatchEvent("change", {});
else change(select);
}
}
}
void input(Rml::Element *);
void scale_chalk_shadow() {
// Pinned RmlUI font effects read integer pixels even for dp properties.
// Match the HTML's two logical pixels at the current stage density.
if (auto *label = doc_->QuerySelector(".tactic-effort-label")) {
const auto offset = std::to_string(int(std::round(2 * scale_)));
label->SetProperty("font-effect",
"shadow(" + offset + "px " + offset + "px #386824)");
}
}
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_);
scale_chalk_shadow();
dirty_ = true;
if (statistics_trophy_.contains("asset"))
needs_render_ = true;
}
void select_sync_keyboard() {
if (select_menu_ && select_menu_->is_open()) {
if (!SDL_IsTextInputActive()) {
SDL_StartTextInput();
select_text_input_owned_ = true;
}
} else if (select_text_input_owned_) {
auto *focus = context_ ? context_->GetFocusElement() : nullptr;
auto *input = dynamic_cast<Rml::ElementFormControlInput *>(focus);
const auto type = input ? input->GetAttribute<Rml::String>("type", "text") : "";
const bool editable = input && type != "range" && type != "checkbox" && type != "radio" && type != "button";
if (!editable && (!focus || focus->GetTagName() != "textarea")) SDL_StopTextInput();
select_text_input_owned_ = false;
}
}
void render() {
if (engine_mode_) { engine_render(); return; }
if (select_menu_) select_menu_->before_render();
if (source_ && scene_=="desktop" && snap().state.value("career",Json::object()).value("ended",false)){scene_="main";menu_.clear();}
if (scene_ == "desktop" && !files_capturing_ && opening_pending()) {
scene_ = "opening";
menu_.clear();
opening_due_ = 0;
}
news_before_render();
fixture_half_width_ = -1.f;
almanac_list_width_ = -1.f;
// A window-close save prompt can leave a menu while its local dialog is
// open. Never keep that menu's modal/input gate in the destination view.
if(menu_=="widgets" && last_rendered_menu_=="widgets")widget_remember_scroll();
if(source_ && scene_=="desktop")init_desktop();
files_before_render();
if (menu_ != last_rendered_menu_) {
if(last_rendered_menu_=="settings")reset_settings();
statistics_trophy_ = Json::object();
planning_dialog_.clear();
career_view_["dialog"] = ""; career_view_["return_focus"] = "";
stadium_view_["dialog"] = ""; stadium_view_["draft"] = Json();
stadium_view_["return_focus"] = ""; stadium_revision_ = 0;
stadium_view_["ticket_return_focus"] = "";
stadium_world_.reset(); stadium_source_ = nullptr;
lineup_drag_ = Json(); lineup_drag_world_.reset(); lineup_ignore_click_ = false;
transfer_dialog_.clear(); transfer_draft_ = transfer_search_draft_ = Json(); transfer_picker_.clear();
transfer_world_.reset(); transfer_revision_ = 0; transfer_return_focus_.clear();
toto_dialog_.clear();
if (menu_ == "toto" && source_)
for (size_t c = 0; c < toto_focus_.size(); ++c) {
const int pick = snap().state.at("toto").at("columns")[c][0];
toto_focus_[c] = {0, pick < 0 ? 1 : pick};
}
amount_.reset();
contracts_dialog_.clear();
contract_draft_ = Json();
report_detail_kind_.clear();
report_picker_.clear();
}
lineup_roster_scroll_.reset();
if (menu_ == "lineup" && last_rendered_menu_ == "lineup") {
if (auto *roster = element("lineup-roster-scroll"))
lineup_roster_scroll_ = lineup_reset_scroll_ ? 0.f : roster->GetScrollTop();
}
lineup_reset_scroll_ = false;
training_scroll_.reset();
if (menu_ == "training" && last_rendered_menu_ == "training")
if (auto *roster = element("training-roster"))
training_scroll_ = roster->GetScrollTop();
report_scroll_.reset();
const auto report_state = source_ ? snap().state.at("reports").dump() : "";
if (menu_ == last_rendered_menu_ && report_state == last_report_state_)
if (auto *list = element("report-list"))
report_scroll_ = list->GetScrollTop();
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 = main_menu()+"<div class=\"fill\" style=\"z-index:100;\">"+render_newgame()+"</div>";
else if (scene_ == "manager")
markup = (adding_manager_?render_desktop():main_menu())+"<div class=\"fill\" style=\"z-index:100;\">"+render_manager()+"</div>";
else if (scene_ == "managerhub")
markup = render_desktop()+"<div class=\"fill\" style=\"z-index:100;\">"+render_career()+"</div>";
else if (scene_ == "opening")
markup = main_menu()+"<div class=\"fill\" style=\"z-index:100;\">"+render_opening()+"</div>";
else if (scene_ == "live")
markup = render_live();
else if (source_)
markup = render_desktop();
if (!menu_.empty())
markup += render_menu(menu_);
setting_menu_markup_ = true;
element("canvas")->SetInnerRML(markup);
++document_generation_;
live_detail_pending_ = live_ticker_pending_ = false;
element("canvas")->SetProperty("overflow", statistics_trophy_.contains("asset") ? "visible" : "hidden");
setting_menu_markup_ = false;
if (manager_confirm_ || manager_success_) {
Rml::ElementList behind;
doc_->QuerySelectorAll(behind, "#entry-manager-underlay button,#entry-manager-underlay input,#entry-manager-underlay select,.window>.titlebar button");
for (auto *node : behind) node->SetProperty("pointer-events", "none");
}
if(scene_=="managerhub" || (scene_=="manager"&&adding_manager_)){
Rml::ElementList background;doc_->QuerySelectorAll(background,".desktop-layer button,.desktop-layer [data-action]");
for(auto *node:background){node->SetProperty("pointer-events","none");node->SetAttribute("tabindex",-1);}
}
if(!national_dialog_.empty() && source_ && snap().state.at("career").value("role","club")=="national"){Rml::ElementList behind;doc_->QuerySelectorAll(behind,"#national-underlay button,#national-underlay select,.window>.titlebar button");for(auto *node:behind){node->SetProperty("pointer-events","none");node->SetAttribute("tabindex",-1);}}
news_after_render();
if (!report_detail_kind_.empty() || !planning_dialog_.empty() || !contracts_dialog_.empty() || !toto_dialog_.empty() || !transfer_dialog_.empty() || !career_view_.value("dialog", "").empty() || !stadium_view_.value("dialog", "").empty()) {
Rml::ElementList behind;
doc_->QuerySelectorAll(behind,
"#report-underlay button,#report-underlay input,#report-underlay select,#contracts-underlay button,#toto-underlay button,#lineup-underlay button,#lineup-underlay select,#lineup-underlay input,#transfer-underlay button,#transfer-underlay select,#transfer-underlay input,#career-report-underlay button,#career-report-underlay input,#career-report-underlay select,.rankings-scorers button,.rankings-scorers select,.rankings-fairplay button,#stadium-underlay button,#stadium-underlay input,#stadium-underlay select,.window .titlebar button");
for (auto *node : behind)
node->SetProperty("pointer-events", "none");
}
if (amount_) {
Rml::ElementList underlay;
doc_->QuerySelectorAll(underlay, ".window>.content,.window>.titlebar");
for (auto *node : underlay) {
node->SetProperty("pointer-events", "none");
node->SetProperty("filter", "blur(10dp)");
}
}
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;
last_rendered_menu_ = menu_;
last_report_state_ = report_state;
scale_chalk_shadow();
dirty_ = true;
if (focus_ticket_) {
if (auto *n = element("desktop-ticket"))
n->Focus();
focus_ticket_ = false;
}
if (!focus_after_render_.empty()) {
if (auto *node = element(focus_after_render_))
node->Focus(keyboard_navigation_);
if (focus_after_render_.starts_with("report-option-") ||
focus_after_render_.starts_with("friendly-opponent-") ||
focus_after_render_.starts_with("alm-match-") ||
focus_after_render_.starts_with("contract-player-") ||
focus_after_render_.starts_with("lineup-name-") ||
focus_after_render_.starts_with("lineup-detail-"))
report_option_to_scroll_ = focus_after_render_;
focus_after_render_.clear();
}
}
void render_popup() {
if (!popup_.empty() && select_menu_) select_menu_->before_render();
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();
}
bool center_fixture_columns() {
bool changed = false;
// History can contain every competition on one date. Keep its whole-row
// buttons on the same centre even when the long list gains a scrollbar.
if (auto *history = element("alm-day-list")) {
if (auto *content = doc_->QuerySelector(".window .content")) {
const float width = content->GetBox().GetSize(Rml::BoxArea::Content).x;
if (std::abs(width - almanac_list_width_) >= .001f) {
almanac_list_width_ = width;
history->SetProperty("width", scalar(width) + "px");
Rml::ElementList rows;
history->QuerySelectorAll(rows, ".alm-list-head,.alm-match-row");
for (auto *row : rows) row->SetProperty("width", scalar(width) + "px");
changed = true;
}
}
}
auto *list = element("report-list");
if (!list || !list->IsClassSet("match-list"))
return changed;
auto *score = list->QuerySelector(".report-cell.score");
if (!score)
return changed;
const auto &box = list->GetBox();
// Rml rounds borders to physical pixels. Use the actual full inner width,
// independently of the scrollport, so fractional density cannot move scores.
const float inner = box.GetSize(Rml::BoxArea::Border).x -
box.GetEdge(Rml::BoxArea::Border, Rml::BoxEdge::Left) -
box.GetEdge(Rml::BoxArea::Border, Rml::BoxEdge::Right);
const float half = std::max(0.f, (inner - score->GetBox().GetSize(Rml::BoxArea::Border).x) / 2.f);
if (std::abs(half - fixture_half_width_) < .001f)
return changed;
fixture_half_width_ = half;
Rml::ElementList sides;
list->QuerySelectorAll(sides, ".report-cell.first,.report-cell:last-child");
for (auto *side : sides)
side->SetProperty("width", scalar(half) + "px");
return true;
}
void frame() {
if (engine_mode_) { engine_frame(); return; }
front_poll();
flush_selects();
if (ticket_)
ticket_->update();
if (needs_render_)
render();
else
live_update_parts();
if(files_default_pending_&&!files_capturing_){update_files_default_thumbnail();render();}
persist_working_desktop();
render_popup();
render_context();
context_->Update();
if (center_selects(*doc_))
context_->Update();
if (select_menu_) {
select_menu_->after_layout();
select_sync_keyboard();
context_->Update();
}
if (amount_select_all_) {
if (auto *input = dynamic_cast<Rml::ElementFormControlInput *>(element("calculator-value"))) input->Select();
amount_select_all_ = false;
}
if (amount_caret_end_) {
if (auto *input = dynamic_cast<Rml::ElementFormControlInput *>(element("calculator-value")))
input->SetSelectionRange(int(input->GetValue().size()), int(input->GetValue().size()));
amount_caret_end_ = false;
}
if (center_fixture_columns())
context_->Update();
if (training_scroll_) {
if (auto *roster = element("training-roster"))
roster->SetScrollTop(*training_scroll_);
training_scroll_.reset();
}
if (report_scroll_) {
if (auto *list = element("report-list"))
list->SetScrollTop(*report_scroll_);
report_scroll_.reset();
}
if (lineup_roster_scroll_) {
if (auto *roster = element("lineup-roster-scroll")) roster->SetScrollTop(*lineup_roster_scroll_);
lineup_roster_scroll_.reset();
}
if (menu_ == "transfer") transfer_restore_scroll();
if (menu_ == "scorers" || menu_ == "fairplay") rankings_restore_scroll();
if (menu_ == "statistics") statistics_restore_scroll();
if (menu_ == "settings") settings_after_render();
files_after_render();
front_after_render();
live_after_render();
if(menu_=="widgets" && widget_restore_scroll_){if(auto *gallery=element("widget-gallery"))gallery->SetScrollTop(widget_gallery_scroll_);widget_restore_scroll_=false;}
if (!report_option_to_scroll_.empty()) {
if (auto *node = element(report_option_to_scroll_))
node->ScrollIntoView(Rml::ScrollIntoViewOptions(Rml::ScrollAlignment::Nearest));
report_option_to_scroll_.clear();
}
renderer_.Clear();
renderer_.BeginFrame();
context_->Render();
renderer_.EndFrame();
if(!files_capturing_)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, italic = false, bold_italic = 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);
italic = Rml::LoadFontFace(rml::asset_path(folder / "segoeuii.ttf"),
"Modern", Rml::Style::FontStyle::Italic,
Rml::Style::FontWeight::Normal);
bold_italic = Rml::LoadFontFace(rml::asset_path(folder / "segoeuiz.ttf"),
"Modern", Rml::Style::FontStyle::Italic,
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);
const fs::path slanted = "/System/Library/Fonts/SFNSItalic.ttf";
if (fs::exists(slanted)) {
italic = Rml::LoadFontFace(rml::asset_path(slanted), "Modern",
Rml::Style::FontStyle::Italic,
Rml::Style::FontWeight::Normal);
bold_italic = Rml::LoadFontFace(rml::asset_path(slanted), "Modern",
Rml::Style::FontStyle::Italic,
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);
italic = Rml::LoadFontFace(
rml::asset_path(fonts / "LiberationSans-Italic.ttf"), "Modern",
Rml::Style::FontStyle::Italic, Rml::Style::FontWeight::Normal);
bold_italic = Rml::LoadFontFace(
rml::asset_path(fonts / "LiberationSans-BoldItalic.ttf"), "Modern",
Rml::Style::FontStyle::Italic, 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 (!italic)
italic = Rml::LoadFontFace(rml::asset_path(assets_ / "LatoLatin-Italic.ttf"),
"Modern", Rml::Style::FontStyle::Italic,
Rml::Style::FontWeight::Normal);
if (!bold_italic)
bold_italic = Rml::LoadFontFace(
rml::asset_path(assets_ / "LatoLatin-BoldItalic.ttf"), "Modern",
Rml::Style::FontStyle::Italic, Rml::Style::FontWeight::Bold);
std::vector<fs::path> chalk_fonts;
#ifdef _WIN32
if (const char *windir = std::getenv("WINDIR")) {
chalk_fonts.push_back(fs::path(windir) / "Fonts" / "comic.ttf");
chalk_fonts.push_back(fs::path(windir) / "Fonts" / "times.ttf");
}
#elif defined(__APPLE__)
chalk_fonts = {"/System/Library/Fonts/Supplemental/Comic Sans MS.ttf",
"/System/Library/Fonts/Supplemental/Apple Chancery.ttf",
"/System/Library/Fonts/Times.ttc"};
#else
chalk_fonts = {
"/usr/share/fonts/truetype/liberation2/LiberationSerif-Regular.ttf",
"/usr/share/fonts/truetype/liberation/LiberationSerif-Regular.ttf"};
#endif
chalk_fonts.push_back(assets_ / "LatoLatin-Regular.ttf");
for (const auto &font : chalk_fonts)
if (fs::exists(font) && Rml::LoadFontFace(rml::asset_path(font), "Chalk",
Rml::Style::FontStyle::Normal,
Rml::Style::FontWeight::Normal))
break;
if (!regular || !bold || !italic || !bold_italic)
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");
select_menu_ = std::make_unique<SelectMenu>(
*context_, *doc_, [this](float size) { return glyph("check", size); },
[this](const std::string &id, int, bool reselected) {
if (!reselected) return;
if (auto *control = element(id)) {
if ((id == "manager-country" || id == "manager-league") && scene_ == "manager")
entry_change(control, true);
else {
Rml::Dictionary parameters;
parameters["ui_select_reselected"] = true;
control->DispatchEvent("change", parameters);
}
}
});
select_capture_.handler = [this](Rml::Event &event) {
if (event.GetType() == "keydown") keyboard_navigation_ = true;
else if (event.GetType() == "mousedown") keyboard_navigation_ = false;
const bool was_open = select_menu_->is_open();
if (select_menu_->process_event(event)) {
event.StopImmediatePropagation();
dirty_ = true;
} else if (was_open != select_menu_->is_open()) dirty_ = true;
select_sync_keyboard();
};
for (const char *event : select_capture_events_)
doc_->AddEventListener(event, &select_capture_, true);
for (const char *event :
{"click", "dblclick", "change", "input", "keydown", "blur", "mousedown",
"mouseup", "mousemove", "contextmenu", "focus"})
doc_->AddEventListener(event, this, Rml::String(event) == "keydown" ||
Rml::String(event) == "blur" || Rml::String(event) == "focus");
try {
ui_preferences_loaded_=fs::exists(ui_preferences_file());
ui_preferences_=load_ui_preferences(ui_preferences_file());
} catch(const std::exception &) {
ui_preferences_error_="Die gespeicherten UI-Einstellungen konnten nicht geladen werden. Die Standardwerte werden verwendet.";
ui_preferences_=default_ui_preferences();ui_preferences_loaded_=false;
}
theme_=ui_preferences_.at("theme").get<std::string>();
if (!config_.theme.empty()) theme_ = config_.theme;
if (theme_ != "midnight" && theme_ != "silver" && theme_ != "matchday")
throw editor::Error("Unbekanntes Modern-Theme.");
front_external_override_=!config_.world.empty();
engine_mode_ = !config_.engine_save.empty();
if (!engine_mode_) collect_mods();
if(config_.world.empty() && config_.scene=="mods")scene_="mods";
if (!config_.world.empty() && !engine_mode_) {
active_mod_.clear();
load_world(config_.world);
scene_ = config_.scene;
if (scene_ != "main" && scene_ != "mods" && scene_ != "newgame" && scene_ != "manager" && scene_ != "managerhub" &&
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() && !ui_preferences_loaded_) {
ui_preferences_=legacy_ui_preferences(snap().state.at("preferences"));
theme_=ui_preferences_.at("theme").get<std::string>();
}
}
if (!config_.theme.empty()) {
// A capture/CLI override is visual only and never edits a career.
ui_preferences_["theme"]=theme_;
}
if (engine_mode_) {
if (config_.world.empty() || !config_.state.empty()) throw editor::Error("--ui-career benötigt --mod und unterstützt keine UI-Demostände.");
scene_ = "engine"; menu_ = config_.scene == "camp" ? "camp" : "";
const auto file = config_.world, save = config_.engine_save;
engine_start("Spielstand wird geladen …", [file, save] {
auto link = EngineBridge::open(file, save);
auto catalog = Catalog::open(file);
auto bundle = link->snapshot();
const auto &meta = bundle.at("desktop").at("meta");
std::string data_revision;
for (const auto *extension : {"x-diamond-modern", "x-world"})
if (catalog->manifest().contains(extension)) data_revision = catalog->manifest().at(extension).value("data_revision", "");
if (catalog->manifest().at("id").get<std::string>() != meta.at("worldId").get<std::string>() || data_revision != meta.at("worldRevision").get<std::string>())
throw editor::Error("Bildkatalog und Engine verwenden unterschiedliche Weltdaten.");
return EngineReply{link, std::move(bundle), Json::object(), std::move(catalog)};
});
} else opening_restore_startup();
if (scene_ == "manager" && selections_["manager-name"].empty())
selections_["manager-name"] = "Alex Berger";
doc_->Show();
resize();
render();
if (!ui_preferences_error_.empty()) message(ui_preferences_error_);
SDL_ShowWindow(video_.window);
frame();
} catch (...) {
shutdown();
throw;
}
}
void shutdown() {
if (engine_job_.valid()) engine_job_.wait();
engine_link_.reset();
select_capture_.handler = {};
if (doc_)
for (const char *event : select_capture_events_)
doc_->RemoveEventListener(event, &select_capture_, true);
select_menu_.reset();
select_sync_keyboard();
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_) {
front_poll();
if (engine_mode_) engine_poll();
opening_tick();
live_tick();
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) {
handle_event(event);
got = SDL_PollEvent(&event) != 0;
}
if (context_->GetNextUpdateDelay() <= 0)
dirty_ = true;
}
return 0;
}
};
#include "modern/ui/entry_controls.inc"
#include "modern/ui/national_screens.inc"
#include "modern/ui/national_controls.inc"
#include "modern/ui/career_screens.inc"
#include "modern/ui/career_controls.inc"
#include "modern/ui/entry_screens.inc"
#include "modern/ui/entry_opening_controls.inc"
#include "modern/ui/entry_opening_screens.inc"
#include "modern/ui/controls.inc"
#include "modern/ui/widgets_screens.inc"
#include "modern/ui/widgets_controls.inc"
#include "modern/ui/files_screens.inc"
#include "modern/ui/files_controls.inc"
#include "modern/ui/front_screens.inc"
#include "modern/ui/front_controls.inc"
#include "modern/ui/screens.inc"
#include "modern/ui/sports_screens.inc"
#include "modern/ui/calendar_screen.inc"
#include "modern/ui/report_pickers.inc"
#include "modern/ui/report_details.inc"
#include "modern/ui/reports_screens.inc"
#include "modern/ui/indoor_screen.inc"
#include "modern/ui/planning_screens.inc"
#include "modern/ui/planning_controls.inc"
#include "modern/ui/almanac_screens.inc"
#include "modern/ui/almanac_controls.inc"
#include "modern/ui/amount_entry.inc"
#include "modern/ui/bank_screens.inc"
#include "modern/ui/bank_controls.inc"
#include "modern/ui/finance_screens.inc"
#include "modern/ui/finance_controls.inc"
#include "modern/ui/contracts_screens.inc"
#include "modern/ui/contracts_controls.inc"
#include "modern/ui/environment_screens.inc"
#include "modern/ui/environment_controls.inc"
#include "modern/ui/advertising_screens.inc"
#include "modern/ui/advertising_controls.inc"
#include "modern/ui/toto_screens.inc"
#include "modern/ui/toto_controls.inc"
#include "modern/ui/nation_flags.inc"
#include "modern/ui/lineup_screens.inc"
#include "modern/ui/lineup_controls.inc"
#include "modern/ui/transfer_screens.inc"
#include "modern/ui/transfer_controls.inc"
#include "modern/ui/career_report_screens.inc"
#include "modern/ui/career_report_controls.inc"
#include "modern/ui/rankings_screens.inc"
#include "modern/ui/rankings_controls.inc"
#include "modern/ui/stadium_screens.inc"
#include "modern/ui/stadium_controls.inc"
#include "modern/ui/statistics_screens.inc"
#include "modern/ui/statistics_controls.inc"
#include "modern/ui/news_screens.inc"
#include "modern/ui/news_controls.inc"
#include "modern/ui/settings_screens.inc"
#include "modern/ui/settings_controls.inc"
#include "modern/ui/live_screens.inc"
#include "modern/ui/live_controls.inc"
#include "modern/ui/postmatch_screens.inc"
#include "modern/ui/postmatch_controls.inc"
#include "modern/ui/engine_screens.inc"
#include "modern/ui/engine_controls.inc"
#include "modern/ui/engine_lineup.inc"
#include "modern/ui/engine_sports.inc"
#include "modern/ui/engine_finance.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