Files
Dreierpack-Manager/tests/modern_select_menu_tests.cpp
T

546 lines
23 KiB
C++

// SPDX-License-Identifier: GPL-3.0-only
// Real Rml input/document tests. The renderer is windowless; controls are not.
#include "modern/ui/controls.hpp"
#include "modern/ui/select_menu.hpp"
#include <RmlUi/Core/ElementText.h>
#include <RmlUi/Core/Elements/ElementFormControlSelect.h>
#include <cmath>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <map>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <vector>
using namespace bmh::modern_ui;
namespace {
using Key = Rml::Input::KeyIdentifier;
void require(bool value, const char *message) {
if (!value)
throw std::runtime_error(message);
}
struct Renderer final : Rml::RenderInterface {
Rml::CompiledGeometryHandle CompileGeometry(Rml::Span<const Rml::Vertex>,
Rml::Span<const int>) override {
return 1;
}
void RenderGeometry(Rml::CompiledGeometryHandle, Rml::Vector2f,
Rml::TextureHandle) override {}
void ReleaseGeometry(Rml::CompiledGeometryHandle) override {}
Rml::TextureHandle LoadTexture(Rml::Vector2i &,
const Rml::String &) override {
return 0;
}
Rml::TextureHandle GenerateTexture(Rml::Span<const Rml::byte>,
Rml::Vector2i) override {
return 1;
}
void ReleaseTexture(Rml::TextureHandle) override {}
void EnableScissorRegion(bool) override {}
void SetScissorRegion(Rml::Rectanglei) override {}
};
struct System final : Rml::SystemInterface {
size_t stylesheet_errors = 0;
double GetElapsedTime() override { return 0; }
bool LogMessage(Rml::Log::Type type, const Rml::String &message) override {
if ((type == Rml::Log::LT_WARNING || type == Rml::Log::LT_ERROR) &&
(message.find("property") != message.npos ||
message.find("style") != message.npos ||
message.find("Syntax error") != message.npos)) {
++stylesheet_errors;
std::cerr << message << '\n';
}
return true;
}
};
struct Commit {
std::string id;
int index;
bool reselected;
int changes_seen;
};
struct Host final : Rml::EventListener {
Rml::Context *context = nullptr;
Rml::ElementDocument *document = nullptr;
SelectMenu *menu = nullptr;
bool populating = false;
std::map<std::string, int> changes;
std::vector<Commit> commits;
int outside_clicks = 0, tab_moves = 0;
void ProcessEvent(Rml::Event &event) override {
if (menu && menu->process_event(event))
return;
auto *target = event.GetTargetElement();
if (!populating && event.GetType() == "change" &&
dynamic_cast<Rml::ElementFormControlSelect *>(target))
++changes[target->GetId()];
if (event.GetType() == "click")
for (auto *node = target; node; node = node->GetParentNode())
if (node->GetId() == "outside") {
++outside_clicks;
break;
}
if (event.GetType() == "keydown" &&
event.GetParameter<int>("key_identifier", 0) == Rml::Input::KI_TAB) {
// Minimal real host navigation: the adapter must cancel and let this run.
const auto id =
context->GetFocusElement() ? context->GetFocusElement()->GetId() : "";
if (id == "basic") {
document->GetElementById("after")->Focus(true);
++tab_moves;
event.StopImmediatePropagation();
}
}
}
};
std::string options(const std::string &selected = "alpha") {
std::string out;
for (const auto &[value, label] :
std::vector<std::pair<std::string, std::string>>{
{"alpha", "Alpha &amp; &lt;Verein&gt; &quot;A&quot;"},
{"blocked", "Blocked"},
{"apfel", "Äpfel"},
{"zulu", "Zulu"},
{"alpine", "Alpine"}})
out += "<option value='" + value + "' " +
(value == selected ? "selected " : "") +
(value == "blocked" ? "disabled" : "") + ">" + label + "</option>";
return out;
}
std::string many_options() {
std::string out;
for (int index = 0; index < 30; ++index)
out += "<option value='" + std::to_string(index) + "' " +
(index == 0 ? "selected" : "") + ">Option " + std::to_string(index) +
"</option>";
return out;
}
std::string contents(const std::string &selected = "alpha") {
const auto select = [](const char *id, const char *position,
const std::string &rows, const char *attributes = "") {
return "<select id='" + std::string(id) +
"' aria-label='Synthetic choice' " + attributes +
" style='position:absolute;height:88dp;font-size:30dp;" + position +
"'>" + rows + "</select>";
};
return "<section id='owner' class='window' "
"style='left:400dp;top:200dp;width:2400dp;height:1600dp;'>" +
select("basic", "left:120dp;top:160dp;width:620dp;",
options(selected)) +
"<button id='after' "
"style='position:absolute;left:120dp;top:60dp;width:400dp;height:76dp;"
"'><span>After select</span></button>" +
select("long", "left:1000dp;top:160dp;width:620dp;", many_options()) +
select("league", "left:120dp;top:500dp;width:800dp;", many_options(),
"data-select-style='league'") +
select("capped", "left:1000dp;top:500dp;width:620dp;", many_options(),
"data-select-max-height='280'") +
select("bottom", "left:120dp;top:1440dp;width:620dp;",
many_options()) +
select("edge", "left:2250dp;top:1050dp;width:100dp;", many_options()) +
select("disabled", "left:1000dp;top:1000dp;width:620dp;", options(),
"disabled") +
select(
"none", "left:1000dp;top:1200dp;width:620dp;",
"<option value='x' selected disabled>No enabled option</option>") +
"</section><button id='outside' "
"style='position:absolute;left:200dp;top:1900dp;width:350dp;height:"
"80dp;'><span>Outside</span></button>";
}
struct Fixture {
Rml::Context *context = nullptr;
Rml::ElementDocument *document = nullptr;
Host host;
std::unique_ptr<SelectMenu> menu;
float ratio;
std::string theme;
const std::vector<std::string> events = {
"mousedown", "mouseup", "click", "contextmenu", "keydown", "textinput",
"change", "input", "blur", "focus", "scroll"};
Fixture(const std::string &css, const std::string &name, float density)
: ratio(density), theme(name) {
context = Rml::CreateContext("select-menu-tests",
{int(3840 * density), int(2160 * density)});
require(context, "Rml context missing");
context->SetDensityIndependentPixelRatio(density);
document = context->LoadDocumentFromMemory(
"<rml><head><style>" + css + "</style></head><body class='" + name +
"'><div id='canvas'>" + contents() + "</div></body></rml>");
require(document, "Rml document missing");
document->Show();
context->Update();
context->Render();
host.context = context;
host.document = document;
menu = std::make_unique<SelectMenu>(
*context, *document,
[](float size) {
const auto n = std::to_string(size);
return "<span class='fixture-check-art' style='display:block;width:" +
n + "dp;height:" + n +
"dp;border-right:2dp var(--accent);border-bottom:2dp "
"var(--accent);'></span>";
},
[&](const std::string &id, int index, bool reselected) {
host.commits.push_back({id, index, reselected, host.changes[id]});
});
host.menu = menu.get();
for (const auto &event : events)
document->AddEventListener(event, &host, true);
settle();
host.changes.clear();
host.commits.clear();
}
~Fixture() {
if (document)
for (const auto &event : events)
document->RemoveEventListener(event, &host, true);
host.menu = nullptr;
menu.reset();
if (document)
document->Close();
if (context)
Rml::RemoveContext("select-menu-tests");
}
Rml::Element *node(const std::string &id) const {
auto *value = document->GetElementById(id);
require(value, "Fixture node missing");
return value;
}
Rml::ElementFormControlSelect *native(const std::string &id) const {
auto *value = dynamic_cast<Rml::ElementFormControlSelect *>(node(id));
require(value, "Fixture is not a real native select");
return value;
}
void settle() {
for (int i = 0; i < 3; ++i) {
context->Update();
menu->after_layout();
context->Update();
center_selects(*document);
context->Render();
}
}
void click(const std::string &id) {
auto *element = node(id);
const auto at = element->GetAbsoluteOffset(Rml::BoxArea::Border),
size = element->GetBox().GetSize(Rml::BoxArea::Border);
context->ProcessMouseMove(int(std::lround(at.x + size.x / 2)),
int(std::lround(at.y + size.y / 2)), 0);
context->ProcessMouseButtonDown(0, 0);
context->ProcessMouseButtonUp(0, 0);
settle();
}
void key(Key value) {
context->ProcessKeyDown(value, 0);
context->ProcessKeyUp(value, 0);
settle();
}
void text(const std::string &value) {
context->ProcessTextInput(value);
settle();
}
int cursor() const { return menu->snapshot().at("cursor").get<int>(); }
void opening(const std::string &id) {
click(id);
require(menu->is_open(), "Real mouse input did not open adapter");
require(!native(id)->IsSelectBoxVisible(),
"Native and external lists opened simultaneously");
require(menu->snapshot().at("id").get<std::string>() == id,
"Popup owner identity incorrect");
}
void escape() {
key(Rml::Input::KI_ESCAPE);
require(!menu->is_open(), "Escape did not cancel popup");
}
void bounded(const std::string &trigger, bool down) {
auto *popup = node("native-select-menu"), *owner = node("owner");
const auto p = popup->GetAbsoluteOffset(Rml::BoxArea::Border),
s = popup->GetBox().GetSize(Rml::BoxArea::Border);
const auto at = owner->GetAbsoluteOffset(Rml::BoxArea::Border),
size = owner->GetBox().GetSize(Rml::BoxArea::Border);
const auto t = node(trigger)->GetAbsoluteOffset(Rml::BoxArea::Border),
ts = node(trigger)->GetBox().GetSize(Rml::BoxArea::Border);
require(p.x >= at.x + 18 * ratio - 2 &&
p.x + s.x <= at.x + size.x - 18 * ratio + 2,
"Popup escaped horizontal window bounds");
require(p.y >= at.y + 18 * ratio - 2 &&
p.y + s.y <= at.y + size.y - 18 * ratio + 2,
"Popup escaped vertical window bounds");
require(down ? p.y >= t.y + ts.y - 1 : p.y + s.y <= t.y + 1,
"Popup opened on wrong side of trigger");
}
};
std::string rendered_text(Rml::Element *node) {
std::string result;
if (auto *text = dynamic_cast<Rml::ElementText *>(node)) {
for (const auto &line : text->GetLines())
result += line.text;
} else
for (int i = 0; i < node->GetNumChildren(); ++i)
result += rendered_text(node->GetChild(i));
return result;
}
void interaction(Fixture &f) {
f.opening("basic");
require(rendered_text(f.node("native-select-option-0"))
.find("Alpha & <Verein> \"A\"") != std::string::npos,
"Option entities were double-escaped or interpreted as markup");
require(f.menu->snapshot().at("option_count").get<int>() == 5 &&
f.cursor() == 0,
"Initial selection/options incorrect");
f.key(Rml::Input::KI_DOWN);
require(f.cursor() == 2, "Arrow did not skip disabled option");
require(f.context->GetFocusElement()->GetId() == "native-select-option-2",
"Cursor focus not moved to enabled option");
f.click("native-select-option-1");
require(f.menu->is_open() && f.native("basic")->GetValue() == "alpha" &&
f.host.commits.empty(),
"Disabled option committed or closed menu");
f.key(Rml::Input::KI_END);
require(f.cursor() == 4, "End did not select last enabled cursor");
f.key(Rml::Input::KI_DOWN);
require(f.cursor() == 0, "Down did not wrap enabled options");
f.key(Rml::Input::KI_UP);
require(f.cursor() == 4, "Up did not wrap enabled options");
f.key(Rml::Input::KI_HOME);
require(f.cursor() == 0, "Home did not select first enabled cursor");
require(f.native("basic")->GetValue() == "alpha" &&
f.host.changes["basic"] == 0 && f.host.commits.empty(),
"Browsing changed real value or dispatched a handler");
f.key(Rml::Input::KI_DOWN);
f.key(Rml::Input::KI_RETURN);
require(!f.menu->is_open() && f.native("basic")->GetValue() == "apfel" &&
f.native("basic")->GetSelection() == 2,
"Enter did not commit real select value/index");
require(
f.host.changes["basic"] == 1 && f.host.commits.size() == 1 &&
!f.host.commits.back().reselected &&
f.host.commits.back().changes_seen == 1,
"Changed choice did not fire exactly one native change before callback");
require(f.context->GetFocusElement()->GetId() == "basic",
"Commit did not restore trigger focus");
f.opening("basic");
f.click("native-select-option-2");
require(f.host.commits.size() == 2 && f.host.commits.back().reselected &&
f.host.changes["basic"] == 1,
"Reselection lost callback or emitted synthetic ordinary change");
f.native("basic")->Focus(true);
f.key(Rml::Input::KI_F4);
require(f.menu->is_open(), "F4 did not open real select adapter");
f.key(Rml::Input::KI_A);
f.text("a");
f.text("lpi");
require(f.cursor() == 4,
"Typeahead prefix doubled key/textinput or ignored enabled text");
f.escape();
f.opening("basic");
f.text("ä");
f.text("p");
require(f.cursor() == 2, "Unicode textinput did not match accented caption");
f.escape();
require(f.native("basic")->GetValue() == "apfel" &&
f.host.changes["basic"] == 1 && f.host.commits.size() == 2,
"Escape/typeahead changed committed value or callback count");
f.opening("basic");
f.key(Rml::Input::KI_DOWN);
f.key(Rml::Input::KI_TAB);
require(!f.menu->is_open() &&
f.context->GetFocusElement()->GetId() == "after" &&
f.host.tab_moves == 1,
"Tab did not cancel before host focus navigation");
require(f.host.changes["basic"] == 1 && f.host.commits.size() == 2,
"Tab committed highlighted option");
f.opening("basic");
f.click("outside");
require(!f.menu->is_open() && f.host.outside_clicks == 1 &&
f.native("basic")->GetValue() == "apfel",
"Outside cancel swallowed click or committed draft");
f.click("disabled");
require(!f.menu->is_open(), "Disabled trigger opened popup");
f.click("none");
require(!f.menu->is_open(), "All-disabled option set opened popup");
}
void geometry(Fixture &f) {
for (const auto &[id, cap] : std::vector<std::pair<std::string, float>>{
{"long", 480}, {"league", 740}, {"capped", 280}}) {
f.opening(id);
f.bounded(id, true);
auto *popup = f.node("native-select-menu"), *control = f.node(id);
require(std::abs(f.menu->snapshot().at("max_height").get<float>() -
cap * f.ratio) < 2,
"Style/custom popup cap incorrect");
require(popup->GetBox().GetSize(Rml::BoxArea::Border).y <=
cap * f.ratio + 2,
"Popup exceeded requested physical height");
const auto font = control->GetComputedValues().font_size();
require(std::abs(f.menu->snapshot().at("font_size").get<float>() - font) <
.05f,
"Popup font does not match physical trigger font");
const auto expected =
f.theme == "silver" ? Rml::Colourb{243, 247, 252, 252}
: f.theme == "matchday"
? Rml::Colourb{48, 48, 55, 252}
: Rml::Colourb{41, 55, 68,
static_cast<Rml::byte>(id == "league" ? 250 : 255)};
require(popup->GetComputedValues().background_color() == expected,
"Popup used wrong theme surface colour");
for (int index = 0; index < 30; ++index)
require(std::abs(f.node("native-select-option-" + std::to_string(index))
->GetComputedValues()
.font_size() -
font) < .05f,
"Option font changed from trigger font");
auto *row = f.node("native-select-option-0");
auto *art = row->QuerySelector(".fixture-check-art"),
*caption = row->QuerySelector(".native-select-text"),
*slot = row->QuerySelector(".native-select-check");
require(art && caption && slot, "Check or caption box disappeared");
const auto mark = art->GetBox().GetSize(Rml::BoxArea::Border),
text = caption->GetBox().GetSize(Rml::BoxArea::Border);
require(mark.x > 0 && mark.y > 0 && text.x > 0 && text.y > 0,
"Check/text geometry collapsed");
require(caption->GetAbsoluteOffset(Rml::BoxArea::Border).x >=
art->GetAbsoluteOffset(Rml::BoxArea::Border).x + mark.x - 1,
"Check art overlaps caption");
require(std::abs(slot->GetBox().GetSize(Rml::BoxArea::Border).x -
(id == "league" ? 34 : 28) * f.ratio) < 1,
"Check slot differs from style geometry");
f.key(Rml::Input::KI_END);
require(f.cursor() == 29 &&
f.menu->snapshot().at("scroll_top").get<float>() > 0,
"End did not scroll long menu");
const float end_scroll = f.menu->snapshot().at("scroll_top").get<float>();
auto *last = f.node("native-select-option-29");
const auto at = last->GetAbsoluteOffset(Rml::BoxArea::Border),
size = last->GetBox().GetSize(Rml::BoxArea::Border);
const auto top = popup->GetAbsoluteOffset(Rml::BoxArea::Border),
height = popup->GetBox().GetSize(Rml::BoxArea::Border);
require(at.y >= top.y - 1 && at.y + size.y <= top.y + height.y + 2,
"End cursor remains clipped outside popup");
f.key(Rml::Input::KI_HOME);
const auto first_at = f.node("native-select-option-0")
->GetAbsoluteOffset(Rml::BoxArea::Border);
const auto first_size = f.node("native-select-option-0")
->GetBox()
.GetSize(Rml::BoxArea::Border);
const auto home_top = popup->GetAbsoluteOffset(Rml::BoxArea::Border),
home_size = popup->GetBox().GetSize(Rml::BoxArea::Border);
const float home_scroll = f.menu->snapshot().at("scroll_top").get<float>();
if (!(f.cursor() == 0 && home_scroll < end_scroll &&
first_at.y >= top.y - 1 &&
first_at.y + first_size.y <= top.y + height.y + 2)) {
std::cerr << "HOME DIAGNOSTIC id=" << id << " density=" << f.ratio
<< " old_popup=[" << top.x << ',' << top.y << ',' << height.x
<< ',' << height.y << "] new_popup=[" << home_top.x << ','
<< home_top.y << ',' << home_size.x << ',' << home_size.y
<< "] first_row=[" << first_at.x << ',' << first_at.y << ','
<< first_size.x << ',' << first_size.y
<< "] scroll_top=" << home_scroll
<< " end_scroll=" << end_scroll << " cursor=" << f.cursor()
<< " fresh_geometry_pass="
<< (f.cursor() == 0 && home_scroll < end_scroll &&
first_at.y >= home_top.y - 1 &&
first_at.y + first_size.y <= home_top.y + home_size.y + 2)
<< '\n';
}
require(f.cursor() == 0 &&
f.menu->snapshot().at("scroll_top").get<float>() < end_scroll &&
first_at.y >= top.y - 1 &&
first_at.y + first_size.y <= top.y + height.y + 2,
"Home did not return to visible first row");
require(f.native(id)->GetValue() == "0" && f.host.changes[id] == 0,
"Scrolling navigated native committed value");
f.escape();
}
f.opening("bottom");
f.bounded("bottom", false);
f.escape();
f.opening("edge");
f.bounded("edge", true);
require(
f.node("native-select-menu")->GetAbsoluteOffset(Rml::BoxArea::Border).x <
f.node("edge")->GetAbsoluteOffset(Rml::BoxArea::Border).x,
"Narrow right-edge trigger did not clamp popup left");
f.escape();
}
void lifecycle(Fixture &f) {
const auto commits = f.host.commits.size();
const int changes = f.host.changes["basic"];
f.opening("basic");
f.native("basic")->SetAttribute("disabled", "disabled");
f.settle();
require(!f.menu->is_open() && f.host.commits.size() == commits &&
f.host.changes["basic"] == changes,
"Disabling open owner committed a value");
f.native("basic")->RemoveAttribute("disabled");
f.settle();
f.opening("basic");
f.menu->before_render();
f.host.populating = true;
f.node("canvas")->SetInnerRML(contents("apfel"));
f.settle();
f.host.populating = false;
require(
!f.menu->is_open() && f.native("basic")->GetValue() == "apfel" &&
f.host.commits.size() == commits,
"Normal DOM replacement retained popup or committed obsolete control");
f.opening("basic");
f.host.populating = true;
f.node("canvas")->SetInnerRML(contents("apfel"));
f.settle();
f.host.populating = false;
require(!f.menu->is_open() && f.host.commits.size() == commits,
"Removed owner did not invalidate open popup lifetime");
const auto snapshot = f.menu->snapshot();
require(!snapshot.at("open").get<bool>() &&
snapshot.at("id").get<std::string>().empty() &&
snapshot.at("cursor").get<int>() == -1,
"Closed snapshot retained stale owner/cursor");
}
} // namespace
int main(int argc, char **argv) try {
require(argc == 2, "Pass the Modern asset directory");
const auto assets = std::filesystem::path(argv[1]);
Renderer renderer;
System system;
Rml::SetRenderInterface(&renderer);
Rml::SetSystemInterface(&system);
require(Rml::Initialise(), "Rml initialization failed");
require(Rml::LoadFontFace((assets / "LatoLatin-Regular.ttf").string(),
"Modern", Rml::Style::FontStyle::Normal,
Rml::Style::FontWeight::Normal),
"Regular font missing");
require(Rml::LoadFontFace((assets / "LatoLatin-Bold.ttf").string(), "Modern",
Rml::Style::FontStyle::Normal,
Rml::Style::FontWeight::Bold),
"Bold font missing");
std::ostringstream css;
for (const auto *name :
{"theme.rcss", "entry.rcss", "settings.rcss", "select_menu.rcss"}) {
std::ifstream input(assets / name);
require(bool(input), "Production stylesheet missing");
css << input.rdbuf() << '\n';
}
for (const auto *theme : {"midnight", "silver", "matchday"})
for (float density : {1.f / 3, .5f, 1.f, 2.f}) {
std::cerr << "SelectMenu " << theme << " density=" << density << '\n';
Fixture fixture(css.str(), theme, density);
require(system.stylesheet_errors == 0,
"Rml rejected a production stylesheet property");
interaction(fixture);
geometry(fixture);
lifecycle(fixture);
}
Rml::Shutdown();
std::cout << "PASS real Rml select menu input: commit/reselect/cancel, "
"Unicode, focus/scroll, theme/fonts/geometry and owner lifetime "
"in 3 themes at 4 densities\n";
return 0;
} catch (const std::exception &error) {
std::cerr << error.what() << '\n';
return 1;
}