diff --git a/assets/modern/live.rcss b/assets/modern/live.rcss new file mode 100644 index 0000000..583bb22 --- /dev/null +++ b/assets/modern/live.rcss @@ -0,0 +1,122 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ +/* Selected text-only Gold layout in the existing 3840x2160 logical canvas. */ +body {--live-bg:#0e1d27;--live-surface:#182b38e8;--live-wash:#d2e6f40b;--live-selected:#a0c8ba18;--live-line:#c2d8e52c;--live-accent:#b5dbd2;--live-muted:#a8bfcb;--live-text:#eaf2f6;} +body.silver {--live-bg:#e8eff5;--live-surface:#edf3f9f5;--live-wash:#7595ac12;--live-selected:#6f9db128;--live-line:#617e9438;--live-accent:#376b84;--live-muted:#5a7181;--live-text:#293e4c;} +body.matchday {--live-bg:#242426;--live-surface:#302f34ec;--live-wash:#efc7ce0a;--live-selected:#efb2aa18;--live-line:#e6d2d52c;--live-accent:#efb2aa;--live-muted:#bbb6bb;--live-text:#f2ebee;} +.live-stage {position:absolute;left:0;top:0;width:3840dp;height:2160dp;color:var(--live-text);background-color:var(--live-bg);font-family:Modern;font-size:40dp;} +.live-stage h1,.live-stage h2,.live-stage h3,.live-stage p {margin:0;} +.live-stage button {display:flex;align-items:center;justify-content:center;min-width:0;gap:16dp;background-color:var(--live-wash);color:var(--live-text);border:2dp var(--live-line);border-radius:18dp;font-size:36dp;font-weight:normal;} +.live-stage button:hover,.live-stage button:focus-visible {border-color:var(--live-accent);background-color:var(--live-selected);} +.live-stage button:disabled {opacity:0.45;} +.live-stage .selected {background-color:var(--live-selected);color:var(--live-accent);border-color:var(--live-accent);} +.live-stage button>span,.live-stage h1>span,.live-stage h2>span,.live-stage h3>span,.live-stage p>span {display:block;min-width:0;} +.live-header {position:absolute;left:128dp;right:128dp;top:0;height:232dp;display:flex;align-items:center;justify-content:space-between;border-bottom:2dp var(--live-line);gap:40dp;} +.live-header>div {display:block;min-width:0;flex:1;} +.live-eyebrow {display:block;font-size:30dp;letter-spacing:4dp;color:var(--live-muted);margin-bottom:14dp;} +.live-header h1 {font-size:60dp;font-weight:normal;} +.live-demo-tag {display:block;font-size:28dp;color:var(--live-accent);border:2dp var(--live-line);border-radius:32dp;padding:14dp 24dp;flex-shrink:0;} +.live-body {position:absolute;left:128dp;right:128dp;top:280dp;height:1684dp;display:flex;gap:44dp;} +.live-left {width:2096dp;min-width:0;flex-shrink:0;display:flex;flex-direction:column;gap:36dp;height:100%;} +.live-panel {background-color:var(--live-surface);border:2dp var(--live-line);border-radius:32dp;overflow:hidden;min-width:0;min-height:0;} +.live-overview {flex-shrink:0;} +.live-coverage {height:110dp;display:flex;align-items:center;gap:14dp;padding:18dp 30dp;border-bottom:2dp var(--live-line);} +.live-coverage button {height:72dp;padding:0 26dp;font-size:32dp;} +.live-clock {display:block;margin-left:auto;color:var(--live-accent);font-size:44dp;flex-shrink:0;} +.live-cards {padding:24dp;display:flex;flex-wrap:wrap;gap:20dp;} +.live-stage .live-game {width:48%;flex-grow:1;flex-shrink:0;height:178dp;min-width:0;display:block;border:2dp var(--live-line);border-radius:22dp;background-color:var(--live-wash);padding:12dp 22dp;} +.live-coverage .live-match-arrow {width:70dp;padding:0;} +.live-cards.single .live-game {width:100%;} +.live-game.active {border-color:var(--live-accent);} +.live-owners {display:block;font-size:24dp;color:var(--live-accent);text-align:center;margin-bottom:8dp;height:30dp;overflow:hidden;white-space:nowrap;} +.live-scoreline {height:68dp;display:flex;align-items:center;justify-content:center;gap:16dp;min-width:0;} +.live-team-name {display:block;flex:1;min-width:0;font-size:31dp;max-height:78dp;overflow:hidden;line-height:1.2;} +.live-team-name.home {text-align:right;} +.live-team-name.away {text-align:left;} +.live-score {display:block;font-size:64dp;font-weight:normal;flex-shrink:0;text-align:center;min-width:134dp;white-space:nowrap;} +.live-card-caption {display:block;font-size:22dp;color:var(--live-muted);text-align:center;margin-top:8dp;} +.live-badge {display:flex;align-items:center;justify-content:center;flex-shrink:0;} +.live-ticker {display:flex;flex-direction:column;flex:1;min-height:0;} +.live-panel-heading {height:108dp;padding:24dp 42dp;display:flex;align-items:center;justify-content:space-between;gap:24dp;border-bottom:2dp var(--live-line);flex-shrink:0;} +.live-panel-heading h2 {display:block;min-width:0;flex:1;font-size:42dp;font-weight:normal;} +.live-small {display:block;font-size:28dp;color:var(--live-muted);} +.live-filters {display:flex;align-items:center;gap:14dp;padding:18dp 32dp;border-bottom:2dp var(--live-line);flex-shrink:0;} +.live-filters button {height:64dp;padding:0 24dp;font-size:30dp;} +.live-event-list {display:block;flex:1;min-height:0;overflow-y:auto;overflow-x:hidden;} +.live-event {display:flex;align-items:flex-start;gap:24dp;padding:30dp 40dp;border-bottom:2dp var(--live-line);} +.live-event.is-goal {background-color:var(--live-selected);} +.live-event-time {display:block;width:116dp;flex-shrink:0;color:var(--live-muted);font-size:31dp;line-height:1.5;} +.live-event-copy {display:block;flex:1;min-width:0;} +.live-event-copy h3 {display:block;width:100%;font-size:38dp;font-weight:normal;line-height:1.25;} +.live-event-copy p {display:block;width:100%;font-size:32dp;line-height:1.4;color:var(--live-muted);margin-top:12dp;} +.live-event-owners {display:block;color:var(--live-accent);font-size:25dp;margin-bottom:10dp;} +.live-event-score {display:block;font-size:31dp;color:var(--live-muted);min-width:72dp;text-align:right;flex-shrink:0;} +.live-ticker-footer {height:94dp;display:flex;align-items:center;justify-content:space-between;gap:20dp;padding:20dp 38dp;border-top:2dp var(--live-line);flex-shrink:0;} +.live-detail {flex:1;min-width:0;display:flex;flex-direction:column;height:100%;} +.live-detail>.live-panel-heading {height:134dp;padding:24dp 42dp;} +.live-detail-heading {display:block;min-width:0;flex:1;} +.live-detail-heading h2 {display:block;width:100%;font-size:40dp;line-height:1.2;} +.live-detail-heading p {display:block;width:100%;font-size:27dp;color:var(--live-muted);margin-top:10dp;} +.live-team-switch {display:flex;gap:14dp;flex-shrink:0;} +.live-team-switch button {width:74dp;height:70dp;padding:0;} +.live-tabs {display:flex;gap:12dp;padding:24dp 26dp;border-bottom:2dp var(--live-line);flex-shrink:0;} +.live-tabs button {height:66dp;padding:0 14dp;font-size:31dp;flex:1;} +.live-detail-body {display:block;flex:1;min-height:0;overflow-y:auto;overflow-x:hidden;} +.live-detail-footer {height:112dp;display:flex;align-items:center;gap:20dp;padding:22dp 36dp;border-top:2dp var(--live-line);flex-shrink:0;} +.live-detail-footer button {height:70dp;padding:0 28dp;font-size:32dp;} +.live-roster {padding:18dp 36dp;} +.live-roster-row {height:66dp;display:flex;gap:16dp;align-items:center;border-bottom:2dp var(--live-line);font-size:32dp;} +.live-roster-row.heading {height:56dp;font-size:24dp;color:var(--live-muted);} +.live-roster-number {display:block;width:64dp;flex-shrink:0;} +.live-roster-name {display:block;min-width:0;flex:1;overflow:hidden;white-space:nowrap;} +.live-roster-stat {display:block;width:90dp;flex-shrink:0;text-align:right;} +.live-roster-note {display:block;margin:20dp 0 12dp;color:var(--live-accent);font-size:27dp;line-height:1.35;} +.live-note {display:block;color:var(--live-muted);font-size:28dp;line-height:1.5;padding:28dp 40dp;} +.live-note>span {display:block;} +.live-context {padding:36dp 42dp;} +.live-context h3 {display:block;font-size:40dp;font-weight:normal;line-height:1.3;} +.live-context p {display:block;font-size:31dp;color:var(--live-muted);line-height:1.5;margin-top:20dp;} +.live-context button {height:76dp;padding:0 32dp;margin-top:28dp;font-size:32dp;} +.live-pitch {width:100%;height:630dp;display:flex;align-items:center;justify-content:center;margin-top:30dp;} +.live-stat {padding:26dp 42dp;} +.live-stat-label {display:flex;justify-content:space-between;align-items:center;gap:20dp;font-size:36dp;} +.live-stat-label>span {display:block;min-width:0;} +.live-stat-label>.stat-title {font-size:31dp;color:var(--live-muted);text-align:center;flex:1;} +.live-stat-bar {margin-top:18dp;height:10dp;display:flex;gap:10dp;} +.live-stat-bar>.home {height:10dp;border-radius:6dp;background-color:var(--live-accent);} +.live-stat-bar>.away {height:10dp;border-radius:6dp;background-color:var(--live-muted);flex:1;opacity:0.4;} +.live-table-row {display:flex;align-items:center;gap:16dp;height:62dp;padding:6dp 24dp;border-bottom:2dp var(--live-line);font-size:30dp;} +.live-table-row.heading {height:78dp;font-size:25dp;color:var(--live-muted);} +.live-table-row.own {background-color:var(--live-selected);border-left:6dp var(--live-accent);padding-left:18dp;} +.live-table-pos {display:block;width:50dp;flex-shrink:0;text-align:center;} +.live-table-team {display:flex;align-items:center;gap:16dp;flex:1;min-width:0;} +.live-table-team>span {display:block;min-width:0;flex:1;overflow:hidden;white-space:nowrap;} +.live-table-number {display:block;width:78dp;flex-shrink:0;text-align:center;} +.live-table-goals {width:100dp;} +.live-speed {position:absolute;left:30dp;top:710dp;width:56dp;display:flex;flex-direction:column;align-items:center;gap:20dp;color:var(--live-muted);font-size:26dp;} +.live-speed>span {display:block;} +#live-speed {width:40dp;height:600dp;padding:0;border:0;background-color:transparent;} +#live-speed slidertrack {width:8dp;height:600dp;margin:0 16dp;border-radius:4dp;background-color:var(--live-line);} +#live-speed sliderbar {width:30dp;height:30dp;margin:0;border:0;border-radius:15dp;background-color:var(--live-accent);} +#live-speed sliderarrowdec,#live-speed sliderarrowinc {width:0;height:0;} +.live-speed-value {display:block;text-align:center;font-size:23dp;white-space:nowrap;} +.live-bottom {position:absolute;left:128dp;right:128dp;bottom:0;height:184dp;display:flex;align-items:center;justify-content:space-between;gap:30dp;} +.live-bottom-actions {display:flex;align-items:center;gap:24dp;flex-shrink:0;} +.live-bottom button {height:100dp;padding:0 40dp;font-size:36dp;} +.live-bottom-note {display:block;flex:1;min-width:0;text-align:center;font-size:28dp;color:var(--live-muted);line-height:1.4;} +.live-feedback {position:absolute;left:128dp;right:128dp;bottom:184dp;padding:18dp 32dp;background-color:var(--live-surface);border:2dp var(--live-line);border-radius:18dp;font-size:30dp;color:var(--live-accent);} +.live-dialog-layer {position:absolute;left:0;top:0;right:0;bottom:0;background-color:#051019a8;display:flex;align-items:center;justify-content:center;} +.live-dialog {width:2200dp;max-height:1780dp;padding:54dp;border:2dp var(--live-line);border-radius:28dp;background-color:var(--live-bg);display:flex;flex-direction:column;gap:30dp;} +.live-dialog h2 {display:block;width:100%;font-size:46dp;font-weight:normal;} +.live-dialog p {display:block;width:100%;color:var(--live-muted);font-size:32dp;line-height:1.4;} +.live-dialog label {display:block;width:100%;font-size:34dp;} +.live-dialog select {display:block;width:100%;height:88dp;font-size:36dp;margin-top:20dp;} +.live-dialog-actions {display:flex;justify-content:flex-end;gap:24dp;} +.live-dialog-actions button {height:90dp;padding:0 40dp;font-size:34dp;} +.live-tactic-row {display:flex;align-items:center;justify-content:space-between;gap:30dp;padding:16dp 0;border-bottom:2dp var(--live-line);font-size:36dp;} +.live-tactic-row>span {display:block;min-width:0;flex:1;} +.live-tactic-row button {height:76dp;width:760dp;font-size:34dp;} +.live-review {position:absolute;left:128dp;right:128dp;top:280dp;bottom:200dp;padding:50dp;display:flex;flex-direction:column;gap:32dp;overflow-y:auto;} +.live-review h2 {display:block;width:100%;font-size:48dp;font-weight:normal;} +.live-review-card {display:block;padding:36dp;border:2dp var(--live-line);border-radius:24dp;} +.live-review-card .live-scoreline {height:108dp;} +.live-review-card p {display:block;width:100%;font-size:31dp;color:var(--live-muted);margin-top:28dp;line-height:1.4;text-align:center;} diff --git a/assets/modern/modern.rml b/assets/modern/modern.rml index 596c14a..03b7f8a 100644 --- a/assets/modern/modern.rml +++ b/assets/modern/modern.rml @@ -1,6 +1,6 @@ OpenBMH - +
diff --git a/docs/new_ui/NATIVE_STATUS.md b/docs/new_ui/NATIVE_STATUS.md index 6826a09..e22d6ba 100644 --- a/docs/new_ui/NATIVE_STATUS.md +++ b/docs/new_ui/NATIVE_STATUS.md @@ -1,6 +1,6 @@ # Native Modern UI · erster Umsetzungsstand -Stand: 26. Oktober 2026. **Experimenteller RmlUI-Unterbau und erster +Stand: 27. Oktober 2026. **Experimenteller RmlUI-Unterbau und erster bedienbarer Durchlauf. Noch keine vollständige Umsetzung des HTML-Mockups.** Die normale Classic-Konfiguration bleibt unverändert; die neue Oberfläche wird ausdrücklich mit `OPENBMH_BUILD_MODERN_UI=ON` gebaut. @@ -140,8 +140,12 @@ wird ausdrücklich mit `OPENBMH_BUILD_MODERN_UI=ON` gebaut. Hauptschalter. Gemeinsamer Entwurf bis Anwenden, getrennte globale Speicherung und Synchronisierung mit den vier Trainingsautomatiken. -**Anstoß führt keine Aktion aus**, weder per Maus noch per Tastatur. Das gilt -auch für die direkte Aktionsschnittstelle des Demoanbieters. +- [Nativer Live-Ticker](desktop/live/README.md): Anstoß öffnet eine ausdrücklich + markierte, endliche UI-Demoaufzeichnung. Ein bis vier eindeutige menschliche + Partien, gemeinsamer Ticker, unabhängige rechte Managerdetails, drei Skins, + reine Wiedergabepause und lokale Wechsel-/Taktikvorschauen. Rasen endet bei 90, + Halle bei 40 Minuten; es wird keine Enginepartie gestartet oder Saison fortgesetzt. + `DataSource::read_live` bleibt ohne ausdrücklich gebundenen Anbieter unverfügbar. ## Noch offen @@ -149,8 +153,9 @@ Die verbleibenden Routen und Teilbereiche werden in zusammengehörigen Paketen vom HTML-Mockup übertragen. Für fehlende Ports erscheinen keine vereinfachten Ersatzlayouts. Der allgemeine Capture-Katalog zählt 34 direkt zugeordnete Ansichten und drei noch nicht separat zugeordnete Routen. Neuer Spieler und Saisonvorbereitung -werden zusätzlich als echte Bedienfolgen geprüft; Anstoß bleibt bewusst -ohne Aktion. Diese Zuordnungszahl ist kein Fertigstellungsprozentsatz und +werden zusätzlich als echte Bedienfolgen geprüft. Der neue Live-Ticker hat +eine eigene Bedienkohorte; die historische Katalogzählung wird dadurch nicht +als neue vollständige Menüabnahme ausgegeben. Diese Zuordnungszahl ist kein Fertigstellungsprozentsatz und bestätigt keine vollständige gestalterische Abnahme aller Ansichten. Bildschirmkonfiguration und Audioausgabe benötigen noch die Plattform-/Engine-Anbindung der nun gespeicherten UI-Voreinstellungen. Übersetzungen, echte Engine-Anbindung und Plattform-Abnahme diff --git a/docs/new_ui/README.md b/docs/new_ui/README.md index 73e848c..e95ae45 100644 --- a/docs/new_ui/README.md +++ b/docs/new_ui/README.md @@ -19,6 +19,7 @@ Implementierung in der Spiel-Engine. | Spieleinstieg | [Grundeinstellungen, Managerwahl und Bestätigung](main-menu/entry/README.md) | | Saisonvorbereitung | [Teilnehmer, Ziehung und Fortsetzung](main-menu/opening/README.md) | | Desktop | [Statusleiste, Gestaltung und Fenster](desktop/README.md) | +| Live-Ticker-Demo | [Vorgegebene Aufzeichnung, unabhängige Managerdetails und Read-Provider](desktop/live/README.md) | | Manager & Rollen | [Aktive Person, Nationalansicht, Abgabe und Hallenaufgebot](desktop/manager/README.md) | | Widgets | [17 Typen, 48 Größen, Raster, Fixierung und Arbeitsanordnung](desktop/widgets/README.md) | | Dateiverwaltung | [Spielstände und Desktopansichten mit Vorschauen](desktop/save-load/README.md) | diff --git a/docs/new_ui/desktop/live/README.md b/docs/new_ui/desktop/live/README.md new file mode 100644 index 0000000..af45075 --- /dev/null +++ b/docs/new_ui/desktop/live/README.md @@ -0,0 +1,177 @@ + +# Nativer Live-Ticker als UI-Demo (by Codex) + +Der Anstoß-Einstieg der nativen Modern-Demo öffnet ausschließlich den Textticker. +Eine grafische Spielansicht gehört nicht zu diesem Paket. Die Fläche bleibt im +vorhandenen 3840×2160-Canvas proportional 16:9; die drei Skins verwenden dieselbe +Geometrie. Links stehen eine bis vier eindeutige menschliche Partien und ein +geteilter Ticker. Rechts wechseln unabhängige Managerpfeile zwischen Team, +Taktik, Gegner, Live-Tabelle und Statistik. Es gibt keine Schiedsrichterbox, +Manager-Tableiste oben oder leere Eingriffsbox. + +Diese Ansicht spielt eine endliche, vorgegebene **UI-Demoaufzeichnung** ab. Ihre +Ergebnisse, Spielereignisse, Statistik und Tabellenstände sind deklarierte +Fixtures. Die sichtbare Kennzeichnung bleibt beim Abspielen und im Bericht +vorhanden. Weltidentitäten, Namen und vorhandene Spielerattribute stammen aus +dem schreibgeschützten Katalog; unbekannte Attribute bleiben unbekannt. Die +Ansicht konstruiert weder GameState noch Runtime, liest keinen Spiel-RNG und +führt aus einem Timer keine Spielaktion aus. Es entsteht keine zweite +Match-Engine. + +## Provider und Identität + +`DataSource::read_live(const Json&) const` liefert standardmäßig +`{ok:false,error:"live_unavailable"}`. Eine spätere autoritative Sessionanbindung +muss diesen Read ausdrücklich implementieren. Der aktuelle `DemoSource` +überschreibt ihn allein mit dem reinen Provider `query_demo_live`. + +```json +{"kind":"fixture","revision":7} +``` + +Das Ergebnis enthält `ok`, `schema:"openbmh-live-fixture@1"`, +`source:"ui-demo-fixture"`, `fixture_id`, `source_revision`, `world`, `date`, +`role`, `surface`, `duration`, `field_count`, `owners`, `matches` und `frames`. +Die Source-Revision bezeichnet den gelesenen Ausgangszustand; sie ist weder +Ereignissequenz noch Managerauswahl. Die Fixture-ID ist unabhängig von der +rechts gewählten Person. Match-IDs enthalten Welt, Datum, Bereich, Fläche und +beide Teamidentitäten; Owner-IDs verwenden die stabile Porträtidentität. Zwei +menschliche Gegner erscheinen in derselben Partie mit zwei Owner-Referenzen. +Jede Partie und jedes Ereignis hat eine eigene ID. + +```json +{"kind":"frame","sequence":3,"fixture_id":"ui-live:…","revision":7} +``` + +Dieser Read liefert genau einen vorgegebenen Snapshot mit `sequence`, `minute`, +`phase`, Matchwerten und dem bis dahin sichtbaren Ereignisprefix. Wiederholte +Reads sind identisch und verändern weder Sourcezustand/-revision noch +Dirty-Baseline, Weltdateien oder Kalender. Fremde Queryfelder, ungültige +Sequenzen und veraltete Revisionen/Fixture-IDs werden ausdrücklich abgewiesen. +Ein fehlender Provider wird nicht durch geratene Ergebnisse ersetzt. + +Die Aufzeichnung enthält Anpfiff, Heimführung, Verwarnung, Halbzeit, Wiederanpfiff, +Ausgleich, Torchance, erneute Heimführung und Abpfiff. Sie endet nach exakt +90 Minuten auf Rasen und 40 Minuten in der Halle. Diese Werte beschreiben die +Fixture; sie sind keine hinzugefügten Regeln einer Matchsimulation. Ein kurzer +Ergebnis-/Berichtsbildschirm zeigt danach den festgelegten Verlauf, ohne Datum, +Wertung, Konten, Nachrichten oder Saisonfortschritt zu publizieren. + +## Kader- und Bereichsprojektion + +Aktive Personen, Team und Fläche kommen aus `demo_career_context`. Nur die +aktive Nationalrolle stellt Deutschland und den zugehörigen menschlichen Owner +dar; Vereinsfinanzen und eine Vereins-Ligatabelle werden dort nicht eingeblendet. +Die bisherige native Nationaldemo benutzt ausdrücklich die Vereinsaufstellung +als **Demokaderbasis**, nicht als behauptete Nationalkaderberufung. `Caps` und +internationale Tore werden nur bei entsprechenden Katalogattributen angezeigt; +andernfalls steht `—`, nie eine aus Vereinsstatistiken geratene Zahl. + +Für jeden Verein liest der Provider dessen aktuelle Präsentationsaufstellung +und Taktik: beim aktiven Owner direkt, bei inaktiven aus `career_views[club]`. +Unbesuchte Vereine bekommen ausschließlich reine Aufstellungs-/Taktikdefaults, +ohne `Source.apply`. So übernimmt die rechte Ansicht nicht versehentlich den +Kader oder die Änderungen des ersten Managers. + +Hallenfelder bleiben getrennt: `on_field_limit=6`, `rotation_rows=min(11, +roster_size)`, `roster_size` ist die tatsächliche Spielerzahl und +`roster_limit=null`, weil hier keine allgemeine harte Kadergrenze belegt wird. +Die Ansicht gruppiert sechs Aktive, bis zu fünf Partner des ersten 11er-Plans +und weitere vorhandene Reserven. Die komplette echte Kaderliste bleibt lesbar; +interne elf Strukturpunkte machen keine zusätzlichen Feldspieler. Rasen hat +elf aktive Positionen und ebenfalls alle vorhandenen Reserven. Der Provider +leitet daraus keine neue Auswechsel- oder Kaderregel ab. + +Die Live-Tabelle nutzt echte Teamidentitäten, aber ausschließlich vorgegebene +Demozahlen, sichtbar als solche gekennzeichnet. Alle Owner derselben +Katalogkonkurrenz lesen dabei denselben Tabellensnapshot; nur die eigene +Zeilenmarkierung wechselt. Sie rekonstruiert keine +Ligahistorie. Kleine Kataloge liefern weniger Zeilen, höchstens 18 werden in der +Demo-Tabelle dargestellt. Das Nationaldemo-Länderspiel besitzt keine Ligatabelle. + +## Reine Wiedergabe und Eingabe + +`LivePlayback` hält eine lokale Kopie der validierten Aufzeichnung. `next()` +zeigt deren nächsten Snapshot; `elapse(milliseconds)` darf bei Speed 1–4 nur +vorhandene Snapshots enthüllen. Speed 0 ist Pause. Ein verzögertes Fenster +überspringt keinen unbeschränkten Rückstau. Reads, Managerwahl und Tabwechsel +führen keine Ereignisse aus und schreiben keine Savefelder. + +Der dezente senkrechte Regler hat seine Pausenstellung unten. Weil RmlUI-Werte +nach unten wachsen, speichert allein das native Widget den invertierten +Positionswert `4-speed`; API, Snapshot, Beschriftung und ARIA-Wert verwenden die +logische Geschwindigkeit 0–4. Home setzt Pause, End die höchste Stufe, +Pfeil-hoch/-runter ändern die Stufe. `P` und der Abspielen-/Pausebutton bedienen +dieselbe Wiedergabe. Der Regler wird während eines Pointerdrags nicht durch einen +Timerrender ersetzt. + +Die rechte Ownerauswahl verändert weder Sequenz noch den links gewählten Match- +oder Tickerfilter und erhält die Scrollposition des gemeinsamen Tickers. Für ein +Einzelspiel gibt es eigene linke Partiepfeile. Beide Auswahlachsen sind getrennt. +Tab/Escape und Kontextrechtsklick bleiben auf Liveansicht oder offenem Dialog +begrenzt; eine offene gemeinsame Optionsliste behält ihre eigene erste Priorität. + +## Wechsel- und Taktikvorschau + +Aufstellung/Wechsel und Taktik verwenden die vorhandenen reinen Edithelper an +einem **lokalen Ownerentwurf**. Die Dialoge benennen ihre Demogrenze. Eine +Übernahme zeigt nur diese Vorschau; sie sendet kein erfolgreiches Enginekommando, +ändert keine Source-Revision und beeinflusst die feste Ereignisfolge nicht. +Abbrechen verwirft den Entwurf. Die Halle bietet auch weitere vorhandene +Reserven an und erfindet keine zusätzliche Austauschgrenze. + +Beim Öffnen eines Dialogs pausiert die Wiedergabe; nach Schließen kann nur die +vorherige Wiedergabestufe weiterlaufen. Wechselnde Sourceidentität, Welt oder +Revision pausieren einen alten Mitschnitt. Ein erneuter Anstoß liest dann eine +neue Aufzeichnung. Weltwechsel löschen die lokale Wiedergabe und Entwürfe. +Ein normaler Desktop-Rückweg pausiert und kann denselben unveränderten Mitschnitt +später wieder öffnen. Kein Playbackzustand wird in einem Karrierecheckpoint +oder Original-OBW gespeichert. + +## Dateien und Prüfung + +- `demo_live.hpp/.cpp`: reiner Provider, Validierung und finite Playbackklasse. +- `live_state.inc`, `live_screens.inc`, `live_controls.inc`: lokale Appansicht und + Maus-/Tastatureingaben; `assets/modern/live.rcss`: Layout und drei Skins. +- `modern_live_ui_tests`: synthetischer Katalog mit mehreren Menschen, Quellen- + invarianten, identischen Reads, Matchdedupe, Ownerwechsel ohne Seek, reiner + Pause, 40/90-Abschluss, Scopeguards und lokalen Kaderreferenzen. + +Mit `modern_live_ui_tests --write-fixtures ` können reproduzierbare, +synthetische Weltdaten und gültige native Democheckpoints für GUI-Tests erzeugt +werden. Sie enthalten keine Originaldaten. Die abschließende Linux-/SDL-/RmlUI-Kohorte besteht zehn normal beendete +Prozesse mit **1.811 von 1.811 Prüfungen**: alle drei Skins bei 1080 und 720, +geteilte menschliche Partie, tatsächlicher National-/Hallenwechsel über den +Managerhub und ein 3840×2160-Lauf. Geprüft sind echte Maus-/Tastatur-/Mausrad- +Eingaben, gesetzte Themepräferenz, Textflächen, Zweispaltigkeit, native +Optionsauswahl der letzten echten Reserve, Vorschauabbruch/-übernahme, +Home/End/P, unveränderte Source-/Revisions-/Dirty-Werte und Bericht/Rückweg. + +Ein separater echter SDL/X11-Lauf mit physischem Down→Move→Halten→mehrere +Moves→Up besteht 18/18 Prüfungen. In derselben gehaltenen Geste werden Stufen 4, +2 und 0 erreicht; auch über einen fälligen Replayframe hinaus bleibt die Sequenz +bis Pointer-up unverändert. Erst nach Ende der Geste darf das lokale Markup +ersetzt werden; der Regler erhält dann seinen Tastaturfokus zurück. Es gibt +keinen globalen Mouse-Capture-Workaround. + +Die fünf betroffenen CTest-Gruppen `modern_live_ui_tests`, +`modern_career_ui_tests`, `modern_lineup_ui_tests`, `modern_opening_ui_tests` +und `modern_ui_core_tests` sind grün. Die finalen nativen Theme-/Scope-PNGs +wurden tatsächlich gesichtet. Private GUI-Ressourcen und Bildschirmbelege +bleiben außerhalb dieses öffentlichen Repositories. Windows und macOS sind +nicht interaktiv geprüft; dies ist kein Engine- oder Plattformrelease. + +Der wiederholbare native Eingabelauf liegt in +`tools/modern_ui/live_demo_qa.py`. Beispiel mit selbst erzeugten Fixtures: + +```sh +modern_live_ui_tests --write-fixtures /tmp/live-fixtures +python3 tools/modern_ui/live_demo_qa.py \ + --binary /path/to/build/OpenBMH --fixtures /tmp/live-fixtures \ + --gui-assets /path/to/own/gui --output /tmp/live-evidence +``` + +Der Treiber erfindet keine Livezustände: Klick, Taste, Mausrad und Wartezeit +laufen durch die normalen RmlUI-/SDL-Pfade. Die JSON-/DOM-/Geometrieproben und +PNG-Ausgaben bleiben am angegebenen Ziel. Für den eigenen Xvfb werden ein +installiertes `Xvfb` oder alternativ `--display` benötigt. diff --git a/src/modern/ui/CMakeLists.txt b/src/modern/ui/CMakeLists.txt index 8321021..636e5f8 100644 --- a/src/modern/ui/CMakeLists.txt +++ b/src/modern/ui/CMakeLists.txt @@ -1,5 +1,5 @@ # SPDX-License-Identifier: GPL-3.0-only -add_library(bmh_modern_ui_core STATIC catalog.cpp model.cpp demo_career.cpp gui_assets.cpp desktop.cpp demo_sports.cpp demo_calendar.cpp demo_reports.cpp demo_almanac.cpp demo_finance.cpp demo_environment.cpp demo_advertising.cpp demo_toto.cpp demo_lineup.cpp demo_transfer.cpp demo_career_reports.cpp demo_rankings.cpp demo_stadium.cpp demo_statistics.cpp demo_news.cpp demo_settings.cpp ui_preferences.cpp demo_widgets.cpp demo_files.cpp demo_opening.cpp) +add_library(bmh_modern_ui_core STATIC catalog.cpp model.cpp demo_career.cpp gui_assets.cpp desktop.cpp demo_sports.cpp demo_calendar.cpp demo_reports.cpp demo_almanac.cpp demo_finance.cpp demo_environment.cpp demo_advertising.cpp demo_toto.cpp demo_lineup.cpp demo_live.cpp demo_transfer.cpp demo_career_reports.cpp demo_rankings.cpp demo_stadium.cpp demo_statistics.cpp demo_news.cpp demo_settings.cpp ui_preferences.cpp demo_widgets.cpp demo_files.cpp demo_opening.cpp) target_include_directories(bmh_modern_ui_core PUBLIC ../..) target_link_libraries(bmh_modern_ui_core PUBLIC bmh_asset_io) add_library(bmh_modern_ui_mods STATIC mod_library.cpp) @@ -38,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 select_menu.rcss career.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 live.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 career.rcss) configure_file("${CMAKE_SOURCE_DIR}/assets/modern/${asset}" "${modern_assets}/${asset}" COPYONLY) endforeach() @@ -124,7 +124,7 @@ foreach(component environment advertising toto lineup transfer stadium) add_test(NAME modern_${component}_ui_tests COMMAND modern_${component}_ui_tests) endforeach() -foreach(component statistics news settings desktop files entry opening career) +foreach(component statistics news settings desktop files entry opening career live) add_executable(modern_${component}_ui_tests ../../../tests/modern_${component}_ui_tests.cpp) target_link_libraries(modern_${component}_ui_tests PRIVATE bmh_modern_ui_core) if(MSVC) diff --git a/src/modern/ui/controls.inc b/src/modern/ui/controls.inc index 13e3412..cd980f4 100644 --- a/src/modern/ui/controls.inc +++ b/src/modern/ui/controls.inc @@ -148,6 +148,7 @@ void App::ProcessEvent(Rml::Event &event) try { if (n->GetId() == "native-ticket-layer") return; if(front_event(event))return; + if (live_event(event)) return; if (career_event(event)) return; if (entry_event(event)) return; if (opening_event(event)) return; @@ -465,6 +466,7 @@ void App::dispatch(const std::string &action, Rml::Element *target) { const auto id = target ? target->GetAttribute("data-id", "") : std::string(); if(front_action(action,target))return; + if (live_action(action, target)) return; if (career_action(action,target)) return; if (entry_action(action, target)) return; if (opening_action(action, target)) return; @@ -924,6 +926,13 @@ void App::script() { context_->ProcessMouseMove(point.x + (end.x - point.x) * i / 12, point.y + (end.y - point.y) * i / 12, 0); context_->ProcessMouseButtonUp(0, 0); + } else if (type == "wheel") { + const auto point = locate(command); + const float delta = command.at("delta").get(); + if (!std::isfinite(delta) || std::abs(delta) > 1000) + throw editor::Error("UI-Skript: ungültiger Mausradweg."); + context_->ProcessMouseMove(point.x, point.y, 0); + context_->ProcessMouseWheel(delta, 0); } else if (type == "text") context_->ProcessTextInput(command.value("value", std::string())); else if (type == "key") { @@ -934,6 +943,7 @@ void App::script() { {"LEFT", Rml::Input::KI_LEFT}, {"RIGHT", Rml::Input::KI_RIGHT}, {"UP", Rml::Input::KI_UP}, {"DOWN", Rml::Input::KI_DOWN}, {"A", Rml::Input::KI_A}, {"Z", Rml::Input::KI_Z}, {"V", Rml::Input::KI_V}, + {"P", Rml::Input::KI_P}, {"BACKSPACE", Rml::Input::KI_BACK}, {"DELETE", Rml::Input::KI_DELETE}, {"F4", Rml::Input::KI_F4}, {"F10", Rml::Input::KI_F10}, {"CONTEXT", Rml::Input::KI_APPS}, {"0", Rml::Input::KI_0}, {"1", Rml::Input::KI_1}, {"2", Rml::Input::KI_2}, {"3", Rml::Input::KI_3}, {"4", Rml::Input::KI_4}, {"5", Rml::Input::KI_5}, {"6", Rml::Input::KI_6}, {"7", Rml::Input::KI_7}, @@ -955,6 +965,7 @@ void App::script() { pump_events(); front_poll(); opening_tick(); + live_tick(); frame(); SDL_Delay(5); } @@ -969,6 +980,7 @@ void App::script() { editor::path(command.at("path").get()), Json{{"scene", scene_}, {"menu", menu_}, + {"live_view", live_snapshot()}, {"report_picker", report_picker_}, {"planning_dialog", planning_dialog_}, {"bank_view", bank_view_}, {"bank_property", bank_property_}, {"bank_stock", bank_stock_}, @@ -1000,7 +1012,7 @@ void App::script() { .dump(2)); else if(type=="metrics"){ context_->Update();Json rows=Json::array(); - for(const auto &selector:command.at("selectors")){Rml::ElementList nodes;doc_->QuerySelectorAll(nodes,selector.get());for(auto *node:nodes){auto at=node->GetAbsoluteOffset(Rml::BoxArea::Border),size=node->GetBox().GetSize(Rml::BoxArea::Border);rows.push_back({{"selector",selector},{"id",node->GetId()},{"x",at.x},{"y",at.y},{"width",size.x},{"height",size.y},{"scroll_top",node->GetScrollTop()},{"scroll_height",node->GetScrollHeight()},{"client_height",node->GetClientHeight()},{"visible",node->IsVisible(true)}});}} + for(const auto &selector:command.at("selectors")){Rml::ElementList nodes;doc_->QuerySelectorAll(nodes,selector.get());for(auto *node:nodes){auto at=node->GetAbsoluteOffset(Rml::BoxArea::Border),size=node->GetBox().GetSize(Rml::BoxArea::Border);rows.push_back({{"selector",selector},{"id",node->GetId()},{"x",at.x},{"y",at.y},{"width",size.x},{"height",size.y},{"scroll_top",node->GetScrollTop()},{"scroll_height",node->GetScrollHeight()},{"client_height",node->GetClientHeight()},{"font_size",node->GetComputedValues().font_size()},{"rml",node->GetInnerRML()},{"visible",node->IsVisible(true)}});}} editor::write_atomic(editor::path(command.at("path").get()),rows.dump(2)); } else if (type == "dom") diff --git a/src/modern/ui/demo_live.cpp b/src/modern/ui/demo_live.cpp new file mode 100644 index 0000000..034c346 --- /dev/null +++ b/src/modern/ui/demo_live.cpp @@ -0,0 +1,369 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "modern/ui/demo_live.hpp" +#include "modern/ui/demo_career.hpp" +#include "modern/ui/demo_lineup.hpp" +#include "modern/ui/demo_sports.hpp" +#include +#include +#include +#include + +namespace bmh::modern_ui { +namespace { +Json failure(const char *error) { return {{"ok", false}, {"error", error}}; } +std::string fingerprint(const std::string &text) { + // Stable recording identity, independent of std::hash or active right pane. + uint64_t hash = 14695981039346656037ULL; + for (unsigned char c : text) { hash ^= c; hash *= 1099511628211ULL; } + static const char hex[] = "0123456789abcdef"; + std::string value(16, '0'); + for (int i = 15; i >= 0; --i) { value[size_t(i)] = hex[hash & 15]; hash >>= 4; } + return value; +} +Json team(const Catalog &world, const std::string &id) { + const auto *row = world.find("clubs", id); + return {{"id", id}, {"name", row ? world.name(*row) : "Demo-Gegner"}, + {"role", "club"}, {"catalogue", row != nullptr}}; +} +Json owner_view(const Catalog &world, const Json &state, const Json &manager, + bool national, bool indoor) { + const auto club = manager.value("club", ""); + Json view = state; + const auto active_club = demo_career_manager(state).value("club", ""); + if (club != active_club) { + const auto views = state.value("career_views", Json::object()); + if (views.contains(club)) restore_demo_career_view(view, views.at(club)); + else { + view["lineup"] = demo_lineup(world, club); + view["tactics"] = demo_tactics(); + view.erase("indoor_lineup"); + } + } + view["career"]["active_portrait"] = manager.at("portrait"); + view["career"]["surface"] = indoor ? "indoor" : "outdoor"; + if (!migrate_demo_lineup(view, world, club)) + return {{"ok", false}, {"error", "live_owner_lineup_unavailable"}}; + auto projection = demo_lineup_rows(view, world, club); + if (!projection.value("ok", false)) return projection; + auto rows = projection.at("rows"); + // These are catalogue attributes, never fixture-generated fitness/strength. + for (auto &row : rows) { + row["caps"] = nullptr; + row["international_goals"] = nullptr; + if (const auto *player = world.find("players", row.at("id"))) { + const auto attributes = player->value("attributes", Json::object()); + for (const auto *key : {"caps", "international_goals"}) + if (attributes.contains(key) && attributes.at(key).is_number_integer() && + attributes.at(key) >= 0) row[key] = attributes.at(key); + } + } + Json edit_state = {{"lineup", view.at("lineup")}, + {"tactics", view.value("tactics", demo_tactics())}, + {"career", {{"surface", indoor ? "indoor" : "outdoor"}}}, + {"date", state.at("date")}}; + if (view.contains("indoor_lineup")) edit_state["indoor_lineup"] = view.at("indoor_lineup"); + return {{"ok", true}, {"rows", rows}, {"board", demo_lineup_visible(view)}, + {"tactics", view.value("tactics", demo_tactics())}, + {"edit_state", edit_state}, + {"club_basis", club}, {"national_demo_basis", national}, + {"field_count", indoor ? 6 : 11}, {"on_field_limit", indoor ? 6 : 11}, + {"rotation_rows", indoor ? Json(std::min(size_t(11), rows.size())) : Json()}, + {"roster_size", rows.size()}, {"roster_limit", nullptr}}; +} +// Every outcome, statistic and minute below is authored fixture data. There is +// no event generation, chance/goal rule, random draw or match clock simulation. +struct Moment { + int outdoor, indoor; + const char *phase, *kind, *headline, *body; + std::array score, chances, yellow, red; + std::array points, goals_for, goals_against; +}; +constexpr std::array recording{{ + {0, 0, "first_half", "kickoff", "Anpfiff!", "Der Ball rollt. Beide Mannschaften beginnen mit ihrer Aufstellung.", {0,0}, {0,0}, {0,0}, {0,0}, {22,19}, {20,18}, {10,12}}, + {12, 6, "first_half", "goal", "Die Heimelf geht in Führung", "Die Gastgeber nutzen ihre Gelegenheit und gehen mit 1:0 in Führung.", {1,0}, {2,1}, {0,0}, {0,0}, {24,18}, {21,18}, {10,13}}, + {23, 11, "first_half", "yellow", "Gelbe Karte für die Gäste", "Die Gäste werden verwarnt. Es bleibt beim knappen Rückstand.", {1,0}, {3,2}, {0,1}, {0,0}, {24,18}, {21,18}, {10,13}}, + {45, 20, "interval", "interval", "Halbzeit", "Mit einer knappen Führung der Gastgeber geht es in die Pause.", {1,0}, {4,3}, {0,1}, {0,0}, {24,18}, {21,18}, {10,13}}, + {46, 21, "second_half", "restart", "Die zweite Hälfte beginnt", "Die Mannschaften sind zurück. Die Heimelf beginnt mit einem Tor Vorsprung.", {1,0}, {4,3}, {0,1}, {0,0}, {24,18}, {21,18}, {10,13}}, + {62, 28, "second_half", "goal", "Ausgleich für die Gäste", "Die Gäste treffen zum 1:1. Damit ist die Begegnung wieder offen.", {1,1}, {5,4}, {0,1}, {0,0}, {22,19}, {21,19}, {11,13}}, + {70, 32, "second_half", "chance", "Eine weitere Torchance", "Die Heimelf kommt zum Abschluss. Der Spielstand bleibt unverändert.", {1,1}, {6,5}, {0,1}, {0,0}, {22,19}, {21,19}, {11,13}}, + {78, 36, "second_half", "goal", "Die Heimelf trifft erneut", "Die Gastgeber erzielen das 2:1 und liegen wieder vorn.", {2,1}, {7,5}, {0,1}, {0,0}, {24,18}, {22,19}, {11,14}}, + {90, 40, "finished", "fulltime", "Abpfiff", "Die Partie endet mit einem 2:1 für die Heimmannschaft.", {2,1}, {8,6}, {0,1}, {0,0}, {24,18}, {22,19}, {11,14}} +}}; +Json standings(const Catalog &world, const Json &match, const Moment &moment) { + // One declared snapshot per catalogue competition, independent of the owner + // or watched match. Both passes are authored table ordering, not a computed + // league ranking; all pairs in this recording share the same fixed outcomes. + Json rows = Json::array(); + const auto *home = world.find("clubs", match.at("home").at("id")); + if (!home) return rows; + const auto pool = world.clubs(home->value("competition", "")); + for (size_t side = 0; side < 2; ++side) + for (size_t slot = side; slot < std::min(size_t(18), pool.size()); slot += 2) + rows.push_back({{"position", rows.size() + 1}, {"team", team(world, pool[slot]->at("id"))}, + {"played", 8}, {"gf", moment.goals_for[side]}, + {"ga", moment.goals_against[side]}, {"points", moment.points[side]}}); + return rows; +} +bool uint_value(const Json &v, uint64_t maximum) { + return (v.is_number_unsigned() && v.get() <= maximum) || + (v.is_number_integer() && v.get() >= 0 && + uint64_t(v.get()) <= maximum); +} +bool string_value(const Json &v, size_t maximum = 240) { + if (!v.is_string()) return false; + const auto &value = v.get_ref(); + return !value.empty() && value.size() <= maximum && + std::none_of(value.begin(), value.end(), [](unsigned char c) { return c < 32 || c == 127; }); +} +bool team_value(const Json &v, const Json &role) { + return v.is_object() && string_value(v.at("id")) && string_value(v.at("name")) && v.at("role") == role; +} +} // namespace + +Json make_demo_live(const Catalog &world, const Json &state, uint64_t revision) { + try { + if (!state.is_object() || state.value("schema", "") != "openbmh-ui-demo@1") + return failure("live_demo_state_required"); + const auto context = demo_career_context(state, world); + if (context.value("ended", false)) return failure("live_career_ended"); + const auto role = context.value("role", ""), surface = context.value("surface", ""); + if ((role != "club" && role != "national") || + (surface != "outdoor" && surface != "indoor") || + (role == "national" && surface != "outdoor")) return failure("invalid_live_scope"); + const bool national = role == "national", indoor = surface == "indoor"; + const auto humans = context.at("active_managers"); + if (!humans.is_array() || humans.empty() || humans.size() > 4) + return failure("invalid_live_owners"); + Json owners = Json::array(), matches = Json::array(); + std::set portraits; + for (const auto &manager : humans) { + if (national && manager.at("portrait") != context.at("current_manager").at("portrait")) continue; + const int portrait = manager.at("portrait"); + if (portrait < 0 || portrait > 11 || !portraits.insert(portrait).second || + !world.manageable(manager.value("club", ""))) return failure("invalid_live_owners"); + const auto managed = national ? context.at("current_team") : team(world, manager.at("club")); + const auto view = owner_view(world, state, manager, national, indoor); + if (!view.value("ok", false)) return failure("live_owner_lineup_unavailable"); + owners.push_back({{"id", "manager:" + std::to_string(portrait)}, {"portrait", portrait}, + {"name", manager.at("name")}, {"team", managed}, {"view", view}}); + } + for (auto &owner : owners) { + const std::string id = owner.at("team").at("id"); + auto existing = std::find_if(matches.begin(), matches.end(), [&](const auto &match) { + return match.at("home").at("id") == id || match.at("away").at("id") == id; + }); + if (existing != matches.end()) { owner["match_id"] = existing->at("id"); existing->at("owners").push_back(owner.at("id")); continue; } + Json home = owner.at("team"), away; + if (national) { + away = {{"id", "fixture:national-opponent"}, {"name", "Demo-Nationalteam"}, {"role", "national"}, {"catalogue", false}}; + for (const auto &nation : world.rows("nations")) if (nation.value("id", "") != "nation:de") { + away = {{"id", "national:" + nation.at("id").get()}, {"name", world.name(nation)}, {"role", "national"}, {"nation", nation.at("id")}, {"catalogue", true}}; break; + } + } else { + const auto *club = world.find("clubs", id); + const auto pool = world.clubs(club ? club->value("competition", "") : ""); + auto at = std::find_if(pool.begin(), pool.end(), [&](const auto *c) { return c->value("id", "") == id; }); + if (at == pool.end()) return failure("live_team_unavailable"); + const size_t index = size_t(at - pool.begin()), partner = index % 2 ? index - 1 : index + 1; + if (partner < pool.size()) { + away = team(world, pool[partner]->at("id")); + if (index % 2) std::swap(home, away); + } else away = team(world, "fixture:opponent:" + id); + } + const auto match_id = "ui-match:" + fingerprint(Json::array({world.manifest().value("id", ""), state.at("date"), role, surface, home.at("id"), away.at("id")}).dump()); + owner["match_id"] = match_id; + matches.push_back({{"id", match_id}, {"home", home}, {"away", away}, + {"owners", Json::array({owner.at("id")})}, + {"competition", national ? "Länderspiel · Demo" : indoor ? "Hallenpartie · Demo" : "Spieltag · Demo"}}); + } + Json frames = Json::array(), events = Json::array(); + for (size_t sequence = 0; sequence < recording.size(); ++sequence) { + const auto &moment = recording[sequence]; + Json scores = Json::array(); + for (const auto &match : matches) { + const auto event_id = match.at("id").get() + ":event:" + std::to_string(sequence); + events.push_back({{"id", event_id}, {"sequence", sequence}, {"match_id", match.at("id")}, + {"minute", indoor ? moment.indoor : moment.outdoor}, {"kind", moment.kind}, + {"headline", moment.headline}, {"body", moment.body}, {"score", moment.score}, + {"side", std::string(moment.kind) == "yellow" || sequence == 5 ? "away" : "home"}}); + scores.push_back({{"match_id", match.at("id")}, {"score", moment.score}, + {"chances", moment.chances}, {"yellow", moment.yellow}, {"red", moment.red}, + {"players", indoor ? Json::array({6,6}) : Json::array({11,11})}, + {"standings", national ? Json::array() : standings(world, match, moment)}}); + } + frames.push_back({{"sequence", sequence}, {"minute", indoor ? moment.indoor : moment.outdoor}, + {"phase", moment.phase}, {"matches", scores}, {"events", events}}); + } + const auto identity = Json{{"world", world.manifest().value("id", "")}, {"date", state.at("date")}, + {"role", role}, {"surface", surface}, {"matches", matches}}; + return {{"ok", true}, {"schema", "openbmh-live-fixture@1"}, {"source", "ui-demo-fixture"}, + {"fixture_id", "ui-live:" + fingerprint(identity.dump())}, {"source_revision", revision}, + {"world", world.manifest().value("id", "")}, {"date", state.at("date")}, + {"role", role}, {"surface", surface}, {"duration", indoor ? 40 : 90}, + {"field_count", indoor ? 6 : 11}, {"owners", owners}, {"matches", matches}, + {"frames", frames}, {"notice", "UI-Demo · vorgegebene Ergebnisse, keine Spielsimulation"}}; + } catch (const std::exception &) { return failure("invalid_live_demo"); } +} + +bool valid_live_fixture(const Json &v) { + try { + if (!v.is_object() || !v.value("ok", false) || v.at("schema") != "openbmh-live-fixture@1" || + v.at("source") != "ui-demo-fixture" || !v.at("fixture_id").is_string() || + !uint_value(v.at("source_revision"), UINT64_MAX) || !v.at("owners").is_array() || + v.at("owners").empty() || v.at("owners").size() > 4 || !v.at("matches").is_array() || + v.at("matches").empty() || v.at("matches").size() > 4 || !v.at("frames").is_array() || + v.at("frames").size() < 2 || v.at("frames").size() > 2000) return false; + const bool indoor = v.at("surface") == "indoor", national = v.at("role") == "national"; + if ((!national && v.at("role") != "club") || (!indoor && v.at("surface") != "outdoor") || + (national && (indoor || v.at("owners").size() != 1)) || + v.at("duration") != (indoor ? 40 : 90) || v.at("field_count") != (indoor ? 6 : 11)) return false; + std::set owner_ids, match_ids, teams, assigned_owners; + std::set portraits; + for (const auto &owner : v.at("owners")) { + if (!string_value(owner.at("id")) || !owner_ids.insert(owner.at("id")).second || + !uint_value(owner.at("portrait"), 11) || !portraits.insert(owner.at("portrait").get()).second || + !string_value(owner.at("name")) || !team_value(owner.at("team"), v.at("role"))) return false; + const auto &view = owner.at("view"); + if (!view.value("ok", false) || !view.at("rows").is_array() || view.at("rows").size() > 2000 || + view.at("field_count") != v.at("field_count") || view.at("on_field_limit") != v.at("field_count") || + view.at("roster_size") != view.at("rows").size() || !view.at("roster_limit").is_null() || + !view.at("board").at("order").is_array() || !view.at("board").at("points").is_array() || + view.at("board").at("points").size() != 11 || !view.at("edit_state").is_object() || + !view.at("edit_state").at("lineup").is_object() || !valid_demo_tactics(view.at("tactics")) || + view.at("national_demo_basis") != national) return false; + if ((indoor && view.at("rotation_rows") != std::min(size_t(11), view.at("rows").size())) || + (!indoor && !view.at("rotation_rows").is_null())) return false; + std::set players; + size_t slot = 0; + for (const auto &row : view.at("rows")) { + if (!string_value(row.at("id")) || !players.insert(row.at("id")).second || !string_value(row.at("name")) || + row.at("slot") != slot++ || !row.contains("strength") || !row.contains("condition")) return false; + for (auto field : {"caps", "international_goals"}) + if (!row.at(field).is_null() && !uint_value(row.at(field), 1000000)) return false; + } + } + for (const auto &match : v.at("matches")) { + if (!string_value(match.at("id")) || !match_ids.insert(match.at("id")).second || + !match.at("owners").is_array() || match.at("owners").empty()) return false; + for (auto side : {"home", "away"}) + if (!team_value(match.at(side), v.at("role")) || + !teams.insert(match.at(side).at("id")).second) return false; + std::set assigned; + for (const auto &owner_id : match.at("owners")) { + if (!owner_id.is_string() || !owner_ids.contains(owner_id) || !assigned.insert(owner_id).second || !assigned_owners.insert(owner_id).second) return false; + const auto owner = std::find_if(v.at("owners").begin(), v.at("owners").end(), [&](const auto &o) { return o.at("id") == owner_id; }); + if (owner->at("match_id") != match.at("id") || + (owner->at("team").at("id") != match.at("home").at("id") && owner->at("team").at("id") != match.at("away").at("id"))) return false; + } + } + if (assigned_owners != owner_ids) return false; + for (const auto &owner : v.at("owners")) if (!match_ids.contains(owner.at("match_id"))) return false; + int minute = -1; size_t sequence = 0; + std::map history; + for (const auto &frame : v.at("frames")) { + if (!uint_value(frame.at("sequence"), v.at("frames").size() - 1) || frame.at("sequence") != sequence++ || !uint_value(frame.at("minute"), indoor ? 40 : 90) || + frame.at("minute").get() < minute || !frame.at("events").is_array() || + frame.at("events").size() > 8000 || !frame.at("matches").is_array() || + frame.at("matches").size() != match_ids.size()) return false; + const auto phase = frame.value("phase", ""); + if (phase != "first_half" && phase != "interval" && phase != "second_half" && phase != "finished") return false; + if (phase == "finished" && sequence != v.at("frames").size()) return false; + minute = frame.at("minute"); std::set scored, event_ids; + for (const auto &m : frame.at("matches")) { + if (!match_ids.contains(m.at("match_id")) || !scored.insert(m.at("match_id")).second) return false; + for (auto key : {"score", "chances", "yellow", "red", "players"}) + if (!m.at(key).is_array() || m.at(key).size() != 2 || !uint_value(m.at(key)[0], 1000) || !uint_value(m.at(key)[1], 1000)) return false; + if (!m.at("standings").is_array() || m.at("standings").size() > 128 || (national && !m.at("standings").empty())) return false; + for (const auto &row : m.at("standings")) { + if (!team_value(row.at("team"), v.at("role"))) return false; + for (auto key : {"position", "played", "gf", "ga", "points"}) if (!uint_value(row.at(key), 1000000)) return false; + } + } + const auto previous_history = history; + for (const auto &event : frame.at("events")) { + if (!string_value(event.at("id")) || !event_ids.insert(event.at("id")).second || + !match_ids.contains(event.at("match_id")) || !uint_value(event.at("sequence"), sequence - 1) || + !uint_value(event.at("minute"), uint64_t(minute)) || !string_value(event.at("headline")) || + !string_value(event.at("body"), 2200) || !string_value(event.at("kind"), 40) || + (event.at("side") != "home" && event.at("side") != "away") || !event.at("score").is_array() || + event.at("score").size() != 2 || !uint_value(event.at("score")[0], 1000) || !uint_value(event.at("score")[1], 1000)) return false; + const std::string id = event.at("id"); + if (history.contains(id) && history.at(id) != event) return false; + history[id] = event; + } + for (const auto &[id, event] : previous_history) { (void)event; if (!event_ids.contains(id)) return false; } + } + return v.at("frames").front().at("minute") == 0 && minute == (indoor ? 40 : 90) && + v.at("frames").back().at("phase") == "finished"; + } catch (const std::exception &) { return false; } +} +Json live_fixture_frame(const Json &v, size_t sequence) { + if (!valid_live_fixture(v)) return failure("invalid_live_fixture"); + if (sequence >= v.at("frames").size()) return failure("invalid_live_sequence"); + auto frame = v.at("frames")[sequence]; + frame["ok"] = true; frame["source"] = v.at("source"); frame["fixture_id"] = v.at("fixture_id"); + frame["source_revision"] = v.at("source_revision"); return frame; +} +Json query_demo_live(const Catalog &world, const Json &state, uint64_t revision, const Json &q) { + try { + if (!q.is_object()) return failure("invalid_live_query"); + for (const auto &[key, value] : q.items()) { (void)value; + if (key != "kind" && key != "revision" && key != "sequence" && key != "fixture_id") return failure("invalid_live_query"); + } + if (q.contains("revision") && (!uint_value(q.at("revision"), UINT64_MAX) || q.at("revision") != revision)) return failure("stale_live_revision"); + const auto kind = q.value("kind", "fixture"); + if (kind != "fixture" && kind != "frame") return failure("invalid_live_query"); + auto fixture = make_demo_live(world, state, revision); + if (!fixture.value("ok", false)) return fixture; + if (q.contains("fixture_id") && q.at("fixture_id") != fixture.at("fixture_id")) return failure("stale_live_fixture"); + if (kind == "fixture") return q.contains("sequence") ? failure("invalid_live_query") : fixture; + if (!q.contains("sequence") || !uint_value(q.at("sequence"), fixture.at("frames").size() - 1)) return failure("invalid_live_sequence"); + return live_fixture_frame(fixture, q.at("sequence").get()); + } catch (const std::exception &) { return failure("invalid_live_query"); } +} + +bool LivePlayback::open(const Json &fixture, const std::string &owner_id) { + if (!valid_live_fixture(fixture)) return false; + LivePlayback next; next.fixture_ = fixture; + next.owner_ = fixture.at("owners").front().at("id"); + if (!owner_id.empty() && !next.owner(owner_id)) return false; + *this = std::move(next); return true; +} +void LivePlayback::close() { fixture_ = nullptr; sequence_ = 0; speed_ = 0; elapsed_ = 0; owner_.clear(); } +bool LivePlayback::finished() const { return available() && sequence_ + 1 == fixture_.at("frames").size(); } +bool LivePlayback::next() { + if (!available() || finished()) return false; + ++sequence_; elapsed_ = 0; if (finished()) speed_ = 0; return true; +} +bool LivePlayback::speed(int value) { + if (!available() || value < 0 || value > 4 || (finished() && value)) return false; + speed_ = value; elapsed_ = 0; return true; +} +bool LivePlayback::elapse(uint64_t milliseconds) { + if (!available() || !speed_ || finished()) return false; + constexpr std::array intervals{0, 2400, 1400, 800, 400}; + const auto interval = intervals[size_t(speed_)]; + // A delayed/hidden window never skips an arbitrary backlog of recorded scenes. + elapsed_ = std::min(interval, elapsed_ + std::min(milliseconds, interval)); + return elapsed_ >= interval && next(); +} +bool LivePlayback::owner(const std::string &id) { + if (!available()) return false; + for (const auto &o : fixture_.at("owners")) if (o.at("id") == id) { owner_ = id; return true; } + return false; +} +bool LivePlayback::cycle_owner(int direction) { + if (!available() || (direction != -1 && direction != 1)) return false; + const auto &owners = fixture_.at("owners"); + for (size_t i = 0; i < owners.size(); ++i) if (owners[i].at("id") == owner_) + return owner(owners[(i + owners.size() + direction) % owners.size()].at("id")); + return false; +} +Json LivePlayback::frame() const { return available() ? live_fixture_frame(fixture_, sequence_) : failure("live_unavailable"); } +Json LivePlayback::status() const { + return {{"source", available() ? Json("ui-demo-fixture") : Json()}, {"available", available()}, + {"fixture_id", available() ? fixture_.at("fixture_id") : Json()}, + {"source_revision", available() ? fixture_.at("source_revision") : Json()}, + {"sequence", sequence_}, {"speed", speed_}, {"owner", owner_}, {"finished", finished()}}; +} +} // namespace bmh::modern_ui diff --git a/src/modern/ui/demo_live.hpp b/src/modern/ui/demo_live.hpp new file mode 100644 index 0000000..6882c3e --- /dev/null +++ b/src/modern/ui/demo_live.hpp @@ -0,0 +1,45 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +#include "modern/ui/catalog.hpp" +#include + +namespace bmh::modern_ui { +// A finite, authored presentation recording. No simulation, game state, RNG, +// calendar progression or source mutation is involved in constructing/reading it. +// Only catalogue identities and explicit owner presentation boards are reused. +Json make_demo_live(const Catalog &, const Json &state, uint64_t revision); +// Requests: {kind:"fixture",revision?:uint64}; or +// {kind:"frame",sequence:uint,fixture_id?:string,revision?:uint64}. +Json query_demo_live(const Catalog &, const Json &state, uint64_t revision, + const Json &request); +bool valid_live_fixture(const Json &); +Json live_fixture_frame(const Json &, size_t sequence); + +// Playback belongs to the view, never to DataSource or a saved career. Elapsed +// time only reveals the next prerecorded snapshot; it cannot execute an action. +class LivePlayback { +public: + bool open(const Json &fixture, const std::string &owner = {}); + void close(); + bool next(); + bool speed(int value); // 0 = pause, 1..4 = recording playback speed + bool elapse(uint64_t milliseconds); + bool owner(const std::string &id); + bool cycle_owner(int direction); + Json frame() const; + Json status() const; + const Json &fixture() const { return fixture_; } + size_t sequence() const { return sequence_; } + int speed() const { return speed_; } + const std::string &owner() const { return owner_; } + bool available() const { return fixture_.is_object(); } + bool finished() const; + +private: + Json fixture_; + size_t sequence_ = 0; + int speed_ = 0; + uint64_t elapsed_ = 0; + std::string owner_; +}; +} // namespace bmh::modern_ui diff --git a/src/modern/ui/live_controls.inc b/src/modern/ui/live_controls.inc new file mode 100644 index 0000000..316f655 --- /dev/null +++ b/src/modern/ui/live_controls.inc @@ -0,0 +1,208 @@ +// SPDX-License-Identifier: GPL-3.0-only +bool App::live_open() { + if (!source_) { message("Für diese Ansicht steht keine Live-Datenquelle bereit."); return false; } + const auto snapshot = snap(); + if (!live_.available() || live_source_ != source_.get() || live_world_ != snapshot.world || + live_.fixture().at("source_revision") != snapshot.revision) { + const auto fixture = source_->read_live({{"kind", "fixture"}, {"revision", snapshot.revision}}); + const auto owner_id = "manager:" + std::to_string(demo_career_manager(snapshot.state).value("portrait", 0)); + if (!fixture.value("ok", false) || !live_.open(fixture, owner_id)) { + message("Live-Ticker nicht verfügbar: " + fixture.value("error", "invalid_live_fixture")); return false; + } + live_source_ = source_.get(); live_world_ = snapshot.world; + live_drafts_ = Json::object(); live_dialog_.clear(); live_dialog_draft_ = Json(); + live_coverage_ = "all"; live_filter_ = "all"; live_tab_ = "team"; + live_selected_match_ = fixture.at("matches").front().at("id"); + live_ticker_scroll_ = live_detail_scroll_ = 0; + live_reset_ticker_ = live_reset_detail_ = true; + live_feedback_.clear(); live_resume_speed_ = 0; + } + live_review_ = false; live_speed_dragging_ = false; + live_last_tick_ = SDL_GetTicks64(); scene_ = "live"; menu_.clear(); + focus_after_render_ = live_.finished() ? "live-review" : "live-next"; + refresh(); return true; +} +void App::live_close() { + live_.speed(0); live_dialog_.clear(); live_dialog_draft_ = Json(); + live_resume_speed_ = 0; live_speed_dragging_ = false; + scene_ = "desktop"; menu_.clear(); focus_after_render_ = "object-app-kickoff"; refresh(); +} +void App::live_set_speed(int value) { + if (!live_.speed(value)) return; + live_feedback_.clear(); + live_last_tick_ = SDL_GetTicks64(); + if (auto *node = dynamic_cast(element("live-speed"))) { + // Native vertical sliders increase downward; the user's logical speed is + // deliberately inverted so the bottom position always means zero/pause. + node->SetValue(std::to_string(4 - value)); node->SetAttribute("aria-valuenow", value); + node->SetAttribute("aria-valuetext", value ? "Wiedergabe Stufe " + std::to_string(value) : "Pause"); + } + if (auto *node = element("live-speed-value")) node->SetInnerRML(esc(value ? std::to_string(value) + "×" : "Pause")); + if (auto *node = element("live-pause")) node->SetInnerRML(live_text(value ? "Pause" : "Abspielen", "control-label")); + const auto &frame = live_.fixture().at("frames")[live_.sequence()]; + const std::string phase = live_.finished() ? "Beendet" : frame.at("phase") == "interval" ? "Halbzeit" : value ? "Aufzeichnung läuft" : "Gemeinsam pausiert"; + if (auto *node = element("live-phase-status")) node->SetInnerRML(esc(phase)); + if (auto *node = element("live-playback-status")) node->SetInnerRML(esc(phase + " · " + std::to_string(frame.at("minute").get()) + "′ · keine Spielwertänderung")); + dirty_ = true; +} +void App::live_tick() { + if (scene_ != "live" || !live_.available()) return; + const auto now = SDL_GetTicks64(), elapsed = now - live_last_tick_; live_last_tick_ = now; + if (!popup_.empty() || !live_dialog_.empty() || live_speed_dragging_ || live_review_) return; + const auto current = source_ ? source_->snapshot() : Snapshot(); + if (!source_ || source_.get() != live_source_ || current.world != live_world_ || + current.revision != live_.fixture().at("source_revision").get()) { + live_.speed(0); + if (live_feedback_ != "Die Quelle hat sich geändert. Diese Aufzeichnung bleibt pausiert; öffne Anstoß erneut.") { live_feedback_ = "Die Quelle hat sich geändert. Diese Aufzeichnung bleibt pausiert; öffne Anstoß erneut."; needs_render_ = true; } + return; + } + if (live_.elapse(elapsed)) needs_render_ = true; +} +void App::live_dialog_close(bool apply_draft) { + if (live_dialog_.empty()) return; + if (apply_draft) { + auto proposed = live_dialog_draft_; + if (live_dialog_ == "lineup") { + const auto owner = live_owner(); + const auto error = edit_demo_lineup(proposed, {{"kind", "swap"}, {"a", live_out_}, {"b", live_in_}}, + *live_world_, owner.at("view").at("club_basis")); + if (!error.empty()) { live_feedback_ = "Die Demovorschau konnte nicht geändert werden: " + error; refresh(); return; } + } + live_drafts_[live_.owner()] = std::move(proposed); + live_feedback_ = "Lokale Demovorschau geändert. Spielverlauf und Quelle bleiben unverändert."; + } + const auto was = live_dialog_; live_dialog_.clear(); live_dialog_draft_ = Json(); + live_out_.clear(); live_in_.clear(); live_speed_dragging_ = false; + const int resume = live_resume_speed_; live_resume_speed_ = 0; + if (resume && !live_.finished()) live_.speed(resume); + live_last_tick_ = SDL_GetTicks64(); focus_after_render_ = was == "lineup" ? "live-lineup-edit" : "live-tactics-edit"; + refresh(); +} +bool App::live_action(const std::string &action, Rml::Element *target) { + if (action == "open:kickoff") { live_open(); return true; } + if (!action.starts_with("live-")) return false; + if (scene_ != "live" || !live_.available()) return true; + const auto id = target ? target->GetAttribute("data-id", "") : ""; + if (!live_dialog_.empty() && action != "live-dialog-cancel" && action != "live-dialog-apply" && action != "live-tactic-cycle") return true; + if (action == "live-back") { live_close(); return true; } + if (action == "live-owner-prev" || action == "live-owner-next") { + live_.cycle_owner(action == "live-owner-prev" ? -1 : 1); live_reset_detail_ = true; + } else if (action == "live-tab") { + if (id != "team" && id != "tactics" && id != "opponent" && id != "table" && id != "stats") return true; + live_tab_ = id; live_reset_detail_ = true; + } else if (action == "live-filter") { + if (id != "all" && id != "highlights" && id != "goal" && id != "yellow") return true; + live_filter_ = id; live_reset_ticker_ = true; + } else if (action == "live-coverage") { + if (id != "all" && id != "single" && id != "conference") return true; + live_coverage_ = id; live_reset_ticker_ = true; + } else if (action == "live-match") { + for (const auto &match : live_.fixture().at("matches")) if (match.at("id") == id) { + live_selected_match_ = id; live_reset_ticker_ = true; break; + } + } else if (action == "live-match-prev" || action == "live-match-next") { + const auto &matches = live_.fixture().at("matches"); + for (size_t i = 0; i < matches.size(); ++i) if (matches[i].at("id") == live_selected_match_) { + live_selected_match_ = matches[(i + matches.size() + (action == "live-match-prev" ? -1 : 1)) % matches.size()].at("id"); break; + } + live_reset_ticker_ = true; + } else if (action == "live-next") { + live_.next(); live_last_tick_ = SDL_GetTicks64(); + } else if (action == "live-pause") { + live_set_speed(live_.speed() ? 0 : 1); + } else if (action == "live-review" && live_.finished()) { + live_review_ = true; + } else if (action == "live-review-back") { + live_review_ = false; + } else if (action == "live-intervene-lineup" || action == "live-intervene-tactics") { + if (live_.finished()) return true; + const auto owner = live_owner(); live_dialog_draft_ = live_owner_state(owner); + live_dialog_ = action == "live-intervene-lineup" ? "lineup" : "tactics"; + live_resume_speed_ = live_.speed(); live_.speed(0); live_last_tick_ = SDL_GetTicks64(); + live_out_.clear(); live_in_.clear(); + const auto rows = live_owner_rows(owner); const size_t count = live_.fixture().at("field_count"); + if (!rows.empty()) live_out_ = rows[0].at("id"); + if (rows.size() > count) live_in_ = rows[count].at("id"); + focus_after_render_ = "live-dialog-cancel"; + } else if (action == "live-dialog-cancel" || action == "live-dialog-apply") { + live_dialog_close(action == "live-dialog-apply"); return true; + } else if (action == "live-tactic-cycle" && live_dialog_ == "tactics") { + try { + const int index = std::stoi(id); + if (index < 0 || index > 7) return true; + const auto error = edit_demo_tactics(live_dialog_draft_["tactics"], {{"kind", "cycle"}, {"index", index}}); + if (!error.empty()) return true; + } catch (const std::exception &) { return true; } + } else return true; + if (target && focus_after_render_.empty()) focus_after_render_ = target->GetId(); + refresh(); return true; +} +bool App::live_event(Rml::Event &event) { + if (scene_ != "live" || !live_.available() || !popup_.empty()) return false; + const auto type = event.GetType(); auto *target = event.GetTargetElement(); + bool speed_control = false; + for (auto *node = target; node && node != doc_; node = node->GetParentNode()) if (node->GetId() == "live-speed") speed_control = true; + if (type == "mousedown" && speed_control) live_speed_dragging_ = true; + if (type == "mouseup" && live_speed_dragging_) { + live_speed_dragging_ = false; live_last_tick_ = SDL_GetTicks64(); + focus_after_render_ = "live-speed"; needs_render_ = true; + } + if ((type == "change" || type == "input") && speed_control) { + if (setting_menu_markup_) return true; + if (auto *input = dynamic_cast(element("live-speed"))) { + try { live_set_speed(4 - std::stoi(input->GetValue())); } catch (const std::exception &) {} + } + return true; + } + if ((type == "change" || type == "input") && !live_dialog_.empty()) { + if (setting_menu_markup_) return true; + if (target->GetId() == "live-player-out") live_out_ = field("live-player-out"); + if (target->GetId() == "live-player-in") live_in_ = field("live-player-in"); + return true; + } + if (type == "mouseup" && event.GetParameter("button", 0) == 1) { + if (!live_dialog_.empty()) live_dialog_close(false); else live_close(); + event.StopImmediatePropagation(); return true; + } + if (type == "keydown") { + const auto key = Rml::Input::KeyIdentifier(event.GetParameter("key_identifier", 0)); + if (key == Rml::Input::KI_ESCAPE) { + if (!live_dialog_.empty()) live_dialog_close(false); else live_close(); + event.StopImmediatePropagation(); return true; + } + if (key == Rml::Input::KI_TAB) { + Rml::ElementList controls; doc_->QuerySelectorAll(controls, live_dialog_.empty() ? "#live-stage button,#live-stage input" : "#live-dialog button,#live-dialog select"); + Rml::ElementList visible; for (auto *node : controls) if (node->IsVisible(true) && !node->HasAttribute("disabled")) visible.push_back(node); + if (!visible.empty()) { + auto at = std::find(visible.begin(), visible.end(), context_->GetFocusElement()); + int index = at == visible.end() ? -1 : int(at - visible.begin()); + const bool reverse = event.GetParameter("shift_key", 0) != 0; + index = (index + int(visible.size()) + (reverse ? -1 : 1)) % int(visible.size()); visible[size_t(index)]->Focus(true); + } + event.StopImmediatePropagation(); return true; + } + if (live_dialog_.empty() && key == Rml::Input::KI_P && !live_.finished()) { + live_set_speed(live_.speed() ? 0 : 1); event.StopImmediatePropagation(); return true; + } + if (speed_control && (key == Rml::Input::KI_HOME || key == Rml::Input::KI_END || key == Rml::Input::KI_UP || key == Rml::Input::KI_DOWN)) { + live_set_speed(key == Rml::Input::KI_HOME ? 0 : key == Rml::Input::KI_END ? 4 : std::clamp(live_.speed() + (key == Rml::Input::KI_UP ? 1 : -1), 0, 4)); + event.StopImmediatePropagation(); return true; + } + } + if (type == "click" && live_dialog_.empty()) for (auto *node = target; node && node != doc_; node = node->GetParentNode()) if (node->HasAttribute("data-live-match")) { + live_selected_match_ = node->GetAttribute("data-live-match", ""); + if (live_coverage_ == "single") live_reset_ticker_ = true; + refresh(); return true; + } + return false; +} +Json App::live_snapshot() const { + auto status = live_.status(); status["tab"] = live_tab_; status["coverage"] = live_coverage_; + status["selected_match"] = live_selected_match_; status["filter"] = live_filter_; + status["review"] = live_review_; status["dialog"] = live_dialog_; + status["drafts"] = live_drafts_; status["dialog_draft"] = live_dialog_draft_; + status["ticker_scroll"] = element("live-ticker") ? element("live-ticker")->GetScrollTop() : live_ticker_scroll_; + status["frame"] = live_.frame(); + if (live_.available()) { status["owners"] = live_.fixture().at("owners"); status["matches"] = live_.fixture().at("matches"); } + return status; +} diff --git a/src/modern/ui/live_screens.inc b/src/modern/ui/live_screens.inc new file mode 100644 index 0000000..f960be5 --- /dev/null +++ b/src/modern/ui/live_screens.inc @@ -0,0 +1,206 @@ +// SPDX-License-Identifier: GPL-3.0-only +namespace { +std::string live_text(const std::string &value, const std::string &css = {}) { + return "" + esc(value) + ""; +} +std::string live_score_text(const Json &score) { + return std::to_string(score[0].get()) + " : " + std::to_string(score[1].get()); +} +const Json &live_match_by_id(const Json &rows, const Json &id) { + for (const auto &row : rows) if (row.at("id") == id) return row; + throw editor::Error("live_match_unavailable"); +} +const Json &live_score_by_id(const Json &frame, const Json &id) { + for (const auto &row : frame.at("matches")) if (row.at("match_id") == id) return row; + throw editor::Error("live_score_unavailable"); +} +} // namespace + +Json App::live_owner() const { + for (const auto &owner : live_.fixture().at("owners")) if (owner.at("id") == live_.owner()) return owner; + return Json(); +} +Json App::live_owner_state(const Json &owner) const { + const auto id = owner.at("id").get(); + return live_drafts_.contains(id) ? live_drafts_.at(id) : owner.at("view").at("edit_state"); +} +Json App::live_owner_rows(const Json &owner) const { + if (!live_world_) return Json::array(); + const auto view = live_owner_state(owner); + const auto projection = demo_lineup_rows(view, *live_world_, owner.at("view").at("club_basis")); + if (!projection.value("ok", false)) return Json::array(); + auto rows = projection.at("rows"); + for (auto &row : rows) { + row["caps"] = nullptr; row["international_goals"] = nullptr; + for (const auto &base : owner.at("view").at("rows")) if (base.at("id") == row.at("id")) { + row["caps"] = base.at("caps"); row["international_goals"] = base.at("international_goals"); + } + } + return rows; +} +std::string App::live_badge(const Json &team, double size) { + std::string art; + if (team.value("role", "club") == "national") { + auto nation = team.value("nation", team.value("id", "") == "national-de" ? "nation:de" : ""); + if (nation.starts_with("nation:")) nation = nation.substr(7); + const auto flag = ui_nation_flag_svg(nation); + if (!flag.empty()) art = picture(renderer_.diagram("live-flag-" + nation, flag, int(size * 2)), size, size * .7); + } else if (live_world_) { + if (const auto *club = live_world_->find("clubs", team.value("id", "")); club && !club->value("crest", "").empty()) art = crest(club, size); + } + if (art.empty()) art = glyph(team.value("role", "club") == "national" ? "world" : "shirt", size); + return "
" + art + "
"; +} +std::string App::live_roster(const Json &owner) { + const bool national = live_.fixture().at("role") == "national"; + const int field_count = live_.fixture().at("field_count"); + std::string out = "
" + + live_text("Nr.", "live-roster-number") + live_text(owner.at("team").at("name"), "live-roster-name") + + live_text(national ? "Caps" : "Stä.", "live-roster-stat") + live_text(national ? "Tore" : "Ko.", "live-roster-stat") + "
"; + const auto rows = live_owner_rows(owner); + if (national) out += "

" + live_text("Demokader auf Vereinsbasis · keine Nationalkaderberufung") + "

"; + for (size_t i = 0; i < rows.size(); ++i) { + if (int(i) == field_count) out += "

" + live_text(field_count == 6 ? "Rotationspartner · erster 11er-Plan" : "Reserven · Demovorschau") + "

"; + if (field_count == 6 && i == 11) out += "

" + live_text("Weitere Kaderreserven") + "

"; + const auto &row = rows[i]; + out += "
()) + "\">" + + live_text(std::to_string(i + 1), "live-roster-number") + live_text(row.at("name"), "live-roster-name") + + live_text(lineup_value(row.at(national ? "caps" : "strength")), "live-roster-stat") + + live_text(lineup_value(row.at(national ? "international_goals" : "condition")), "live-roster-stat") + "
"; + } + if (rows.empty()) out += "

" + live_text("Für diese Demomannschaft sind keine Kaderspieler verfügbar.") + "

"; + return out + "
"; +} +std::string App::live_detail(const Json &owner, const Json &frame) { + const auto &fixture = live_.fixture(); + const auto &match = live_match_by_id(fixture.at("matches"), owner.at("match_id")); + const auto &score = live_score_by_id(frame, match.at("id")); + if (live_tab_ == "team") return live_roster(owner); + if (live_tab_ == "table") { + if (fixture.at("role") == "national") return "

" + live_text("Dieses Demo-Länderspiel gehört zu keiner Liga. Der Spielstand steht links; eine Vereins-Live-Tabelle wird nicht eingeblendet.") + "

"; + std::string out = "

" + live_text("Vorgegebene Demo-Tabelle · keine echte Saisonwertung") + "

" + + live_text("Pl.", "live-table-pos") + "
" + live_text("Verein") + "
" + live_text("Sp.", "live-table-number") + + live_text("Tore", "live-table-number live-table-goals") + live_text("Diff.", "live-table-number") + live_text("Pkt.", "live-table-number") + "
"; + for (const auto &row : score.at("standings")) { + const bool own = row.at("team").at("id") == owner.at("team").at("id"); + const int difference = row.at("gf").get() - row.at("ga").get(); + out += "
()) + "\"" + (own ? " aria-current=\"true\"" : "") + ">" + + live_text(std::to_string(row.at("position").get()), "live-table-pos") + + "
" + live_badge(row.at("team"), 48) + live_text(row.at("team").at("name")) + "
" + + live_text(std::to_string(row.at("played").get()), "live-table-number") + + live_text(std::to_string(row.at("gf").get()) + ":" + std::to_string(row.at("ga").get()), "live-table-number live-table-goals") + + live_text((difference > 0 ? "+" : "") + std::to_string(difference), "live-table-number") + + live_text(std::to_string(row.at("points").get()), "live-table-number") + "
"; + } + return out + "
"; + } + if (live_tab_ == "tactics") { + const auto state = live_owner_state(owner), board = demo_lineup_visible(state); + Json points = Json::array(); const int count = fixture.at("field_count"); + for (int i = 0; i < count; ++i) points.push_back(board.at("points")[size_t(i)]); + return "

" + live_text("Aktuelle Demoaufstellung") + "

" + live_text(std::to_string(count) + " Spieler auf dem Feld · unabhängige Manageransicht") + "

" + + picture(renderer_.diagram("live-formation", lineup_mini(points, theme_), 1200), 1140, 684) + "
" + + btn("live-intervene-tactics", "Taktik als Demo bearbeiten", "", "id=\"live-tactics-edit\" " + std::string(live_.finished() ? "disabled" : "")) + + "

" + live_text("Die Vorschau verändert weder diese feste Ereignisfolge noch Spiel- oder Saisonwerte.") + "

"; + } + std::string out; + if (live_tab_ == "opponent") { + const auto &opponent = match.at(owner.at("team").at("id") == match.at("home").at("id") ? "away" : "home"); + out = "

" + live_text(opponent.at("name")) + "

" + live_text("Gegner dieser vorgegebenen Demopartie. Es werden keine unbekannten Gegneranweisungen behauptet.") + "

"; + } + const std::array, 5> fields{{{"Tore", "score"}, {"Chancen", "chances"}, {"Gelbe Karten", "yellow"}, {"Rote Karten", "red"}, {"Spieler auf dem Feld", "players"}}}; + for (const auto &[label, key] : fields) { + const auto &pair = score.at(key); const int a = pair[0], b = pair[1]; + const double percent = a + b ? 100.0 * a / (a + b) : 50; + out += "
" + live_text(std::to_string(a)) + live_text(label, "stat-title") + live_text(std::to_string(b)) + + "
"; + } + return out + "

" + live_text(match.at("home").at("name").get() + " · " + match.at("away").at("name").get() + " · vorgegebene Demowerte") + "

"; +} +std::string App::live_dialog_markup(const Json &owner) { + if (live_dialog_.empty()) return ""; + const auto rows = live_owner_rows(owner); + std::string body = "

" + live_text(live_dialog_ == "lineup" ? "Aufstellung & Wechsel · Demo" : "Taktik · Demo") + "

" + live_text("Nur lokale Vorschau für " + owner.at("name").get() + " · " + owner.at("team").at("name").get() + ". Keine Änderung an der Partie; der feste Spielverlauf bleibt unverändert.") + "

"; + if (live_dialog_ == "lineup") { + std::vector> active, bench; + for (size_t i = 0; i < rows.size(); ++i) (i < size_t(live_.fixture().at("field_count").get()) ? active : bench).emplace_back(rows[i].at("id"), rows[i].at("name")); + body += ""; + if (active.empty() || bench.empty()) body += "

" + live_text("Für diese Demokaderbasis ist kein Wechselpaar verfügbar.") + "

"; + } else { + const std::array names{"Defensiv / offensiv", "Pass-/Schussbild unten", "Pass-/Schussbild Mitte", "Pass-/Schussbild links", "Flache / hohe Bälle", "Flügelbild links", "Flügelbild rechts", "Einsatz"}; + const auto &values = live_dialog_draft_.at("tactics").at("values"); + for (size_t i = 0; i < names.size(); ++i) + body += "
" + live_text(names[i]) + btn("live-tactic-cycle", "Wert " + std::to_string(values[i].get()), "", "id=\"live-tactic-" + std::to_string(i) + "\" data-id=\"" + std::to_string(i) + "\"") + "
"; + } + body += "
" + btn("live-dialog-cancel", "Abbrechen", "", "id=\"live-dialog-cancel\"") + + btn("live-dialog-apply", "Demovorschau anzeigen", "", "id=\"live-dialog-apply\" " + std::string(live_dialog_ == "lineup" && (live_out_.empty() || live_in_.empty()) ? "disabled" : "")) + "
"; + return "
" + body + "
"; +} +std::string App::render_live() { + if (!live_.available()) return ""; + if (auto *node = element("live-ticker")) live_ticker_scroll_ = live_reset_ticker_ ? 0 : node->GetScrollTop(); + if (auto *node = element("live-detail-body")) live_detail_scroll_ = live_reset_detail_ ? 0 : node->GetScrollTop(); + live_reset_detail_ = live_reset_ticker_ = false; + live_restore_scroll_ = true; + const auto &fixture = live_.fixture(); const auto frame = live_.frame(); const auto owner = live_owner(); + const int minute = frame.at("minute"); const auto phase = frame.at("phase").get(); + const auto phase_text = live_.finished() ? "Beendet" : phase == "interval" ? "Halbzeit" : live_.speed() ? "Aufzeichnung läuft" : "Gemeinsam pausiert"; + const auto arrow = [&](bool right) { const auto color = theme_ == "silver" ? "#376b84" : theme_ == "matchday" ? "#efb2aa" : "#b5dbd2"; return picture(renderer_.diagram(right ? "live-arrow-right" : "live-arrow-left", "", 72), 36, 36); }; + std::string out = "
()) + "\">
" + live_text("SPIELTAG · LIVE-TICKER", "live-eyebrow") + + "

" + live_text(live_review_ ? "Ergebnisse & Bericht" : fixture.at("role") == "national" ? "Deutschland · Demo-Länderspiel" : fixture.at("surface") == "indoor" ? "Hallenpartien · 40 Minuten" : "Gemeinsamer Spieltag") + "

" + live_text("UI-Demo · vorgegebene Ergebnisse", "live-demo-tag") + "
"; + const auto scoreline = [&](const Json &match) { + const auto &value = live_score_by_id(frame, match.at("id")); + return "
" + live_text(match.at("home").at("name"), "live-team-name home") + live_badge(match.at("home"), 58) + live_text(live_score_text(value.at("score")), "live-score") + live_badge(match.at("away"), 58) + live_text(match.at("away").at("name"), "live-team-name away") + "
"; + }; + if (live_review_) { + out += "

" + live_text("Die Demoaufzeichnung ist abgeschlossen.") + "

" + live_text("Diese Ergebnisse und Berichte sind vorgegeben. Datum, Tabellen, Konten und Saisonfortschritt der Quelle wurden nicht verändert.") + "

"; + for (const auto &match : fixture.at("matches")) out += "
()) + "\">" + scoreline(match) + "

" + live_text("1:0 · Führung der Heimelf | Halbzeit 1:0 | 1:1 · Ausgleich | 2:1 · Endstand nach " + std::to_string(fixture.at("duration").get()) + " Minuten") + "

"; + out += "
" + btn("live-back", "Zum Desktop", "", "id=\"live-back\"") + "
" + live_text("Kein Saisonfortschritt · keine Spielwertänderung", "live-bottom-note") + btn("live-review-back", "Zum Ticker", "", "id=\"live-review-back\"") + "
"; + return out; + } + out += "
"; + for (const auto &match : fixture.at("matches")) { + if (live_coverage_ == "single" && match.at("id") != live_selected_match_) continue; + std::string names; + for (const auto &id : match.at("owners")) for (const auto &person : fixture.at("owners")) if (person.at("id") == id) { if (!names.empty()) names += " · "; names += person.at("name").get(); } + out += ""; + } + out += "

" + live_text("Gemeinsamer Live-Ticker") + "

" + live_text(live_coverage_ == "single" ? "Gewählte Partie" : "Alle Manager", "live-small") + "
"; + size_t shown = 0; + for (auto i = frame.at("events").rbegin(); i != frame.at("events").rend(); ++i) { + const auto &event = *i; const auto kind = event.value("kind", ""); + if (live_coverage_ == "single" && event.at("match_id") != live_selected_match_) continue; + if (live_filter_ == "goal" && kind != "goal") continue; + if (live_filter_ == "yellow" && kind != "yellow" && kind != "red") continue; + if (live_filter_ == "highlights" && kind != "goal" && kind != "chance" && kind != "red") continue; + const auto &match = live_match_by_id(fixture.at("matches"), event.at("match_id")); + out += "
()) + "\">" + live_text(std::to_string(event.at("minute").get()) + "′", "live-event-time") + live_badge(match.at(event.at("side").get()), 54) + + "
" + live_text(match.at("home").at("name").get() + " · " + match.at("away").at("name").get(), "live-event-owners") + "

" + live_text(event.at("headline")) + "

" + live_text(event.at("body")) + "

" + live_text(live_score_text(event.at("score")), "live-event-score") + "
"; + ++shown; + } + if (!shown) out += "

" + live_text("Für diesen Filter liegt noch keine Demomeldung vor.") + "

"; + out += "
" + live_text(std::to_string(shown) + " Meldungen · feste Aufzeichnung", "live-small") + "" + esc(phase_text) + "
"; + out += "
" + live_text("+") + "" + esc(live_.finished() ? "Ende" : live_.speed() ? std::to_string(live_.speed()) + "×" : "Pause") + "
"; + out += "
" + btn("live-back", "Zum Desktop", "", "id=\"live-back\"") + btn("live-pause", live_.speed() ? "Pause" : "Abspielen", "", "id=\"live-pause\" " + std::string(live_.finished() ? "disabled" : "")) + "
" + esc(live_feedback_.empty() ? std::string(phase_text) + " · " + std::to_string(minute) + "′ · keine Spielwertänderung" : live_feedback_) + "" + + btn(live_.finished() ? "live-review" : "live-next", live_.finished() ? "Zur Auswertung" : "Nächste Meldung", "", "id=\"" + std::string(live_.finished() ? "live-review" : "live-next") + "\"") + "
"; + return out + live_dialog_markup(owner) + ""; +} +void App::live_after_render() { + if (scene_ != "live" || !live_restore_scroll_) return; + live_restore_scroll_ = false; + if (auto *node = element("live-ticker")) node->SetScrollTop(live_ticker_scroll_); + if (auto *node = element("live-detail-body")) node->SetScrollTop(live_detail_scroll_); + if (!live_dialog_.empty()) { + Rml::ElementList controls; doc_->QuerySelectorAll(controls, "#live-underlay button,#live-speed,.live-bottom button"); + for (auto *node : controls) { node->SetProperty("pointer-events", "none"); node->SetAttribute("tabindex", "-1"); } + } +} diff --git a/src/modern/ui/live_state.inc b/src/modern/ui/live_state.inc new file mode 100644 index 0000000..4fea6d5 --- /dev/null +++ b/src/modern/ui/live_state.inc @@ -0,0 +1,30 @@ +// SPDX-License-Identifier: GPL-3.0-only + LivePlayback live_; + Json live_drafts_ = Json::object(), live_dialog_draft_; + std::string live_tab_ = "team", live_coverage_ = "all", live_filter_ = "all", + live_selected_match_, live_dialog_, live_feedback_, live_out_, live_in_; + uint64_t live_last_tick_ = 0; + const DataSource *live_source_ = nullptr; + std::shared_ptr live_world_; + int live_resume_speed_ = 0; + bool live_speed_dragging_ = false, live_review_ = false, + live_reset_detail_ = false, live_reset_ticker_ = false, + live_restore_scroll_ = false; + float live_ticker_scroll_ = 0, live_detail_scroll_ = 0; + std::string render_live(); + std::string live_roster(const Json &owner); + std::string live_detail(const Json &owner, const Json &frame); + std::string live_dialog_markup(const Json &owner); + std::string live_badge(const Json &, double); + Json live_owner() const; + Json live_owner_rows(const Json &) const; + Json live_owner_state(const Json &) const; + bool live_open(); + void live_close(); + bool live_action(const std::string &, Rml::Element *); + bool live_event(Rml::Event &); + void live_tick(); + void live_after_render(); + void live_set_speed(int); + void live_dialog_close(bool); + Json live_snapshot() const; diff --git a/src/modern/ui/model.cpp b/src/modern/ui/model.cpp index ce38d0e..2ad8317 100644 --- a/src/modern/ui/model.cpp +++ b/src/modern/ui/model.cpp @@ -7,6 +7,7 @@ #include "modern/ui/demo_environment.hpp" #include "modern/ui/demo_finance.hpp" #include "modern/ui/demo_lineup.hpp" +#include "modern/ui/demo_live.hpp" #include "modern/ui/demo_news.hpp" #include "modern/ui/demo_opening.hpp" #include "modern/ui/demo_reports.hpp" @@ -241,6 +242,9 @@ Json DemoSource::read_almanac(const Json &request) const { Json DemoSource::read_statistics(const Json &request) const { return demo_statistics(*catalog_, state_, request); } +Json DemoSource::read_live(const Json &request) const { + return query_demo_live(*catalog_, state_, revision_, request); +} ActionResult DemoSource::apply(const Action &action) { if (action.revision != revision_) return {false, revision_, "stale_revision"}; diff --git a/src/modern/ui/model.hpp b/src/modern/ui/model.hpp index 25a22dc..68401ce 100644 --- a/src/modern/ui/model.hpp +++ b/src/modern/ui/model.hpp @@ -37,6 +37,10 @@ public: virtual Json read_statistics(const Json &) const { return {{"ok", false}, {"error", "statistics_unavailable"}}; } + // Explicit authoritative adapter required; reading never starts a match. + virtual Json read_live(const Json &) const { + return {{"ok", false}, {"error", "live_unavailable"}}; + } }; class DemoSource final : public DataSource { public: @@ -47,6 +51,7 @@ public: ActionResult apply(const Action &) override; Json read_almanac(const Json &) const override; Json read_statistics(const Json &) const override; + Json read_live(const Json &) const override; void save(const fs::path &, const Json &desktop); Json load(const fs::path &); // UI continuation may retain the previous explicit-save clean baseline. diff --git a/src/modern/ui/view.cpp b/src/modern/ui/view.cpp index 892c15a..b51c085 100644 --- a/src/modern/ui/view.cpp +++ b/src/modern/ui/view.cpp @@ -15,6 +15,7 @@ #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_career.hpp" #include "modern/ui/demo_transfer.hpp" #include "modern/ui/demo_career_reports.hpp" @@ -449,6 +450,7 @@ class App final : public Rml::EventListener { #include "modern/ui/widgets_state.inc" #include "modern/ui/files_state.inc" #include "modern/ui/front_state.inc" +#include "modern/ui/live_state.inc" std::map selections_; Rml::Element *element(const std::string &id) const { return doc_->GetElementById(id); @@ -615,6 +617,9 @@ class App final : public Rml::EventListener { } void publish_world(std::shared_ptr next, std::unique_ptr 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(); @@ -936,6 +941,8 @@ class App final : public Rml::EventListener { markup = render_desktop()+"
"+render_career()+"
"; else if (scene_ == "opening") markup = main_menu()+"
"+render_opening()+"
"; + else if (scene_ == "live") + markup = render_live(); else if (source_) markup = render_desktop(); if (!menu_.empty()) @@ -1123,6 +1130,7 @@ class App final : public Rml::EventListener { 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_)) @@ -1385,6 +1393,7 @@ public: while (!closed_) { front_poll(); opening_tick(); + live_tick(); if (needs_render_ || dirty_) frame(); SDL_Event event; @@ -1455,6 +1464,8 @@ public: #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" } // namespace bool is_modern_world(const fs::path &file) { try { diff --git a/tests/modern_live_ui_tests.cpp b/tests/modern_live_ui_tests.cpp new file mode 100644 index 0000000..a4cbb23 --- /dev/null +++ b/tests/modern_live_ui_tests.cpp @@ -0,0 +1,233 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "modern/ui/demo_live.hpp" +#include "modern/ui/demo_career.hpp" +#include "modern/ui/desktop.hpp" +#include "modern/ui/model.hpp" +#include +#include + +using namespace bmh::modern_ui; +namespace { +void require(bool yes, const char *message) { + if (!yes) throw std::runtime_error(message); +} +struct Fixture { + fs::path root; + std::shared_ptr world; + Fixture() : root(fs::temp_directory_path() / bmh::editor::new_id("openbmh-live-test-")) { + fs::create_directories(root / "world"); + const auto write = [&](const char *path, const Json &data) { + bmh::editor::write_atomic(root / path, data.dump()); + }; + write("manifest.json", {{"format", "openbmh-world"}, {"kind", "world"}, + {"format_version", "1.1"}, {"id", "world:synthetic-live"}, + {"start_date", "2032-07-01"}, {"requires", {"editor:world-v1"}}, + {"x-editor", {{"profile", "editor-world-v1"}}}}); + write("world/nations.json", {{"items", {{{"id", "nation:de"}, {"name", "Deutschland"}}, + {{"id", "nation:es"}, {"name", "Spanien"}}}}}); + write("world/competitions.json", {{"items", {{{"id", "competition:de"}, {"name", "Demo-Liga"}, + {"nation", "nation:de"}, {"type", "league"}}}}}); + Json clubs = Json::array(), players = Json::array(); + for (int team = 0; team < 8; ++team) { + const auto id = "club:live-" + std::to_string(team); + clubs.push_back({{"id", id}, {"name", "Demo-Verein " + std::to_string(team)}, + {"nation", "nation:de"}, {"competition", "competition:de"}}); + for (int n = 0; n < 18; ++n) + players.push_back({{"id", "player:live-" + std::to_string(team) + "-" + std::to_string(n)}, + {"name", "Spieler " + std::to_string(team) + "-" + std::to_string(n)}, + {"team", id}, {"squad_order", n}, {"nation", "nation:de"}, + {"positions", Json::array({n < 2 ? "gk" : n < 7 ? "def" : n < 13 ? "mid" : "fwd"})}, + {"attributes", n == 0 ? Json{{"strength", 73}, {"caps", 4}} : Json::object()}}); + } + write("world/clubs.json", {{"items", clubs}}); + write("world/players.json", {{"items", players}}); + world = Catalog::open(root); + } + ~Fixture() { std::error_code error; fs::remove_all(root, error); } +}; +Json start(const std::vector &clubs) { + Json managers = Json::array(); int index = 0; + for (int club : clubs) { + managers.push_back({{"name", "Manager " + std::to_string(index)}, + {"club", "club:live-" + std::to_string(club)}, {"portrait", index}, + {"portrait_style", "photo"}, {"strength_choice", 1}}); + ++index; + } + return {{"setup", {{"duration", 5}, {"difficulty", 3}, {"players", managers.size()}, + {"mode", 3}, {"league", true}, {"world", true}}}, {"managers", managers}}; +} +Json fixture(DemoSource &source) { + const auto snapshot = source.snapshot(); + return make_demo_live(*snapshot.world, snapshot.state, snapshot.revision); +} +} // namespace + +int main(int argc, char **argv) { + try { + struct UnavailableSource final : DataSource { + Snapshot snapshot() const override { return {}; } + ActionResult apply(const Action &) override { return {false, 0, "unavailable"}; } + } unavailable; + require(unavailable.read_live(Json::object()).at("error") == "live_unavailable", "unbound authoritative provider cannot invent live data"); + Fixture f; + DemoSource source(f.world); + require(source.apply({0, "start", start({0,1,2,3})}).ok, "four-human presentation start"); + const auto initial = source.snapshot(); const bool dirty = source.dirty(); + const auto catalog_before = f.world->summary(); + const auto live = fixture(source); + require(valid_live_fixture(live), "well-formed finite authored recording"); + require(live.at("source") == "ui-demo-fixture" && live.at("source_revision") == initial.revision, + "fixture provenance separate from source revision"); + require(live.at("owners").size() == 4 && live.at("matches").size() == 2, + "opposing human owners share one match card"); + require(live.at("matches")[0].at("owners").size() == 2 && + live.at("owners")[0].at("match_id") == live.at("owners")[1].at("match_id"), + "owner IDs remain separate from match ID"); + require(live.at("frames")[1].at("matches")[0].at("standings") == + live.at("frames")[1].at("matches")[1].at("standings"), + "owners in the same catalogue competition share one declared table snapshot"); + require(live == fixture(source), "repeat reads deterministic"); + require(source.read_live({{"kind", "fixture"}}) == live, "DemoSource explicitly overrides read-only live hook"); + auto another_date = initial.state; another_date["date"] = "2032-07-02"; + const auto other_day = make_demo_live(*f.world, another_date, initial.revision); + require(other_day.at("fixture_id") != live.at("fixture_id") && other_day.at("matches")[0].at("id") != live.at("matches")[0].at("id"), + "match/event identity separates worlds/dates from owner identity"); + for (int i = 0; i < 25; ++i) { + require(query_demo_live(*f.world, initial.state, initial.revision, {{"kind", "fixture"}}) == live, + "read query deterministic"); + const auto frame = query_demo_live(*f.world, initial.state, initial.revision, + {{"kind", "frame"}, {"sequence", i % 9}, {"fixture_id", live.at("fixture_id")}}); + require(frame.value("ok", false) && frame.at("sequence") == i % 9, "explicit recorded sequence read"); + } + require(source.snapshot().state == initial.state && source.snapshot().revision == initial.revision && + source.dirty() == dirty && f.world->summary() == catalog_before, + "reads preserve source state, revision, dirty baseline and catalogue"); + require(!query_demo_live(*f.world, initial.state, initial.revision, {{"revision", initial.revision + 1}}).at("ok"), "stale revision rejected"); + for (const auto &query : Json::array({Json{{"kind", "tick"}}, Json{{"sequence", 1}}, + Json{{"kind", "frame"}, {"sequence", -1}}, + Json{{"kind", "frame"}, {"sequence", 9}}, + Json{{"kind", "frame"}, {"sequence", 0.5}}, + Json{{"kind", "fixture"}, {"owner", "manager:0"}}, + Json{{"fixture_id", "wrong"}}})) + require(!query_demo_live(*f.world, initial.state, initial.revision, query).at("ok"), "unsupported/stale request rejected"); + + LivePlayback playback; + require(playback.open(live, "manager:0"), "recording opens paused"); + require(playback.sequence() == 0 && playback.speed() == 0 && !playback.elapse(100000), + "pause never advances recording"); + require(playback.next() && playback.frame().at("minute") == 12, "next reveals predetermined goal snapshot"); + const auto before_owner = playback.frame(); const auto status = playback.status(); + require(playback.cycle_owner(1) && playback.owner() == "manager:1" && playback.frame() == before_owner, + "manager arrow cannot change match clock, score or common ticker"); + require(playback.owner("manager:3") && playback.frame() == before_owner, + "select another match owner does not filter/seek left recording"); + const auto selected = playback.status(); + require(!playback.owner("manager:unknown") && playback.status() == selected, "unknown owner rejected without mutation"); + require(!playback.speed(-1) && !playback.speed(5), "speed bounds"); + require(playback.speed(4) && !playback.elapse(399) && playback.elapse(1) && playback.sequence() == 2, + "elapsed time reveals exactly next authored snapshot"); + require(playback.elapse(1000000) && playback.sequence() == 3, + "delayed window cannot replay unbounded timer backlog"); + require(playback.speed(0) && !playback.elapse(1000000) && playback.frame().at("phase") == "interval", + "pause is only playback state"); + while (playback.next()) {} + require(playback.finished() && playback.frame().at("minute") == 90 && playback.speed() == 0 && + !playback.next() && !playback.speed(1), "outdoor recording ends exactly at90 without season progression"); + require(source.snapshot().state == initial.state && source.snapshot().revision == initial.revision && source.dirty() == dirty, + "playback has no source/session side effects"); + (void)status; + const auto ended_status = playback.status(); auto invalid = live; invalid["source"] = "pretend-engine"; + require(!playback.open(invalid) && playback.status() == ended_status, "reject fictional authority without replacing active recording"); + for (int failure = 0; failure < 5; ++failure) { + invalid = live; + if (failure == 0) invalid["matches"][1]["id"] = invalid["matches"][0]["id"]; + if (failure == 1) invalid["frames"][2]["sequence"] = 7; + if (failure == 2) invalid["frames"][2]["events"][0]["match_id"] = "wrong"; + if (failure == 3) invalid["frames"][2]["matches"][0]["score"][0] = -1; + if (failure == 4) invalid["owners"][0]["match_id"] = "wrong"; + require(!valid_live_fixture(invalid), "malformed external recording rejected"); + } + require(source.apply({source.snapshot().revision, "career", {{"kind", "surface"}, {"value", "indoor"}}}).ok, + "choose existing indoor presentation board"); + auto hall = fixture(source); + require(valid_live_fixture(hall) && hall.at("duration") == 40 && hall.at("field_count") == 6, + "indoor scope duration and field count"); + for (const auto &owner : hall.at("owners")) + require(owner.at("view").at("rows").size() == 18 && owner.at("view").at("on_field_limit") == 6 && + owner.at("view").at("rotation_rows") == 11 && owner.at("view").at("roster_size") == 18 && + owner.at("view").at("roster_limit").is_null() && + owner.at("view").at("board").at("points").size() == 11, + "hall separates six active, five rotation partners and all further reserves without invented roster limit"); + require(playback.open(hall), "indoor recording opens"); while (playback.next()) {} + require(playback.frame().at("minute") == 40 && playback.finished(), "indoor recording ends exactly at40"); + require(source.apply({source.snapshot().revision, "career", {{"kind", "role"}, {"value", "national"}}}).ok, + "choose existing national presentation role"); + const auto national = fixture(source); + require(valid_live_fixture(national) && national.at("owners").size() == 1 && + national.at("owners")[0].at("team").at("id") == "national-de" && + national.at("owners")[0].at("view").at("national_demo_basis") == true, + "national identity and explicit demonstration squad basis"); + require(national.at("frames")[0].at("matches")[0].at("standings").empty(), + "national scope has no invented club league table"); + require(national.at("owners")[0].at("view").at("rows")[0].at("caps") == 4 && + national.at("owners")[0].at("view").at("rows")[1].at("caps").is_null(), + "caps use only catalogue values; unknown is never fabricated"); + auto bad_scope = source.snapshot().state; bad_scope["career"]["surface"] = "indoor"; + require(!make_demo_live(*f.world, bad_scope, 0).at("ok"), "national indoor rejected"); + bad_scope["career"]["surface"] = "outdoor"; bad_scope["career"]["ended"] = true; + require(!make_demo_live(*f.world, bad_scope, 0).at("ok"), "ended career cannot launch recording"); + + DemoSource four(f.world); + require(four.apply({0, "start", start({0,2,4,6})}).ok, "four distinct human matches start"); + require(four.apply({four.snapshot().revision, "tactics", {{"kind", "cycle"}, {"index", 0}}}).ok, + "owner zero has a real presentation tactic edit"); + const auto owner_zero_tactics = four.snapshot().state.at("tactics"); + const auto old_order = four.snapshot().state.at("lineup").at("order"); + require(four.apply({four.snapshot().revision, "lineup", {{"kind", "swap"}, {"a", old_order[1]}, {"b", old_order[4]}}}).ok, + "owner zero has a real presentation lineup edit"); + const auto owner_zero_board = four.snapshot().state.at("lineup"); + const auto four_live = fixture(four); + require(valid_live_fixture(four_live) && four_live.at("matches").size() == 4, "one card per unique human match, up tofour"); + require(four_live.at("owners")[0].at("view").at("tactics") == owner_zero_tactics && + four_live.at("owners")[0].at("view").at("board") == owner_zero_board && + four_live.at("owners")[1].at("view").at("board").at("club") == "club:live-2", + "recording reads actual edited owner board and separate unvisited owner defaults"); + const auto live_id = four_live.at("fixture_id"); + require(four.apply({four.snapshot().revision, "career", {{"kind", "select_manager"}, {"portrait", 2}}}).ok, + "change actual active desktop manager"); + require(fixture(four).at("fixture_id") == live_id, "right-owner identity does not define shared recording identity"); + require(fixture(four).at("owners")[0].at("view").at("board") == owner_zero_board && + fixture(four).at("owners")[0].at("view").at("tactics") == owner_zero_tactics, + "inactive owner board comes from retained career view, never the active manager"); + require(four.mark_saved(four.snapshot().revision), "clean source baseline"); + for (int i = 0; i < 5; ++i) (void)fixture(four); + require(!four.dirty(), "read cannot dirty saved career"); + four.save(f.root / "checkpoint.json", default_desktop()); + const auto checkpoint = Json::parse(bmh::editor::read_file(f.root / "checkpoint.json")); + require(checkpoint.dump().find("ui-demo-fixture") == std::string::npos, "playback never enters career checkpoint"); + DemoSource high_portrait(f.world); auto high_start = start({0}); high_start["managers"][0]["portrait"] = 11; + require(high_portrait.apply({0, "start", high_start}).ok && fixture(high_portrait).at("owners")[0].at("id") == "manager:11", + "all twelve supported portraits retain stable owner identity"); + if (argc == 3 && std::string(argv[1]) == "--write-fixtures") { + fs::create_directories(argv[2]); + fs::copy(f.root / "world", fs::path(argv[2]) / "world", fs::copy_options::recursive | fs::copy_options::overwrite_existing); + fs::copy_file(f.root / "manifest.json", fs::path(argv[2]) / "manifest.json", fs::copy_options::overwrite_existing); + const auto complete = [&](DemoSource &s) { + while (s.snapshot().state.at("opening_flow").at("phase") != "done") { + const auto phase = s.snapshot().state.at("opening_flow").at("phase"); + const auto action = phase == "draw" ? "skip" : phase == "overview" ? "finish" : "next"; + require(s.apply({s.snapshot().revision, "opening.flow", {{"kind", action}}}).ok, "fixture setup preparation"); + } + }; + complete(four); four.save(fs::path(argv[2]) / "demo.json", default_desktop()); + DemoSource paired(f.world); require(paired.apply({0, "start", start({0,1,2,3})}).ok, "paired fixture"); + complete(paired); paired.save(fs::path(argv[2]) / "paired.json", default_desktop()); + DemoSource single(f.world); single.save(fs::path(argv[2]) / "single.json", default_desktop()); + require(single.apply({single.snapshot().revision, "career", {{"kind", "surface"}, {"value", "indoor"}}}).ok, "indoor GUI fixture"); + single.save(fs::path(argv[2]) / "indoor.json", default_desktop()); + require(single.apply({single.snapshot().revision, "career", {{"kind", "role"}, {"value", "national"}}}).ok, "national GUI fixture"); + single.save(fs::path(argv[2]) / "national.json", default_desktop()); + } + std::cout << "live fixture and pure playback tests passed\n"; return 0; + } catch (const std::exception &e) { std::cerr << e.what() << '\n'; return 1; } +} diff --git a/tools/modern_ui/live_demo_qa.py b/tools/modern_ui/live_demo_qa.py new file mode 100644 index 0000000..ba75e7d --- /dev/null +++ b/tools/modern_ui/live_demo_qa.py @@ -0,0 +1,163 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-3.0-only +"""Native RmlUI input/geometry QA using generated synthetic live fixtures. + +Run modern_live_ui_tests --write-fixtures NEWDIR first. This tool never sets a +live sequence or source value: mouse, keyboard, wheel and timer events use the +normal native UI command driver. Evidence stays in the requested output folder. +""" +import argparse, contextlib, datetime, hashlib, json, os, select, subprocess, shutil +from pathlib import Path + +p=argparse.ArgumentParser() +for arg in ['binary','fixtures','gui-assets','output']:p.add_argument('--'+arg,required=True,type=Path) +p.add_argument('--display');p.add_argument('--cases',default='all');a=p.parse_args() +a.output.mkdir(parents=True,exist_ok=True) +def write(path,value):path.write_text(json.dumps(value,ensure_ascii=False,indent=2)+'\n') +def sha(path):return hashlib.sha256(path.read_bytes()).hexdigest() +def tree(path):return {str(x.relative_to(path)):sha(x) for x in sorted(path.rglob('*')) if x.is_file()} +@contextlib.contextmanager +def display(): + if a.display:yield a.display;return + read,send=os.pipe();process=None + try: + with (a.output/'xvfb.log').open('wb') as log: + process=subprocess.Popen(['Xvfb','-displayfd',str(send),'-screen','0','3840x2160x24','-nolisten','tcp'],pass_fds=(send,),stdout=log,stderr=log) + os.close(send);send=-1 + if not select.select([read],[],[],15)[0]:raise RuntimeError('Xvfb did not start') + number=os.read(read,64).decode().strip() + if not number.isdigit():raise RuntimeError('Invalid Xvfb display') + yield ':'+number + finally: + os.close(read) + if send>=0:os.close(send) + if process and process.poll() is None:process.terminate();process.wait(timeout=10) + +selectors=['#live-stage','.live-header','.live-body','.live-left','.live-overview','.live-game','.live-game .live-team-name','.live-ticker','#live-ticker','.live-event','.live-event-copy h3','.live-event-copy p','#live-detail','.live-detail-heading h2','.live-detail-heading p','.live-tabs','.live-tabs button','.live-tabs .control-label','#live-detail-body','.live-roster-row','.live-roster-note','.live-table-row','.live-table-row.heading .live-table-team>span','#live-speed','.live-speed','.live-bottom','.live-bottom button','.live-bottom .control-label','#live-dialog','#live-dialog button','#live-dialog select','.live-review','.live-review-card'] +def commands(folder,full): + rows=[] + def event(t,**kw):rows.append(dict(type=t,**kw)) + def click(s):event('click',selector=s) + def key(v,**kw):event('key',value=v,**kw) + def cap(name,png=False): + event('snapshot',path=str(folder/(name+'.json')));event('dom',path=str(folder/(name+'.rml')));event('metrics',selectors=selectors,path=str(folder/(name+'.metrics.json'))) + if png:event('screenshot',path=str(folder/(name+'.png'))) + cap('before');click('#object-app-kickoff');event('assert',scene='live');cap('start',True) + for _ in range(3):click('#live-next') + cap('interval',False) + event('wheel',selector='#live-ticker',delta=5);event('wait',milliseconds=150);cap('scroll-before') + click('#live-owner-next');cap('owner') + click('#live-coverage-single');cap('single-before');click('#live-match-next');cap('left-selected');click('#live-owner-next');cap('single-after') + click('#live-coverage-all');click('#live-tab-tactics');cap('tactics',True) + if full: + click('#live-tactics-edit');cap('tactic-dialog');key('TAB');cap('dialog-tab');key('TAB',shift=True);cap('dialog-reverse-tab');click('#live-tactic-0');click('#live-dialog-cancel');cap('tactic-cancel') + click('#live-tactics-edit');click('#live-tactic-0');click('#live-dialog-apply');cap('tactic-applied') + click('#live-tab-team');click('#live-lineup-edit');cap('lineup-dialog');click('#live-player-in');key('END');key('ENTER');cap('lineup-choice');click('#live-dialog-apply');cap('lineup-applied') + click('#live-tab-opponent');cap('opponent',False);click('#live-tab-table');cap('table',True);click('#live-tab-stats');cap('statistics',True) + click('#live-speed');key('HOME');cap('paused');event('wait',milliseconds=1050);cap('paused-after');key('END');event('wait',milliseconds=450);key('P');cap('played') + for _ in range(4):click('#live-next') + event('assert',selector='#live-review');cap('end',full);click('#live-review');cap('report',True);click('#live-review-back');click('#live-back');event('assert',scene='desktop');cap('after') + return rows + +checks=[] +def check(ok,label): + checks.append({'passed':bool(ok),'name':label}) + if not ok:raise AssertionError(label) +def validate(folder,expected,full): + def snap(n):return json.loads((folder/(n+'.json')).read_text()) + before=snap('before');start=snap('start');begin=start['live_view'];phase=snap('interval')['live_view'] + check(begin['source']=='ui-demo-fixture' and begin['sequence']==0 and begin['speed']==0,'explicit recording opens paused') + check(len(begin['matches'])==expected,'unique match count') + check(phase['frame']['phase']=='interval' and phase['sequence']==3,'authored interval reached through native Next clicks') + owner=snap('owner')['live_view'];scroll=snap('scroll-before')['live_view'] + check(owner['frame']==phase['frame'] and owner['owner']!=phase['owner'],'right manager arrow does not advance or replace common frame') + check(abs(owner['ticker_scroll']-scroll['ticker_scroll'])<=1,'right manager arrow preserves actual wheel scroll position') + check(scroll['ticker_scroll']>0,'real mouse wheel scroll exercised') + left=snap('left-selected')['live_view'];right=snap('single-after')['live_view'] + check(left['selected_match']!=snap('single-before')['live_view']['selected_match'],'independent left match arrow works') + check(left['selected_match']==right['selected_match'] and left['frame']==right['frame'] and left['owner']!=right['owner'],'right owner never redirects selected left match') + if full: + check(snap('dialog-tab')['focus']=='live-dialog-apply' and snap('dialog-reverse-tab')['focus']=='live-dialog-cancel','native dialog Tab/ShiftTab remains trapped and reversible') + check(snap('tactic-cancel')['live_view']['drafts']=={},'tactic cancel discards local draft') + applied=snap('tactic-applied')['live_view'];chosen=next(o for o in applied['owners'] if o['id']==applied['owner']) + check(applied['drafts'][applied['owner']]['tactics']!=chosen['view']['edit_state']['tactics'],'tactic acceptance changes only explicit local preview') + lineup=snap('lineup-applied')['live_view'];draft=lineup['drafts'][lineup['owner']];board=draft.get('indoor_lineup') if begin['owners'][0]['view']['on_field_limit']==6 else draft['lineup'];origin=chosen['view']['board'] + check(board['order'][0]==origin['order'][-1] and board['order'][-1]==origin['order'][0],'native picker accepts last actual reserve without invented limit') + check(lineup['frame']==phase['frame'],'local lineup/tactic proposal cannot change recording frame') + paused=snap('paused')['live_view'];after_pause=snap('paused-after')['live_view'];played=snap('played')['live_view'];end=snap('end')['live_view'] + check(snap('paused')['focus']=='live-speed','speed slider retains keyboard focus after real mouse click') + check(paused['speed']==after_pause['speed']==0 and paused['frame']==after_pause['frame'],'native speed0 wait has no playback advancement') + check(played['sequence']==4 and played['speed']==0,'native End/timer/P reveals exactly next authored snapshot then pauses') + check(end['finished'] and end['frame']['minute']==90 and end['speed']==0,'outdoor recording stops at90') + check(snap('report')['live_view']['review'],'actual results/report navigation') + for name in ['start','interval','owner','single-after','tactic-cancel','tactic-applied','lineup-applied','paused-after','played','end','report','after']: + if not (folder/(name+'.json')).exists():continue + s=snap(name);check(s['demo']==before['demo'] and s['source_revision']==before['source_revision'] and s['game_dirty']==before['game_dirty'] and s['desktop']==before['desktop'],'source/revision/dirty/desktop invariant '+name) + for name in ['start','tactics','table','statistics','report']: + file=folder/(name+'.metrics.json') + if not file.exists():continue + metrics=json.loads(file.read_text());stage=next(r for r in metrics if r['id']=='live-stage') + check(abs(stage['width']/stage['height']-16/9)<.0001,'fixed proportional canvas '+name) + for r in metrics: + if not r['visible']:continue + if r['selector'] in ['.live-tabs .control-label','.live-bottom .control-label']:check(r['width']>0 and r['height']>0 and r.get('rml','').strip()!='','actual native button text has area '+name+' '+r['id']) + if r['width']<=0 or r['height']<=0:continue + if r['selector'] in ['.live-event','.live-event-copy h3','.live-event-copy p','.live-roster-row','.live-roster-note','.live-table-row','.live-review-card']:continue # intentional inner scroll content + check(r['x']>=stage['x']-1 and r['y']>=stage['y']-1 and r['x']+r['width']<=stage['x']+stage['width']+1 and r['y']+r['height']<=stage['y']+stage['height']+1,'visible box inside canvas '+name+' '+r['selector']+' '+r['id']) + if r['selector'] in ['.live-tabs .control-label','.live-bottom .control-label']: + check(r['width']>0 and r['height']>0 and r.get('rml','').strip()!='','actual native button text has area '+name+' '+r['id']) + if full: + table=json.loads((folder/'table.metrics.json').read_text());head=[r for r in table if r['selector']=='.live-table-row.heading .live-table-team>span'];check(len(head)==1 and head[0]['width']>0 and head[0]['height']>0 and head[0]['rml']=='Verein','native club table heading actually has visible text area') + cards=json.loads((folder/'start.metrics.json').read_text());cards=[r for r in cards if r['selector']=='.live-game'] + check(len(cards)==expected and len(set(round(r['y'],1) for r in cards))==(2 if expected>2 else 1),'match cards use actual one/two-row layout') + check('referee' not in (folder/'start.rml').read_text() and 'manager-tabs' not in (folder/'start.rml').read_text(),'no referee or top manager tab bar') + +def special_commands(folder,kind): + rows=[] + def e(t,**kw):rows.append(dict(type=t,**kw)) + def click(s):e('click',selector=s) + def cap(n,png=False): + e('snapshot',path=str(folder/(n+'.json')));e('dom',path=str(folder/(n+'.rml')));e('metrics',selectors=selectors,path=str(folder/(n+'.metrics.json'))) + if png:e('screenshot',path=str(folder/(n+'.png'))) + click('#object-app-newplayer');click('#career-role-national' if kind=='national' else '#career-surface-indoor');click('#window-close');cap('before');click('#object-app-kickoff');e('assert',scene='live');e('assert',selector='#live-owner-next',disabled=True);cap('start',True) + click('#live-tab-table');cap('table',True);click('#live-tab-team');click('#live-lineup-edit');click('#live-player-in');e('key',value='END');e('key',value='ENTER');cap('reserve-choice',True);click('#live-dialog-apply');cap('lineup-applied',True) + for _ in range(8):click('#live-next') + cap('end',True);click('#live-review');cap('report',True);click('#live-back');cap('after');e('assert',scene='desktop');return rows + +def validate_special(folder,kind): + def snap(n):return json.loads((folder/(n+'.json')).read_text()) + before=snap('before');start=snap('start');v=start['live_view'];owner=v['owners'][0] + check(v['source']=='ui-demo-fixture' and len(v['owners'])==1 and len(v['matches'])==1,'single owner scoped recording '+kind) + check(before['career_context']['role']==('national' if kind=='national' else 'club') and before['career_context']['surface']==('indoor' if kind=='indoor' else 'outdoor'),'actual manager hub scope command '+kind) + if kind=='national': + check(owner['team']['id']=='national-de' and 'Deutschland' in (folder/'start.rml').read_text() and 'Caps' in (folder/'start.rml').read_text(),'actual national identity and separate Caps heading') + check('live-table-row' not in (folder/'table.rml').read_text() and 'keiner Liga' in (folder/'table.rml').read_text(),'national live table has no club data') + else: + check(owner['view']['on_field_limit']==6 and owner['view']['rotation_rows']==11 and owner['view']['roster_size']==18 and owner['view']['roster_limit'] is None,'six active eleven rotation and actual unbounded reserves separated') + dom=(folder/'start.rml').read_text();check('Rotationspartner' in dom and 'Weitere Kaderreserven' in dom and dom.count('data-live-player=')==18,'all native hall groups and genuine reserves visible in roster') + swapped=snap('lineup-applied')['live_view'];draft=swapped['drafts'][swapped['owner']];board=draft['indoor_lineup' if kind=='indoor' else 'lineup'];original=owner['view']['board']['order'] + check(board['order'][0]==original[-1] and board['order'][-1]==original[0],'last actual reserve can enter local preview '+kind) + check(snap('end')['live_view']['frame']['minute']==(40 if kind=='indoor' else 90) and snap('end')['live_view']['finished'],'scope-specific exact recording finish '+kind) + for n in ['start','table','reserve-choice','lineup-applied','end','report','after']: + s=snap(n);check(s['demo']==before['demo'] and s['source_revision']==before['source_revision'] and s['game_dirty']==before['game_dirty'],'scope recording/preview never mutates source '+kind+' '+n) + +matrix=[(f'{theme}-{w}x{h}',theme,w,h,'demo.json',4,w==1920,None) for theme in ['midnight','silver','matchday'] for w,h in [(1920,1080),(1280,720)]] +matrix += [('paired','midnight',1920,1080,'paired.json',2,True,None),('national','midnight',1920,1080,'single.json',1,False,'national'),('indoor','midnight',1920,1080,'single.json',1,False,'indoor'),('midnight-3840x2160','midnight',3840,2160,'demo.json',4,False,None)] +receipt={'created':datetime.datetime.now(datetime.timezone.utc).isoformat(),'binary_before':sha(a.binary),'runtime_before':tree(a.binary.parent/'assets/modern'),'fixtures_before':tree(a.fixtures),'cases':[]} +try: + with display() as screen: + for name,theme,w,h,state,count,full,special in matrix: + if a.cases!='all' and name not in a.cases.split(','):continue + folder=a.output/name;folder.mkdir(exist_ok=True);script=folder/'script.jsonl';script.write_text(''.join(json.dumps(v,ensure_ascii=False)+'\n' for v in (special_commands(folder,special) if special else commands(folder,full)))) + cmd=[str(a.binary),'--modern-ui-demo','--mod',str(a.fixtures),'--ui-state',str(a.fixtures/state),'--gui-assets',str(a.gui_assets),'--ui-scene','desktop','--ui-theme',theme,'--ui-size',f'{w}x{h}','--ui-script',str(script),'--ui-preferences',str(folder/'preferences.json'),'--ui-userdata',str(folder/'userdata'),'--ui-screenshot',str(folder/'last.png')];write(folder/'command.json',cmd) + run=subprocess.run(cmd,env=os.environ|{'DISPLAY':screen,'OPENBMH_NO_ERROR_DIALOG':'1'},capture_output=True,text=True,timeout=180);(folder/'native.log').write_text(run.stdout+run.stderr) + record={'case':name,'exit_code':run.returncode};receipt['cases'].append(record);write(a.output/'receipt.json',receipt) + check(run.returncode==0,'native process normal exit '+name) + check('live.rcss:' not in run.stdout+run.stderr,'live RCSS parses without errors '+name) + check(json.loads((folder/'start.json').read_text())['ui_preferences']['theme']==theme,'actual applied native theme '+name) + start=len(checks);validate_special(folder,special) if special else validate(folder,count,full);record['passed']=len(checks)-start;write(folder/'checks.json',checks[start:]);print(name,record['passed'],'passed',flush=True) + receipt['binary_after']=sha(a.binary);receipt['runtime_after']=tree(a.binary.parent/'assets/modern');receipt['fixtures_after']=tree(a.fixtures) + check(receipt['binary_before']==receipt['binary_after'],'binary unchanged throughout cohort');check(receipt['runtime_before']==receipt['runtime_after'],'runtime unchanged throughout cohort');check(receipt['fixtures_before']==receipt['fixtures_after'],'fixture source files unchanged throughout cohort');receipt['status']='passed' +except Exception as e:receipt['status']='failed';receipt['error']=str(e);raise +finally: + receipt['checks']=checks;write(a.output/'receipt.json',receipt)