Center native controls and preserve dropdown editing and focus (by Codex)

This commit is contained in:
Codex committed 2026-10-23 19:43:15 +02:00
1 parent 11a6356c1e
commit 42b728d4ea
14 files changed
+541 -64

No files matched your search

+13 -2
View File
@@ -6,7 +6,7 @@ add_library(bmh_modern_ui STATIC view.cpp ticket_popover.cpp)
target_link_libraries(bmh_modern_ui PUBLIC bmh_modern_ui_core PRIVATE bmh_rmlui bmh_launcher nfd::nfd ${BMH_SDL_TARGET})
if(MSVC)
target_compile_options(bmh_modern_ui_core PRIVATE /W4 /utf-8)
target_compile_options(bmh_modern_ui PRIVATE /W4 /utf-8)
target_compile_options(bmh_modern_ui PRIVATE /W4 /utf-8 /bigobj)
else()
target_compile_options(bmh_modern_ui_core PRIVATE -Wall -Wextra -Wpedantic)
target_compile_options(bmh_modern_ui PRIVATE -Wall -Wextra -Wpedantic)
@@ -17,7 +17,12 @@ file(MAKE_DIRECTORY "${modern_assets}")
foreach(asset modern.rml theme.rcss ticket.rcss)
configure_file("${CMAKE_SOURCE_DIR}/assets/modern/${asset}" "${modern_assets}/${asset}" COPYONLY)
endforeach()
file(COPY "${CMAKE_SOURCE_DIR}/assets/modern/icons" DESTINATION "${modern_assets}")
file(GLOB modern_icons CONFIGURE_DEPENDS "${CMAKE_SOURCE_DIR}/assets/modern/icons/*.svg")
file(MAKE_DIRECTORY "${modern_assets}/icons")
foreach(icon ${modern_icons})
get_filename_component(icon_name "${icon}" NAME)
configure_file("${icon}" "${modern_assets}/icons/${icon_name}" COPYONLY)
endforeach()
foreach(weight Regular Bold)
configure_file("${rmlui_SOURCE_DIR}/Samples/assets/LatoLatin-${weight}.ttf"
"${modern_assets}/LatoLatin-${weight}.ttf" COPYONLY)
@@ -44,3 +49,9 @@ endif()
foreach(theme midnight silver matchday)
add_test(NAME modern_ticket_${theme} COMMAND modern_ticket_document_tests "${modern_assets}" ${theme})
endforeach()
add_executable(modern_control_layout_tests ../../../tests/modern_control_layout_tests.cpp)
target_link_libraries(modern_control_layout_tests PRIVATE bmh_modern_ui_core RmlUi::Core)
if(MSVC)
target_compile_options(modern_control_layout_tests PRIVATE /utf-8)
endif()
add_test(NAME modern_control_layout_tests COMMAND modern_control_layout_tests "${modern_assets}")
+59
View File
@@ -0,0 +1,59 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "modern/ui/catalog.hpp"
#include <RmlUi/Core.h>
#include <cmath>
namespace bmh::modern_ui {
inline Rml::Element *select_part(Rml::Element &select, const std::string &tag) {
// WidgetDropDown appends these as non-DOM children. QuerySelector excludes
// them.
for (int i = 0; i < select.GetNumChildren(true); ++i)
if (auto *child = select.GetChild(i); child->GetTagName() == tag)
return child;
return nullptr;
}
inline std::string button_markup(const std::string &action,
const std::string &label,
const std::string &css = {},
const std::string &attributes = {}) {
// RmlUI needs an explicit flex item for text; anonymous text disappears.
const bool plain = label.find('<') == std::string::npos;
return "<button data-action=\"" + editor::escaped(action) + "\" class=\"" +
css + (plain ? " control-button" : "") + "\" " + attributes + ">" +
(plain ? "<span class=\"control-label\">" + label + "</span>"
: label) +
"</button>";
}
inline bool center_selects(Rml::ElementDocument &document) {
bool changed = false;
Rml::ElementList controls;
document.QuerySelectorAll(controls, "select");
const auto set_pixels = [&](Rml::Element *element, const char *name,
float value) {
const auto *old = element->GetLocalProperty(name);
if (old && old->unit == Rml::Unit::PX &&
std::abs(old->Get<float>() - value) < .02f)
return;
element->SetProperty(name, std::to_string(value) + "px");
changed = true;
};
for (auto *select : controls) {
if (!select->IsVisible(true))
continue;
auto *caption = select_part(*select, "selectvalue"),
*arrow = select_part(*select, "selectarrow");
const float height = select->GetBox().GetSize(Rml::BoxArea::Content).y;
if (height <= 0 || !caption || !arrow)
continue;
// WidgetDropDown fixes both offsets at the content-box top. A flex
// selectvalue loses its text in pinned RmlUI; center its line instead.
set_pixels(caption, "line-height", height);
set_pixels(arrow, "margin-top",
std::max(0.f, (height -
arrow->GetBox().GetSize(Rml::BoxArea::Border).y) /
2));
}
return changed;
}
} // namespace bmh::modern_ui
+68 -31
View File
@@ -196,6 +196,18 @@ void App::ProcessEvent(Rml::Event &event) try {
}
}
if (key == Rml::Input::KI_ESCAPE) {
Rml::ElementList selects;
doc_->QuerySelectorAll(selects, "select");
for (auto *node : selects)
if (auto *select = dynamic_cast<Rml::ElementFormControlSelect *>(node);
select && select->IsSelectBoxVisible()) {
select->CancelSelectBox();
select->Focus(true);
event.StopImmediatePropagation();
dirty_ = true;
return;
}
if (context_open_) {
context_open_ = false;
dirty_ = true;
@@ -615,32 +627,39 @@ void App::dispatch(const std::string &action, Rml::Element *target) {
message("Die Dateiauswahl konnte nicht geöffnet werden.");
return;
}
try {
auto candidate = Catalog::open(editor::path(chosen.get()));
std::string name = candidate->title();
launch::ModLibrary::validate_name(name);
const auto destination = root_ / "mods" / editor::path(name);
if (fs::exists(destination))
throw std::runtime_error(
"Eine Mod mit diesem Namen ist bereits vorhanden.");
fs::create_directories(destination.parent_path());
const auto staging = destination.parent_path() /
(".ui-import-" + std::to_string(SDL_GetTicks64()));
fs::create_directory(staging);
try {
fs::copy_file(editor::path(chosen.get()), staging / "content.obw");
(void)Catalog::open(staging / "content.obw");
fs::rename(staging, destination);
} catch (...) {
fs::remove_all(staging);
throw;
}
collect_mods();
selected_mod_ = name;
refresh();
} catch (const std::exception &e) {
message(e.what());
}
const auto file = editor::path(chosen.get());
auto candidate = Catalog::open(file);
auto initial = candidate->title();
for (char &c : initial)
if (std::string("/\\:*?\"<>|").find(c) != std::string::npos)
c = '-';
if (initial.empty())
initial = "Modern";
text_dialog("Bezeichnung der neuen Mod", initial,
[this, file](const std::string &name) {
launch::ModLibrary::validate_name(name);
const auto destination = root_ / "mods" / editor::path(name);
if (fs::exists(destination))
throw editor::Error(
"Eine Mod mit diesem Namen ist bereits vorhanden.");
fs::create_directories(destination.parent_path());
const auto staging =
destination.parent_path() /
(".ui-import-" + std::to_string(SDL_GetTicks64()));
if (!fs::create_directory(staging))
throw editor::Error("Import wird bereits vorbereitet.");
try {
fs::copy_file(file, staging / "content.obw");
(void)Catalog::open(staging / "content.obw");
fs::rename(staging, destination);
} catch (...) {
fs::remove_all(staging);
throw;
}
collect_mods();
selected_mod_ = name;
refresh();
});
return;
}
if (action == "import-classic") {
@@ -660,11 +679,16 @@ void App::dispatch(const std::string &action, Rml::Element *target) {
request.name = game.family == launch::GameFamily::english ? "FTDL-classic"
: "BMH-classic";
request.migrate = false;
launch::ModLibrary library(root_);
library.add(request, migrate_);
collect_mods();
selected_mod_ = request.name;
refresh();
text_dialog("Bezeichnung der neuen Mod", request.name,
[this, request](const std::string &name) mutable {
launch::ModLibrary::validate_name(name);
request.name = name;
launch::ModLibrary library(root_);
library.add(request, migrate_);
collect_mods();
selected_mod_ = name;
refresh();
});
} catch (const std::exception &e) {
message(e.what());
}
@@ -1032,6 +1056,19 @@ void App::change(Rml::Element *target) {
if (!control)
return;
const auto value = control->GetValue();
if (auto *select = dynamic_cast<Rml::ElementFormControlSelect *>(target);
select && select->IsSelectBoxVisible()) {
pending_selects_.insert(target->GetId());
return;
}
if ((kind == "manager-country" || kind == "table-country") &&
value == country_)
return;
if ((kind == "manager-league" || kind == "table-league") && value == league_)
return;
if (kind == "manager-country" || kind == "manager-league" ||
kind == "table-country" || kind == "table-league")
focus_after_render_ = target->GetId();
if (kind == "manager-country" || kind == "manager-league") {
if (!manager_picker_)
selections_["manager-name"] = field("manager-name");
+25 -4
View File
@@ -34,7 +34,12 @@ std::string App::widget(const std::string &id, const Json &o) {
"style=\"font-size:240dp;line-height:1.1;\">" +
std::to_string(std::stoi(day)) + "</p><p class=\"small\">" +
esc(date) + "</p></div>" +
btn("open:calendar", "Kalender öffnen ↗", "card-button",
btn("open:calendar",
glyph("calendar", 32) +
"<span>Kalender öffnen</span><span "
"class=\"calendar-arrow\">" +
glyph("arrow-diagonal", 30) + "</span>",
"card-button calendar-link",
"style=\"left:0;bottom:0;width:100%;height:90dp;border-top:2dp "
"var(--border);font-size:25dp;color:var(--muted);\"");
}
@@ -203,10 +208,25 @@ std::string App::render_desktop() {
"</div>";
else {
const auto route = id.substr(4);
const std::array<std::string, 31> colors = {
"#3d789b", "#375a83", "#477c73", "#42846b", "#a58a49", "#586ba0",
"#517d71", "#668a98", "#af6860", "#6b809c", "#657cb3", "#507b9c",
"#559b76", "#a7474e", "#967d50", "#648f91", "#54856b", "#558f93",
"#6379a3", "#788598", "#8d7856", "#a66d64", "#748474", "#6887a2",
"#6b9270", "#7c8b9c", "#ac8b52", "#7783a4", "#648f83", "#927d9d",
"#ac5e63"};
const auto i = std::find(routes.begin(), routes.end(), route);
const auto color = colors[size_t(i - routes.begin())];
const auto top = theme_ == "matchday" ? mixed_color(color, "#27282e", .55)
: mixed_color(color, "#c5ddf1", .1);
const auto bottom =
theme_ == "matchday" ? "#272a30" : mixed_color(color, "#07111e", .38);
out += "<button id=\"object-" + esc(id) + "\" data-object=\"" + esc(id) +
"\" data-action=\"open:" + route +
"\" class=\"desktop-app\" style=\"" + style +
"\"><div class=\"app-tile\">" +
"\"><div class=\"app-tile\" "
"style=\"decorator:linear-gradient(140deg," +
top + "," + bottom + ");\">" +
img("button." + route, 146, 146, false, false, 256) +
"</div><span class=\"app-name\">" + esc(title(route)) + "</span>" +
(o.value("pinned", true) ? "<div class=\"pin-dot\"></div>" : "") +
@@ -649,7 +669,7 @@ std::string App::render_table(bool strengths, bool indoor) {
"</div>";
if (strengths) {
const auto players = world_->squad(c->value("id", ""));
for (const auto &position : {"gk", "df", "mf", "fw", "all"}) {
for (const auto &position : {"gk", "def", "mid", "fwd", "all"}) {
int sum = 0, n = 0;
for (auto *p : players) {
const auto positions = p->value("positions", Json::array());
@@ -799,7 +819,8 @@ std::string App::render_settings() {
settings_category_ == key ? "primary" : "",
"data-id=\"" + key +
"\" "
"style=\"display:block;width:100%;height:100dp;margin-"
"style=\"display:flex;justify-content:flex-start;width:100%;"
"height:100dp;margin-"
"bottom:14dp;text-align:left;\"");
}
std::string pane = "<h2>" +
+74 -13
View File
@@ -5,6 +5,7 @@
#include "launch/process.hpp"
#include "launch/rml_path.hpp"
#include "launch/rml_video.hpp"
#include "modern/ui/controls.hpp"
#include "modern/ui/desktop.hpp"
#include "modern/ui/gui_assets.hpp"
#include "modern/ui/model.hpp"
@@ -12,6 +13,7 @@
#include "version.hpp"
#include <RmlUi/Core.h>
#include <RmlUi/Core/Elements/ElementFormControl.h>
#include <RmlUi/Core/Elements/ElementFormControlSelect.h>
#include <RmlUi_Platform_SDL.h>
#include <SDL.h>
#include <algorithm>
@@ -32,14 +34,24 @@ std::string scalar(double n) {
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 data-action=\"" + esc(action) + "\" class=\"" + css + "\" " +
attrs + ">" + label + "</button>";
return button_markup(action, label, css, attrs);
}
const std::array<std::string, 31> routes = {
"tables", "league", "strengths", "lineup", "achievements",
@@ -84,6 +96,14 @@ 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")
@@ -149,13 +169,22 @@ public:
return {};
raster = editor::images::decode(bytes.first, bytes.second, pixels);
} else if (key.starts_with("icon.")) {
const auto name = key.substr(5);
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 {};
raster = editor::images::decode(
editor::read_file(assets_ / "icons" / (name + ".svg")), ".svg",
pixels);
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 (gui_.contains(key))
raster = gui_.decode(key, pixels);
else if (key == "background")
@@ -244,6 +273,8 @@ class App final : public Rml::EventListener {
std::unique_ptr<DemoSource> source_;
std::unique_ptr<TicketPopover> ticket_;
bool focus_ticket_ = false;
std::set<std::string> pending_selects_;
std::string focus_after_render_;
float device_ratio_ = 1.f;
Json desktop_ = Json::object(), saved_desktop_ = Json::object(),
options_ = Json::object();
@@ -334,7 +365,8 @@ class App final : public Rml::EventListener {
return c ? img(c->value("crest", ""), size, size, true) : "";
}
std::string glyph(const std::string &name, double size) {
return img("icon." + name, size, size, false, false, int(size));
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>" +
@@ -466,7 +498,9 @@ class App final : public Rml::EventListener {
{"exit", "Beenden"}}};
for (const auto &[key, name] : actions)
out += btn(
key, esc(name) + (key == "network" ? "<small>Demnächst</small>" : ""),
key,
(key == "network" ? "<span>" + esc(name) + "</span>" : esc(name)) +
(key == "network" ? "<small>Demnächst</small>" : ""),
{},
key == "network" || (key == "new" && !m && !world_) ? "disabled"
: "");
@@ -534,6 +568,19 @@ class App final : public Rml::EventListener {
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))
change(select);
}
}
void input(Rml::Element *);
void resize() {
int w, h, pw, ph;
@@ -594,6 +641,11 @@ class App final : public Rml::EventListener {
n->Focus();
focus_ticket_ = false;
}
if (!focus_after_render_.empty()) {
if (auto *node = element(focus_after_render_))
node->Focus(true);
focus_after_render_.clear();
}
}
void render_popup() {
if (popup_.empty()) {
@@ -626,6 +678,7 @@ class App final : public Rml::EventListener {
button->Focus();
}
void frame() {
flush_selects();
if (ticket_)
ticket_->update();
if (needs_render_)
@@ -633,6 +686,8 @@ class App final : public Rml::EventListener {
render_popup();
render_context();
context_->Update();
if (center_selects(*doc_))
context_->Update();
renderer_.Clear();
renderer_.BeginFrame();
context_->Render();
@@ -728,12 +783,15 @@ public:
{"click", "dblclick", "change", "input", "keydown", "mousedown",
"mouseup", "mousemove", "contextmenu"})
doc_->AddEventListener(event, this);
if(!config_.theme.empty())theme_ = config_.theme;
if(theme_!="midnight"&&theme_!="silver"&&theme_!="matchday")throw editor::Error("Unbekanntes Modern-Theme.");
if (!config_.theme.empty())
theme_ = config_.theme;
if (theme_ != "midnight" && theme_ != "silver" && theme_ != "matchday")
throw editor::Error("Unbekanntes Modern-Theme.");
collect_mods();
if (!mods_.empty())
active_mod_ = mods_.front().name;
if (!config_.world.empty()) {
active_mod_.clear();
load_world(config_.world);
scene_ = config_.scene;
if (scene_ != "main" && scene_ != "newgame" && scene_ != "manager" &&
@@ -745,10 +803,13 @@ public:
if (!config_.state.empty() && source_) {
desktop_ = source_->load(config_.state);
saved_desktop_ = desktop_;
if(config_.theme.empty())theme_ = snap().state.at("preferences").value("theme", theme_);
if (config_.theme.empty())
theme_ = snap().state.at("preferences").value("theme", theme_);
}
if(source_&&!config_.theme.empty()){
auto preferences=snap().state.at("preferences");preferences["theme"]=theme_;apply("preferences",preferences);
if (source_ && !config_.theme.empty()) {
auto preferences = snap().state.at("preferences");
preferences["theme"] = theme_;
apply("preferences", preferences);
}
if (scene_ == "manager" && selections_["manager-name"].empty())
selections_["manager-name"] = "Alex Berger";