From 11a6356c1e2c78124d953f8d8d5d5e763309f033 Mon Sep 17 00:00:00 2001 From: Codex Date: Fri, 23 Oct 2026 18:51:02 +0200 Subject: [PATCH] Add opt-in native Modern UI foundation and first desktop flow (by Codex) --- CMakeLists.txt | 15 +- assets/modern/icons/ball.svg | 2 + assets/modern/icons/chart.svg | 2 + assets/modern/icons/check.svg | 2 + assets/modern/icons/coins.svg | 2 + assets/modern/icons/heart.svg | 2 + assets/modern/icons/lock.svg | 2 + assets/modern/icons/person.svg | 2 + assets/modern/icons/pitch.svg | 2 + assets/modern/icons/save.svg | 2 + assets/modern/icons/shirt.svg | 2 + assets/modern/icons/star.svg | 2 + assets/modern/icons/trash.svg | 2 + assets/modern/icons/world.svg | 2 + assets/modern/modern.rml | 10 + assets/modern/theme.rcss | 141 +++ assets/modern/ticket.rcss | 36 + docs/new_ui/NATIVE_STATUS.md | 99 ++ docs/new_ui/PLAN.md | 4 +- docs/new_ui/README.md | 1 + docs/new_ui/desktop/entry-price/README.md | 4 +- src/app/main.cpp | 57 +- src/editor/CMakeLists.txt | 16 +- src/modern/ui/CMakeLists.txt | 46 + src/modern/ui/catalog.cpp | 216 ++++ src/modern/ui/catalog.hpp | 40 + src/modern/ui/controls.inc | 1195 +++++++++++++++++++++ src/modern/ui/desktop.cpp | 239 +++++ src/modern/ui/desktop.hpp | 20 + src/modern/ui/desktop_screens.inc | 92 ++ src/modern/ui/gui_assets.cpp | 62 ++ src/modern/ui/gui_assets.hpp | 20 + src/modern/ui/model.cpp | 184 ++++ src/modern/ui/model.hpp | 42 + src/modern/ui/screens.inc | 958 +++++++++++++++++ src/modern/ui/ticket_popover.cpp | 392 +++++++ src/modern/ui/ticket_popover.hpp | 56 + src/modern/ui/view.cpp | 859 +++++++++++++++ src/modern/ui/view.hpp | 16 + tests/modern_ticket_document_tests.cpp | 201 ++++ tests/modern_ui_core_tests.cpp | 186 ++++ tools/modern_ui/prepare_gui_assets.py | 109 ++ 42 files changed, 5333 insertions(+), 9 deletions(-) create mode 100644 assets/modern/icons/ball.svg create mode 100644 assets/modern/icons/chart.svg create mode 100644 assets/modern/icons/check.svg create mode 100644 assets/modern/icons/coins.svg create mode 100644 assets/modern/icons/heart.svg create mode 100644 assets/modern/icons/lock.svg create mode 100644 assets/modern/icons/person.svg create mode 100644 assets/modern/icons/pitch.svg create mode 100644 assets/modern/icons/save.svg create mode 100644 assets/modern/icons/shirt.svg create mode 100644 assets/modern/icons/star.svg create mode 100644 assets/modern/icons/trash.svg create mode 100644 assets/modern/icons/world.svg create mode 100644 assets/modern/modern.rml create mode 100644 assets/modern/theme.rcss create mode 100644 assets/modern/ticket.rcss create mode 100644 docs/new_ui/NATIVE_STATUS.md create mode 100644 src/modern/ui/CMakeLists.txt create mode 100644 src/modern/ui/catalog.cpp create mode 100644 src/modern/ui/catalog.hpp create mode 100644 src/modern/ui/controls.inc create mode 100644 src/modern/ui/desktop.cpp create mode 100644 src/modern/ui/desktop.hpp create mode 100644 src/modern/ui/desktop_screens.inc create mode 100644 src/modern/ui/gui_assets.cpp create mode 100644 src/modern/ui/gui_assets.hpp create mode 100644 src/modern/ui/model.cpp create mode 100644 src/modern/ui/model.hpp create mode 100644 src/modern/ui/screens.inc create mode 100644 src/modern/ui/ticket_popover.cpp create mode 100644 src/modern/ui/ticket_popover.hpp create mode 100644 src/modern/ui/view.cpp create mode 100644 src/modern/ui/view.hpp create mode 100644 tests/modern_ticket_document_tests.cpp create mode 100644 tests/modern_ui_core_tests.cpp create mode 100644 tools/modern_ui/prepare_gui_assets.py diff --git a/CMakeLists.txt b/CMakeLists.txt index ec862e1..74c03c2 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -349,9 +349,13 @@ else() target_compile_options(bmh_modern_session PRIVATE -Wall -Wextra) endif() option(OPENBMH_BUILD_EDITOR "Build the standalone OBW editor" OFF) -if(OPENBMH_BUILD_EDITOR) +option(OPENBMH_BUILD_MODERN_UI "Build the experimental native Modern UI demonstration" OFF) +if(OPENBMH_BUILD_EDITOR OR OPENBMH_BUILD_MODERN_UI) add_subdirectory(src/editor) endif() +if(OPENBMH_BUILD_MODERN_UI) + add_subdirectory(src/modern/ui) +endif() target_link_libraries(bmhui PUBLIC bmh_content) add_executable(driver_barrier_tests tests/driver_barrier_tests.cpp) target_link_libraries(driver_barrier_tests PRIVATE bmhcore) @@ -476,6 +480,10 @@ add_executable(openbmh_play ${BMH_APP_CONTROLLER_SOURCE} ${BMH_APP_SESSION_SDL_SOURCE}) target_link_libraries(openbmh_play PRIVATE bmhui bmh_launcher bmhlaunch_dialog openbmh_audio ${BMH_SDL_TARGET}) +if(OPENBMH_BUILD_MODERN_UI) + target_link_libraries(openbmh_play PRIVATE bmh_modern_ui) + target_compile_definitions(openbmh_play PRIVATE OPENBMH_MODERN_UI=1) +endif() # a game without a console window on double-click (SDL2main provides WinMain); started from a # console it attaches to that one for --version, --help and start errors (src/app/main.cpp) set_target_properties(openbmh_play PROPERTIES WIN32_EXECUTABLE TRUE OUTPUT_NAME OpenBMH) @@ -483,6 +491,11 @@ if(CMAKE_CONFIGURATION_TYPES) add_custom_command(TARGET openbmh_play POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_directory "${CMAKE_BINARY_DIR}/assets/launcher" "$/assets/launcher") + if(OPENBMH_BUILD_MODERN_UI) + add_custom_command(TARGET openbmh_play POST_BUILD + COMMAND ${CMAKE_COMMAND} -E copy_directory "${CMAKE_BINARY_DIR}/assets/modern" + "$/assets/modern") + endif() endif() if(MSVC) target_compile_options(openbmh_play PRIVATE /utf-8) diff --git a/assets/modern/icons/ball.svg b/assets/modern/icons/ball.svg new file mode 100644 index 0000000..448d88e --- /dev/null +++ b/assets/modern/icons/ball.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/modern/icons/chart.svg b/assets/modern/icons/chart.svg new file mode 100644 index 0000000..ef65b97 --- /dev/null +++ b/assets/modern/icons/chart.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/modern/icons/check.svg b/assets/modern/icons/check.svg new file mode 100644 index 0000000..c2d69d0 --- /dev/null +++ b/assets/modern/icons/check.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/modern/icons/coins.svg b/assets/modern/icons/coins.svg new file mode 100644 index 0000000..175fc56 --- /dev/null +++ b/assets/modern/icons/coins.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/modern/icons/heart.svg b/assets/modern/icons/heart.svg new file mode 100644 index 0000000..5803a6f --- /dev/null +++ b/assets/modern/icons/heart.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/modern/icons/lock.svg b/assets/modern/icons/lock.svg new file mode 100644 index 0000000..f9c475e --- /dev/null +++ b/assets/modern/icons/lock.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/modern/icons/person.svg b/assets/modern/icons/person.svg new file mode 100644 index 0000000..78bf2ff --- /dev/null +++ b/assets/modern/icons/person.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/modern/icons/pitch.svg b/assets/modern/icons/pitch.svg new file mode 100644 index 0000000..25aaf82 --- /dev/null +++ b/assets/modern/icons/pitch.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/modern/icons/save.svg b/assets/modern/icons/save.svg new file mode 100644 index 0000000..bf679d5 --- /dev/null +++ b/assets/modern/icons/save.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/modern/icons/shirt.svg b/assets/modern/icons/shirt.svg new file mode 100644 index 0000000..744c42d --- /dev/null +++ b/assets/modern/icons/shirt.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/modern/icons/star.svg b/assets/modern/icons/star.svg new file mode 100644 index 0000000..4488bb7 --- /dev/null +++ b/assets/modern/icons/star.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/modern/icons/trash.svg b/assets/modern/icons/trash.svg new file mode 100644 index 0000000..60b2e21 --- /dev/null +++ b/assets/modern/icons/trash.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/modern/icons/world.svg b/assets/modern/icons/world.svg new file mode 100644 index 0000000..36ac7a9 --- /dev/null +++ b/assets/modern/icons/world.svg @@ -0,0 +1,2 @@ + + diff --git a/assets/modern/modern.rml b/assets/modern/modern.rml new file mode 100644 index 0000000..02057ec --- /dev/null +++ b/assets/modern/modern.rml @@ -0,0 +1,10 @@ + +OpenBMH + +
+
+ +
+
+ +
diff --git a/assets/modern/theme.rcss b/assets/modern/theme.rcss new file mode 100644 index 0000000..78f8bd6 --- /dev/null +++ b/assets/modern/theme.rcss @@ -0,0 +1,141 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ +* { box-sizing:border-box; } +div,h1,h2,h3,p,label,header,section,aside,footer,nav {display:block;} +span,small,strong {display:inline-block;} +body { + --text:#e9f0f6;--muted:#afbfcd;--accent:#a5e2cf;--desk-top:#3c5264a8;--desk-bottom:#172b3ee0; + --strong:#152a3af5;--soft:#d4eaff0b;--border:#e0f0ff2b; + --menu-top:#303c49eb;--menu-bottom:#1a2531f2;--panel:#12243155;--input:#172633b0; + --hover:#bad5f21a;--selected:#477f7c77;--danger:#f0aaa7;--on-accent:#152a3a; + margin:0;width:100%;height:100%;overflow:hidden;font-family:Modern;font-size:32dp;color:var(--text);background-color:#0b121c; +} +body.silver { + --text:#233443;--muted:#526779;--accent:#25617a;--desk-top:#f4f9f3e6;--desk-bottom:#d6e1e9e8; + --strong:#e7f0f5fc;--soft:#315b7110;--border:#6c879c4a; + --menu-top:#f0f5f9f5;--menu-bottom:#d4e0eaf5;--panel:#f1f6fa80;--input:#ffffffad; + --hover:#9eb9d43b;--selected:#a3c3dd54;--danger:#a23f45;--on-accent:#f7fcff; +} +body.matchday { + --text:#efeded;--muted:#b7b4b9;--accent:#efb2aa;--desk-top:#303238f5;--desk-bottom:#1d2025f2; + --strong:#272a30fc;--soft:#f9f4ed0b;--border:#ead9da29; + --menu-top:#343338f5;--menu-bottom:#202126f7;--panel:#1d1e2466;--input:#191a208a; + --hover:#d5b3b423;--selected:#d48c7b26;--danger:#f0a6a7;--on-accent:#2a2022; +} +#background {position:absolute;left:0;top:0;width:100%;height:100%;overflow:hidden;} +#canvas {position:absolute;width:3840dp;height:2160dp;overflow:hidden;} +button,input,select,textarea {font-family:Modern;color:var(--text);font-size:32dp;} +button {padding:16dp 26dp;background-color:var(--soft);border:2dp var(--border);border-radius:14dp;cursor:pointer;text-align:center;tab-index:auto;} +button:hover {background-color:var(--hover);} +button:disabled,button[disabled] {opacity:0.4;cursor:default;tab-index:none;} +button:focus-visible,input:focus-visible,select:focus-visible {border-color:var(--accent);} +button.primary {background-color:var(--selected);border-color:var(--accent);} +input,select,textarea {padding:14dp 20dp;border:2dp var(--border);border-radius:12dp;background-color:var(--input);tab-index:auto;} +select {width:520dp;padding-right:45dp;} +.row select,.toolbar select {flex:1;min-width:0;} +select selectvalue {padding-right:24dp;} +select selectarrow {width:10dp;height:10dp;margin-right:-12dp;margin-top:6dp;border-bottom:2dp var(--muted);border-right:2dp var(--muted);transform:rotate(45deg);} +select selectbox {padding:8dp;border:2dp var(--border);border-radius:12dp;background-color:var(--strong);max-height:760dp;} +select option {font-size:32dp;padding:12dp 20dp;min-height:42dp;} +select option:hover,select option:checked {background-color:var(--selected);} +scrollbarvertical {width:18dp;} +scrollbarhorizontal {height:18dp;} +scrollbarvertical slidertrack,scrollbarhorizontal slidertrack {background-color:var(--soft);} +scrollbarvertical sliderbar {width:10dp;margin:4dp;border-radius:5dp;background-color:var(--muted);} +scrollbarhorizontal sliderbar {height:10dp;margin:4dp;border-radius:5dp;background-color:var(--muted);} +scrollbarvertical sliderarrowinc,scrollbarvertical sliderarrowdec,scrollbarhorizontal sliderarrowinc,scrollbarhorizontal sliderarrowdec {display:none;} +input[type=range] {height:60dp;padding:0;background-color:transparent;border-width:0;flex-shrink:0;} +input[type=range] slidertrack {height:8dp;margin:26dp 0;background-color:var(--muted);border-radius:4dp;} +input[type=range] sliderbar {width:36dp;height:36dp;margin-top:12dp;background-color:var(--accent);border:4dp var(--strong);border-radius:18dp;} +input[type=range] sliderarrowinc,input[type=range] sliderarrowdec {display:none;} +input[type=checkbox] {width:38dp;height:38dp;padding:0;border-radius:9dp;} +input[type=checkbox]:checked {background-color:var(--accent);} +h1,h2,h3,p {margin:0;} +h1 {font-size:40dp;font-weight:bold;} +h2 {font-size:38dp;font-weight:normal;} +h3 {font-size:31dp;font-weight:bold;} +.small {font-size:26dp;color:var(--muted);} +.muted {color:var(--muted);} +.accent {color:var(--accent);} +.row {display:flex;align-items:center;gap:24dp;} +.column {display:flex;flex-direction:column;gap:24dp;} +.center {text-align:center;} +.grow {flex:1;} +.fill {position:absolute;left:0;top:0;width:100%;height:100%;} +.clip {overflow:hidden;} +.image-frame {overflow:hidden;display:flex;align-items:center;justify-content:center;} +.center>.image-frame {margin-left:auto;margin-right:auto;} +.front-shade {decorator:linear-gradient(90deg,#061019f5,#08131dea 29%,#09151d8c 55%,#07131c33 80%);} +.brand {position:absolute;left:320dp;top:340dp;} +.brand p {font-size:28dp;letter-spacing:10dp;color:#9cb7c3;margin:0 0 28dp 8dp;} +.brand h1 {font-size:174dp;letter-spacing:-7dp;color:#f0f4f5;font-weight:bold;} +.brand span {color:#a9d5c9;} +.main-options {position:absolute;left:308dp;top:764dp;width:1250dp;} +.main-options button {display:block;width:100%;height:128dp;margin-bottom:18dp;padding:18dp 38dp;background-color:transparent;border-color:transparent;text-align:left;font-size:59dp;font-weight:normal;color:#d3dfe7;} +.main-options button:hover,.main-options button:focus {background-color:#b5dbd51a;border-color:#c6e3df26;color:#ecf9f4;} +.main-options button:disabled {color:#7a8f9e;} +.main-options small {font-size:25dp;margin-left:36dp;} +.front-footer {position:absolute;left:346dp;right:180dp;bottom:140dp;display:flex;align-items:flex-end;justify-content:space-between;color:#bacdd7;} +.front-footer p {font-size:29dp;} +.front-footer small {font-size:22dp;color:#849dad;} +.window {position:absolute;left:560dp;top:60dp;width:2720dp;height:2040dp;overflow:hidden;border:2dp var(--border);border-radius:30dp;decorator:linear-gradient(155deg,var(--menu-top),var(--menu-bottom));backdrop-filter:blur(36dp);box-shadow:0dp 24dp 70dp #0008;} +.titlebar {position:absolute;left:0;top:0;width:100%;height:108dp;display:flex;align-items:center;padding:0 28dp;border-bottom:2dp var(--border);background-color:var(--soft);} +.titlebar h1 {flex:1;text-align:center;margin-right:76dp;} +.close {width:76dp;height:76dp;padding:0;border-width:0;background-color:transparent;} +.close span {display:block;width:48dp;height:48dp;margin:13dp;border-radius:24dp;background-color:#fa6a60;color:#592420;font-size:37dp;text-align:center;} +.content {position:absolute;left:52dp;right:52dp;top:148dp;bottom:24dp;overflow:hidden;} +.panel {border:2dp var(--border);border-radius:18dp;background-color:var(--panel);overflow:hidden;} +.toolbar {display:flex;align-items:center;gap:24dp;} +.toolbar button,.toolbar select {min-height:86dp;} +.bottom-controls {position:absolute;left:0;right:0;bottom:0;height:94dp;display:flex;gap:24dp;} +.bottom-controls button,.bottom-controls select {flex:1;height:94dp;} +.list {overflow:auto;} +.table {width:100%;display:table;font-size:36dp;} +.table .tr {display:table-row;} +.table .th,.table .td {display:table-cell;vertical-align:middle;padding:12dp 16dp;height:78dp;border-bottom:1dp var(--border);} +.table .th {font-size:30dp;color:var(--muted);} +.table .tr.odd {background-color:var(--soft);} +.table .tr:hover {background-color:var(--hover);} +.table button {background-color:transparent;border-width:0;padding:0;text-align:left;font-size:36dp;} +.club-label {display:flex;align-items:center;gap:20dp;} +.club-label img {flex-shrink:0;} +.rank {width:75dp;text-align:right;color:var(--muted);} +.info-bar {position:absolute;left:0;top:0;width:100%;height:148dp;display:flex;align-items:center;gap:64dp;padding:0 64dp;border-bottom:2dp var(--border);decorator:linear-gradient(145deg,var(--desk-top),var(--desk-bottom));backdrop-filter:blur(48dp);} +.identity {display:flex;align-items:center;gap:26dp;min-width:650dp;padding:0;background-color:transparent;border-width:0;text-align:left;} +.identity strong {font-size:38dp;} +.identity small {display:block;font-size:27dp;color:var(--muted);margin-top:8dp;} +.info-date {margin-left:auto;min-width:430dp;font-size:34dp;} +.info-date small {display:block;font-size:27dp;color:var(--muted);margin-top:8dp;} +.info-cash {min-width:450dp;padding-left:58dp;border-left:2dp var(--border);} +.info-cash small {display:block;font-size:27dp;color:var(--muted);} +.info-cash strong {font-size:40dp;color:var(--accent);} +.desktop-card {position:absolute;border:2dp var(--border);border-radius:36dp;decorator:linear-gradient(145deg,var(--desk-top),var(--desk-bottom));backdrop-filter:blur(34dp);overflow:hidden;} +.desktop-card.pinned {border-color:var(--border);} +.card-heading {position:absolute;left:30dp;right:30dp;top:22dp;color:var(--muted);font-size:25dp;} +.card-button {position:absolute;background-color:transparent;border-width:0;padding:0;} +.desktop-app {position:absolute;width:224dp;height:224dp;padding:0;background-color:transparent;border-width:0;text-align:center;} +.app-tile {position:absolute;left:25dp;top:0;width:174dp;height:174dp;padding:12dp;border:2dp #e3efff59;border-radius:42dp;decorator:linear-gradient(140deg,#597d8e,#274956);box-shadow:0dp 12dp 25dp #0005;} +.app-name {position:absolute;left:-20dp;top:190dp;width:264dp;font-size:29dp;color:#f6f8fa;} +.desktop-app:hover .app-tile {background-color:#ffffff20;} +.pin-dot {position:absolute;right:16dp;top:16dp;width:14dp;height:14dp;border-radius:7dp;background-color:var(--accent);} +.field-row {display:flex;align-items:center;justify-content:space-between;gap:28dp;min-height:112dp;padding:20dp 0;border-bottom:2dp var(--border);} +.field-row label {flex:1;font-size:32dp;} +.field-row input,.field-row select {width:540dp;} +.choice {padding:24dp;border:2dp var(--border);border-radius:18dp;background-color:var(--panel);} +.choice.selected {background-color:var(--selected);border-color:var(--accent);} +.choice.locked {opacity:0.4;} +#popup {position:absolute;left:0;top:0;width:100%;height:100%;display:none;align-items:center;justify-content:center;z-index:200;} +#popup.visible {display:flex;} +.popup-backdrop {background-color:#08101980;} +.popup-box {position:relative;width:1500dp;padding:50dp;border:2dp var(--border);border-radius:24dp;background-color:var(--strong);} +.popup-box h2 {margin-bottom:30dp;} +.popup-box p {font-size:32dp;line-height:1.5;margin-bottom:30dp;} +.popup-box footer {display:flex;justify-content:flex-end;gap:20dp;} +#toast {position:absolute;left:50%;bottom:20dp;width:1100dp;margin-left:-550dp;padding:18dp 30dp;border:2dp var(--border);border-radius:18dp;background-color:var(--strong);text-align:center;font-size:27dp;display:none;z-index:250;} +#desktop-context {display:none;position:absolute;width:280px;padding:6px;border:1px var(--border);border-radius:12px;background-color:var(--strong);z-index:180;box-shadow:0px 8px 24px #0005;} +#desktop-context button {display:block;width:100%;padding:9px 12px;border:0px;border-radius:6px;background-color:transparent;text-align:left;font-size:15px;} +#desktop-context button:hover {background-color:var(--selected);} +#desktop-context .separator {height:1px;margin:5px;background-color:var(--border);} +.gallery-card {position:absolute;width:800dp;height:440dp;padding:30dp;} +.gallery-card h2 {font-size:32dp;margin-bottom:24dp;} +.gallery-card p {font-size:26dp;color:var(--muted);margin:15dp 0;} +.gallery-card button {font-size:26dp;} diff --git a/assets/modern/ticket.rcss b/assets/modern/ticket.rcss new file mode 100644 index 0000000..bec4d7f --- /dev/null +++ b/assets/modern/ticket.rcss @@ -0,0 +1,36 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ +/* Font size is set in physical px by TicketPopover, independently of desktop dp. */ +#native-ticket-layer { + position:absolute;left:0;top:0;width:100%;height:100%;z-index:100000; + font-family:Modern;color:var(--text);line-height:1.35; +} +#native-ticket-panel { + position:absolute;box-sizing:border-box;width:23.571429em;height:14em;min-height:14em; + display:flex;flex-direction:column;gap:0.571429em;padding:0.857143em; + border:0.071429em var(--border);border-radius:0.857143em;background-color:var(--strong); + box-shadow:0px 0.571429em 2.142857em #0006;overflow:auto;font-size:1em; +} +#native-ticket-panel h2 {font-size:1.142857em;font-weight:bold;margin:0;} +.native-ticket-heading {display:flex;justify-content:space-between;align-items:center;gap:0.857143em;} +.native-ticket-heading span {font-size:1em;color:var(--muted);white-space:nowrap;} +.native-ticket-editor {display:flex;flex-direction:column;gap:0.142857em;text-align:center;} +#native-ticket-amount,.native-ticket-review strong {font-size:1.857143em;line-height:1.2;font-weight:bold;color:var(--accent);} +#native-ticket-range {width:100%;height:2em;min-height:0em;margin:0;padding:0;border-width:0em;background-color:transparent;font-size:1em;} +#native-ticket-range slidertrack {height:0.285714em;margin:0.857143em 0em;background-color:var(--muted);border-radius:0.142857em;} +#native-ticket-range sliderbar {box-sizing:border-box;width:1.285714em;height:1.285714em;margin-top:0.357143em;background-color:var(--accent);border:0.142857em var(--strong);border-radius:0.642857em;} +#native-ticket-range sliderarrowdec,#native-ticket-range sliderarrowinc {width:0em;height:0em;} +.native-ticket-limits {display:flex;justify-content:space-between;font-size:1em;color:var(--muted);} +.native-ticket-review {gap:0.571429em;} +.native-ticket-review p {margin:0;font-size:1em;} +.native-ticket-arrow {display:inline-block;position:relative;width:0.8em;height:0.55em;vertical-align:middle;} +.native-ticket-arrow-line {position:absolute;left:0em;top:0.25em;width:0.7em;border-top:0.06em var(--muted);} +.native-ticket-arrow-head {position:absolute;left:0.42em;top:0.1em;width:0.25em;height:0.25em;border-top:0.06em var(--muted);border-right:0.06em var(--muted);transform:rotate(45deg);} +#native-ticket-error {margin:0;font-size:1em;color:var(--danger);} +.native-ticket-actions {display:flex;justify-content:flex-end;gap:0.428571em;margin-top:auto;} +#native-ticket-panel button { + box-sizing:border-box;min-height:2.428571em;padding:0.428571em 0.714286em;border:0.071429em var(--border); + border-radius:0.428571em;background-color:var(--soft);font-size:1em;color:var(--text);white-space:nowrap; +} +#native-ticket-panel button:hover {background-color:var(--hover);} +#native-ticket-panel button.native-ticket-primary {background-color:var(--selected);border-color:var(--accent);} +#native-ticket-panel button:focus-visible,#native-ticket-range:focus-visible {border-color:var(--accent);} diff --git a/docs/new_ui/NATIVE_STATUS.md b/docs/new_ui/NATIVE_STATUS.md new file mode 100644 index 0000000..1c50f7c --- /dev/null +++ b/docs/new_ui/NATIVE_STATUS.md @@ -0,0 +1,99 @@ +# Native Modern UI · erster Umsetzungsstand + +Stand: 23. 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. + +## Vorhanden + +- Gemeinsamer SDL2-/RmlUI-Unterbau mit den vorhandenen OpenGL-/Direct3D- + Renderern, den drei Farbpaletten und dem 2720 × 2040 großen 4:3-Fenster. +- Schreibgeschützter OBW-Katalog für Diamond Modern: Vereine, Ligen, Spieler, + Wappen und Fotos. SVG-Wappen werden gegenüber kleinen Legacy-Bildern bevorzugt. +- Eigene GUI-Ressourcen für Hintergründe, Desktop-Icons, Managerporträts, + Karten und Trainingslagerbilder. Der Vorbereitungsbefehl verändert weder + das Mockup noch die Weltdatei. +- Hauptmenü und Mod-Auswahl; Grundeinstellungen mit vier großen Auswahlfeldern; + Manager-/Vereinswahl mit Foto- und Illustrationsporträts. Ausländische + Vereine bleiben sichtbar und sind für Manager gesperrt. +- Drei Teilnehmerseiten, automatische Demo-Auslosung mit Pause/Überspringen + und Übersicht; in dieser Folge gibt es keinen Schließen-Knopf. +- Desktop mit Statusleiste, Buttons, fixierter Standardanordnung, Raster und + freiem Verschieben, Rechtsklickmenü, gemeinsamer Fixierung, Rückgängig, + Widgetauswahl und den vorgesehenen Widgetgrößen. Kurven-/Statistikinhalte + und die Widgetvorschauen benötigen noch den detaillierten Mockup-Abgleich. +- Eintrittspreis-Popover: 330 × 196 Punkte, Entwurf, gesonderte Bestätigung, + Abbrechen, Fehler-/Revisionsschutz und Tastaturbedienung. +- Trainingslager: drei Karten, 18 Angebote, eigene GUI-Bilder und lokale + Vormerkung. Tabellen/Stärken sowie Speichern/Laden sind als erste native + Ansichten vorhanden; ihr vollständiger Bedienungsabgleich bleibt offen. +- Separate UI-Demostände und Desktopansichten. Ansichten speichern zusätzlich + einen Screenshot; die Standardansicht kann nicht gelöscht werden. + +**Anstoß führt keine Aktion aus**, weder per Maus noch per Tastatur. Das gilt +auch für die direkte Aktionsschnittstelle des Demoanbieters. + +## Noch offen + +Die übrigen Desktop-Untermenüs werden anschließend einzeln vom HTML-Mockup +übertragen. Für sie erscheinen derzeit keine vereinfachten Ersatzlayouts. +Der Einstellungsdialog, die vollständigen Widgetinhalte, Sortierung/Details, +Mod-Importkomfort und dauerhafte globale Voreinstellungen sind noch nicht +vollständig. Übersetzungen, echte Engine-Anbindung und Plattform-Abnahme +unter Windows/macOS folgen später. Dies ist kein freigegebenes Test-Release. + +## Architekturgrenze für die Engine + +Die Oberfläche liegt unter `src/modern/ui`, verwendet aber den Namespace +`bmh::modern_ui`. Damit verdeckt sie nicht `bmh::ui`, auf das die Modern- +Session des Engine-Forks derzeit zugreift. + +`DataSource` liefert besitzende, unveränderliche `Snapshot`-Werte mit Revision +und nimmt `Action`-Anfragen entgegen. Aktuell implementiert ausschließlich +`DemoSource` diese Grenze. Keine Ansicht greift auf `GameState` zu; die Demo +ruft keine Modern-Session, Zufallsquelle oder Matchfunktion auf. Ihr `.json`- +Speicherformat ist ausdrücklich kein `.obs`-Spielstand und keine neue +Spielregel. Ein späterer Session-Adapter ersetzt den Demoanbieter. + +Die bisher nur für den Editor verwendeten Archiv-/Bild-Hilfen sind als +`bmh_asset_io` geteilt. Editor-Oberfläche, MCP-Server und HTTP-Server werden +nicht in die Modern UI eingebunden. + +## Lokal bauen und ansehen + +```sh +python3 tools/modern_ui/prepare_gui_assets.py \ + --mockup /path/to/bmh_4k_ui --output /path/to/gui-resources +cmake -S . -B build-modern -DOPENBMH_BUILD_MODERN_UI=ON \ + -DBMH_MODERN_GUI_ASSETS=/path/to/gui-resources +cmake --build build-modern --target openbmh_play modern_ui_core_tests modern_ticket_document_tests +ctest --test-dir build-modern -R '^modern_(ui_core|ticket_)' --output-on-failure +./build-modern/OpenBMH --modern-ui-demo --mod /path/to/Diamond_Modern.obw +``` + +Bei Mehrkonfigurations-Generatoren liegt das Programm im Konfigurationsordner; +`--config Release` beziehungsweise `ctest -C Release` ergänzen. Die +Spieler-/Vereinsdaten und die privaten Referenzmotive werden nicht mit diesem +Quellcode verteilt. Ohne externe GUI-Ressourcen kann das Hauptmenü den bereits +mitgelieferten Launcher-Hintergrund verwenden. + +Entwicklungsoptionen: `--gui-assets`, `--ui-scene`, `--ui-theme`, `--ui-size`, +`--ui-state`, `--ui-screenshot` und `--ui-script`. Das zeilenweise JSON- +Eingabeskript führt Maus-/Tastaturaktionen durch RmlUI aus; es ersetzt keine +Sessionaktionen durch direkte Zustandsmanipulation. `checkpoint` schreibt einen +wiederherstellbaren Demostand passend zu den Bildschirmaufnahmen. + +## Prüfung + +Synthetische Tests prüfen Katalog, HQ-Bildauswahl, ausländische Übernahmesperre, +Revisionsschutz, Desktop-Grenzen/Fixierung/Größen und atomare Demostand- +Wiederherstellung. Drei fensterlose RmlUI-Tests prüfen den Eintrittspreis in +allen Themes, einschließlich doppelter Pixeldichte und abgewiesener Übernahme. + +Ein nativer Linux-/OpenGL-Durchlauf mit externem Diamond-Datensatz führt über +das Hauptmenü, die Managerwahl und Auslosung zum Desktop, verändert den +Eintrittspreis nach Bestätigung, öffnet das Nahost-Lager und prüft Verschieben +und Rückgängig. Bildschirmaufnahmen, Eingabeskripte und Demostände bleiben im +privaten Mockup-Repository. Windows-/macOS-Laufzeitverhalten wird damit nicht +als geprüft ausgegeben. diff --git a/docs/new_ui/PLAN.md b/docs/new_ui/PLAN.md index c01f7eb..095e2aa 100644 --- a/docs/new_ui/PLAN.md +++ b/docs/new_ui/PLAN.md @@ -1,6 +1,8 @@ # Native Modern UI bis zum Anstoß -Stand: 23. Oktober 2026. **Abgestimmter Umfang; native Umsetzung noch offen.** +Stand: 23. Oktober 2026. **Abgestimmter Gesamtumfang; native Umsetzung begonnen.** +Der [native Umsetzungsstand](NATIVE_STATUS.md) unterscheidet den bereits +bedienbaren Unterbau von den noch ausstehenden Menüübertragungen. Diese Seite hält die Entscheidungen aus dem UI-Plan fest. Sie ersetzt keine Implementierungs- oder Abnahmebelege. Die Engine entsteht parallel bei Claude. diff --git a/docs/new_ui/README.md b/docs/new_ui/README.md index ba818f5..357c04d 100644 --- a/docs/new_ui/README.md +++ b/docs/new_ui/README.md @@ -8,6 +8,7 @@ Implementierung in der Spiel-Engine. | Bereich | Dokument | |---|---| | Umsetzung | [Abgestimmter Umfang der nativen UI bis zum Anstoß](PLAN.md) | +| Nativer Stand | [Unterbau, erster Durchlauf und noch offene Übertragungen](NATIVE_STATUS.md) | | Ressourcen | [GUI-Assets, Weltbilder und spätere Paketbereinigung](assets.md) | | Desktop | [Statusleiste, Gestaltung und Fenster](desktop/README.md) | | Eintrittspreis | [Kompakter Schieberegler im Konto-Widget](desktop/entry-price/README.md) | diff --git a/docs/new_ui/desktop/entry-price/README.md b/docs/new_ui/desktop/entry-price/README.md index e34e1a3..e17c96e 100644 --- a/docs/new_ui/desktop/entry-price/README.md +++ b/docs/new_ui/desktop/entry-price/README.md @@ -1,7 +1,7 @@ # Eintrittspreis · Konto-/Eintritts-Widget -Stand: 23. Oktober 2026. Im HTML-Mockup umgesetzt; die native Modern UI -übernimmt diese Bedienung bei ihrer Umsetzung. +Stand: 23. Oktober 2026. Im HTML-Mockup und im experimentellen nativen +RmlUI-Desktop umgesetzt. Siehe [nativer Umsetzungsstand](../../NATIVE_STATUS.md). ## Bedienung und Größe diff --git a/src/app/main.cpp b/src/app/main.cpp index 3d9ed9b..99b81f8 100644 --- a/src/app/main.cpp +++ b/src/app/main.cpp @@ -32,6 +32,9 @@ #include "launch/game_data.hpp" #include "launch/launcher.hpp" #include "launch/startup_error.hpp" +#ifdef OPENBMH_MODERN_UI +#include "modern/ui/view.hpp" +#endif #include "content/package.hpp" #include "version.hpp" #include "app/live_matchday_events.hpp" @@ -95,6 +98,10 @@ int main(int argc, char** argv) { rml::attach_parent_console(); const std::vector args = launch::utf8_arguments(argc, argv); // (file names beyond the code page) fs::path data, save_directory; +#ifdef OPENBMH_MODERN_UI + modern_ui::Config modern_ui; + bool modern_demo = false; +#endif uint32_t seed = uint32_t(std::chrono::system_clock::now().time_since_epoch().count()); bool muted = false, music_enabled = true; int live_frame_ms = 0; @@ -104,9 +111,37 @@ int main(int argc, char** argv) { live_frame_ms_explicit = true; } float volume = 1.0F; + try { for (size_t i = 1; i < args.size(); ++i) { const auto is = [&](const char* name) { return args[i] == name; }; const bool value = i + 1 < args.size(); +#ifdef OPENBMH_MODERN_UI + if (is("--modern-ui-demo")) { + modern_demo = true; + } else if (is("--gui-assets") && value) { + modern_ui.gui_assets = launch::path_from_utf8(args[++i]); + } else if (is("--ui-scene") && value) { + modern_ui.scene = args[++i]; + } else if (is("--ui-theme") && value) { + modern_ui.theme = args[++i]; + } else if (is("--ui-screenshot") && value) { + modern_ui.screenshot = launch::path_from_utf8(args[++i]); + modern_demo = true; + } else if (is("--ui-script") && value) { + modern_ui.commands = launch::path_from_utf8(args[++i]); + modern_demo = true; + } else if (is("--ui-state") && value) { + modern_ui.state = launch::path_from_utf8(args[++i]); + } else if (is("--ui-size") && value) { + const auto size = args[++i]; + const auto separator = size.find('x'); + if (separator == std::string::npos) throw std::runtime_error("--ui-size requires WIDTHxHEIGHT"); + modern_ui.width = std::stoi(size.substr(0, separator)); + modern_ui.height = std::stoi(size.substr(separator + 1)); + if (modern_ui.width < 960 || modern_ui.width > 7680 || modern_ui.height < 540 || modern_ui.height > 4320) + throw std::runtime_error("Unsupported Modern UI preview size"); + } else +#endif if (is("--mute")) { muted = true; } else if (is("--music")) { @@ -131,6 +166,11 @@ int main(int argc, char** argv) { std::printf("usage: OpenBMH [--mod ] [--seed ] " "[--save-directory ] [--mute] [--volume <0..1>] [--no-music] " "[--live-frame-ms <0..1000>]\n"); +#ifdef OPENBMH_MODERN_UI + std::printf("Modern UI preview: --modern-ui-demo --gui-assets " + "[--ui-scene main|desktop|camp|manager|newgame|tables] " + "[--ui-theme midnight|silver|matchday] [--ui-size WIDTHxHEIGHT]\n"); +#endif return 0; } else if (args[i].rfind("--", 0) != 0 && data.empty()) { data = launch::path_from_utf8(args[i]); @@ -139,6 +179,7 @@ int main(int argc, char** argv) { return 1; } } + }catch(const std::exception &e){show_start_error(e.what());return 1;} std::filesystem::path executable; if (char *base = SDL_GetBasePath()) { executable = launch::path_from_utf8(base); @@ -150,9 +191,13 @@ int main(int argc, char** argv) { #endif } else executable = fs::absolute(launch::path_from_utf8(args.front())); - if (data.empty()) { + if (data.empty() +#ifdef OPENBMH_MODERN_UI + || modern_demo || modern_ui::is_modern_world(data) +#endif + ) { try { - return launch::run_launcher(executable, [](const fs::path &package, const fs::path &source, + const launch::SaveMigrator migrate = [](const fs::path &package, const fs::path &source, const fs::path &destination) { const auto content = content::open(package); content::Mount mount(package, content); @@ -164,7 +209,13 @@ int main(int argc, char** argv) { if (!migrated.save_game(destination, migrated.state().memory.u8(::bmh::layout::ActiveManager), false, error)) throw FormatError("Spielstand konnte nicht übernommen werden: " + error); - }); + }; +#ifdef OPENBMH_MODERN_UI + modern_ui.world = data; + return modern_ui::run(executable, migrate, modern_ui); +#else + return launch::run_launcher(executable, migrate); +#endif } catch (const std::exception &e) { show_start_error(e.what()); return 1; diff --git a/src/editor/CMakeLists.txt b/src/editor/CMakeLists.txt index 5be1b6a..16ccef2 100644 --- a/src/editor/CMakeLists.txt +++ b/src/editor/CMakeLists.txt @@ -61,10 +61,22 @@ foreach(component editor_json editor_http editor_images editor_svg editor_xml) endforeach() file(APPEND "${CMAKE_BINARY_DIR}/editor-dependencies.json" "}\n") -add_library(bmh_editor_core STATIC archive.cpp world.cpp session.cpp comparison.cpp regulations.cpp images.cpp options.cpp mcp.cpp) +add_library(bmh_asset_io STATIC archive.cpp images.cpp) +target_include_directories(bmh_asset_io PUBLIC ..) +target_link_libraries(bmh_asset_io PUBLIC nlohmann_json::nlohmann_json bmh_content + PRIVATE bmh_miniz ${BMH_SDL_TARGET} SDL2_image::SDL2_image-static lunasvg::lunasvg pugixml::pugixml) +if(MSVC) + target_compile_options(bmh_asset_io PRIVATE /W4 /utf-8) +else() + target_compile_options(bmh_asset_io PRIVATE -Wall -Wextra -Wpedantic) +endif() +if(NOT OPENBMH_BUILD_EDITOR) + return() +endif() +add_library(bmh_editor_core STATIC world.cpp session.cpp comparison.cpp regulations.cpp options.cpp mcp.cpp) target_compile_definitions(bmh_editor_core PUBLIC OPENBMH_EDITOR_VERSION="${OPENBMH_EDITOR_VERSION}") target_include_directories(bmh_editor_core PUBLIC .. ${editor_http_SOURCE_DIR}) -target_link_libraries(bmh_editor_core PUBLIC nlohmann_json::nlohmann_json bmh_content +target_link_libraries(bmh_editor_core PUBLIC bmh_asset_io nlohmann_json::nlohmann_json bmh_content PRIVATE bmh_miniz ${BMH_SDL_TARGET} SDL2_image::SDL2_image-static lunasvg::lunasvg pugixml::pugixml) find_package(Threads REQUIRED) target_link_libraries(bmh_editor_core PUBLIC Threads::Threads) diff --git a/src/modern/ui/CMakeLists.txt b/src/modern/ui/CMakeLists.txt new file mode 100644 index 0000000..8a370fb --- /dev/null +++ b/src/modern/ui/CMakeLists.txt @@ -0,0 +1,46 @@ +# SPDX-License-Identifier: GPL-3.0-only +add_library(bmh_modern_ui_core STATIC catalog.cpp model.cpp gui_assets.cpp desktop.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 STATIC view.cpp ticket_popover.cpp) +target_link_libraries(bmh_modern_ui PUBLIC bmh_modern_ui_core PRIVATE bmh_rmlui bmh_launcher nfd::nfd ${BMH_SDL_TARGET}) +if(MSVC) + target_compile_options(bmh_modern_ui_core PRIVATE /W4 /utf-8) + target_compile_options(bmh_modern_ui PRIVATE /W4 /utf-8) +else() + target_compile_options(bmh_modern_ui_core PRIVATE -Wall -Wextra -Wpedantic) + target_compile_options(bmh_modern_ui PRIVATE -Wall -Wextra -Wpedantic) +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) + configure_file("${CMAKE_SOURCE_DIR}/assets/modern/${asset}" "${modern_assets}/${asset}" COPYONLY) +endforeach() +file(COPY "${CMAKE_SOURCE_DIR}/assets/modern/icons" DESTINATION "${modern_assets}") +foreach(weight Regular Bold) + configure_file("${rmlui_SOURCE_DIR}/Samples/assets/LatoLatin-${weight}.ttf" + "${modern_assets}/LatoLatin-${weight}.ttf" COPYONLY) +endforeach() +set(BMH_MODERN_GUI_ASSETS "" CACHE PATH "Optional externally supplied Modern GUI resource directory") +if(BMH_MODERN_GUI_ASSETS) + if(NOT EXISTS "${BMH_MODERN_GUI_ASSETS}/gui-assets.json") + message(FATAL_ERROR "BMH_MODERN_GUI_ASSETS does not contain gui-assets.json") + endif() + file(COPY "${BMH_MODERN_GUI_ASSETS}/" DESTINATION "${modern_assets}/gui") +endif() +install(DIRECTORY "${modern_assets}/" DESTINATION assets/modern COMPONENT Runtime) +add_executable(modern_ui_core_tests ../../../tests/modern_ui_core_tests.cpp) +target_link_libraries(modern_ui_core_tests PRIVATE bmh_modern_ui_core) +if(MSVC) + target_compile_options(modern_ui_core_tests PRIVATE /utf-8) +endif() +add_test(NAME modern_ui_core_tests COMMAND modern_ui_core_tests) +add_executable(modern_ticket_document_tests ../../../tests/modern_ticket_document_tests.cpp ticket_popover.cpp) +target_link_libraries(modern_ticket_document_tests PRIVATE bmh_modern_ui_core RmlUi::Core) +if(MSVC) + target_compile_options(modern_ticket_document_tests PRIVATE /utf-8) +endif() +foreach(theme midnight silver matchday) + add_test(NAME modern_ticket_${theme} COMMAND modern_ticket_document_tests "${modern_assets}" ${theme}) +endforeach() diff --git a/src/modern/ui/catalog.cpp b/src/modern/ui/catalog.cpp new file mode 100644 index 0000000..e8021bf --- /dev/null +++ b/src/modern/ui/catalog.cpp @@ -0,0 +1,216 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "modern/ui/catalog.hpp" +#include +#include +#include + +namespace bmh::modern_ui { +std::string localized(const Json &v, const std::string &language) { + if (v.is_string()) + return v.get(); + if (!v.is_object()) + return {}; + for (const auto &key : {language, std::string("default"), std::string("en")}) + if (auto i = v.find(key); i != v.end() && i->is_string() && + !i->get_ref().empty()) + return i->get(); + if (v.contains("first") || v.contains("last")) { + const auto first = localized(v.value("first", Json())), + last = localized(v.value("last", Json())); + return first + (first.empty() || last.empty() ? "" : " ") + last; + } + return {}; +} +std::string number(int64_t n) { + const auto raw = std::to_string(n); + std::string out; + for (size_t i = 0; i < raw.size(); ++i) { + if (i && raw[i - 1] != '-' && (raw.size() - i) % 3 == 0) + out += '.'; + out += raw[i]; + } + return out; +} +std::string money(int64_t n, const Json ¤cy) { + const int units = currency.value("minor_units", 0); + const auto code = currency.value("code", std::string("EUR")); + const auto suffix = code == "EUR" ? " €" : " " + code; + if (!units) + return number(n) + suffix; + if (units != 2) + throw editor::Error("unsupported_currency_precision"); + const auto remainder = int(n % 100 < 0 ? -(n % 100) : n % 100); + return (n < 0 && n > -100 ? "-" : "") + number(n / 100) + "," + + (remainder < 10 ? "0" : "") + std::to_string(remainder) + suffix; +} +bool Catalog::modern_manifest(const Json &m) { + if (!m.is_object() || m.value("format", "") != "openbmh-world" || + m.value("kind", "") != "world") + return false; + const auto required = m.value("requires", Json::array()); + if (!required.is_array()) + return false; + if (std::find(required.begin(), required.end(), "runtime:modern-v1") != + required.end()) + return true; + return std::find(required.begin(), required.end(), "editor:world-v1") != + required.end() && + m.value("x-editor", Json::object()).value("profile", "") == + "editor-world-v1"; +} +std::shared_ptr Catalog::open(const fs::path &input) { + auto c = std::shared_ptr(new Catalog); + c->source_ = fs::absolute(input).lexically_normal(); + c->store_ = editor::ArchiveStore::open(c->source_); + c->manifest_ = Json::parse(c->store_->read("manifest.json")); + if (!modern_manifest(c->manifest_)) + throw editor::Error("modern_world_required"); + if (!c->manifest_.value("format_version", std::string()).starts_with("1.")) + throw editor::Error("unsupported_version"); + for (const char *table : + {"nations", "clubs", "players", "competitions", "contracts", "finance", + "staff", "stadiums", "rules", "calendar", "assets"}) { + const auto file = std::string(table) == "assets" + ? "assets/index.json" + : std::string("world/") + table + ".json"; + Json items = Json::array(); + if (c->store_->contains(file)) { + const auto doc = Json::parse(c->store_->read(file)); + if (!doc.is_object() || !doc.contains("items") || + !doc["items"].is_array()) + throw editor::Error("invalid_table", {{"file", file}}); + items = doc["items"]; + } else if (std::string(table) == "clubs" || + std::string(table) == "players" || + std::string(table) == "competitions") + throw editor::Error("missing_table", {{"file", file}}); + auto &index = c->indices_[table]; + for (size_t i = 0; i < items.size(); ++i) { + if (!items[i].is_object()) + throw editor::Error("invalid_record", {{"file", file}}); + const auto id = items[i].value( + std::string(table) == "assets" ? "key" : "id", std::string()); + if (id.empty() || !index.emplace(id, i).second) + throw editor::Error("duplicate_or_missing_id", {{"file", file}}); + } + c->tables_[table] = std::move(items); + } + if (const auto file = c->manifest_.value("presentation", std::string()); + !file.empty()) + c->presentation_ = Json::parse(c->store_->read(file)); + for (const auto *league : c->leagues()) { + const auto id = league->value("id", ""); + for (const auto *club : c->clubs(id)) + if (!c->find("nations", club->value("nation", ""))) + throw editor::Error("unknown_nation"); + } + return c; +} +const Json &Catalog::rows(const std::string &table) const { + return tables_.at(table); +} +const Json *Catalog::find(const std::string &table, + const std::string &id) const { + const auto t = indices_.find(table); + if (t == indices_.end()) + return nullptr; + const auto i = t->second.find(id); + return i == t->second.end() ? nullptr : &tables_.at(table).at(i->second); +} +std::string Catalog::title() const { + return localized(manifest_.value("title", Json())); +} +std::string Catalog::name(const Json &row) const { + return localized(row.value("name", Json())); +} +std::string Catalog::nation_name(const std::string &id) const { + const auto *n = find("nations", id); + return n ? name(*n) : id; +} +std::vector Catalog::leagues(const std::string &nation) const { + std::vector out; + for (const auto &r : rows("competitions")) + if (r.value("type", "") == "league" && + (nation.empty() || r.value("nation", "") == nation)) + out.push_back(&r); + return out; +} +std::vector Catalog::clubs(const std::string &league) const { + std::vector out; + for (const auto &r : rows("clubs")) + if (r.value("type", "club") == "club" && + (league.empty() || r.value("competition", "") == league)) + out.push_back(&r); + return out; +} +std::vector Catalog::squad(const std::string &club) const { + std::vector out; + for (const auto &r : rows("players")) + if (r.value("team", "") == club) + out.push_back(&r); + std::stable_sort(out.begin(), out.end(), [](auto a, auto b) { + return a->value("squad_order", 999) < b->value("squad_order", 999); + }); + return out; +} +bool Catalog::manageable(const std::string &club) const { + const auto *r = find("clubs", club); + const auto *league = + r ? find("competitions", r->value("competition", "")) : nullptr; + return r && r->value("type", "club") == "club" && + r->value("nation", "") == "nation:de" && league && + league->value("nation", "") == "nation:de" && + league->value("type", "") == "league"; +} +std::pair Catalog::asset(const std::string &key, + int pixels) const { + const auto *a = find("assets", key); + if (!a && !presentation_.is_null() && key.find("/photo") != std::string::npos) + a = find("assets", presentation_.value("player_photo_fallback", "")); + if (!a) + return {}; + const auto files = a->value("files", Json::object()); + std::string file; + if (files.contains("svg") && files["svg"].is_string()) + file = files["svg"].get(); + if (file.empty()) { + std::vector> candidates; + for (const auto &[size, value] : files.items()) { + if (!value.is_string() || size == "native" || size == "svg") + continue; + try { + candidates.emplace_back(std::stoi(size), value.get()); + } catch (const std::exception &) { + if (file.empty()) + file = value.get(); + } + } + if (!candidates.empty()) { + std::sort(candidates.begin(), candidates.end()); + file = candidates.back().second; + for (const auto &[size, name] : candidates) + if (size >= pixels) { + file = name; + break; + } + } + } + if (file.empty()) + file = files.value("native", ""); + if (file.empty() || !store_->contains(file)) + return {}; + return {store_->read(file), fs::path(file).extension().string()}; +} +Json Catalog::summary() const { + Json leagues_json = Json::array(); + for (auto *r : leagues()) + leagues_json.push_back({{"id", r->value("id", "")}, + {"name", name(*r)}, + {"clubs", clubs(r->value("id", "")).size()}}); + return {{"title", title()}, + {"leagues", leagues_json}, + {"clubs", rows("clubs").size()}, + {"players", rows("players").size()}, + {"engine", false}}; +} +} // namespace bmh::modern_ui diff --git a/src/modern/ui/catalog.hpp b/src/modern/ui/catalog.hpp new file mode 100644 index 0000000..e3a24dd --- /dev/null +++ b/src/modern/ui/catalog.hpp @@ -0,0 +1,40 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +#include "editor/archive.hpp" +#include + +namespace bmh::modern_ui { +using Json = editor::Json; +namespace fs = std::filesystem; + +// Immutable presentation data. This reader does not construct a game state. +class Catalog { +public: + static std::shared_ptr open(const fs::path &); + static bool modern_manifest(const Json &); + const Json &manifest() const { return manifest_; } + const Json &rows(const std::string &) const; + const Json *find(const std::string &, const std::string &) const; + std::string title() const; + std::string name(const Json &) const; + std::string nation_name(const std::string &) const; + std::vector leagues(const std::string &nation = {}) const; + std::vector clubs(const std::string &league = {}) const; + std::vector squad(const std::string &) const; + bool manageable(const std::string &) const; + std::pair asset(const std::string &, + int pixels = 512) const; + Json summary() const; + const fs::path &source() const { return source_; } + +private: + fs::path source_; + std::shared_ptr store_; + Json manifest_, presentation_; + std::map tables_; + std::map> indices_; +}; +std::string localized(const Json &, const std::string &language = "de"); +std::string number(int64_t); +std::string money(int64_t, const Json ¤cy); +} // namespace bmh::modern_ui diff --git a/src/modern/ui/controls.inc b/src/modern/ui/controls.inc new file mode 100644 index 0000000..88717ee --- /dev/null +++ b/src/modern/ui/controls.inc @@ -0,0 +1,1195 @@ +// SPDX-License-Identifier: GPL-3.0-only +// Input and navigation share the same paths for human and scripted events. +void App::context_menu(const std::string &id, int x, int y) { + init_desktop(); + context_id_ = id; + context_x_ = x; + context_y_ = y; + context_open_ = true; + context_dirty_ = true; + dirty_ = true; +} +void App::render_context() { + auto *root = element("desktop-context"); + root->SetProperty("display", context_open_ ? "block" : "none"); + if (!context_open_ || !context_dirty_) + return; + std::string body; + if (!context_id_.empty()) { + const auto &o = desktop_["objects"].at(context_id_); + body += btn("context-pin", + o.value("pinned", true) ? "Fixierung lösen" : "Fixieren"); + if (o.value("widget", false)) { + body += btn("context-remove", "Widget entfernen"); + for (const auto &d : widget_definitions()) + if (d.id == context_id_) + for (auto [w, h] : d.sizes) + body += btn("context-size", + std::to_string(w) + " × " + std::to_string(h), {}, + "data-id=\"" + std::to_string(w) + "x" + + std::to_string(h) + "\""); + } + body += "
"; + } + bool all_pinned = true; + for (const auto &[id, o] : desktop_["objects"].items()) { + (void)id; + if (o.value("visible", false) && !o.value("pinned", true)) + all_pinned = false; + } + body += + btn("context-undo", "Rückgängig", {}, undo_.empty() ? "disabled" : "") + + btn("context-pin-all", all_pinned ? "Alles lösen" : "Alles fixieren") + + btn("context-grid", desktop_.value("grid", true) ? "Raster ausschalten" + : "Raster einschalten") + + btn("context-arrange", "Am Raster anordnen") + + "
" + + btn("context-widgets", "Widget hinzufügen") + + btn("context-view-save", "Ansicht speichern") + + btn("context-view-load", "Ansicht laden") + + btn("context-background", "Hintergrundbild ändern") + + "
" + btn("context-quit", "Spiel beenden"); + root->SetInnerRML(body); + context_->Update(); + const auto size = context_->GetDimensions(); + root->SetProperty( + "left", + scalar(std::clamp(context_x_, 4, std::max(4, size.x - 288))) + "px"); + root->SetProperty( + "top", scalar(std::clamp( + context_y_, 4, + std::max(4, size.y - int(root->GetBox().GetSize().y) - 8))) + + "px"); + context_dirty_ = false; +} +void App::drag_event(Rml::Event &event) { + const auto type = event.GetType(); + if (type == "mousedown") + suppress_click_ = false; + const float x = event.GetParameter("mouse_x", 0), + y = event.GetParameter("mouse_y", 0); + if (type == "mousedown" && event.GetParameter("button", 0) == 0 && + scene_ == "desktop" && menu_.empty() && popup_.empty()) { + auto *target = event.GetTargetElement(); + bool interactive = false; + for (auto *n = target; n && n != doc_; n = n->GetParentNode()) { + if (n->HasAttribute("data-interactive")) + interactive = true; + if (n->HasAttribute("data-object")) { + if (interactive) + return; + const auto id = n->GetAttribute("data-object", ""); + const auto &o = desktop_["objects"].at(id); + if (o.value("pinned", true)) + return; + drag_ = {true, false, id, x, y, o.value("x", 0.0), o.value("y", 0.0)}; + return; + } + } + } + if (!drag_.active) + return; + if (type == "mousemove") { + if (!drag_.moved && std::hypot(x - drag_.x, y - drag_.y) < 6) + return; + if (!drag_.moved) { + undo_.push_back(desktop_); + if (undo_.size() > 40) + undo_.erase(undo_.begin()); + drag_.moved = true; + } + auto &o = desktop_["objects"][drag_.id]; + if (o.value("pinned", true)) + return; + const double left = std::clamp(drag_.left + (x - drag_.x) / scale_, 0.0, + 3840.0 - o.value("w", 224)); + const double top = std::clamp(drag_.top + (y - drag_.y) / scale_, 224.0, + 2160.0 - o.value("h", 224)); + o["x"] = left; + o["y"] = top; + if (auto *n = element("object-" + drag_.id)) { + n->SetProperty("left", scalar(left) + "dp"); + n->SetProperty("top", scalar(top) + "dp"); + } + dirty_ = true; + } + if (type == "mouseup") { + if (drag_.moved) { + suppress_click_ = true; + auto &o = desktop_["objects"][drag_.id]; + auto proposed = undo_.back(); + const int x = o.value("x", 64), y = o.value("y", 224); + if (place_desktop_object(proposed, drag_.id, x, y)) + desktop_ = std::move(proposed); + else + desktop_ = undo_.back(); + + refresh(); + } + drag_.active = false; + } +} +void App::ProcessEvent(Rml::Event &event) try { + const auto type = event.GetType(); + for (auto *n = event.GetTargetElement(); n && n != doc_; + n = n->GetParentNode()) + if (n->GetId() == "native-ticket-layer") + return; + if (type == "mouseup" && event.GetParameter("button", 0) == 1) { + if (scene_ == "desktop" && menu_.empty() && popup_.empty()) { + std::string id; + for (auto *n = event.GetTargetElement(); n && n != doc_; + n = n->GetParentNode()) + if (n->HasAttribute("data-object")) { + id = n->GetAttribute("data-object", ""); + break; + } + context_menu(id, event.GetParameter("mouse_x", 0), + event.GetParameter("mouse_y", 0)); + } + event.StopPropagation(); + return; + } + if (type == "mousedown" && event.GetParameter("button", 0) == 0 && + context_open_) { + bool inside = false; + for (auto *n = event.GetTargetElement(); n && n != doc_; + n = n->GetParentNode()) + if (n->GetId() == "desktop-context") + inside = true; + if (!inside) { + context_open_ = false; + dirty_ = true; + event.StopPropagation(); + return; + } + } + if (type == "mousedown" || type == "mousemove" || type == "mouseup") { + drag_event(event); + return; + } + auto *target = event.GetTargetElement(); + if (type == "contextmenu") { + if (scene_ != "desktop" || !menu_.empty() || !popup_.empty()) + return; + std::string id; + for (auto *n = target; n && n != doc_; n = n->GetParentNode()) + if (n->HasAttribute("data-object")) { + id = n->GetAttribute("data-object", ""); + break; + } + context_menu(id, event.GetParameter("mouse_x", 0), + event.GetParameter("mouse_y", 0)); + event.StopPropagation(); + return; + } + if (type == "keydown") { + const auto key = + Rml::Input::KeyIdentifier(event.GetParameter("key_identifier", 0)); + if (key == Rml::Input::KI_RETURN || key == Rml::Input::KI_SPACE) { + for (auto *n = target; n && n != doc_; n = n->GetParentNode()) + if (n->GetTagName() == "button") { + if (!n->HasAttribute("disabled")) + n->DispatchEvent("click", {}); + event.StopImmediatePropagation(); + return; + } + } + if (key == Rml::Input::KI_ESCAPE) { + if (context_open_) { + context_open_ = false; + dirty_ = true; + } else if (!popup_.empty()) { + popup_.clear(); + confirm_ = {}; + text_accept_ = {}; + quit_after_save_ = false; + dirty_ = true; + } else if (!menu_.empty()) { + menu_.clear(); + draft_preferences_ = nullptr; + refresh(); + } else if (scene_ == "manager") { + scene_ = "newgame"; + refresh(); + } else if (scene_ == "newgame" || scene_ == "mods") { + scene_ = "main"; + refresh(); + } + event.StopPropagation(); + return; + } + if (key == Rml::Input::KI_Z && event.GetParameter("ctrl_key", 0) && + scene_ == "desktop" && menu_.empty() && !undo_.empty()) { + desktop_ = undo_.back(); + undo_.pop_back(); + refresh(); + event.StopPropagation(); + return; + } + if (key == Rml::Input::KI_TAB && + (!menu_.empty() || !popup_.empty() || scene_ != "desktop")) { + Rml::ElementList controls; + auto *root = !popup_.empty() ? element("popup") : element("canvas"); + root->QuerySelectorAll( + controls, !popup_.empty() + ? "button,input,select" + : ".window button,.window input,.window select"); + controls.erase(std::remove_if(controls.begin(), controls.end(), + [](auto *n) { + return !n->IsVisible() || + n->HasAttribute("disabled"); + }), + controls.end()); + const auto current = context_->GetFocusElement(); + const auto i = std::find(controls.begin(), controls.end(), current); + if (!controls.empty()) { + const int old = i == controls.end() ? -1 : int(i - controls.begin()); + const bool backwards = event.GetParameter("shift_key", 0) != 0; + const auto next = (old + (backwards ? -1 : 1) + int(controls.size())) % + int(controls.size()); + controls[size_t(next)]->Focus(true); + event.StopImmediatePropagation(); + } + return; + } + } + if (type == "change") { + change(target); + return; + } + if (type == "input") { + input(target); + return; + } + if (type != "click" && type != "dblclick") + return; + if (suppress_click_) { + suppress_click_ = false; + event.StopPropagation(); + return; + } + if (type == "dblclick") + return; + for (auto *n = target; n && n != doc_; n = n->GetParentNode()) + if (n->HasAttribute("data-action")) { + if (!n->HasAttribute("disabled")) + dispatch(n->GetAttribute("data-action", ""), n); + return; + } +} catch (const std::exception &e) { + message(e.what()); +} +void App::dispatch(const std::string &action, Rml::Element *target) { + const auto id = + target ? target->GetAttribute("data-id", "") : std::string(); + if (action == "popup-close") { + popup_.clear(); + confirm_ = {}; + text_accept_ = {}; + quit_after_save_ = false; + dirty_ = true; + return; + } + if (action == "popup-confirm") { + auto fn = std::move(confirm_); + auto text_fn = std::move(text_accept_); + const auto text = field("popup-text"); + popup_.clear(); + confirm_ = {}; + text_accept_ = {}; + if (text_fn) + text_fn(text); + else if (fn) + fn(); + dirty_ = true; + return; + } + if (action == "exit") { + closed_ = true; + return; + } + if (action == "quit-without-save") { + closed_ = true; + return; + } + if (action.starts_with("context-")) { + context_open_ = false; + dirty_ = true; + init_desktop(); + if (action == "context-quit") { + if (!source_->dirty() && desktop_ == saved_desktop_) { + confirmation("Spiel beenden?", [this] { closed_ = true; }); + return; + } + confirmation("Deine Änderungen wurden noch nicht gespeichert. Vor dem " + "Beenden speichern?", + [this] { + quit_after_save_ = true; + menu_ = "save"; + refresh(); + }); + popup_accept_ = "Speichern"; + popup_extra_ = btn("quit-without-save", "Nicht speichern"); + return; + } + if (action == "context-widgets" || action == "context-view-save" || + action == "context-view-load" || action == "context-background") { + menu_ = action.substr(8); + refresh(); + return; + } + if (action == "context-undo") { + if (!undo_.empty()) { + desktop_ = undo_.back(); + undo_.pop_back(); + refresh(); + } + return; + } + auto before = desktop_; + bool ok = true; + if (action == "context-pin") + desktop_["objects"][context_id_]["pinned"] = + !desktop_["objects"][context_id_].value("pinned", true); + else if (action == "context-pin-all") { + bool all = true; + for (const auto &[key, o] : desktop_["objects"].items()) { + (void)key; + if (o.value("visible", false) && !o.value("pinned", true)) + all = false; + } + for (auto &[key, o] : desktop_["objects"].items()) { + (void)key; + if (o.value("visible", false)) + o["pinned"] = !all; + } + } else if (action == "context-grid") + desktop_["grid"] = !desktop_.value("grid", true); + else if (action == "context-arrange") + ok = arrange_desktop(desktop_); + else if (action == "context-remove") + desktop_["objects"][context_id_]["visible"] = false; + else if (action == "context-size") { + const auto split = id.find('x'); + ok = split != id.npos && + resize_desktop_widget(desktop_, context_id_, + std::stoi(id.substr(0, split)), + std::stoi(id.substr(split + 1))); + } + if (ok && desktop_ != before) { + undo_.push_back(std::move(before)); + refresh(); + } else if (!ok) + message("Kein freier Platz. Fixierte Widgets zuerst lösen oder andere " + "Elemente entfernen."); + return; + } + if (action == "widget-add") { + auto before = desktop_; + auto &o = desktop_["objects"].at(id); + o["pinned"] = false; + if (place_desktop_object(desktop_, id, 64, 224)) { + undo_.push_back(before); + menu_.clear(); + refresh(); + } else { + desktop_ = before; + message("Für dieses Widget ist kein freier Platz vorhanden."); + } + return; + } + if (action == "view-default") { + undo_.push_back(desktop_); + desktop_ = default_desktop(); + menu_.clear(); + refresh(); + return; + } + if (action == "view-save-confirm") { + const auto name = field("view-name"); + launch::ModLibrary::validate_name(name); + const auto file = user_dir() / "layouts" / editor::path(name + ".json"); + const auto save = [this, file] { + const auto old_menu = menu_; + menu_.clear(); + refresh(); + frame(); + auto image = file; + image.replace_extension(".png"); + try { + screenshot(image); + editor::write_atomic(file, desktop_.dump(2)); + menu_.clear(); + refresh(); + } catch (...) { + menu_ = old_menu; + refresh(); + throw; + } + }; + if (fs::exists(file)) + confirmation("Gespeicherte Ansicht überschreiben?", save); + else + save(); + return; + } + if (action == "view-select") { + selections_["view"] = id; + refresh(); + return; + } + if (action == "view-load-confirm") { + launch::ModLibrary::validate_name(selections_["view"]); + const auto file = + user_dir() / "layouts" / editor::path(selections_["view"] + ".json"); + auto next = Json::parse(editor::read_file(file)); + if (!valid_desktop(next)) + throw editor::Error("Ungültige Desktopansicht."); + undo_.push_back(desktop_); + desktop_ = std::move(next); + menu_.clear(); + refresh(); + return; + } + if (action == "view-delete") { + const auto name = selections_["view"]; + if (name.empty()) + return; + launch::ModLibrary::validate_name(name); + confirmation("Ansicht „" + name + "“ löschen?", [this, name] { + const auto file = user_dir() / "layouts" / editor::path(name + ".json"); + fs::remove(file); + auto image = file; + image.replace_extension(".png"); + fs::remove(image); + selections_["view"].clear(); + refresh(); + }); + return; + } + if (action == "close") { + menu_.clear(); + draft_preferences_ = nullptr; + if (scene_ != "desktop") + scene_ = "main"; + refresh(); + return; + } + if (action == "mods") { + collect_mods(); + scene_ = "mods"; + refresh(); + return; + } + if (action == "settings") { + settings_category_ = "display"; + draft_preferences_ = nullptr; + menu_ = "settings"; + refresh(); + return; + } + if (action == "load") { + if (!source_) { + if (auto *m = mod(active_mod_); m && m->type == "Modern") + load_world(m->file); + else { + message("Bitte zuerst eine Modern-Mod aktivieren."); + return; + } + } + menu_ = "load"; + refresh(); + return; + } + if (action == "new") { + if (auto *m = mod(active_mod_); m && m->type == "Classic") { + try { + const auto contents = content::open(m->file); + launch::ModEntry entry{m->name, + "Classic", + contents->content_id, + {}, + m->file.parent_path()}; + launch::ModLibrary library(root_); + const auto user = library.user_directory(entry); + SDL_HideWindow(video_.window); + const int code = + launch::run_child(executable_, + {"--run-mod", editor::utf8(m->file), + "--save-directory", editor::utf8(user)}, + [] {}); + SDL_ShowWindow(video_.window); + if (code) + message("Classic wurde mit Fehlercode " + std::to_string(code) + + " beendet."); + refresh(); + } catch (const std::exception &e) { + SDL_ShowWindow(video_.window); + message(e.what()); + } + return; + } + if (!gui_.available()) { + message("Die GUI-Ressourcen für Modern fehlen. Bitte das vollständige " + "Modern-UI-Paket verwenden."); + return; + } + if (auto *m = mod(active_mod_); m && m->type == "Modern") + load_world(m->file); + if (!source_) { + message("Bitte eine Modern-Mod aktivieren."); + return; + } + scene_ = "newgame"; + menu_.clear(); + refresh(); + return; + } + if (action == "mod-select") { + selected_mod_ = id; + refresh(); + return; + } + if (action == "mod-activate") { + if (auto *m = mod(selected_mod_)) { + if (!m->error.empty()) { + message(m->error); + return; + } + active_mod_ = m->name; + } + refresh(); + return; + } + if (action == "mod-remove") { + if (auto *m = mod(selected_mod_)) { + const auto name = m->name; + confirmation( + "Mod „" + name + "“ löschen? Persönliche Daten bleiben erhalten.", + [this, name] { + auto *m = mod(name); + if (!m) + return; + launch::ModLibrary library(root_); + library.remove({m->name, m->type, {}, {}, m->file.parent_path()}); + if (active_mod_ == name) + active_mod_.clear(); + selected_mod_.clear(); + collect_mods(); + refresh(); + }); + } + return; + } + if (action == "mod-rename") { + auto *m = mod(selected_mod_); + if (!m) + return; + const auto previous = m->name; + text_dialog("Mod umbenennen", previous, + [this, previous](const std::string &name) { + launch::ModLibrary::validate_name(name); + auto *m = mod(previous); + if (!m) + throw editor::Error("Mod ist nicht mehr vorhanden."); + launch::ModLibrary library(root_); + library.rename( + {m->name, m->type, {}, {}, m->file.parent_path()}, name); + if (active_mod_ == previous) + active_mod_ = name; + selected_mod_ = name; + collect_mods(); + refresh(); + }); + return; + } + if (action == "import-modern") { + NFD::Guard guard; + NFD::UniquePath chosen; + const nfdfilteritem_t filter[] = {{"OpenBMH-Welt", "obw"}}; + const auto result = NFD::OpenDialog(chosen, filter, 1); + if (result == NFD_CANCEL) + return; + if (result != NFD_OKAY) { + message("Die Dateiauswahl konnte nicht geöffnet werden."); + return; + } + try { + auto candidate = Catalog::open(editor::path(chosen.get())); + std::string name = candidate->title(); + launch::ModLibrary::validate_name(name); + const auto destination = root_ / "mods" / editor::path(name); + if (fs::exists(destination)) + throw std::runtime_error( + "Eine Mod mit diesem Namen ist bereits vorhanden."); + fs::create_directories(destination.parent_path()); + const auto staging = destination.parent_path() / + (".ui-import-" + std::to_string(SDL_GetTicks64())); + fs::create_directory(staging); + try { + fs::copy_file(editor::path(chosen.get()), staging / "content.obw"); + (void)Catalog::open(staging / "content.obw"); + fs::rename(staging, destination); + } catch (...) { + fs::remove_all(staging); + throw; + } + collect_mods(); + selected_mod_ = name; + refresh(); + } catch (const std::exception &e) { + message(e.what()); + } + return; + } + if (action == "import-classic") { + NFD::Guard guard; + NFD::UniquePath chosen; + const auto result = NFD::PickFolder(chosen); + if (result == NFD_CANCEL) + return; + if (result != NFD_OKAY) { + message("Die Ordnerauswahl konnte nicht geöffnet werden."); + return; + } + try { + launch::AddMod request; + request.source = editor::path(chosen.get()); + const auto game = launch::check_game_directory(request.source); + request.name = game.family == launch::GameFamily::english ? "FTDL-classic" + : "BMH-classic"; + request.migrate = false; + launch::ModLibrary library(root_); + library.add(request, migrate_); + collect_mods(); + selected_mod_ = request.name; + refresh(); + } catch (const std::exception &e) { + message(e.what()); + } + return; + } + if (action == "setup-step") { + const auto step = target->GetAttribute("data-step", 0); + const int limit = id == "duration" ? 5 + : id == "difficulty" ? 10 + : id == "players" + ? (start_options_.value("league", true) ? 4 : 1) + : 3; + if (id == "duration" || id == "difficulty" || id == "players" || + id == "mode") + start_options_[id] = + std::clamp(start_options_.value(id, 1) + step, 1, limit); + refresh(); + return; + } + if (action == "setup-competition") { + if (id == "league" || id == "world") { + auto next = start_options_; + next[id] = !next.value(id, true); + if ((next.value("league", true) || next.value("world", true)) && + (next.value("league", true) || next.value("players", 1) == 1)) + start_options_ = std::move(next); + } + refresh(); + return; + } + if (action == "setup-next") { + managers_draft_ = Json::array(); + manager_index_ = 0; + adding_manager_ = false; + manager_picker_ = false; + selections_["portrait"] = "0"; + selections_["manager-name"] = "Alex Berger"; + scene_ = "manager"; + refresh(); + return; + } + if (action == "manager-clubs") { + selections_["manager-name"] = field("manager-name"); + manager_picker_ = true; + refresh(); + return; + } + if (action == "manager-clubs-back") { + manager_picker_ = false; + refresh(); + return; + } + if (action == "portrait-style") { + selections_["manager-name"] = field("manager-name"); + selections_["portrait-style"] = id; + refresh(); + return; + } + if (action == "portrait") { + selections_["manager-name"] = field("manager-name"); + selections_["portrait"] = id; + refresh(); + return; + } + if (action == "manager-club") { + if (!world_->manageable(id)) + return; + selected_club_ = id; + country_ = "nation:de"; + league_ = world_->find("clubs", id)->value("competition", league_); + manager_picker_ = false; + refresh(); + return; + } + if (action == "manager-back") { + scene_ = adding_manager_ ? "desktop" : "newgame"; + refresh(); + return; + } + if (action == "manager-next") { + const auto name = field("manager-name"); + if (name.empty() || !world_->manageable(selected_club_)) { + message("Bitte einen Namen und einen deutschen Verein wählen."); + return; + } + const Json m = { + {"name", name}, + {"club", selected_club_}, + {"portrait", selections_["portrait"].empty() + ? 0 + : std::stoi(selections_["portrait"])}, + {"portrait_style", + selections_["portrait-style"] == "painted" ? "painted" : "photo"}, + {"strength_choice", selections_["manager-strength"].empty() + ? 1 + : std::stoi(selections_["manager-strength"])}}; + confirmation("Sind alle Eingaben richtig?", [this, m] { + auto candidate = managers_draft_; + candidate.push_back(m); + if (!adding_manager_ && + manager_index_ + 1 < start_options_.value("players", 1)) { + managers_draft_ = candidate; + ++manager_index_; + selections_["manager-name"] = std::array{ + "Alex Berger", "Chris Winter", "Robin Meier", + "Jamie Sommer"}[size_t(manager_index_)]; + for (int p = 0; p < 12; ++p) + if (std::none_of( + candidate.begin(), candidate.end(), + [&](const auto &v) { return v.value("portrait", 0) == p; })) { + selections_["portrait"] = std::to_string(p); + break; + } + refresh(); + return; + } + if (!apply("managers", candidate)) + return; + managers_draft_ = std::move(candidate); + apply("edit", {{"key", "setup"}, {"value", start_options_}}); + scene_ = adding_manager_ || !start_options_.value("league", true) + ? "desktop" + : "opening"; + opening_page_ = 0; + draw_revealed_ = 0; + refresh(); + }); + return; + } + if (action == "opening-play") { + draw_playing_ = !draw_playing_; + draw_at_ = SDL_GetTicks64() + 900; + refresh(); + return; + } + if (action == "opening-next") { + ++opening_page_; + if (opening_page_ == 3) + draw_at_ = SDL_GetTicks64() + 900; + refresh(); + return; + } + if (action == "opening-all") { + draw_revealed_ = 64; + opening_page_ = 4; + refresh(); + return; + } + if (action == "opening-finish") { + if (opening_page_ != 4) + return; + scene_ = "desktop"; + apply("opening", "complete"); + refresh(); + return; + } + if (action == "desktop-context") { + context_menu({}, 0, 0); + return; + } + if (action.starts_with("open:")) { + const auto route = action.substr(5); + if (route == "kickoff") + return; + if (route == "newplayer") { + const auto existing = snap().state.at("managers"); + if (existing.size() >= 4) { + message("Alle vier Mitspielerplätze sind belegt."); + return; + } + managers_draft_ = existing; + manager_index_ = int(existing.size()); + adding_manager_ = true; + manager_picker_ = false; + selections_["manager-name"] = std::array{ + "Alex Berger", "Chris Winter", "Robin Meier", + "Jamie Sommer"}[existing.size()]; + for (int p = 0; p < 12; ++p) + if (std::none_of(existing.begin(), existing.end(), [&](const auto &v) { + return v.value("portrait", 0) == p; + })) { + selections_["portrait"] = std::to_string(p); + break; + } + menu_.clear(); + scene_ = "manager"; + refresh(); + return; + } + static const std::set available = { + "tables", "strengths", "camp", "settings", "save", "load"}; + if (!available.contains(route)) { + message("Diese native Ansicht wird im nächsten Menüpaket übertragen."); + return; + } + menu_ = route; + if (route == "settings") { + settings_category_ = "display"; + draft_preferences_ = nullptr; + } + refresh(); + return; + } + if (action == "ticket") { + if (ticket_) { + ticket_->open(target, device_ratio_); + dirty_ = true; + } + return; + } + if (action == "camp-region") { + selections_["camp-region"] = id; + refresh(); + return; + } + if (action == "camp-select") { + apply("camp.select", id); + refresh(); + return; + } + if (action == "camp-remember") { + if (apply("camp.remember", {})) + message("Trainingslager für die Demo vorgemerkt."); + return; + } + if (action == "settings-category") { + settings_category_ = id; + refresh(); + return; + } + if (action == "settings-theme") { + draft_preferences_["theme"] = id; + refresh(); + return; + } + if (action == "settings-apply") { + if (settings_category_ == "display") { + for (const auto *key : {"mode", "resolution", "scale"}) { + const auto value = field(std::string("display-") + key); + if (!value.empty()) + draft_preferences_[key] = value; + } + } + if (settings_category_ == "sound") { + draft_preferences_["effects"] = + element("sound-effects")->HasAttribute("checked"); + draft_preferences_["sound-style"] = field("sound-style"); + } + if (source_ && !apply("preferences", draft_preferences_)) + return; + theme_ = draft_preferences_.value("theme", theme_); + draft_preferences_ = nullptr; + menu_.clear(); + refresh(); + return; + } + if (action == "save-select") { + selections_["save"] = id; + refresh(); + return; + } + if (action == "save-new") { + selections_["save"].clear(); + refresh(); + return; + } + if (action == "save-confirm") { + auto name = + selections_["save"].empty() ? field("save-name") : selections_["save"]; + try { + launch::ModLibrary::validate_name(name); + const auto file = user_dir() / "saves" / editor::path(name + ".json"); + fs::create_directories(file.parent_path()); + const auto save = [this, file] { + init_desktop(); + source_->save(file, desktop_); + saved_desktop_ = desktop_; + menu_.clear(); + if (quit_after_save_) + closed_ = true; + refresh(); + }; + if (fs::exists(file)) + confirmation("Vorhandenen Demo-Spielstand überschreiben?", save); + else + save(); + } catch (const std::exception &e) { + message(e.what()); + } + return; + } + if (action == "load-confirm") { + const auto name = selections_["save"]; + if (name.empty()) + return; + try { + launch::ModLibrary::validate_name(name); + desktop_ = + source_->load(user_dir() / "saves" / editor::path(name + ".json")); + saved_desktop_ = desktop_; + theme_ = snap().state.at("preferences").value("theme", theme_); + menu_.clear(); + scene_ = "desktop"; + refresh(); + } catch (const std::exception &e) { + message(e.what()); + } + return; + } + if (action == "save-rename") { + const auto previous = selections_["save"]; + if (previous.empty()) + return; + text_dialog( + "Speicherstand umbenennen", previous, + [this, previous](const std::string &name) { + launch::ModLibrary::validate_name(name); + if (name == previous) + return; + const auto folder = user_dir() / "saves", + old_file = folder / editor::path(previous + ".json"), + new_file = folder / editor::path(name + ".json"); + if (fs::exists(new_file)) + throw editor::Error("Diese Bezeichnung ist bereits vorhanden."); + fs::rename(old_file, new_file); + selections_["save"] = name; + refresh(); + }); + return; + } + if (action == "save-delete") { + const auto name = selections_["save"]; + if (name.empty()) + return; + confirmation("Demo-Spielstand „" + name + "“ löschen?", [this, name] { + launch::ModLibrary::validate_name(name); + fs::remove(user_dir() / "saves" / editor::path(name + ".json")); + selections_["save"].clear(); + refresh(); + }); + return; + } + if (action == "player-detail") { + if (const auto *p = world_->find("players", id)) + message(world_->name(*p) + " · Stärke " + + std::to_string( + p->value("attributes", Json::object()).value("strength", 0))); + return; + } + if (action == "club-detail") { + if (const auto *c = world_->find("clubs", id)) + message(world_->name(*c) + " · " + + std::to_string(world_->squad(id).size()) + " Spieler"); + return; + } + if (action == "squad-tactics") { + menu_ = "tactics"; + refresh(); + return; + } +} +void App::change(Rml::Element *target) { + const auto kind = target->GetAttribute("data-change", ""); + auto *control = dynamic_cast(target); + if (!control) + return; + const auto value = control->GetValue(); + if (kind == "manager-country" || kind == "manager-league") { + if (!manager_picker_) + selections_["manager-name"] = field("manager-name"); + if (kind == "manager-country") { + country_ = value; + league_.clear(); + } else + league_ = value; + refresh(); + } else if (kind == "manager-strength") { + selections_["manager-strength"] = value; + } else if (kind == "table-country") { + country_ = value; + league_.clear(); + refresh(); + } else if (kind == "table-league") { + league_ = value; + refresh(); + } else if (kind == "table-scope") { + selections_["table-scope"] = value; + } +} +void App::input(Rml::Element *target) { + const auto kind = target->GetAttribute("data-input", ""); + auto *control = dynamic_cast(target); + if (!control) + return; + const auto value = control->GetValue(); + if (kind == "sound-volume") { + const int n = std::stoi(value); + draft_preferences_["volume"] = n; + element("volume-value")->SetInnerRML(std::to_string(n) + " %"); + dirty_ = true; + } + if (kind == "camp-focus") { + const auto i = std::stoi(target->GetAttribute("data-id", "0")); + if (i < 0 || i > 2) + return; + auto focus = snap().state.at("camp").at("focus"); + focus[size_t(i)] = std::stoi(value); + if (apply("camp.focus", focus)) { + element("camp-value-" + std::to_string(i))->SetInnerRML(value + " / 15"); + const int rest = + 15 - + (focus[0].get() + focus[1].get() + focus[2].get()) / 3; + element("camp-value-3")->SetInnerRML(std::to_string(rest) + " / 15"); + if (auto *c = + dynamic_cast(element("camp-focus-3"))) + c->SetValue(std::to_string(rest)); + dirty_ = true; + } + } +} +void App::script() { + std::ifstream stream(config_.commands); + if (!stream) + throw editor::Error("UI-Skript kann nicht gelesen werden."); + const auto locate = [&](const Json &command) { + if (command.contains("selector")) { + context_->Update(); + auto *node = + doc_->QuerySelector(command.at("selector").get()); + if (!node || !node->IsVisible(true)) + throw editor::Error("UI-Skript: Element nicht sichtbar."); + const auto at = node->GetAbsoluteOffset(Rml::BoxArea::Border), + size = node->GetBox().GetSize(Rml::BoxArea::Border); + return Rml::Vector2i{int(at.x + size.x * .5f), int(at.y + size.y * .5f)}; + } + return Rml::Vector2i{command.at("x").get(), + command.at("y").get()}; + }; + std::string line; + size_t index = 0; + while (std::getline(stream, line)) { + ++index; + if (line.empty()) + continue; + try { + const auto command = Json::parse(line); + const auto type = command.value("type", std::string()); + if (type == "click" || type == "right") { + const auto point = locate(command); + const int button = type == "right" ? 1 : 0; + context_->ProcessMouseMove(point.x, point.y, 0); + context_->ProcessMouseButtonDown(button, 0); + context_->ProcessMouseButtonUp(button, 0); + } else if (type == "drag") { + const auto point = locate(command), + end = Rml::Vector2i{command.at("to_x"), command.at("to_y")}; + context_->ProcessMouseMove(point.x, point.y, 0); + context_->ProcessMouseButtonDown(0, 0); + for (int i = 1; i <= 12; ++i) + 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 == "text") + context_->ProcessTextInput(command.value("value", std::string())); + else if (type == "key") { + const std::map keys = { + {"ESC", Rml::Input::KI_ESCAPE}, {"ENTER", Rml::Input::KI_RETURN}, + {"TAB", Rml::Input::KI_TAB}, {"SPACE", Rml::Input::KI_SPACE}, + {"HOME", Rml::Input::KI_HOME}, {"END", Rml::Input::KI_END}, + {"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}}; + const auto name = command.at("value").get(); + if (!keys.contains(name)) + throw editor::Error("Unbekannte UI-Skripttaste."); + const int mods = + (command.value("ctrl", false) ? Rml::Input::KM_CTRL : 0) | + (command.value("shift", false) ? Rml::Input::KM_SHIFT : 0); + context_->ProcessKeyDown(keys.at(name), mods); + context_->ProcessKeyUp(keys.at(name), mods); + } else if (type == "screenshot") + screenshot(editor::path(command.at("path").get())); + else if (type == "checkpoint") { + init_desktop(); + source_->save(editor::path(command.at("path").get()), + desktop_); + } else if (type == "snapshot") + editor::write_atomic( + editor::path(command.at("path").get()), + Json{{"scene", scene_}, + {"menu", menu_}, + {"desktop", desktop_}, + {"demo", source_ ? snap().state : Json()}} + .dump(2)); + else if (type == "dom") + editor::write_atomic( + editor::path(command.at("path").get()), + doc_->GetInnerRML()); + else if (type == "assert") { + if (command.contains("scene") && + scene_ != command.at("scene").get()) + throw editor::Error("UI-Skript: falsche Szene."); + if (command.contains("menu") && + menu_ != command.at("menu").get()) + throw editor::Error("UI-Skript: falsches Menü."); + if (command.contains("selector")) { + auto *node = + doc_->QuerySelector(command.at("selector").get()); + const bool present = node && node->IsVisible(true); + if (present != command.value("visible", true)) + throw editor::Error("UI-Skript: falsche Sichtbarkeit."); + if (command.contains("disabled") && + (!node || node->HasAttribute("disabled") != + command.at("disabled").get())) + throw editor::Error("UI-Skript: falscher Sperrstatus."); + } + if (command.contains("ticket") && + snap().state.at("ticket") != command.at("ticket")) + throw editor::Error("UI-Skript: falscher Eintrittspreis."); + } else + throw editor::Error("Unbekannter UI-Skriptbefehl: " + type); + frame(); + } catch (const std::exception &e) { + throw editor::Error("UI-Skript Zeile " + std::to_string(index) + ": " + + e.what()); + } + } +} diff --git a/src/modern/ui/desktop.cpp b/src/modern/ui/desktop.cpp new file mode 100644 index 0000000..be4b2d5 --- /dev/null +++ b/src/modern/ui/desktop.cpp @@ -0,0 +1,239 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "modern/ui/desktop.hpp" +#include +#include +#include + +namespace bmh::modern_ui { +namespace { +constexpr int pitch = 248, gap = 24, cell = 224, left = 64, top = 224; +bool overlaps(const Json &a, const Json &b, int spacing) { + const int x = a.at("x"), y = a.at("y"), bx = b.at("x"), by = b.at("y"); + return x < bx + b.at("w").get() + spacing && + x + a.at("w").get() + spacing > bx && + y < by + b.at("h").get() + spacing && + y + a.at("h").get() + spacing > by; +} +bool find_space(Json &layout, const std::string &id, int near_x, int near_y, + bool nearest) { + auto &object = layout.at("objects").at(id); + const int width = object.at("w"), height = object.at("h"); + const bool grid = layout.value("grid", true); + const int step = grid ? pitch : 32; + double best = std::numeric_limits::max(); + int found_x = -1, found_y = -1; + for (int y = top; y + height <= 2160 - gap; y += step) { + for (int x = left; x + width <= 3840 - gap; x += step) { + Json candidate = object; + candidate["x"] = x; + candidate["y"] = y; + bool collision = false; + for (const auto &[other_id, other] : layout.at("objects").items()) { + if (other_id != id && other.value("visible", false) && + overlaps(candidate, other, grid ? gap : 20)) { + collision = true; + break; + } + } + if (collision) + continue; + const double distance = nearest ? std::hypot(x - near_x, y - near_y) : 0; + if (distance < best) { + best = distance; + found_x = x; + found_y = y; + } + if (!nearest) + break; + } + if (!nearest && found_x >= 0) + break; + } + if (found_x < 0) + return false; + object["x"] = found_x; + object["y"] = found_y; + return true; +} +Json object(int column, int row, int columns, int rows, bool widget, + bool visible) { + return {{"x", left + column * pitch}, + {"y", top + row * pitch}, + {"w", columns * pitch - gap}, + {"h", rows * pitch - gap}, + {"pinned", true}, + {"visible", visible}, + {"widget", widget}}; +} +} // namespace +const std::vector &desktop_routes() { + static const std::vector value = { + "tables", "league", "strengths", "lineup", "achievements", + "other", "friendlies", "postpone", "calendar", "indoor", + "load", "save", "kickoff", "toto", "bank", + "camp", "training", "transfer", "tactics", "settings", + "scorers", "advertising", "stadium", "statistics", "environment", + "fairplay", "highscore", "contracts", "balance", "newplayer", + "news"}; + return value; +} +const std::vector &widget_definitions() { + static const std::vector value = { + {"calendar", "Kalender", {{2, 2}, {2, 3}, {3, 3}}}, + {"account", "Konto & Eintritt", {{4, 1}, {2, 2}, {4, 2}, {4, 3}}}, + {"competition", "Wettbewerb & Gegner", {{2, 2}, {4, 2}, {4, 3}}}, + {"portrait", "Managerporträt", {{2, 2}, {3, 3}}}, + {"crest", "Vereinswappen", {{2, 2}, {3, 3}}}, + {"opponent-crest", "Gegnerwappen", {{2, 2}, {3, 3}}}, + {"warnings", "Warnlampen", {{4, 1}, {2, 2}, {4, 2}, {4, 3}}}, + {"fans", "Fan-Stimmung", {{2, 1}, {4, 1}}}, + {"own-curve", + "Tabellenplatz · eigener Verein", + {{2, 2}, {3, 3}, {4, 2}, {4, 4}}}, + {"opponent-curve", + "Tabellenplatz · Gegner", + {{2, 2}, {3, 3}, {4, 2}, {4, 4}}}, + {"comparison-curve", + "Tabellenplätze · Vergleich", + {{3, 3}, {4, 2}, {4, 4}}}, + {"results", "Letzte sechs Spiele", {{4, 1}, {2, 2}, {4, 2}, {4, 4}}}, + {"duels", "Direkter Vergleich", {{2, 2}, {4, 2}}}, + {"own-summary", "Platz & Stärke · eigener Verein", {{2, 1}, {4, 1}}}, + {"opponent-summary", "Platz & Stärke · Gegner", {{2, 1}, {4, 1}}}, + {"news", "Nachrichten", {{2, 2}, {4, 2}, {4, 4}}}, + {"trash", "Papierkorb", {{1, 1}, {2, 2}}}}; + return value; +} +Json default_desktop() { + Json layout = {{"schema", "openbmh-modern-desktop@1"}, + {"grid", true}, + {"objects", Json::object()}}; + for (const auto &definition : widget_definitions()) { + const auto [w, h] = definition.sizes.front(); + layout["objects"][definition.id] = object(0, 0, w, h, true, false); + } + auto &objects = layout["objects"]; + objects["calendar"] = object(0, 0, 2, 3, true, true); + objects["account"] = object(2, 0, 4, 2, true, true); + objects["competition"] = object(2, 2, 4, 2, true, true); + objects["portrait"] = object(6, 0, 2, 2, true, true); + objects["crest"] = object(8, 0, 2, 2, true, true); + objects["opponent-crest"] = object(10, 0, 2, 2, true, true); + objects["warnings"] = object(6, 2, 4, 2, true, true); + objects["trash"] = object(14, 6, 1, 1, true, true); + for (const auto &route : desktop_routes()) { + const auto id = "app-" + route; + objects[id] = object(0, 0, 1, 1, false, false); + if (!find_space(layout, id, left, top, false)) + throw editor::Error("default_desktop_full"); + objects[id]["visible"] = true; + } + return layout; +} +bool valid_desktop(const Json &layout) { + try { + if (layout.at("schema") != "openbmh-modern-desktop@1" || + !layout.at("grid").is_boolean()) + return false; + const auto &objects = layout.at("objects"); + if (!objects.is_object() || + objects.size() != widget_definitions().size() + desktop_routes().size()) + return false; + const auto check = [&](const std::string &id, bool widget) { + const auto &o = objects.at(id); + for (const auto *key : {"x", "y", "w", "h"}) + if (!o.at(key).is_number_integer() || o.at(key) < 0 || o.at(key) > 3840) + return false; + if (!o.at("visible").is_boolean() || !o.at("pinned").is_boolean() || + o.at("widget") != widget) + return false; + const int x = o.at("x"), y = o.at("y"), w = o.at("w"), h = o.at("h"); + return w > 0 && h > 0 && w <= 3840 && h <= 2160 - top && x >= 0 && + y >= top && x <= 3840 - w && y <= 2160 - h && + (widget || (w == cell && h == cell && o.at("visible") == true)); + }; + for (const auto &d : widget_definitions()) { + if (!check(d.id, true)) + return false; + const auto &o = objects.at(d.id); + if (std::none_of(d.sizes.begin(), d.sizes.end(), [&](auto s) { + return o.at("w") == s.first * pitch - gap && + o.at("h") == s.second * pitch - gap; + })) + return false; + } + for (const auto &route : desktop_routes()) + if (!check("app-" + route, false)) + return false; + return true; + } catch (const Json::exception &) { + return false; + } +} +bool place_desktop_object(Json &layout, const std::string &id, int x, int y, + bool nearest) { + if (!valid_desktop(layout) || !layout["objects"].contains(id)) + return false; + auto next = layout; + auto &o = next["objects"][id]; + if (o.at("pinned") == true) + return false; + if (!next.at("grid").get()) { + o["x"] = std::clamp(x, 0, 3840 - o.at("w").get()); + o["y"] = std::clamp(y, top, 2160 - o.at("h").get()); + } else if (!find_space(next, id, x, y, nearest)) + return false; + o["visible"] = true; + layout = std::move(next); + return true; +} +bool resize_desktop_widget(Json &layout, const std::string &id, int columns, + int rows) { + if (!valid_desktop(layout)) + return false; + const auto found = + std::find_if(widget_definitions().begin(), widget_definitions().end(), + [&](const auto &d) { return d.id == id; }); + if (found == widget_definitions().end() || + std::find(found->sizes.begin(), found->sizes.end(), + std::pair{columns, rows}) == found->sizes.end()) + return false; + auto next = layout; + auto &o = next["objects"][id]; + if (o.at("pinned") == true) + return false; + o["w"] = columns * pitch - gap; + o["h"] = rows * pitch - gap; + if (!find_space(next, id, o.at("x"), o.at("y"), true)) + return false; + o["visible"] = true; + layout = std::move(next); + return true; +} +bool arrange_desktop(Json &layout) { + if (!valid_desktop(layout)) + return false; + auto next = layout; + next["grid"] = true; + std::vector loose; + for (auto &[id, o] : next["objects"].items()) + if (o.at("visible") == true && o.at("pinned") == false) { + loose.push_back(id); + o["visible"] = false; + } + std::stable_sort( + loose.begin(), loose.end(), [&](const auto &a, const auto &b) { + const auto &x = next["objects"][a], &y = next["objects"][b]; + return x.at("w").template get() * x.at("h").template get() > + y.at("w").template get() * y.at("h").template get(); + }); + for (const auto &id : loose) { + auto &o = next["objects"][id]; + if (!find_space(next, id, o.at("x"), o.at("y"), false)) + return false; + o["visible"] = true; + } + layout = std::move(next); + return true; +} +} // namespace bmh::modern_ui diff --git a/src/modern/ui/desktop.hpp b/src/modern/ui/desktop.hpp new file mode 100644 index 0000000..e9c591c --- /dev/null +++ b/src/modern/ui/desktop.hpp @@ -0,0 +1,20 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +#include "modern/ui/catalog.hpp" + +namespace bmh::modern_ui { +struct WidgetDefinition { + std::string id, name; + std::vector> sizes; +}; +const std::vector &widget_definitions(); +const std::vector &desktop_routes(); +// These operations stage the whole layout. Failed placement leaves it +// untouched. +Json default_desktop(); +bool valid_desktop(const Json &); +bool place_desktop_object(Json &, const std::string &, int x, int y, + bool nearest = true); +bool resize_desktop_widget(Json &, const std::string &, int columns, int rows); +bool arrange_desktop(Json &); +} // namespace bmh::modern_ui diff --git a/src/modern/ui/desktop_screens.inc b/src/modern/ui/desktop_screens.inc new file mode 100644 index 0000000..e671a7c --- /dev/null +++ b/src/modern/ui/desktop_screens.inc @@ -0,0 +1,92 @@ +// SPDX-License-Identifier: GPL-3.0-only +std::string App::render_desktop_tools(const std::string &key) { + init_desktop(); + if (key == "background") + return "
" + + img("background", 2200, 1240, false, true, 1800) + + "

Stadion bei Nacht

Aktueller " + "Hintergrund

"; + if (key == "widgets") { + std::string body = + "
"; + size_t i = 0; + for (const auto &definition : widget_definitions()) { + const auto &o = desktop_["objects"].at(definition.id); + body += "

" + + esc(definition.name) + "

"; + for (auto [w, h] : definition.sizes) + body += std::to_string(w) + " × " + std::to_string(h) + "   "; + body += "

" + + btn("widget-add", + o.value("visible", false) ? "Bereits auf dem Desktop" + : "Hinzufügen", + {}, + "data-id=\"" + definition.id + + "\" " + "style=\"position:absolute;left:30dp;right:30dp;bottom:" + "30dp;\" " + + (o.value("visible", false) ? "disabled" : "")) + + "
"; + ++i; + } + return body + "
"; + } + const bool saving = key == "view-save"; + const auto directory = user_dir() / "layouts"; + std::vector names; + if (fs::exists(directory)) + for (const auto &entry : fs::directory_iterator(directory)) + if (entry.is_regular_file() && entry.path().extension() == ".json") + names.push_back(editor::utf8(entry.path().stem())); + std::sort(names.begin(), names.end()); + std::string body = "
"; + if (!saving) + body += btn("view-default", "Standardansicht · fixiert", "choice", + "style=\"width:100%;height:120dp;text-align:left;margin-bottom:" + "18dp;\""); + for (const auto &name : names) + body += btn("view-select", esc(name), + std::string("choice ") + + (name == selections_["view"] ? "selected" : ""), + "data-id=\"" + esc(name) + + "\" " + "style=\"width:100%;height:120dp;text-align:left;margin-" + "bottom:18dp;\""); + body += + "

" + + std::string(saving ? "Aktuelle Ansicht speichern" + : selections_["view"].empty() ? "Ansicht auswählen" + : esc(selections_["view"])) + + "

"; + if (!selections_["view"].empty()) { + launch::ModLibrary::validate_name(selections_["view"]); + auto preview = directory / editor::path(selections_["view"] + ".png"); + if (fs::is_regular_file(preview)) + body += ""; + } + if (saving) + body += "
"; + body += "
" + + btn("view-delete", "Löschen", {}, + selections_["view"].empty() ? "disabled" : "") + + btn("close", "Abbrechen") + + btn(saving ? "view-save-confirm" : "view-load-confirm", + saving ? "Speichern" : "Laden", "primary", + !saving && selections_["view"].empty() ? "disabled" : "") + + "
"; + return body; +} diff --git a/src/modern/ui/gui_assets.cpp b/src/modern/ui/gui_assets.cpp new file mode 100644 index 0000000..9ea469e --- /dev/null +++ b/src/modern/ui/gui_assets.cpp @@ -0,0 +1,62 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "modern/ui/gui_assets.hpp" +#include +#include + +namespace bmh::modern_ui { +GuiAssets::GuiAssets(fs::path root) : root_(std::move(root)) { + if (root_.empty() || !fs::exists(root_ / "gui-assets.json")) + return; + root_ = fs::weakly_canonical(root_); + auto document = Json::parse(editor::read_file(root_ / "gui-assets.json")); + if (document.value("schema", "") != "openbmh-gui-assets@1" || + !document.at("items").is_object()) + throw editor::Error("invalid_gui_catalog"); + items_ = document.at("items"); + for (const auto &[key, item] : items_.items()) { + const auto relative = editor::path(item.at("file").get()); + const auto full = fs::weakly_canonical(root_ / relative); + const auto inside = full.lexically_relative(root_); + if (relative.is_absolute() || inside.empty() || *inside.begin() == ".." || + !fs::is_regular_file(full)) + throw editor::Error("missing_or_unsafe_gui_asset", {{"key", key}}); + } +} +editor::images::Raster GuiAssets::decode(const std::string &key, + int pixels) const { + if (!items_.contains(key)) + throw editor::Error("missing_gui_asset", {{"key", key}}); + const auto item = items_.at(key); + const auto file = root_ / editor::path(item.at("file").get()); + auto image = editor::images::decode(editor::read_file(file), + file.extension().string(), pixels); + if (!item.contains("crop")) + return image; + const auto crop = item.at("crop"); + if (!crop.is_array() || crop.size() != 4) + throw editor::Error("invalid_gui_crop"); + for (const auto &n : crop) + if (!n.is_number() || !std::isfinite(n.get()) || n < 0 || n > 1) + throw editor::Error("invalid_gui_crop"); + if (crop[2] <= 0 || crop[3] <= 0 || + crop[0].get() + crop[2].get() > 1.000001 || + crop[1].get() + crop[3].get() > 1.000001) + throw editor::Error("invalid_gui_crop"); + const auto x = std::clamp( + int(std::round(crop[0].get() * image.width)), 0, image.width - 1); + const auto y = + std::clamp(int(std::round(crop[1].get() * image.height)), 0, + image.height - 1); + const auto width = std::clamp( + int(std::round(crop[2].get() * image.width)), 1, image.width - x); + const auto height = + std::clamp(int(std::round(crop[3].get() * image.height)), 1, + image.height - y); + editor::images::Raster out{width, height, + std::vector(size_t(width) * height * 4)}; + for (int row = 0; row < height; ++row) + std::copy_n(image.pixels.data() + (size_t(y + row) * image.width + x) * 4, + size_t(width) * 4, out.pixels.data() + size_t(row) * width * 4); + return out; +} +} // namespace bmh::modern_ui diff --git a/src/modern/ui/gui_assets.hpp b/src/modern/ui/gui_assets.hpp new file mode 100644 index 0000000..2c33a65 --- /dev/null +++ b/src/modern/ui/gui_assets.hpp @@ -0,0 +1,20 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +#include "editor/images.hpp" +#include "modern/ui/catalog.hpp" + +namespace bmh::modern_ui { +class GuiAssets { +public: + explicit GuiAssets(fs::path root = {}); + bool available() const { return !items_.empty(); } + editor::images::Raster decode(const std::string &, int pixels = 1024) const; + bool contains(const std::string &key) const { return items_.contains(key); } + const Json &items() const { return items_; } + const fs::path &root() const { return root_; } + +private: + fs::path root_; + Json items_ = Json::object(); +}; +} // namespace bmh::modern_ui diff --git a/src/modern/ui/model.cpp b/src/modern/ui/model.cpp new file mode 100644 index 0000000..e964da6 --- /dev/null +++ b/src/modern/ui/model.cpp @@ -0,0 +1,184 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "modern/ui/model.hpp" +#include "modern/ui/desktop.hpp" +#include +#include + +namespace bmh::modern_ui { +namespace { +bool valid_date(const Json &value) { + if (!value.is_string()) + return false; + const auto text = value.get(); + if (text.size() != 10 || text[4] != '-' || text[7] != '-') + return false; + for (size_t i = 0; i < text.size(); ++i) + if (i != 4 && i != 7 && (text[i] < '0' || text[i] > '9')) + return false; + const int year = std::stoi(text.substr(0, 4)), + month = std::stoi(text.substr(5, 2)), + day = std::stoi(text.substr(8, 2)); + return year > 0 && + std::chrono::year_month_day{std::chrono::year{year}, + std::chrono::month{unsigned(month)}, + std::chrono::day{unsigned(day)}} + .ok(); +} +bool camp_id(const Json &value) { + if (!value.is_string()) + return false; + const auto id = value.get(); + for (int i = 0; i < 18; ++i) + if (id == "resort:" + std::to_string(i)) + return true; + return false; +} +bool preferences(const Json &value) { + if (!value.is_object()) + return false; + const auto theme = value.value("theme", std::string("midnight")); + return (theme == "midnight" || theme == "silver" || theme == "matchday") && + (!value.contains("volume") || + (value["volume"].is_number_integer() && value["volume"] >= 0 && + value["volume"] <= 100)) && + (!value.contains("effects") || value["effects"].is_boolean()); +} +} // namespace +DemoSource::DemoSource(std::shared_ptr catalog) + : catalog_(std::move(catalog)) { + std::string club; + for (const auto *c : catalog_->clubs()) { + if (!catalog_->manageable(c->value("id", ""))) + continue; + club = c->value("id", ""); + break; + } + if (club.empty()) + throw editor::Error("no_manageable_demo_club"); + state_ = { + {"schema", "openbmh-ui-demo@1"}, + {"world", catalog_->manifest().value("id", "")}, + {"date", catalog_->manifest().value("start_date", "2026-07-01")}, + {"managers", + Json::array( + {{{"name", "Alex Berger"}, {"club", club}, {"portrait", 0}}})}, + {"cash", 12450000}, + {"deposit", 600000}, + {"debt", 0}, + {"ticket", 13}, + {"fans", 67}, + {"camp", + {{"selected", "resort:4"}, {"confirmed", ""}, {"focus", {5, 4, 6}}}}, + {"opening", "complete"}, + {"preferences", + {{"theme", "midnight"}, {"volume", 80}, {"effects", true}}}, + {"edits", Json::object()}}; + saved_ = state_; + if (!valid_date(state_.at("date"))) + throw editor::Error("invalid_demo_date"); +} +Snapshot DemoSource::snapshot() const { return {revision_, catalog_, state_}; } +ActionResult DemoSource::apply(const Action &action) { + if (action.revision != revision_) + return {false, revision_, "stale_revision"}; + auto next = state_; + try { + if (action.kind == "ticket") { + if (!action.value.is_number_integer() || action.value < 0 || + action.value > 25) + return {false, revision_, "invalid_demo_ticket"}; + next["ticket"] = action.value; + } else if (action.kind == "managers") { + if (!action.value.is_array() || action.value.empty() || + action.value.size() > 4) + return {false, revision_, "invalid_managers"}; + std::set clubs; + std::set portraits; + for (const auto &m : action.value) { + const auto club = m.at("club").get(); + const auto name = m.at("name").get(); + if (!catalog_->manageable(club)) + return {false, revision_, "club_locked"}; + const auto portrait = m.value("portrait", 0); + if (name.find_first_not_of(" \t\r\n") == name.npos || + name.size() > 160 || portrait < 0 || portrait > 11 || + !clubs.insert(club).second || !portraits.insert(portrait).second) + return {false, revision_, "invalid_manager"}; + } + next["managers"] = action.value; + } else if (action.kind == "camp.select") { + if (!camp_id(action.value)) + return {false, revision_, "camp_unknown"}; + next["camp"]["selected"] = action.value; + } else if (action.kind == "camp.focus") { + if (!action.value.is_array() || action.value.size() != 3) + return {false, revision_, "invalid_focus"}; + for (const auto &v : action.value) + if (!v.is_number_integer() || v < 0 || v > 15) + return {false, revision_, "invalid_focus"}; + next["camp"]["focus"] = action.value; + } else if (action.kind == "camp.remember") + next["camp"]["confirmed"] = next["camp"]["selected"]; + else if (action.kind == "opening") + next["opening"] = action.value; + else if (action.kind == "preferences") { + if (!preferences(action.value)) + return {false, revision_, "invalid_preferences"}; + next["preferences"] = action.value; + } else if (action.kind == "edit") { + const auto key = action.value.at("key").get(); + if (key.empty() || key.size() > 100) + return {false, revision_, "invalid_edit"}; + next["edits"][key] = action.value.at("value"); + } else + return {false, revision_, "unsupported_demo_action"}; + } catch (const Json::exception &) { + return {false, revision_, "invalid_action"}; + } + state_ = std::move(next); + return {true, ++revision_, {}}; +} +void DemoSource::save(const fs::path &file, const Json &desktop) { + if (!valid_desktop(desktop)) + throw editor::Error("invalid_demo_desktop"); + auto out = state_; + out["desktop"] = desktop; + editor::write_atomic(file, out.dump(2)); + saved_ = state_; +} +Json DemoSource::load(const fs::path &file) { + const auto data = Json::parse(editor::read_file(file)); + if (data.value("schema", "") != "openbmh-ui-demo@1" || + data.value("world", "") != catalog_->manifest().value("id", "")) + throw editor::Error("wrong_demo_world"); + auto validation = DemoSource(catalog_); + const auto result = validation.apply({0, "managers", data.at("managers")}); + if (!result.ok) + throw editor::Error(result.error); + if (!data.at("ticket").is_number_integer() || data.at("ticket") < 0 || + data.at("ticket") > 25) + throw editor::Error("invalid_demo_ticket"); + for (const auto *key : {"cash", "deposit", "debt", "fans"}) + if (!data.at(key).is_number_integer()) + throw editor::Error("invalid_demo_number"); + if (!valid_date(data.at("date")) || !preferences(data.at("preferences")) || + !data.at("edits").is_object() || !data.at("opening").is_string() || + !camp_id(data.at("camp").at("selected"))) + throw editor::Error("invalid_demo_state"); + const auto &focus = data.at("camp").at("focus"); + if (!focus.is_array() || focus.size() != 3) + throw editor::Error("invalid_focus"); + for (const auto &v : focus) + if (!v.is_number_integer() || v < 0 || v > 15) + throw editor::Error("invalid_focus"); + auto next = data; + const auto desktop = next.value("desktop", Json::object()); + if (!valid_desktop(desktop)) + throw editor::Error("invalid_demo_desktop"); + next.erase("desktop"); + state_ = std::move(next); + saved_ = state_; + ++revision_; + return desktop; +} +} // namespace bmh::modern_ui diff --git a/src/modern/ui/model.hpp b/src/modern/ui/model.hpp new file mode 100644 index 0000000..6cb5bec --- /dev/null +++ b/src/modern/ui/model.hpp @@ -0,0 +1,42 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +#include "modern/ui/catalog.hpp" + +namespace bmh::modern_ui { +struct Snapshot { + uint64_t revision = 0; + std::shared_ptr world; + Json state; +}; +struct Action { + uint64_t revision = 0; + std::string kind; + Json value; +}; +struct ActionResult { + bool ok = false; + uint64_t revision = 0; + std::string error; +}; +// The native view depends on this presentation boundary, never on GameState. +class DataSource { +public: + virtual ~DataSource() = default; + virtual Snapshot snapshot() const = 0; + virtual ActionResult apply(const Action &) = 0; +}; +class DemoSource final : public DataSource { +public: + explicit DemoSource(std::shared_ptr); + Snapshot snapshot() const override; + ActionResult apply(const Action &) override; + void save(const fs::path &, const Json &desktop); + Json load(const fs::path &); + bool dirty() const { return state_ != saved_; } + +private: + std::shared_ptr catalog_; + Json state_, saved_; + uint64_t revision_ = 0; +}; +} // namespace bmh::modern_ui diff --git a/src/modern/ui/screens.inc b/src/modern/ui/screens.inc new file mode 100644 index 0000000..69fe958 --- /dev/null +++ b/src/modern/ui/screens.inc @@ -0,0 +1,958 @@ +// SPDX-License-Identifier: GPL-3.0-only +// Included in the native UI implementation's anonymous namespace. +void App::init_desktop() { + if (!desktop_.contains("objects")) { + desktop_ = default_desktop(); + saved_desktop_ = desktop_; + } +} + +std::string App::widget(const std::string &id, const Json &o) { + const auto s = snap(); + const auto *own = club(s); + const auto w = o.value("w", 472), h = o.value("h", 472); + const auto row = world_->clubs(own ? own->value("competition", "") : league_); + const auto *opponent = + row.size() > 1 ? (row[0] == own ? row[1] : row[0]) : own; + auto heading = [&](const std::string &name) { + return "
" + esc(name) + "
"; + }; + if (id == "calendar") { + const auto date = s.state.value("date", std::string("2026-07-01")); + const auto year = date.substr(0, 4), day = date.substr(8, 2); + const int month = std::stoi(date.substr(5, 2)); + const std::array months = { + "Januar", "Februar", "März", "April", "Mai", "Juni", + "Juli", "August", "September", "Oktober", "November", "Dezember"}; + return "
" + + std::string(months[size_t(std::clamp(month, 1, 12) - 1)]) + " " + + year + + "

Saisonvorbereitung

" + + std::to_string(std::stoi(day)) + "

" + + esc(date) + "

" + + btn("open:calendar", "Kalender öffnen ↗", "card-button", + "style=\"left:0;bottom:0;width:100%;height:90dp;border-top:2dp " + "var(--border);font-size:25dp;color:var(--muted);\""); + } + if (id == "account") { + if (h < 300) + return "
Konto

" + + cash(s.state.value("cash", int64_t(0))) + "

" + + btn("ticket", + "Eintritt   " + + std::to_string(s.state.value("ticket", 13)) + " €", + "card-button", + "id=\"desktop-ticket\" data-interactive=\"true\" " + "style=\"right:20dp;top:45dp;font-size:32dp;\""); + return heading("Vereinskasse") + + "

Guthaben

" + + cash(s.state.value("cash", int64_t(0))) + + "

Sparbuch

" + + cash(s.state.value("deposit", int64_t(0))) + "

" + + btn("ticket", + "Eintritt
" + + std::to_string(s.state.value("ticket", 13)) + " €   ›", + "card-button", + "id=\"desktop-ticket\" data-interactive=\"true\" " + "style=\"right:30dp;bottom:20dp;min-width:200dp;padding:12dp " + "24dp;font-size:34dp;background-color:var(--soft);border-radius:" + "18dp;\""); + } + if (id == "portrait") + return img(std::string(manager(s).value("portrait_style", "photo") == + "painted" + ? "manager-painted." + : "manager.") + + std::to_string(manager(s).value("portrait", 0)), + w, h, false, true, 800) + + "
Manager

" + + esc(manager(s).value("name", "")) + "

"; + if (id == "crest" || id == "opponent-crest") + return "
" + + crest(id == "crest" ? own : opponent, std::min(w - 60, h - 150)) + + "

" + + (id == "crest" ? "Dein Verein" : "Nächster Gegner") + "

" + + esc(world_->name(*(id == "crest" ? own : opponent))) + "

"; + if (id == "competition") + return heading("Nächste Begegnung") + + "
" + + crest(own, 80) + "

" + + esc(own ? world_->name(*own) : "") + + "

Freundschaftsspiel

19:00

Heim · " + "Samstag

" + + crest(opponent, 80) + + "

" + + esc(opponent ? world_->name(*opponent) : "") + "

"; + if (id == "warnings") { + const std::array names = { + "Aktiengewinn", "Kontostand", "Freie Werbeflächen", + "Sondertraining", "Erschöpfung", "Startaufstellung", + "Ersatzspieler", "Taktischer Einsatz", "Auslaufende Verträge", + "Lizenz"}; + const std::array icons = { + "chart", "coins", "shirt", "star", "heart", + "person", "person", "chart", "save", "check"}; + const std::array wide_members = {0, 1, 2, 3, 5, 7, 8, 9}; + const bool wide = h < 300; + const int columns = wide ? 8 : 5, count = wide ? 8 : 10; + std::string out = heading("Vereinsstatus"); + for (int i = 0; i < count; ++i) { + const int member = wide ? wide_members[size_t(i)] : i; + const int cell_w = (w - 52) / columns; + const int x = 26 + cell_w * (i % columns), + y = wide ? 90 : 95 + (i / columns) * 175; + out += "
" + + glyph(icons[size_t(member)], 36) + "
" + + (wide ? "" + : "

" + + std::string(names[size_t(member)]) + "

") + + "
"; + } + return out; + } + if (id == "trash") + return "
" + + glyph("trash", 100) + + "

Papierkorb

"; + if (id == "fans") + return heading("Fan-Stimmung") + + "

" + + std::to_string(s.state.value("fans", 67)) + " %

"; + if (id == "news") + return heading("Nachrichten") + + "

Willkommen zur " + "neuen Saison.

"; + if (id == "results") + return heading("Letzte sechs Spiele") + + "
––––––
"; + if (id == "own-summary" || id == "opponent-summary") + return heading(id == "own-summary" ? "Platz & Stärke · eigener Verein" + : "Platz & Stärke · Gegner") + + "
––
"; + const auto caption = id == "duels" ? "Direkter Vergleich" + : id == "comparison-curve" ? "Tabellenplätze · Vergleich" + : id == "own-curve" ? "Tabellenplatz · eigener Verein" + : "Tabellenplatz · Gegner"; + return heading(caption) + + "

Saisonvorbereitung

"; +} +std::string App::render_desktop() { + init_desktop(); + const auto s = snap(); + const auto *c = club(s); + std::string out = + "
" + + btn("desktop-context", + crest(c, 82) + "" + esc(c ? world_->name(*c) : "") + + "" + esc(manager(s).value("name", "")) + + "", + "identity") + + "
Saisonvorbereitung" + + esc(s.state.value("date", std::string())) + + "
Guthaben" + + cash(s.state.value("cash", int64_t(0))) + "
"; + for (const auto &[id, o] : desktop_["objects"].items()) { + if (!o.value("visible", false)) + continue; + const auto style = rect(o.value("x", 0), o.value("y", 0), o.value("w", 224), + o.value("h", 224)); + if (o.value("widget", false)) + out += "
" + + widget(id, o) + + (o.value("pinned", true) ? "
" : "") + + "
"; + else { + const auto route = id.substr(4); + out += ""; + } + } + return out; +} +std::string App::render_newgame() { + std::string body = "

Grundeinstellungen

Zuerst die " + "Partie, dann die Manager.

"; + const std::array keys = {"duration", "difficulty", "players", + "mode"}; + const std::array names = {"Spieldauer", "Schwierigkeit", + "Mitspieler", "Modus"}; + const std::array limits = { + 5, 10, start_options_.value("league", true) ? 4 : 1, 3}; + for (int i = 0; i < 4; ++i) { + const auto key = std::string(keys[size_t(i)]); + const int value = start_options_.value(key, 1), x = (i % 2) * 1320, + y = 120 + (i / 2) * 716; + std::string symbols, caption; + if (i == 0) { + symbols = "" + + std::string(value == 5 ? "∞" : std::to_string(value)) + + ""; + caption = value == 5 ? "Unbegrenzt" : value == 1 ? "Saison" : "Saisons"; + } else if (i == 1) { + symbols = "
"; + const int cols = std::min(value, 5); + for (int n = 0; n < value; ++n) + symbols += "
" + glyph("ball", 92) + "
"; + symbols += "
"; + caption = "Spielstärke " + std::to_string(value) + " von 10"; + } else if (i == 2) { + symbols = + "
"; + for (int n = 0; n < value; ++n) + symbols += glyph("person", 110); + symbols += "
"; + caption = std::to_string(value) + " Mitspieler"; + } else { + symbols = "" + + std::string(value == 1 ? "I" + : value == 2 ? "II" + : "III") + + ""; + caption = value == 1 ? "Grundfunktionen" + : value == 2 ? "Erweiterte Funktionen" + : "Alle Funktionen"; + } + body += "

" + names[size_t(i)] + + "

"; + body += + btn("setup-step", "−", {}, + "data-id=\"" + key + + "\" data-step=\"-1\" " + "style=\"width:94dp;height:124dp;padding:0;font-size:72dp;\" " + + (value == 1 ? "disabled" : "")); + body += "
" + + symbols + "

" + caption + "

"; + body += + btn("setup-step", "+", {}, + "data-id=\"" + key + + "\" data-step=\"1\" " + "style=\"width:94dp;height:124dp;padding:0;font-size:72dp;\" " + + (value == limits[size_t(i)] ? "disabled" : "")) + + "
"; + } + body += "
"; + for (const auto *key : {"league", "world"}) { + const bool league = std::string(key) == "league", + active = start_options_.value(key, true), + locked = active && + (league ? (start_options_.value("players", 1) > 1 || + !start_options_.value("world", true)) + : !start_options_.value("league", true)); + body += + btn("setup-competition", + glyph(league ? "pitch" : "world", 70) + "" + + (league ? "Ligaspiel" : "WM / EM") + "   " + + (active ? "Aktiv" : "Aus") + "", + active ? "primary row" : "row", + "data-id=\"" + std::string(key) + + "\" style=\"flex:1;height:126dp;justify-content:center;\" " + + (locked ? "disabled" : "")); + } + body += "

Mindestens " + "ein Wettbewerb bleibt aktiv.

" + + btn("close", "Abbrechen") + btn("setup-next", "Weiter", "primary") + + "
"; + return window("Neues Spiel", body); +} +std::string App::render_manager() { + const int limit = adding_manager_ ? 4 : start_options_.value("players", 1); + const auto used_club = [&](const std::string &id) { + return std::any_of( + managers_draft_.begin(), managers_draft_.end(), + [&](const auto &m) { return m.value("club", "") == id; }); + }; + const auto used_portrait = [&](int id) { + return std::any_of( + managers_draft_.begin(), managers_draft_.end(), + [&](const auto &m) { return m.value("portrait", 0) == id; }); + }; + const int portrait = + selections_["portrait"].empty() ? 0 : std::stoi(selections_["portrait"]); + const auto style = selections_["portrait-style"] == "painted" + ? "manager-painted." + : "manager."; + if (!world_->manageable(selected_club_) || used_club(selected_club_)) + for (auto *c : world_->clubs()) + if (world_->manageable(c->value("id", "")) && + !used_club(c->value("id", ""))) { + selected_club_ = c->value("id", ""); + break; + } + std::string body; + std::vector> countries; + std::set seen; + for (auto *r : world_->leagues()) { + const auto id = r->value("nation", ""); + if (seen.insert(id).second) + countries.emplace_back(id, world_->nation_name(id)); + } + auto leagues = world_->leagues(country_); + if (std::none_of(leagues.begin(), leagues.end(), + [&](auto *r) { return r->value("id", "") == league_; })) + league_ = leagues.empty() ? "" : leagues.front()->value("id", ""); + std::vector> choices; + for (auto *r : leagues) + choices.emplace_back(r->value("id", ""), world_->name(*r)); + if (manager_picker_) { + body = + "

Verein auswählen

" + + btn("manager-clubs-back", "Zurück") + + "
" + + select("manager-country", countries, country_, "manager-country") + + select("manager-league", choices, league_, "manager-league") + + "
"; + const auto clubs = world_->clubs(league_); + for (size_t i = 0; i < clubs.size(); ++i) { + const auto *c = clubs[i]; + const auto id = c->value("id", ""); + const bool locked = !world_->manageable(id), used = used_club(id); + const auto x = (i % 4) * 650, y = (i / 4) * 340; + body += + ""; + } + return window("Neuer Spieler", body + "
"); + } + const auto *c = world_->find("clubs", selected_club_); + body = "

Mitspieler " + std::to_string(manager_index_ + 1) + " von " + + std::to_string(limit) + + "

Dein Name. Dein " + "Verein. Dein Porträt.

"; + body += + "

So wirst du im Spiel " + "angesprochen.

Porträt " + + std::to_string(portrait + 1) + + "

" + + img(style + std::to_string(portrait), 174, 232, false, true, 320) + + "
"; + body += "

Verein

" + + btn("manager-clubs", + crest(c, 176) + + "
" + + esc(c ? world_->name(*c) : "") + + "" + + esc(c ? world_->name(*world_->find( + "competitions", c->value("competition", ""))) + : "") + + "Verein wählen ›
", + "row", + "style=\"margin-top:10dp;width:100%;height:230dp;background-" + "color:transparent;border-width:0;padding:0;text-align:left;\"") + + "
"; + body += + "

Startliga

" + + select("manager-country", countries, country_, "manager-country") + + select("manager-league", choices, league_, "manager-league") + + "

Vereinsstärke

" + + select("manager-strength", + {{"0", "Unteres Drittel"}, + {"1", "Mittelfeld"}, + {"2", "Oberes Drittel"}}, + selections_["manager-strength"].empty() + ? "1" + : selections_["manager-strength"], + "manager-strength") + + "
"; + body += "

Managerporträt

" + + btn("portrait-style", "Foto", + selections_["portrait-style"] != "painted" ? "primary" : "", + "data-id=\"photo\"") + + btn("portrait-style", "Illustration", + selections_["portrait-style"] == "painted" ? "primary" : "", + "data-id=\"painted\"") + + "
"; + for (int i = 0; i < 12; ++i) { + const int x = 26 + (i % 6) * 320, y = 100 + (i / 6) * 440; + const bool used = used_portrait(i); + body += ""; + } + body += "

Mitspieler dieser Partie

"; + for (size_t i = 0; i < managers_draft_.size(); ++i) { + const auto &m = managers_draft_[i]; + body += "
" + + img("manager." + std::to_string(m.value("portrait", 0)), 90, 120, + false, true, 180) + + "
Spieler " + std::to_string(i + 1) + + "

" + + esc(m.value("name", "")) + "

" + + esc(world_->name(*world_->find("clubs", m.value("club", "")))) + + "
"; + } + body += "

" + + std::to_string(limit - int(managers_draft_.size())) + + " weitere Plätze frei

" + + btn("manager-back", adding_manager_ ? "Abbrechen" : "Zurück") + + btn("manager-next", + adding_manager_ ? "Mitspieler hinzufügen" + : manager_index_ + 1 == limit ? "Spiel starten" + : "Mitspieler bestätigen", + "primary", + world_->manageable(selected_club_) && manager_index_ < limit + ? "" + : "disabled") + + "
"; + return window("Neuer Spieler", body); +} +std::string App::render_opening() { + const std::array names = {"UEFA-Cup", "Champions League", + "Europapokal der Pokalsieger"}; + const auto german = world_->clubs("comp:de-1"); + std::vector pool; + for (auto *l : world_->leagues("nation:de")) + for (auto *c : world_->clubs(l->value("id", ""))) + if (pool.size() < 64) + pool.push_back(c); + std::string body; + if (opening_page_ < 3) { + body = "

" + + std::string(names[size_t(opening_page_)]) + + "

Deutsche Teams " + "· Saison " + + esc(snap().state.value("date", std::string()).substr(0, 4)) + "

"; + const int count = opening_page_ == 0 ? 4 : 1; + for (int i = 0; i < count && size_t(i) < german.size(); ++i) { + const auto *c = german[size_t((i + opening_page_) % int(german.size()))]; + const bool single = count == 1; + const int x = single ? 704 : 150 + (i % 2) * 1178, + y = single ? 360 : 180 + (i / 2) * 730; + body += "
" + crest(c, single ? 620 : 360) + + "

" + + esc(world_->name(*c)) + "

"; + } + body += + "
" + + btn("opening-next", "Weiter", "primary", + "style=\"flex:none;width:390dp;\"") + + "
"; + } else { + const auto pair = [&](int index, int known, int size) { + const size_t a = size_t(index * 2), b = a + 1; + if (b >= pool.size()) + return std::string(); + const auto label_for = [&](const Json *c, bool home) { + return "" + + (home ? "" + esc(world_->name(*c)) + "" + + crest(c, size) + : crest(c, size) + "" + esc(world_->name(*c)) + + "") + + ""; + }; + return "
" + + std::to_string(index + 1) + "" + + (known > 0 ? label_for(pool[a], true) + : "Heim") + + "–" + + (known > 1 ? label_for(pool[b], false) + : "Noch nicht " + "gezogen") + + "
"; + }; + body = "

" + + std::string(opening_page_ == 3 ? "1. Runde" : "DFB-Pokal") + + "

" + + (opening_page_ == 3 ? "DFB-Pokal · Saison " : "1. Runde · Saison ") + + esc(snap().state.value("date", std::string()).substr(0, 4)) + "

"; + if (opening_page_ == 3) { + body += "" + + std::to_string(draw_revealed_) + + " / 64 Mannschaften
" + + img("art.cup-draw-v1.png", 2608, 850, false, false, 1800) + + "
"; + const int current = std::max(0, (draw_revealed_ - 1) / 2), + known = draw_revealed_ ? draw_revealed_ - current * 2 : 0; + body += "
" + + pair(current, known, 66) + "
"; + for (int i = std::max(0, current - 3); i < current; ++i) + body += + "
" + pair(i, 2, 42) + "
"; + body += "
" + + btn("opening-play", draw_playing_ ? "Pause" : "Fortsetzen", {}, + "style=\"flex:none;width:390dp;\"") + + btn("opening-all", "Alle Paarungen anzeigen", {}, + "style=\"flex:none;width:600dp;\"") + + "
"; + } else { + for (int column = 0; column < 2; ++column) { + body += "
"; + for (int row = 0; row < 16; ++row) + body += "
" + + pair(column * 16 + row, 2, 36) + "
"; + body += "
"; + } + body += "
" + + btn("opening-finish", "Weiter zum Desktop", "primary", + "style=\"flex:none;width:550dp;\"") + + "
"; + } + } + return window(opening_page_ < 3 ? "Deutsche Teams" : "DFB-Pokal", body, + false); +} +std::string App::render_table(bool strengths, bool indoor) { + auto leagues = world_->leagues(country_); + if (std::none_of(leagues.begin(), leagues.end(), + [&](auto *r) { return r->value("id", "") == league_; })) + league_ = leagues.empty() ? "" : leagues.front()->value("id", ""); + const auto clubs = world_->clubs(league_); + std::string body = "
" + + btn("table-sort", "Pl. / Verein", {}, "data-id=\"rank\"") + + "
"; + const std::vector headers = + strengths ? std::vector{"Tor", "Abwehr", "Mittelfeld", + "Sturm", "Gesamt"} + : std::vector{"Sp.", "S", "U", "N", + "Punkte", "Tore", "Diff."}; + for (const auto &h : headers) + body += "
" + + btn("table-sort", esc(h), {}, "data-id=\"" + esc(h) + "\"") + + "
"; + body += "
"; + for (size_t i = 0; i < clubs.size(); ++i) { + auto *c = clubs[i]; + body += "
" + + btn("club-detail", + "" + + std::to_string(i + 1) + "." + crest(c, 40) + + "" + esc(world_->name(*c)) + "", + {}, "data-id=\"" + esc(c->value("id", "")) + "\"") + + "
"; + if (strengths) { + const auto players = world_->squad(c->value("id", "")); + for (const auto &position : {"gk", "df", "mf", "fw", "all"}) { + int sum = 0, n = 0; + for (auto *p : players) { + const auto positions = p->value("positions", Json::array()); + if (std::string(position) == "all" || + std::find(positions.begin(), positions.end(), position) != + positions.end()) { + sum += p->value("attributes", Json::object()).value("strength", 0); + ++n; + } + } + body += "
" + + (n ? std::to_string(sum / n) : "–") + "
"; + } + } else + for (int n = 0; n < 7; ++n) + body += "
" + + std::string(n == 5 ? "0:0" : "0") + "
"; + body += "
"; + } + body += "
"; + if (!strengths && !indoor) + body += btn("table-overall", "Gesamt") + select("table-scope", + {{"all", "Alle Spiele"}, + {"first", "Hinrunde"}, + {"second", "Rückrunde"}, + {"home", "Heim"}, + {"away", "Auswärts"}}, + selections_["table-scope"], + "table-scope"); + std::vector> countries, league_rows; + std::set seen; + for (auto *l : world_->leagues()) { + const auto id = l->value("nation", ""); + if (seen.insert(id).second) + countries.emplace_back(id, world_->nation_name(id)); + if (id == country_) + league_rows.emplace_back(l->value("id", ""), world_->name(*l)); + } + body += select("table-country", countries, country_, "table-country") + + select("table-league", league_rows, league_, "table-league") + + "
"; + return body; +} +std::string App::render_camp() { + const auto index_file = + Json::parse(editor::read_file(gui_.root() / "gui-assets.json")); + const auto demo = index_file.at("demo"), camps = demo.at("training_camps"); + const auto s = snap(); + const auto id = s.state.at("camp").value("selected", std::string("resort:4")); + const Json *chosen = nullptr; + for (const auto &c : camps) + if (c.value("id", "") == id) + chosen = &c; + if (!chosen) + chosen = &camps.at(0); + auto region = selections_["camp-region"]; + if (region.empty()) + region = chosen->value("map", "map:eu"); + std::string body = "
"; + for (const auto &m : demo.at("maps")) + body += btn("camp-region", esc(m.value("name", "")), + m.value("id", "") == region ? "primary" : "", + "data-id=\"" + esc(m.value("id", "")) + "\""); + body += "
" + + img("map." + region.substr(4), 1440, 1603.2, false, false, 1600); + for (const auto &c : camps) + if (c.value("map", "") == region) { + const double x = c.value("x", 0) * 1.2, y = c.value("y", 0) * 1.2; + body += btn("camp-select", + "", + c.value("id", "") == id ? "primary" : "", + "data-id=\"" + esc(c.value("id", "")) + + "\" style=\"position:absolute;" + + rect(x - 34, y - 34, 68, 68) + + "padding:23dp;border-radius:34dp;\""); + } + body += "
<" + "div style=\"height:570dp;overflow:hidden;border-radius:24dp;\">" + + img(chosen->value("gui_image", ""), 1100, 570, false, true, 1400) + + "

" + + esc(chosen->value("name", "")) + + "

" + + esc(chosen->value("place", "")) + "

"; + const std::array qualities = { + "Platzqualität", "Fitnessgeräte", "Verpflegung", "Unterkunft"}; + for (size_t i = 0; i < 4; ++i) { + const int q = chosen->at("quality")[i].get(); + std::string stars; + for (int j = 0; j < q; ++j) + stars += glyph("star", 32); + body += "
" + + std::string(qualities[i]) + + "" + + stars + "
"; + } + body += "
Preis" + + cash(chosen->value("price", int64_t(0))) + "
"; + const std::array focus = {"Kondition", "Technik", "Spiel", + "Erholung"}; + const auto values = s.state.at("camp").at("focus"); + int sum = 0; + for (const auto &v : values) + sum += v.get(); + for (int i = 0; i < 4; ++i) { + const int value = i == 3 ? 15 - sum / 3 : values[size_t(i)].get(); + body += "
" + + std::to_string(value) + " / 15
"; + } + body += "
" + + btn("camp-remember", "Vormerken", "primary") + "
"; + return body; +} +std::string App::render_settings() { + if (draft_preferences_.is_null()) + draft_preferences_ = + source_ ? snap().state.at("preferences") + : Json{{"theme", theme_}, {"volume", 80}, {"effects", true}}; + std::string nav; + for (const auto &[key, label] : + std::vector>{ + {"display", "Anzeige"}, + {"sound", "Sound"}, + {"game", "Spiel"}, + {"automation", "Automatik"}}) { + if (scene_ == "main" && (key == "game" || key == "automation")) + continue; + nav += btn("settings-category", label, + settings_category_ == key ? "primary" : "", + "data-id=\"" + key + + "\" " + "style=\"display:block;width:100%;height:100dp;margin-" + "bottom:14dp;text-align:left;\""); + } + std::string pane = "

" + + std::string(settings_category_ == "display" ? "Anzeige" + : settings_category_ == "sound" ? "Sound" + : settings_category_ == "game" ? "Spiel" + : "Automatik") + + "

"; + if (settings_category_ == "display") { + pane += + "

Gestaltung

"; + for (const auto &[id, name] : + std::vector>{ + {"midnight", "Midnight Glass"}, + {"silver", "Silver Glass"}, + {"matchday", "Matchday"}}) + pane += + btn("settings-theme", + img("background", 520, 270, false, true, 650) + + "

" + name + "

", + std::string("choice ") + + (draft_preferences_.value("theme", theme_) == id ? "selected" + : ""), + "data-id=\"" + id + "\" style=\"width:570dp;padding:20dp;\""); + pane += + "

Bildschirm

" + + select("display-mode", + {{"window", "Fenster"}, {"fullscreen", "Vollbild"}}, + draft_preferences_.value("mode", "window")) + + "
" + + select("display-resolution", + {{"1280x720", "1280 × 720"}, + {"1920x1080", "1920 × 1080"}, + {"2560x1440", "2560 × 1440"}, + {"3840x2160", "3840 × 2160"}}, + draft_preferences_.value("resolution", "1920x1080")) + + "
" + + select("display-scale", + {{"auto", "Auto"}, {"1", "1×"}, {"1.5", "1,5×"}, {"2", "2×"}}, + draft_preferences_.value("scale", "auto")) + + "
"; + } else if (settings_category_ == "sound") + pane += + "
" + + std::to_string(draft_preferences_.value("volume", 80)) + + " %
" + + select("sound-style", {{"classic", "Klassisch"}, {"modern", "Modern"}}, + draft_preferences_.value("sound-style", "classic")) + + "
"; + else if (settings_category_ == "automation") { + pane += "
"; + for (const auto *name : + {"Aufstellung", "Auswechslungen", "Taktik", "Manndeckung", "Training"}) + pane += "
"; + } else + pane += + std::string( + "
"; + return "
" + + nav + + "
" + + pane + "
" + + btn("close", "Abbrechen") + + btn("settings-apply", "Anwenden", "primary") + "
"; +} +std::string App::render_save(bool save) { + const auto directory = user_dir() / "saves"; + std::string body = "
"; + if (save) + body += btn("save-new", "Neuer Speicherstand", "choice", + "style=\"width:100%;text-align:left;min-height:100dp;margin-" + "bottom:14dp;\""); + if (fs::exists(directory)) + for (const auto &file : fs::directory_iterator(directory)) + if (file.path().extension() == ".json") { + const auto name = editor::utf8(file.path().stem()); + body += btn("save-select", esc(name), + std::string("choice ") + + (selections_["save"] == name ? "selected" : ""), + "data-id=\"" + esc(name) + + "\" " + "style=\"width:100%;min-height:110dp;text-align:left;" + "margin-bottom:14dp;\""); + } + body += "

" + + esc(selections_["save"].empty() ? "Speicherstand auswählen" + : selections_["save"]) + + "

"; + const auto s = snap(); + body += + "
" + crest(club(s), 340) + + "
Saison" + + esc(s.state.value("date", std::string()).substr(0, 4)) + + "
SpieltagSaisonvorbereitung
Datum" + + esc(s.state.value("date", std::string())) + + "
Mitspieler" + + std::to_string(s.state.at("managers").size()) + "
"; + if (save && selections_["save"].empty()) + body += "
"; + return body + "
" + + btn("save-delete", "Löschen") + btn("save-rename", "Umbenennen") + + btn("close", "Abbrechen") + + btn(save ? "save-confirm" : "load-confirm", + save ? "Speichern" : "Laden", "primary") + + "
"; +} +std::string App::render_menu(const std::string &key) { + std::string body; + if (key == "tables" || key == "strengths") + body = render_table(key == "strengths", false); + else if (key == "camp") + body = render_camp(); + else if (key == "settings") + body = render_settings(); + else if (key == "save" || key == "load") + body = render_save(key == "save"); + else if (key == "widgets" || key == "view-save" || key == "view-load" || + key == "background") + body = render_desktop_tools(key); + else + throw editor::Error("Diese native Ansicht ist noch nicht verfügbar."); + return "
" + + window(title(key), body) + "
"; +} diff --git a/src/modern/ui/ticket_popover.cpp b/src/modern/ui/ticket_popover.cpp new file mode 100644 index 0000000..384b27a --- /dev/null +++ b/src/modern/ui/ticket_popover.cpp @@ -0,0 +1,392 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "modern/ui/ticket_popover.hpp" + +#include +#include +#include +#include +#include +#include +#include + +namespace bmh::modern_ui { +namespace { +std::string escaped(const std::string &value) { + std::string out; + for (char c : value) { + if (c == '&') + out += "&"; + else if (c == '<') + out += "<"; + else if (c == '>') + out += ">"; + else if (c == '"') + out += """; + else + out += c; + } + return out; +} +std::string px(float value) { + std::ostringstream out; + out.imbue(std::locale::classic()); + out << value << "px"; + return out.str(); +} +std::optional price(const Snapshot &snapshot) { + const auto it = snapshot.state.find("ticket"); + if (it == snapshot.state.end() || !it->is_number_integer()) + return {}; + const auto n = it->get(); + if (n < std::numeric_limits::min() || + n > std::numeric_limits::max()) + return {}; + return int(n); +} +std::string button(const char *action, const char *label, bool primary = false, + bool disabled = false) { + return ""; +} +bool inside(Rml::Element *node, Rml::Element *root) { + for (; node; node = node->GetParentNode()) + if (node == root) + return true; + return false; +} +} // namespace + +TicketPopover::TicketPopover(Rml::Context &context, + Rml::ElementDocument &document, DataSource &source, + std::function on_commit) + : context_(context), document_(document), source_(source), + on_commit_(std::move(on_commit)) { + auto layer = document_.CreateElement("div"); + layer->SetId("native-ticket-layer"); + layer->SetProperty("display", "none"); + layer_ = document_.AppendChild(std::move(layer)); + for (const char *type : {"click", "change", "input", "mousedown", "mouseup", + "mousemove", "contextmenu"}) + layer_->AddEventListener(type, this); + // Capture before the range widget's default key handler to avoid double + // steps. + layer_->AddEventListener("keydown", this, true); +} +TicketPopover::~TicketPopover() { + // The owner must destroy this editor before closing its document/context. + close(false); + if (layer_) + document_.RemoveChild(layer_); +} + +bool TicketPopover::open(Rml::Element *anchor, float device_pixel_ratio, + int min, int max, int step) { + close(false); + const auto snapshot = source_.snapshot(); + const auto current = price(snapshot); + const auto interval = int64_t(max) - min; + if (!anchor || anchor->GetOwnerDocument() != &document_ || + anchor->GetId().empty() || !anchor->IsVisible(true) || + !std::isfinite(device_pixel_ratio) || device_pixel_ratio <= 0 || + min > max || step <= 0 || interval % step != 0 || !current || + *current < min || *current > max || (int64_t(*current) - min) % step != 0) + return false; + anchor_id_ = anchor->GetId(); + revision_ = snapshot.revision; + world_ = snapshot.world; + original_ = value_ = *current; + min_ = min; + max_ = max; + step_ = step; + ratio_ = device_pixel_ratio; + review_ = false; + error_.clear(); + open_ = true; + layer_->SetProperty("display", "block"); + layer_->SetProperty("font-size", px(14.f * ratio_)); + render(); + return open_; +} +void TicketPopover::focus_opener() { + if (auto *anchor = document_.GetElementById(anchor_id_); + anchor && anchor->IsVisible(true)) + anchor->Focus(true); +} +void TicketPopover::close(bool restore_focus) { + if (!open_) + return; + open_ = false; + layer_->SetProperty("display", "none"); + layer_->SetInnerRML(""); + world_.reset(); + error_.clear(); + if (restore_focus) + focus_opener(); +} +bool TicketPopover::fresh() const { + const auto snapshot = source_.snapshot(); + return snapshot.revision == revision_ && snapshot.world == world_ && + price(snapshot) == original_; +} +void TicketPopover::resize(float device_pixel_ratio) { + if (!open_) + return; + if (!std::isfinite(device_pixel_ratio) || device_pixel_ratio <= 0) { + close(false); + return; + } + ratio_ = device_pixel_ratio; + layer_->SetProperty("font-size", px(14.f * ratio_)); + position(); +} +void TicketPopover::update() { + if (!open_) + return; + if (!fresh()) { + close(false); + return; + } + position(); + if (open_ && !inside(context_.GetFocusElement(), layer_)) { + if (auto *control = layer_->GetElementById(review_ ? "native-ticket-back" + : "native-ticket-range")) + control->Focus(true); + } +} +void TicketPopover::position() { + if (!open_) + return; + auto *anchor = document_.GetElementById(anchor_id_); + auto *panel = layer_->GetElementById("native-ticket-panel"); + if (!anchor || !anchor->IsVisible(true) || !panel) { + close(false); + return; + } + const auto viewport = context_.GetDimensions(); + const float margin = 8.f * ratio_, gap = 8.f * ratio_; + const float available_width = float(viewport.x) - 2 * margin; + const float available_height = float(viewport.y) - 2 * margin; + if (available_width <= 0 || available_height <= 0) { + close(false); + return; + } + panel->SetProperty("width", px(std::min(330.f * ratio_, available_width))); + panel->SetProperty("max-height", px(available_height)); + document_.UpdateDocument(); + const auto at = anchor->GetAbsoluteOffset(Rml::BoxArea::Border); + const auto size = anchor->GetBox().GetSize(Rml::BoxArea::Border); + const auto popup = panel->GetBox().GetSize(Rml::BoxArea::Border); + if (size.x <= 0 || size.y <= 0) { + close(false); + return; + } + const float below = float(viewport.y) - at.y - size.y - gap; + const float above = at.y - gap; + const bool down = below >= popup.y || below >= above; + const float left = + std::clamp(at.x + size.x - popup.x, margin, + std::max(margin, float(viewport.x) - popup.x - margin)); + const float top = + std::clamp(down ? at.y + size.y + gap : at.y - gap - popup.y, margin, + std::max(margin, float(viewport.y) - popup.y - margin)); + panel->SetProperty("left", px(left)); + panel->SetProperty("top", px(top)); + panel->SetAttribute("data-side", down ? "below" : "above"); +} +void TicketPopover::render(bool focus_range) { + const auto amount = std::to_string(value_); + std::string content = + "
" + "

Eintrittspreis

Aktuell: " + + std::to_string(original_) + " €
"; + if (review_) { + content += + "
" + + std::to_string(original_) + + " € " + + amount + " €
"; + } else { + content += "
" + + amount + + " €
" + "
" + + std::to_string(min_) + " €" + std::to_string(max_) + + " €
"; + } + if (!error_.empty()) + content += "

" + + escaped(error_) + "

"; + content += + "
" + button("cancel", "Abbrechen"); + if (review_) + content += "" + + button("confirm", "Bestätigen", true); + else + content += button("review", "Übernehmen", true, value_ == original_); + content += "
"; + layer_->SetInnerRML(content); + position(); + if (open_ && focus_range) { + if (auto *control = layer_->GetElementById(review_ ? "native-ticket-back" + : "native-ticket-range")) + control->Focus(true); + } +} +void TicketPopover::draft(int value) { + if (review_ || value < min_ || value > max_ || + (int64_t(value) - min_) % step_ != 0 || value == value_) + return; + value_ = value; + layer_->GetElementById("native-ticket-amount") + ->SetInnerRML(std::to_string(value_) + " €"); + auto *range = layer_->GetElementById("native-ticket-range"); + range->SetAttribute("aria-valuetext", std::to_string(value_) + " Euro"); + if (range->GetAttribute("value", value_) != value_) + range->SetAttribute("value", value_); + Rml::ElementList buttons; + layer_->GetElementsByTagName(buttons, "button"); + for (auto *node : buttons) + if (node->GetAttribute("data-ticket-action", "") == "review") + if (auto *control = dynamic_cast(node)) + control->SetDisabled(value_ == original_); +} +void TicketPopover::confirm() { + if (!fresh()) { + close(false); + return; + } + const auto result = source_.apply({revision_, "ticket", value_}); + if (!result.ok) { + if (!fresh()) { + close(false); + return; + } + error_ = result.error.empty() + ? "Der Eintrittspreis konnte nicht übernommen werden." + : result.error; + render(); + return; + } + close(); + if (on_commit_) + on_commit_(); +} +void TicketPopover::ProcessEvent(Rml::Event &event) { + if (!open_) + return; + const auto &type = event.GetType(); + auto *target = event.GetTargetElement(); + if (type == "keydown") { + const auto key = + Rml::Input::KeyIdentifier(event.GetParameter("key_identifier", 0)); + event.StopImmediatePropagation(); + if (key == Rml::Input::KI_ESCAPE) { + close(); + return; + } + if (key == Rml::Input::KI_TAB) { + Rml::ElementList controls; + layer_->QuerySelectorAll(controls, "input,button"); + controls.erase( + std::remove_if(controls.begin(), controls.end(), + [](auto *node) { + auto *control = + dynamic_cast(node); + return !node->IsVisible(true) || + (control && control->IsDisabled()); + }), + controls.end()); + if (controls.empty()) + return; + const auto current = std::find(controls.begin(), controls.end(), + context_.GetFocusElement()); + const bool backwards = event.GetParameter("shift_key", 0) != 0; + const int n = int(controls.size()), + old = current == controls.end() + ? (backwards ? 0 : -1) + : int(current - controls.begin()); + controls[size_t((old + (backwards ? -1 : 1) + n) % n)]->Focus(true); + return; + } + if (!review_ && target->GetId() == "native-ticket-range") { + const int64_t delta = + (key == Rml::Input::KI_LEFT || key == Rml::Input::KI_DOWN) + ? -int64_t(step_) + : int64_t(step_); + if (key == Rml::Input::KI_HOME) + draft(min_); + else if (key == Rml::Input::KI_END) + draft(max_); + else if (key == Rml::Input::KI_LEFT || key == Rml::Input::KI_RIGHT || + key == Rml::Input::KI_UP || key == Rml::Input::KI_DOWN) + draft(int( + std::clamp(int64_t(value_) + delta, int64_t(min_), int64_t(max_)))); + return; + } + if (key != Rml::Input::KI_RETURN && key != Rml::Input::KI_NUMPADENTER && + key != Rml::Input::KI_SPACE) + return; + } else { + // Leave slider default mouse handling intact, but never bubble into desktop + // drag/actions. + event.StopPropagation(); + if (type == "change" || type == "input") { + if (!review_ && target->GetId() == "native-ticket-range") { + const auto raw = event.GetParameter( + "value", std::numeric_limits::quiet_NaN()); + if (std::isfinite(raw) && raw >= min_ && raw <= max_) { + const auto n = std::llround(raw); + if (std::abs(raw - double(n)) < 1e-4) + draft(int(n)); + } + } + return; + } + if (type != "click") + return; + if (target == layer_) { + close(); + return; + } + } + if (!fresh()) { + close(false); + return; + } + for (auto *node = target; node && node != layer_; + node = node->GetParentNode()) { + const auto action = + node->GetAttribute("data-ticket-action", ""); + if (action.empty()) + continue; + if (auto *control = dynamic_cast(node); + control && control->IsDisabled()) + return; + if (action == "cancel") + close(); + else if (action == "back") { + review_ = false; + error_.clear(); + render(); + } else if (action == "review" && value_ != original_) { + review_ = true; + error_.clear(); + render(); + } else if (action == "confirm" && review_) + confirm(); + return; + } +} +} // namespace bmh::modern_ui diff --git a/src/modern/ui/ticket_popover.hpp b/src/modern/ui/ticket_popover.hpp new file mode 100644 index 0000000..fda867a --- /dev/null +++ b/src/modern/ui/ticket_popover.hpp @@ -0,0 +1,56 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once + +#include "modern/ui/model.hpp" +#include +#include +#include +#include +#include + +namespace Rml { +class Context; +class Element; +class ElementDocument; +} // namespace Rml + +namespace bmh::modern_ui { +// A presentation-only editor. Default bounds describe the demo, not engine +// rules. +class TicketPopover final : public Rml::EventListener { +public: + TicketPopover(Rml::Context &, Rml::ElementDocument &, DataSource &, + std::function on_commit); + ~TicketPopover() override; + TicketPopover(const TicketPopover &) = delete; + TicketPopover &operator=(const TicketPopover &) = delete; + + bool open(Rml::Element *anchor, float device_pixel_ratio, int min = 0, + int max = 25, int step = 1); + void close(bool restore_focus = true); + void resize(float device_pixel_ratio); + void update(); + bool is_open() const { return open_; } + void ProcessEvent(Rml::Event &) override; + +private: + void render(bool focus_range = true); + void position(); + void draft(int value); + void confirm(); + void focus_opener(); + bool fresh() const; + + Rml::Context &context_; + Rml::ElementDocument &document_; + DataSource &source_; + std::function on_commit_; + Rml::Element *layer_ = nullptr; + std::string anchor_id_, error_; + std::shared_ptr world_; + uint64_t revision_ = 0; + float ratio_ = 1.f; + int original_ = 0, value_ = 0, min_ = 0, max_ = 25, step_ = 1; + bool open_ = false, review_ = false; +}; +} // namespace bmh::modern_ui diff --git a/src/modern/ui/view.cpp b/src/modern/ui/view.cpp new file mode 100644 index 0000000..7f4b46a --- /dev/null +++ b/src/modern/ui/view.cpp @@ -0,0 +1,859 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "modern/ui/view.hpp" +#include "content/package.hpp" +#include "launch/game_data.hpp" +#include "launch/process.hpp" +#include "launch/rml_path.hpp" +#include "launch/rml_video.hpp" +#include "modern/ui/desktop.hpp" +#include "modern/ui/gui_assets.hpp" +#include "modern/ui/model.hpp" +#include "modern/ui/ticket_popover.hpp" +#include "version.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace bmh::modern_ui { +namespace { +std::string esc(std::string_view value) { return editor::escaped(value); } +std::string scalar(double n) { + std::ostringstream s; + s.imbue(std::locale::classic()); + s << n; + return s.str(); +} +std::string rect(double x, double y, double w, double h) { + return "left:" + scalar(x) + "dp;top:" + scalar(y) + "dp;width:" + scalar(w) + + "dp;height:" + scalar(h) + "dp;"; +} +std::string btn(const std::string &action, const std::string &label, + const std::string &css = {}, const std::string &attrs = {}) { + return ""; +} +const std::array routes = { + "tables", "league", "strengths", "lineup", "achievements", + "other", "friendlies", "postpone", "calendar", "indoor", + "load", "save", "kickoff", "toto", "bank", + "camp", "training", "transfer", "tactics", "settings", + "scorers", "advertising", "stadium", "statistics", "environment", + "fairplay", "highscore", "contracts", "balance", "newplayer", + "news"}; +const std::array titles = {"Tabellen", + "Ligaspiele", + "Stärken", + "Aufstellung", + "Erfolge", + "Übrige Spiele", + "Freundschaftsspiele", + "Verlegen", + "Kalender", + "Hallentabellen", + "Laden", + "Speichern", + "Anstoß", + "TOTO", + "Bank", + "Trainingslager", + "Training", + "Transfermarkt", + "Taktik", + "Einstellungen", + "Spielerstatistiken", + "Werbung", + "Stadion", + "Statistiken", + "Umfeld", + "Fairplay", + "Highscore", + "Verträge", + "Bilanz", + "Neuer Spieler", + "Nachrichten"}; +std::string title(const std::string &route) { + const auto i = std::find(routes.begin(), routes.end(), route); + if (i != routes.end()) + return titles[size_t(i - routes.begin())]; + if (route == "newgame") + return "Neues Spiel"; + if (route == "mods") + return "Mod"; + if (route == "opening") + return "Saisonvorbereitung"; + return "OpenBMH"; +} +struct Picture { + std::string token; + int width = 1, height = 1; +}; +class Renderer final : public rml::Renderer { + GuiAssets &gui_; + fs::path assets_; + std::shared_ptr world_; + struct Entry { + std::string key; + bool world; + int pixels; + editor::images::Raster raster; + }; + std::map entries_; + std::map keys_; + size_t serial_ = 0; + +public: + Renderer(rml::Video &video, GuiAssets &gui, fs::path assets) + : rml::Renderer(video), gui_(gui), assets_(std::move(assets)) {} + Picture local_image(const fs::path &file, int pixels) { + const auto identity = + editor::utf8(file) + ":" + + std::to_string(fs::last_write_time(file).time_since_epoch().count()); + if (!keys_.contains(identity)) { + auto raster = editor::images::decode( + editor::read_file(file), editor::utf8(file.extension()), pixels); + const auto token = "modern-image-" + std::to_string(serial_++) + ".png"; + entries_[token] = {identity, false, pixels, std::move(raster)}; + keys_[identity] = token; + } + const auto token = keys_.at(identity); + const auto &r = entries_.at(token).raster; + return {token, r.width, r.height}; + } + void world(std::shared_ptr value) { + Rml::ReleaseTextures(this); + entries_.clear(); + keys_.clear(); + world_ = std::move(value); + } + Picture image(const std::string &key, bool world = false, int pixels = 512) { + const auto identity = + (world ? "world:" : "gui:") + key + ":" + std::to_string(pixels); + auto found = keys_.find(identity); + if (found == keys_.end()) { + auto token = "modern-image-" + std::to_string(serial_++) + ".png"; + editor::images::Raster raster; + if (world) { + if (!world_) + return {}; + const auto bytes = world_->asset(key, pixels); + if (bytes.first.empty()) + return {}; + raster = editor::images::decode(bytes.first, bytes.second, pixels); + } else if (key.starts_with("icon.")) { + const auto name = key.substr(5); + if (name.empty() || + name.find_first_not_of("abcdefghijklmnopqrstuvwxyz-") != name.npos) + return {}; + raster = editor::images::decode( + editor::read_file(assets_ / "icons" / (name + ".svg")), ".svg", + pixels); + } else if (gui_.contains(key)) + raster = gui_.decode(key, pixels); + else if (key == "background") + raster = editor::images::decode( + editor::read_file(assets_.parent_path() / "launcher" / + "stadium.tga"), + ".tga", pixels); + else + return {}; + // Decode at source fidelity, then bound GPU storage to the requested + // display detail. + const auto largest = std::max(raster.width, raster.height); + if (largest > pixels) { + const double scale = double(pixels) / largest; + editor::images::Raster small{ + std::max(1, int(std::round(raster.width * scale))), + std::max(1, int(std::round(raster.height * scale))), + {}}; + small.pixels.resize(size_t(small.width) * small.height * 4); + SDL_Surface *source = SDL_CreateRGBSurfaceWithFormatFrom( + raster.pixels.data(), raster.width, raster.height, 32, + raster.width * 4, SDL_PIXELFORMAT_RGBA32); + SDL_Surface *destination = SDL_CreateRGBSurfaceWithFormatFrom( + small.pixels.data(), small.width, small.height, 32, small.width * 4, + SDL_PIXELFORMAT_RGBA32); + if (!source || !destination) { + if (source) + SDL_FreeSurface(source); + if (destination) + SDL_FreeSurface(destination); + throw std::runtime_error(SDL_GetError()); + } + SDL_SetSurfaceBlendMode(source, SDL_BLENDMODE_NONE); + SDL_BlitScaled(source, nullptr, destination, nullptr); + SDL_FreeSurface(source); + SDL_FreeSurface(destination); + raster = std::move(small); + } + entries_[token] = {key, world, pixels, std::move(raster)}; + keys_[identity] = token; + found = keys_.find(identity); + } + const auto &r = entries_.at(found->second).raster; + return {found->second, r.width, r.height}; + } + Rml::TextureHandle LoadTexture(Rml::Vector2i &dimensions, + const Rml::String &source) override { + const auto token = editor::utf8(editor::path(source).filename()); + auto found = entries_.find(token); + if (found == entries_.end()) + return rml::Renderer::LoadTexture(dimensions, source); + auto pixels = found->second.raster.pixels; + for (size_t i = 0; i < pixels.size(); i += 4) + for (int c = 0; c < 3; ++c) + pixels[i + c] = + uint8_t((unsigned(pixels[i + c]) * pixels[i + 3] + 127) / 255); + dimensions = {found->second.raster.width, found->second.raster.height}; + return GenerateTexture(pixels, dimensions); + } +}; +struct Mod { + std::string name, type, error; + fs::path file; + Json manifest; +}; +class App final : public Rml::EventListener { + fs::path executable_, root_, assets_, gui_root_; + launch::SaveMigrator migrate_; + Config config_; + GuiAssets gui_; + rml::Video video_; + rml::AssetFiles files_; + SystemInterface_SDL system_; + Renderer renderer_; + TextInputMethodEditor_SDL ime_; + Rml::Context *context_ = nullptr; + Rml::ElementDocument *doc_ = nullptr; + bool initialized_ = false, closed_ = false, dirty_ = true, + needs_render_ = true; + double scale_ = 1, canvas_left_ = 0, canvas_top_ = 0; + std::string scene_ = "main", menu_, theme_ = "midnight", active_mod_, + selected_mod_, notice_, country_ = "nation:de", league_, + selected_club_; + std::vector mods_; + std::shared_ptr world_; + std::unique_ptr source_; + std::unique_ptr ticket_; + bool focus_ticket_ = false; + float device_ratio_ = 1.f; + Json desktop_ = Json::object(), saved_desktop_ = Json::object(), + options_ = Json::object(); + Json managers_draft_ = Json::array(), + start_options_ = {{"duration", 5}, {"difficulty", 3}, {"players", 1}, + {"mode", 3}, {"league", true}, {"world", true}}; + int manager_index_ = 0; + bool manager_picker_ = false, adding_manager_ = false; + struct Drag { + bool active = false, moved = false; + std::string id; + float x = 0, y = 0; + double left = 0, top = 0; + }; + Drag drag_; + bool suppress_click_ = false; + std::vector undo_; + std::function confirm_; + std::string popup_, rendered_popup_; + bool rendered_confirm_ = false; + std::string popup_input_, popup_extra_, popup_accept_ = "Bestätigen"; + bool popup_has_input_ = false, quit_after_save_ = false; + std::function text_accept_; + bool context_open_ = false, context_dirty_ = false; + std::string context_id_; + int context_x_ = 0, context_y_ = 0; + int opening_page_ = 0, draw_revealed_ = 0; + bool draw_playing_ = true; + uint64_t draw_at_ = 0; + std::string settings_category_ = "display"; + Json draft_preferences_; + std::map selections_; + Rml::Element *element(const std::string &id) const { + return doc_->GetElementById(id); + } + std::string field(const std::string &id) const { + auto *p = dynamic_cast(element(id)); + return p ? p->GetValue() : ""; + } + Snapshot snap() const { return source_->snapshot(); } + const Json &manager(const Snapshot &s) const { + return s.state.at("managers").at(0); + } + const Json *club(const Snapshot &s) const { + return s.world->find("clubs", manager(s).value("club", "")); + } + std::string cash(int64_t value) const { + return money(value, + world_ ? world_->manifest().value("currency", Json::object()) + : Json::object()); + } + fs::path user_dir() const { + const auto id = world_ ? world_->manifest().value("id", std::string("none")) + : std::string("none"); + return root_ / "userdata" / "ui-demo" / content::sha256(id); + } + std::string img(const std::string &key, double w, double h, + bool world = false, bool cover = false, int pixels = 512) { + const auto p = renderer_.image(key, world, pixels); + if (p.token.empty()) + return "
"; + double iw = w, ih = h; + std::string crop; + if (cover) { + const auto a = double(p.width) / p.height, b = w / h; + double x = 0, y = 0, sw = p.width, sh = p.height; + if (a > b) { + sw = sh * b; + x = (p.width - sw) / 2; + } else { + sh = sw / b; + y = (p.height - sh) / 2; + } + crop = " rect=\"" + scalar(x) + " " + scalar(y) + " " + scalar(sw) + " " + + scalar(sh) + "\""; + } else { + const auto factor = std::min(w / p.width, h / p.height); + iw = p.width * factor; + ih = p.height * factor; + } + return "
"; + } + std::string crest(const Json *c, double size) { + return c ? img(c->value("crest", ""), size, size, true) : ""; + } + std::string glyph(const std::string &name, double size) { + return img("icon." + name, size, size, false, false, int(size)); + } + std::string label(const Json *c, double size = 40) { + return c ? "" + crest(c, size) + "" + + esc(world_->name(*c)) + "" + : ""; + } + std::string window(const std::string &heading, const std::string &content, + bool close = true) { + return "
" + + (close ? btn("close", "×", "close") + : "") + + "

" + esc(heading) + "

" + + content + "
"; + } + std::string + select(const std::string &id, + const std::vector> &rows, + const std::string &value, const std::string &action = {}) { + std::string out = + ""; + } + bool apply(const std::string &kind, const Json &value) { + const auto r = source_->apply({source_->snapshot().revision, kind, value}); + if (!r.ok) { + message("Die Eingabe konnte nicht übernommen werden: " + r.error); + return false; + } + return true; + } + void reset_popup() { + popup_has_input_ = false; + popup_input_.clear(); + popup_extra_.clear(); + popup_accept_ = "Bestätigen"; + text_accept_ = {}; + rendered_popup_.clear(); + } + void message(const std::string &text) { + reset_popup(); + popup_ = text; + confirm_ = {}; + dirty_ = true; + } + void confirmation(const std::string &text, std::function accepted) { + reset_popup(); + popup_ = text; + confirm_ = std::move(accepted); + dirty_ = true; + } + void text_dialog(const std::string &text, const std::string &initial, + std::function accepted) { + confirmation(text, {}); + popup_has_input_ = true; + popup_input_ = initial; + text_accept_ = std::move(accepted); + dirty_ = true; + } + void refresh() { + needs_render_ = true; + dirty_ = true; + } + void collect_mods() { + mods_.clear(); + const auto folder = root_ / "mods"; + if (!fs::exists(folder)) + return; + for (const auto &entry : fs::directory_iterator(folder)) { + if (!entry.is_directory() || entry.is_symlink() || + editor::utf8(entry.path().filename()).starts_with('.')) + continue; + Mod m{editor::utf8(entry.path().filename()), + "", + {}, + entry.path() / "content.obw", + {}}; + try { + auto store = editor::ArchiveStore::open(m.file); + m.manifest = Json::parse(store->read("manifest.json")); + m.type = Catalog::modern_manifest(m.manifest) ? "Modern" : "Classic"; + } catch (const std::exception &e) { + m.error = e.what(); + m.type = "Unbekannt"; + } + mods_.push_back(std::move(m)); + } + std::sort(mods_.begin(), mods_.end(), + [](const auto &a, const auto &b) { return a.name < b.name; }); + } + Mod *mod(const std::string &name) { + for (auto &m : mods_) + if (m.name == name) + return &m; + return nullptr; + } + void load_world(const fs::path &file) { + auto next = Catalog::open(file); + auto demo = std::make_unique(next); + ticket_.reset(); + renderer_.world(next); + world_ = std::move(next); + source_ = std::move(demo); + desktop_ = Json::object(); + ticket_ = + std::make_unique(*context_, *doc_, *source_, [this] { + focus_ticket_ = true; + refresh(); + }); + league_ = world_->leagues("nation:de").empty() + ? "" + : world_->leagues("nation:de").front()->value("id", ""); + selected_club_ = manager(snap()).value("club", ""); + } + std::string main_menu() { + const auto *m = mod(active_mod_); + std::string out = + "

FUSSBALLMANAGER

OpenBMH

"; + const std::array, 6> actions = { + {{"new", "Neues Spiel"}, + {"load", "Spiel laden"}, + {"network", "Netzwerk"}, + {"mods", "Mod"}, + {"settings", "Einstellungen"}, + {"exit", "Beenden"}}}; + for (const auto &[key, name] : actions) + out += btn( + key, esc(name) + (key == "network" ? "Demnächst" : ""), + {}, + key == "network" || (key == "new" && !m && !world_) ? "disabled" + : ""); + out += + "
Aktive Mod

" + + esc(m ? m->name + : world_ ? world_->title() + : "Keine Mod aktiviert") + + "

v" + std::string(kOpenBmhVersion) + + (m && m->type == "Classic" ? "" : " · Modern UI Demo") + + "
"; + return out; + } + std::string mods_page() { + if (selected_mod_.empty() && !mods_.empty()) + selected_mod_ = mods_.front().name; + std::string left = "

Installierte Mods

"; + for (const auto &m : mods_) + left += btn( + "mod-select", + "" + esc(m.name) + "" + + esc(m.type) + "", + std::string("row choice ") + + (m.name == selected_mod_ ? "selected" : ""), + "data-id=\"" + esc(m.name) + + "\" style=\"width:100%;margin-bottom:12dp;min-height:120dp;\""); + left += "
"; + std::string right; + if (auto *m = mod(selected_mod_)) + right = + "
" + + img("background", 1300, 400, false, true, 1600) + "

" + + esc(m->name) + "

" + esc(m->type) + + (m->type == "Modern" ? " · Oberfläche bis zum Anstoß" : "") + + "

" + esc(m->error) + "

" + + btn("mod-activate", m->name == active_mod_ ? "Aktiv" : "Aktivieren", + "primary", m->name == active_mod_ ? "disabled" : "") + + "
"; + return window( + "Mod", + "
" + + left + "
" + right + + "
" + + btn("import-modern", "OBW-Paket hinzufügen") + + btn("import-classic", "BMH / Football Limited") + + btn("mod-rename", "Umbenennen") + btn("mod-remove", "Löschen") + + "
"); + } + std::string render_desktop(); + void init_desktop(); + std::string widget(const std::string &, const Json &); + std::string render_table(bool strengths = false, bool indoor = false); + std::string render_camp(); + std::string render_settings(); + std::string render_save(bool save); + std::string render_desktop_tools(const std::string &); + void render_context(); + void context_menu(const std::string &id, int x, int y); + void drag_event(Rml::Event &); + std::string render_newgame(); + std::string render_manager(); + std::string render_opening(); + std::string render_menu(const std::string &); + void dispatch(const std::string &, Rml::Element *); + void change(Rml::Element *); + void input(Rml::Element *); + void resize() { + int w, h, pw, ph; + SDL_GetWindowSize(video_.window, &w, &h); + video_.drawable_size(pw, ph); + if (w <= 0 || h <= 0 || pw <= 0 || ph <= 0) + return; + scale_ = std::min(double(pw) / 3840, double(ph) / 2160); + canvas_left_ = (pw - 3840 * scale_) / 2; + canvas_top_ = (ph - 2160 * scale_) / 2; + device_ratio_ = float(pw) / w; + renderer_.SetViewport(pw, ph); + context_->SetDimensions({pw, ph}); + context_->SetDensityIndependentPixelRatio(float(scale_)); + element("canvas")->SetProperty("left", scalar(canvas_left_) + "px"); + element("canvas")->SetProperty("top", scalar(canvas_top_) + "px"); + if (ticket_) + ticket_->resize(device_ratio_); + dirty_ = true; + } + void render() { + if (ticket_) + ticket_->close(false); + context_open_ = false; + context_dirty_ = true; + doc_->SetClassNames(theme_); + std::string markup; + if (scene_ == "main") + markup = main_menu(); + else if (scene_ == "mods") + markup = mods_page(); + else if (scene_ == "newgame") + markup = render_newgame(); + else if (scene_ == "manager") + markup = render_manager(); + else if (scene_ == "opening") + markup = render_opening(); + else if (source_) + markup = render_desktop(); + if (!menu_.empty()) + markup += render_menu(menu_); + element("canvas")->SetInnerRML(markup); + const auto size = context_->GetDimensions(); + const auto background = + img("background", size.x / scale_, size.y / scale_, false, true, 2048); + element("background")->SetInnerRML(background); + element("background") + ->SetProperty("filter", scene_ == "main" ? "none" + : theme_ == "silver" + ? "saturate(0.2) brightness(0.9)" + : theme_ == "matchday" + ? "saturate(0.13) brightness(0.56)" + : "saturate(0.34) brightness(0.70)"); + needs_render_ = false; + dirty_ = true; + if (focus_ticket_) { + if (auto *n = element("desktop-ticket")) + n->Focus(); + focus_ticket_ = false; + } + } + void render_popup() { + if (popup_.empty()) { + element("popup")->SetClass("visible", false); + rendered_popup_.clear(); + return; + } + element("popup")->SetClass("visible", true); + if (popup_ == rendered_popup_ && bool(confirm_) == rendered_confirm_) + return; + element("popup")->SetInnerRML( + "

OpenBMH

" + + esc(popup_) + "

" + + (popup_has_input_ + ? "" + : "") + + "
" + + btn("popup-close", + confirm_ || text_accept_ ? "Abbrechen" : "Verstanden") + + popup_extra_ + + ((confirm_ || text_accept_) + ? btn("popup-confirm", popup_accept_, "primary") + : "") + + "
"); + rendered_popup_ = popup_; + rendered_confirm_ = bool(confirm_); + if (auto *button = element("popup")->QuerySelector("button")) + button->Focus(); + } + void frame() { + if (ticket_) + ticket_->update(); + if (needs_render_) + render(); + render_popup(); + render_context(); + context_->Update(); + renderer_.Clear(); + renderer_.BeginFrame(); + context_->Render(); + renderer_.EndFrame(); + video_.present(); + dirty_ = false; + } + void screenshot(const fs::path &file) { + frame(); + int w, h; + auto bytes = video_.capture(w, h); + fs::create_directories(file.parent_path()); + editor::write_atomic(file, + editor::images::encode_png({w, h, std::move(bytes)})); + } + void load_fonts() { + bool regular = false, bold = false; +#ifdef _WIN32 + const char *base = std::getenv("WINDIR"); + if (base) { + const auto folder = fs::path(base) / "Fonts"; + regular = Rml::LoadFontFace(rml::asset_path(folder / "segoeui.ttf"), + "Modern", Rml::Style::FontStyle::Normal, + Rml::Style::FontWeight::Normal); + bold = Rml::LoadFontFace(rml::asset_path(folder / "segoeuib.ttf"), + "Modern", Rml::Style::FontStyle::Normal, + Rml::Style::FontWeight::Bold); + } +#elif defined(__APPLE__) + const fs::path system = "/System/Library/Fonts/SFNS.ttf"; + if (fs::exists(system)) { + regular = Rml::LoadFontFace(rml::asset_path(system), "Modern", + Rml::Style::FontStyle::Normal, + Rml::Style::FontWeight::Normal); + bold = Rml::LoadFontFace(rml::asset_path(system), "Modern", + Rml::Style::FontStyle::Normal, + Rml::Style::FontWeight::Bold); + } +#else + const fs::path fonts = fs::exists("/usr/share/fonts/truetype/liberation2") + ? "/usr/share/fonts/truetype/liberation2" + : "/usr/share/fonts/truetype/liberation"; + if (fs::exists(fonts)) { + regular = Rml::LoadFontFace( + rml::asset_path(fonts / "LiberationSans-Regular.ttf"), "Modern", + Rml::Style::FontStyle::Normal, Rml::Style::FontWeight::Normal); + bold = Rml::LoadFontFace( + rml::asset_path(fonts / "LiberationSans-Bold.ttf"), "Modern", + Rml::Style::FontStyle::Normal, Rml::Style::FontWeight::Bold); + } +#endif + if (!regular) + regular = Rml::LoadFontFace( + rml::asset_path(assets_ / "LatoLatin-Regular.ttf"), "Modern", + Rml::Style::FontStyle::Normal, Rml::Style::FontWeight::Normal); + if (!bold) + bold = Rml::LoadFontFace(rml::asset_path(assets_ / "LatoLatin-Bold.ttf"), + "Modern", Rml::Style::FontStyle::Normal, + Rml::Style::FontWeight::Bold); + if (!regular || !bold) + throw std::runtime_error( + "GUI-Schriften fehlen. Bitte das vollständige Paket entpacken."); + } + void script(); + +public: + App(fs::path executable, launch::SaveMigrator migrate, Config config) + : executable_(std::move(executable)), root_(executable_.parent_path()), + assets_(root_ / "assets" / "modern"), + gui_root_(config.gui_assets.empty() ? assets_ / "gui" + : config.gui_assets), + migrate_(std::move(migrate)), config_(std::move(config)), + gui_(gui_root_), + video_("OpenBMH", config_.width, config_.height, 960, 540), + system_(video_.window), renderer_(video_, gui_, assets_) { + try { + Rml::SetSystemInterface(&system_); + Rml::SetFileInterface(&files_); + Rml::SetRenderInterface(&renderer_); + Rml::SetTextInputHandler(&ime_); + initialized_ = Rml::Initialise(); + if (!initialized_) + throw std::runtime_error("RmlUI initialization failed"); + load_fonts(); + context_ = + Rml::CreateContext("modern-ui", {config_.width, config_.height}); + if (!context_) + throw std::runtime_error("Modern UI context failed"); + doc_ = context_->LoadDocument(rml::asset_path(assets_ / "modern.rml")); + if (!doc_) + throw std::runtime_error("Modern UI layout missing"); + for (const char *event : + {"click", "dblclick", "change", "input", "keydown", "mousedown", + "mouseup", "mousemove", "contextmenu"}) + doc_->AddEventListener(event, this); + if(!config_.theme.empty())theme_ = config_.theme; + if(theme_!="midnight"&&theme_!="silver"&&theme_!="matchday")throw editor::Error("Unbekanntes Modern-Theme."); + collect_mods(); + if (!mods_.empty()) + active_mod_ = mods_.front().name; + if (!config_.world.empty()) { + load_world(config_.world); + scene_ = config_.scene; + if (scene_ != "main" && scene_ != "newgame" && scene_ != "manager" && + scene_ != "opening" && scene_ != "desktop") { + menu_ = scene_; + scene_ = "desktop"; + } + } + if (!config_.state.empty() && source_) { + desktop_ = source_->load(config_.state); + saved_desktop_ = desktop_; + if(config_.theme.empty())theme_ = snap().state.at("preferences").value("theme", theme_); + } + if(source_&&!config_.theme.empty()){ + auto preferences=snap().state.at("preferences");preferences["theme"]=theme_;apply("preferences",preferences); + } + if (scene_ == "manager" && selections_["manager-name"].empty()) + selections_["manager-name"] = "Alex Berger"; + doc_->Show(); + resize(); + render(); + SDL_ShowWindow(video_.window); + frame(); + } catch (...) { + shutdown(); + throw; + } + } + void shutdown() { + ticket_.reset(); + if (doc_) { + doc_->Close(); + doc_ = nullptr; + } + if (context_) { + const auto name = context_->GetName(); + context_ = nullptr; + Rml::RemoveContext(name); + } + if (initialized_) { + Rml::Shutdown(); + initialized_ = false; + } + } + ~App() { shutdown(); } + void ProcessEvent(Rml::Event &event) override; + int run() { + if (!config_.commands.empty()) + script(); + if (!config_.screenshot.empty()) { + screenshot(config_.screenshot); + return 0; + } + while (!closed_) { + if (scene_ == "opening" && opening_page_ == 3 && draw_revealed_ < 64 && + draw_playing_ && SDL_GetTicks64() >= draw_at_ && + (SDL_GetWindowFlags(video_.window) & SDL_WINDOW_INPUT_FOCUS)) { + ++draw_revealed_; + draw_at_ = SDL_GetTicks64() + 900; + if (draw_revealed_ == 64) + opening_page_ = 4; + refresh(); + } + if (needs_render_ || dirty_) + frame(); + SDL_Event event; + const auto timeout = + int(std::clamp(context_->GetNextUpdateDelay(), 0.0, .2) * 1000); + bool got = SDL_WaitEventTimeout(&event, timeout) != 0; + while (got) { + if (event.type == SDL_QUIT) { + if (source_ && scene_ != "main") { + dispatch("context-quit", nullptr); + } else + closed_ = true; + } else { + if (event.type == SDL_WINDOWEVENT) + resize(); + int w, h, pw, ph; + SDL_GetWindowSize(video_.window, &w, &h); + video_.drawable_size(pw, ph); + if (w > 0 && h > 0) { + if (event.type == SDL_MOUSEMOTION) { + event.motion.x = int(double(event.motion.x) * pw / w); + event.motion.y = int(double(event.motion.y) * ph / h); + } + if (event.type == SDL_MOUSEBUTTONDOWN || + event.type == SDL_MOUSEBUTTONUP) { + event.button.x = int(double(event.button.x) * pw / w); + event.button.y = int(double(event.button.y) * ph / h); + context_->ProcessMouseMove(event.button.x, event.button.y, + RmlSDL::GetKeyModifierState()); + } + } + RmlSDL::InputEventHandler(context_, video_.window, event); + dirty_ = true; + } + got = SDL_PollEvent(&event) != 0; + } + if (context_->GetNextUpdateDelay() <= 0) + dirty_ = true; + } + return 0; + } +}; +#include "modern/ui/controls.inc" +#include "modern/ui/desktop_screens.inc" +#include "modern/ui/screens.inc" +} // namespace +bool is_modern_world(const fs::path &file) { + try { + auto store = editor::ArchiveStore::open(file); + return Catalog::modern_manifest(Json::parse(store->read("manifest.json"))); + } catch (const std::exception &) { + return false; + } +} +int run(const fs::path &executable, const launch::SaveMigrator &migrate, + const Config &config) { + App app(executable, migrate, config); + return app.run(); +} +} // namespace bmh::modern_ui diff --git a/src/modern/ui/view.hpp b/src/modern/ui/view.hpp new file mode 100644 index 0000000..24f8b36 --- /dev/null +++ b/src/modern/ui/view.hpp @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +#include "launch/mods.hpp" + +namespace bmh::modern_ui { +struct Config { + std::filesystem::path world, gui_assets, screenshot, commands, state; + std::string scene = "main", theme; + int width = 1280, height = 720; +}; +// Returns before Classic initialization. The demonstration never starts a +// match. +int run(const std::filesystem::path &executable, const launch::SaveMigrator &, + const Config &); +bool is_modern_world(const std::filesystem::path &); +} // namespace bmh::modern_ui diff --git a/tests/modern_ticket_document_tests.cpp b/tests/modern_ticket_document_tests.cpp new file mode 100644 index 0000000..167c77f --- /dev/null +++ b/tests/modern_ticket_document_tests.cpp @@ -0,0 +1,201 @@ +// SPDX-License-Identifier: GPL-3.0-only +// Synthetic document test; no original content or window server required. +#include "modern/ui/ticket_popover.hpp" +#include +#include +#include +#define CHECK(value) \ + do { \ + if (!(value)) \ + throw std::runtime_error("Check failed: " #value); \ + } while (false) +#include +#include +#include +#include +using namespace bmh::modern_ui; +struct NullRenderer final : Rml::RenderInterface { + Rml::CompiledGeometryHandle CompileGeometry(Rml::Span, + Rml::Span) override { + return 1; + } + void RenderGeometry(Rml::CompiledGeometryHandle, Rml::Vector2f, + Rml::TextureHandle) override {} + void ReleaseGeometry(Rml::CompiledGeometryHandle) override {} + Rml::TextureHandle LoadTexture(Rml::Vector2i &, + const Rml::String &) override { + return 0; + } + Rml::TextureHandle GenerateTexture(Rml::Span, + Rml::Vector2i) override { + return 1; + } + void ReleaseTexture(Rml::TextureHandle) override {} + void EnableScissorRegion(bool) override {} + void SetScissorRegion(Rml::Rectanglei) override {} +}; +struct Fake final : DataSource { + Snapshot s{1, {}, {{"ticket", 13}}}; + bool fail = false; + int applies = 0; + Snapshot snapshot() const override { return s; } + ActionResult apply(const Action &a) override { + ++applies; + CHECK(a.kind == "ticket" && a.revision == s.revision); + if (fail) + return {false, s.revision, "Speicher voll. Bitte erneut versuchen."}; + s.state["ticket"] = a.value; + return {true, ++s.revision, {}}; + } +}; +struct Spy final : Rml::EventListener { + int count = 0; + void ProcessEvent(Rml::Event &e) override { + ++count; + std::cerr << "LEAK " << e.GetType() << " " << e.GetTargetElement()->GetId() + << "\n"; + } +}; +int main(int argc, char **argv) try { + CHECK(argc >= 2); + const auto assets = std::filesystem::path(argv[1]); + const std::string theme_name = argc > 2 ? argv[2] : "midnight"; + NullRenderer renderer; + Rml::SystemInterface system; + Rml::SetRenderInterface(&renderer); + Rml::SetSystemInterface(&system); + CHECK(Rml::Initialise()); + CHECK(Rml::LoadFontFace((assets / "LatoLatin-Regular.ttf").string(), "Modern", + Rml::Style::FontStyle::Normal, + Rml::Style::FontWeight::Normal)); + CHECK(Rml::LoadFontFace((assets / "LatoLatin-Bold.ttf").string(), "Modern", + Rml::Style::FontStyle::Normal, + Rml::Style::FontWeight::Bold)); + auto *context = Rml::CreateContext("ticket-fixture", {1280, 720}); + CHECK(context); + context->SetDensityIndependentPixelRatio(1.f / 3); + std::ifstream theme(assets / "theme.rcss"), ticket(assets / "ticket.rcss"); + std::ostringstream css; + css << theme.rdbuf() << ticket.rdbuf(); + auto *doc = context->LoadDocumentFromMemory( + ""); + CHECK(doc); + doc->Show(); + context->Update(); + Fake source; + int commits = 0; + Spy spy; + doc->AddEventListener("click", &spy); + doc->AddEventListener("keydown", &spy); + { + TicketPopover popup(*context, *doc, source, [&] { ++commits; }); + auto *anchor = doc->GetElementById("desktop-ticket"); + auto node = [&](const char *id) { + auto *n = doc->GetElementById(id); + CHECK(n); + return n; + }; + auto key = [&](Rml::Input::KeyIdentifier k) { + Rml::Dictionary p; + p["key_identifier"] = int(k); + node("native-ticket-range")->DispatchEvent("keydown", p); + context->Update(); + popup.update(); + }; + auto click = [&](const char *action) { + Rml::ElementList all; + node("native-ticket-layer") + ->QuerySelectorAll(all, std::string("[data-ticket-action=\"") + + action + "\"]"); + CHECK(all.size() == 1); + all[0]->DispatchEvent("click", {}); + context->Update(); + popup.update(); + }; + auto geometry = [&](float ratio) { + context->Update(); + popup.update(); + context->Update(); + auto *p = node("native-ticket-panel"); + const auto b = p->GetBox().GetSize(Rml::BoxArea::Border); + const auto at = p->GetAbsoluteOffset(Rml::BoxArea::Border); + std::cerr << "geometry " << b.x << " " << b.y << " at " << at.x << " " + << at.y << " font " << p->GetComputedValues().font_size() + << "\n"; + CHECK(std::abs(b.x - 330 * ratio) < 1); + CHECK(std::abs(b.y - 196 * ratio) < 1); + CHECK(std::abs( + node("native-ticket-range")->GetComputedValues().font_size() - + 14 * ratio) < .1); + CHECK(at.x >= 8 * ratio - 1 && at.y >= 8 * ratio - 1); + }; + CHECK(popup.open(anchor, 1)); + geometry(1); + CHECK(source.applies == 0); + key(Rml::Input::KI_END); + CHECK(node("native-ticket-range")->GetAttribute("value", -1) == 25); + CHECK(source.s.state["ticket"] == 13); + CHECK(spy.count == 0); + click("review"); + CHECK(source.applies == 0); + CHECK(node("native-ticket-panel")->GetInnerRML().find("13 €") != + std::string::npos); + click("back"); + key(Rml::Input::KI_HOME); + key(Rml::Input::KI_RIGHT); + CHECK(node("native-ticket-range")->GetAttribute("value", -1) == 1); + click("review"); + source.fail = true; + click("confirm"); + CHECK(popup.is_open() && source.s.state["ticket"] == 13 && commits == 0); + CHECK(node("native-ticket-error")->GetInnerRML().find("Speicher") != + std::string::npos); + source.fail = false; + click("confirm"); + CHECK(!popup.is_open() && source.s.state["ticket"] == 1 && commits == 1); + CHECK(context->GetFocusElement() == anchor); + CHECK(spy.count == 0); + CHECK(popup.open(anchor, 1)); + key(Rml::Input::KI_END); + key(Rml::Input::KI_ESCAPE); + CHECK(!popup.is_open() && source.s.state["ticket"] == 1); + CHECK(popup.open(anchor, 1)); + node("native-ticket-layer")->DispatchEvent("click", {}); + CHECK(!popup.is_open()); + CHECK(popup.open(anchor, 1)); + source.s.revision++; + popup.update(); + CHECK(!popup.is_open()); + context->SetDimensions({2560, 1440}); + context->SetDensityIndependentPixelRatio(2.f / 3); + CHECK(popup.open(anchor, 2)); + geometry(2); + popup.close(); + context->SetDimensions({1280, 720}); + context->SetDensityIndependentPixelRatio(1.f / 3); + anchor->SetProperty("left", "1190px"); + anchor->SetProperty("top", "650px"); + context->Update(); + CHECK(popup.open(anchor, 1)); + geometry(1); + CHECK(node("native-ticket-panel") + ->GetAttribute("data-side", "") == "above"); + auto at = + node("native-ticket-panel")->GetAbsoluteOffset(Rml::BoxArea::Border); + CHECK(at.x + 330 <= 1273); + popup.close(); + CHECK(!popup.open(anchor, 1, 2, 25, 2)); + CHECK(!popup.is_open()); + } + doc->Close(); + Rml::RemoveContext("ticket-fixture"); + Rml::Shutdown(); + std::cout << "PASS native ticket fixture\n"; +} catch (const std::exception &e) { + std::cerr << e.what() << "\n"; + return 1; +} diff --git a/tests/modern_ui_core_tests.cpp b/tests/modern_ui_core_tests.cpp new file mode 100644 index 0000000..865d774 --- /dev/null +++ b/tests/modern_ui_core_tests.cpp @@ -0,0 +1,186 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "modern/ui/desktop.hpp" +#include "modern/ui/gui_assets.hpp" +#include "modern/ui/model.hpp" +#include +#include +#include + +using namespace bmh::modern_ui; +namespace { +void require(bool value, const char *message) { + if (!value) + throw std::runtime_error(message); +} +void write(const fs::path &root, const std::string &file, const Json &value) { + fs::create_directories((root / file).parent_path()); + bmh::editor::write_atomic(root / file, value.dump()); +} +void table(const fs::path &root, const std::string &name, const Json &rows) { + write(root, + name == "assets" ? "assets/index.json" : "world/" + name + ".json", + {{"schema", name + "@1.0"}, {"items", rows}}); +} +} // namespace +int main(int argc, char **argv) try { + if (argc == 2) { + auto catalog = Catalog::open(bmh::editor::path(argv[1])); + const auto before = catalog->summary(); + DemoSource demo(catalog); + require(!demo.apply({0, "kickoff", {}}).ok, + "Demo must never expose kickoff"); + require(demo.snapshot().revision == 0, "Rejected action changed revision"); + require(catalog->summary() == before, "UI modified its world"); + std::cout << before.dump(2) << '\n'; + return 0; + } + const auto root = + fs::temp_directory_path() / + ("openbmh-modern-ui-" + + std::to_string( + std::chrono::steady_clock::now().time_since_epoch().count())); + struct Cleanup { + fs::path p; + ~Cleanup() { + std::error_code ec; + fs::remove_all(p, ec); + } + } cleanup{root}; + fs::create_directories(root); + write(root, "manifest.json", + {{"format", "openbmh-world"}, + {"kind", "world"}, + {"format_version", "1.1"}, + {"id", "world:synthetic-ui"}, + {"title", {{"default", "Synthetic UI world"}}}, + {"requires", {"editor:world-v1"}}, + {"x-editor", {{"profile", "editor-world-v1"}, {"playable", false}}}}); + table(root, "nations", + Json::array({{{"id", "nation:de"}, {"name", "Testland"}}, + {{"id", "nation:other"}, {"name", "Otherland"}}})); + table(root, "competitions", + Json::array({{{"id", "comp:home"}, + {"name", "Home league"}, + {"type", "league"}, + {"nation", "nation:de"}}, + {{"id", "comp:other"}, + {"name", "Other league"}, + {"type", "league"}, + {"nation", "nation:other"}}})); + table(root, "clubs", + Json::array({{{"id", "club:a"}, + {"name", "Test A"}, + {"nation", "nation:de"}, + {"competition", "comp:home"}}, + {{"id", "club:b"}, + {"name", "Test B"}, + {"nation", "nation:other"}, + {"competition", "comp:other"}}})); + table(root, "players", + Json::array({{{"id", "player:a"}, + {"name", {{"first", "Alex"}, {"last", "Example"}}}, + {"team", "club:a"}, + {"squad_order", 1}}, + {{"id", "player:b"}, + {"name", {{"first", "Robin"}, {"last", "Sample"}}}, + {"team", "club:a"}, + {"squad_order", 0}}})); + bmh::editor::write_atomic(root / "small.txt", "low resolution"); + bmh::editor::write_atomic(root / "vector.svg", "vector artwork"); + table(root, "assets", + Json::array( + {{{"key", "asset:club/a/crest"}, + {"files", {{"native", "small.txt"}, {"svg", "vector.svg"}}}}})); + const auto original = bmh::editor::read_file(root / "manifest.json"); + auto world = Catalog::open(root); + require(world->manageable("club:a") && !world->manageable("club:b"), + "Foreign management policy"); + require(world->clubs("comp:other").size() == 1, + "Foreign clubs must remain visible"); + require(world->squad("club:a").front()->at("id") == "player:b", + "Squad order must come from OBW"); + require(world->name(world->rows("players")[0]) == "Alex Example", + "Split names were not presented"); + require(world->asset("asset:club/a/crest").first == "vector artwork", + "Low-resolution native image overrides SVG"); + require(number(-1234567) == "-1.234.567", "Integer presentation"); + require(money(-1, {{"minor_units", 2}, {"code", "EUR"}}) == "-0,01 €", + "Minor currency units"); + DemoSource source(world); + const auto before = source.snapshot(); + require(!source + .apply({0, "managers", + Json::array({{{"name", "Pat"}, {"club", "club:b"}}})}) + .ok, + "Foreign club was selectable"); + require(source.snapshot().state == before.state && + source.snapshot().revision == 0, + "Rejected action mutated state"); + require(source.apply({0, "ticket", 17}).ok && source.dirty(), + "Accepted draft action"); + require(!source.apply({0, "ticket", 18}).ok && + source.snapshot().state["ticket"] == 17, + "Stale revision mutated state"); + require(!source.apply({1, "kickoff", {}}).ok, "Kickoff became available"); + require(!source.apply({1, "ticket", 26}).ok, + "Invalid demo ticket was accepted"); + const auto save = root / "demo.ui.json"; + auto layout = default_desktop(); + require(valid_desktop(layout), "Default desktop must validate"); + auto moved = layout; + require(!place_desktop_object(moved, "account", 3000, 1500) && + moved == layout, + "Pinned widget moved"); + moved["objects"]["account"]["pinned"] = false; + require(resize_desktop_widget(moved, "account", 4, 1), + "Approved 4x1 account size failed"); + require(valid_desktop(moved), "Resize produced invalid desktop"); + const auto resized = moved; + require(!resize_desktop_widget(moved, "account", 3, 7) && moved == resized, + "Invalid widget size mutated layout"); + auto corrupt = layout; + corrupt["objects"]["calendar"]["x"] = 999999; + require(!valid_desktop(corrupt), "Out of bounds desktop accepted"); + source.save(save, layout); + require(!source.dirty(), "Saved demo remains dirty"); + require(source.apply({1, "ticket", 21}).ok, "Second action"); + const auto desktop = source.load(save); + require(source.snapshot().state["ticket"] == 17 && desktop == layout, + "Demo restoration"); + require(bmh::editor::read_file(root / "manifest.json") == original, + "Demo altered the OBW source"); + auto bad = Json::parse(bmh::editor::read_file(save)); + bad["world"] = "world:different"; + write(root, "bad.ui.json", bad); + const auto accepted = source.snapshot(); + bool rejected = false; + try { + source.load(root / "bad.ui.json"); + } catch (const std::exception &) { + rejected = true; + } + require(rejected && source.snapshot().state == accepted.state && + source.snapshot().revision == accepted.revision, + "Failed load changed the session"); + bad = Json::parse(bmh::editor::read_file(save)); + bad["desktop"] = corrupt; + write(root, "bad-layout.ui.json", bad); + rejected = false; + try { + source.load(root / "bad-layout.ui.json"); + } catch (const std::exception &) { + rejected = true; + } + require(rejected && source.snapshot().state == accepted.state && + source.snapshot().revision == accepted.revision, + "Invalid desktop partially restored demo"); + GuiAssets absent(root / "missing-gui"); + require(!absent.available(), + "World resources were mistaken for GUI resources"); + std::cout << "Modern UI catalogue, asset priority, ownership, revision and " + "demo-save checks passed\n"; + return 0; +} catch (const std::exception &e) { + std::cerr << e.what() << '\n'; + return 1; +} diff --git a/tools/modern_ui/prepare_gui_assets.py b/tools/modern_ui/prepare_gui_assets.py new file mode 100644 index 0000000..7078c29 --- /dev/null +++ b/tools/modern_ui/prepare_gui_assets.py @@ -0,0 +1,109 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-3.0-only +"""Prepare a separate private GUI resource directory from the approved HTML mockup. + +Never modifies the source study or an OBW world. Original reference directories, +club catalogues and player databases are not copied into the GUI resource set. +""" +import argparse +import ast +import hashlib +import json +import math +from pathlib import Path +import re +import shutil +import subprocess + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--mockup', type=Path, required=True) + parser.add_argument('--output', type=Path, required=True) + args = parser.parse_args() + source = args.mockup.resolve(strict=True) + output = args.output.resolve() + if output == source or source in output.parents or output in source.parents: + parser.error('Source and output must be independent directories.') + output.mkdir(parents=True, exist_ok=True) + items = {} + + def add(key, relative, crop=None): + path = (source / relative).resolve(strict=True) + if not path.is_relative_to(source): + raise ValueError('GUI source escapes the supplied mockup directory.') + relative = path.relative_to(source).as_posix() + destination = output / relative + if not destination.resolve().is_relative_to(output): + raise ValueError("GUI output escapes the supplied output directory.") + destination.parent.mkdir(parents=True, exist_ok=True) + if not destination.exists() or destination.read_bytes() != path.read_bytes(): + shutil.copyfile(path, destination) + item = {'file': relative, 'sha256': hashlib.sha256(path.read_bytes()).hexdigest()} + if crop: + item['crop'] = crop + items[key] = item + + add('background', 'assets/vendor/stadium-night.png') + data = (source / 'desktop/assets.js').read_text() + buttons = json.loads(data[data.index('{'):data.rfind('}') + 1])['buttons'] + routes = ['tables', 'league', 'strengths', 'lineup', 'achievements', 'other', + 'friendlies', 'postpone', 'calendar', 'indoor', 'load', 'save', + 'kickoff', 'toto', 'bank', 'camp', 'training', 'transfer', 'tactics', + 'settings', 'scorers', 'advertising', 'stadium', 'statistics', + 'environment', 'fairplay', 'highscore', 'contracts', 'balance', 'newplayer'] + for route, button in zip(routes, buttons, strict=True): + add('button.' + route, button['src'].removeprefix('../')) + add('button.news', 'assets/vector/desktop-news.svg') + for i in range(12): + add('manager.' + str(i), 'assets/studies/submenus/manager-portraits-photo-v1.png', + [(i % 4) / 4, (i // 4) / 3, 1 / 4, 1 / 3]) + add('manager-painted.' + str(i), 'assets/studies/submenus/manager-portraits-v1.png', + [(i % 4) / 4, (i // 4) / 3, 1 / 4, 1 / 3]) + for folder in ['assets/studies/submenus', 'assets/vector']: + for path in sorted((source / folder).rglob('*')): + if path.is_file() and path.suffix.lower() in ('.png', '.svg', '.jpg', '.webp'): + add('art.' + path.relative_to(source / folder).as_posix(), path.relative_to(source).as_posix()) + map_source = (source / 'desktop/camp-map-data.js').read_text() + maps = json.loads(re.search(r'Object.freeze\((.*)\);', map_source).group(1)) + regions = {'germany': 'de', 'europe': 'eu', 'gulf': 'me'} + map_rows = [] + for key, value in maps.items(): + add('map.' + regions[key], value['file']) + map_rows.append({'id': 'map:' + regions[key], 'name': value['label'], + 'width': value['view_box'][2], 'height': value['view_box'][3]}) + camp_source = (source / 'desktop/camp-menu.js').read_text() + block = re.search(r'const resorts=\[(.*?)\n\];', camp_source, re.S).group(1) + camps = ast.literal_eval('[' + re.sub(r'\b(\w+):', r'"\1":', block) + ']') + camp_rows = [] + for index, camp in enumerate(camps): + crop = None + if 'image' in camp: + image = camp['image'] + elif camp['region'] == 'gulf': + image = 'camp-gulf-resort-v1.png' + else: + photo = camp['photo'] + image = 'camp-resorts-a-v1.png' if photo < 4 else 'camp-resorts-b-v2.png' + cell = photo % 4 + crop = [(cell % 2) / 2, (cell // 2) / 2, .5, .5] + add('camp.' + str(index), 'assets/studies/submenus/' + image, crop) + projection = maps[camp['region']]['project'] + x = (projection['ox'] + (math.radians(camp['lon']) - projection['xmin']) * projection['scale']) + y = projection['oy'] + (projection['ymax'] - math.log(math.tan(math.pi / 4 + math.radians(camp['lat']) / 2))) * projection['scale'] + camp_rows.append({'id': 'resort:' + str(index), 'name': camp['name'], 'place': camp['city'], + 'map': 'map:' + regions[camp['region']], 'x': round(x), 'y': round(y), + 'quality': camp['quality'], 'price': camp['price'], 'gui_image': 'camp.' + str(index)}) + try: + revision = subprocess.check_output(['git', '-C', str(source), 'rev-parse', 'HEAD'], text=True).strip() + except subprocess.CalledProcessError: + revision = 'unversioned' + document = {'schema': 'openbmh-gui-assets@1', 'source_revision': revision, + 'distribution': 'private-reference-assets', 'items': items, + 'demo': {'maps': map_rows, 'training_camps': camp_rows}} + (output / 'gui-assets.json').write_text(json.dumps(document, ensure_ascii=False, indent=2) + '\n') + print(f'Prepared {len(items)} GUI entries, {len(map_rows)} maps and {len(camp_rows)} demo camps.') + + +if __name__ == '__main__': + main()