Files
Dreierpack-Manager/src/modern/ui/view.cpp
T
MichaelandClaude Fable 5.2 3330dfb69c The seller decides on the bids for a player he listed
At the weekly deadline the original shows the seller the bids for a player
on the transfer list; without that screen every bid for a human seller was
declined, so a listed player could never be sold. session.advance now takes
transferOffers {playerId: {accept: index} | {action: "decline"}}: bids
without an answer take the run back and decision_pending carries them, as a
contract running out does. Only an interface that sends the field is asked,
so a client that does not know the question keeps the run it always had.

The notebook lists the bids with club, fee, salary and term; one is
accepted or all are declined, and the kickoff is sent again.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-16 14:54:48 +01:00

1866 lines
86 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/crest_contrast.hpp"
#include "modern/ui/engine_bridge.hpp"
#include "modern/ui/engine_live.hpp"
#include "modern/ui/news_catalog.hpp"
#include "modern/ui/career_files.hpp"
#include "modern/ui/live_match_info.hpp"
#include "modern/ui/date_text.hpp"
#include "modern/ui/tactic_text.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/stadium_scene.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 <RmlUi/Core/ElementText.h>
#include <cstring>
#include <tuple>
#include <utility>
#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 "Dreierpack Manager";
}
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};
}
// A picture computed by the program itself; `key` names its variant (e.g. the skin).
Picture texture(const std::string &slot, const std::string &key, const std::function<editor::images::Raster()> &make) {
const auto token = "modern-texture-" + slot + ".png";
auto found = entries_.find(token);
if (found == entries_.end() || found->second.key != key) {
if (const auto loaded = loaded_sources_.find(token); loaded != loaded_sources_.end()) {
Rml::ReleaseTexture(loaded->second, this);
loaded_sources_.erase(loaded);
}
auto raster = make();
entries_[token] = {key, false, raster.width, 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};
}
// A club's colour, read from its crest: the strongest hue among its opaque pixels, dark
// enough to carry white type. Empty when the crest has no colour to speak of.
std::string crest_colour(const std::string &key) {
const auto identity = "crest-colour:" + key;
if (const auto found = keys_.find(identity); found != keys_.end()) return found->second;
std::string colour;
const auto source = image(key, true);
if (!source.token.empty()) {
const auto &raster = entries_.at(source.token).raster;
std::array<double, 12> weight{}, red{}, green{}, blue{};
for (size_t i = 0; i + 3 < raster.pixels.size(); i += 4) {
const int r = raster.pixels[i], g = raster.pixels[i + 1], b = raster.pixels[i + 2], a = raster.pixels[i + 3];
const int high = std::max({r, g, b}), low = std::min({r, g, b});
if (a < 200 || high - low < 60 || high < 70) continue;
double hue = high == r ? double(g - b) / (high - low) : high == g ? 2 + double(b - r) / (high - low) : 4 + double(r - g) / (high - low);
if (hue < 0) hue += 6;
const size_t bucket = size_t(hue * 2) % 12;
const double w = double(high - low) / 255;
weight[bucket] += w; red[bucket] += r * w; green[bucket] += g * w; blue[bucket] += b * w;
}
const size_t best = size_t(std::max_element(weight.begin(), weight.end()) - weight.begin());
if (weight[best] > 40) {
double r = red[best] / weight[best], g = green[best] / weight[best], b = blue[best] / weight[best];
// white type needs a dark ground
const double light = (.299 * r + .587 * g + .114 * b) / 255;
if (light > .46) { const double f = .46 / light; r *= f; g *= f; b *= f; }
char text[8];
std::snprintf(text, sizeof text, "#%02x%02x%02x", int(r), int(g), int(b));
colour = text;
}
}
keys_[identity] = colour;
return colour;
}
Picture crest(const std::string &key, bool light_surface) {
const auto source = image(key, true);
if (!light_surface || source.token.empty()) return source;
const auto identity = "light-crest:" + source.token;
auto found = keys_.find(identity);
if (found == keys_.end()) {
auto variant = crest_for_light_surface(entries_.at(source.token).raster);
auto token = source.token;
if (variant) {
token = "modern-image-" + std::to_string(serial_++) + ".png";
entries_[token] = {key, true, 512, std::move(*variant)};
}
// Also cache the decision to keep a coloured/original texture. Theme
// changes reuse both variants; world() invalidates them together.
found = keys_.emplace(identity, token).first;
}
const auto &raster = entries_.at(found->second).raster;
return {found->second, raster.width, raster.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;
bool desk_top_ = false;
// A menu window (2720 x 2040 at the middle of the stage) is shown as large as the screen
// allows; the desk behind it is cropped. Without a window the whole stage is fitted.
bool window_zoom_ = false;
bool entry_stage_ = false; // the stage shows the table of the entry: it fills the window
std::string scene_ = "main", menu_, theme_ = "silver", 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 ticket_engine_bound_ = false;
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;
// the offered value is still as it was opened: the first digit key replaces it
bool amount_untouched_ = false;
std::string bank_view_ = "credit", bank_hint_; // the page of the bank that is open
Json bank_players() const;
static std::string bank_view_of(const std::string &route);
int bank_property_ = 0, bank_owned_ = 0, bank_stock_ = 11;
bool balance_future_ = false;
// the balance sheet's what-if calculation (finance_simulation.inc)
bool balance_sim_ = false;
int balance_sim_price_ = 0, balance_sim_crowd_ = 0, balance_sim_matches_ = 17;
std::string balance_simulation_result();
std::string render_balance_simulation();
bool balance_simulation_event(Rml::Event &);
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;
std::string advertising_page_ = "advertising"; // or "investments": the second page of the menu
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();
// the stadium's card model: what the camera looks at ("" the whole ground, "stadium", or a
// part such as "block:3"), and its flight from one focus to the next
std::string stadium_focus_;
// how each view of the model is looked at: zoom and the place of the picture's corner
std::map<std::string, std::array<double, 3>> stadium_cams_;
Json stadium_drag_; // the pointer while the view is dragged
bool stadium_dragged_ = false; // the next click only ends a drag
std::string stadium_tip_, stadium_hover_; // what the pointer is on
std::array<double, 2> stadium_tip_at_{}; // where its name is shown, in units of the page
std::vector<stadium_scene::Hot> stadium_hots_; // the parts of the view that is shown
std::array<double, 3> stadium_cam(bool outer);
// the flight of the camera from one view of the model to the other: where it started,
// where it is, where it lands; `stadium_seen_` is the view that was drawn last
std::array<double, 3> stadium_from_{}, stadium_now_{}, stadium_to_{};
bool stadium_flying_ = false;
uint64_t stadium_flight_start_ = 0;
std::string stadium_seen_;
void stadium_flight_tick();
std::string stadium_cam_style(const std::array<double, 3> &cam);
bool stadium_stage_event(Rml::Event &);
std::string render_stadium_data();
bool stadium_focus_action(const std::string &, Rml::Element *);
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";
std::string popup_body_; // markup under the question, for a question that lists things
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;
std::string window_shown_ = "\x01"; // the menu whose window is on screen (window())
#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/engine_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);
}
// the theme, and "calm" when the player asked for reduced motion
std::string body_classes() const {
return theme_ + (ui_preferences_.is_object() && ui_preferences_.contains("display") &&
ui_preferences_.at("display").value("motion", "full") == "reduced" ? " calm" : "");
}
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 ? picture(renderer_.crest(c->value("crest", ""), theme_ == "silver"), size, size) : "";
}
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>"
: "";
}
// A sheet may carry a faint picture of its subject under its content: the data set's
// "art.paper-<motif>.png" for the menu, else its general one. The paper's own tone and
// gradient stay on top of the picture's; without such pictures the sheet is plain.
std::string window_art() {
static const std::map<std::string, std::string> motifs{
{"stadium", "seats"}, {"advertising", "boards"}, {"calendar", "bench"}, {"postpone", "bench"}, {"friendlies", "bench"}, {"camp", "training"},
{"almanac", "trophies"}, {"achievements", "trophies"}, {"highscore", "trophies"}, {"news", "press"}, {"newplayer", "press"}, {"settings", "press"}, {"environment", "fans"}, {"training", "training"}, {"camps", "training"},
{"lineup", "bench"}, {"tactics", "bench"}, {"squad", "locker"}, {"contracts", "locker"}, {"transfer", "press"},
{"tables", "stand"}, {"league", "stand"}, {"other", "stand"}, {"strengths", "stand"}, {"statistics", "kickoff"},
{"scorers", "kickoff"}, {"fairplay", "kickoff"}};
if (theme_ != "silver" || notebook_page()) return {};
const auto found = motifs.find(menu_);
for (const std::string motif : {found == motifs.end() ? std::string("ball") : found->second, std::string("ball")}) {
const auto key = "art.paper-" + motif + ".png";
const auto art = renderer_.image(key, false, 2048);
if (art.token.empty() || art.width <= 0 || art.height <= 0) continue;
return "<div class=\"window-art\">" + picture(art, 2720, 1932, true) + "</div>";
}
return {};
}
std::string window(const std::string &heading, const std::string &content,
bool close = true) {
// a sheet of paper on two more; it slides in once when its menu opens, not on every redraw
const std::string arriving = window_shown_ == menu_ ? "" : " window-in";
window_shown_ = menu_;
// the head of every sheet carries the manager's club: its crest at the right, its colour
// as the rule under the title
std::string club_rule, club_mark;
try {
std::string own;
if (engine_mode_) own = engine_data_.at("desktop").at("meta").at("scope").at("teamId").get<std::string>();
else if (world_ && source_ && snap().state.at("career").value("role", "club") == "club") own = manager(snap()).value("club", "");
if (const auto *club = world_ && !own.empty() ? world_->find("clubs", own) : nullptr; club && !club->value("crest", "").empty()) {
if (const auto colour = renderer_.crest_colour(club->value("crest", "")); !colour.empty()) club_rule = " style=\"border-bottom:6dp " + colour + ";\"";
club_mark = "<div class=\"titlebar-club\">" + crest(club, 68) + "</div>";
}
} catch (const std::exception &) {
}
// on a page of the notebook the sheet has no frame of its own and lies where the book lies
const bool page = notebook_page();
if (page) club_mark.clear();
return (page ? "<div class=\"nb-sheet-layer\" style=\"top:" + scalar(notebook_top()) + "dp;\"><div class=\"window nb-sheet" + std::string(page_native() ? " pg-root" : "") + arriving + "\"><div class=\"titlebar\">"
: "<div class=\"sheet-under first" + arriving + "\"></div><div class=\"sheet-under second" + arriving + "\"></div><div class=\"window" + arriving + "\"><div class=\"titlebar\"" + club_rule + ">") +
(close ? btn("close", "<span>×</span>", "close", "id=\"window-close\" aria-label=\"" + std::string("Fenster schließen") + "\"")
: "<span style=\"width:76dp;\"></span>") +
"<h1>" + esc(heading) + "</h1>" + club_mark + "</div>" + window_art() + "<div class=\"content\">" +
content + "</div>" + (amount_ ? render_amount() : "") + "</div>" + (page ? "</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_body_.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();
ticket_engine_bound_ = false;
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_focus_.clear(); stadium_drag_ = Json();
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_ = "credit";
bank_hint_.clear();
balance_future_ = false;
balance_sim_ = 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();
// the career's calendar: -1 the twelve months, else the opened month (calendar_year.inc)
int calendar_month_ = -1, calendar_from_ = 0;
std::string calendar_anim_;
std::string render_calendar_year();
// the career's notebook (notebook.inc)
double notebook_top() const;
std::string notebook_section_of(const std::string &route) const;
std::string notebook_shell(const std::function<bool(const std::string &)> &enabled, const std::string &head);
Picture notebook_art();
// the home page (notebook_home.inc)
std::string notebook_crest(const Json &team, double size);
std::string notebook_chart(const std::string &slot, const std::vector<std::pair<std::vector<int>, std::string>> &series, double w, double h);
std::string notebook_card(const std::string &type, int cols, int rows, const Json &model, std::string &look);
Json &notebook_pages();
void notebook_pages_changed();
void notebook_home_do(const std::string &command);
bool notebook_home_event(Rml::Event &event);
// the home pages and their cards; an open menu, a page being named, a card being dragged
Json home_, home_menu_, home_drag_, home_model_;
int home_page_ = 0, home_rename_ = -1;
bool home_swallow_click_ = false;
std::string notebook_home(const Json &model);
Json notebook_news();
static Json notebook_lamps(Json lamps);
// the building blocks of a notebook page (pages.inc)
bool page_native() const;
static std::string pg(double units);
static std::string pg_css(std::string_view css);
// the entry into the game: one pad on a table (front_screens.inc)
static constexpr double kEntryUnit = 2.29665;
static std::string es(double units);
std::string entry_stage(const std::string &paper, const std::string &over = {});
std::string entry_sheet(const std::string &kicker, const std::string &title, const std::string &body, const std::string &foot, const std::string &right = {});
std::string entry_pad(const std::string &kicker, const std::string &title, const std::string &body, const std::string &foot, const std::string &right = {}, const std::string &over = {});
std::string render_files_pad();
static std::string pg_upper(const std::string &text);
static std::string pg_kicker(const std::string &text, const std::string &css = {});
static std::string pg_stat(const std::string &label, const std::string &value, const std::string &sub = {});
static std::string pg_bar(double percent, const std::string &kind = {});
static std::string pg_dots(int on, int of);
static std::string pg_pos(const std::string &code);
static std::string pg_form(const std::string &marks);
static std::string pg_status(const std::string &text);
static std::string pg_button(const std::string &action, const std::string &label, const std::string &css = {}, const std::string &attrs = {});
static std::string pg_th(const std::string &label, double width, const std::string &align = {}, const std::string &sort_action = {}, const std::string &attrs = {}, int sorted = 0);
static std::string pg_td(const std::string &html, double width, const std::string &align = {}, bool cell = false);
static std::string pg_dialog(const std::string &title, const std::string &sub, const std::string &body, const std::string &actions, double width, const std::string &attrs = {});
std::string pg_club(const std::string &id, double size = 50, bool reverse = false);
void notebook_finish(std::string &markup);
std::string render_lineup_page(); // lineup_page.inc
// postponing and friendlies (planning_page.inc)
std::string page_months(const Json &calendar, bool booking, bool postpone, const std::set<int> &movable);
static std::string page_steps(const std::string &first, const std::string &second, bool at_second);
// the tactics sketch (tactics_page.inc): what is being dragged on it
bool tactics_page_event(Rml::Event &event);
Json tactic_drag_;
// what the page says in the heading of the sheet instead of its plain name, and after it
std::string page_title_, page_hint_;
// a career menu is a page of the notebook, not a window of its own
// the manager's page is a scene of its own; for the book it is the page "newplayer"
std::string notebook_menu() const { return scene_ == "managerhub" ? std::string("newplayer") : menu_; }
bool notebook_page() const { return (scene_ == "desktop" || scene_ == "engine" || scene_ == "managerhub") && !notebook_menu().empty(); }
bool calendar_month_action(const std::string &, Rml::Element *);
void calendar_open_month(int);
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 *);
bool almanac_layout_update();
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;
std::string career_hint_; // the scene of the manager's picture the pointer is on
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 #1b3329)");
}
}
// Called after the stage was rebuilt: zoom in when it now shows a menu window.
void sync_window_zoom() {
// a page of the notebook is no window: the book keeps the whole stage
const bool wanted = (doc_->QuerySelector(".window") != nullptr && doc_->QuerySelector(".nb-sheet") == nullptr) || doc_->QuerySelector(".live-stage") != nullptr;
if (!wanted) window_shown_ = "\x01";
// the career's desk hangs from the top edge of a taller screen, so its bar is the
// screen's bar and the spare height shows the stadium below
const bool entry = doc_->QuerySelector(".es-stage") != nullptr;
const bool desk = !wanted && !entry && (scene_ == "engine" || scene_ == "desktop" || scene_ == "managerhub");
if (wanted == window_zoom_ && desk == desk_top_ && entry == entry_stage_) return;
entry_stage_ = entry;
window_zoom_ = wanted;
desk_top_ = desk;
resize();
}
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);
if (window_zoom_) scale_ = std::max(scale_, std::min(double(pw) / 2760, double(ph) / 2080));
// the table of the entry fills the window; its pad (930 x 690 units about the middle) stays whole
if (entry_stage_) scale_ = std::min({std::max(double(pw) / 3840, double(ph) / 2160), double(pw) / (930 * kEntryUnit), double(ph) / (690 * kEntryUnit)});
canvas_left_ = (pw - 3840 * scale_) / 2;
canvas_top_ = (ph - 2160 * scale_) / 2;
if (desk_top_ && canvas_top_ > 0) canvas_top_ = 0;
// a career's desk is as high as the screen shows of it; menus keep their 16:9 stage
const bool desk_scene = !entry_stage_ && (scene_ == "engine" || scene_ == "desktop" || scene_ == "managerhub");
const double fitted = std::min(double(pw) / 3840, double(ph) / 2160);
const int stage_height = desk_scene ? std::clamp(int(ph / fitted), 2160, 2880) : 2160;
if (stage_height != desktop_height()) {
set_desktop_height(stage_height);
needs_render_ = true;
}
element("canvas")->SetProperty("height", std::to_string(stage_height) + "dp");
if (desk_scene && desktop_.is_object() && desktop_.contains("objects")) {
const bool clean = desktop_ == saved_desktop_;
if (fit_desktop(desktop_)) {
if (clean) saved_desktop_ = desktop_;
needs_render_ = true;
}
}
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(body_classes());
std::string markup;
// from the main menu the saves and the sound are written on the pad as well
const bool pad_menu = scene_ == "main" && (menu_ == "load" || menu_ == "settings");
if (pad_menu)
markup = menu_ == "load" ? render_files(false, false) : render_settings();
else 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_ == "managerhub")
markup = render_desktop()+"<div class=\"fill menu-layer\" style=\"z-index:100;\">"+render_career()+"</div>";
else if (scene_ == "opening")
markup = render_opening();
else if (scene_ == "live")
markup = render_live();
else if (source_)
markup = render_desktop();
if (!menu_.empty() && !pad_menu)
markup += render_menu(menu_);
setting_menu_markup_ = true;
notebook_finish(markup);
element("canvas")->SetInnerRML(markup);
needs_render_ = false;
++document_generation_;
sync_window_zoom();
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_=="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)");
// (a stage that changed its height while this was drawn asks for one more drawing)
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>" + std::string(confirm_ || text_accept_ ? "Rückfrage" : "Hinweis") + "</h2><p>" +
esc(popup_) + "</p>" + popup_body_ +
(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.
changed |= almanac_layout_update();
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() {
engine_create_poll();
engine_files_poll();
stadium_flight_tick();
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);
// The display serif for headings and names, and the chalk hand of the tactics board;
// both ship with the game. Without the files the text falls back to the system fonts below.
const auto own = assets_ / "fonts";
bool display = fs::exists(own / "SourceSerif4-Regular.ttf") &&
Rml::LoadFontFace(rml::asset_path(own / "SourceSerif4-Regular.ttf"), "Display", Rml::Style::FontStyle::Normal, Rml::Style::FontWeight::Normal);
if (display && fs::exists(own / "SourceSerif4-Semibold.ttf"))
Rml::LoadFontFace(rml::asset_path(own / "SourceSerif4-Semibold.ttf"), "Display", Rml::Style::FontStyle::Normal, Rml::Style::FontWeight::Bold);
bool chalk = fs::exists(own / "CabinSketch-Regular.ttf") &&
Rml::LoadFontFace(rml::asset_path(own / "CabinSketch-Regular.ttf"), "Chalk", Rml::Style::FontStyle::Normal, Rml::Style::FontWeight::Normal);
if (chalk && fs::exists(own / "CabinSketch-Bold.ttf"))
Rml::LoadFontFace(rml::asset_path(own / "CabinSketch-Bold.ttf"), "Chalk", Rml::Style::FontStyle::Normal, Rml::Style::FontWeight::Bold);
// the pencil hand of the tactics sketch; without its files the chalk hand writes there
bool pencil = fs::exists(own / "Caveat-Regular.ttf") &&
Rml::LoadFontFace(rml::asset_path(own / "Caveat-Regular.ttf"), "Pencil", Rml::Style::FontStyle::Normal, Rml::Style::FontWeight::Normal);
if (pencil && fs::exists(own / "Caveat-Bold.ttf"))
Rml::LoadFontFace(rml::asset_path(own / "Caveat-Bold.ttf"), "Pencil", Rml::Style::FontStyle::Normal, Rml::Style::FontWeight::Bold);
if (!pencil && chalk) {
Rml::LoadFontFace(rml::asset_path(own / "CabinSketch-Regular.ttf"), "Pencil", Rml::Style::FontStyle::Normal, Rml::Style::FontWeight::Normal);
if (fs::exists(own / "CabinSketch-Bold.ttf")) Rml::LoadFontFace(rml::asset_path(own / "CabinSketch-Bold.ttf"), "Pencil", Rml::Style::FontStyle::Normal, Rml::Style::FontWeight::Bold);
}
if (!display) {
std::vector<fs::path> serif;
#ifdef _WIN32
if (const char *windir = std::getenv("WINDIR")) serif = {fs::path(windir) / "Fonts" / "georgia.ttf", fs::path(windir) / "Fonts" / "times.ttf"};
#elif defined(__APPLE__)
serif = {"/System/Library/Fonts/Supplemental/Georgia.ttf", "/System/Library/Fonts/NewYork.ttf", "/System/Library/Fonts/Times.ttc"};
#else
serif = {"/usr/share/fonts/truetype/liberation2/LiberationSerif-Regular.ttf", "/usr/share/fonts/truetype/liberation/LiberationSerif-Regular.ttf"};
#endif
serif.push_back(assets_ / "LatoLatin-Regular.ttf");
for (const auto &font : serif)
if (fs::exists(font) && Rml::LoadFontFace(rml::asset_path(font), "Display", Rml::Style::FontStyle::Normal, Rml::Style::FontWeight::Normal)) break;
}
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");
if (!chalk)
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_, assets_ / "art"),
video_("Dreierpack Manager", 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", "mousescroll"})
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 if(config_.preview_only) 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();
engine_create_poll();
engine_files_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"
#include "modern/ui/engine_commerce.inc"
#include "modern/ui/engine_contracts.inc"
#include "modern/ui/engine_calendar.inc"
#include "modern/ui/engine_friendlies.inc"
#include "modern/ui/engine_almanac.inc"
#include "modern/ui/engine_reports.inc"
#include "modern/ui/calendar_year.inc"
#include "modern/ui/notebook.inc"
#include "modern/ui/notebook_home.inc"
#include "modern/ui/pages.inc"
#include "modern/ui/tactics_page.inc"
#include "modern/ui/planning_page.inc"
#include "modern/ui/lineup_page.inc"
#include "modern/ui/finance_simulation.inc"
#include "modern/ui/statistics_analysis.inc"
#include "modern/ui/engine_rankings.inc"
#include "modern/ui/engine_creation.inc"
#include "modern/ui/engine_files.inc"
#include "modern/ui/engine_statistics.inc"
#include "modern/ui/engine_toto.inc"
#include "modern/ui/engine_stadium.inc"
#include "modern/ui/engine_transfer.inc"
#include "modern/ui/engine_achievements.inc"
#include "modern/ui/engine_news.inc"
#include "modern/ui/engine_balance.inc"
#include "modern/ui/engine_widgets.inc"
#include "modern/ui/engine_indoor.inc"
#include "modern/ui/engine_settings.inc"
#include "modern/ui/engine_managers.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