Files
Dreierpack-Manager/tests/modern_control_layout_tests.cpp
T

361 lines
21 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
// Exercise the production control builder and stylesheet with synthetic labels.
#include "modern/ui/controls.hpp"
#include "modern/ui/script_locator.hpp"
#include "modern/ui/postmatch_eleven_markup.hpp"
#include <RmlUi/Core/ElementText.h>
#include <RmlUi/Core/Elements/ElementFormControlSelect.h>
#include <RmlUi/Core/FontEngineInterface.h>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <sstream>
#include <stdexcept>
using namespace bmh::modern_ui;
namespace {
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;
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;
}
};
void text_centers(Rml::Element &node, float cx, float cy, bool horizontal,
size_t &lines) {
if (auto *text = dynamic_cast<Rml::ElementText *>(&node)) {
const auto origin = text->GetAbsoluteOffset();
const auto metrics = Rml::GetFontEngineInterface()->GetFontMetrics(
text->GetFontFaceHandle());
for (const auto &line : text->GetLines()) {
if (line.text.empty())
continue;
++lines;
const float x = origin.x + line.position.x + line.width / 2.f;
const float y = origin.y + line.position.y - metrics.ascent +
(metrics.ascent + metrics.descent) / 2.f;
require(std::abs(y - cy) <= .8f,
"Control text is not vertically centered");
if (horizontal)
require(std::abs(x - cx) <= .8f,
"Control text is not horizontally centered");
}
}
for (int i = 0; i < node.GetNumChildren(); ++i)
text_centers(*node.GetChild(i), cx, cy, horizontal, lines);
}
void centered_text(Rml::Element &text_root, Rml::Element &control,
bool horizontal = true) {
const auto p = control.GetAbsoluteOffset(Rml::BoxArea::Border),
s = control.GetBox().GetSize(Rml::BoxArea::Border);
size_t lines = 0;
text_centers(text_root, p.x + s.x / 2, p.y + s.y / 2, horizontal, lines);
require(lines == 1, "A control label disappeared or wrapped");
}
size_t visible_text_lines(Rml::Element &node) {
size_t count = 0;
if (auto *text = dynamic_cast<Rml::ElementText *>(&node))
for (const auto &line : text->GetLines())
if (!line.text.empty() && line.width > 0) ++count;
for (int i = 0; i < node.GetNumChildren(); ++i)
count += visible_text_lines(*node.GetChild(i));
return count;
}
struct ClickListener final : Rml::EventListener {
int clicks = 0;
void ProcessEvent(Rml::Event &event) override {
if (event.GetType() == "click")
++clicks;
}
};
void script_locator_cases(Rml::Context &context, float density) {
struct Case {
const char *transform;
Rml::Vector2f expected;
bool blocked;
};
for (const auto &test :
{Case{"none", {700, 730}, false},
Case{"translate(70dp,-160dp)", {770, 570}, false},
Case{"scale(1.5)", {800, 795}, false},
Case{"rotate(90deg)", {370, 800}, false}, Case{"scale(0)", {}, true},
Case{"none", {}, true}}) {
const bool covered = test.blocked && std::string(test.transform) == "none";
auto *doc = context.LoadDocumentFromMemory(
"<rml><head><style>body{margin:0;font-family:Modern;font-size:20dp;}"
"#parent{position:absolute;left:500dp;top:600dp;width:600dp;height:"
"300dp;transform-origin:0 0;transform:" +
std::string(test.transform) +
";}"
"#target{position:absolute;left:100dp;top:80dp;width:200dp;height:"
"100dp;margin:0;padding:0;border:0;}"
"#label{position:absolute;left:0;right:0;top:0;bottom:0;}"
"#cover{position:absolute;left:500dp;top:600dp;width:600dp;height:"
"300dp;z-index:999;}"
"</style></head><body><div id='parent'><button id='target'><span "
"id='label'>Click</span></button></div>" +
(covered ? std::string("<div id='cover'></div>") : std::string()) +
"</body></rml>");
require(doc, "Script locator document missing");
doc->Show();
context.Update();
context.Render();
auto *target = doc->GetElementById("target");
const auto point = script_click_point(context, *target);
if (test.blocked)
require(!point,
"Singular/covered locator silently clicks another element");
else {
require(bool(point),
"Transformed script locator rejected visible control");
require(std::abs(point->x - test.expected.x * density) <= 1.f &&
std::abs(point->y - test.expected.y * density) <= 1.f,
"Script locator did not map the visible transformed center");
ClickListener listener;
target->AddEventListener("click", &listener);
context.ProcessMouseMove(point->x, point->y, 0);
context.ProcessMouseButtonDown(0, 0);
context.ProcessMouseButtonUp(0, 0);
require(listener.clicks == 1,
"Script locator point did not click requested control");
target->RemoveEventListener("click", &listener);
}
doc->Close();
context.Update();
}
}
void postmatch_eleven_cases(Rml::Context &context,const std::string &css,const char *theme) {
const auto fixture=std::filesystem::path(__FILE__).parent_path()/"fixtures/modern_post_match_eleven.json";
std::ifstream file(fixture);require(bool(file),"Synthetic supplied eleven fixture missing");
const auto data=Json::parse(file).at("eleven");
const PostmatchBadge badge=[](const Json &,double size){return "<span style='width:"+std::to_string(size)+"dp;height:"+std::to_string(size)+"dp;'>B</span>";};
const auto markup=postmatch_eleven_markup(data,badge,"<div class='image-frame'></div>");
auto *doc=context.LoadDocumentFromMemory("<rml><head><style>"+css+"</style></head><body class='"+theme+"'><section class='postmatch' style='width:2612dp;height:1460dp;'>"+markup+"</section></body></rml>");
require(doc,"Supplied eleven document missing");doc->Show();context.Update();context.Render();fit_postmatch_pitch(*doc);context.Update();context.Render();
Rml::ElementList field,list;doc->QuerySelectorAll(field,".postmatch-field-player");doc->QuerySelectorAll(list,".postmatch-nominee-name");require(field.size()==11&&list.size()==11,"Supplied eleven must render eleven field and list controls");
auto *pitch=doc->GetElementById("postmatch-pitch-surface");const auto bounds=pitch->GetBox().GetSize(Rml::BoxArea::Content);require(std::abs(bounds.x/bounds.y-740.f/1110.f)<.003f,"Supplied eleven field aspect changed");
for(size_t i=0;i<field.size();++i){require(bool(script_click_point(context,*field[i])),"Nominee field control is clipped/occluded");require(visible_text_lines(*list[i])>0,"Nominee full name lost its text");}
doc->Close();context.Update();
const auto detail=postmatch_nominee_detail(data.at("rows")[0],badge);
auto *dialog=context.LoadDocumentFromMemory("<rml><head><style>"+css+"</style></head><body class='"+theme+"'><div class='entry-dialog postmatch-dialog' style='position:absolute;left:100dp;top:100dp;'>"+detail+"</div></body></rml>");
require(dialog,"Nominee detail missing");dialog->Show();context.Update();context.Render();Rml::ElementList facts;dialog->QuerySelectorAll(facts,"dd");require(facts.size()==2&&visible_text_lines(*facts[0])>0&&visible_text_lines(*facts[1])>0,"Nominee position/unknown rating must render");dialog->Close();context.Update();
}
} // namespace
int main(int argc, char **argv) try {
require(argc == 2, "Pass the Modern asset directory");
const auto root = std::filesystem::path(argv[1]);
Renderer renderer;
System system;
Rml::SetRenderInterface(&renderer);
Rml::SetSystemInterface(&system);
require(Rml::Initialise(), "Rml initialization");
require(Rml::LoadFontFace((root / "LatoLatin-Regular.ttf").string(), "Modern",
Rml::Style::FontStyle::Normal,
Rml::Style::FontWeight::Normal),
"Font missing");
require(Rml::LoadFontFace((root / "LatoLatin-Bold.ttf").string(), "Modern",
Rml::Style::FontStyle::Normal,
Rml::Style::FontWeight::Bold),
"Bold font missing");
require(Rml::LoadFontFace((root / "LatoLatin-BoldItalic.ttf").string(), "Modern",
Rml::Style::FontStyle::Italic,
Rml::Style::FontWeight::Bold),
"Bold italic font missing");
std::ostringstream css;
for (const auto *name : {"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", "postmatch.rcss"}) {
std::ifstream input(root / 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}) {
auto *context = Rml::CreateContext(
"controls", {int(3840 * density), int(2160 * density)});
require(context, "Context missing");
context->SetDensityIndependentPixelRatio(density);
const auto select = [](const std::string &id) {
return "<select id='" + id +
"'><option value='a' selected>Option A</option><option "
"value='b'>Option B</option><option value='c'>Option "
"C</option></select>";
};
std::string content =
button_markup("decrease", "−", {},
"id='step' "
"style='position:absolute;left:40dp;top:40dp;width:"
"94dp;height:124dp;font-size:72dp;padding:0;' ");
content += button_markup(
"region", "Region", {},
"id='region' "
"style='position:absolute;left:200dp;top:40dp;min-height:86dp;' ");
content += button_markup("list", "Sample slot", "choice",
"id='list' "
"style='position:absolute;left:40dp;top:220dp;"
"width:600dp;height:120dp;text-align:left;' ");
content += button_markup(
"rich",
"<div class='picture' style='height:100dp;'>Image</div><p "
"class='caption'>Portrait</p>",
"choice",
"id='rich' "
"style='position:absolute;left:700dp;top:40dp;width:250dp;height:"
"260dp;' ");
content +=
"<div style='position:absolute;left:1200dp;top:40dp;width:1294dp;height:94dp;'>" +
button_markup("statistics-absolute", "<span id='stats-scale-label' class='statistics-cell-text'>REL.</span>",
"statistics-action statistics-absolute", "style='left:0;top:0;width:100%;height:94dp;'") + "</div>" +
"<div class='statistics-cell statistics-col-0' style='position:absolute;left:1200dp;top:160dp;width:1000dp;height:80dp;'>" +
button_markup("player-detail", "<span id='stats-player-label' class='statistics-cell-text'>Synthetic player</span>",
"statistics-player-link") + "</div>" +
"<div class='statistics-cell statistics-col-0' style='position:absolute;left:1200dp;top:260dp;width:1000dp;height:80dp;'>" +
button_markup("statistics-trophy", "<span class='statistics-world-trophy-art'></span><span id='stats-world-label' class='statistics-cell-text'>WM 2098</span>",
"statistics-world-trophy") + "</div>" +
"<div style='position:absolute;left:2300dp;top:160dp;width:1000dp;height:80dp;'>" +
button_markup("club-detail", "<span id='stats-from-label' class='report-club-name'>Synthetic source club</span><span style='width:42dp;height:42dp;'></span>",
"report-club-button statistics-club name-first") + "</div>" +
"<span id='news-brand-test' class='news-wordmark' style='position:absolute;left:2700dp;top:280dp;'>kicker</span>" +
"<div class='statistics-trophy-winner' style='left:2700dp;top:430dp;width:900dp;height:100dp;font-size:70dp;'>" +
"<div class='image-frame' style='width:100dp;height:100dp;'></div><span id='stats-winner-label'>Sample winner</span></div>" +
button_markup("statistics-curve", "<span class='statistics-series-dot'></span><span id='stats-legend-label' class='statistics-series-label'>Mannschaftsstärke</span>",
"statistics-action statistics-series-button", "style='left:2700dp;top:580dp;width:836dp;height:82dp;'");
content +=
"<div "
"style='position:absolute;left:40dp;top:400dp;width:2608dp;height:"
"1000dp;'>" +
select("natural") +
"<div class='toolbar' "
"style='position:absolute;top:140dp;width:2500dp;'>" +
select("toolbar") +
"</div><div style='position:absolute;top:280dp;width:1200dp;'>" +
select("manager-strength") + "</div><div class='bottom-controls'>" +
button_markup("continue", "Continue", {}, "id='footer'") +
select("tall") + "</div></div>";
content += "<div style='position:absolute;left:2700dp;top:800dp;width:1100dp;'>"
"<div class='settings-row'><label><span id='settings-row-label'>Automatische Aufstellung</span>"
"<small id='settings-row-help'>Aufgaben an den Co-Trainer abgeben.</small></label>"
"<select id='settings-control' class='settings-select'><option selected>1920 × 1080</option>"
"<option>3840 × 2160</option></select></div>"
"<div class='settings-jump-label'><select id='settings-jump-test' class='settings-select'>"
"<option selected>Spielablauf und Wettbewerbe</option><option>Ergebnisse</option></select></div></div>";
content += "<div class='desktop-card desk-card' style='left:40dp;top:1500dp;width:472dp;height:472dp;'>"
"<div id='month-box' class='desk-calendar-month'><span id='month-label'>Juli 2032</span></div></div>"
"<button class='desk-warning' style='left:700dp;top:1500dp;width:180dp;height:176dp;'><span class='status-lamp'></span>"
"<span id='warning-label' class='warning-caption'>Kontostand</span></button>"
"<div class='desk-card' style='position:absolute;left:1100dp;top:1500dp;width:968dp;height:472dp;'>"
"<div class='desk-fixture'><div><span id='fixture-label'>Synthetic Club</span></div></div></div>";
content += "<div id='gallery-scroll-test' class='modern-widget-gallery' style='left:2700dp;top:1500dp;width:900dp;height:200dp;max-height:200dp;'>"
"<div style='position:relative;height:1000dp;'><article class='widget-gallery-item' style='top:600dp;'></article></div></div>";
content += "<div class='main-options' style='left:40dp;top:2020dp;'>" +
button_markup("load", "<span id='front-test-label'>Spiel laden</span><span class='front-hover-arrow'>›</span>", "front-menu-action", "id='front-test-button'") + "</div>"
"<div class='front-mod-entry' style='position:absolute;left:2100dp;top:1800dp;width:1100dp;'>"
"<span class='front-mod-copy'><strong id='mod-test-name'>Synthetic world</strong><small><span>OpenBMH</span></small></span><span class='front-mod-type'>Modern</span></div>";
auto *doc = context->LoadDocumentFromMemory(
"<rml><head><style>" + css.str() + "</style></head><body class='" +
theme + "'>" + content + "</body></rml>");
require(doc, "Document missing");
require(system.stylesheet_errors == 0,
"Rml rejected a production stylesheet declaration");
doc->Show();
context->Update();
context->Render();
for (int i = 0; i < 3; ++i) {
if (center_selects(*doc))
context->Update();
context->Render();
}
require(doc->GetElementById("gallery-scroll-test")->GetScrollHeight() > doc->GetElementById("gallery-scroll-test")->GetClientHeight()*2,"Gallery content does not contribute to scroll extent");
require(!center_selects(*doc), "Control centering does not settle");
for (const auto *id : {"stats-scale-label", "stats-legend-label", "stats-player-label", "stats-world-label", "stats-from-label", "stats-winner-label", "news-brand-test", "settings-row-label", "settings-row-help", "month-label", "warning-label", "fixture-label", "front-test-label", "mod-test-name"}) {
auto *label = doc->GetElementById(id);
require(label && label->GetBox().GetSize(Rml::BoxArea::Content).x > 0 && visible_text_lines(*label) > 0,
"A production statistics/news label has collapsed or lost its font face");
}
for (const auto *id : {"step", "region", "footer"}) {
auto *button = doc->GetElementById(id);
require(button, "Button missing");
centered_text(*button, *button);
}
centered_text(*doc->GetElementById("month-label"), *doc->GetElementById("month-box"));
centered_text(*doc->GetElementById("front-test-label"),*doc->GetElementById("front-test-button"),false);
auto *list = doc->GetElementById("list");
centered_text(*list, *list, false);
auto *rich = doc->GetElementById("rich");
require(!rich->IsClassSet("control-button"),
"Rich card became a horizontal text control");
require(rich->QuerySelector(".caption")->GetAbsoluteOffset().y >
rich->QuerySelector(".picture")->GetAbsoluteOffset().y,
"Rich card stacking changed");
for (const auto *id :
{"natural", "toolbar", "tall", "manager-strength", "settings-control", "settings-jump-test"}) {
auto *control = doc->GetElementById(id);
auto *caption = select_part(*control, "selectvalue"),
*arrow = select_part(*control, "selectarrow");
require(caption && arrow, "Select parts missing");
centered_text(*caption, *control, false);
const auto y = control->GetAbsoluteOffset(Rml::BoxArea::Border).y +
control->GetBox().GetSize(Rml::BoxArea::Border).y / 2;
require(std::abs(arrow->GetAbsoluteOffset(Rml::BoxArea::Border).y +
arrow->GetBox().GetSize(Rml::BoxArea::Border).y / 2 -
y) < .8f,
"Dropdown arrow is off center");
auto *select_control =
dynamic_cast<Rml::ElementFormControlSelect *>(control);
select_control->ShowSelectBox();
context->Update();
context->Render();
auto *option = select_control->GetOption(0);
require(option->GetComputedValues().font_size() ==
control->GetComputedValues().font_size(),
"Dropdown popup font differs from its caption");
require(option->GetComputedValues().line_height().value <
control->GetBox().GetSize(Rml::BoxArea::Content).y ||
std::string(id) == "natural",
"Caption centering leaked into popup rows");
select_control->CancelSelectBox();
context->Update();
}
doc->Close();
context->Update();
script_locator_cases(*context,density);
Rml::RemoveContext("controls");
}
Rml::Shutdown();
std::cout << "Control text, dropdown arrows, popup fonts and rich cards "
"passed in 3 themes at 4 densities\n";
} catch (const std::exception &e) {
std::cerr << e.what() << '\n';
return 1;
}