Unify Modern dropdown menus with Gold layout and safe keyboard selection (by Codex)

This commit is contained in:
Codex committed 2026-10-26 13:45:19 +01:00
1 parent e81ecf95f2
commit fff2cc2f0b
18 files changed
+1361 -17

No files matched your search

+14 -2
View File
@@ -13,9 +13,21 @@ else()
target_compile_options(bmh_modern_ui_mods PRIVATE -Wall -Wextra -Wpedantic)
endif()
add_test(NAME modern_mods_ui_tests COMMAND modern_mods_ui_tests)
add_library(bmh_modern_ui_select_menu STATIC select_menu.cpp)
target_link_libraries(bmh_modern_ui_select_menu PUBLIC bmh_modern_ui_core RmlUi::Core)
add_executable(modern_select_menu_tests ../../../tests/modern_select_menu_tests.cpp)
target_link_libraries(modern_select_menu_tests PRIVATE bmh_modern_ui_select_menu)
if(MSVC)
target_compile_options(bmh_modern_ui_select_menu PRIVATE /W4 /utf-8)
target_compile_options(modern_select_menu_tests PRIVATE /W4 /utf-8)
else()
target_compile_options(bmh_modern_ui_select_menu PRIVATE -Wall -Wextra -Wpedantic)
target_compile_options(modern_select_menu_tests PRIVATE -Wall -Wextra -Wpedantic)
endif()
add_test(NAME modern_select_menu_tests COMMAND modern_select_menu_tests "${CMAKE_BINARY_DIR}/assets/modern")
find_package(Threads REQUIRED)
add_library(bmh_modern_ui STATIC view.cpp ticket_popover.cpp)
target_link_libraries(bmh_modern_ui PUBLIC bmh_modern_ui_core PRIVATE Threads::Threads bmh_modern_ui_mods bmh_rmlui bmh_launcher nfd::nfd ${BMH_SDL_TARGET})
target_link_libraries(bmh_modern_ui PUBLIC bmh_modern_ui_core PRIVATE Threads::Threads bmh_modern_ui_mods bmh_modern_ui_select_menu 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 /bigobj)
@@ -26,7 +38,7 @@ endif()
set(modern_assets "${CMAKE_BINARY_DIR}/assets/modern")
FetchContent_GetProperties(rmlui)
file(MAKE_DIRECTORY "${modern_assets}")
foreach(asset modern.rml theme.rcss ticket.rcss sports.rcss calendar.rcss reports.rcss report_details.rcss report_pickers.rcss indoor.rcss planning.rcss almanac.rcss finance.rcss bank.rcss contracts.rcss amount.rcss environment.rcss advertising.rcss toto.rcss lineup.rcss transfer.rcss career_reports.rcss rankings.rcss stadium.rcss statistics.rcss news.rcss settings.rcss widgets.rcss files.rcss front.rcss entry.rcss opening.rcss)
foreach(asset modern.rml theme.rcss ticket.rcss sports.rcss calendar.rcss reports.rcss report_details.rcss report_pickers.rcss indoor.rcss planning.rcss almanac.rcss finance.rcss bank.rcss contracts.rcss amount.rcss environment.rcss advertising.rcss toto.rcss lineup.rcss transfer.rcss career_reports.rcss rankings.rcss stadium.rcss statistics.rcss news.rcss settings.rcss widgets.rcss files.rcss front.rcss entry.rcss opening.rcss select_menu.rcss)
configure_file("${CMAKE_SOURCE_DIR}/assets/modern/${asset}" "${modern_assets}/${asset}" COPYONLY)
endforeach()
+1 -1
View File
@@ -969,7 +969,7 @@ void App::script() {
{"transfer_view", transfer_view_}, {"transfer_dialog", transfer_dialog_}, {"transfer_draft", transfer_draft_},
{"career_view", career_view_}, {"rankings_view", rankings_view_},
{"stadium_view", stadium_view_},
{"entry_view", entry_snapshot()}, {"front_view",front_snapshot_view()}, {"files_view",{{"mode",files_mode_},{"selected",files_selected_},{"name",files_name_},{"feedback",files_feedback_}}}, {"widget_view",{{"query",widget_query_},{"notice",widget_notice_}}}, {"ui_preferences",ui_preferences_}, {"settings_draft",settings_draft_}, {"settings_category",settings_category_}, {"settings_query",settings_query_}, {"settings_notice",settings_notice_},
{"select_menu", select_menu_ ? select_menu_->snapshot() : Json()}, {"entry_view", entry_snapshot()}, {"front_view",front_snapshot_view()}, {"files_view",{{"mode",files_mode_},{"selected",files_selected_},{"name",files_name_},{"feedback",files_feedback_}}}, {"widget_view",{{"query",widget_query_},{"notice",widget_notice_}}}, {"ui_preferences",ui_preferences_}, {"settings_draft",settings_draft_}, {"settings_category",settings_category_}, {"settings_query",settings_query_}, {"settings_notice",settings_notice_},
{"statistics_view", statistics_view_}, {"statistics_trophy", statistics_trophy_},
{"statistics_scrolls", statistics_scrolls_},
{"news_view", news_view_}, {"news_dialog", news_dialog_},
+6 -5
View File
@@ -216,7 +216,7 @@ void App::entry_confirm() {
refresh();
}
bool App::entry_action(const std::string &action, Rml::Element *target) {
if ((scene_ != "newgame" && scene_ != "manager") || !popup_.empty())
if ((scene_ != "newgame" && scene_ != "manager") || !popup_.empty() || menu_ == "quit")
return false;
const auto id =
target ? target->GetAttribute<Rml::String>("data-id", "") : std::string();
@@ -339,7 +339,7 @@ bool App::entry_action(const std::string &action, Rml::Element *target) {
refresh();
return true;
}
bool App::entry_change(Rml::Element *target) {
bool App::entry_change(Rml::Element *target, bool user_reselected) {
if (scene_ != "manager" || manager_confirm_ || manager_success_)
return false;
const auto kind = target->GetAttribute<Rml::String>("data-change", "");
@@ -357,16 +357,17 @@ bool App::entry_change(Rml::Element *target) {
if (!manager_picker_)
selections_["manager-name"] = field("manager-name");
if (kind == "manager-country") {
if (value == country_)
if (value == country_ && !user_reselected)
return true;
country_ = value;
league_.clear();
} else {
if (value == league_)
if (value == league_ && !user_reselected)
return true;
league_ = value;
}
club_search_.clear();
if (!manager_picker_ && user_reselected) selected_club_.clear();
if (manager_picker_) {
const auto leagues = entry_world()->leagues(country_);
if (std::none_of(leagues.begin(), leagues.end(),
@@ -406,7 +407,7 @@ bool App::entry_input(Rml::Element *target) {
return true;
}
bool App::entry_event(Rml::Event &event) {
if ((scene_ != "newgame" && scene_ != "manager") || !popup_.empty())
if ((scene_ != "newgame" && scene_ != "manager") || !popup_.empty() || menu_ == "quit")
return false;
const auto type = event.GetType();
auto *target = event.GetTargetElement();
+1
View File
@@ -159,6 +159,7 @@ std::string App::render_manager() {
const std::vector<std::pair<std::string, std::string>> &rows,
const std::string &value) {
auto out = select(id, rows, value, id);
out.insert(out.find('>'), " data-select-style=\"league\"");
if (full)
out.insert(out.find('>'), " disabled");
return out;
+1 -1
View File
@@ -204,7 +204,7 @@ std::string App::render_lineup() {
return "<span class=\"lineup-option-mark\" aria-hidden=\"true\"><span class=\"lineup-option-check\"></span></span><span class=\"lineup-option-text\">"+esc(name)+"</span>";
};
for (int i=0;i<3;++i) {
out+="<label class=\"lineup-taker-label\" style=\"left:"+scalar(i*(lineup_taker_width_dp+18.0))+"dp;\"><span>"+std::string(labels[size_t(i)])+"</span><select class=\"lineup-taker\" id=\"lineup-taker-"+std::to_string(i)+"\" data-lineup-taker=\""+std::to_string(i)+"\" aria-label=\""+std::string(labels[size_t(i)])+"schütze\"><option value=\"\" "+std::string(l.at("takers")[size_t(i)]==""?"selected=\"selected\"":"")+">"+option_text("AUTO")+"</option>";
out+="<label class=\"lineup-taker-label\" style=\"left:"+scalar(i*(lineup_taker_width_dp+18.0))+"dp;\"><span>"+std::string(labels[size_t(i)])+"</span><select class=\"lineup-taker\" data-select-max-height=\"280\" id=\"lineup-taker-"+std::to_string(i)+"\" data-lineup-taker=\""+std::to_string(i)+"\" aria-label=\""+std::string(labels[size_t(i)])+"schütze\"><option value=\"\" "+std::string(l.at("takers")[size_t(i)]==""?"selected=\"selected\"":"")+">"+option_text("AUTO")+"</option>";
for (size_t r=0;r<std::min(size_t(11),rows.size());++r) {
const auto id=rows[r].at("id").get<std::string>();
out+="<option value=\""+esc(id)+"\" "+std::string(l.at("takers")[size_t(i)]==id?"selected=\"selected\"":"")+">"+option_text(rows[r].at("name").get<std::string>())+"</option>";
+548
View File
@@ -0,0 +1,548 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "modern/ui/select_menu.hpp"
#include <RmlUi/Core.h>
#include <RmlUi/Core/ElementText.h>
#include <RmlUi/Core/Elements/ElementFormControlSelect.h>
#include <RmlUi/Core/StringUtilities.h>
#include <algorithm>
#include <chrono>
#include <cmath>
#include <utility>
#include <vector>
namespace bmh::modern_ui {
namespace {
using Select = Rml::ElementFormControlSelect;
using Clock = std::chrono::steady_clock;
std::string plain_text(Rml::Element *node) {
if (auto *text = dynamic_cast<Rml::ElementText *>(node))
return Rml::StringUtilities::DecodeRml(text->GetText());
std::string text;
for (int i = 0; i < node->GetNumChildren(); ++i)
text += plain_text(node->GetChild(i));
return text;
}
std::string tidy(std::string text) {
std::string out;
bool space = false;
for (const auto c : text) {
if (c == ' ' || c == '\t' || c == '\n' || c == '\r') {
space = !out.empty();
continue;
}
if (space)
out += ' ';
space = false;
out += c;
}
return out;
}
// Country/league labels use Latin scripts. Keep UTF-8 intact and support their
// common accented capitals, rather than lowercasing individual non-ASCII bytes.
std::string folded(std::string text) {
for (size_t i = 0; i < text.size(); ++i) {
const auto c = static_cast<unsigned char>(text[i]);
if (c >= 'A' && c <= 'Z')
text[i] = char(c + ('a' - 'A'));
else if (c == 0xc3 && i + 1 < text.size()) {
const auto next = static_cast<unsigned char>(text[i + 1]);
if (next >= 0x80 && next <= 0x9e && next != 0x97)
text[++i] = char(next + 0x20);
}
}
return text;
}
bool within(Rml::Element *node, const Rml::Element *root) {
for (; node; node = node->GetParentNode())
if (node == root)
return true;
return false;
}
Select *native_select(Rml::Element *node) {
for (; node; node = node->GetParentNode())
if (auto *select = dynamic_cast<Select *>(node))
return select;
return nullptr;
}
bool supported(Select *select) {
return select && !select->GetId().empty() &&
!select->HasAttribute("multiple");
}
bool available(Select *select) {
if (!supported(select) || select->IsDisabled() || !select->IsVisible(true))
return false;
for (auto *node = select->GetParentNode(); node; node = node->GetParentNode())
if (node->HasAttribute("inert") || node->HasAttribute("hidden"))
return false;
return true;
}
bool pixels(Rml::Element &node, Rml::PropertyId property, float value) {
const auto *old = node.GetLocalProperty(property);
if (old && old->unit == Rml::Unit::PX &&
std::abs(old->Get<float>() - value) < .02f)
return false;
node.SetProperty(property, Rml::Property(value, Rml::Unit::PX));
return true;
}
} // namespace
struct SelectMenu::Impl {
struct Option {
std::string text, value;
bool disabled = false;
bool operator==(const Option &) const = default;
};
Rml::Context &context;
Rml::ElementDocument &document;
CheckMarkupFn check;
CommitFn on_commit;
Rml::ObserverPtr<Rml::Element> anchor, canvas, popup;
std::vector<Option> options;
std::string id, typed;
Clock::time_point typed_at{};
int cursor = -1, selected = -1;
bool open = false, league = false, reveal_cursor = false,
focus_cursor = false;
bool suppress_right_release = false, suppress_context_menu = false;
Clock::time_point right_dismissed_at{};
float max_height = 0;
Impl(Rml::Context &c, Rml::ElementDocument &d, CheckMarkupFn glyph,
CommitFn commit)
: context(c), document(d), check(std::move(glyph)),
on_commit(std::move(commit)) {}
Select *control() const { return dynamic_cast<Select *>(anchor.get()); }
std::vector<Option> read_options(Select &select) const {
std::vector<Option> rows;
const int count = select.GetNumOptions();
rows.reserve(size_t(std::max(0, count)));
for (int i = 0; i < count; ++i) {
auto *node = select.GetOption(i);
rows.push_back({tidy(plain_text(node)),
node->GetAttribute<Rml::String>("value", ""),
node->HasAttribute("disabled")});
}
return rows;
}
void remove_popup() {
if (popup)
if (auto *parent = popup->GetParentNode())
parent->RemoveChild(popup.get());
popup.reset();
}
void close(bool focus) {
auto old = anchor;
if (auto *select = control()) {
select->HideSelectBox();
if (select->GetAttribute<Rml::String>("aria-expanded", "") != "false")
select->SetAttribute("aria-expanded", "false");
select->RemoveAttribute("aria-controls");
}
// An ongoing Tab event can still hold its original popup-row target.
// Hide now, but destroy only at the next safe layout/render boundary.
if (popup)
popup->SetProperty("display", "none");
open = false;
anchor.reset();
canvas.reset();
id.clear();
options.clear();
typed.clear();
cursor = selected = -1;
max_height = 0;
reveal_cursor = focus_cursor = false;
if (focus)
if (auto *select = dynamic_cast<Select *>(old.get()); available(select))
select->Focus(true);
}
int endpoint(bool last) const {
if (last) {
for (int i = int(options.size()) - 1; i >= 0; --i)
if (!options[size_t(i)].disabled)
return i;
} else {
for (size_t i = 0; i < options.size(); ++i)
if (!options[i].disabled)
return int(i);
}
return -1;
}
void mark_cursor(bool focus) {
if (!popup)
return;
for (int i = 0; i < popup->GetNumChildren(); ++i) {
auto *row = popup->GetChild(i);
const bool active = i == cursor;
if (row->IsClassSet("is-cursor") != active)
row->SetClass("is-cursor", active);
}
if (cursor >= 0)
if (auto *row = popup->GetChild(cursor)) {
if (focus)
focus_cursor = true;
reveal_cursor = true;
}
}
bool show(Select &select, bool last) {
close(false);
remove_popup();
if (!available(&select))
return false;
auto rows = read_options(select);
if (rows.empty() || std::none_of(rows.begin(), rows.end(),
[](const auto &o) { return !o.disabled; }))
return false;
auto *stage = document.GetElementById("canvas");
if (!stage)
return false;
anchor = select.GetObserverPtr();
canvas = stage->GetObserverPtr();
id = select.GetId();
options = std::move(rows);
selected = select.GetSelection();
league =
select.GetAttribute<Rml::String>("data-select-style", "") == "league";
cursor = last ? endpoint(true) : selected;
if (cursor < 0 || cursor >= int(options.size()) ||
options[size_t(cursor)].disabled)
cursor = endpoint(false);
std::string rml;
const auto marker = check ? check(league ? 28.f : 24.f) : std::string();
for (size_t i = 0; i < options.size(); ++i) {
const auto &option = options[i];
rml += "<button type=\"button\" class=\"native-select-option\" "
"id=\"native-select-option-" +
std::to_string(i) +
"\" role=\"option\" tabindex=\"-1\" data-index=\"" +
std::to_string(i) + "\" aria-selected=\"" +
(int(i) == selected ? "true" : "false") + "\" " +
(option.disabled ? "disabled" : "") +
"><span class=\"native-select-check\" aria-hidden=\"true\">" +
(int(i) == selected ? marker : "") +
"</span><span class=\"native-select-text\">" +
editor::escaped(option.text) + "</span></button>";
}
auto layer = document.CreateElement("div");
layer->SetId("native-select-menu");
layer->SetClassNames(std::string("native-select-menu") +
(league ? " league" : ""));
layer->SetAttribute("role", "listbox");
layer->SetAttribute("aria-label", select.GetAttribute<Rml::String>(
"aria-label", "Auswahl"));
layer->SetAttribute("data-select-id", id);
layer->SetInnerRML(rml);
popup = stage->AppendChild(std::move(layer))->GetObserverPtr();
select.HideSelectBox();
select.SetAttribute("aria-haspopup", "listbox");
select.SetAttribute("aria-expanded", "true");
select.SetAttribute("aria-controls", "native-select-menu");
open = true;
mark_cursor(true);
layout();
return true;
}
void commit(int index) {
if (!open)
return;
if (!fresh()) {
close(false);
return;
}
if (index < 0 || index >= int(options.size()) ||
options[size_t(index)].disabled)
return;
auto old = anchor;
const auto committed_id = id;
const bool reselected = index == selected;
close(true);
if (auto *select = dynamic_cast<Select *>(old.get()); available(select)) {
// A changed index sends the native change itself. Reselection sends none.
if (!reselected)
select->SetSelection(index);
if (on_commit)
on_commit(committed_id, index, reselected);
}
}
void move(int direction) {
if (options.empty())
return;
int next = cursor;
for (size_t tried = 0; tried < options.size(); ++tried) {
next = (next + direction + int(options.size())) % int(options.size());
if (!options[size_t(next)].disabled) {
cursor = next;
mark_cursor(true);
return;
}
}
}
void type(const std::string &text) {
if (text.empty())
return;
const auto now = Clock::now();
typed =
now - typed_at < std::chrono::milliseconds(700) ? typed + text : text;
typed_at = now;
const auto prefix = folded(typed);
for (size_t i = 0; i < options.size(); ++i)
if (!options[i].disabled && folded(options[i].text).starts_with(prefix)) {
cursor = int(i);
mark_cursor(true);
return;
}
}
bool fresh() const {
auto *select = control();
return available(select) && canvas && popup &&
document.GetElementById(id) == select &&
document.GetElementById("canvas") == canvas.get() &&
select->GetSelection() == selected &&
read_options(*select) == options;
}
void layout() {
if (!open) {
remove_popup();
return;
}
if (!fresh()) {
close(false);
remove_popup();
return;
}
auto *select = control();
select->HideSelectBox();
const float ratio =
std::max(.001f, context.GetDensityIndependentPixelRatio());
Rml::Element *owner = select->GetParentNode();
while (owner && !owner->IsClassSet("window"))
owner = owner->GetParentNode();
if (!owner)
owner = canvas.get();
const auto owner_at = owner->GetAbsoluteOffset(Rml::BoxArea::Border);
const auto at = select->GetAbsoluteOffset(Rml::BoxArea::Border);
const auto size = select->GetBox().GetSize(Rml::BoxArea::Border);
const auto stage_at = canvas->GetAbsoluteOffset(Rml::BoxArea::Border);
const auto border_origin =
owner->GetBox().GetPosition(Rml::BoxArea::Padding);
const float left_edge = owner_at.x + border_origin.x,
top_edge = owner_at.y + border_origin.y;
const float right_edge = left_edge + owner->GetClientWidth();
const float bottom_edge = top_edge + owner->GetClientHeight();
const float padding = 20 * ratio, gap = (league ? 12.f : 8.f) * ratio;
const float width =
std::min(std::max(0.f, right_edge - left_edge - 2 * padding),
std::max(size.x, 360 * ratio));
const float left =
std::clamp(at.x, left_edge + padding,
std::max(left_edge + padding, right_edge - padding - width));
const float above = std::max(0.f, at.y - top_edge - padding),
below = std::max(0.f, bottom_edge - at.y - size.y - padding);
float cap_dp = league ? 740.f : 480.f;
const float custom =
select->GetAttribute<float>("data-select-max-height", cap_dp);
if (std::isfinite(custom) && custom > 0)
cap_dp = std::min(cap_dp, custom);
const float cap = cap_dp * ratio;
const float desired =
std::min(float(options.size()) * 58 * ratio + 20 * ratio, cap);
const bool down = below >= std::min(desired, 220 * ratio) || below >= above;
max_height = std::min(cap, std::max(0.f, (down ? below : above) - gap));
bool changed = pixels(*popup.get(), Rml::PropertyId::Width, width);
changed |= pixels(*popup.get(), Rml::PropertyId::FontSize,
select->GetComputedValues().font_size());
changed |= pixels(*popup.get(), Rml::PropertyId::MaxHeight, max_height);
changed |= pixels(*popup.get(), Rml::PropertyId::Left, left - stage_at.x);
if (changed)
context.Update();
const float height = popup->GetBox().GetSize(Rml::BoxArea::Border).y;
const float top = down ? at.y + size.y + gap : at.y - height - gap;
if (pixels(*popup.get(), Rml::PropertyId::Top, top - stage_at.y))
context.Update();
if (reveal_cursor && cursor >= 0) {
if (auto *row = popup->GetChild(cursor)) {
if (focus_cursor)
row->Focus(true);
// Match the HTML list's local scroll adjustment. Pinned RmlUI's
// generic ScrollIntoView adds the popup border to the start offset,
// which clips the first row at larger density factors.
const float row_top = row->GetAbsoluteOffset(Rml::BoxArea::Border).y;
const float row_bottom =
row_top + row->GetBox().GetSize(Rml::BoxArea::Border).y;
const float view_top =
popup->GetAbsoluteOffset(Rml::BoxArea::Border).y +
popup->GetClientTop();
const float view_bottom = view_top + popup->GetClientHeight();
const float scroll = popup->GetScrollTop();
if (row_top < view_top)
popup->SetScrollTop(scroll + row_top - view_top);
else if (row_bottom > view_bottom)
popup->SetScrollTop(scroll + row_bottom - view_bottom);
}
reveal_cursor = focus_cursor = false;
}
}
Rml::Element *row(Rml::Element *target) const {
for (auto *node = target; node && node != popup.get();
node = node->GetParentNode())
if (node->IsClassSet("native-select-option") && within(node, popup.get()))
return node;
return nullptr;
}
bool event(Rml::Event &event) {
const auto type = event.GetType();
auto *target = event.GetTargetElement();
const auto consume = [&] {
event.StopImmediatePropagation();
return true;
};
auto *select = native_select(target);
if (!suppress_right_release &&
Clock::now() - right_dismissed_at > std::chrono::milliseconds(500))
suppress_context_menu = false;
if (type == "contextmenu") {
if (open) {
close(true);
suppress_context_menu = false;
return consume();
}
if (suppress_context_menu) {
suppress_context_menu = false;
return consume();
}
}
if (type == "mouseup" && event.GetParameter<int>("button", 0) == 1 &&
suppress_right_release) {
suppress_right_release = false;
right_dismissed_at = Clock::now();
return consume();
}
if (type == "mousedown") {
if (event.GetParameter<int>("button", 0) == 1 && open) {
close(true);
suppress_right_release = suppress_context_menu = true;
right_dismissed_at = Clock::now();
return consume();
}
if (event.GetParameter<int>("button", 0) != 1)
suppress_context_menu = false;
if (auto *choice = open ? row(target) : nullptr) {
const int index = choice->GetAttribute<int>("data-index", -1);
if (index >= 0 && index < int(options.size()) &&
!options[size_t(index)].disabled) {
cursor = index;
mark_cursor(true);
}
return consume();
}
if (supported(select) && event.GetParameter<int>("button", 0) == 0) {
if (open && anchor == select)
close(true);
else
show(*select, false);
return consume();
}
if (open && !within(target, popup.get()))
close(false);
} else if (type == "click") {
if (auto *choice = open ? row(target) : nullptr) {
commit(choice->GetAttribute<int>("data-index", -1));
return consume();
}
if (supported(select))
return consume(); // Never let the native list open.
} else if (type == "textinput" && open) {
typeahead_event(event);
return consume();
} else if (type == "keydown") {
// A keyboard context-menu request starts a new gesture.
if (!suppress_right_release)
suppress_context_menu = false;
const auto key = Rml::Input::KeyIdentifier(
event.GetParameter<int>("key_identifier", 0));
if (open) {
if (key == Rml::Input::KI_TAB) {
close(true);
return false;
}
if (key == Rml::Input::KI_ESCAPE || key == Rml::Input::KI_F4) {
close(true);
return consume();
}
if (key == Rml::Input::KI_UP || key == Rml::Input::KI_DOWN) {
move(key == Rml::Input::KI_UP ? -1 : 1);
return consume();
}
if (key == Rml::Input::KI_HOME || key == Rml::Input::KI_END) {
cursor = endpoint(key == Rml::Input::KI_END);
mark_cursor(true);
return consume();
}
if (key == Rml::Input::KI_RETURN || key == Rml::Input::KI_NUMPADENTER ||
key == Rml::Input::KI_SPACE) {
commit(cursor);
return consume();
}
// Printable input is handled by textinput, including UTF-8. Consuming
// keydown prevents native widget navigation or menu-level shortcuts.
if (!event.GetParameter<int>("ctrl_key", 0) &&
!event.GetParameter<int>("alt_key", 0) &&
!event.GetParameter<int>("meta_key", 0))
return consume();
} else if (available(select) &&
(key == Rml::Input::KI_UP || key == Rml::Input::KI_DOWN ||
key == Rml::Input::KI_RETURN ||
key == Rml::Input::KI_NUMPADENTER ||
key == Rml::Input::KI_SPACE || key == Rml::Input::KI_F4)) {
show(*select, key == Rml::Input::KI_UP);
return consume();
}
}
return false;
}
void typeahead_event(Rml::Event &event) {
type(event.GetParameter<Rml::String>("text", ""));
}
};
SelectMenu::SelectMenu(Rml::Context &context, Rml::ElementDocument &document,
CheckMarkupFn check, CommitFn commit)
: impl_(std::make_unique<Impl>(context, document, std::move(check),
std::move(commit))) {}
SelectMenu::~SelectMenu() {
impl_->close(false);
impl_->remove_popup();
}
bool SelectMenu::process_event(Rml::Event &event) {
return impl_->event(event);
}
void SelectMenu::before_render() {
impl_->close(false);
impl_->remove_popup();
}
void SelectMenu::after_layout() { impl_->layout(); }
bool SelectMenu::is_open() const { return impl_->open; }
editor::Json SelectMenu::snapshot() const {
auto &menu = *impl_;
editor::Json rect = editor::Json::object();
float font = 0, scroll = 0;
if (menu.open && menu.popup) {
const auto at = menu.popup->GetAbsoluteOffset(Rml::BoxArea::Border);
const auto size = menu.popup->GetBox().GetSize(Rml::BoxArea::Border);
rect = {{"x", at.x}, {"y", at.y}, {"width", size.x}, {"height", size.y}};
font = menu.popup->GetComputedValues().font_size();
scroll = menu.popup->GetScrollTop();
}
return {{"open", menu.open},
{"id", menu.id},
{"cursor", menu.cursor},
{"selected", menu.selected},
{"option_count", menu.options.size()},
{"rect", rect},
{"font_size", font},
{"ratio", menu.context.GetDensityIndependentPixelRatio()},
{"max_height", menu.max_height},
{"scroll_top", scroll}};
}
} // namespace bmh::modern_ui
+46
View File
@@ -0,0 +1,46 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "editor/archive.hpp"
#include <functional>
#include <memory>
#include <string>
namespace Rml {
class Context;
class ElementDocument;
class Event;
} // namespace Rml
namespace bmh::modern_ui {
// The visible native Select remains the only form control/value owner. Its
// native list stays closed; this adapter owns a temporary list inside #canvas.
class SelectMenu final {
public:
using CheckMarkupFn = std::function<std::string(float size_dp)>;
// Called after SetSelection and its ordinary change event. Reselection emits
// no synthetic change; the owner may explicitly handle that user intent here.
using CommitFn =
std::function<void(const std::string &id, int index, bool reselected)>;
SelectMenu(Rml::Context &, Rml::ElementDocument &, CheckMarkupFn, CommitFn);
~SelectMenu();
SelectMenu(const SelectMenu &) = delete;
SelectMenu &operator=(const SelectMenu &) = delete;
// Invoke in capture phase before menu-specific handlers. True means consumed.
// Tab cancels the popup and returns false so normal focus navigation
// proceeds.
bool process_event(Rml::Event &);
// Call before replacing canvas contents. Does not restore an obsolete focus.
void before_render();
// Call after context Update: checks lifetime/disabled state and places popup.
void after_layout();
bool is_open() const;
editor::Json snapshot() const;
private:
struct Impl;
std::unique_ptr<Impl> impl_;
};
} // namespace bmh::modern_ui
+66 -1
View File
@@ -5,6 +5,7 @@
#include "launch/rml_path.hpp"
#include "launch/rml_video.hpp"
#include "modern/ui/controls.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"
@@ -346,6 +347,16 @@ class App final : public Rml::EventListener {
std::shared_ptr<const Catalog> world_;
std::unique_ptr<DemoSource> source_;
std::unique_ptr<TicketPopover> ticket_;
std::unique_ptr<SelectMenu> select_menu_;
bool select_text_input_owned_ = false;
struct SelectCapture final : Rml::EventListener {
std::function<void(Rml::Event &)> handler;
void ProcessEvent(Rml::Event &event) override {
if (handler) handler(event);
}
} select_capture_;
static constexpr std::array<const char *, 9> select_capture_events_ = {
"mousedown", "mouseup", "click", "keydown", "textinput", "blur", "scroll", "mousemove", "contextmenu"};
bool focus_ticket_ = false;
std::set<std::string> pending_selects_;
std::string focus_after_render_;
@@ -758,7 +769,7 @@ class App final : public Rml::EventListener {
void entry_sync_club();
void entry_confirm();
bool entry_action(const std::string &, Rml::Element *);
bool entry_change(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;
@@ -828,7 +839,23 @@ class App final : public Rml::EventListener {
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 (select_menu_) select_menu_->before_render();
if (scene_ == "desktop" && !files_capturing_ && opening_pending()) {
scene_ = "opening";
menu_.clear();
@@ -961,6 +988,7 @@ class App final : public Rml::EventListener {
}
}
void render_popup() {
if (!popup_.empty() && select_menu_) select_menu_->before_render();
if (popup_.empty()) {
element("popup")->SetClass("visible", false);
rendered_popup_.clear();
@@ -1043,6 +1071,11 @@ class App final : public Rml::EventListener {
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;
@@ -1221,6 +1254,32 @@ public:
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"})
@@ -1277,6 +1336,12 @@ public:
}
}
void shutdown() {
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();
+17 -1
View File
@@ -188,7 +188,7 @@ bool App::widget_event(Rml::Event &event) {
return widget_change(target);
}
}
if (type != "keydown" || scene_ != "desktop")
if (type != "keydown" || (scene_ != "desktop" && menu_ != "quit"))
return false;
const auto key =
Rml::Input::KeyIdentifier(event.GetParameter<int>("key_identifier", 0));
@@ -233,6 +233,22 @@ bool App::widget_event(Rml::Event &event) {
event.StopImmediatePropagation();
return true;
}
if (key == Rml::Input::KI_TAB && menu_ == "quit") {
Rml::ElementList buttons;
if (auto *modal = doc_->QuerySelector(".desktop-modal-layer"))
modal->QuerySelectorAll(buttons, "button");
std::erase_if(buttons, [](auto *button) {
return !button->IsVisible(true) || button->HasAttribute("disabled");
});
if (!buttons.empty()) {
const auto found = std::find(buttons.begin(), buttons.end(), context_->GetFocusElement());
const int count = int(buttons.size());
const int old = found == buttons.end() ? (shift ? 0 : -1) : int(found - buttons.begin());
buttons[size_t((old + (shift ? -1 : 1) + count) % count)]->Focus(true);
}
event.StopImmediatePropagation();
return true;
}
if (key == Rml::Input::KI_ESCAPE && menu_ == "quit") {
widget_action("desktop-quit-cancel", nullptr);
event.StopImmediatePropagation();