Integrate native OBW editor and three submenu themes (by Codex)
# Conflicts: # tools/public_release/check_public_tree.py
No files matched your search
@@ -0,0 +1,76 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-only
|
||||
name: OBW Editor POC
|
||||
on:
|
||||
push:
|
||||
branches: [feat/obw-editor-poc]
|
||||
workflow_dispatch:
|
||||
permissions:
|
||||
contents: read
|
||||
concurrency:
|
||||
group: obw-editor-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
jobs:
|
||||
editor:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- runner: ubuntu-24.04
|
||||
platform: linux-x64
|
||||
- runner: windows-2022
|
||||
platform: windows-x64
|
||||
- runner: macos-14
|
||||
platform: macos-arm64
|
||||
runs-on: ${{ matrix.runner }}
|
||||
timeout-minutes: 45
|
||||
steps:
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd
|
||||
with:
|
||||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
- name: Check public sources
|
||||
run: python3 tools/public_release/check_public_tree.py --root . --history --revision HEAD
|
||||
- name: Existing package boundaries
|
||||
if: runner.os == 'Linux'
|
||||
run: python3 tests/package_tests.py
|
||||
- name: Linux dependencies
|
||||
if: runner.os == 'Linux'
|
||||
run: sudo apt-get update && sudo apt-get install -y ninja-build pkg-config libgtk-3-dev libx11-dev libxext-dev libxrandr-dev libxcursor-dev libxi-dev libxfixes-dev libxss-dev libgl1-mesa-dev xvfb xauth xdotool
|
||||
- name: MSVC x64
|
||||
if: runner.os == 'Windows'
|
||||
uses: ilammy/msvc-dev-cmd@a102174a2b586eec2ea151a69e6fd14404a8ce7c
|
||||
with:
|
||||
arch: x64
|
||||
- name: Configure
|
||||
shell: bash
|
||||
run: |
|
||||
args=()
|
||||
if [[ "$RUNNER_OS" == "macOS" ]]; then args+=(-DCMAKE_OSX_ARCHITECTURES=arm64 -DCMAKE_OSX_DEPLOYMENT_TARGET=11.0); fi
|
||||
cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release -DOPENBMH_BUILD_EDITOR=ON -DBMH_DATA= "${args[@]}"
|
||||
- name: Build editor and synthetic tests
|
||||
run: cmake --build build --target openbmh_editor editor_core_tests --parallel 2
|
||||
- name: Native editor core and MCP tests
|
||||
run: ctest --test-dir build -C Release -R ^editor_core_tests$ --output-on-failure --output-junit editor-tests.xml
|
||||
- name: Linux native GUI smoke
|
||||
if: runner.os == 'Linux'
|
||||
run: |
|
||||
xvfb-run -a -s '-screen 0 1600x1000x24' python3 tests/editor_gui_smoke.py build/OpenBMHEditor
|
||||
xvfb-run -a -s '-screen 0 1600x1000x24' build/OpenBMHEditor --demo --page players --settings build/test-options.json --screenshot build/editor.png --quit-after-ms 1800
|
||||
- name: Package editor
|
||||
shell: bash
|
||||
run: |
|
||||
args=()
|
||||
if [[ "$RUNNER_OS" == "Linux" ]]; then args+=(--source-package); fi
|
||||
python3 tools/package/make_editor_package.py --build build --out dist --platform ${{ matrix.platform }} "${args[@]}"
|
||||
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02
|
||||
with:
|
||||
name: OpenBMHEditor-${{ matrix.platform }}
|
||||
path: dist/*.zip
|
||||
if-no-files-found: error
|
||||
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02
|
||||
if: always()
|
||||
with:
|
||||
name: editor-checks-${{ matrix.platform }}
|
||||
path: |
|
||||
build/editor-tests.xml
|
||||
build/editor.png
|
||||
@@ -326,6 +326,10 @@ endif()
|
||||
|
||||
add_subdirectory(src/ui)
|
||||
add_subdirectory(src/import)
|
||||
option(OPENBMH_BUILD_EDITOR "Build the standalone OBW editor proof of concept" OFF)
|
||||
if(OPENBMH_BUILD_EDITOR)
|
||||
add_subdirectory(src/editor)
|
||||
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)
|
||||
@@ -1064,12 +1068,15 @@ bmh_add_data_test(NAME sportschau_app_tests REQUIRED_OPTIONS BMH_TEST_SPORTSCHAU
|
||||
install(TARGETS openbmh_play openbmh_cli RUNTIME DESTINATION . COMPONENT Runtime)
|
||||
install(FILES README.md LICENSE THIRD_PARTY_NOTICES.md ACKNOWLEDGEMENTS.md CONTRIBUTING.md
|
||||
DESTINATION . COMPONENT Runtime)
|
||||
install(DIRECTORY docs/ DESTINATION docs COMPONENT Runtime)
|
||||
install(DIRECTORY docs/ DESTINATION docs COMPONENT Runtime PATTERN "qa" EXCLUDE)
|
||||
if(MSVC)
|
||||
set(CMAKE_INSTALL_SYSTEM_RUNTIME_DESTINATION .)
|
||||
set(CMAKE_INSTALL_SYSTEM_RUNTIME_COMPONENT Runtime)
|
||||
set(CMAKE_INSTALL_UCRT_LIBRARIES TRUE)
|
||||
include(InstallRequiredSystemLibraries)
|
||||
if(OPENBMH_BUILD_EDITOR)
|
||||
install(PROGRAMS ${CMAKE_INSTALL_SYSTEM_RUNTIME_LIBS} DESTINATION . COMPONENT Editor)
|
||||
endif()
|
||||
endif()
|
||||
|
||||
add_executable(tax_animation_unit_tests tests/tax_animation_unit_tests.cpp)
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
# OpenBMH
|
||||
|
||||
The separate experimental [OBW Editor POC](docs/EDITOR.md) uses native RmlUI,
|
||||
supports German/English, image editing and a local MCP server. Enable it with
|
||||
`-DOPENBMH_BUILD_EDITOR=ON`; edited worlds are independent of the Classic runtime.
|
||||
|
||||
A modern and faithful open source rebuild of the *Bundesliga Manager Hattrick* engine.
|
||||
|
||||
OpenBMH is a standalone C++20 engine with an SDL2 interface for *Bundesliga Manager Hattrick* (1994/95) and its English edition, *Football Limited*. The project develops a playable reconstruction alongside a platform for new rules, content and interfaces. Keeping the familiar game enjoyable and making it easier to extend are equally important goals.
|
||||
|
||||
@@ -13,6 +13,13 @@ OpenBMH's own code and documentation use GPL-3.0-only. This does not replace the
|
||||
| [RmlUi](https://github.com/mikke89/RmlUi/tree/6.3) | 6.3, Core and SDL2/OpenGL backend | MIT | [RmlUi.txt](docs/licenses/RmlUi.txt), [containers](docs/licenses/RmlUi-containers.txt), [Khronos notice](docs/licenses/RmlUi-Khronos.txt) |
|
||||
| [FreeType](https://github.com/freetype/freetype/tree/VER-2-13-3) | 2.13.3 | FreeType License (FTL) | [license choices](docs/licenses/FreeType.txt), [FTL](docs/licenses/FreeType-FTL.txt), [BDF](docs/licenses/FreeType-BDF.txt), [PCF](docs/licenses/FreeType-PCF.txt), [internal gzip/zlib](docs/licenses/FreeType-zlib.txt) |
|
||||
| LatoLatin Regular and Bold | Unmodified fonts included with RmlUi 6.3 | SIL Open Font License 1.1 | [font notices](docs/licenses/RmlUi-fonts.txt) |
|
||||
| nlohmann/json (optional editor) | 3.12.0 | MIT | [notice](docs/licenses/nlohmann-json.txt) |
|
||||
| cpp-httplib (optional editor) | 0.63.0, local HTTP without TLS | MIT | [notice](docs/licenses/cpp-httplib.txt) |
|
||||
| SDL2_image (optional editor) | 2.8.8, selected static codecs | zlib | [notice](docs/licenses/SDL2_image.txt) |
|
||||
| stb_image (SDL2_image PNG/JPEG decoder) | Version supplied by SDL2_image 2.8.8 | MIT option | [verbatim alternatives](docs/licenses/stb-image.txt) |
|
||||
| libwebp (optional editor) | SDL2_image's pinned `1.0.3-SDL` fork, commit `05b15cb8`, including upstream backported fixes | BSD-3-Clause and patent grant | [license](docs/licenses/libwebp.txt), [patents](docs/licenses/libwebp-PATENTS.txt) |
|
||||
| LunaSVG / bundled PlutoVG (optional editor) | LunaSVG 3.5.0 and its tracked PlutoVG sources | MIT | [LunaSVG](docs/licenses/LunaSVG.txt), [PlutoVG](docs/licenses/PlutoVG.txt) |
|
||||
| pugixml (optional editor) | 1.15 | MIT | [notice](docs/licenses/pugixml.txt) |
|
||||
| [Nuked OPL3](https://github.com/nukeykt/Nuked-OPL3/tree/765ec962e473aeb767e4cba74ffdc8f588ffbfe8) | Commit `765ec962e473aeb767e4cba74ffdc8f588ffbfe8` | LGPL-2.1-or-later | [LGPL-2.1.txt](docs/licenses/LGPL-2.1.txt), [copyright and source notice](docs/licenses/Nuked-OPL3-notices.txt) |
|
||||
|
||||
The miniz implementation provides a zlib-compatible API; it is not the zlib library. FreeType's internal gzip module includes its bundled zlib code; an external zlib library is not linked by the pinned build. SDL2 and nativefiledialog-extended use the **zlib license**, which is distinct from using zlib code. A system-library build or distributor's package can have additional runtime dependencies; its notices must match the libraries actually included.
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
<!-- SPDX-License-Identifier: GPL-3.0-only -->
|
||||
<rml>
|
||||
<head><title>OpenBMH Editor</title><link type="text/rcss" href="theme.rcss"/></head>
|
||||
<body id="app" class="midnight">
|
||||
<div id="shell">
|
||||
<header><div class="brand"><div class="brand-mark">O<span>B</span></div><div><h2>OpenBMH <span>Editor</span></h2><small id="tagline"></small></div></div><div id="world-caption"></div><div id="top-actions"></div></header>
|
||||
<div id="main"><aside><div class="eyebrow" id="nav-label"></div><div id="navigation"></div><div class="aside-foot"><div class="small-pitch"><div></div></div><span>OBW 1.1</span><small id="profile-note"></small></div></aside>
|
||||
<section id="workspace"><div id="page-heading"><div><div class="eyebrow" id="page-kicker"></div><h1 id="page-title"></h1><p id="page-subtitle"></p></div><div id="page-actions"></div></div>
|
||||
<div id="toolbar"></div><div id="page-content"></div><div id="pagination"></div></section>
|
||||
</div>
|
||||
<footer><div id="state"></div><div id="status-message"></div><div id="bottom-actions"></div></footer>
|
||||
</div>
|
||||
<div id="overlay"><div id="modal"><div class="modal-head"><h2 id="modal-title"></h2><button data-action="cancel-modal" class="close">×</button></div><div id="modal-content"></div><div id="modal-error"></div><div id="modal-buttons"></div></div></div>
|
||||
</body></rml>
|
||||
@@ -0,0 +1,244 @@
|
||||
/* SPDX-License-Identifier: GPL-3.0-only */
|
||||
/* The submenu palettes are shared by every surface and control. RmlUI 6.3
|
||||
resolves these inherited custom properties when the body class changes. */
|
||||
body {
|
||||
--text: #dce3e9;
|
||||
--muted: #a8b8c8;
|
||||
--accent: #a9dccb;
|
||||
--window-top: #303c49;
|
||||
--window-bottom: #1a2531;
|
||||
--chrome: #d5e3ed0a;
|
||||
--sidebar: #111a2426;
|
||||
--panel: #111a2433;
|
||||
--wash: #e3edf605;
|
||||
--control-top: #c1d1e31c;
|
||||
--control-bottom: #869eb312;
|
||||
--input: #17232e99;
|
||||
--popup: #293744;
|
||||
--hover: #d0e2f226;
|
||||
--selected: #a9d4c526;
|
||||
--selected-hover: #a9d4c53d;
|
||||
--selected-text: #e8f5ef;
|
||||
--border: #e2ebf02b;
|
||||
--divider: #d4e1eb12;
|
||||
--accent-border: #a9d4c55c;
|
||||
--focus: #8cc8ff;
|
||||
--danger: #f0aaa7;
|
||||
--danger-border: #f0aaa75c;
|
||||
--warning: #e1c68b;
|
||||
--positive: #b5dfcf;
|
||||
--note: #a9d4c50a;
|
||||
--modal: #283542;
|
||||
--overlay: #0b11189c;
|
||||
--image-stage: #1b2733;
|
||||
--crop: #a9dccb;
|
||||
--crop-wash: #a9dccb16;
|
||||
--scrollbar: #a8b8c860;
|
||||
--scrollbar-hover: #a8b8c899;
|
||||
--toggle-off: #617483;
|
||||
--toggle-on: #a9dccb;
|
||||
margin: 0; width: 100%; height: 100%; overflow: hidden;
|
||||
font-family: LatoLatin; font-size: 15dp; color: var(--text);
|
||||
background-color: var(--window-bottom);
|
||||
decorator: linear-gradient(155deg, var(--window-top), var(--window-bottom));
|
||||
}
|
||||
body.silver {
|
||||
--text: #233443;
|
||||
--muted: #526779;
|
||||
--accent: #25617a;
|
||||
--window-top: #f0f5f9;
|
||||
--window-bottom: #d4e0ea;
|
||||
--chrome: #ffffff45;
|
||||
--sidebar: #42627d09;
|
||||
--panel: #f1f6fa80;
|
||||
--wash: #42627d09;
|
||||
--control-top: #ffffffb0;
|
||||
--control-bottom: #bfd0e259;
|
||||
--input: #ffffffad;
|
||||
--popup: #f3f7fc;
|
||||
--hover: #9eb9d43b;
|
||||
--selected: #a3c3dd54;
|
||||
--selected-hover: #a3c3dd88;
|
||||
--selected-text: #193b52;
|
||||
--border: #6c879c4a;
|
||||
--divider: #6c879c28;
|
||||
--accent-border: #356f966e;
|
||||
--focus: #2b729a;
|
||||
--danger: #a23f45;
|
||||
--danger-border: #a23f4566;
|
||||
--warning: #805b18;
|
||||
--positive: #2e6953;
|
||||
--note: #2e69530a;
|
||||
--modal: #eaf1f7;
|
||||
--overlay: #21324166;
|
||||
--image-stage: #cfdae3;
|
||||
--crop: #25617a;
|
||||
--crop-wash: #25617a16;
|
||||
--scrollbar: #6c879c88;
|
||||
--scrollbar-hover: #526779bb;
|
||||
--toggle-off: #91a8b8;
|
||||
--toggle-on: #25617a;
|
||||
}
|
||||
body.matchday {
|
||||
--text: #efeded;
|
||||
--muted: #b7b4b9;
|
||||
--accent: #efb2aa;
|
||||
--window-top: #343338;
|
||||
--window-bottom: #202126;
|
||||
--chrome: #ffffff07;
|
||||
--sidebar: #1d1e2426;
|
||||
--panel: #1d1e2466;
|
||||
--wash: #f8e7e00a;
|
||||
--control-top: #e8d6dc12;
|
||||
--control-bottom: #a1a0aa0d;
|
||||
--input: #191a208a;
|
||||
--popup: #303037;
|
||||
--hover: #d5b3b423;
|
||||
--selected: #d48c7b26;
|
||||
--selected-hover: #d48c7b3d;
|
||||
--selected-text: #ffe5de;
|
||||
--border: #ead9da29;
|
||||
--divider: #ead9da16;
|
||||
--accent-border: #e5a19770;
|
||||
--focus: #efb2aa;
|
||||
--danger: #f0a6a7;
|
||||
--danger-border: #f0a6a75c;
|
||||
--warning: #e1c68b;
|
||||
--positive: #afd1be;
|
||||
--note: #afd1be0a;
|
||||
--modal: #2c2c32;
|
||||
--overlay: #1111149c;
|
||||
--image-stage: #23242a;
|
||||
--crop: #efb2aa;
|
||||
--crop-wash: #efb2aa16;
|
||||
--scrollbar: #827c8199;
|
||||
--scrollbar-hover: #b7b4b999;
|
||||
--toggle-off: #68646c;
|
||||
--toggle-on: #efb2aa;
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
div, h1, h2, p, label, header, aside, section, footer { display: block; }
|
||||
span { display: inline-block; }
|
||||
#shell { width: 100%; height: 100%; display: flex; flex-direction: column; }
|
||||
header { height: 86dp; flex-shrink: 0; display: flex; align-items: center; padding: 0 28dp; background-color: var(--chrome); border-bottom: 1dp var(--border); }
|
||||
.brand { display: flex; align-items: center; width: 300dp; }
|
||||
.brand-mark { width: 43dp; height: 43dp; line-height: 43dp; font-size: 21dp; font-weight: bold; text-align: center; border: 1dp var(--accent-border); border-radius: 13dp; color: var(--accent); background-color: var(--wash); margin-right: 13dp; }
|
||||
.brand-mark span { color: var(--text); }
|
||||
h1, h2, p { margin: 0; }
|
||||
h2 { font-size: 20dp; font-weight: bold; }
|
||||
h2 span { font-weight: normal; color: var(--muted); }
|
||||
small { display: block; font-size: 12dp; color: var(--muted); margin-top: 4dp; }
|
||||
#world-caption { flex: 1; font-size: 14dp; color: var(--muted); overflow: hidden; white-space: nowrap; }
|
||||
#top-actions, #bottom-actions, #page-actions, .button-row { display: flex; align-items: center; gap: 8dp; }
|
||||
button { font-family: LatoLatin; font-size: 14dp; color: var(--text); background-color: transparent; decorator: linear-gradient(var(--control-top), var(--control-bottom)); border: 1dp var(--border); border-radius: 8dp; padding: 9dp 14dp; cursor: pointer; text-align: center; white-space: nowrap; tab-index: auto; }
|
||||
button:hover { background-color: var(--hover); decorator: none; }
|
||||
button.primary { background-color: var(--selected); decorator: none; color: var(--selected-text); border-color: var(--accent-border); font-weight: bold; }
|
||||
button.primary:hover { background-color: var(--selected-hover); }
|
||||
button.danger { color: var(--danger); border-color: var(--danger-border); }
|
||||
button:disabled { opacity: 0.35; cursor: unavailable; }
|
||||
button.quiet { border-color: transparent; background-color: transparent; decorator: none; }
|
||||
button.quiet:hover { background-color: var(--hover); }
|
||||
#main { flex: 1; display: flex; min-height: 0; }
|
||||
aside { width: 220dp; flex-shrink: 0; padding: 28dp 14dp 18dp; display: flex; flex-direction: column; background-color: var(--sidebar); border-right: 1dp var(--divider); }
|
||||
.eyebrow { font-size: 11dp; font-weight: bold; letter-spacing: 1.5dp; color: var(--muted); text-transform: uppercase; }
|
||||
#nav-label { padding: 0 14dp 18dp; }
|
||||
#navigation { display: flex; flex-direction: column; gap: 5dp; }
|
||||
.nav { width: 100%; display: flex; align-items: center; padding: 11dp 13dp; text-align: left; border-color: transparent; background-color: transparent; decorator: none; font-size: 15dp; }
|
||||
.nav .glyph { width: 20dp; height: 20dp; margin-right: 16dp; flex-shrink: 0; }
|
||||
.nav.selected { background-color: var(--selected); color: var(--accent); border-color: var(--accent-border); }
|
||||
.aside-foot { margin-top: auto; padding: 24dp 14dp 0; font-size: 12dp; color: var(--muted); }
|
||||
.aside-foot small { line-height: 1.45; }
|
||||
.small-pitch { height: 50dp; width: 84dp; border: 1dp var(--border); border-radius: 4dp; margin-bottom: 15dp; position: relative; }
|
||||
.small-pitch div { position: absolute; width: 20dp; height: 20dp; border: 1dp var(--border); border-radius: 10dp; left: 31dp; top: 14dp; }
|
||||
#workspace { flex: 1; padding: 28dp 30dp 16dp; display: flex; flex-direction: column; min-width: 0; }
|
||||
#page-heading { display: flex; justify-content: space-between; align-items: center; margin-bottom: 23dp; flex-shrink: 0; }
|
||||
h1 { font-size: 28dp; font-weight: bold; margin-top: 7dp; }
|
||||
#page-subtitle { color: var(--muted); margin-top: 7dp; font-size: 14dp; }
|
||||
#toolbar { display: flex; gap: 10dp; margin-bottom: 16dp; flex-shrink: 0; align-items: center; }
|
||||
input, select, textarea { font-family: LatoLatin; font-size: 14dp; background-color: var(--input); color: var(--text); border: 1dp var(--border); border-radius: 7dp; padding: 9dp 10dp; height: 38dp; tab-index: auto; }
|
||||
input[type=checkbox] { width: 18dp; height: 18dp; padding: 2dp; background-color: var(--toggle-off); }
|
||||
input[type=checkbox]:checked { background-color: var(--toggle-on); decorator: none; }
|
||||
input[type=range] { height: 24dp; padding: 0; }
|
||||
input[type=range] track { height: 4dp; background-color: var(--scrollbar); margin: 9dp 0; border-radius: 2dp; }
|
||||
input[type=range] bar { width: 16dp; height: 16dp; border-radius: 8dp; background-color: var(--accent); margin-top: 3dp; }
|
||||
select { padding-right: 25dp; }
|
||||
select selectvalue { padding: 0; }
|
||||
select selectarrow { width: 9dp; height: 9dp; margin-right: 9dp; margin-top: 11dp; decorator: none; border-bottom: 2dp var(--muted); border-right: 2dp var(--muted); transform: rotate(45deg); }
|
||||
select selectbox { background-color: var(--popup); color: var(--text); border: 1dp var(--border); border-radius: 8dp; padding: 5dp; max-height: 290dp; overflow-y: auto; }
|
||||
select option { font-size: 14dp; padding: 8dp; border-radius: 4dp; }
|
||||
select option:hover, select option:checked { background-color: var(--selected); color: var(--selected-text); }
|
||||
#search { width: 250dp; margin-right: auto; }
|
||||
#filter-nation, #filter-league { width: 205dp; }
|
||||
#filter-team { width: 240dp; }
|
||||
#page-content { flex: 1; min-height: 0; display: flex; }
|
||||
.split { width: 100%; display: flex; gap: 20dp; min-height: 0; }
|
||||
.list-panel { flex: 1; min-width: 0; border: 1dp var(--border); border-radius: 12dp; overflow: hidden; background-color: var(--panel); display: flex; flex-direction: column; }
|
||||
.table-header { display: flex; align-items: center; height: 42dp; flex-shrink: 0; padding: 0 16dp; background-color: var(--wash); border-bottom: 1dp var(--divider); }
|
||||
.table-header button { flex: 1; text-align: left; padding: 0; border: 0; background-color: transparent; decorator: none; font-size: 12dp; color: var(--muted); }
|
||||
.table-header button:hover { color: var(--text); }
|
||||
.table-header button:first-child { flex: 2; }
|
||||
.table-scroll { flex: 1; overflow-y: auto; }
|
||||
.record { display: flex; align-items: center; width: 100%; min-height: 49dp; padding: 9dp 16dp; border: 0; border-bottom: 1dp var(--divider); border-radius: 0; background-color: transparent; decorator: none; text-align: left; }
|
||||
.record:hover { background-color: var(--hover); }
|
||||
.record.selected { background-color: var(--selected); border-left: 3dp var(--accent); padding-left: 13dp; }
|
||||
.record .cell { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; padding-right: 10dp; font-size: 13dp; color: var(--muted); }
|
||||
.record .cell:first-child { flex: 2; font-size: 14dp; color: var(--text); display: flex; align-items: center; }
|
||||
.record.selected .cell { color: var(--selected-text); }
|
||||
.mini-logo { width: 27dp; height: 27dp; margin-right: 12dp; flex-shrink: 0; }
|
||||
.inspector { width: 370dp; flex-shrink: 0; border: 1dp var(--border); border-radius: 12dp; background-color: var(--panel); display: flex; flex-direction: column; overflow: hidden; }
|
||||
.inspector-head { padding: 22dp; border-bottom: 1dp var(--divider); display: flex; align-items: center; flex-shrink: 0; }
|
||||
.hero-image { width: 70dp; height: 70dp; margin-right: 16dp; }
|
||||
.inspector-head h2 { font-size: 19dp; }
|
||||
.inspector-head small { font-size: 10dp; margin-top: 7dp; }
|
||||
.inspector-scroll { flex: 1; overflow-y: auto; padding: 20dp 22dp; }
|
||||
.form-field { margin-bottom: 15dp; }
|
||||
.form-field label { display: block; font-size: 12dp; color: var(--muted); margin-bottom: 6dp; }
|
||||
.form-field input, .form-field select, .form-field textarea { width: 100%; }
|
||||
textarea { height: 110dp; font-size: 12dp; line-height: 1.5; }
|
||||
.form-section { padding-top: 8dp; margin-bottom: 15dp; font-size: 12dp; font-weight: bold; color: var(--accent); }
|
||||
.form-help { font-size: 11dp; color: var(--muted); line-height: 1.5; margin-top: 6dp; }
|
||||
.inspector-actions { padding: 16dp 20dp; border-top: 1dp var(--divider); display: flex; gap: 8dp; flex-shrink: 0; }
|
||||
.inspector-actions button { flex: 1; }
|
||||
.empty { margin: auto; padding: 45dp; text-align: center; color: var(--muted); line-height: 1.7; }
|
||||
#pagination { display: flex; justify-content: space-between; align-items: center; flex-shrink: 0; padding-top: 14dp; color: var(--muted); font-size: 12dp; }
|
||||
footer { height: 57dp; padding: 0 28dp; display: flex; align-items: center; gap: 20dp; flex-shrink: 0; border-top: 1dp var(--divider); background-color: var(--sidebar); font-size: 12dp; }
|
||||
#state { width: 210dp; color: var(--positive); }
|
||||
#status-message { flex: 1; color: var(--muted); }
|
||||
#bottom-actions button { font-size: 12dp; padding: 7dp 11dp; }
|
||||
.dashboard { width: 100%; overflow-y: auto; padding-right: 7dp; }
|
||||
.hero { padding: 32dp; border: 1dp var(--border); border-radius: 16dp; background-color: var(--wash); margin-bottom: 22dp; }
|
||||
.hero h1 { font-size: 32dp; margin: 0 0 12dp; }
|
||||
.hero p { color: var(--muted); line-height: 1.6; max-width: 700dp; margin-bottom: 23dp; }
|
||||
.metrics { display: flex; flex-wrap: wrap; gap: 14dp; }
|
||||
.metric { width: 23%; flex-grow: 1; min-width: 180dp; min-height: 106dp; padding: 20dp; border: 1dp var(--border); border-radius: 12dp; background-color: var(--panel); decorator: none; text-align: left; }
|
||||
.metric span { display: block; font-size: 28dp; font-weight: bold; color: var(--text); margin-top: 9dp; }
|
||||
.note { margin-top: 22dp; padding: 18dp 20dp; background-color: var(--note); border: 1dp var(--accent-border); border-radius: 10dp; color: var(--positive); font-size: 13dp; line-height: 1.6; }
|
||||
.source-json { font-size: 11dp; line-height: 1.5; white-space: pre-wrap; color: var(--muted); margin: 14dp 0; }
|
||||
.history-row, .diagnostic { padding: 15dp 20dp; border-bottom: 1dp var(--divider); line-height: 1.6; }
|
||||
.diagnostic.error { color: var(--danger); }
|
||||
.diagnostic.warning { color: var(--warning); }
|
||||
.badge { display: inline-block; font-size: 11dp; border: 1dp var(--accent-border); color: var(--positive); border-radius: 5dp; padding: 3dp 6dp; }
|
||||
#overlay { display: none; position: absolute; left: 0; top: 0; width: 100%; height: 100%; background-color: var(--overlay); align-items: center; justify-content: center; }
|
||||
#modal { width: 620dp; max-height: 91%; padding: 27dp; border: 1dp var(--border); border-radius: 18dp; background-color: var(--modal); display: flex; flex-direction: column; }
|
||||
#modal.wide { width: 880dp; }
|
||||
.modal-head { display: flex; justify-content: space-between; align-items: center; margin-bottom: 22dp; flex-shrink: 0; }
|
||||
.close { padding: 0 7dp; background-color: transparent; decorator: none; border-color: transparent; font-size: 25dp; }
|
||||
#modal-content { overflow-y: auto; line-height: 1.6; }
|
||||
#modal-buttons { margin-top: 23dp; display: flex; justify-content: flex-end; gap: 9dp; flex-shrink: 0; }
|
||||
#modal-error { color: var(--danger); font-size: 13dp; margin-top: 10dp; }
|
||||
.image-layout { display: flex; gap: 24dp; }
|
||||
.image-stage { flex: 1; min-height: 360dp; background-color: var(--image-stage); border: 1dp var(--border); border-radius: 10dp; display: flex; align-items: center; justify-content: center; overflow: hidden; }
|
||||
#crop-canvas { position: relative; }
|
||||
#edit-preview { display: block; }
|
||||
#crop-box { position: absolute; border: 2dp var(--crop); background-color: var(--crop-wash); pointer-events: none; }
|
||||
.image-controls { width: 215dp; }
|
||||
.pair { display: flex; gap: 8dp; }
|
||||
.pair .form-field { flex: 1; min-width: 0; }
|
||||
.check-label { display: flex; align-items: center; gap: 10dp; font-size: 14dp; margin: 14dp 0; }
|
||||
scrollbarvertical { width: 7dp; margin: 3dp; }
|
||||
scrollbarvertical slidertrack { background-color: transparent; }
|
||||
scrollbarvertical sliderbar { background-color: var(--scrollbar); border-radius: 4dp; min-height: 30dp; }
|
||||
scrollbarvertical sliderbar:hover { background-color: var(--scrollbar-hover); }
|
||||
scrollbarvertical sliderarrowdec, scrollbarvertical sliderarrowinc { height: 0; }
|
||||
button:focus, input:focus, select:focus, textarea:focus { border-color: var(--focus); }
|
||||
.nav:focus { border-color: var(--focus); }
|
||||
@@ -0,0 +1,78 @@
|
||||
# OpenBMH Editor POC
|
||||
|
||||
Der eigenständige, native Editor verwendet **RmlUI, SDL2 und OpenGL**. Er bearbeitet Startdatenbanken, keine laufenden Spielstände. Das Spiel und seine Classic-Prüfung bleiben unverändert.
|
||||
|
||||
## Starten und Daten öffnen
|
||||
|
||||
Das vollständige Editor-Paket entpacken und `OpenBMHEditor.exe` (Windows) beziehungsweise `OpenBMHEditor` (Linux/macOS) starten. `assets/editor` muss beim Programm bleiben. Auf macOS kann die unsignierte Testanwendung über **Rechtsklick → Öffnen** gestartet werden. Eine Signatur/Notarisierung ist nicht Bestandteil dieses POC.
|
||||
|
||||
**Öffnen** bietet OBW-Dateien und entpackte Welten an. **BMH / FLTD importieren** liest einen Ordner mit einer unterstützten BMH- oder Football-Limited-Installation durch den bestehenden Konverter. Das Original wird nicht überschrieben. Eine bestehende Classic-OBW wird zunächst überprüft und dann in eine bearbeitbare Editorwelt übernommen.
|
||||
|
||||
**Demo öffnen** lädt ausschließlich synthetische Testdaten. Echte Vereine, Spielerdaten, Fotos und importierte Originalgrafiken gehören in getrennte, private Datenpakete.
|
||||
|
||||
## Bearbeiten
|
||||
|
||||
- Links einen Datenbereich auswählen; die Liste lässt sich durchsuchen, filtern, sortieren und seitenweise durchgehen. Rechts Änderungen mit **Anwenden** übernehmen. **Speichern** übernimmt auch die aktuellen Eingaben.
|
||||
- Länder, Wettbewerbe, Vereine, Spieler, Kader, Stadien und Schiedsrichter lassen sich anlegen und bearbeiten. Referenzierte Datensätze werden erst nach Änderung ihrer Verknüpfungen gelöscht. Vereinswechsel zwischen Ligen aktualisieren auch deren Mitgliederlisten.
|
||||
- Spielwerte behalten ihre **quellenspezifischen Wertebereiche**. Ein Classic-Wert wird nicht auf eine erfundene 1–10-Skala umgerechnet. Neue Spieler ohne belegte Werte bleiben zunächst unbewertet.
|
||||
- Kader bleiben vollständig erhalten. Die Schaltfläche **24** schaltet lediglich die Seitengröße um. Spieler lassen sich über das Vereinsfeld verschieben, zum Tausch merken und mit einem anderen Spieler tauschen; die Pfeile ändern ihre Reihenfolge.
|
||||
- **Prüfen** zeigt überlieferte Quellenkonflikte. Eine Auswahl übernimmt den gewählten Wert; die übrigen Quellen bleiben erhalten. Fehlende Daten sind Hinweise, fehlerhafte Verknüpfungen oder unzulässige Werte blockieren Änderungen und Speichern.
|
||||
- Rückgängig/Wiederholen gilt gemeinsam für native Oberfläche und MCP. Noch nicht angewendete Eingaben werden bei externen Änderungen nicht automatisch ersetzt; eine veraltete Änderung muss nach Aktualisierung erneut geprüft werden.
|
||||
- **Bilder** und die Bildaktionen am Datensatz unterstützen PNG, JPEG, WebP und eigenständige SVG. Vor dem Import: Ausschnitt ziehen oder Werte eingeben, frei drehen, spiegeln. Ein unveränderter Import behält seine Originalbytes. Bearbeitete Rasterbilder werden PNG, SVG bleibt Vektor. Das Original und die Transformationswerte bleiben für erneutes Bearbeiten im Paket. Classic-Porträts werden aus ihren eingefrorenen Rezepten angezeigt; eine Umbenennung ändert das Gesicht nicht.
|
||||
- Bildänderungen am Spieler, Verein oder Wettbewerb erhalten eine eigene Zuordnung. Gemeinsame Platzhalter und Bilder anderer Datensätze bleiben dabei erhalten. Im Bereich **Bilder** kann ein gemeinsam verwendetes Bild bewusst zentral bearbeitet werden.
|
||||
|
||||
**Speichern** erzeugt ausschließlich `.obw` im Profil **`editor-world-v1`, Format 1.1**. Editorwelten sind **noch nicht im Classic-Spiel startbar**. Die Bezeichnung ist im Editor sichtbar. Unbekannte Erweiterungen, nicht bearbeitete Dokumente, Quellnachweise und Bilder bleiben erhalten. Noch nicht im Formular angebotene Regeln, Kalender- und Finanzdaten werden erhalten, aber nicht als vollständig editierbare Bereiche ausgegeben.
|
||||
|
||||
Shortcuts: Ctrl/Cmd+O, Ctrl/Cmd+S, Shift+Ctrl/Cmd+S, Ctrl/Cmd+Z und Shift+Ctrl/Cmd+Z. In Textfeldern gilt die lokale Text-Rückgängig-Funktion.
|
||||
|
||||
## Optionen und MCP
|
||||
|
||||
**Optionen** bietet Deutsch/Englisch, Midnight Glass/Silver Glass/Matchday und den integrierten MCP-Server. Die Sprache ändert die Oberfläche; Namen und Quelldaten werden nicht übersetzt. Einstellungen werden im Benutzerprofil gespeichert.
|
||||
|
||||
Unter **Darstellung** stehen die drei Farbwelten der modernen Untermenüs zur Auswahl:
|
||||
|
||||
- **Midnight Glass:** Schiefergrau mit dezenten Mint-Akzenten.
|
||||
- **Silver Glass:** helle silbergraue Flächen mit Petrol-Akzenten.
|
||||
- **Matchday:** Graphit mit warmen Korall-Akzenten.
|
||||
|
||||
**Anwenden** wechselt das Theme ohne Neustart. Die Farbwahl gilt auch für Tabellen, Eigenschaften, Dropdowns, Meldungen und die Bildbearbeitung. [Native Vergleichsbilder](qa/editor-poc/README.md#theme-comparison) zeigen alle drei mit denselben synthetischen Daten.
|
||||
|
||||
Der MCP-Server ist standardmäßig aktiviert und bindet ausschließlich `127.0.0.1`, standardmäßig Port `8765`. Port `0` wählt einen freien Port. Status und tatsächlicher Port sind in Optionen sichtbar. **Verbindung kopieren** kopiert eine JSON-Konfiguration einschließlich Bearer-Token für HTTP-fähige MCP-Clients. Das Token bleibt lokal im Benutzerprofil und wird nur auf ausdrückliches Kopieren/CLI-Anfordern ausgegeben. Ein anderer bereits laufender Editor kann den Standardport belegen; dann einen anderen Port wählen.
|
||||
|
||||
Implementiert ist [MCP Streamable HTTP 2025-11-25](https://modelcontextprotocol.io/specification/2025-11-25/basic/transports), mit Aushandlung von 2025-06-18; JSON-Antworten, ohne optionale SSE-Sitzungen. Neuere MCP-Versionen werden nicht als unterstützt beworben. Der Server prüft Token, Host und gegebenenfalls Origin. Oberfläche und Agent bearbeiten dieselbe Welt, verwenden dieselbe Validierung und dieselbe Undo-Historie. Für konkurrierende Änderungen `expected_revision` aus `editor_info`/`editor_get` mitsenden.
|
||||
|
||||
Werkzeuge: `editor_info`, `editor_open`, `editor_new`, `editor_list`, `editor_get`, `editor_apply`, `editor_rules`, `editor_validate`, `editor_history`, `editor_save`, `editor_undo`, `editor_redo`, `editor_roster_move`, `editor_roster_swap`, `editor_roster_order`, `editor_review_resolve`, `editor_image_import`, `editor_image_edit`, `editor_image_preview`, `editor_image_export`. Die eingeblendeten Tools enthalten Parameterschemata und Beschreibungen. Öffnen einer anderen Welt verwirft ungespeicherte Änderungen nur mit `discard: true`.
|
||||
|
||||
## Kompilieren
|
||||
|
||||
Voraussetzungen entsprechen dem Hauptprojekt: C++20-Compiler, Git, CMake ≥ 3.24 und Ninja. Windows: Visual Studio 2022 C++ Build Tools / x64 Native Tools Prompt; macOS ARM: Xcode Command Line Tools, CMake und Ninja; Linux: GTK3-, X11- und OpenGL-Entwicklungspakete wie im Haupt-README. Die Grafikausgabe benötigt OpenGL 3.3, auf macOS OpenGL 4.1.
|
||||
|
||||
```sh
|
||||
cmake -S . -B build-editor -G Ninja -DCMAKE_BUILD_TYPE=Release -DOPENBMH_BUILD_EDITOR=ON
|
||||
cmake --build build-editor --target openbmh_editor editor_core_tests --parallel 2
|
||||
ctest --test-dir build-editor -C Release -R '^editor_core_tests$' --output-on-failure
|
||||
```
|
||||
|
||||
macOS ARM zusätzlich bei der Konfiguration: `-DCMAKE_OSX_ARCHITECTURES=arm64 -DCMAKE_OSX_DEPLOYMENT_TARGET=11.0`. Unter Windows das Argument nach `-R` ohne einfache Shell-Anführungszeichen verwenden. Der Editor wird beim normalen Spiel-Build standardmäßig nicht mitgebaut.
|
||||
|
||||
```sh
|
||||
build-editor/OpenBMHEditor --demo
|
||||
build-editor/OpenBMHEditor --headless --open world.obw --validate
|
||||
build-editor/OpenBMHEditor --headless --open world.obw --output edited.obw
|
||||
build-editor/OpenBMHEditor --serve --open world.obw --mcp-port 8765
|
||||
build-editor/OpenBMHEditor --stdio-mcp --open world.obw
|
||||
```
|
||||
|
||||
Weitere Argumente: `--settings datei.json`, `--assets verzeichnis`, `--commands script.json`, `--print-mcp-config`. Ein Command-Script ist ein Array aus `{"command":"…","args":{…}}`, mit denselben Kommandos wie die gemeinsame Session (z. B. `get`, `apply`, `save`). `--headless` startet kein Fenster. `--stdio-mcp` bietet dieselben Werkzeuge über newline-delimited JSON-RPC; stdout enthält dabei ausschließlich Protokollnachrichten. Testaufnahmen: `--screenshot bild.png --quit-after-ms 1800 --page clubs` (unter Linux mit Xvfb möglich).
|
||||
|
||||
Pakete baut `tools/package/make_editor_package.py --build build-editor --out dist --platform linux-x64` (oder `windows-x64`, `macos-arm64`). `--source-package` ergänzt den zugehörigen Quellcode mit den tatsächlich verwendeten, gepinnten Abhängigkeiten. Die CI **OBW Editor POC** baut und prüft alle drei Plattformen. Die nativen Tests unterscheiden sich von einem späteren menschlichen GUI-Test auf Windows/macOS.
|
||||
|
||||
## English quick start
|
||||
|
||||
Extract the complete package and run **OpenBMHEditor**. Open an OBW archive or an unpacked world, import a supported BMH/Football Limited installation, or open the synthetic demo. Use the sidebar, searchable/filterable list and property inspector; **Apply** records one shared, undoable transaction. **Save** writes only an **OBW 1.1 editor world**, not a playable Classic mod or a legacy installation.
|
||||
|
||||
The editor retains full squads, original image data, source claims and unknown extensions. Its 24-player view does not remove players. Image import offers normalized crop, arbitrary rotation and mirroring; re-editing uses the preserved source. Classic portraits keep their frozen appearance recipe. Unsupported editing areas are preserved rather than replaced.
|
||||
|
||||
In **Options**, switch the interface to **English**, choose one of the three themes, and enable/disable the integrated local MCP server. **Copy connection** provides the authenticated configuration. The server defaults to loopback port 8765; use port 0 for a free port. GUI and MCP share the same world, validation and undo history. It supports MCP Streamable HTTP 2025-11-25/2025-06-18 and optional stdio mode. Use `expected_revision` for concurrent edits.
|
||||
|
||||
Build with the three commands above, including `-DOPENBMH_BUILD_EDITOR=ON`. The native application requires OpenGL 3.3 (macOS 4.1) and the platform development dependencies documented in the main README. The proof of concept is unsigned and does not bundle any real-world dataset or proprietary game assets.
|
||||
@@ -1,5 +1,9 @@
|
||||
# OBW: OpenBMH world, save and pack format (concept, format version 1.0)
|
||||
|
||||
The standalone editor additionally implements the non-playable
|
||||
[OBW 1.1 `editor-world-v1` profile](obw/editor-v1.md). This does not relax the
|
||||
Classic 1.0 content contract or seals. See [the editor guide](../EDITOR.md).
|
||||
|
||||
Status: **format concept with a complete Classic installation-content converter** for roadmap 0.2, with preparation for 0.4. `openbmh_import` produces `BMH-classic` and `FLTD-classic` worlds under the guarded [`runtime:classic-v1` contract](obw/classic-v1.md), including all startup inputs and media. The [import guide](obw/import.md) distinguishes this from the explicitly partial `legacy-database-v1` development export. The 0.2 development branch adds a sealed Classic runtime, portable launcher and native career checkpoints; see [the runtime contract](obw/runtime-0.2.md). The released 0.1 engine still reads legacy installations.
|
||||
|
||||
## 1. Goals and non-goals
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
# OBW 1.1 editor-world-v1
|
||||
|
||||
This additive profile is a native editing interchange. It does **not** change
|
||||
`classic-installation-v1`, its seals, the Classic runtime or save files.
|
||||
|
||||
## Identification
|
||||
|
||||
```json
|
||||
{
|
||||
"format": "openbmh-world",
|
||||
"format_version": "1.1",
|
||||
"min_reader": "1.1",
|
||||
"kind": "world",
|
||||
"title": {"default": "My world"},
|
||||
"start_date": "2026-07-01",
|
||||
"currency": {"code": "EUR", "minor_units": 2},
|
||||
"requires": ["editor:world-v1"],
|
||||
"extensions": [{"id": "x-editor", "version": "1"}],
|
||||
"x-editor": {"profile": "editor-world-v1", "playable": false}
|
||||
}
|
||||
```
|
||||
|
||||
The required editor capability is deliberately different from
|
||||
`runtime:classic-v1`. An edited world must not be resealed as a Classic world.
|
||||
On import the editor keeps the original manifest under
|
||||
`x-editor.original_manifest`, leaves compatibility/source regions intact, and
|
||||
requires Save As. An original Classic seal is historical evidence only in this
|
||||
profile. The existing Classic reader/validator is not broadened to accept it.
|
||||
|
||||
## Tables and values
|
||||
|
||||
The existing `world/*.json` and `assets/index.json` structure remains. Each table
|
||||
is an object with `schema` and `items`. Stable `id` identifiers (asset `key`)
|
||||
are references, never array positions. Existing identifiers and unknown fields
|
||||
are preserved. New identifiers have a namespace and opaque suffix.
|
||||
|
||||
The editor adds explicit club `competition`, competition `members` (club IDs),
|
||||
and player `squad_order`. These are the editable projections of Classic league
|
||||
slots/squad rows. Moving a club updates league membership in the same
|
||||
transaction. The historical Classic slots stay source evidence; a future
|
||||
playable format adapter must choose and implement its own generation rules.
|
||||
|
||||
Player `born` can be `null`; an imported `age_at_start` object remains an age,
|
||||
not an invented birth date. `team: null` is an unassigned projection; an
|
||||
`x-editor.membership_unresolved` or `membership_unassigned` marker distinguishes
|
||||
missing/contradictory source facts from a verified free agent. Reported
|
||||
nationalities and sporting eligibility remain separate. No full roster is
|
||||
cut down to the 24 rows of a Classic compatibility view.
|
||||
|
||||
Attribute sets declare their actual numeric ranges in `world/rules.json`:
|
||||
`type: "attribute_set"`, optional `attribute_set` alias, and `fields` mapping
|
||||
attribute names to `{min,max,...}`. The Classic importer declares strength
|
||||
0–99, form/condition/technique/bonus 0–127, skills 0–3. An FC set remains a
|
||||
separate 0–99 system. Missing values are null/absent; `unrated@1` with empty
|
||||
attributes does not invent a rating.
|
||||
|
||||
Competition `trophy` and optional fallback remain logical asset references;
|
||||
images are indexed just like crests and portraits. Arbitrary new competitions
|
||||
can use their own trophy or a package-supplied generic trophy.
|
||||
|
||||
## Sources, conflicts and images
|
||||
|
||||
- `x-source/` can contain unchanged or losslessly gzipped normalized source
|
||||
tables, input hashes, source-to-projection identifiers and identity evidence.
|
||||
References include package-local file paths and JSON pointers. Sources do
|
||||
not become authoritative merely by being present.
|
||||
- `x-editor/review.json` has `items` with `id`, `reason`, `resolved`, optional
|
||||
`table`, `entity`, `field` (JSON pointer), and `alternatives` with `value` and
|
||||
source descriptions. Choosing a value updates its target plus the review
|
||||
record in one undoable transaction. Original alternatives remain.
|
||||
- Raster and SVG sources are stored unchanged. Identity imports preserve exact
|
||||
bytes. Edits use a normalized recipe: `angle` degrees, `flip_x`, `flip_y`,
|
||||
`crop: {x,y,width,height}`. Mirroring precedes clockwise rotation; rotation
|
||||
expands the canvas; crop coordinates refer to that expanded canvas. Values
|
||||
are finite, crop dimensions positive and inside [0,1]. JSON floating-point
|
||||
values must survive round trips.
|
||||
- An edited asset's `x-editor` stores `original`, `original_sha256` and
|
||||
`transform`. Originals live in `x-editor/originals/`, rendered files in
|
||||
`assets/edited/`, addressed by SHA-256. Raster edits are PNG with transparent
|
||||
expanded edges, SVG edits remain vectors. Import does not upscale portraits.
|
||||
Referenced external SVG resources are refused. Originals and source recipes
|
||||
remain available on re-edit; no repeated destructive resampling is needed.
|
||||
- Portrait part sets and frozen `appearance` recipes remain valid. The editor
|
||||
composes those layers for display; a rename never regenerates the recipe.
|
||||
|
||||
## Container, validation and saving
|
||||
|
||||
ZIP/ZIP64, stored or deflated entries; UTF-8 JSON; package-local paths without
|
||||
absolute paths, `..`, backslashes or symlinks. The editor limits are 100,000
|
||||
entries, 64 MiB per uncompressed entry and 2 GiB total uncompressed bytes. This
|
||||
is independent of the smaller Classic 1.0 reader limits.
|
||||
|
||||
The editor checks identifier uniqueness, typed references, valid dates,
|
||||
declared attribute ranges and assets. Missing facts/source questions are
|
||||
warnings; structural errors block saving. A transaction either validates and
|
||||
commits or is rolled back. `revision` increases monotonically, including
|
||||
undo/redo. Undoing to the saved state clears the dirty flag.
|
||||
|
||||
Unknown entries, extensions, binary assets and untouched table bytes are
|
||||
retained. Large assets remain lazily read from an immutable source snapshot.
|
||||
Saving streams a temporary ZIP and atomically replaces the destination only
|
||||
after finalization. Modified-on-disk sources require Save As. The editor never
|
||||
writes legacy files or a running save.
|
||||
|
||||
The [1.1 editor schema](schema/1.1/editor-world.json) documents structural
|
||||
constraints. Runtime validation additionally resolves cross-table references
|
||||
and rule-declared scales. This is not a claim that the generic world can yet
|
||||
be played by a game engine.
|
||||
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://openbmh.org/schema/1.1/editor-world.json",
|
||||
"title": "OBW 1.1 editor-world-v1 manifest",
|
||||
"type": "object",
|
||||
"required": ["format", "format_version", "min_reader", "kind", "title", "requires", "x-editor"],
|
||||
"properties": {
|
||||
"format": {"const": "openbmh-world"},
|
||||
"format_version": {"const": "1.1"},
|
||||
"min_reader": {"const": "1.1"},
|
||||
"kind": {"const": "world"},
|
||||
"title": {"oneOf": [{"type": "string"}, {"type": "object", "additionalProperties": {"type": "string"}}]},
|
||||
"start_date": {"type": "string", "format": "date"},
|
||||
"requires": {"type": "array", "contains": {"const": "editor:world-v1"}, "items": {"type": "string"}},
|
||||
"x-editor": {
|
||||
"type": "object", "required": ["profile", "playable"],
|
||||
"properties": {"profile": {"const": "editor-world-v1"}, "playable": {"const": false}},
|
||||
"additionalProperties": true
|
||||
}
|
||||
},
|
||||
"additionalProperties": true,
|
||||
"$defs": {
|
||||
"table": {"type": "object", "required": ["schema", "items"], "properties": {"schema": {"type": "string"}, "items": {"type": "array", "items": {"type": "object"}}}, "additionalProperties": true},
|
||||
"transform": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"angle": {"type": "number", "minimum": -360, "maximum": 360},
|
||||
"flip_x": {"type": "boolean"}, "flip_y": {"type": "boolean"},
|
||||
"crop": {"type": "object", "properties": {
|
||||
"x": {"type": "number", "minimum": 0, "maximum": 1}, "y": {"type": "number", "minimum": 0, "maximum": 1},
|
||||
"width": {"type": "number", "exclusiveMinimum": 0, "maximum": 1}, "height": {"type": "number", "exclusiveMinimum": 0, "maximum": 1}
|
||||
}, "additionalProperties": true}
|
||||
}, "additionalProperties": true
|
||||
},
|
||||
"review": {"type": "object", "required": ["id", "reason", "resolved", "alternatives"], "properties": {
|
||||
"id": {"type": "string", "minLength": 1}, "reason": {"type": "string"}, "resolved": {"type": "boolean"},
|
||||
"table": {"type": "string"}, "entity": {"type": "string"}, "field": {"type": "string", "pattern": "^/"},
|
||||
"alternatives": {"type": "array", "items": {"type": "object", "required": ["value"], "additionalProperties": true}}
|
||||
}, "additionalProperties": true}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2020-2025 Samuel Ugochukwu <sammycageagle@gmail.com>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2020-2025 Samuel Ugochukwu <sammycageagle@gmail.com>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -13,5 +13,6 @@ These files preserve upstream license and attribution wording. They are not a gr
|
||||
- [Lato font notices](RmlUi-fonts.txt): unmodified Regular and Bold Latin fonts from RmlUi 6.3, under SIL OFL 1.1. The upstream sample-font notice is retained verbatim.
|
||||
- [Nuked OPL3 copyright and license notice](Nuked-OPL3-notices.txt): unchanged leading notice from its vendored implementation.
|
||||
- [LGPL version 2.1](LGPL-2.1.txt): full license supplied with Nuked OPL3. Its source notices permit version 2.1 or any later version.
|
||||
- Optional native editor: [nlohmann/json](nlohmann-json.txt), [cpp-httplib](cpp-httplib.txt), [SDL2_image](SDL2_image.txt), [stb_image](stb-image.txt), [libwebp](libwebp.txt) with its [patent grant](libwebp-PATENTS.txt), [LunaSVG](LunaSVG.txt), [PlutoVG](PlutoVG.txt), and [pugixml](pugixml.txt). These are verbatim upstream notices for the pinned versions listed in the root notices.
|
||||
|
||||
[THIRD_PARTY_NOTICES.md](../../THIRD_PARTY_NOTICES.md) identifies the upstream versions and distribution requirements. Include this directory, that notice file and the root LICENSE with release packages. Preserve upstream attribution within these verbatim texts.
|
||||
@@ -0,0 +1,17 @@
|
||||
Copyright (C) 1997-2025 Sam Lantinga <slouken@libsdl.org>
|
||||
|
||||
This software is provided 'as-is', without any express or implied
|
||||
warranty. In no event will the authors be held liable for any damages
|
||||
arising from the use of this software.
|
||||
|
||||
Permission is granted to anyone to use this software for any purpose,
|
||||
including commercial applications, and to alter it and redistribute it
|
||||
freely, subject to the following restrictions:
|
||||
|
||||
1. The origin of this software must not be misrepresented; you must not
|
||||
claim that you wrote the original software. If you use this software
|
||||
in a product, an acknowledgment in the product documentation would be
|
||||
appreciated but is not required.
|
||||
2. Altered source versions must be plainly marked as such, and must not be
|
||||
misrepresented as being the original software.
|
||||
3. This notice may not be removed or altered from any source distribution.
|
||||
@@ -0,0 +1,22 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2017 yhirose
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
Additional IP Rights Grant (Patents)
|
||||
------------------------------------
|
||||
|
||||
"These implementations" means the copyrightable works that implement the WebM
|
||||
codecs distributed by Google as part of the WebM Project.
|
||||
|
||||
Google hereby grants to you a perpetual, worldwide, non-exclusive, no-charge,
|
||||
royalty-free, irrevocable (except as stated in this section) patent license to
|
||||
make, have made, use, offer to sell, sell, import, transfer, and otherwise
|
||||
run, modify and propagate the contents of these implementations of WebM, where
|
||||
such license applies only to those patent claims, both currently owned by
|
||||
Google and acquired in the future, licensable by Google that are necessarily
|
||||
infringed by these implementations of WebM. This grant does not include claims
|
||||
that would be infringed only as a consequence of further modification of these
|
||||
implementations. If you or your agent or exclusive licensee institute or order
|
||||
or agree to the institution of patent litigation or any other patent
|
||||
enforcement activity against any entity (including a cross-claim or
|
||||
counterclaim in a lawsuit) alleging that any of these implementations of WebM
|
||||
or any code incorporated within any of these implementations of WebM
|
||||
constitute direct or contributory patent infringement, or inducement of
|
||||
patent infringement, then any patent rights granted to you under this License
|
||||
for these implementations of WebM shall terminate as of the date such
|
||||
litigation is filed.
|
||||
@@ -0,0 +1,30 @@
|
||||
Copyright (c) 2010, Google Inc. All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are
|
||||
met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
|
||||
* Redistributions in binary form must reproduce the above copyright
|
||||
notice, this list of conditions and the following disclaimer in
|
||||
the documentation and/or other materials provided with the
|
||||
distribution.
|
||||
|
||||
* Neither the name of Google nor the names of its contributors may
|
||||
be used to endorse or promote products derived from this software
|
||||
without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2013-2025 Niels Lohmann
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,24 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2006-2025 Arseny Kapoulkine
|
||||
|
||||
Permission is hereby granted, free of charge, to any person
|
||||
obtaining a copy of this software and associated documentation
|
||||
files (the "Software"), to deal in the Software without
|
||||
restriction, including without limitation the rights to use,
|
||||
copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the
|
||||
Software is furnished to do so, subject to the following
|
||||
conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
||||
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
||||
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
OTHER DEALINGS IN THE SOFTWARE.
|
||||
@@ -0,0 +1,36 @@
|
||||
ALTERNATIVE A - MIT License
|
||||
Copyright (c) 2017 Sean Barrett
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
this software and associated documentation files (the "Software"), to deal in
|
||||
the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do
|
||||
so, subject to the following conditions:
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
------------------------------------------------------------------------------
|
||||
ALTERNATIVE B - Public Domain (www.unlicense.org)
|
||||
This is free and unencumbered software released into the public domain.
|
||||
Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
|
||||
software, either in source code form or as a compiled binary, for any purpose,
|
||||
commercial or non-commercial, and by any means.
|
||||
In jurisdictions that recognize copyright laws, the author or authors of this
|
||||
software dedicate any and all copyright interest in the software to the public
|
||||
domain. We make this dedication for the benefit of the public at large and to
|
||||
the detriment of our heirs and successors. We intend this dedication to be an
|
||||
overt act of relinquishment in perpetuity of all present and future rights to
|
||||
this software under copyright law.
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
|
||||
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
------------------------------------------------------------------------------
|
||||
@@ -0,0 +1,82 @@
|
||||
# Native editor POC — QA evidence
|
||||
|
||||
All images here contain **synthetic demo data and project-owned geometric
|
||||
artwork**. No real club, player photograph, original game screen, imported game
|
||||
artwork, local filesystem path or MCP credential is included. These exact
|
||||
reviewed image hashes are allowlisted by the public-tree check.
|
||||
|
||||
| Screenshot | Coverage |
|
||||
|---|---|
|
||||
| [Clubs](clubs-midnight-de.png) | Native RmlUI master/detail view, Midnight Glass, German |
|
||||
| [Players](players-silver-en.png) | Silver Glass, English interface, retained authored German demo names |
|
||||
| [Squads](roster-matchday-de.png) | Matchday theme, full squads and optional 24-row view |
|
||||
| [Search](gui-search.png) | Actual keyboard input, focus retained across filtering |
|
||||
| [Options](options-midnight-de.png) | Language, theme, integrated MCP toggle/port |
|
||||
| [Image editor](image-editor-midnight-de.png) | Source-preserving crop, free rotation and mirroring; the demo's geometric SVG crest |
|
||||
|
||||
## Theme comparison
|
||||
|
||||
The three editor palettes follow the modern game's submenu colours. Midnight
|
||||
uses a slate-grey gradient and restrained mint accents, Silver pale silver-blue
|
||||
surfaces and petrol accents, and Matchday graphite surfaces and coral accents.
|
||||
All components consume the inherited palette, including dropdown popups,
|
||||
validation/error text, scrollbars, image stages and crop outlines. The comparison
|
||||
uses the same German `World::demo()` view in each theme.
|
||||
|
||||
| Theme | Clubs | Options | Image editor |
|
||||
|---|---|---|---|
|
||||
| Midnight Glass | [View](clubs-midnight-de.png) | [View](options-midnight-de.png) | [View](image-editor-midnight-de.png) |
|
||||
| Silver Glass | [View](clubs-silver-de.png) | [View](options-silver-de.png) | [View](image-editor-silver-de.png) |
|
||||
| Matchday | [View](clubs-matchday-de.png) | [View](options-matchday-de.png) | [View](image-editor-matchday-de.png) |
|
||||
|
||||
[Previous Midnight view](https://github.com/Weyoune/openbmh/blob/fcf6092063c2354dec400462d5fa0c7dda3afe11/docs/qa/editor-poc/clubs-midnight-de.png)
|
||||
provides the before image for the change from saturated navy to the submenu
|
||||
palette. Data and layout are identical.
|
||||
|
||||
Environment: Debian 13 x86-64; actual SDL2/OpenGL/RmlUI window inside Xvfb,
|
||||
software OpenGL requested with `LIBGL_ALWAYS_SOFTWARE=1`; 1440×900 window.
|
||||
These are native application captures, not HTML/browser mockups.
|
||||
|
||||
Validation performed:
|
||||
|
||||
- `editor_core_tests`: 59 assertions for edit/rollback, revision conflicts,
|
||||
references, dates/scales, roster moves/swaps/order, shared undo/redo/save
|
||||
checkpoint, atomic OBW overwrite, exact image originals, arbitrary SVG/raster
|
||||
transforms, unknown-extension preservation and authenticated MCP HTTP.
|
||||
Individual image edits also verify that shared fallback images and other
|
||||
records remain unchanged.
|
||||
Windows additionally checks a profile directory containing non-ASCII letters.
|
||||
- `tests/editor_gui_smoke.py`: real mouse/keyboard inspector edit; untouched
|
||||
JSON colour field retained; native search focus; shared MCP/native undo/redo;
|
||||
save to OBW. This check caught and fixed RmlUI textarea entity handling and
|
||||
select-initialization refresh loops.
|
||||
- Native theme QA: switch Midnight → Silver → Matchday → Midnight through the
|
||||
actual Options dropdown and Apply button; verify persisted settings and
|
||||
compare rendered body, list and inspector pixels against a fresh startup
|
||||
in each theme. Reopen the editor using the saved preference. Inspect the
|
||||
Options popup, rejected invalid port input, dashboard, players, review,
|
||||
history and image editor in each palette. The rejected input leaves the
|
||||
saved options unchanged. No new platform GUI claim is implied.
|
||||
- Private local checks, whose data is not published here: raw BMH and raw
|
||||
Football Limited import, existing converted Classic OBWs, save/reopen, frozen
|
||||
Classic portrait composition, and the large private merged 32-league world.
|
||||
Structural checks passed; missing biographies/source conflicts remain
|
||||
explicit warnings.
|
||||
- Manifest/table JSON schemas checked against the private Classic-derived and
|
||||
merged-world outputs. This is separate from runtime reference/range checks.
|
||||
|
||||
Reproduce the synthetic view from a configured build:
|
||||
|
||||
```sh
|
||||
OpenBMHEditor --demo --page clubs --screenshot clubs.png --quit-after-ms 1800
|
||||
```
|
||||
|
||||
The synthetic data is generated by `World::demo()`, not a career save. Options
|
||||
files used for captures are local QA profiles and are not included. The image
|
||||
editor captures use the demo's geometric SVG crest. Earlier history also
|
||||
contains a synthetic portrait made from a blue rectangle, circular head and
|
||||
rounded shoulders; no real or AI-generated player photo is used.
|
||||
|
||||
Windows x64/macOS ARM64 build and core/MCP checks are run by the separate
|
||||
**OBW Editor POC** workflow. A CI pass is not a human GUI acceptance test on
|
||||
either platform.
|
||||
|
After Width: | Height: | Size: 134 KiB |
|
After Width: | Height: | Size: 179 KiB |
|
After Width: | Height: | Size: 157 KiB |
|
After Width: | Height: | Size: 131 KiB |
|
After Width: | Height: | Size: 93 KiB |
|
After Width: | Height: | Size: 97 KiB |
|
After Width: | Height: | Size: 103 KiB |
|
After Width: | Height: | Size: 99 KiB |
|
After Width: | Height: | Size: 106 KiB |
|
After Width: | Height: | Size: 115 KiB |
|
After Width: | Height: | Size: 178 KiB |
|
After Width: | Height: | Size: 160 KiB |
@@ -0,0 +1,84 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-only
|
||||
include(FetchContent)
|
||||
set(JSON_BuildTests OFF CACHE BOOL "" FORCE)
|
||||
FetchContent_Declare(editor_json GIT_REPOSITORY https://github.com/nlohmann/json.git
|
||||
GIT_TAG v3.12.0 GIT_SHALLOW TRUE)
|
||||
FetchContent_Declare(editor_http GIT_REPOSITORY https://github.com/yhirose/cpp-httplib.git
|
||||
GIT_TAG v0.63.0 GIT_SHALLOW TRUE SOURCE_SUBDIR no-cmake)
|
||||
set(SDL2IMAGE_INSTALL OFF CACHE BOOL "" FORCE)
|
||||
set(SDL2IMAGE_SAMPLES OFF CACHE BOOL "" FORCE)
|
||||
set(SDL2IMAGE_TESTS OFF CACHE BOOL "" FORCE)
|
||||
set(SDL2IMAGE_VENDORED ON CACHE BOOL "" FORCE)
|
||||
set(SDL2IMAGE_DEPS_SHARED OFF CACHE BOOL "" FORCE)
|
||||
set(SDL2IMAGE_BACKEND_STB ON CACHE BOOL "" FORCE)
|
||||
set(SDL2IMAGE_BACKEND_IMAGEIO OFF CACHE BOOL "" FORCE)
|
||||
set(SDL2IMAGE_BACKEND_WIC OFF CACHE BOOL "" FORCE)
|
||||
foreach(codec AVIF BMP GIF JXL LBM PCX PNM QOI SVG TIF XCF XPM XV)
|
||||
set(SDL2IMAGE_${codec} OFF CACHE BOOL "" FORCE)
|
||||
endforeach()
|
||||
set(SDL2IMAGE_PNG ON CACHE BOOL "" FORCE)
|
||||
set(SDL2IMAGE_JPG ON CACHE BOOL "" FORCE)
|
||||
set(SDL2IMAGE_WEBP ON CACHE BOOL "" FORCE)
|
||||
set(SDL2IMAGE_PNG_SAVE OFF CACHE BOOL "" FORCE)
|
||||
set(SDL2IMAGE_JPG_SAVE OFF CACHE BOOL "" FORCE)
|
||||
FetchContent_Declare(editor_images GIT_REPOSITORY https://github.com/libsdl-org/SDL_image.git
|
||||
GIT_TAG release-2.8.8 GIT_SHALLOW TRUE GIT_SUBMODULES external/libwebp)
|
||||
set(LUNASVG_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE)
|
||||
FetchContent_Declare(editor_svg GIT_REPOSITORY https://github.com/sammycage/lunasvg.git
|
||||
GIT_TAG v3.5.0 GIT_SHALLOW TRUE)
|
||||
set(PUGIXML_BUILD_TESTS OFF CACHE BOOL "" FORCE)
|
||||
set(PUGIXML_BUILD_SHARED_AND_STATIC_LIBS OFF CACHE BOOL "" FORCE)
|
||||
FetchContent_Declare(editor_xml GIT_REPOSITORY https://github.com/zeux/pugixml.git
|
||||
GIT_TAG v1.15 GIT_SHALLOW TRUE)
|
||||
FetchContent_MakeAvailable(editor_json editor_http editor_images editor_svg editor_xml)
|
||||
file(WRITE "${CMAKE_BINARY_DIR}/editor-dependencies.json" "{\n")
|
||||
foreach(component editor_json editor_http editor_images editor_svg editor_xml)
|
||||
file(TO_CMAKE_PATH "${${component}_SOURCE_DIR}" component_path)
|
||||
file(APPEND "${CMAKE_BINARY_DIR}/editor-dependencies.json" "\"${component}\": \"${component_path}\"")
|
||||
if(NOT component STREQUAL "editor_xml")
|
||||
file(APPEND "${CMAKE_BINARY_DIR}/editor-dependencies.json" ",")
|
||||
endif()
|
||||
file(APPEND "${CMAKE_BINARY_DIR}/editor-dependencies.json" "\n")
|
||||
endforeach()
|
||||
file(APPEND "${CMAKE_BINARY_DIR}/editor-dependencies.json" "}\n")
|
||||
|
||||
add_library(bmh_editor_core STATIC archive.cpp world.cpp session.cpp images.cpp options.cpp mcp.cpp)
|
||||
target_include_directories(bmh_editor_core PUBLIC .. ${editor_http_SOURCE_DIR})
|
||||
target_link_libraries(bmh_editor_core PUBLIC 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)
|
||||
if(WIN32)
|
||||
target_link_libraries(bmh_editor_core PRIVATE ws2_32 crypt32)
|
||||
endif()
|
||||
add_executable(openbmh_editor main.cpp ui.cpp)
|
||||
set_target_properties(openbmh_editor PROPERTIES OUTPUT_NAME OpenBMHEditor
|
||||
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}")
|
||||
target_link_libraries(openbmh_editor PRIVATE bmh_editor_core bmh_rmlui nfd::nfd ${BMH_SDL_TARGET})
|
||||
if(MSVC)
|
||||
target_compile_options(bmh_editor_core PRIVATE /W4 /utf-8)
|
||||
target_compile_options(openbmh_editor PRIVATE /utf-8)
|
||||
else()
|
||||
target_compile_options(bmh_editor_core PRIVATE -Wall -Wextra -Wpedantic)
|
||||
endif()
|
||||
if(WIN32)
|
||||
set_target_properties(openbmh_editor PROPERTIES WIN32_EXECUTABLE TRUE)
|
||||
endif()
|
||||
set(editor_assets "${CMAKE_BINARY_DIR}/assets/editor")
|
||||
FetchContent_GetProperties(rmlui)
|
||||
file(MAKE_DIRECTORY "${editor_assets}")
|
||||
foreach(asset editor.rml theme.rcss)
|
||||
configure_file("${CMAKE_SOURCE_DIR}/assets/editor/${asset}" "${editor_assets}/${asset}" COPYONLY)
|
||||
endforeach()
|
||||
foreach(weight Regular Bold)
|
||||
configure_file("${rmlui_SOURCE_DIR}/Samples/assets/LatoLatin-${weight}.ttf"
|
||||
"${editor_assets}/LatoLatin-${weight}.ttf" COPYONLY)
|
||||
endforeach()
|
||||
install(TARGETS openbmh_editor RUNTIME DESTINATION . COMPONENT Editor)
|
||||
install(DIRECTORY "${editor_assets}/" DESTINATION assets/editor COMPONENT Editor)
|
||||
add_executable(editor_core_tests ../../tests/editor_core_tests.cpp)
|
||||
target_link_libraries(editor_core_tests PRIVATE bmh_editor_core)
|
||||
if(MSVC)
|
||||
target_compile_options(editor_core_tests PRIVATE /utf-8)
|
||||
endif()
|
||||
add_test(NAME editor_core_tests COMMAND editor_core_tests)
|
||||
@@ -0,0 +1,326 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#include "editor/archive.hpp"
|
||||
#include "content/digest.hpp"
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <cwctype>
|
||||
#include <fstream>
|
||||
#include <miniz.h>
|
||||
#include <mutex>
|
||||
#include <random>
|
||||
#ifdef _WIN32
|
||||
#define NOMINMAX
|
||||
#include <windows.h>
|
||||
#endif
|
||||
|
||||
namespace bmh::editor {
|
||||
namespace {
|
||||
constexpr uint64_t max_entry = 64ull * 1024 * 1024;
|
||||
constexpr uint64_t max_total = 2ull * 1024 * 1024 * 1024;
|
||||
constexpr size_t max_entries = 100000;
|
||||
void publish(const fs::path &temporary, const fs::path &destination) {
|
||||
#ifdef _WIN32
|
||||
if (!MoveFileExW(temporary.c_str(), destination.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH))
|
||||
throw Error("save_failed", {{"path", utf8(destination)}, {"system", GetLastError()}});
|
||||
#else
|
||||
std::error_code ec;
|
||||
fs::rename(temporary, destination, ec);
|
||||
if (ec)
|
||||
throw Error("save_failed", {{"path", utf8(destination)}, {"system", ec.message()}});
|
||||
#endif
|
||||
}
|
||||
struct Remove {
|
||||
fs::path target;
|
||||
~Remove() {
|
||||
if (!target.empty()) {
|
||||
std::error_code ec;
|
||||
fs::remove_all(target, ec);
|
||||
}
|
||||
}
|
||||
};
|
||||
} // namespace
|
||||
std::string utf8(const fs::path &value) {
|
||||
const auto data = value.generic_u8string();
|
||||
return {data.begin(), data.end()};
|
||||
}
|
||||
fs::path path(std::string_view value) { return fs::path(std::u8string(value.begin(), value.end())); }
|
||||
bool safe_name(std::string_view value) {
|
||||
if (value.empty() || value.front() == '/' || value.find('\\') != value.npos || value.find(':') != value.npos ||
|
||||
value.find('\0') != value.npos || value.back() == '/')
|
||||
return false;
|
||||
const auto relative = path(value);
|
||||
for (const auto &part : relative)
|
||||
if (part == "." || part == ".." || part.empty())
|
||||
return false;
|
||||
return !relative.is_absolute();
|
||||
}
|
||||
std::string new_id(const std::string &prefix) {
|
||||
static std::mutex lock;
|
||||
static std::mt19937_64 random(std::random_device{}());
|
||||
std::lock_guard guard(lock);
|
||||
static const char *digits = "0123456789abcdef";
|
||||
std::string result = prefix;
|
||||
for (int n = 0; n < 2; ++n) {
|
||||
auto number = random();
|
||||
for (int i = 0; i < 16; ++i) {
|
||||
result += digits[number & 15];
|
||||
number >>= 4;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
std::string folded(std::string value) {
|
||||
// UTF-8 byte equality is retained; the small UI search additionally handles
|
||||
// ASCII case without changing authored spelling or source identity.
|
||||
for (char &c : value)
|
||||
if (c >= 'A' && c <= 'Z')
|
||||
c = char(c + ('a' - 'A'));
|
||||
return value;
|
||||
}
|
||||
std::string read_file(const fs::path &file, uint64_t maximum) {
|
||||
std::ifstream source(file, std::ios::binary);
|
||||
if (!source)
|
||||
throw Error("open_failed", {{"path", utf8(file)}});
|
||||
source.seekg(0, std::ios::end);
|
||||
auto size = source.tellg();
|
||||
if (size < 0 || uint64_t(size) > maximum)
|
||||
throw Error("size_limit", {{"path", utf8(file)}});
|
||||
source.seekg(0);
|
||||
std::string bytes(size_t(size), '\0');
|
||||
source.read(bytes.data(), std::streamsize(bytes.size()));
|
||||
if (!source && !bytes.empty())
|
||||
throw Error("open_failed", {{"path", utf8(file)}});
|
||||
return bytes;
|
||||
}
|
||||
void write_atomic(const fs::path &file, std::string_view data, bool overwrite) {
|
||||
if (!overwrite && fs::exists(file))
|
||||
throw Error("destination_exists");
|
||||
if (fs::is_symlink(fs::symlink_status(file)))
|
||||
throw Error("unsafe_path");
|
||||
const auto parent = file.has_parent_path() ? file.parent_path() : fs::path(".");
|
||||
if (!fs::is_directory(parent))
|
||||
throw Error("output_parent_missing");
|
||||
auto temporary = parent / new_id(".openbmh-editor-");
|
||||
Remove cleanup{temporary};
|
||||
{
|
||||
std::ofstream output(temporary, std::ios::binary);
|
||||
output.write(data.data(), std::streamsize(data.size()));
|
||||
output.close();
|
||||
if (!output)
|
||||
throw Error("save_failed");
|
||||
}
|
||||
publish(temporary, file);
|
||||
}
|
||||
|
||||
struct ArchiveStore::Impl {
|
||||
fs::path cache;
|
||||
fs::path root;
|
||||
mutable std::ifstream input;
|
||||
mutable mz_zip_archive zip{};
|
||||
struct Item {
|
||||
uint64_t size;
|
||||
mz_uint index;
|
||||
fs::path file;
|
||||
};
|
||||
std::map<std::string, Item> entries;
|
||||
std::map<std::string, std::shared_ptr<const std::string>> changed;
|
||||
mutable std::mutex mutex;
|
||||
bool zip_open = false;
|
||||
static size_t read_at(void *opaque, mz_uint64 offset, void *data, size_t count) {
|
||||
auto &in = static_cast<Impl *>(opaque)->input;
|
||||
in.clear();
|
||||
in.seekg(std::streamoff(offset));
|
||||
in.read(static_cast<char *>(data), std::streamsize(count));
|
||||
return size_t(in.gcount());
|
||||
}
|
||||
~Impl() {
|
||||
if (zip_open)
|
||||
mz_zip_reader_end(&zip);
|
||||
input.close();
|
||||
if (!cache.empty()) {
|
||||
std::error_code ec;
|
||||
fs::remove_all(cache, ec);
|
||||
}
|
||||
}
|
||||
};
|
||||
ArchiveStore::ArchiveStore() : impl_(std::make_unique<Impl>()) {}
|
||||
ArchiveStore::~ArchiveStore() = default;
|
||||
std::shared_ptr<ArchiveStore> ArchiveStore::open(const fs::path &source) {
|
||||
auto result = std::make_shared<ArchiveStore>();
|
||||
auto &s = *result->impl_;
|
||||
uint64_t total = 0;
|
||||
auto add = [&](std::string name, Impl::Item item) {
|
||||
if (!safe_name(name) || item.size > max_entry || total + item.size > max_total ||
|
||||
s.entries.size() >= max_entries)
|
||||
throw Error("archive_limit", {{"entry", name}});
|
||||
if (!s.entries.emplace(name, std::move(item)).second)
|
||||
throw Error("duplicate_entry", {{"entry", name}});
|
||||
total += item.size;
|
||||
};
|
||||
if (fs::is_symlink(fs::symlink_status(source)))
|
||||
throw Error("unsafe_path");
|
||||
if (fs::is_directory(source)) {
|
||||
const auto original = fs::canonical(source);
|
||||
s.cache = fs::temp_directory_path() / new_id("openbmh-editor-");
|
||||
s.root = s.cache / "world";
|
||||
fs::create_directories(s.root);
|
||||
for (const auto &entry : fs::recursive_directory_iterator(original)) {
|
||||
if (entry.is_symlink())
|
||||
throw Error("unsafe_path");
|
||||
if (entry.is_regular_file()) {
|
||||
const auto relative = entry.path().lexically_relative(original);
|
||||
const auto snapshot = s.root / relative;
|
||||
add(utf8(relative), {entry.file_size(), 0, snapshot});
|
||||
fs::create_directories(snapshot.parent_path());
|
||||
fs::copy_file(entry.path(), snapshot);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (!fs::is_regular_file(source) || fs::file_size(source) > max_total)
|
||||
throw Error("archive_limit");
|
||||
s.cache = fs::temp_directory_path() / new_id("openbmh-editor-");
|
||||
fs::create_directory(s.cache);
|
||||
const auto snapshot = s.cache / "source.obw";
|
||||
fs::copy_file(source, snapshot);
|
||||
s.input.open(snapshot, std::ios::binary);
|
||||
s.zip.m_pRead = Impl::read_at;
|
||||
s.zip.m_pIO_opaque = &s;
|
||||
if (!mz_zip_reader_init(&s.zip, fs::file_size(snapshot), 0))
|
||||
throw Error("invalid_archive");
|
||||
s.zip_open = true;
|
||||
auto count = mz_zip_reader_get_num_files(&s.zip);
|
||||
if (count > max_entries)
|
||||
throw Error("archive_limit");
|
||||
for (mz_uint index = 0; index < count; ++index) {
|
||||
mz_zip_archive_file_stat stat{};
|
||||
if (!mz_zip_reader_file_stat(&s.zip, index, &stat))
|
||||
throw Error("invalid_archive");
|
||||
if (stat.m_is_directory)
|
||||
continue;
|
||||
if (((stat.m_external_attr >> 16) & 0170000) == 0120000)
|
||||
throw Error("unsafe_path");
|
||||
if (stat.m_is_encrypted || !stat.m_is_supported)
|
||||
throw Error("unsupported_archive");
|
||||
add(stat.m_filename, {stat.m_uncomp_size, index, {}});
|
||||
}
|
||||
}
|
||||
if (!s.entries.contains("manifest.json"))
|
||||
throw Error("missing_manifest");
|
||||
return result;
|
||||
}
|
||||
bool ArchiveStore::contains(const std::string &name) const {
|
||||
return impl_->changed.contains(name) || impl_->entries.contains(name);
|
||||
}
|
||||
std::vector<std::string> ArchiveStore::names() const {
|
||||
std::set<std::string> all;
|
||||
for (const auto &[key, _] : impl_->entries)
|
||||
all.insert(key);
|
||||
for (const auto &[key, _] : impl_->changed)
|
||||
all.insert(key);
|
||||
return {all.begin(), all.end()};
|
||||
}
|
||||
uint64_t ArchiveStore::size(const std::string &name) const {
|
||||
if (auto i = impl_->changed.find(name); i != impl_->changed.end())
|
||||
return i->second->size();
|
||||
if (auto i = impl_->entries.find(name); i != impl_->entries.end())
|
||||
return i->second.size;
|
||||
throw Error("missing_asset", {{"path", name}});
|
||||
}
|
||||
std::string ArchiveStore::read(const std::string &name) const {
|
||||
if (auto i = impl_->changed.find(name); i != impl_->changed.end())
|
||||
return *i->second;
|
||||
const auto entry = impl_->entries.find(name);
|
||||
if (entry == impl_->entries.end())
|
||||
throw Error("missing_asset", {{"path", name}});
|
||||
if (!entry->second.file.empty()) {
|
||||
if (fs::is_symlink(fs::symlink_status(entry->second.file)))
|
||||
throw Error("unsafe_path");
|
||||
return read_file(entry->second.file, max_entry);
|
||||
}
|
||||
std::lock_guard guard(impl_->mutex);
|
||||
std::string bytes(size_t(entry->second.size), '\0');
|
||||
if (!mz_zip_reader_extract_to_mem(&impl_->zip, entry->second.index, bytes.data(), bytes.size(), 0))
|
||||
throw Error("invalid_archive", {{"entry", name}});
|
||||
return bytes;
|
||||
}
|
||||
void ArchiveStore::set(const std::string &name, std::shared_ptr<const std::string> bytes) {
|
||||
if (!safe_name(name) || !bytes || bytes->size() > max_entry)
|
||||
throw Error("unsafe_asset");
|
||||
impl_->changed[name] = std::move(bytes);
|
||||
}
|
||||
std::shared_ptr<const std::string> ArchiveStore::overlay(const std::string &name) const {
|
||||
auto i = impl_->changed.find(name);
|
||||
return i == impl_->changed.end() ? nullptr : i->second;
|
||||
}
|
||||
void ArchiveStore::restore(const std::string &name, std::shared_ptr<const std::string> value) {
|
||||
if (value)
|
||||
set(name, std::move(value));
|
||||
else
|
||||
impl_->changed.erase(name);
|
||||
}
|
||||
void ArchiveStore::save(const fs::path &target, const std::map<std::string, std::string> &docs,
|
||||
const std::set<std::string> &excluded) const {
|
||||
if (target.extension() != ".obw")
|
||||
throw Error("obw_only");
|
||||
if (fs::is_symlink(fs::symlink_status(target)))
|
||||
throw Error("unsafe_path");
|
||||
auto parent = target.has_parent_path() ? target.parent_path() : fs::path(".");
|
||||
if (!fs::is_directory(parent))
|
||||
throw Error("output_parent_missing");
|
||||
auto temporary = parent / new_id(".openbmh-editor-");
|
||||
Remove cleanup{temporary};
|
||||
std::ofstream output(temporary, std::ios::binary);
|
||||
if (!output)
|
||||
throw Error("save_failed");
|
||||
mz_zip_archive writer{};
|
||||
writer.m_pIO_opaque = &output;
|
||||
writer.m_pWrite = [](void *opaque, mz_uint64 position, const void *data, size_t count) -> size_t {
|
||||
auto &stream = *static_cast<std::ofstream *>(opaque);
|
||||
stream.seekp(std::streamoff(position));
|
||||
stream.write(static_cast<const char *>(data), std::streamsize(count));
|
||||
return stream ? count : 0;
|
||||
};
|
||||
if (!mz_zip_writer_init_v2(&writer, 0, MZ_ZIP_FLAG_WRITE_ZIP64))
|
||||
throw Error("save_failed");
|
||||
struct Close {
|
||||
mz_zip_archive *p;
|
||||
~Close() { mz_zip_writer_end(p); }
|
||||
} closer{&writer};
|
||||
std::set<std::string> all;
|
||||
for (auto &name : names())
|
||||
all.insert(name);
|
||||
for (auto &[name, _] : docs)
|
||||
all.insert(name);
|
||||
if (all.size() > max_entries)
|
||||
throw Error("archive_limit");
|
||||
uint64_t total = 0;
|
||||
for (const auto &name : all) {
|
||||
if (excluded.contains(name))
|
||||
continue;
|
||||
if (!safe_name(name))
|
||||
throw Error("unsafe_path");
|
||||
auto replacement = docs.find(name);
|
||||
const auto bytes_size = replacement != docs.end() ? replacement->second.size() : size(name);
|
||||
if (bytes_size > max_entry || (total += bytes_size) > max_total)
|
||||
throw Error("archive_limit");
|
||||
auto existing = impl_->entries.find(name);
|
||||
if (replacement == docs.end() && !impl_->changed.contains(name) && impl_->zip_open &&
|
||||
existing != impl_->entries.end()) {
|
||||
std::lock_guard guard(impl_->mutex);
|
||||
if (!mz_zip_writer_add_from_zip_reader(&writer, &impl_->zip, existing->second.index))
|
||||
throw Error("save_failed");
|
||||
} else {
|
||||
auto bytes = replacement != docs.end() ? replacement->second : read(name);
|
||||
const auto level = name.ends_with(".json") ? MZ_BEST_SPEED : MZ_NO_COMPRESSION;
|
||||
if (!mz_zip_writer_add_mem(&writer, name.c_str(), bytes.data(), bytes.size(), level))
|
||||
throw Error("save_failed");
|
||||
}
|
||||
}
|
||||
if (!mz_zip_writer_finalize_archive(&writer))
|
||||
throw Error("save_failed");
|
||||
output.close();
|
||||
if (!output)
|
||||
throw Error("save_failed");
|
||||
publish(temporary, target);
|
||||
}
|
||||
} // namespace bmh::editor
|
||||
@@ -0,0 +1,28 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#pragma once
|
||||
#include "editor/types.hpp"
|
||||
#include <functional>
|
||||
|
||||
namespace bmh::editor {
|
||||
// Asset bytes are read on demand. A private source snapshot permits replacing
|
||||
// the user's own editor file atomically on Windows as well as POSIX systems.
|
||||
class ArchiveStore {
|
||||
public:
|
||||
ArchiveStore();
|
||||
static std::shared_ptr<ArchiveStore> open(const fs::path &);
|
||||
~ArchiveStore();
|
||||
bool contains(const std::string &) const;
|
||||
std::vector<std::string> names() const;
|
||||
uint64_t size(const std::string &) const;
|
||||
std::string read(const std::string &) const;
|
||||
void set(const std::string &, std::shared_ptr<const std::string>);
|
||||
std::shared_ptr<const std::string> overlay(const std::string &) const;
|
||||
void restore(const std::string &, std::shared_ptr<const std::string>);
|
||||
void save(const fs::path &, const std::map<std::string, std::string> &documents,
|
||||
const std::set<std::string> &excluded = {}) const;
|
||||
|
||||
private:
|
||||
struct Impl;
|
||||
std::unique_ptr<Impl> impl_;
|
||||
};
|
||||
} // namespace bmh::editor
|
||||
@@ -0,0 +1,316 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#include "editor/images.hpp"
|
||||
#include <SDL.h>
|
||||
#include <SDL_image.h>
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <functional>
|
||||
#include <limits>
|
||||
#include <lunasvg.h>
|
||||
#include <miniz.h>
|
||||
#include <pugixml.hpp>
|
||||
#include <sstream>
|
||||
|
||||
namespace bmh::editor::images {
|
||||
namespace {
|
||||
constexpr uint64_t maximum_pixels = 32ull * 1024 * 1024;
|
||||
void bounds(int w, int h) {
|
||||
if (w <= 0 || h <= 0 || w > 8192 || h > 8192 || uint64_t(w) * uint64_t(h) > maximum_pixels)
|
||||
throw Error("image_dimensions");
|
||||
}
|
||||
struct Geometry {
|
||||
double angle = 0, x = 0, y = 0, width = 1, height = 1;
|
||||
bool flip_x = false, flip_y = false;
|
||||
explicit Geometry(const Json &input) {
|
||||
const Json value = input.is_null() ? Json::object() : input;
|
||||
if (!value.is_object())
|
||||
throw Error("invalid_transform");
|
||||
angle = value.value("angle", 0.0);
|
||||
flip_x = value.value("flip_x", false);
|
||||
flip_y = value.value("flip_y", false);
|
||||
if (value.contains("crop")) {
|
||||
const auto &crop = value["crop"];
|
||||
x = crop.value("x", 0.0);
|
||||
y = crop.value("y", 0.0);
|
||||
width = crop.value("width", 1.0);
|
||||
height = crop.value("height", 1.0);
|
||||
}
|
||||
if (!std::isfinite(angle) || !std::isfinite(x) || !std::isfinite(y) || !std::isfinite(width) ||
|
||||
!std::isfinite(height) || std::abs(angle) > 360 || x < 0 || y < 0 || width <= 0 || height <= 0 ||
|
||||
x + width > 1.000001 || y + height > 1.000001)
|
||||
throw Error("invalid_transform");
|
||||
}
|
||||
Json json() const {
|
||||
return {{"angle", angle},
|
||||
{"flip_x", flip_x},
|
||||
{"flip_y", flip_y},
|
||||
{"crop", {{"x", x}, {"y", y}, {"width", width}, {"height", height}}}};
|
||||
}
|
||||
};
|
||||
std::pair<double, double> canvas(double w, double h, double angle) {
|
||||
const auto rad = angle * std::acos(-1.0) / 180.0;
|
||||
auto c = std::abs(std::cos(rad)), s = std::abs(std::sin(rad));
|
||||
return {std::ceil(w * c + h * s - 1e-9), std::ceil(w * s + h * c - 1e-9)};
|
||||
}
|
||||
void validate_svg(pugi::xml_node node) {
|
||||
for (auto attr : node.attributes()) {
|
||||
const std::string key = attr.name(), value = attr.value();
|
||||
const auto lower = folded(value);
|
||||
if ((key == "href" || key == "xlink:href") && std::string(node.name()) != "a" && !value.empty() &&
|
||||
value.front() != '#' && !value.starts_with("data:image/"))
|
||||
throw Error("external_svg_resource");
|
||||
if (lower.find("url(") != lower.npos && lower.find("url(#") == lower.npos &&
|
||||
lower.find("url('#") == lower.npos && lower.find("url(\"#") == lower.npos)
|
||||
throw Error("external_svg_resource");
|
||||
}
|
||||
if (std::string(node.name()) == "style") {
|
||||
const std::string css = folded(node.text().as_string());
|
||||
if (css.find("@import") != css.npos || css.find("http:") != css.npos || css.find("https:") != css.npos ||
|
||||
css.find("file:") != css.npos)
|
||||
throw Error("external_svg_resource");
|
||||
}
|
||||
for (auto child : node.children())
|
||||
validate_svg(child);
|
||||
}
|
||||
std::unique_ptr<lunasvg::Document> svg_document(std::string_view bytes) {
|
||||
pugi::xml_document xml;
|
||||
if (!xml.load_buffer(bytes.data(), bytes.size()))
|
||||
throw Error("invalid_image");
|
||||
validate_svg(xml.document_element());
|
||||
auto doc = lunasvg::Document::loadFromData(bytes.data(), bytes.size());
|
||||
if (!doc || doc->width() <= 0 || doc->height() <= 0 || !std::isfinite(doc->width()) ||
|
||||
!std::isfinite(doc->height()))
|
||||
throw Error("invalid_image");
|
||||
return doc;
|
||||
}
|
||||
std::string transform_svg(std::string_view bytes, const Geometry &g, int &width, int &height) {
|
||||
auto source = svg_document(bytes);
|
||||
const double w = source->width(), h = source->height();
|
||||
const auto [cw, ch] = canvas(w, h, g.angle);
|
||||
const auto ow = std::max(1.0, cw * g.width), oh = std::max(1.0, ch * g.height);
|
||||
if (ow > 1000000 || oh > 1000000)
|
||||
throw Error("image_dimensions");
|
||||
width = int(std::round(ow));
|
||||
height = int(std::round(oh));
|
||||
pugi::xml_document original, output;
|
||||
if (!original.load_buffer(bytes.data(), bytes.size()))
|
||||
throw Error("invalid_image");
|
||||
auto root = output.append_child("svg");
|
||||
root.append_attribute("xmlns") = "http://www.w3.org/2000/svg";
|
||||
root.append_attribute("xmlns:xlink") = "http://www.w3.org/1999/xlink";
|
||||
root.append_attribute("width") = ow;
|
||||
root.append_attribute("height") = oh;
|
||||
const auto view = "0 0 " + std::to_string(ow) + ' ' + std::to_string(oh);
|
||||
root.append_attribute("viewBox") = view.c_str();
|
||||
auto group = root.append_child("g");
|
||||
std::ostringstream matrix;
|
||||
matrix.imbue(std::locale::classic());
|
||||
matrix << "translate(" << -g.x * cw << ' ' << -g.y * ch << ") translate(" << cw / 2 << ' ' << ch / 2 << ") rotate("
|
||||
<< g.angle << ") scale(" << (g.flip_x ? -1 : 1) << ' ' << (g.flip_y ? -1 : 1) << ") translate(" << -w / 2
|
||||
<< ' ' << -h / 2 << ')';
|
||||
group.append_attribute("transform") = matrix.str().c_str();
|
||||
auto child = group.append_copy(original.document_element());
|
||||
if (!child.attribute("width"))
|
||||
child.append_attribute("width");
|
||||
if (!child.attribute("height"))
|
||||
child.append_attribute("height");
|
||||
child.attribute("width") = w;
|
||||
child.attribute("height") = h;
|
||||
std::ostringstream serialized;
|
||||
output.save(serialized, "", pugi::format_raw, pugi::encoding_utf8);
|
||||
return serialized.str();
|
||||
}
|
||||
double kernel(double x) {
|
||||
x = std::abs(x);
|
||||
if (x <= 1)
|
||||
return (1.5 * x - 2.5) * x * x + 1;
|
||||
if (x < 2)
|
||||
return ((-0.5 * x + 2.5) * x - 4) * x + 2;
|
||||
return 0;
|
||||
}
|
||||
void sample(const Raster &source, double x, double y, uint8_t *destination) {
|
||||
const int ix = int(std::floor(x)), iy = int(std::floor(y));
|
||||
double alpha = 0;
|
||||
std::array<double, 3> color{};
|
||||
for (int j = iy - 1; j <= iy + 2; ++j)
|
||||
for (int i = ix - 1; i <= ix + 2; ++i) {
|
||||
if (i < 0 || j < 0 || i >= source.width || j >= source.height)
|
||||
continue;
|
||||
const auto *pixel = source.pixels.data() + (size_t(j) * source.width + i) * 4;
|
||||
const double weight = kernel(x - i) * kernel(y - j);
|
||||
const double a = pixel[3] / 255.0;
|
||||
alpha += weight * a;
|
||||
for (int c = 0; c < 3; ++c)
|
||||
color[c] += pixel[c] * a * weight;
|
||||
}
|
||||
for (int c = 0; c < 3; ++c)
|
||||
destination[c] = alpha > 1e-8 ? uint8_t(std::clamp(std::round(color[c] / alpha), 0.0, 255.0)) : 0;
|
||||
destination[3] = uint8_t(std::clamp(std::round(alpha * 255), 0.0, 255.0));
|
||||
}
|
||||
Raster rotate_crop(const Raster &source, const Geometry &g, int maximum = 8192) {
|
||||
const auto [cw, ch] = canvas(source.width, source.height, g.angle);
|
||||
double ow = std::max(1.0, std::round(cw * g.width)), oh = std::max(1.0, std::round(ch * g.height));
|
||||
const double factor = std::min(1.0, maximum / std::max(ow, oh));
|
||||
Raster result{std::max(1, int(std::round(ow * factor))), std::max(1, int(std::round(oh * factor))), {}};
|
||||
bounds(result.width, result.height);
|
||||
result.pixels.resize(size_t(result.width) * result.height * 4);
|
||||
const auto rad = g.angle * std::acos(-1.0) / 180.0;
|
||||
const auto cosine = std::cos(rad), sine = std::sin(rad);
|
||||
for (int y = 0; y < result.height; ++y)
|
||||
for (int x = 0; x < result.width; ++x) {
|
||||
double dx = (x + .5) * ow / result.width + g.x * cw - cw / 2;
|
||||
double dy = (y + .5) * oh / result.height + g.y * ch - ch / 2;
|
||||
double sx = cosine * dx + sine * dy, sy = -sine * dx + cosine * dy;
|
||||
if (g.flip_x)
|
||||
sx = -sx;
|
||||
if (g.flip_y)
|
||||
sy = -sy;
|
||||
sample(source, sx + source.width / 2.0 - .5, sy + source.height / 2.0 - .5,
|
||||
result.pixels.data() + (size_t(y) * result.width + x) * 4);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
void be32(std::string &data, uint32_t n) {
|
||||
for (int shift = 24; shift >= 0; shift -= 8)
|
||||
data += char(n >> shift);
|
||||
}
|
||||
void chunk(std::string &out, const char *type, const std::string &data) {
|
||||
be32(out, uint32_t(data.size()));
|
||||
const auto start = out.size();
|
||||
out.append(type, 4);
|
||||
out += data;
|
||||
be32(out, uint32_t(mz_crc32(0, reinterpret_cast<const unsigned char *>(out.data() + start), data.size() + 4)));
|
||||
}
|
||||
} // namespace
|
||||
Raster decode(std::string_view bytes, const std::string &extension, int vector_size) {
|
||||
if (bytes.size() > 64ull * 1024 * 1024)
|
||||
throw Error("size_limit");
|
||||
if (folded(extension) == ".svg" || extension == "svg") {
|
||||
auto doc = svg_document(bytes);
|
||||
const double scale = vector_size / std::max(doc->width(), doc->height());
|
||||
auto bitmap = doc->renderToBitmap(std::max(1, int(std::round(doc->width() * scale))),
|
||||
std::max(1, int(std::round(doc->height() * scale))));
|
||||
if (bitmap.isNull())
|
||||
throw Error("invalid_image");
|
||||
bitmap.convertToRGBA();
|
||||
Raster result{bitmap.width(), bitmap.height(), {}};
|
||||
bounds(result.width, result.height);
|
||||
result.pixels.resize(size_t(result.width) * result.height * 4);
|
||||
for (int y = 0; y < result.height; ++y)
|
||||
std::memcpy(result.pixels.data() + size_t(y) * result.width * 4,
|
||||
bitmap.data() + size_t(y) * bitmap.stride(), size_t(result.width) * 4);
|
||||
return result;
|
||||
}
|
||||
auto *stream = SDL_RWFromConstMem(bytes.data(), int(bytes.size()));
|
||||
if (!stream)
|
||||
throw Error("invalid_image");
|
||||
SDL_Surface *loaded = IMG_Load_RW(stream, 1);
|
||||
if (!loaded)
|
||||
throw Error("invalid_image", {{"detail", IMG_GetError()}});
|
||||
struct Free {
|
||||
SDL_Surface *p;
|
||||
~Free() { SDL_FreeSurface(p); }
|
||||
} source{loaded};
|
||||
bounds(loaded->w, loaded->h);
|
||||
SDL_Surface *converted = SDL_ConvertSurfaceFormat(loaded, SDL_PIXELFORMAT_RGBA32, 0);
|
||||
if (!converted)
|
||||
throw Error("invalid_image");
|
||||
Free rgba{converted};
|
||||
Raster result{converted->w, converted->h, {}};
|
||||
result.pixels.resize(size_t(result.width) * result.height * 4);
|
||||
for (int y = 0; y < result.height; ++y)
|
||||
std::memcpy(result.pixels.data() + size_t(y) * result.width * 4,
|
||||
static_cast<const uint8_t *>(converted->pixels) + size_t(y) * converted->pitch,
|
||||
size_t(result.width) * 4);
|
||||
return result;
|
||||
}
|
||||
std::string encode_png(const Raster &image) {
|
||||
bounds(image.width, image.height);
|
||||
if (image.pixels.size() != size_t(image.width) * image.height * 4)
|
||||
throw Error("invalid_image");
|
||||
std::string result("\x89PNG\r\n\x1a\n", 8), header;
|
||||
be32(header, uint32_t(image.width));
|
||||
be32(header, uint32_t(image.height));
|
||||
header.append("\x08\x06\0\0\0", 5);
|
||||
chunk(result, "IHDR", header);
|
||||
std::string scanlines;
|
||||
scanlines.reserve((size_t(image.width) * 4 + 1) * image.height);
|
||||
for (int y = 0; y < image.height; ++y) {
|
||||
scanlines += '\0';
|
||||
scanlines.append(reinterpret_cast<const char *>(image.pixels.data() + size_t(y) * image.width * 4),
|
||||
size_t(image.width) * 4);
|
||||
}
|
||||
mz_ulong size = mz_compressBound(scanlines.size());
|
||||
std::string packed(size, '\0');
|
||||
if (mz_compress2(reinterpret_cast<unsigned char *>(packed.data()), &size,
|
||||
reinterpret_cast<const unsigned char *>(scanlines.data()), scanlines.size(),
|
||||
MZ_BEST_SPEED) != MZ_OK)
|
||||
throw Error("image_encode_failed");
|
||||
packed.resize(size);
|
||||
chunk(result, "IDAT", packed);
|
||||
chunk(result, "IEND", {});
|
||||
return result;
|
||||
}
|
||||
Result transform(std::string_view original, const std::string &extension, const Json &recipe) {
|
||||
Geometry g(recipe);
|
||||
Result result;
|
||||
result.recipe = g.json();
|
||||
if (g.angle == 0 && !g.flip_x && !g.flip_y && g.x == 0 && g.y == 0 && g.width == 1 && g.height == 1) {
|
||||
// Import without an edit preserves the exact source pixels and codec.
|
||||
auto source = decode(original, extension);
|
||||
result.bytes = original;
|
||||
result.extension = extension.starts_with('.') ? extension : '.' + extension;
|
||||
if (result.extension == ".svg") {
|
||||
auto svg = svg_document(original);
|
||||
result.width = int(std::round(svg->width()));
|
||||
result.height = int(std::round(svg->height()));
|
||||
} else {
|
||||
result.width = source.width;
|
||||
result.height = source.height;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
if (folded(extension) == ".svg" || extension == "svg") {
|
||||
result.bytes = transform_svg(original, g, result.width, result.height);
|
||||
result.extension = ".svg";
|
||||
} else {
|
||||
auto source = decode(original, extension);
|
||||
auto output = rotate_crop(source, g);
|
||||
result.width = output.width;
|
||||
result.height = output.height;
|
||||
result.extension = ".png";
|
||||
result.bytes = encode_png(output);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
Raster preview(std::string_view bytes, const std::string &extension, const Json &recipe, int maximum) {
|
||||
Geometry g(recipe);
|
||||
if (folded(extension) == ".svg" || extension == "svg") {
|
||||
int w, h;
|
||||
auto svg = transform_svg(bytes, g, w, h);
|
||||
return decode(svg, ".svg", maximum);
|
||||
}
|
||||
return rotate_crop(decode(bytes, extension), g, maximum);
|
||||
}
|
||||
std::string base64(std::string_view bytes) {
|
||||
static const char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
std::string result;
|
||||
for (size_t i = 0; i < bytes.size(); i += 3) {
|
||||
uint32_t value = uint8_t(bytes[i]) << 16;
|
||||
if (i + 1 < bytes.size())
|
||||
value |= uint8_t(bytes[i + 1]) << 8;
|
||||
if (i + 2 < bytes.size())
|
||||
value |= uint8_t(bytes[i + 2]);
|
||||
result += alphabet[(value >> 18) & 63];
|
||||
result += alphabet[(value >> 12) & 63];
|
||||
result += i + 1 < bytes.size() ? alphabet[(value >> 6) & 63] : '=';
|
||||
result += i + 2 < bytes.size() ? alphabet[value & 63] : '=';
|
||||
}
|
||||
return result;
|
||||
}
|
||||
std::string silhouette() {
|
||||
return R"(<svg xmlns="http://www.w3.org/2000/svg" width="180" height="180" viewBox="0 0 180 180"><rect width="180" height="180" rx="24" fill="#293c4c"/><circle cx="90" cy="62" r="30" fill="#91acba"/><path d="M26 180v-27c0-35 25-50 64-50s64 15 64 50v27" fill="#91acba"/></svg>)";
|
||||
}
|
||||
} // namespace bmh::editor::images
|
||||
@@ -0,0 +1,22 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#pragma once
|
||||
#include "editor/types.hpp"
|
||||
#include <cstdint>
|
||||
|
||||
namespace bmh::editor::images {
|
||||
struct Raster {
|
||||
int width = 0, height = 0;
|
||||
std::vector<uint8_t> pixels;
|
||||
};
|
||||
struct Result {
|
||||
std::string bytes, extension;
|
||||
int width = 0, height = 0;
|
||||
Json recipe;
|
||||
};
|
||||
Raster decode(std::string_view bytes, const std::string &extension, int vector_size = 1024);
|
||||
std::string encode_png(const Raster &);
|
||||
Result transform(std::string_view original, const std::string &extension, const Json &recipe);
|
||||
Raster preview(std::string_view original, const std::string &extension, const Json &recipe, int maximum = 1024);
|
||||
std::string base64(std::string_view);
|
||||
std::string silhouette();
|
||||
} // namespace bmh::editor::images
|
||||
@@ -0,0 +1,157 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#include "editor/ui.hpp"
|
||||
#include <SDL.h>
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <csignal>
|
||||
#include <iostream>
|
||||
#include <thread>
|
||||
|
||||
namespace {
|
||||
std::atomic<bool> stopped{false};
|
||||
void stop(int) { stopped = true; }
|
||||
} // namespace
|
||||
int main(int argc, char **argv) {
|
||||
using namespace bmh::editor;
|
||||
std::string language = "de";
|
||||
try {
|
||||
bool headless = false, serve = false, stdio = false, demo = false, blank = false, validate = false,
|
||||
print = false;
|
||||
fs::path input, output, settings, script;
|
||||
UiConfig ui;
|
||||
int port = -1;
|
||||
for (int i = 1; i < argc; ++i) {
|
||||
std::string arg = argv[i];
|
||||
auto next = [&]() -> std::string {
|
||||
if (++i >= argc)
|
||||
throw Error("invalid_change", {{"argument", arg}});
|
||||
return argv[i];
|
||||
};
|
||||
if (arg == "--headless")
|
||||
headless = true;
|
||||
else if (arg == "--serve")
|
||||
serve = headless = true;
|
||||
else if (arg == "--stdio-mcp")
|
||||
stdio = headless = true;
|
||||
else if (arg == "--open")
|
||||
input = path(next());
|
||||
else if (arg == "--output")
|
||||
output = path(next());
|
||||
else if (arg == "--settings")
|
||||
settings = path(next());
|
||||
else if (arg == "--commands")
|
||||
script = path(next());
|
||||
else if (arg == "--mcp-port")
|
||||
port = std::stoi(next());
|
||||
else if (arg == "--demo")
|
||||
demo = true;
|
||||
else if (arg == "--new")
|
||||
blank = true;
|
||||
else if (arg == "--validate")
|
||||
validate = true;
|
||||
else if (arg == "--print-mcp-config")
|
||||
print = true;
|
||||
else if (arg == "--assets")
|
||||
ui.assets = path(next());
|
||||
else if (arg == "--screenshot")
|
||||
ui.screenshot = path(next());
|
||||
else if (arg == "--page")
|
||||
ui.page = next();
|
||||
else if (arg == "--quit-after-ms")
|
||||
ui.quit_after_ms = std::stoi(next());
|
||||
else if (arg == "--help") {
|
||||
std::cout << "OpenBMHEditor [--open world.obw|installation] [--demo|--new]\n"
|
||||
" [--settings file] [--assets directory] [--page "
|
||||
"clubs|players|...]\n"
|
||||
" [--headless --validate] [--output world.obw] [--commands "
|
||||
"script.json]\n"
|
||||
" [--serve --mcp-port 8765] [--stdio-mcp] "
|
||||
"[--print-mcp-config]\n";
|
||||
return 0;
|
||||
} else if (!arg.starts_with('-') && input.empty())
|
||||
input = path(arg);
|
||||
else
|
||||
throw Error("invalid_change", {{"argument", arg}});
|
||||
}
|
||||
auto options = Options::load(settings);
|
||||
language = options.language;
|
||||
if (port >= 0) {
|
||||
options.mcp_port = port;
|
||||
options.mcp_enabled = true;
|
||||
}
|
||||
Session session;
|
||||
if (!input.empty())
|
||||
session.execute("open", {{"path", utf8(input)}});
|
||||
else if (demo || blank)
|
||||
session.execute(demo ? "demo" : "new");
|
||||
if (!script.empty()) {
|
||||
const auto actions = Json::parse(read_file(script, 8 * 1024 * 1024));
|
||||
if (!actions.is_array())
|
||||
throw Error("invalid_change");
|
||||
for (const auto &action : actions) {
|
||||
auto result = session.execute(str(action, "command"), action.value("args", Json::object()));
|
||||
if (headless && !stdio)
|
||||
std::cout << result.dump() << '\n';
|
||||
}
|
||||
}
|
||||
bool has_errors = false;
|
||||
if (validate) {
|
||||
auto result = session.execute("validate");
|
||||
for (auto &row : result["diagnostics"])
|
||||
if (row["severity"] == "error")
|
||||
has_errors = true;
|
||||
if (headless && !stdio)
|
||||
std::cout << result.dump() << '\n';
|
||||
}
|
||||
if (!output.empty())
|
||||
session.execute("save", {{"path", utf8(output)}});
|
||||
McpServer server(session);
|
||||
if (stdio) {
|
||||
std::string line;
|
||||
while (std::getline(std::cin, line)) {
|
||||
try {
|
||||
auto reply = server.dispatch(Json::parse(line));
|
||||
if (!reply.is_null())
|
||||
std::cout << reply.dump() << std::endl;
|
||||
} catch (const std::exception &) {
|
||||
std::cout << "{\"jsonrpc\":\"2.0\",\"id\":null,\"error\":{\"code\":-"
|
||||
"32700,\"message\":\"Parse error\"}}"
|
||||
<< std::endl;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
if (serve || !headless) {
|
||||
try {
|
||||
server.start(options);
|
||||
} catch (const Error &e) {
|
||||
std::cerr << tr(language, e.code) << '\n';
|
||||
if (serve)
|
||||
throw;
|
||||
}
|
||||
}
|
||||
if (print)
|
||||
std::cout << server.connection(options).dump(2) << '\n';
|
||||
if (serve) {
|
||||
std::cerr << "OpenBMH Editor MCP: http://127.0.0.1:" << server.port() << "/mcp\n";
|
||||
std::signal(SIGINT, stop);
|
||||
std::signal(SIGTERM, stop);
|
||||
while (!stopped)
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(80));
|
||||
} else if (!headless) {
|
||||
if (ui.assets.empty()) {
|
||||
char *base = SDL_GetBasePath();
|
||||
ui.assets = (base ? path(base) : fs::absolute(path(argv[0])).parent_path()) / "assets/editor";
|
||||
SDL_free(base);
|
||||
}
|
||||
return run_ui(session, options, server, ui);
|
||||
}
|
||||
return has_errors ? 2 : 0;
|
||||
} catch (const Error &e) {
|
||||
std::cerr << Json{{"error", e.code}, {"message", tr(language, e.code)}, {"details", e.details}}.dump() << '\n';
|
||||
return 1;
|
||||
} catch (const std::exception &e) {
|
||||
std::cerr << tr(language, "error") << ": " << e.what() << '\n';
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,357 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#include "editor/mcp.hpp"
|
||||
#include <atomic>
|
||||
#include <httplib.h>
|
||||
#include <thread>
|
||||
|
||||
namespace bmh::editor {
|
||||
namespace {
|
||||
Json schema(Json properties = Json::object(), Json required = Json::array()) {
|
||||
if (properties.is_null())
|
||||
properties = Json::object();
|
||||
if (required.is_null())
|
||||
required = Json::array();
|
||||
return {{"type", "object"}, {"properties", properties}, {"required", required}, {"additionalProperties", false}};
|
||||
}
|
||||
Json field(const char *type, const char *description = "") { return {{"type", type}, {"description", description}}; }
|
||||
Json rpc_error(const Json &id, int code, const std::string &message, Json data = Json::object()) {
|
||||
return {{"jsonrpc", "2.0"}, {"id", id}, {"error", {{"code", code}, {"message", message}, {"data", data}}}};
|
||||
}
|
||||
bool local_authority(const std::string &host) {
|
||||
for (auto name : {"127.0.0.1", "localhost", "[::1]"}) {
|
||||
const std::string base(name);
|
||||
if (host == base)
|
||||
return true;
|
||||
if (host.starts_with(base + ':')) {
|
||||
const auto port = host.substr(base.size() + 1);
|
||||
if (!port.empty() && port.find_first_not_of("0123456789") == port.npos)
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
bool local_origin(std::string value) {
|
||||
if (value.starts_with("http://"))
|
||||
value.erase(0, 7);
|
||||
else if (value.starts_with("https://"))
|
||||
value.erase(0, 8);
|
||||
else
|
||||
return false;
|
||||
return local_authority(value);
|
||||
}
|
||||
bool equal_secret(const std::string &a, const std::string &b) {
|
||||
if (a.size() != b.size())
|
||||
return false;
|
||||
unsigned difference = 0;
|
||||
for (size_t i = 0; i < a.size(); ++i)
|
||||
difference |= unsigned(a[i] ^ b[i]);
|
||||
return difference == 0;
|
||||
}
|
||||
const std::map<std::string, std::string> commands{{"editor_info", "info"},
|
||||
{"editor_open", "open"},
|
||||
{"editor_new", "new"},
|
||||
{"editor_list", "list"},
|
||||
{"editor_get", "get"},
|
||||
{"editor_apply", "apply"},
|
||||
{"editor_validate", "validate"},
|
||||
{"editor_rules", "rules"},
|
||||
{"editor_save", "save"},
|
||||
{"editor_undo", "undo"},
|
||||
{"editor_redo", "redo"},
|
||||
{"editor_history", "history"},
|
||||
{"editor_roster_move", "roster.move"},
|
||||
{"editor_roster_swap", "roster.swap"},
|
||||
{"editor_roster_order", "roster.order"},
|
||||
{"editor_review_resolve", "review.resolve"},
|
||||
{"editor_image_import", "asset.import"},
|
||||
{"editor_image_edit", "asset.edit"},
|
||||
{"editor_image_preview", "asset.preview"},
|
||||
{"editor_image_export", "asset.export"}};
|
||||
} // namespace
|
||||
struct McpServer::Impl {
|
||||
explicit Impl(Session &value) : session(value) {}
|
||||
Session &session;
|
||||
std::unique_ptr<httplib::Server> http;
|
||||
std::thread worker;
|
||||
std::atomic<bool> active{false};
|
||||
int port = 0;
|
||||
std::string token;
|
||||
};
|
||||
McpServer::McpServer(Session &s) : impl_(std::make_unique<Impl>(s)) {}
|
||||
McpServer::~McpServer() { stop(); }
|
||||
int McpServer::port() const { return impl_->port; }
|
||||
bool McpServer::running() const { return impl_->active; }
|
||||
void McpServer::stop() {
|
||||
if (impl_->http)
|
||||
impl_->http->stop();
|
||||
if (impl_->worker.joinable())
|
||||
impl_->worker.join();
|
||||
impl_->active = false;
|
||||
impl_->http.reset();
|
||||
impl_->port = 0;
|
||||
}
|
||||
Json McpServer::connection(const Options &options) const {
|
||||
return {{"mcpServers",
|
||||
{{"openbmh-editor",
|
||||
{{"type", "http"},
|
||||
{"url", "http://127.0.0.1:" + std::to_string(port()) + "/mcp"},
|
||||
{"headers", {{"Authorization", "Bearer " + options.token}}}}}}}};
|
||||
}
|
||||
Json McpServer::tools() {
|
||||
Json result = Json::array();
|
||||
const auto revision = field("integer", "Optional optimistic concurrency guard; use revision "
|
||||
"from editor_info/get.");
|
||||
const auto id = field("string", "Stable world identifier; never an array index.");
|
||||
const auto table = field("string", "nations, competitions, clubs, players, stadiums, staff, "
|
||||
"assets, review, or read-only preserved tables.");
|
||||
auto add = [&](const char *name, const char *description, Json properties, Json required = Json::array(),
|
||||
bool read_only = false) {
|
||||
result.push_back({{"name", name},
|
||||
{"description", description},
|
||||
{"inputSchema", schema(properties, required)},
|
||||
{"annotations",
|
||||
{{"readOnlyHint", read_only}, {"destructiveHint", !read_only}, {"openWorldHint", false}}}});
|
||||
};
|
||||
add("editor_info",
|
||||
"Current world, counts, dirty flag, monotonic revision and undo/redo "
|
||||
"state.",
|
||||
{}, {}, true);
|
||||
add("editor_open",
|
||||
"Open OBW archive, unpacked world, or legacy BMH/FLTD installation. "
|
||||
"Refuses unsaved replacement unless discard=true.",
|
||||
{{"path", field("string")},
|
||||
{"start_date", field("string")},
|
||||
{"discard", field("boolean")},
|
||||
{"expected_revision", revision}},
|
||||
{"path"});
|
||||
add("editor_new", "Create a blank editor world; never writes legacy files.",
|
||||
{{"title", field("string")}, {"discard", field("boolean")}, {"expected_revision", revision}});
|
||||
add("editor_list",
|
||||
"Search, filter, sort and page rows. Maximum page size 200; no data is "
|
||||
"truncated on disk.",
|
||||
{{"table", table},
|
||||
{"search", field("string")},
|
||||
{"nation", id},
|
||||
{"competition", id},
|
||||
{"team", id},
|
||||
{"role", field("string")},
|
||||
{"offset", field("integer")},
|
||||
{"limit", field("integer")},
|
||||
{"sort", field("string")},
|
||||
{"descending", field("boolean")},
|
||||
{"unresolved_only", field("boolean")}},
|
||||
{"table"}, true);
|
||||
add("editor_get", "Read a complete row, including preserved extensions and sources.",
|
||||
{{"table", table}, {"id", id}}, {"table", "id"}, true);
|
||||
add("editor_apply",
|
||||
"Atomic undoable transaction, max 5000 changes. Each change: table, "
|
||||
"op=create/update/delete, id. Create has data/name; update has set {JSON "
|
||||
"pointer:value}, unset [JSON pointer]. IDs are immutable. References and "
|
||||
"declared attribute ranges are checked before commit.",
|
||||
{{"changes", {{"type", "array"}, {"items", {{"type", "object"}}}, {"maxItems", 5000}}},
|
||||
{"expected_revision", revision}},
|
||||
{"changes"});
|
||||
add("editor_validate", "Structural errors plus non-blocking missing/source warnings.", {}, {}, true);
|
||||
add("editor_rules",
|
||||
"Read attribute systems and their actual ranges. Do not guess an "
|
||||
"attribute scale.",
|
||||
{}, {}, true);
|
||||
add("editor_history", "Shared GUI/MCP transaction history.", {}, {}, true);
|
||||
add("editor_save",
|
||||
"Atomically save only a new-format .obw. A Classic source requires a new "
|
||||
"filename. This editor profile is not executable in Classic 0.2.",
|
||||
{{"path", field("string")}, {"expected_revision", revision}});
|
||||
for (auto name : {"editor_undo", "editor_redo"})
|
||||
add(name, "Undo/redo one shared transaction.", {{"expected_revision", revision}});
|
||||
add("editor_roster_move", "Move one player to a club, or null for an explicitly chosen free agent.",
|
||||
{{"player", id},
|
||||
{"team", {{"type", {"string", "null"}}}},
|
||||
{"number", field("integer")},
|
||||
{"expected_revision", revision}},
|
||||
{"player", "team"});
|
||||
add("editor_roster_swap",
|
||||
"Exchange club, shirt number and squad order between two players "
|
||||
"atomically.",
|
||||
{{"first", id}, {"second", id}, {"expected_revision", revision}}, {"first", "second"});
|
||||
add("editor_roster_order",
|
||||
"Set complete club squad order; every assigned player must occur exactly "
|
||||
"once.",
|
||||
{{"team", id}, {"players", {{"type", "array"}, {"items", field("string")}}}, {"expected_revision", revision}},
|
||||
{"team", "players"});
|
||||
add("editor_review_resolve",
|
||||
"Choose a recorded source alternative and update its linked entity. "
|
||||
"Original claims remain preserved.",
|
||||
{{"id", id}, {"choice", field("integer")}, {"expected_revision", revision}}, {"id", "choice"});
|
||||
const auto crop = schema(
|
||||
{{"x", field("number")}, {"y", field("number")}, {"width", field("number")}, {"height", field("number")}});
|
||||
const auto transform = schema(
|
||||
{{"angle", field("number")}, {"flip_x", field("boolean")}, {"flip_y", field("boolean")}, {"crop", crop}});
|
||||
add("editor_image_import",
|
||||
"Import PNG/JPEG/WebP/SVG with optional arbitrary rotation, mirror, crop "
|
||||
"(normalized on the rotated canvas). Preserves source and recipe; "
|
||||
"identity import preserves exact bytes. target={table,id,field} "
|
||||
"optionally assigns the logical key.",
|
||||
{{"file", field("string")},
|
||||
{"key", id},
|
||||
{"target", field("object")},
|
||||
{"transform", transform},
|
||||
{"expected_revision", revision}},
|
||||
{"file"});
|
||||
add("editor_image_edit",
|
||||
"Re-edit an existing image using its preserved original. No repeated "
|
||||
"resampling. Optional source_key clones that source into key; target assigns it to one entity without changing "
|
||||
"other users of a shared fallback.",
|
||||
{{"key", id},
|
||||
{"source_key", id},
|
||||
{"target", field("object")},
|
||||
{"transform", transform},
|
||||
{"expected_revision", revision}},
|
||||
{"key", "transform"});
|
||||
add("editor_image_preview", "Return a PNG preview as an MCP image content block.",
|
||||
{{"key", id}, {"transform", transform}}, {"key"}, true);
|
||||
add("editor_image_export", "Export an image as PNG to an explicit filesystem path.",
|
||||
{{"key", id}, {"path", field("string")}}, {"key", "path"});
|
||||
return result;
|
||||
}
|
||||
Json McpServer::dispatch(const Json &request) {
|
||||
if (!request.is_object())
|
||||
return rpc_error(nullptr, -32600, "Invalid request");
|
||||
const auto id = request.value("id", Json());
|
||||
if (!request.is_object() || str(request, "jsonrpc") != "2.0" || !request.contains("method") ||
|
||||
!request["method"].is_string() || (request.contains("id") && !id.is_string() && !id.is_number_integer()))
|
||||
return rpc_error(id, -32600, "Invalid request");
|
||||
const auto method = str(request, "method");
|
||||
if (!request.contains("id"))
|
||||
return Json();
|
||||
const auto params = request.value("params", Json::object());
|
||||
if (!params.is_object())
|
||||
return rpc_error(id, -32602, "Invalid parameters");
|
||||
Json result;
|
||||
if (method == "initialize") {
|
||||
auto version = str(params, "protocolVersion");
|
||||
if (version != "2025-06-18")
|
||||
version = "2025-11-25";
|
||||
result = {{"protocolVersion", version},
|
||||
{"capabilities", {{"tools", {{"listChanged", false}}}}},
|
||||
{"serverInfo", {{"name", "OpenBMH Editor"}, {"version", "0.1.0-poc"}}},
|
||||
{"instructions", "Edits share the native editor's undo history. Read rules for real "
|
||||
"attribute ranges. Save only OBW editor worlds. These are not Classic "
|
||||
"0.2 playable packages."}};
|
||||
} else if (method == "ping")
|
||||
result = Json::object();
|
||||
else if (method == "tools/list")
|
||||
result = {{"tools", tools()}};
|
||||
else if (method == "tools/call") {
|
||||
auto name = str(params, "name");
|
||||
if (!commands.contains(name))
|
||||
return rpc_error(id, -32602, "Unknown tool");
|
||||
auto args = params.value("arguments", Json::object());
|
||||
if (!args.is_object())
|
||||
return rpc_error(id, -32602, "Arguments must be an object");
|
||||
try {
|
||||
auto response = impl_->session.execute(commands.at(name), args);
|
||||
if (name == "editor_image_preview") {
|
||||
result = {{"content",
|
||||
Json::array({{{"type", "image"}, {"mimeType", "image/png"}, {"data", response["data"]}}})},
|
||||
{"isError", false}};
|
||||
} else
|
||||
result = {{"content", Json::array({{{"type", "text"}, {"text", response.dump()}}})},
|
||||
{"structuredContent", response.is_object() ? response : Json{{"items", response}}},
|
||||
{"isError", false}};
|
||||
} catch (const Error &e) {
|
||||
Json detail{{"code", e.code}, {"details", e.details}};
|
||||
result = {{"content", Json::array({{{"type", "text"}, {"text", detail.dump()}}})}, {"isError", true}};
|
||||
} catch (const std::exception &) {
|
||||
result = {{"content",
|
||||
Json::array({{{"type", "text"}, {"text", "Invalid tool arguments or inaccessible file."}}})},
|
||||
{"isError", true}};
|
||||
}
|
||||
} else
|
||||
return rpc_error(id, -32601, "Method not found");
|
||||
return {{"jsonrpc", "2.0"}, {"id", id}, {"result", result}};
|
||||
}
|
||||
void McpServer::start(const Options &options) {
|
||||
stop();
|
||||
if (!options.mcp_enabled)
|
||||
return;
|
||||
impl_->token = options.token;
|
||||
auto server = std::make_unique<httplib::Server>();
|
||||
server->set_payload_max_length(8 * 1024 * 1024);
|
||||
server->set_read_timeout(10, 0);
|
||||
server->set_write_timeout(30, 0);
|
||||
server->new_task_queue = [] { return new httplib::ThreadPool(2); };
|
||||
auto authorized = [this](const httplib::Request &request, httplib::Response &response) {
|
||||
response.set_header("Cache-Control", "no-store");
|
||||
if (!local_authority(request.get_header_value("Host")) ||
|
||||
(request.has_header("Origin") && !local_origin(request.get_header_value("Origin")))) {
|
||||
response.status = 403;
|
||||
return false;
|
||||
}
|
||||
if (!equal_secret(request.get_header_value("Authorization"), "Bearer " + impl_->token)) {
|
||||
response.status = 401;
|
||||
response.set_header("WWW-Authenticate", "Bearer");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
server->Post("/mcp", [this, authorized](const httplib::Request &request, httplib::Response &response) {
|
||||
if (!authorized(request, response))
|
||||
return;
|
||||
if (!request.get_header_value("Content-Type").starts_with("application/json")) {
|
||||
response.status = 415;
|
||||
return;
|
||||
}
|
||||
const auto version = request.get_header_value("MCP-Protocol-Version");
|
||||
if (!version.empty() && version != "2025-11-25" && version != "2025-06-18" && version != "2025-03-26") {
|
||||
response.status = 400;
|
||||
response.set_content(rpc_error(nullptr, -32600, "Supported versions: 2025-11-25, 2025-06-18").dump(),
|
||||
"application/json");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
auto input = Json::parse(request.body);
|
||||
if (!input.is_object()) {
|
||||
response.status = 400;
|
||||
response.set_content(rpc_error(nullptr, -32600, "Invalid request").dump(), "application/json");
|
||||
return;
|
||||
}
|
||||
auto output = dispatch(input);
|
||||
if (output.is_null()) {
|
||||
response.status = 202;
|
||||
return;
|
||||
}
|
||||
response.set_content(output.dump(), "application/json");
|
||||
} catch (const Json::exception &) {
|
||||
response.status = 400;
|
||||
response.set_content(rpc_error(nullptr, -32700, "Parse error").dump(), "application/json");
|
||||
} catch (const std::exception &) {
|
||||
response.status = 500;
|
||||
response.set_content(rpc_error(nullptr, -32603, "Internal error").dump(), "application/json");
|
||||
}
|
||||
});
|
||||
for (auto method : {0, 1}) {
|
||||
auto unsupported = [authorized](const httplib::Request &request, httplib::Response &response) {
|
||||
if (authorized(request, response)) {
|
||||
response.status = 405;
|
||||
response.set_header("Allow", "POST");
|
||||
}
|
||||
};
|
||||
if (method == 0)
|
||||
server->Get("/mcp", unsupported);
|
||||
else
|
||||
server->Delete("/mcp", unsupported);
|
||||
}
|
||||
impl_->port = options.mcp_port ? (server->bind_to_port("127.0.0.1", options.mcp_port) ? options.mcp_port : -1)
|
||||
: server->bind_to_any_port("127.0.0.1");
|
||||
if (impl_->port <= 0) {
|
||||
impl_->port = 0;
|
||||
throw Error("server_failed");
|
||||
}
|
||||
impl_->http = std::move(server);
|
||||
impl_->active = true;
|
||||
impl_->worker = std::thread([this] {
|
||||
impl_->http->listen_after_bind();
|
||||
impl_->active = false;
|
||||
});
|
||||
}
|
||||
} // namespace bmh::editor
|
||||
@@ -0,0 +1,28 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#pragma once
|
||||
#include "editor/options.hpp"
|
||||
#include "editor/session.hpp"
|
||||
#include <memory>
|
||||
|
||||
namespace bmh::editor {
|
||||
// A local Streamable HTTP MCP endpoint. GUI and MCP own no separate world
|
||||
// state. Protocol 2025-11-25 (also negotiates 2025-06-18), no optional
|
||||
// SSE/session state.
|
||||
class McpServer {
|
||||
public:
|
||||
explicit McpServer(Session &);
|
||||
~McpServer();
|
||||
McpServer(const McpServer &) = delete;
|
||||
void start(const Options &);
|
||||
void stop();
|
||||
int port() const;
|
||||
bool running() const;
|
||||
Json connection(const Options &) const;
|
||||
static Json tools();
|
||||
Json dispatch(const Json &request);
|
||||
|
||||
private:
|
||||
struct Impl;
|
||||
std::unique_ptr<Impl> impl_;
|
||||
};
|
||||
} // namespace bmh::editor
|
||||
@@ -0,0 +1,420 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#include "editor/options.hpp"
|
||||
#include <cstdlib>
|
||||
#include <map>
|
||||
#include <random>
|
||||
#ifdef _WIN32
|
||||
#define NOMINMAX
|
||||
#include <windows.h>
|
||||
#else
|
||||
#include <sys/stat.h>
|
||||
#endif
|
||||
namespace bmh::editor {
|
||||
Options Options::load(fs::path override_path) {
|
||||
Options result;
|
||||
if (override_path.empty()) {
|
||||
#ifdef _WIN32
|
||||
// The narrow CRT environment is encoded in the active Windows code
|
||||
// page, not UTF-8. Use the native path for names such as Müller.
|
||||
wchar_t base[32768]{};
|
||||
const auto count = GetEnvironmentVariableW(L"APPDATA", base, 32768);
|
||||
override_path =
|
||||
(count > 0 && count < 32768 ? fs::path(base) : fs::temp_directory_path()) / "OpenBMH" / "editor.json";
|
||||
#elif defined(__APPLE__)
|
||||
auto base = std::getenv("HOME");
|
||||
override_path =
|
||||
(base ? path(base) : fs::temp_directory_path()) / "Library/Application Support/OpenBMH/editor.json";
|
||||
#else
|
||||
if (auto base = std::getenv("XDG_CONFIG_HOME"))
|
||||
override_path = path(base) / "openbmh/editor.json";
|
||||
else {
|
||||
auto user = std::getenv("HOME");
|
||||
override_path = (user ? path(user) : fs::temp_directory_path()) / ".config/openbmh/editor.json";
|
||||
}
|
||||
#endif
|
||||
}
|
||||
result.settings_file = std::move(override_path);
|
||||
if (fs::exists(result.settings_file)) {
|
||||
try {
|
||||
auto json = Json::parse(read_file(result.settings_file, 1024 * 1024));
|
||||
result.apply(json);
|
||||
result.token = str(json, "mcp_token");
|
||||
} catch (const std::exception &) {
|
||||
throw Error("invalid_settings", {{"path", utf8(result.settings_file)}});
|
||||
}
|
||||
}
|
||||
if (result.token.size() < 32) {
|
||||
// random_device uses the OS entropy source on supported release targets;
|
||||
// identifiers from the editor's PRNG are deliberately not credentials.
|
||||
std::random_device entropy;
|
||||
static constexpr char hex[] = "0123456789abcdef";
|
||||
result.token.clear();
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
auto number = entropy();
|
||||
for (int j = 0; j < 8; ++j) {
|
||||
result.token += hex[number & 15];
|
||||
number >>= 4;
|
||||
}
|
||||
}
|
||||
}
|
||||
result.save();
|
||||
return result;
|
||||
}
|
||||
Json Options::json(bool secret) const {
|
||||
Json value{{"language", language}, {"theme", theme}, {"mcp_enabled", mcp_enabled}, {"mcp_port", mcp_port}};
|
||||
if (secret)
|
||||
value["mcp_token"] = token;
|
||||
return value;
|
||||
}
|
||||
void Options::apply(const Json &value) {
|
||||
auto language_value = str(value, "language", language), theme_value = str(value, "theme", theme);
|
||||
auto port = value.value("mcp_port", mcp_port);
|
||||
if ((language_value != "de" && language_value != "en") ||
|
||||
(theme_value != "midnight" && theme_value != "silver" && theme_value != "matchday") || port < 0 || port > 65535)
|
||||
throw Error("invalid_settings");
|
||||
language = language_value;
|
||||
theme = theme_value;
|
||||
mcp_port = port;
|
||||
mcp_enabled = value.value("mcp_enabled", mcp_enabled);
|
||||
}
|
||||
void Options::save() const {
|
||||
if (settings_file.has_parent_path())
|
||||
fs::create_directories(settings_file.parent_path());
|
||||
write_atomic(settings_file, json(true).dump(2));
|
||||
#ifndef _WIN32
|
||||
chmod(settings_file.c_str(), 0600);
|
||||
#endif
|
||||
}
|
||||
std::string tr(const std::string &language, const std::string &key) {
|
||||
using Pair = std::pair<std::string, std::string>;
|
||||
static const std::map<std::string, Pair> words{
|
||||
{"data_areas", {"Datenbereiche", "World data"}},
|
||||
{"invalid_manifest",
|
||||
{"Die Kennzeichnung der Editorwelt ist ungültig.", "The editor world identification is invalid."}},
|
||||
{"facilities", {"Ausstattung", "Facilities"}},
|
||||
{"draft_prompt", {"Eingaben übernehmen?", "Apply these entries?"}},
|
||||
{"draft_detail",
|
||||
{"Die Eigenschaften enthalten noch nicht übernommene Eingaben.",
|
||||
"The inspector contains entries that have not been applied."}},
|
||||
{"trophy", {"Pokalbild", "Trophy image"}},
|
||||
{"author", {"Urheber", "Author"}},
|
||||
{"license", {"Lizenz", "License"}},
|
||||
{"copy", {"Kopie", "Copy"}},
|
||||
{"applied", {"Übernommen", "Applied"}},
|
||||
{"undone", {"Zurückgenommen", "Undone"}},
|
||||
{"edit", {"Bearbeitung", "Edit"}},
|
||||
{"image_import", {"Bild importieren", "Import image"}},
|
||||
{"width", {"Breite", "Width"}},
|
||||
{"height", {"Höhe", "Height"}},
|
||||
{"x", {"Links", "Left"}},
|
||||
{"y", {"Oben", "Top"}},
|
||||
{"open_folder", {"Entpackte Welt öffnen", "Open unpacked world"}},
|
||||
{"subtitle_overview", {"Ein Arbeitsplatz für deine Fußballwelt", "A workspace for your football world"}},
|
||||
{"subtitle_nations", {"Länder, Verbände und Simulation", "Countries, associations and simulation"}},
|
||||
{"subtitle_competitions", {"Ligen, Zuordnungen und Pokalbilder", "Leagues, membership and trophy images"}},
|
||||
{"subtitle_clubs", {"Stammdaten, Farben und Spielstätten", "Details, colours and home grounds"}},
|
||||
{"subtitle_players",
|
||||
{"Spielerdaten und quellengerechte Spielwerte", "Player details and source-specific attributes"}},
|
||||
{"subtitle_stadiums", {"Kapazität und Ausstattung", "Capacity and facilities"}},
|
||||
{"subtitle_staff", {"Schiedsrichter und ihre Eigenschaften", "Referees and their attributes"}},
|
||||
{"subtitle_assets", {"Wappen, Porträts und Pokale", "Crests, portraits and trophies"}},
|
||||
{"subtitle_review", {"Quellen vergleichen", "Compare sources"}},
|
||||
{"subtitle_roster", {"Vollständige Kader ohne Datenverlust", "Complete squads without losing data"}},
|
||||
{"subtitle_changes", {"Gemeinsame Historie von Oberfläche und MCP", "One history for the interface and MCP"}},
|
||||
{"preservation_note",
|
||||
{"Quellen, Bilder und Erweiterungen bleiben erhalten. Bearbeitungen "
|
||||
"ändern keine Originalinstallation.",
|
||||
"Sources, images and extensions are retained. Edits do not change the "
|
||||
"original installation."}},
|
||||
{"unrated_hint",
|
||||
{"Keine belegten Spielwerte vorhanden. Es werden keine Stärken "
|
||||
"erfunden.",
|
||||
"No sourced attributes available. Ratings are not invented."}},
|
||||
{"crop_hint",
|
||||
{"Im Bild einen Rahmen ziehen oder den Ausschnitt als Werte eingeben. "
|
||||
"Ohne Zuschnitt bleibt die Originalauflösung erhalten.",
|
||||
"Drag a rectangle on the image or enter crop values. Without cropping, "
|
||||
"the original resolution is retained."}},
|
||||
{"video_failed",
|
||||
{"Die Grafikausgabe benötigt OpenGL 3.3 (macOS: 4.1).", "The interface requires OpenGL 3.3 (macOS: 4.1)."}},
|
||||
{"ui_assets_missing",
|
||||
{"Editor-Oberfläche fehlt. Bitte das vollständige Paket entpacken.",
|
||||
"Editor interface files are missing. Please extract the complete "
|
||||
"package."}},
|
||||
{"dialog_failed", {"Der Dateidialog konnte nicht geöffnet werden.", "The file dialog could not be opened."}},
|
||||
{"invalid_attributes", {"Ungültige Spielwerte.", "Invalid player attributes."}},
|
||||
{"app", {"OpenBMH Editor", "OpenBMH Editor"}},
|
||||
{"poc", {"Dateneditor · Vorschau", "World editor · Preview"}},
|
||||
{"overview", {"Übersicht", "Overview"}},
|
||||
{"nations", {"Länder", "Countries"}},
|
||||
{"competitions", {"Ligen & Pokale", "Leagues & cups"}},
|
||||
{"clubs", {"Vereine", "Clubs"}},
|
||||
{"players", {"Spieler", "Players"}},
|
||||
{"roster", {"Kader", "Squads"}},
|
||||
{"stadiums", {"Stadien", "Stadiums"}},
|
||||
{"staff", {"Schiedsrichter", "Referees"}},
|
||||
{"assets", {"Bilder", "Images"}},
|
||||
{"review", {"Prüfen", "Review"}},
|
||||
{"changes", {"Änderungen", "Changes"}},
|
||||
{"options", {"Optionen", "Options"}},
|
||||
{"open", {"Öffnen", "Open"}},
|
||||
{"open_world", {"OBW öffnen", "Open OBW"}},
|
||||
{"import_legacy", {"BMH / FLTD importieren", "Import BMH / FLTD"}},
|
||||
{"new_world", {"Neue Welt", "New world"}},
|
||||
{"demo", {"Demo öffnen", "Open demo"}},
|
||||
{"save", {"Speichern", "Save"}},
|
||||
{"save_as", {"Speichern unter …", "Save as …"}},
|
||||
{"undo", {"Rückgängig", "Undo"}},
|
||||
{"redo", {"Wiederholen", "Redo"}},
|
||||
{"search", {"Suchen …", "Search …"}},
|
||||
{"all", {"Alle", "All"}},
|
||||
{"all_nations", {"Alle Länder", "All countries"}},
|
||||
{"all_leagues", {"Alle Ligen", "All leagues"}},
|
||||
{"all_clubs", {"Alle Vereine", "All clubs"}},
|
||||
{"add", {"Hinzufügen", "Add"}},
|
||||
{"duplicate", {"Duplizieren", "Duplicate"}},
|
||||
{"delete", {"Löschen", "Delete"}},
|
||||
{"apply", {"Anwenden", "Apply"}},
|
||||
{"cancel", {"Abbrechen", "Cancel"}},
|
||||
{"close", {"Schließen", "Close"}},
|
||||
{"confirm", {"Bestätigen", "Confirm"}},
|
||||
{"discard", {"Verwerfen", "Discard"}},
|
||||
{"unknown", {"Unbekannt", "Unknown"}},
|
||||
{"empty", {"Keine Einträge", "No records"}},
|
||||
{"select_record", {"Datensatz auswählen", "Select a record"}},
|
||||
{"name", {"Name", "Name"}},
|
||||
{"short_name", {"Kurzname", "Short name"}},
|
||||
{"first", {"Vorname", "First name"}},
|
||||
{"last", {"Nachname", "Last name"}},
|
||||
{"known_as", {"Anzeigename", "Known as"}},
|
||||
{"nation", {"Land", "Country"}},
|
||||
{"nationalities", {"Nationalitätsangaben", "Nationality claims"}},
|
||||
{"competition", {"Liga", "League"}},
|
||||
{"team", {"Verein", "Club"}},
|
||||
{"stadium", {"Stadion", "Stadium"}},
|
||||
{"born", {"Geburtsdatum", "Date of birth"}},
|
||||
{"age_at_start", {"Alter zum Saisonbeginn", "Age at season start"}},
|
||||
{"positions", {"Position", "Position"}},
|
||||
{"gk", {"Tor", "Goalkeeper"}},
|
||||
{"def", {"Abwehr", "Defender"}},
|
||||
{"mid", {"Mittelfeld", "Midfielder"}},
|
||||
{"fwd", {"Sturm", "Forward"}},
|
||||
{"squad_number", {"Rückennummer", "Shirt number"}},
|
||||
{"squad_order", {"Kaderplatz", "Squad order"}},
|
||||
{"attribute_set", {"Attributsystem", "Attribute set"}},
|
||||
{"attributes", {"Spielwerte", "Attributes"}},
|
||||
{"type", {"Art", "Type"}},
|
||||
{"tier", {"Spielklasse", "Tier"}},
|
||||
{"visible", {"Sichtbare Liga", "Visible league"}},
|
||||
{"playable", {"Ligen vollständig simulieren", "Fully simulated leagues"}},
|
||||
{"confederation", {"Verband", "Confederation"}},
|
||||
{"founded", {"Gründungsjahr", "Founded"}},
|
||||
{"capacity", {"Kapazität", "Capacity"}},
|
||||
{"total", {"Gesamt", "Total"}},
|
||||
{"standing", {"Stehplätze", "Standing"}},
|
||||
{"seated", {"Sitzplätze", "Seated"}},
|
||||
{"boxes", {"Logen", "Boxes"}},
|
||||
{"owner", {"Eigentümer", "Owner"}},
|
||||
{"colors", {"Vereinsfarben", "Club colours"}},
|
||||
{"role", {"Rolle", "Role"}},
|
||||
{"strictness", {"Strenge", "Strictness"}},
|
||||
{"strength", {"Stärke", "Strength"}},
|
||||
{"technique", {"Technik", "Technique"}},
|
||||
{"condition", {"Kondition", "Condition"}},
|
||||
{"form", {"Form", "Form"}},
|
||||
{"overall", {"Gesamtstärke", "Overall"}},
|
||||
{"potential", {"Potenzial", "Potential"}},
|
||||
{"acceleration", {"Antritt", "Acceleration"}},
|
||||
{"sprintspeed", {"Sprinttempo", "Sprint speed"}},
|
||||
{"positioning", {"Offensivstellung", "Attacking position"}},
|
||||
{"finishing", {"Abschluss", "Finishing"}},
|
||||
{"shotpower", {"Schusskraft", "Shot power"}},
|
||||
{"longshots", {"Fernschüsse", "Long shots"}},
|
||||
{"volleys", {"Volleys", "Volleys"}},
|
||||
{"penalties", {"Elfmeter", "Penalties"}},
|
||||
{"crossing", {"Flanken", "Crossing"}},
|
||||
{"shortpassing", {"Kurzpass", "Short passing"}},
|
||||
{"longpassing", {"Langpass", "Long passing"}},
|
||||
{"curve", {"Effet", "Curve"}},
|
||||
{"freekickaccuracy", {"Freistöße", "Free kicks"}},
|
||||
{"vision", {"Übersicht", "Vision"}},
|
||||
{"dribbling", {"Dribbling", "Dribbling"}},
|
||||
{"ballcontrol", {"Ballkontrolle", "Ball control"}},
|
||||
{"agility", {"Beweglichkeit", "Agility"}},
|
||||
{"balance", {"Balance", "Balance"}},
|
||||
{"reactions", {"Reaktion", "Reactions"}},
|
||||
{"composure", {"Ruhe am Ball", "Composure"}},
|
||||
{"interceptions", {"Abfangen", "Interceptions"}},
|
||||
{"headingaccuracy", {"Kopfball", "Heading"}},
|
||||
{"standingtackle", {"Zweikampf", "Standing tackle"}},
|
||||
{"slidingtackle", {"Grätsche", "Sliding tackle"}},
|
||||
{"defensiveawareness", {"Defensivstellung", "Defensive awareness"}},
|
||||
{"jumping", {"Sprungkraft", "Jumping"}},
|
||||
{"stamina", {"Ausdauer", "Stamina"}},
|
||||
{"aggression", {"Aggressivität", "Aggression"}},
|
||||
{"gkdiving", {"TW-Hechten", "GK diving"}},
|
||||
{"gkhandling", {"TW-Fangen", "GK handling"}},
|
||||
{"gkkicking", {"TW-Abschlag", "GK kicking"}},
|
||||
{"gkpositioning", {"TW-Stellung", "GK positioning"}},
|
||||
{"gkreflexes", {"TW-Reflexe", "GK reflexes"}},
|
||||
{"bonus", {"Bonus", "Bonus"}},
|
||||
{"teamplay", {"Teamspiel", "Team play"}},
|
||||
{"speed", {"Schnelligkeit", "Speed"}},
|
||||
{"shooting", {"Schuss", "Shooting"}},
|
||||
{"passing", {"Pass", "Passing"}},
|
||||
{"tackling", {"Zweikampf", "Tackling"}},
|
||||
{"free_kick", {"Freistoß", "Free kick"}},
|
||||
{"corner", {"Ecke", "Corner"}},
|
||||
{"yes", {"Ja", "Yes"}},
|
||||
{"no", {"Nein", "No"}},
|
||||
{"league", {"Liga", "League"}},
|
||||
{"cup", {"Pokal", "Cup"}},
|
||||
{"national", {"Nationalmannschaft", "National team"}},
|
||||
{"club", {"Verein", "Club"}},
|
||||
{"foreign", {"Auslandsverein", "Foreign club"}},
|
||||
{"amateur", {"Amateur", "Amateur"}},
|
||||
{"image_import", {"Bild importieren", "Import image"}},
|
||||
{"image_edit", {"Bild bearbeiten", "Edit image"}},
|
||||
{"image_export", {"PNG exportieren", "Export PNG"}},
|
||||
{"angle", {"Drehwinkel", "Rotation"}},
|
||||
{"flip_x", {"Horizontal spiegeln", "Flip horizontally"}},
|
||||
{"flip_y", {"Vertikal spiegeln", "Flip vertically"}},
|
||||
{"crop", {"Zuschnitt", "Crop"}},
|
||||
{"free", {"Frei", "Free"}},
|
||||
{"reset", {"Zurücksetzen", "Reset"}},
|
||||
{"source", {"Quelle", "Source"}},
|
||||
{"original", {"Original", "Original"}},
|
||||
{"preview", {"Vorschau", "Preview"}},
|
||||
{"language", {"Sprache", "Language"}},
|
||||
{"theme", {"Darstellung", "Theme"}},
|
||||
{"mcp_enabled", {"MCP-Server aktivieren", "Enable MCP server"}},
|
||||
{"mcp_port", {"Port", "Port"}},
|
||||
{"copy_connection", {"Verbindung kopieren", "Copy connection"}},
|
||||
{"mcp_local", {"Lokal auf diesem Rechner", "Local to this computer"}},
|
||||
{"online", {"Aktiv", "Online"}},
|
||||
{"offline", {"Aus", "Offline"}},
|
||||
{"saved", {"Gespeichert", "Saved"}},
|
||||
{"unsaved", {"Ungespeichert", "Unsaved"}},
|
||||
{"not_playable", {"Editorwelt · noch nicht im Spiel startbar", "Editor world · not yet playable"}},
|
||||
{"workspace", {"Deine Fußballwelt", "Your football world"}},
|
||||
{"welcome",
|
||||
{"Stammdaten bearbeiten. Quellen erhalten. Neues gestalten.",
|
||||
"Edit the details. Keep the sources. Build something new."}},
|
||||
{"welcome_hint",
|
||||
{"Öffne eine OBW-Welt, importiere BMH oder Football Limited oder "
|
||||
"probiere die Demo aus.",
|
||||
"Open an OBW world, import BMH or Football Limited, or explore the "
|
||||
"demo."}},
|
||||
{"records", {"Einträge", "records"}},
|
||||
{"previous", {"Zurück", "Previous"}},
|
||||
{"next", {"Weiter", "Next"}},
|
||||
{"details", {"Eigenschaften", "Properties"}},
|
||||
{"provenance", {"Herkunft & Hinweise", "Sources & notes"}},
|
||||
{"resolve", {"Auswahl übernehmen", "Use selected value"}},
|
||||
{"resolved", {"Erledigt", "Resolved"}},
|
||||
{"unresolved", {"Offen", "Open"}},
|
||||
{"review_hint", {"Quellen vergleichen und eine Angabe auswählen.", "Compare sources and choose a value."}},
|
||||
{"roster_hint",
|
||||
{"Verein wählen, Spieler verschieben oder zwei Spieler tauschen.",
|
||||
"Choose a club, move a player or swap two players."}},
|
||||
{"move_player", {"Spieler verschieben", "Move player"}},
|
||||
{"remember_player", {"Zum Tausch merken", "Remember for swap"}},
|
||||
{"swap_player", {"Mit gemerktem Spieler tauschen", "Swap with remembered player"}},
|
||||
{"compatibility24", {"24-Spieler-Ansicht", "24-player view"}},
|
||||
{"validate", {"Welt prüfen", "Validate world"}},
|
||||
{"warnings", {"Hinweise", "Warnings"}},
|
||||
{"errors", {"Fehler", "Errors"}},
|
||||
{"no_changes", {"Noch keine Änderungen", "No changes yet"}},
|
||||
{"dirty_prompt", {"Änderungen speichern?", "Save changes?"}},
|
||||
{"dirty_detail", {"Diese Welt enthält ungespeicherte Änderungen.", "This world has unsaved changes."}},
|
||||
{"delete_prompt", {"Datensatz wirklich löschen?", "Delete this record?"}},
|
||||
{"new_name", {"Name des neuen Datensatzes", "Name of the new record"}},
|
||||
{"new_title", {"Neue Fußballwelt", "New football world"}},
|
||||
{"start_date", {"Saisonbeginn", "Season start"}},
|
||||
{"title", {"Titel", "Title"}},
|
||||
{"currency", {"Währung", "Currency"}},
|
||||
{"loading", {"Wird geladen …", "Loading …"}},
|
||||
{"saved_ok", {"Welt gespeichert", "World saved"}},
|
||||
{"copied", {"In die Zwischenablage kopiert", "Copied to clipboard"}},
|
||||
{"error", {"Fehler", "Error"}},
|
||||
{"open_failed", {"Die Datei konnte nicht geöffnet werden.", "The file could not be opened."}},
|
||||
{"save_failed",
|
||||
{"Speichern fehlgeschlagen. Die bisherige Datei bleibt erhalten.",
|
||||
"Saving failed. The previous file is retained."}},
|
||||
{"invalid_archive",
|
||||
{"Das Archiv ist beschädigt oder wird nicht unterstützt.", "The archive is damaged or unsupported."}},
|
||||
{"unsupported_archive", {"Dieses Archivformat wird nicht unterstützt.", "This archive format is unsupported."}},
|
||||
{"archive_limit",
|
||||
{"Das Datenpaket überschreitet die unterstützten Grenzen.", "The data package exceeds the supported limits."}},
|
||||
{"unsafe_path", {"Unzulässiger Dateipfad.", "Invalid file path."}},
|
||||
{"size_limit", {"Die Datei ist zu groß.", "The file is too large."}},
|
||||
{"missing_manifest", {"Keine OBW-Welt gefunden.", "No OBW world found."}},
|
||||
{"not_world", {"Bitte eine OBW-Startdatenbank öffnen.", "Please open an OBW starting world."}},
|
||||
{"unsupported_version", {"Diese Formatversion wird nicht unterstützt.", "This format version is unsupported."}},
|
||||
{"invalid_json", {"Die JSON-Daten sind ungültig.", "The JSON data is invalid."}},
|
||||
{"invalid_table", {"Eine Datentabelle ist ungültig.", "A data table is invalid."}},
|
||||
{"unknown_table", {"Unbekannter Datenbereich.", "Unknown data table."}},
|
||||
{"missing_asset", {"Das Bild fehlt im Datenpaket.", "The image is missing from the package."}},
|
||||
{"unsafe_asset", {"Das Bild kann nicht übernommen werden.", "The image cannot be imported."}},
|
||||
{"invalid_image", {"Das Bild konnte nicht gelesen werden.", "The image could not be decoded."}},
|
||||
{"image_dimensions", {"Das Bild hat nicht unterstützte Abmessungen.", "The image dimensions are unsupported."}},
|
||||
{"invalid_transform",
|
||||
{"Der Bildzuschnitt oder Drehwinkel ist ungültig.", "The image crop or rotation is invalid."}},
|
||||
{"external_svg_resource",
|
||||
{"Das SVG verweist auf externe Bilddateien. Bitte ein eigenständiges "
|
||||
"SVG verwenden.",
|
||||
"The SVG references external images. Please use a self-contained "
|
||||
"SVG."}},
|
||||
{"image_encode_failed",
|
||||
{"Das bearbeitete Bild konnte nicht erstellt werden.", "The edited image could not be created."}},
|
||||
{"obw_only", {"Es kann ausschließlich als .obw gespeichert werden.", "Only .obw output is supported."}},
|
||||
{"preserve_source",
|
||||
{"Bitte unter einem neuen Namen speichern. Der Classic-Import bleibt "
|
||||
"erhalten.",
|
||||
"Please save under a new name. The Classic source is retained."}},
|
||||
{"validation_failed",
|
||||
{"Bitte zuerst die angezeigten Datenfehler beheben.", "Please fix the reported data errors first."}},
|
||||
{"invalid_date",
|
||||
{"Bitte ein gültiges Datum im Format JJJJ-MM-TT eingeben.",
|
||||
"Please enter a valid date in YYYY-MM-DD format."}},
|
||||
{"duplicate_id",
|
||||
{"Eine Kennung fehlt oder ist mehrfach vorhanden.", "An identifier is missing or duplicated."}},
|
||||
{"missing_reference", {"Ein verknüpfter Datensatz fehlt.", "A referenced record is missing."}},
|
||||
{"attribute_range",
|
||||
{"Ein Spielwert liegt außerhalb seines Wertebereichs.", "An attribute is outside its declared range."}},
|
||||
{"unknown_attribute_set", {"Das Attributsystem ist nicht definiert.", "The attribute set is not defined."}},
|
||||
{"missing_name", {"Ein Name fehlt.", "A name is missing."}},
|
||||
{"missing_birthday", {"Das Geburtsdatum ist unbekannt.", "The date of birth is unknown."}},
|
||||
{"review_open", {"Eine Quellenfrage ist noch offen.", "A source decision is still open."}},
|
||||
{"record_referenced",
|
||||
{"Der Datensatz wird noch verwendet. Bitte zuerst die Verknüpfungen "
|
||||
"ändern.",
|
||||
"The record is still referenced. Please update its links first."}},
|
||||
{"record_missing", {"Der Datensatz wurde nicht gefunden.", "The record was not found."}},
|
||||
{"immutable_id",
|
||||
{"Kennungen können nicht nachträglich geändert werden.", "Identifiers cannot be changed after creation."}},
|
||||
{"stale_revision",
|
||||
{"Die Daten wurden inzwischen geändert. Bitte die Ansicht "
|
||||
"aktualisieren.",
|
||||
"The data has changed. Please refresh the view."}},
|
||||
{"invalid_change", {"Diese Änderung ist nicht gültig.", "This change is invalid."}},
|
||||
{"nothing_to_undo", {"Keine Änderung zum Rückgängigmachen.", "There is nothing to undo."}},
|
||||
{"nothing_to_redo", {"Keine Änderung zum Wiederholen.", "There is nothing to redo."}},
|
||||
{"no_world", {"Bitte zuerst eine Welt öffnen.", "Please open a world first."}},
|
||||
{"invalid_settings", {"Die Optionen sind ungültig.", "The options are invalid."}},
|
||||
{"output_parent_missing", {"Der Zielordner existiert nicht.", "The output folder does not exist."}},
|
||||
{"destination_exists", {"Die Zieldatei existiert bereits.", "The destination file already exists."}},
|
||||
{"duplicate_entry", {"Das Archiv enthält doppelte Dateinamen.", "The archive contains duplicate entry names."}},
|
||||
{"server_failed",
|
||||
{"MCP konnte nicht gestartet werden. Bitte den Port prüfen.",
|
||||
"MCP could not be started. Please check the port."}},
|
||||
{"source_changed",
|
||||
{"Die Quelldatei wurde außerhalb des Editors geändert. Bitte Speichern "
|
||||
"unter verwenden.",
|
||||
"The source file changed outside the editor. Please use Save as."}}};
|
||||
const auto found = words.find(key);
|
||||
if (found == words.end())
|
||||
return key;
|
||||
return language == "en" ? found->second.second : found->second.first;
|
||||
}
|
||||
} // namespace bmh::editor
|
||||
@@ -0,0 +1,16 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#pragma once
|
||||
#include "editor/types.hpp"
|
||||
namespace bmh::editor {
|
||||
struct Options {
|
||||
std::string language = "de", theme = "midnight", token;
|
||||
bool mcp_enabled = true;
|
||||
int mcp_port = 8765;
|
||||
fs::path settings_file;
|
||||
static Options load(fs::path override_path = {});
|
||||
Json json(bool include_secret = false) const;
|
||||
void apply(const Json &);
|
||||
void save() const;
|
||||
};
|
||||
std::string tr(const std::string &language, const std::string &key);
|
||||
} // namespace bmh::editor
|
||||
@@ -0,0 +1,574 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#include "editor/session.hpp"
|
||||
#include "content/digest.hpp"
|
||||
#include "editor/images.hpp"
|
||||
#include <algorithm>
|
||||
#include <limits>
|
||||
|
||||
namespace bmh::editor {
|
||||
namespace {
|
||||
bool editable(const std::string &name) {
|
||||
return name == "nations" || name == "competitions" || name == "clubs" || name == "players" || name == "stadiums" ||
|
||||
name == "staff" || name == "assets" || name == "review" || name == "image-edits" || name == "manifest";
|
||||
}
|
||||
Json defaults(const std::string &table, const std::string &name) {
|
||||
auto localized = Json{{"default", name}};
|
||||
if (table == "players")
|
||||
return {{"name", {{"first", ""}, {"last", name}}},
|
||||
{"born", nullptr},
|
||||
{"nationalities", Json::array()},
|
||||
{"positions", Json::array()},
|
||||
{"attributes", Json::object()},
|
||||
{"attribute_set", "unrated@1"}};
|
||||
if (table == "clubs")
|
||||
return {{"name", localized}, {"type", "club"}, {"nation", nullptr}, {"colors", Json::array()}};
|
||||
if (table == "nations")
|
||||
return {{"name", localized}, {"confederation", "other"}, {"playable", false}};
|
||||
if (table == "competitions")
|
||||
return {{"name", localized}, {"type", "league"}, {"nation", nullptr}, {"tier", 1},
|
||||
{"visible", true}, {"members", Json::array()}, {"stages", Json::array()}};
|
||||
if (table == "stadiums")
|
||||
return {{"name", localized}, {"capacity", Json::object()}, {"facilities", Json::object()}};
|
||||
if (table == "staff")
|
||||
return {{"name", localized}, {"role", "referee"}, {"attributes", Json::object()}};
|
||||
return Json::object();
|
||||
}
|
||||
std::string prefix(const std::string &table) {
|
||||
if (table == "nations")
|
||||
return "nation:";
|
||||
if (table == "competitions")
|
||||
return "comp:";
|
||||
if (table == "assets")
|
||||
return "asset:";
|
||||
if (table == "staff")
|
||||
return "staff:";
|
||||
if (table == "image-edits")
|
||||
return "image-edit:";
|
||||
return table.substr(0, table.size() - 1) + ':';
|
||||
}
|
||||
} // namespace
|
||||
World &Session::world() {
|
||||
if (!world_)
|
||||
throw Error("no_world");
|
||||
return *world_;
|
||||
}
|
||||
bool Session::dirty() const { return world_ && state_ != saved_state_; }
|
||||
Json Session::info() const {
|
||||
Json result = world_ ? world_->statistics() : Json{{"title", ""}, {"counts", Json::object()}};
|
||||
result["loaded"] = bool(world_);
|
||||
result["revision"] = revision_;
|
||||
result["dirty"] = dirty();
|
||||
result["can_undo"] = cursor_ > 0;
|
||||
result["can_redo"] = cursor_ < history_.size();
|
||||
result["path"] = utf8(saved_path_);
|
||||
return result;
|
||||
}
|
||||
void Session::replace(World value) {
|
||||
world_ = std::make_unique<World>(std::move(value));
|
||||
history_.clear();
|
||||
cursor_ = 0;
|
||||
++revision_;
|
||||
state_ = next_state_++;
|
||||
saved_state_ = world_->source_path.empty() || world_->imported ? 0 : state_;
|
||||
saved_path_ = world_->source_path.empty() || world_->imported || !fs::is_regular_file(world_->source_path)
|
||||
? fs::path{}
|
||||
: world_->source_path;
|
||||
if (!saved_path_.empty() && fs::is_regular_file(saved_path_)) {
|
||||
saved_time_ = fs::last_write_time(saved_path_);
|
||||
saved_size_ = fs::file_size(saved_path_);
|
||||
}
|
||||
}
|
||||
void Session::frame(const Frame &f, bool forward) {
|
||||
for (const auto &change : f.changes) {
|
||||
auto value = forward ? change.after : change.before;
|
||||
if (change.table == "manifest") {
|
||||
if (value)
|
||||
world().manifest = *value;
|
||||
} else
|
||||
world().change(change.table, change.id, value);
|
||||
}
|
||||
for (const auto &file : f.files)
|
||||
world().store->restore(file.name, forward ? file.after : file.before);
|
||||
state_ = forward ? f.after : f.before;
|
||||
}
|
||||
Json Session::apply(const Json &args, std::vector<FileDelta> files, const std::string &label) {
|
||||
auto &w = world();
|
||||
if (args.contains("expected_revision") && args["expected_revision"].get<uint64_t>() != revision_)
|
||||
throw Error("stale_revision");
|
||||
if (!args.contains("changes") || !args["changes"].is_array() || args["changes"].size() > 5000)
|
||||
throw Error("invalid_change");
|
||||
Frame transaction;
|
||||
transaction.label = label;
|
||||
transaction.files = std::move(files);
|
||||
transaction.before = state_;
|
||||
transaction.after = next_state_;
|
||||
std::map<std::pair<std::string, std::string>, size_t> staged;
|
||||
Json created = Json::array();
|
||||
for (const auto &action : args["changes"]) {
|
||||
const auto name = str(action, "table"), op = str(action, "op", "update");
|
||||
if (!editable(name))
|
||||
throw Error("unknown_table");
|
||||
auto id = str(action, "id");
|
||||
if (op == "create" && id.empty()) {
|
||||
id = new_id(prefix(name) + "editor-");
|
||||
created.push_back(id);
|
||||
}
|
||||
if (name == "manifest")
|
||||
id = "manifest";
|
||||
auto key = std::make_pair(name, id);
|
||||
if (!staged.contains(key)) {
|
||||
const auto *existing = name == "manifest" ? &w.manifest : w.find(name, id);
|
||||
std::optional<Json> before = existing ? std::optional<Json>(*existing) : std::nullopt;
|
||||
staged[key] = transaction.changes.size();
|
||||
transaction.changes.push_back({name, id, before, before});
|
||||
}
|
||||
auto &delta = transaction.changes[staged[key]];
|
||||
if (op == "create") {
|
||||
if (delta.after || name == "manifest")
|
||||
throw Error("duplicate_id");
|
||||
delta.after = defaults(name, str(action, "name"));
|
||||
if (action.contains("data"))
|
||||
delta.after->update(action["data"]);
|
||||
(*delta.after)[name == "assets" ? "key" : "id"] = id;
|
||||
} else if (op == "delete") {
|
||||
if (!delta.after)
|
||||
throw Error("record_missing", {{"table", name}, {"id", id}});
|
||||
if (name == "manifest")
|
||||
throw Error("invalid_change");
|
||||
delta.after.reset();
|
||||
} else if (op == "update") {
|
||||
if (!delta.after)
|
||||
throw Error("record_missing", {{"table", name}, {"id", id}});
|
||||
const auto set = action.value("set", Json::object());
|
||||
if (!set.is_object())
|
||||
throw Error("invalid_change");
|
||||
for (auto it = set.begin(); it != set.end(); ++it) {
|
||||
const auto pointer = it.key();
|
||||
if (pointer.empty() || pointer[0] != '/' || pointer == "/id" || pointer.starts_with("/id/") ||
|
||||
(name == "assets" && pointer == "/key"))
|
||||
throw Error("immutable_id");
|
||||
if (name == "manifest" && pointer != "/title" && !pointer.starts_with("/title/") &&
|
||||
pointer != "/start_date" && pointer != "/currency" && !pointer.starts_with("/currency/") &&
|
||||
pointer != "/languages")
|
||||
throw Error("immutable_id");
|
||||
(*delta.after)[Json::json_pointer(pointer)] = it.value();
|
||||
}
|
||||
for (const auto &field : action.value("unset", Json::array())) {
|
||||
auto pointer = field.get<std::string>();
|
||||
if (pointer.empty() || pointer[0] != '/' || pointer == "/id" || (name == "assets" && pointer == "/key"))
|
||||
throw Error("immutable_id");
|
||||
if (name == "manifest" && pointer != "/title" && !pointer.starts_with("/title/") &&
|
||||
pointer != "/start_date" && pointer != "/currency" && !pointer.starts_with("/currency/") &&
|
||||
pointer != "/languages")
|
||||
throw Error("immutable_id");
|
||||
auto split = pointer.rfind('/');
|
||||
auto parent = Json::json_pointer(pointer.substr(0, split));
|
||||
if (delta.after->contains(parent)) {
|
||||
auto leaf_pointer = Json::json_pointer(pointer);
|
||||
auto &container = (*delta.after)[parent];
|
||||
const auto leaf = leaf_pointer.back();
|
||||
if (container.is_object())
|
||||
container.erase(leaf);
|
||||
else if (container.is_array()) {
|
||||
const auto index = std::stoull(leaf);
|
||||
if (index < container.size())
|
||||
container.erase(container.begin() + std::ptrdiff_t(index));
|
||||
}
|
||||
}
|
||||
}
|
||||
} else
|
||||
throw Error("invalid_change");
|
||||
}
|
||||
transaction.changes.erase(std::remove_if(transaction.changes.begin(), transaction.changes.end(),
|
||||
[](const Delta &d) { return d.before == d.after; }),
|
||||
transaction.changes.end());
|
||||
// Membership is edited once, at the club, and stays consistent in each
|
||||
// affected league. This derived change belongs to the same undo frame.
|
||||
std::map<std::string, Json> memberships;
|
||||
for (const auto &d : transaction.changes)
|
||||
if (d.table == "clubs") {
|
||||
const auto old_league = d.before ? str(*d.before, "competition") : "";
|
||||
const auto new_league = d.after ? str(*d.after, "competition") : "";
|
||||
if (old_league == new_league)
|
||||
continue;
|
||||
for (auto league : {old_league, new_league})
|
||||
if (!league.empty()) {
|
||||
auto *comp = w.find("competitions", league);
|
||||
if (!memberships.contains(league)) {
|
||||
if (comp)
|
||||
memberships[league] = *comp;
|
||||
for (const auto &staged_delta : transaction.changes)
|
||||
if (staged_delta.table == "competitions" && staged_delta.id == league && staged_delta.after)
|
||||
memberships[league] = *staged_delta.after;
|
||||
if (!memberships.contains(league))
|
||||
throw Error("missing_reference");
|
||||
}
|
||||
auto &members = memberships[league]["members"];
|
||||
if (members.is_null())
|
||||
members = Json::array();
|
||||
if (!members.is_array())
|
||||
throw Error("invalid_change");
|
||||
members.erase(std::remove(members.begin(), members.end(), Json(d.id)), members.end());
|
||||
if (league == new_league)
|
||||
members.push_back(d.id);
|
||||
}
|
||||
}
|
||||
for (auto &[id, after] : memberships) {
|
||||
bool found = false;
|
||||
for (auto &d : transaction.changes)
|
||||
if (d.table == "competitions" && d.id == id) {
|
||||
d.after = after;
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
if (!found)
|
||||
transaction.changes.push_back({"competitions", id, *w.find("competitions", id), after});
|
||||
}
|
||||
if (transaction.changes.empty() && transaction.files.empty())
|
||||
return {{"changed", false}, {"revision", revision_}, {"created", created}};
|
||||
try {
|
||||
frame(transaction, true);
|
||||
for (auto &change : transaction.changes)
|
||||
if (!change.after) {
|
||||
auto refs = w.references(change.id);
|
||||
if (!refs.empty()) {
|
||||
Json list = Json::array();
|
||||
for (auto &[table, id] : refs)
|
||||
list.push_back({{"table", table}, {"id", id}});
|
||||
throw Error("record_referenced", {{"references", list}});
|
||||
}
|
||||
}
|
||||
for (const auto &problem : w.validate())
|
||||
if (problem["severity"] == "error")
|
||||
throw Error("validation_failed", {{"diagnostics", w.validate()}});
|
||||
} catch (...) {
|
||||
frame(transaction, false);
|
||||
throw;
|
||||
}
|
||||
history_.resize(cursor_);
|
||||
history_.push_back(std::move(transaction));
|
||||
++cursor_;
|
||||
++next_state_;
|
||||
++revision_;
|
||||
if (history_.size() > 100) {
|
||||
history_.erase(history_.begin());
|
||||
--cursor_;
|
||||
}
|
||||
return {{"changed", true}, {"revision", revision_}, {"created", created}};
|
||||
}
|
||||
Json Session::import_image(const Json &args) {
|
||||
auto &w = world();
|
||||
std::string original, extension, original_name;
|
||||
const auto source_key = str(args, "source_key", str(args, "key"));
|
||||
const auto *existing = w.find("assets", source_key);
|
||||
if (args.contains("file")) {
|
||||
original = read_file(path(str(args, "file")));
|
||||
extension = folded(utf8(path(str(args, "file")).extension()));
|
||||
original_name = utf8(path(str(args, "file")).filename());
|
||||
} else if (source_key.starts_with("portrait:") && w.find("players", source_key.substr(9))) {
|
||||
auto value = asset_bytes(source_key);
|
||||
original = std::move(value.first);
|
||||
extension = value.second;
|
||||
original_name = w.title(*w.find("players", source_key.substr(9)));
|
||||
} else {
|
||||
if (!existing)
|
||||
throw Error("record_missing");
|
||||
auto source = str(existing->value("x-editor", Json::object()), "original");
|
||||
if (source.empty())
|
||||
source = w.asset_file(source_key);
|
||||
original = w.store->read(source);
|
||||
extension = folded(utf8(path(source).extension()));
|
||||
original_name = text(existing->value("name", Json(str(args, "key"))));
|
||||
}
|
||||
if (extension != ".png" && extension != ".jpg" && extension != ".jpeg" && extension != ".webp" &&
|
||||
extension != ".svg")
|
||||
throw Error("invalid_image");
|
||||
auto result = images::transform(original, extension, args.value("transform", Json::object()));
|
||||
auto key = str(args, "key");
|
||||
const auto target = args.value("target", Json::object());
|
||||
const auto target_table = str(target, "table");
|
||||
const auto target_field = str(target, "field",
|
||||
target_table == "players" || target_table == "staff" ? "photo"
|
||||
: target_table == "competitions" ? "trophy"
|
||||
: "crest");
|
||||
if (key.empty()) {
|
||||
if (!target.empty()) {
|
||||
auto id = str(target, "id");
|
||||
auto table = str(target, "table");
|
||||
key = "asset:" + table + '/' + id + '/' + target_field;
|
||||
} else
|
||||
key = new_id("asset:uploaded/");
|
||||
}
|
||||
if (!target.empty() && w.find("assets", key)) {
|
||||
for (const auto &[table, id] : w.references(key))
|
||||
if (table != str(target, "table") || id != str(target, "id")) {
|
||||
key = "asset:editor/" + target_table + '/' + str(target, "id") + '/' + target_field;
|
||||
break;
|
||||
}
|
||||
}
|
||||
const auto original_hash = content::sha256(original), edited_hash = content::sha256(result.bytes);
|
||||
auto source_file = "x-editor/originals/" + original_hash + extension;
|
||||
auto output_file = "assets/edited/" + edited_hash + result.extension;
|
||||
std::vector<FileDelta> files;
|
||||
for (auto &[name, data] :
|
||||
std::vector<std::pair<std::string, std::string>>{{source_file, original}, {output_file, result.bytes}}) {
|
||||
if (!w.store->contains(name))
|
||||
files.push_back({name, w.store->overlay(name), std::make_shared<const std::string>(std::move(data))});
|
||||
}
|
||||
Json row{
|
||||
{"key", key},
|
||||
{"name", {{"default", original_name}}},
|
||||
{"files", {{result.extension == ".svg" ? "svg" : "native", output_file}}},
|
||||
{"width", result.width},
|
||||
{"height", result.height},
|
||||
{"source", "user-import"},
|
||||
{"author", "user-supplied"},
|
||||
{"license", "user-supplied"},
|
||||
{"kind", result.extension == ".svg" ? "vector" : "raster"},
|
||||
{"x-editor", {{"original", source_file}, {"original_sha256", original_hash}, {"transform", result.recipe}}}};
|
||||
if (!args.contains("file") && !source_key.empty() && source_key != key)
|
||||
row["x-editor"]["source_asset"] = source_key;
|
||||
Json changes = Json::array();
|
||||
if (const auto *before = w.find("assets", key)) {
|
||||
auto after = *before;
|
||||
after.update(row);
|
||||
Json set = Json::object();
|
||||
for (auto it = after.begin(); it != after.end(); ++it)
|
||||
if (it.key() != "key")
|
||||
set['/' + it.key()] = it.value();
|
||||
changes.push_back({{"op", "update"}, {"table", "assets"}, {"id", key}, {"set", set}});
|
||||
} else
|
||||
changes.push_back({{"op", "create"}, {"table", "assets"}, {"id", key}, {"data", row}});
|
||||
if (!target.empty())
|
||||
changes.push_back({{"op", "update"},
|
||||
{"table", str(target, "table")},
|
||||
{"id", str(target, "id")},
|
||||
{"set", {{'/' + target_field, key}}}});
|
||||
Json command{{"changes", changes}};
|
||||
if (args.contains("expected_revision"))
|
||||
command["expected_revision"] = args["expected_revision"];
|
||||
auto response = apply(command, std::move(files), "image_import");
|
||||
response["key"] = key;
|
||||
return response;
|
||||
}
|
||||
std::pair<std::string, std::string> Session::asset_bytes(const std::string &key) const {
|
||||
std::lock_guard guard(mutex_);
|
||||
if (!world_)
|
||||
return {images::silhouette(), ".svg"};
|
||||
if (key.starts_with("portrait:")) {
|
||||
const auto *player = world_->find("players", key.substr(9));
|
||||
if (player) {
|
||||
auto photo = world_->asset_file(str(*player, "photo"));
|
||||
if (!photo.empty())
|
||||
return {world_->store->read(photo), utf8(path(photo).extension())};
|
||||
auto recipe = player->value("appearance", Json::object());
|
||||
auto set = str(recipe, "set");
|
||||
const auto file = "assets/portrait-sets/" + set + "/set.json";
|
||||
if (safe_name(file) && world_->store->contains(file)) {
|
||||
const auto parts = Json::parse(world_->store->read(file));
|
||||
int width = parts.value("width", 0), height = parts.value("height", 0);
|
||||
if (width <= 0 || height <= 0 || width > 8192 || height > 8192 ||
|
||||
uint64_t(width) * height > 32ull * 1024 * 1024)
|
||||
throw Error("image_dimensions");
|
||||
images::Raster portrait{width, height, std::vector<uint8_t>(size_t(width) * height * 4)};
|
||||
auto paint = [&](const std::string &asset, int x, int y) {
|
||||
auto input = world_->asset_file(asset);
|
||||
if (input.empty())
|
||||
return;
|
||||
auto layer = images::decode(world_->store->read(input), utf8(path(input).extension()));
|
||||
for (int sy = 0; sy < layer.height; ++sy)
|
||||
for (int sx = 0; sx < layer.width; ++sx) {
|
||||
int dx = x + sx, dy = y + sy;
|
||||
if (dx < 0 || dy < 0 || dx >= width || dy >= height)
|
||||
continue;
|
||||
const auto *src = layer.pixels.data() + (size_t(sy) * layer.width + sx) * 4;
|
||||
auto *dst = portrait.pixels.data() + (size_t(dy) * width + dx) * 4;
|
||||
const unsigned alpha = src[3] * 255u + dst[3] * (255u - src[3]);
|
||||
for (int c = 0; c < 3; ++c)
|
||||
dst[c] =
|
||||
alpha
|
||||
? uint8_t((src[c] * src[3] * 255u + dst[c] * dst[3] * (255u - src[3])) / alpha)
|
||||
: 0;
|
||||
dst[3] = uint8_t((alpha + 127) / 255);
|
||||
}
|
||||
};
|
||||
auto backgrounds = parts.value("backgrounds", Json::array());
|
||||
auto background = recipe.value("background", size_t(0));
|
||||
if (background < backgrounds.size()) {
|
||||
const auto &b = backgrounds[background];
|
||||
paint(str(b, "asset"), b.value("x", 0), b.value("y", 0));
|
||||
}
|
||||
auto layers = parts.value("layers", Json::array()), choices = recipe.value("layers", Json::array());
|
||||
for (size_t i = 0; i < std::min(layers.size(), choices.size()); ++i) {
|
||||
auto options = layers[i].value("parts", Json::array());
|
||||
const auto choice = choices[i].get<size_t>();
|
||||
if (choice < options.size())
|
||||
paint(options[choice].get<std::string>(), layers[i].value("x", 0), layers[i].value("y", 0));
|
||||
}
|
||||
return {images::encode_png(portrait), ".png"};
|
||||
}
|
||||
}
|
||||
return {images::silhouette(), ".svg"};
|
||||
}
|
||||
auto file = key.starts_with("asset:") ? world_->asset_file(key) : key;
|
||||
if (file.empty() || !world_->store->contains(file))
|
||||
return {images::silhouette(), ".svg"};
|
||||
return {world_->store->read(file), utf8(path(file).extension())};
|
||||
}
|
||||
Json Session::execute(const std::string &command, const Json &args) {
|
||||
std::lock_guard guard(mutex_);
|
||||
if (!args.is_object())
|
||||
throw Error("invalid_change");
|
||||
if (args.contains("expected_revision") && args["expected_revision"].get<uint64_t>() != revision_)
|
||||
throw Error("stale_revision");
|
||||
if (command == "info")
|
||||
return info();
|
||||
if (command == "open" || command == "new" || command == "demo") {
|
||||
if (dirty() && !args.value("discard", false))
|
||||
throw Error("unsaved_changes");
|
||||
if (command == "open")
|
||||
replace(World::open(path(str(args, "path")), str(args, "start_date", "2026-07-01")));
|
||||
else
|
||||
replace(command == "demo" ? World::demo() : World::blank(str(args, "title", "Untitled world")));
|
||||
return info();
|
||||
}
|
||||
auto &w = world();
|
||||
if (command == "list")
|
||||
return w.query(args);
|
||||
if (command == "get") {
|
||||
auto name = str(args, "table"), id = str(args, "id");
|
||||
const auto *found = name == "manifest" ? &w.manifest : w.find(name, id);
|
||||
if (!found)
|
||||
throw Error("record_missing");
|
||||
return {{"record", *found}, {"revision", revision_}};
|
||||
}
|
||||
if (command == "rules")
|
||||
return w.rows("rules");
|
||||
if (command == "validate")
|
||||
return {{"diagnostics", w.validate()}, {"revision", revision_}};
|
||||
if (command == "history") {
|
||||
Json values = Json::array();
|
||||
for (size_t i = 0; i < history_.size(); ++i) {
|
||||
Json affected = Json::array();
|
||||
for (auto &delta : history_[i].changes)
|
||||
affected.push_back({{"table", delta.table},
|
||||
{"id", delta.id},
|
||||
{"before", delta.before ? *delta.before : Json()},
|
||||
{"after", delta.after ? *delta.after : Json()}});
|
||||
values.push_back({{"label", history_[i].label}, {"applied", i < cursor_}, {"changes", affected}});
|
||||
}
|
||||
return {{"items", values}, {"revision", revision_}};
|
||||
}
|
||||
if (command == "apply")
|
||||
return apply(args);
|
||||
if (command == "undo" || command == "redo") {
|
||||
if (args.contains("expected_revision") && args["expected_revision"].get<uint64_t>() != revision_)
|
||||
throw Error("stale_revision");
|
||||
if (command == "undo") {
|
||||
if (!cursor_)
|
||||
throw Error("nothing_to_undo");
|
||||
frame(history_[--cursor_], false);
|
||||
} else {
|
||||
if (cursor_ >= history_.size())
|
||||
throw Error("nothing_to_redo");
|
||||
frame(history_[cursor_++], true);
|
||||
}
|
||||
++revision_;
|
||||
return info();
|
||||
}
|
||||
if (command == "save") {
|
||||
const auto destination = args.contains("path") ? path(str(args, "path")) : saved_path_;
|
||||
if (destination.empty())
|
||||
throw Error("output_parent_missing");
|
||||
if (!saved_path_.empty() && fs::absolute(destination) == fs::absolute(saved_path_) &&
|
||||
fs::is_regular_file(saved_path_) &&
|
||||
(fs::last_write_time(saved_path_) != saved_time_ || fs::file_size(saved_path_) != saved_size_))
|
||||
throw Error("source_changed");
|
||||
w.save(destination);
|
||||
saved_path_ = fs::absolute(destination);
|
||||
saved_time_ = fs::last_write_time(saved_path_);
|
||||
saved_size_ = fs::file_size(saved_path_);
|
||||
saved_state_ = state_;
|
||||
return info();
|
||||
}
|
||||
if (command == "roster.move") {
|
||||
auto person = str(args, "player");
|
||||
Json set{{"/team", args.value("team", Json())}};
|
||||
if (args.contains("number"))
|
||||
set["/squad_number"] = args["number"];
|
||||
auto change = Json{{"op", "update"}, {"table", "players"}, {"id", person}, {"set", set}};
|
||||
return apply({{"changes", Json::array({change})}}, {}, "move_player");
|
||||
}
|
||||
if (command == "roster.swap") {
|
||||
auto first = w.find("players", str(args, "first")), second = w.find("players", str(args, "second"));
|
||||
if (!first || !second || first == second)
|
||||
throw Error("invalid_change");
|
||||
Json changes = Json::array();
|
||||
for (auto pair : {std::pair{first, second}, std::pair{second, first}}) {
|
||||
Json set;
|
||||
for (auto field : {"team", "squad_number", "squad_order"})
|
||||
set['/' + std::string(field)] = pair.second->value(field, Json());
|
||||
changes.push_back({{"op", "update"}, {"table", "players"}, {"id", (*pair.first)["id"]}, {"set", set}});
|
||||
}
|
||||
return apply({{"changes", changes}}, {}, "swap_player");
|
||||
}
|
||||
if (command == "roster.order") {
|
||||
auto team = str(args, "team");
|
||||
auto order = args.value("players", Json::array());
|
||||
std::set<std::string> expected, actual;
|
||||
for (auto &row : w.rows("players"))
|
||||
if (str(row, "team") == team)
|
||||
expected.insert(str(row, "id"));
|
||||
for (auto &row : order)
|
||||
actual.insert(row.get<std::string>());
|
||||
if (expected != actual || actual.size() != order.size())
|
||||
throw Error("invalid_change");
|
||||
Json changes = Json::array();
|
||||
for (size_t i = 0; i < order.size(); ++i)
|
||||
changes.push_back(
|
||||
{{"op", "update"}, {"table", "players"}, {"id", order[i]}, {"set", {{"/squad_order", i}}}});
|
||||
return apply({{"changes", changes}}, {}, "roster");
|
||||
}
|
||||
if (command == "review.resolve") {
|
||||
auto record = w.find("review", str(args, "id"));
|
||||
if (!record)
|
||||
throw Error("record_missing");
|
||||
const auto choice = args.value("choice", size_t(0));
|
||||
auto alternatives = record->value("alternatives", Json::array());
|
||||
if (choice >= alternatives.size())
|
||||
throw Error("invalid_change");
|
||||
const auto chosen = alternatives[choice].at("value");
|
||||
Json changes =
|
||||
Json::array({{{"op", "update"},
|
||||
{"table", "review"},
|
||||
{"id", str(args, "id")},
|
||||
{"set", {{"/resolved", true}, {"/selected_index", choice}, {"/chosen_value", chosen}}}}});
|
||||
if (record->contains("entity") && record->contains("field"))
|
||||
changes.push_back({{"op", "update"},
|
||||
{"table", record->value("table", "players")},
|
||||
{"id", (*record)["entity"]},
|
||||
{"set", {{str(*record, "field"), chosen}}}});
|
||||
return apply({{"changes", changes}}, {}, "resolve");
|
||||
}
|
||||
if (command == "asset.import" || command == "asset.edit")
|
||||
return import_image(args);
|
||||
if (command == "asset.preview") {
|
||||
auto [bytes, extension] = asset_bytes(str(args, "key"));
|
||||
auto raster = images::preview(bytes, extension, args.value("transform", Json::object()), 1024);
|
||||
return {{"mimeType", "image/png"},
|
||||
{"data", images::base64(images::encode_png(raster))},
|
||||
{"width", raster.width},
|
||||
{"height", raster.height}};
|
||||
}
|
||||
if (command == "asset.export") {
|
||||
auto [bytes, extension] = asset_bytes(str(args, "key"));
|
||||
auto data = images::encode_png(images::decode(bytes, extension, 2048));
|
||||
auto target = path(str(args, "path"));
|
||||
if (folded(utf8(target.extension())) != ".png")
|
||||
throw Error("invalid_image");
|
||||
write_atomic(target, data);
|
||||
return {{"path", utf8(target)}};
|
||||
}
|
||||
throw Error("invalid_change", {{"command", command}});
|
||||
}
|
||||
} // namespace bmh::editor
|
||||
@@ -0,0 +1,45 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#pragma once
|
||||
#include "editor/world.hpp"
|
||||
#include <mutex>
|
||||
|
||||
namespace bmh::editor {
|
||||
// One command boundary for native widgets, MCP and synthetic tests. No command
|
||||
// owns game rules or operates on a live career.
|
||||
class Session {
|
||||
public:
|
||||
Json execute(const std::string &command, const Json &args = Json::object());
|
||||
std::pair<std::string, std::string> asset_bytes(const std::string &key_or_path) const;
|
||||
|
||||
private:
|
||||
struct Delta {
|
||||
std::string table, id;
|
||||
std::optional<Json> before, after;
|
||||
};
|
||||
struct FileDelta {
|
||||
std::string name;
|
||||
std::shared_ptr<const std::string> before, after;
|
||||
};
|
||||
struct Frame {
|
||||
std::string label;
|
||||
std::vector<Delta> changes;
|
||||
std::vector<FileDelta> files;
|
||||
uint64_t before = 0, after = 0;
|
||||
};
|
||||
mutable std::recursive_mutex mutex_;
|
||||
std::unique_ptr<World> world_;
|
||||
std::vector<Frame> history_;
|
||||
size_t cursor_ = 0;
|
||||
uint64_t revision_ = 0, state_ = 0, next_state_ = 1, saved_state_ = 0;
|
||||
fs::path saved_path_;
|
||||
fs::file_time_type saved_time_{};
|
||||
uint64_t saved_size_ = 0;
|
||||
World &world();
|
||||
bool dirty() const;
|
||||
Json info() const;
|
||||
Json apply(const Json &, std::vector<FileDelta> files = {}, const std::string &label = "edit");
|
||||
void frame(const Frame &, bool forward);
|
||||
void replace(World value);
|
||||
Json import_image(const Json &);
|
||||
};
|
||||
} // namespace bmh::editor
|
||||
@@ -0,0 +1,75 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#pragma once
|
||||
#include <filesystem>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <nlohmann/json.hpp>
|
||||
#include <optional>
|
||||
#include <set>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace bmh::editor {
|
||||
using Json = nlohmann::ordered_json;
|
||||
namespace fs = std::filesystem;
|
||||
struct Error : std::runtime_error {
|
||||
std::string code;
|
||||
Json details;
|
||||
explicit Error(std::string key, Json info = Json::object())
|
||||
: std::runtime_error(key), code(std::move(key)), details(std::move(info)) {}
|
||||
};
|
||||
inline std::string text(const Json &value) {
|
||||
if (value.is_string())
|
||||
return value.get<std::string>();
|
||||
if (value.is_null())
|
||||
return {};
|
||||
if (value.is_object()) {
|
||||
for (auto key : {"default", "known_as", "full"})
|
||||
if (value.contains(key) && value[key].is_string() && !value[key].get<std::string>().empty())
|
||||
return value[key].get<std::string>();
|
||||
if (value.contains("first") || value.contains("last")) {
|
||||
auto first = value.value("first", Json());
|
||||
auto last = value.value("last", Json());
|
||||
return text(first) + (text(first).empty() || text(last).empty() ? "" : " ") + text(last);
|
||||
}
|
||||
}
|
||||
return value.dump();
|
||||
}
|
||||
inline std::string str(const Json &object, std::string_view key, const std::string &fallback = {}) {
|
||||
auto it = object.find(std::string(key));
|
||||
return it == object.end() || !it->is_string() ? fallback : it->get<std::string>();
|
||||
}
|
||||
inline std::string escaped(std::string_view value) {
|
||||
std::string out;
|
||||
for (auto c : value)
|
||||
switch (c) {
|
||||
case '&':
|
||||
out += "&";
|
||||
break;
|
||||
case '<':
|
||||
out += "<";
|
||||
break;
|
||||
case '>':
|
||||
out += ">";
|
||||
break;
|
||||
case '"':
|
||||
out += """;
|
||||
break;
|
||||
case '\'':
|
||||
out += "'";
|
||||
break;
|
||||
default:
|
||||
out += c;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
std::string utf8(const fs::path &);
|
||||
fs::path path(std::string_view);
|
||||
std::string read_file(const fs::path &, uint64_t maximum = 64ull * 1024 * 1024);
|
||||
void write_atomic(const fs::path &, std::string_view, bool overwrite = true);
|
||||
std::string new_id(const std::string &prefix);
|
||||
std::string folded(std::string value);
|
||||
bool safe_name(std::string_view);
|
||||
} // namespace bmh::editor
|
||||
@@ -0,0 +1,11 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#pragma once
|
||||
#include "editor/mcp.hpp"
|
||||
namespace bmh::editor {
|
||||
struct UiConfig {
|
||||
fs::path assets, screenshot;
|
||||
std::string page = "overview";
|
||||
int quit_after_ms = 0;
|
||||
};
|
||||
int run_ui(Session &, Options &, McpServer &, const UiConfig &);
|
||||
} // namespace bmh::editor
|
||||
@@ -0,0 +1,543 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#include "editor/world.hpp"
|
||||
#include "content/digest.hpp"
|
||||
#include "content/package.hpp"
|
||||
#include "import/obw.hpp"
|
||||
#include "launch/game_data.hpp"
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <functional>
|
||||
#include <limits>
|
||||
|
||||
namespace bmh::editor {
|
||||
namespace {
|
||||
Json table(const std::string &name) { return {{"schema", name + "@1.1"}, {"items", Json::array()}}; }
|
||||
bool date_valid(const Json &value) {
|
||||
if (value.is_null())
|
||||
return true;
|
||||
if (!value.is_string())
|
||||
return false;
|
||||
auto s = value.get<std::string>();
|
||||
if (s.size() != 10 || s[4] != '-' || s[7] != '-')
|
||||
return false;
|
||||
for (size_t i = 0; i < s.size(); ++i)
|
||||
if (i != 4 && i != 7 && (s[i] < '0' || s[i] > '9'))
|
||||
return false;
|
||||
int y = std::stoi(s.substr(0, 4)), m = std::stoi(s.substr(5, 2)), d = std::stoi(s.substr(8));
|
||||
static constexpr int days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
|
||||
return y >= 1583 && m >= 1 && m <= 12 && d >= 1 &&
|
||||
d <= days[m - 1] + (m == 2 && (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)));
|
||||
}
|
||||
void walk_refs(const Json &node, const std::function<void(const std::string &)> &emit, bool extension = false) {
|
||||
if (node.is_object()) {
|
||||
for (auto it = node.begin(); it != node.end(); ++it) {
|
||||
if (it.key() == "id" || it.key().starts_with("x-") || it.key() == "sources")
|
||||
continue;
|
||||
if (it.value().is_string() &&
|
||||
(it.key() == "nation" || it.key() == "team" || it.key() == "competition" || it.key() == "stadium" ||
|
||||
it.key() == "owner" || it.key() == "person" || it.key() == "national_team" || it.key() == "photo" ||
|
||||
it.key() == "crest" || it.key() == "trophy"))
|
||||
emit(it.value());
|
||||
else if ((it.key() == "nationalities" || it.key() == "members" || it.key() == "participants" ||
|
||||
it.key() == "teams") &&
|
||||
it.value().is_array()) {
|
||||
for (const auto &value : it.value())
|
||||
if (value.is_string())
|
||||
emit(value);
|
||||
} else if (it.value().is_object() || it.value().is_array())
|
||||
walk_refs(it.value(), emit, extension);
|
||||
}
|
||||
} else if (node.is_array())
|
||||
for (const auto &child : node)
|
||||
walk_refs(child, emit, extension);
|
||||
}
|
||||
Json parse(const std::string &data, const std::string &file) {
|
||||
try {
|
||||
return Json::parse(data);
|
||||
} catch (const Json::exception &e) {
|
||||
throw Error("invalid_json", {{"file", file}, {"detail", e.what()}});
|
||||
}
|
||||
}
|
||||
} // namespace
|
||||
const std::vector<std::string> &World::tables() {
|
||||
static const std::vector<std::string> names{"nations", "competitions", "clubs", "players", "stadiums",
|
||||
"staff", "contracts", "finance", "rules", "calendar",
|
||||
"assets", "review", "image-edits"};
|
||||
return names;
|
||||
}
|
||||
std::string World::file_for(const std::string &name) {
|
||||
if (name == "assets")
|
||||
return "assets/index.json";
|
||||
if (name == "review" || name == "image-edits")
|
||||
return "x-editor/" + name + ".json";
|
||||
return "world/" + name + ".json";
|
||||
}
|
||||
std::string World::identity(const Json &row, const std::string &name) {
|
||||
return str(row, name == "assets" ? "key" : "id");
|
||||
}
|
||||
World World::blank(const std::string &title_value) {
|
||||
World w;
|
||||
w.manifest = {{"format", "openbmh-world"},
|
||||
{"format_version", "1.1"},
|
||||
{"min_reader", "1.1"},
|
||||
{"kind", "world"},
|
||||
{"title", {{"default", title_value}}},
|
||||
{"generator", "OpenBMH Editor POC"},
|
||||
{"provenance", "native"},
|
||||
{"content_license", "user-supplied"},
|
||||
{"start_date", "2026-07-01"},
|
||||
{"currency", {{"code", "EUR"}, {"minor_units", 2}}},
|
||||
{"languages", {"de", "en"}},
|
||||
{"requires", {"editor:world-v1"}},
|
||||
{"extensions", Json::array()},
|
||||
{"x-editor", {{"profile", "editor-world-v1"}, {"playable", false}}}};
|
||||
for (auto &name : tables())
|
||||
w.docs_[file_for(name)] = table(name == "assets" ? "asset-index" : name);
|
||||
w.docs_[file_for("rules")]["items"].push_back({{"id", "rule:unrated@1"},
|
||||
{"type", "attribute_set"},
|
||||
{"attribute_set", "unrated@1"},
|
||||
{"fields", Json::object()}});
|
||||
for (auto &[name, _] : w.docs_)
|
||||
w.dirty_.insert(name);
|
||||
return w;
|
||||
}
|
||||
World World::open(const fs::path &source, const std::string &start_date) {
|
||||
World w;
|
||||
const auto input = fs::absolute(source);
|
||||
bool legacy = false;
|
||||
if (fs::is_directory(input))
|
||||
legacy = !fs::exists(input / "manifest.json");
|
||||
else
|
||||
legacy = folded(utf8(input.extension())) == ".exe";
|
||||
if (legacy) {
|
||||
if (!date_valid(start_date))
|
||||
throw Error("invalid_date");
|
||||
bmh::obw::Options options;
|
||||
options.start_date = start_date;
|
||||
auto docs = bmh::obw::import_installation(input, options);
|
||||
for (auto &[name, bytes] : docs)
|
||||
w.store->set(name, std::make_shared<const std::string>(std::move(bytes)));
|
||||
w.imported = true;
|
||||
} else
|
||||
w.store = ArchiveStore::open(input);
|
||||
w.manifest = parse(w.store->read("manifest.json"), "manifest.json");
|
||||
if (str(w.manifest, "format") != "openbmh-world" || str(w.manifest, "kind") != "world")
|
||||
throw Error("not_world");
|
||||
auto version = str(w.manifest, "format_version");
|
||||
if (!version.starts_with("1."))
|
||||
throw Error("unsupported_version", {{"version", version}});
|
||||
const bool editor = str(w.manifest.value("x-editor", Json::object()), "profile") == "editor-world-v1";
|
||||
if (editor && (version != "1.1" || str(w.manifest, "min_reader") != "1.1" ||
|
||||
w.manifest.value("x-editor", Json::object()).value("playable", true)))
|
||||
throw Error("unsupported_version");
|
||||
if (!editor) {
|
||||
// Only bounded 1.0 Classic packages use the Classic validator. Its
|
||||
// compatibility and seal checks are not relaxed by the new reader.
|
||||
if (!w.imported) {
|
||||
auto docs = bmh::obw::read(input);
|
||||
if (docs.contains("x-classic/seal.json"))
|
||||
bmh::content::verify(docs);
|
||||
}
|
||||
w.imported = true;
|
||||
}
|
||||
w.source_path = input;
|
||||
w.load();
|
||||
if (w.imported)
|
||||
w.editor_profile();
|
||||
return w;
|
||||
}
|
||||
void World::load() {
|
||||
for (auto &name : tables()) {
|
||||
auto file = file_for(name);
|
||||
if (store->contains(file)) {
|
||||
auto bytes = store->read(file);
|
||||
auto value = parse(bytes, file);
|
||||
if (!value.is_object() || !value.contains("items") || !value["items"].is_array())
|
||||
throw Error("invalid_table", {{"file", file}});
|
||||
original_[file] = std::move(bytes);
|
||||
docs_[file] = std::move(value);
|
||||
} else {
|
||||
docs_[file] = table(name == "assets" ? "asset-index" : name);
|
||||
dirty_.insert(file);
|
||||
}
|
||||
}
|
||||
}
|
||||
void World::editor_profile() {
|
||||
manifest["x-editor"] = {{"profile", "editor-world-v1"},
|
||||
{"playable", false},
|
||||
{"original_manifest", manifest},
|
||||
{"source_filename", utf8(source_path.filename())}};
|
||||
manifest["format_version"] = "1.1";
|
||||
manifest["min_reader"] = "1.1";
|
||||
manifest["requires"] = Json::array({"editor:world-v1"});
|
||||
manifest["generator"] = "OpenBMH Editor POC";
|
||||
// The historical seal remains original evidence only. The editor profile
|
||||
// deliberately cannot be passed to the Classic runtime as sealed content.
|
||||
for (auto &comp : rows("competitions")) {
|
||||
if (!comp.contains("members")) {
|
||||
comp["members"] = Json::array();
|
||||
for (auto &stage : comp.value("stages", Json::array()))
|
||||
for (auto &slot : stage.value("slots", Json::array())) {
|
||||
auto teams = slot.value("teams", Json::array());
|
||||
if (slot.contains("team") && slot["team"].is_string())
|
||||
teams.push_back(slot["team"]);
|
||||
for (const auto &team : teams)
|
||||
if (team.is_string()) {
|
||||
const auto tid = team.get<std::string>();
|
||||
if (str(comp, "type") == "league")
|
||||
if (auto club = find("clubs", tid))
|
||||
(*club)["competition"] = comp["id"];
|
||||
if (std::find(comp["members"].begin(), comp["members"].end(), tid) == comp["members"].end())
|
||||
comp["members"].push_back(tid);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for (auto &person : rows("players")) {
|
||||
if (person.contains("x-legacy") && person["x-legacy"].contains("squad_row"))
|
||||
person["squad_order"] = person["x-legacy"]["squad_row"];
|
||||
}
|
||||
touch("competitions");
|
||||
touch("clubs");
|
||||
touch("players");
|
||||
}
|
||||
Json &World::document(const std::string &name) { return docs_.at(file_for(name)); }
|
||||
const Json &World::document(const std::string &name) const { return docs_.at(file_for(name)); }
|
||||
Json &World::rows(const std::string &name) { return document(name)["items"]; }
|
||||
const Json &World::rows(const std::string &name) const { return document(name).at("items"); }
|
||||
const Json *World::find(const std::string &name, const std::string &id) const {
|
||||
for (auto &row : rows(name))
|
||||
if (identity(row, name) == id)
|
||||
return &row;
|
||||
return nullptr;
|
||||
}
|
||||
Json *World::find(const std::string &name, const std::string &id) {
|
||||
return const_cast<Json *>(std::as_const(*this).find(name, id));
|
||||
}
|
||||
void World::touch(const std::string &name) { dirty_.insert(file_for(name)); }
|
||||
void World::change(const std::string &name, const std::string &id, const std::optional<Json> &after) {
|
||||
auto &values = rows(name);
|
||||
for (auto i = values.begin(); i != values.end(); ++i)
|
||||
if (identity(*i, name) == id) {
|
||||
if (after)
|
||||
*i = *after;
|
||||
else
|
||||
values.erase(i);
|
||||
touch(name);
|
||||
return;
|
||||
}
|
||||
if (after) {
|
||||
values.push_back(*after);
|
||||
touch(name);
|
||||
}
|
||||
}
|
||||
std::string World::title(const Json &value, const std::string &language) const {
|
||||
if (value.contains("name")) {
|
||||
const auto &name = value["name"];
|
||||
if (name.is_object() && name.contains(language) && name[language].is_string())
|
||||
return name[language];
|
||||
return text(name);
|
||||
}
|
||||
return str(value, "key", str(value, "id"));
|
||||
}
|
||||
Json World::statistics() const {
|
||||
Json counts = Json::object();
|
||||
for (auto &name : tables())
|
||||
counts[name] = rows(name).size();
|
||||
return {{"title", text(manifest.value("title", Json()))},
|
||||
{"start_date", manifest.value("start_date", Json())},
|
||||
{"format_version", manifest.value("format_version", Json())},
|
||||
{"counts", counts},
|
||||
{"source", utf8(source_path)},
|
||||
{"imported", imported},
|
||||
{"profile", "editor-world-v1"},
|
||||
{"playable", false}};
|
||||
}
|
||||
Json World::query(const Json &args) const {
|
||||
const auto name = str(args, "table", "clubs");
|
||||
if (std::find(tables().begin(), tables().end(), name) == tables().end())
|
||||
throw Error("unknown_table");
|
||||
std::map<std::string, const Json *> clubs;
|
||||
for (const auto &club : rows("clubs"))
|
||||
clubs[str(club, "id")] = &club;
|
||||
std::vector<const Json *> matches;
|
||||
const auto search = folded(str(args, "search")), nation = str(args, "nation"), comp = str(args, "competition"),
|
||||
team = str(args, "team");
|
||||
for (const auto &row : rows(name)) {
|
||||
const Json *club =
|
||||
name == "clubs" ? &row : (clubs.contains(str(row, "team")) ? clubs[str(row, "team")] : nullptr);
|
||||
if (!nation.empty() && str(row, "nation") != nation && (!club || str(*club, "nation") != nation))
|
||||
continue;
|
||||
if (!comp.empty() && str(row, "competition") != comp && (!club || str(*club, "competition") != comp))
|
||||
continue;
|
||||
if (!team.empty() && str(row, "team") != team && str(row, "owner") != team)
|
||||
continue;
|
||||
if (args.contains("role") && str(row, "role") != str(args, "role"))
|
||||
continue;
|
||||
if (name == "competitions" && args.value("leagues_only", false) && str(row, "type") != "league")
|
||||
continue;
|
||||
if (name == "review" && args.value("unresolved_only", false) && row.value("resolved", false))
|
||||
continue;
|
||||
if (!search.empty() && folded(title(row)).find(search) == std::string::npos &&
|
||||
folded(identity(row, name)).find(search) == std::string::npos &&
|
||||
(!club || folded(title(*club)).find(search) == std::string::npos))
|
||||
continue;
|
||||
matches.push_back(&row);
|
||||
}
|
||||
auto sort = str(args, "sort", "name");
|
||||
bool descending = args.value("descending", false);
|
||||
std::stable_sort(matches.begin(), matches.end(), [&](auto a, auto b) {
|
||||
Json av = sort == "name" ? Json(folded(title(*a))) : a->value(sort, Json());
|
||||
Json bv = sort == "name" ? Json(folded(title(*b))) : b->value(sort, Json());
|
||||
if (av == bv)
|
||||
return identity(*a, name) < identity(*b, name);
|
||||
return descending ? av > bv : av < bv;
|
||||
});
|
||||
const auto offset = std::max<int64_t>(0, args.value("offset", int64_t(0)));
|
||||
const auto limit = std::clamp<int64_t>(args.value("limit", int64_t(200)), 1, 200);
|
||||
Json result = Json::array();
|
||||
for (size_t i = size_t(std::min<int64_t>(offset, int64_t(matches.size())));
|
||||
i < matches.size() && int64_t(result.size()) < limit; ++i)
|
||||
result.push_back(*matches[i]);
|
||||
return {{"items", std::move(result)}, {"total", matches.size()}, {"offset", offset}, {"limit", limit}};
|
||||
}
|
||||
std::vector<std::pair<std::string, std::string>> World::references(const std::string &id) const {
|
||||
std::vector<std::pair<std::string, std::string>> found;
|
||||
for (auto &name : tables())
|
||||
if (name != "review" && name != "image-edits" && name != "assets")
|
||||
for (auto &row : rows(name))
|
||||
if (identity(row, name) != id) {
|
||||
bool referenced = false;
|
||||
walk_refs(row, [&](auto &ref) {
|
||||
if (ref == id)
|
||||
referenced = true;
|
||||
});
|
||||
if (referenced)
|
||||
found.emplace_back(name, identity(row, name));
|
||||
}
|
||||
return found;
|
||||
}
|
||||
std::string World::asset_file(const std::string &key) const {
|
||||
auto row = find("assets", key);
|
||||
if (!row || !row->contains("files") || !(*row)["files"].is_object())
|
||||
return {};
|
||||
for (auto type : {"svg", "native", "default", "original", "512", "256", "128", "64"}) {
|
||||
auto found = (*row)["files"].find(type);
|
||||
if (found != (*row)["files"].end() && found->is_string() && store->contains(*found))
|
||||
return *found;
|
||||
}
|
||||
for (auto &value : (*row)["files"])
|
||||
if (value.is_string() && store->contains(value))
|
||||
return value;
|
||||
return {};
|
||||
}
|
||||
std::string World::portrait(const Json &person) const {
|
||||
auto key = str(person, "photo");
|
||||
auto file = asset_file(key.empty() ? "asset:player/" + str(person, "id") + "/photo" : key);
|
||||
return file;
|
||||
}
|
||||
Json World::validate() const {
|
||||
Json diagnostics = Json::array();
|
||||
auto issue = [&](const std::string &severity, const std::string &code, const std::string &name,
|
||||
const std::string &id, Json details = Json::object()) {
|
||||
diagnostics.push_back(
|
||||
{{"severity", severity}, {"code", code}, {"table", name}, {"id", id}, {"details", details}});
|
||||
};
|
||||
std::map<std::string, std::string> ids;
|
||||
const auto editor = manifest.value("x-editor", Json::object());
|
||||
const auto requirements = manifest.value("requires", Json::array());
|
||||
if (str(manifest, "format") != "openbmh-world" || str(manifest, "kind") != "world" ||
|
||||
str(manifest, "format_version") != "1.1" || str(manifest, "min_reader") != "1.1" || !editor.is_object() ||
|
||||
str(editor, "profile") != "editor-world-v1" || !editor.contains("playable") || editor["playable"] != false ||
|
||||
!requirements.is_array() ||
|
||||
std::find(requirements.begin(), requirements.end(), Json("editor:world-v1")) == requirements.end())
|
||||
issue("error", "invalid_manifest", "manifest", "manifest");
|
||||
if (!date_valid(manifest.value("start_date", Json())))
|
||||
issue("error", "invalid_date", "manifest", "manifest");
|
||||
std::map<std::string, const Json *> attribute_sets;
|
||||
for (auto &rule : rows("rules"))
|
||||
if (str(rule, "type") == "attribute_set") {
|
||||
auto key = str(rule, "attribute_set", str(rule, "id"));
|
||||
attribute_sets[key] = &rule;
|
||||
if (key.starts_with("rule:"))
|
||||
attribute_sets[key.substr(5)] = &rule;
|
||||
}
|
||||
for (const auto &name : tables()) {
|
||||
if (name == "image-edits" || name == "review")
|
||||
continue;
|
||||
for (const auto &row : rows(name)) {
|
||||
auto id = identity(row, name);
|
||||
if (id.empty() || !ids.emplace(id, name).second)
|
||||
issue("error", "duplicate_id", name, id);
|
||||
if (name != "assets" && name != "calendar" && name != "rules" && title(row).empty())
|
||||
issue("warning", "missing_name", name, id);
|
||||
if (name == "players") {
|
||||
if (!date_valid(row.value("born", Json())))
|
||||
issue("error", "invalid_date", name, id);
|
||||
if (!row.contains("born") && !row.contains("age_at_start"))
|
||||
issue("warning", "missing_birthday", name, id);
|
||||
if (row.contains("born") && row["born"].is_null())
|
||||
issue("warning", "missing_birthday", name, id);
|
||||
const auto attrs = row.value("attributes", Json::object());
|
||||
if (!attrs.is_object()) {
|
||||
issue("error", "invalid_attributes", name, id);
|
||||
continue;
|
||||
}
|
||||
const auto set = attribute_sets.find(str(row, "attribute_set"));
|
||||
if (set == attribute_sets.end())
|
||||
issue("warning", "unknown_attribute_set", name, id);
|
||||
else {
|
||||
auto fields = set->second->value("fields", Json::object());
|
||||
for (auto it = attrs.begin(); it != attrs.end(); ++it) {
|
||||
if (it->is_null() || !fields.contains(it.key()))
|
||||
continue;
|
||||
const auto &field = fields[it.key()];
|
||||
if (!it->is_number_integer() ||
|
||||
it->get<int64_t>() < field.value("min", std::numeric_limits<int64_t>::min()) ||
|
||||
it->get<int64_t>() > field.value("max", std::numeric_limits<int64_t>::max()))
|
||||
issue("error", "attribute_range", name, id, {{"field", it.key()}});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for (auto &name : tables())
|
||||
if (name != "review" && name != "image-edits")
|
||||
for (auto &row : rows(name))
|
||||
walk_refs(row, [&](const std::string &ref) {
|
||||
if (!ref.empty() && !ids.contains(ref) && !ref.starts_with("asset:"))
|
||||
issue("error", "missing_reference", name, identity(row, name), {{"reference", ref}});
|
||||
});
|
||||
const std::map<std::string, std::string> reference_types{{"team", "clubs"}, {"owner", "clubs"},
|
||||
{"nation", "nations"}, {"competition", "competitions"},
|
||||
{"stadium", "stadiums"}, {"national_team", "clubs"}};
|
||||
for (auto &name : tables())
|
||||
if (name != "review" && name != "image-edits")
|
||||
for (const auto &row : rows(name)) {
|
||||
for (const auto &[field, target] : reference_types)
|
||||
if (row.contains(field) && !row[field].is_null()) {
|
||||
const auto key = str(row, field);
|
||||
if (!row[field].is_string() || (!key.empty() && ids.contains(key) && ids.at(key) != target))
|
||||
issue("error", "missing_reference", name, identity(row, name),
|
||||
{{"field", field}, {"expected_table", target}});
|
||||
}
|
||||
for (const auto &[field, target] :
|
||||
std::map<std::string, std::string>{{"nationalities", "nations"}, {"members", "clubs"}})
|
||||
if (row.contains(field)) {
|
||||
if (!row[field].is_array())
|
||||
issue("error", "missing_reference", name, identity(row, name), {{"field", field}});
|
||||
else
|
||||
for (const auto &key : row[field])
|
||||
if (!key.is_string() ||
|
||||
(ids.contains(key.get<std::string>()) && ids.at(key.get<std::string>()) != target))
|
||||
issue("error", "missing_reference", name, identity(row, name),
|
||||
{{"field", field}, {"expected_table", target}});
|
||||
}
|
||||
}
|
||||
for (auto &asset : rows("assets")) {
|
||||
if (asset_file(str(asset, "key")).empty())
|
||||
issue("warning", "missing_asset", "assets", str(asset, "key"));
|
||||
}
|
||||
for (auto &review : rows("review"))
|
||||
if (!review.value("resolved", false))
|
||||
issue("warning", "review_open", "review", str(review, "id"));
|
||||
return diagnostics;
|
||||
}
|
||||
void World::save(const fs::path &destination) const {
|
||||
if (imported && !source_path.empty() &&
|
||||
fs::absolute(destination).lexically_normal() == source_path.lexically_normal())
|
||||
throw Error("preserve_source");
|
||||
const auto problems = validate();
|
||||
for (auto &row : problems)
|
||||
if (row["severity"] == "error")
|
||||
throw Error("validation_failed", {{"diagnostics", problems}});
|
||||
std::map<std::string, std::string> docs{{"manifest.json", manifest.dump(2)}};
|
||||
for (const auto &[file, value] : docs_)
|
||||
docs[file] = !dirty_.contains(file) && original_.contains(file) ? original_.at(file) : value.dump(2);
|
||||
store->save(destination, docs);
|
||||
}
|
||||
World World::demo() {
|
||||
auto w = blank("OpenBMH Editor – Demo");
|
||||
w.rows("nations").push_back({{"id", "nation:de"},
|
||||
{"name", {{"default", "Deutschland"}, {"en", "Germany"}}},
|
||||
{"confederation", "uefa"},
|
||||
{"playable", true}});
|
||||
w.rows("competitions")
|
||||
.push_back({{"id", "comp:demo"},
|
||||
{"name", {{"default", "Demo-Liga"}, {"en", "Demo league"}}},
|
||||
{"nation", "nation:de"},
|
||||
{"type", "league"},
|
||||
{"tier", 1},
|
||||
{"visible", true},
|
||||
{"members", {"club:north", "club:south"}},
|
||||
{"stages", Json::array()}});
|
||||
w.rows("rules").push_back({{"id", "demo@1"},
|
||||
{"type", "attribute_set"},
|
||||
{"fields",
|
||||
{{"strength", {{"min", 0}, {"max", 99}}},
|
||||
{"technique", {{"min", 0}, {"max", 99}}},
|
||||
{"condition", {{"min", 0}, {"max", 100}}},
|
||||
{"form", {{"min", 0}, {"max", 99}}}}}});
|
||||
for (int i = 0; i < 2; ++i) {
|
||||
auto id = i ? "club:south" : "club:north";
|
||||
auto stadium = i ? "stadium:south" : "stadium:north";
|
||||
const auto key = std::string("asset:demo/") + (i ? "south" : "north");
|
||||
const auto file = std::string("assets/demo/") + (i ? "south.svg" : "north.svg");
|
||||
const auto color = i ? "#b44b5c" : "#3698aa";
|
||||
std::string svg = "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"128\" "
|
||||
"height=\"144\" viewBox=\"0 0 128 144\"><path d=\"M10 8h108v80q0 26-54 "
|
||||
"48Q10 114 10 88Z\" fill=\"" +
|
||||
std::string(color) +
|
||||
"\" stroke=\"#e5efef\" stroke-width=\"6\"/><path d=\"M34 98V40h15l30 "
|
||||
"38V40h15v58H79L49 60v38Z\" fill=\"#fff\"/></svg>";
|
||||
w.store->set(file, std::make_shared<const std::string>(svg));
|
||||
w.rows("assets").push_back({{"key", key},
|
||||
{"name", {{"default", i ? "Südstadt" : "Nordstadt"}}},
|
||||
{"files", {{"svg", file}}},
|
||||
{"source", "synthetic-demo"},
|
||||
{"license", "GPL-3.0-only"},
|
||||
{"kind", "vector"},
|
||||
{"width", 128},
|
||||
{"height", 144}});
|
||||
w.rows("clubs").push_back({{"id", id},
|
||||
{"name", {{"default", i ? "SV Südstadt" : "FC Nordstadt"}}},
|
||||
{"short_name", i ? "Südstadt" : "Nordstadt"},
|
||||
{"type", "club"},
|
||||
{"nation", "nation:de"},
|
||||
{"competition", "comp:demo"},
|
||||
{"stadium", stadium},
|
||||
{"crest", key},
|
||||
{"colors", {i ? "#9c3949" : "#277c8b", "#ffffff"}},
|
||||
{"founded", 1900 + i}});
|
||||
w.rows("stadiums")
|
||||
.push_back({{"id", stadium},
|
||||
{"name", {{"default", i ? "Südpark" : "Nordpark"}}},
|
||||
{"owner", id},
|
||||
{"capacity", {{"total", 22000 + 6000 * i}, {"seated", 18000 + 6000 * i}, {"standing", 4000}}}});
|
||||
for (int n = 0; n < 26; ++n) {
|
||||
w.rows("players").push_back(
|
||||
{{"id", "player:demo-" + std::to_string(i * 26 + n)},
|
||||
{"name", {{"first", n % 2 ? "Alex" : "Robin"}, {"last", "Spieler " + std::to_string(i * 26 + n + 1)}}},
|
||||
{"born", "2000-03-12"},
|
||||
{"nationalities", {"nation:de"}},
|
||||
{"positions",
|
||||
{n < 2 ? "gk"
|
||||
: n < 10 ? "def"
|
||||
: n < 18 ? "mid"
|
||||
: "fwd"}},
|
||||
{"team", id},
|
||||
{"squad_number", n + 1},
|
||||
{"squad_order", n},
|
||||
{"attribute_set", "demo@1"},
|
||||
{"attributes",
|
||||
{{"strength", 68 + (n % 15)}, {"technique", 65 + n % 20}, {"condition", 90}, {"form", 70}}}});
|
||||
}
|
||||
}
|
||||
w.rows("staff").push_back({{"id", "staff:referee-demo"},
|
||||
{"name", {{"default", "Kim Beispiel"}}},
|
||||
{"role", "referee"},
|
||||
{"nation", "nation:de"},
|
||||
{"attributes", {{"strictness", 2}}}});
|
||||
return w;
|
||||
}
|
||||
} // namespace bmh::editor
|
||||
@@ -0,0 +1,42 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#pragma once
|
||||
#include "editor/archive.hpp"
|
||||
|
||||
namespace bmh::editor {
|
||||
class World {
|
||||
public:
|
||||
Json manifest;
|
||||
std::shared_ptr<ArchiveStore> store = std::make_shared<ArchiveStore>();
|
||||
fs::path source_path;
|
||||
bool imported = false;
|
||||
static World open(const fs::path &, const std::string &start_date = "2026-07-01");
|
||||
static World blank(const std::string &title = "Untitled world");
|
||||
static World demo();
|
||||
Json &document(const std::string &);
|
||||
const Json &document(const std::string &) const;
|
||||
Json &rows(const std::string &);
|
||||
const Json &rows(const std::string &) const;
|
||||
const Json *find(const std::string &, const std::string &) const;
|
||||
Json *find(const std::string &, const std::string &);
|
||||
void change(const std::string &table, const std::string &id, const std::optional<Json> &);
|
||||
void touch(const std::string &table);
|
||||
Json query(const Json &) const;
|
||||
Json validate() const;
|
||||
Json statistics() const;
|
||||
std::string asset_file(const std::string &key) const;
|
||||
std::string portrait(const Json &) const;
|
||||
std::string title(const Json &entity, const std::string &language = "de") const;
|
||||
std::vector<std::pair<std::string, std::string>> references(const std::string &id) const;
|
||||
void save(const fs::path &) const;
|
||||
static std::string file_for(const std::string &table);
|
||||
static std::string identity(const Json &row, const std::string &table);
|
||||
static const std::vector<std::string> &tables();
|
||||
|
||||
private:
|
||||
std::map<std::string, Json> docs_;
|
||||
std::map<std::string, std::string> original_;
|
||||
std::set<std::string> dirty_;
|
||||
void load();
|
||||
void editor_profile();
|
||||
};
|
||||
} // namespace bmh::editor
|
||||
@@ -0,0 +1,258 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#include "editor/images.hpp"
|
||||
#include "editor/mcp.hpp"
|
||||
#include "editor/session.hpp"
|
||||
#include <httplib.h>
|
||||
#include <iostream>
|
||||
#include <thread>
|
||||
#ifdef _WIN32
|
||||
#define NOMINMAX
|
||||
#include <windows.h>
|
||||
#endif
|
||||
|
||||
using namespace bmh::editor;
|
||||
namespace {
|
||||
int checks = 0;
|
||||
void check(bool result, const char *message) {
|
||||
++checks;
|
||||
if (!result)
|
||||
throw std::runtime_error(message);
|
||||
}
|
||||
template <class Fn> void rejects(const char *code, Fn fn) {
|
||||
try {
|
||||
fn();
|
||||
} catch (const Error &error) {
|
||||
check(error.code == code, "unexpected rejection code");
|
||||
return;
|
||||
}
|
||||
throw std::runtime_error(std::string("accepted: ") + code);
|
||||
}
|
||||
Json update(const char *table, const char *id, Json set) {
|
||||
return {{"changes", Json::array({{{"table", table}, {"id", id}, {"set", set}}})}};
|
||||
}
|
||||
Json row(Session &session, const char *table, const char *id) {
|
||||
return session.execute("get", {{"table", table}, {"id", id}})["record"];
|
||||
}
|
||||
} // namespace
|
||||
int main() {
|
||||
auto root = fs::temp_directory_path() / new_id("editor-test-");
|
||||
fs::create_directory(root);
|
||||
struct Cleanup {
|
||||
fs::path root;
|
||||
~Cleanup() {
|
||||
std::error_code ec;
|
||||
fs::remove_all(root, ec);
|
||||
}
|
||||
} cleanup{root};
|
||||
try {
|
||||
Session s;
|
||||
s.execute("demo");
|
||||
check(s.execute("list", {{"table", "players"}})["total"] == 52, "all squads retained");
|
||||
check(s.execute("list", {{"table", "players"}, {"team", "club:north"}, {"limit", 24}})["items"].size() == 24,
|
||||
"24 view");
|
||||
check(s.execute("list", {{"table", "players"}, {"team", "club:north"}, {"offset", 24}})["items"].size() == 2,
|
||||
"remaining squad not discarded");
|
||||
auto initial = row(s, "players", "player:demo-0");
|
||||
const auto revision = s.execute("info")["revision"];
|
||||
auto change = update("players", "player:demo-0", {{"/name/last", "Änderung"}, {"/attributes/strength", 99}});
|
||||
change["expected_revision"] = revision;
|
||||
s.execute("apply", change);
|
||||
check(row(s, "players", "player:demo-0")["name"]["last"] == "Änderung", "edit applied");
|
||||
rejects("stale_revision", [&] { s.execute("apply", change); });
|
||||
s.execute("undo");
|
||||
check(row(s, "players", "player:demo-0") == initial, "undo complete row");
|
||||
check(s.execute("info")["revision"] > revision, "revision monotonic across undo");
|
||||
s.execute("redo");
|
||||
check(row(s, "players", "player:demo-0")["attributes"]["strength"] == 99, "redo");
|
||||
rejects("validation_failed",
|
||||
[&] { s.execute("apply", update("players", "player:demo-0", {{"/attributes/strength", 999}})); });
|
||||
check(row(s, "players", "player:demo-0")["attributes"]["strength"] == 99, "failed edit rolled back");
|
||||
rejects("validation_failed",
|
||||
[&] { s.execute("apply", update("players", "player:demo-0", {{"/born", "2001-02-29"}})); });
|
||||
rejects("record_referenced", [&] {
|
||||
s.execute("apply",
|
||||
{{"changes", Json::array({{{"op", "delete"}, {"table", "clubs"}, {"id", "club:north"}}})}});
|
||||
});
|
||||
check(!row(s, "clubs", "club:north").empty(), "delete rolled back");
|
||||
s.execute("roster.swap", {{"first", "player:demo-0"}, {"second", "player:demo-26"}});
|
||||
check(row(s, "players", "player:demo-0")["team"] == "club:south", "roster swap first");
|
||||
check(row(s, "players", "player:demo-26")["team"] == "club:north", "roster swap second");
|
||||
s.execute("undo");
|
||||
auto squad =
|
||||
s.execute("list", {{"table", "players"}, {"team", "club:north"}, {"sort", "squad_order"}})["items"];
|
||||
Json reversed = Json::array();
|
||||
for (auto it = squad.rbegin(); it != squad.rend(); ++it)
|
||||
reversed.push_back((*it)["id"]);
|
||||
s.execute("roster.order", {{"team", "club:north"}, {"players", reversed}});
|
||||
check(row(s, "players", "player:demo-25")["squad_order"] == 0, "complete squad reorder");
|
||||
s.execute("undo");
|
||||
check(row(s, "players", "player:demo-0")["squad_order"] == 0, "squad order undo");
|
||||
rejects("invalid_change", [&] {
|
||||
s.execute("roster.order", {{"team", "club:north"}, {"players", Json::array({"player:demo-0"})}});
|
||||
});
|
||||
rejects("validation_failed",
|
||||
[&] { s.execute("apply", update("players", "player:demo-0", {{"/team", "nation:de"}})); });
|
||||
rejects("immutable_id",
|
||||
[&] { s.execute("apply", update("manifest", "manifest", {{"/x-editor/playable", true}})); });
|
||||
s.execute("apply",
|
||||
{{"changes",
|
||||
Json::array(
|
||||
{{{"op", "create"}, {"table", "competitions"}, {"id", "comp:second"}, {"name", "Second"}}})}});
|
||||
s.execute("apply", update("clubs", "club:north", {{"/competition", "comp:second"}}));
|
||||
check(row(s, "competitions", "comp:second")["members"] == Json::array({"club:north"}), "new league membership");
|
||||
check(row(s, "competitions", "comp:demo")["members"] == Json::array({"club:south"}),
|
||||
"old league membership removed");
|
||||
s.execute("undo");
|
||||
check(row(s, "competitions", "comp:demo")["members"].size() == 2, "membership undo atomic");
|
||||
const auto image = images::Raster{2, 2, {255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 128}};
|
||||
const auto png = images::encode_png(image);
|
||||
write_atomic(root / "input.png", png);
|
||||
check(images::decode(png, ".png").pixels == image.pixels, "PNG lossless RGBA");
|
||||
check(images::transform(png, ".png", Json::object()).bytes == png, "identity preserves exact bytes");
|
||||
auto flip = images::decode(images::transform(png, ".png", {{"flip_x", true}}).bytes, ".png");
|
||||
check(flip.pixels[1] == 255 && flip.pixels[4] == 255, "horizontal mirror pixels");
|
||||
auto rotation = images::transform(png, ".png", {{"angle", 90.0}});
|
||||
check(rotation.width == 2 && rotation.height == 2, "rotation bounds");
|
||||
auto svg = images::silhouette();
|
||||
check(images::transform(svg, ".svg", {}).bytes == svg, "identity keeps SVG");
|
||||
auto vector =
|
||||
images::transform(svg, ".svg", {{"angle", 17.25}, {"flip_y", true}, {"crop", {{"x", .1}, {"width", .8}}}});
|
||||
check(vector.extension == ".svg" && vector.bytes.find("17.25") != std::string::npos,
|
||||
"arbitrary transform remains SVG");
|
||||
rejects("external_svg_resource", [&] {
|
||||
images::decode("<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"10\" "
|
||||
"height=\"10\"><image href=\"file:///tmp/test.png\"/></svg>",
|
||||
".svg");
|
||||
});
|
||||
auto imported = s.execute("asset.import", {{"file", utf8(root / "input.png")},
|
||||
{"key", "asset:test"},
|
||||
{"target", {{"table", "players"}, {"id", "player:demo-0"}}}});
|
||||
check(row(s, "players", "player:demo-0")["photo"] == "asset:test", "image assigned");
|
||||
check(s.asset_bytes("asset:test").first == png, "source exact on import");
|
||||
rejects("record_referenced", [&] {
|
||||
s.execute("apply",
|
||||
{{"changes", Json::array({{{"table", "assets"}, {"id", "asset:test"}, {"op", "delete"}}})}});
|
||||
});
|
||||
s.execute("apply", update("players", "player:demo-1", {{"/photo", "asset:test"}}));
|
||||
s.execute("asset.edit", {{"key", "asset:individual"},
|
||||
{"source_key", "asset:test"},
|
||||
{"transform", {{"angle", 18.0}}},
|
||||
{"target", {{"table", "players"}, {"id", "player:demo-0"}, {"field", "photo"}}}});
|
||||
check(row(s, "players", "player:demo-0")["photo"] == "asset:individual", "individual image assigned");
|
||||
check(row(s, "players", "player:demo-1")["photo"] == "asset:test" && s.asset_bytes("asset:test").first == png,
|
||||
"shared fallback and other person remain unchanged");
|
||||
s.execute("undo");
|
||||
check(row(s, "players", "player:demo-0")["photo"] == "asset:test", "image assignment undo atomic");
|
||||
const auto isolated = s.execute(
|
||||
"asset.import", {{"file", utf8(root / "input.png")},
|
||||
{"key", "asset:test"},
|
||||
{"transform", {{"flip_y", true}}},
|
||||
{"target", {{"table", "players"}, {"id", "player:demo-0"}, {"field", "photo"}}}});
|
||||
check(isolated["key"] != "asset:test" && s.asset_bytes("asset:test").first == png,
|
||||
"targeted import cannot overwrite another entity's shared image");
|
||||
s.execute("undo");
|
||||
s.execute("asset.edit", {{"key", "asset:test"}, {"transform", {{"angle", 30.5}}}});
|
||||
auto metadata = row(s, "assets", "asset:test")["x-editor"];
|
||||
check(metadata["transform"]["angle"] == 30.5, "float angle metadata");
|
||||
check(s.asset_bytes(metadata["original"].get<std::string>()).first == png, "original retained");
|
||||
s.execute("undo");
|
||||
check(s.asset_bytes("asset:test").first == png, "image undo restores native");
|
||||
s.execute("redo");
|
||||
s.execute("save", {{"path", utf8(root / "world.obw")}});
|
||||
check(s.execute("info")["dirty"] == false, "save checkpoint");
|
||||
s.execute("undo");
|
||||
check(s.execute("info")["dirty"] == true, "undo away from save dirty");
|
||||
s.execute("redo");
|
||||
check(s.execute("info")["dirty"] == false, "redo back to save clean");
|
||||
Session reopened;
|
||||
reopened.execute("open", {{"path", utf8(root / "world.obw")}});
|
||||
check(row(reopened, "assets", "asset:test")["x-editor"]["transform"]["angle"] == 30.5,
|
||||
"roundtrip float transform");
|
||||
reopened.execute("save"); // Snapshot permits atomic overwrite on every platform.
|
||||
auto w = World::open(root / "world.obw");
|
||||
const std::string opaque = "{\"future\":1.125,\"ignored\":{\"preserve\":true}}\n";
|
||||
w.store->set("x-future/notes.json", std::make_shared<const std::string>(opaque));
|
||||
w.save(root / "future.obw");
|
||||
auto future = World::open(root / "future.obw");
|
||||
future.save(root / "future2.obw");
|
||||
check(ArchiveStore::open(root / "future2.obw")->read("x-future/notes.json") == opaque,
|
||||
"unknown extension byte preservation");
|
||||
const auto unpacked = root / "unpacked";
|
||||
fs::create_directory(unpacked);
|
||||
auto original_store = ArchiveStore::open(root / "future.obw");
|
||||
for (const auto &name : original_store->names()) {
|
||||
const auto file = unpacked / path(name);
|
||||
fs::create_directories(file.parent_path());
|
||||
write_atomic(file, original_store->read(name));
|
||||
}
|
||||
auto snapshot = ArchiveStore::open(unpacked);
|
||||
write_atomic(unpacked / "x-future/notes.json", "external modification");
|
||||
check(snapshot->read("x-future/notes.json") == opaque, "unpacked source snapshot stable");
|
||||
check(!safe_name("../bad") && !safe_name("/bad") && !safe_name("C:/bad") && safe_name("assets/a.svg"),
|
||||
"archive paths");
|
||||
rejects("obw_only", [&] { future.save(root / "legacy.dat"); });
|
||||
auto options = Options::load(root / "settings.json");
|
||||
check(options.token.size() >= 64 && options.mcp_enabled, "local MCP enabled with token");
|
||||
options.apply({{"language", "en"}, {"theme", "silver"}, {"mcp_port", 0}});
|
||||
options.save();
|
||||
check(Options::load(root / "settings.json").language == "en", "persistent language");
|
||||
#ifdef _WIN32
|
||||
{
|
||||
wchar_t old_value[32768]{};
|
||||
const auto length = GetEnvironmentVariableW(L"APPDATA", old_value, 32768);
|
||||
struct Restore {
|
||||
std::wstring value;
|
||||
bool present;
|
||||
~Restore() { SetEnvironmentVariableW(L"APPDATA", present ? value.c_str() : nullptr); }
|
||||
} restore{old_value, length > 0};
|
||||
const auto profile = root / L"Profil-ÄÖÜ";
|
||||
SetEnvironmentVariableW(L"APPDATA", profile.c_str());
|
||||
const auto native_options = Options::load();
|
||||
check(native_options.settings_file == profile / "OpenBMH/editor.json", "Unicode Windows profile path");
|
||||
check(fs::is_regular_file(native_options.settings_file), "Unicode Windows settings saved");
|
||||
}
|
||||
#endif
|
||||
check(tr("de", "clubs") != tr("en", "clubs"), "bilingual labels");
|
||||
McpServer mcp(s);
|
||||
mcp.start(options);
|
||||
httplib::Client client("127.0.0.1", mcp.port());
|
||||
client.set_connection_timeout(5);
|
||||
client.set_read_timeout(10);
|
||||
httplib::Headers headers{{"Authorization", "Bearer " + options.token},
|
||||
{"Accept", "application/json, text/event-stream"}};
|
||||
auto request = Json{{"jsonrpc", "2.0"},
|
||||
{"id", 1},
|
||||
{"method", "initialize"},
|
||||
{"params",
|
||||
{{"protocolVersion", "2025-11-25"},
|
||||
{"capabilities", Json::object()},
|
||||
{"clientInfo", {{"name", "test"}, {"version", "1"}}}}}};
|
||||
auto result = client.Post("/mcp", headers, request.dump(), "application/json");
|
||||
check(result && result->status == 200 && Json::parse(result->body)["result"]["protocolVersion"] == "2025-11-25",
|
||||
"MCP initialize HTTP");
|
||||
request["method"] = "tools/list";
|
||||
request["params"] = Json::object();
|
||||
result = client.Post("/mcp", headers, request.dump(), "application/json");
|
||||
check(result && Json::parse(result->body)["result"]["tools"].size() >= 18, "MCP tool catalog");
|
||||
request["method"] = "tools/call";
|
||||
request["params"] = {{"name", "editor_roster_move"},
|
||||
{"arguments", {{"player", "player:demo-0"}, {"team", "club:south"}}}};
|
||||
result = client.Post("/mcp", headers, request.dump(), "application/json");
|
||||
check(result && Json::parse(result->body)["result"]["isError"] == false, "MCP edit");
|
||||
check(row(s, "players", "player:demo-0")["team"] == "club:south", "MCP shares GUI session");
|
||||
s.execute("undo");
|
||||
check(row(s, "players", "player:demo-0")["team"] == "club:north", "shared undo");
|
||||
auto no_token = client.Post("/mcp", request.dump(), "application/json");
|
||||
check(no_token && no_token->status == 401, "reject unauthenticated MCP");
|
||||
headers.emplace("Origin", "https://example.org");
|
||||
result = client.Post("/mcp", headers, request.dump(), "application/json");
|
||||
check(result && result->status == 403, "reject foreign origin");
|
||||
mcp.stop();
|
||||
check(!mcp.running(), "server shutdown");
|
||||
std::cout << checks << " editor checks passed\n";
|
||||
return 0;
|
||||
} catch (const std::exception &e) {
|
||||
std::cerr << "Editor check failed after " << checks << ": " << e.what() << '\n';
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: GPL-3.0-only
|
||||
"""Linux native RmlUI integration check; run inside Xvfb with xdotool.
|
||||
|
||||
Tests an actual mouse/keyboard inspector edit and shared MCP undo/save. Uses
|
||||
only generated demo data. No game installation or personal profile is read.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
import urllib.request
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('executable', type=Path)
|
||||
args = parser.parse_args()
|
||||
with tempfile.TemporaryDirectory(prefix='editor-gui-') as temporary:
|
||||
root = Path(temporary)
|
||||
with socket.socket() as probe:
|
||||
probe.bind(('127.0.0.1', 0)); port = probe.getsockname()[1]
|
||||
settings = root / 'settings.json'
|
||||
settings.write_text(json.dumps({'language': 'de', 'theme': 'midnight', 'mcp_enabled': True, 'mcp_port': port}))
|
||||
with (root / 'app.log').open('w') as log:
|
||||
app = subprocess.Popen([str(args.executable.resolve()), '--demo', '--page', 'clubs', '--settings', str(settings)],
|
||||
stdout=log, stderr=log, env={**os.environ, 'LIBGL_ALWAYS_SOFTWARE': '1'})
|
||||
try:
|
||||
request_id = 0
|
||||
def rpc(method, params):
|
||||
nonlocal request_id
|
||||
request_id += 1
|
||||
token = json.loads(settings.read_text()).get('mcp_token', '')
|
||||
request = urllib.request.Request(f'http://127.0.0.1:{port}/mcp',
|
||||
data=json.dumps({'jsonrpc': '2.0', 'id': request_id, 'method': method, 'params': params}).encode(),
|
||||
headers={'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json',
|
||||
'Accept': 'application/json, text/event-stream', 'MCP-Protocol-Version': '2025-11-25'})
|
||||
with urllib.request.urlopen(request, timeout=5) as response:
|
||||
value = json.load(response)
|
||||
if 'error' in value:
|
||||
raise AssertionError(value['error'])
|
||||
return value['result']
|
||||
deadline = time.monotonic() + 15
|
||||
while True:
|
||||
try:
|
||||
rpc('initialize', {'protocolVersion': '2025-11-25', 'capabilities': {},
|
||||
'clientInfo': {'name': 'synthetic-gui-smoke', 'version': '1'}})
|
||||
break
|
||||
except (OSError, ValueError):
|
||||
if app.poll() is not None or time.monotonic() > deadline:
|
||||
raise RuntimeError('Editor did not start')
|
||||
time.sleep(.05)
|
||||
def tool(name, arguments=None):
|
||||
result = rpc('tools/call', {'name': name, 'arguments': arguments or {}})
|
||||
if result.get('isError'):
|
||||
raise AssertionError(result)
|
||||
return result['structuredContent']
|
||||
window = subprocess.check_output(['xdotool', 'search', '--sync', '--onlyvisible', '--pid', str(app.pid)],
|
||||
text=True, timeout=10).splitlines()[-1]
|
||||
def x(*arguments):
|
||||
subprocess.run(['xdotool', *map(str, arguments)], check=True, timeout=5, stdout=subprocess.DEVNULL)
|
||||
def click(a, b):
|
||||
x('mousemove', '--window', window, a, b, 'click', 1); time.sleep(.15)
|
||||
def wait_name(expected):
|
||||
for _ in range(40):
|
||||
row = tool('editor_get', {'table': 'clubs', 'id': 'club:north'})['record']
|
||||
if row['name']['default'] == expected:
|
||||
return
|
||||
time.sleep(.05)
|
||||
raise AssertionError('Native inspector edit not observed: ' + expected)
|
||||
time.sleep(.4); x('windowfocus', window)
|
||||
click(1150, 443); x('key', 'ctrl+a'); x('type', '--clearmodifiers', 'FC Native QA')
|
||||
click(1300, 741); wait_name('FC Native QA')
|
||||
# Exercises textarea values elsewhere in the form as well: the
|
||||
# untouched colours must remain real JSON, not escaped markup.
|
||||
row = tool('editor_get', {'table': 'clubs', 'id': 'club:north'})['record']
|
||||
assert row['colors'] == ['#277c8b', '#ffffff']
|
||||
tool('editor_undo'); wait_name('FC Nordstadt')
|
||||
time.sleep(.6)
|
||||
click(380, 233); x('type', '--clearmodifiers', '--delay', 80, 'Nord')
|
||||
time.sleep(.3)
|
||||
x('key', 'ctrl+a'); x('key', 'BackSpace'); time.sleep(.3)
|
||||
# Native Undo/Redo buttons operate on the same transaction.
|
||||
click(1268, 872); wait_name('FC Native QA')
|
||||
tool('editor_save', {'path': str(root / 'world.obw')})
|
||||
assert (root / 'world.obw').is_file()
|
||||
assert tool('editor_info')['dirty'] is False
|
||||
print('Native RmlUI edit, JSON fields, search focus, shared undo/redo and OBW save passed.')
|
||||
except Exception:
|
||||
log.flush()
|
||||
print((root / 'app.log').read_text())
|
||||
raise
|
||||
finally:
|
||||
app.kill(); app.wait(timeout=5)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,121 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: GPL-3.0-only
|
||||
"""Package the standalone editor, its native assets and corresponding source.
|
||||
|
||||
This deliberately includes no imported world or original game artwork.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import zipfile
|
||||
from make_source_package import COMPONENTS, MINIZ_FILES, git, copy_files
|
||||
|
||||
EXTRA = {
|
||||
'editor_json': ('v3.12.0', 'https://github.com/nlohmann/json'),
|
||||
'editor_http': ('v0.63.0', 'https://github.com/yhirose/cpp-httplib'),
|
||||
'editor_images': ('release-2.8.8', 'https://github.com/libsdl-org/SDL_image'),
|
||||
'editor_svg': ('v3.5.0', 'https://github.com/sammycage/lunasvg'),
|
||||
'editor_xml': ('v1.15', 'https://github.com/zeux/pugixml'),
|
||||
}
|
||||
|
||||
|
||||
def zip_tree(root, target):
|
||||
with zipfile.ZipFile(target, 'w', zipfile.ZIP_DEFLATED, compresslevel=6) as archive:
|
||||
for file in sorted(root.rglob('*')):
|
||||
if file.is_file():
|
||||
info = zipfile.ZipInfo.from_file(file, Path(root.name) / file.relative_to(root))
|
||||
archive.writestr(info, file.read_bytes(), compress_type=zipfile.ZIP_DEFLATED)
|
||||
|
||||
|
||||
def copy_dependency(directory, target, name, reference):
|
||||
if name == 'miniz' and not (directory / '.git').exists():
|
||||
for file, expected in MINIZ_FILES.items():
|
||||
if hashlib.sha256((directory / file).read_bytes()).hexdigest() != expected:
|
||||
raise RuntimeError('Unexpected miniz source')
|
||||
copy_files(directory, target, list(map(Path, MINIZ_FILES)), required=True)
|
||||
return {'archive': reference}
|
||||
commit = git(directory, 'rev-parse', 'HEAD').decode().strip()
|
||||
expected = git(directory, 'rev-parse', reference + '^{commit}').decode().strip()
|
||||
if commit != expected or git(directory, 'diff', '--name-only', '--ignore-submodules=all').strip():
|
||||
raise RuntimeError('Modified dependency: ' + name)
|
||||
files, modules = [], {}
|
||||
for entry in git(directory, 'ls-files', '--stage', '-z').split(b'\0'):
|
||||
if not entry:
|
||||
continue
|
||||
meta, file = entry.split(b'\t', 1); file = Path(file.decode())
|
||||
if meta.startswith(b'160000 '):
|
||||
# Only this codec is enabled. Freetype's dlg is unused by CMake.
|
||||
required = name == 'editor_images' and file.as_posix() == 'external/libwebp'
|
||||
if required:
|
||||
module_commit = meta.split()[1].decode()
|
||||
modules[str(file)] = copy_dependency(directory / file, target / file, name + '/libwebp', module_commit)
|
||||
else:
|
||||
modules[str(file)] = {'unbuilt': True, 'commit': meta.split()[1].decode()}
|
||||
else:
|
||||
files.append(file)
|
||||
if name == 'lzma_sdk':
|
||||
files = [f for f in files if f.parts[0] == 'C' or f == Path('DOC/License.txt')]
|
||||
hashes = copy_files(directory, target, files, required=True)
|
||||
return {'commit': commit, 'files': hashes, 'submodules': modules}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--source', type=Path, default=Path(__file__).resolve().parents[2])
|
||||
parser.add_argument('--build', type=Path, required=True)
|
||||
parser.add_argument('--out', type=Path, required=True)
|
||||
parser.add_argument('--platform', required=True, choices=['linux-x64', 'windows-x64', 'macos-arm64'])
|
||||
parser.add_argument('--source-package', action='store_true')
|
||||
args = parser.parse_args()
|
||||
source, build = args.source.resolve(), args.build.resolve()
|
||||
args.out.mkdir(parents=True, exist_ok=True)
|
||||
commit = git(source, 'rev-parse', 'HEAD').decode().strip()
|
||||
name = 'OpenBMHEditor-poc-' + args.platform
|
||||
with tempfile.TemporaryDirectory(prefix='editor-package-') as td:
|
||||
stage = Path(td) / name; stage.mkdir()
|
||||
exe = 'OpenBMHEditor.exe' if args.platform.startswith('windows') else 'OpenBMHEditor'
|
||||
subprocess.run(['cmake', '--install', str(build), '--component', 'Editor', '--config', 'Release',
|
||||
'--prefix', str(stage)], check=True)
|
||||
shutil.copytree(source / 'docs/licenses', stage / 'licenses')
|
||||
for file in ('LICENSE', 'THIRD_PARTY_NOTICES.md'):
|
||||
shutil.copy2(source / file, stage / file)
|
||||
shutil.copy2(source / 'docs/EDITOR.md', stage / 'EDITOR.md')
|
||||
if args.platform.startswith('windows'):
|
||||
# Uses the same app-local CRT/UCRT installation as the main game.
|
||||
# A successful runner launch alone does not prove deployability.
|
||||
for dll in ('vcruntime140.dll', 'msvcp140.dll'):
|
||||
if not (stage / dll).is_file():
|
||||
raise RuntimeError('Required Windows runtime missing: ' + dll)
|
||||
(stage / 'BUILD.json').write_text(json.dumps({'commit': commit, 'platform': args.platform,
|
||||
'editor_profile': 'editor-world-v1', 'game_data_included': False}, indent=2) + '\n')
|
||||
zip_tree(stage, args.out / (name + '.zip'))
|
||||
print(args.out / (name + '.zip'))
|
||||
if args.source_package:
|
||||
deps = {**json.loads((build / 'package-dependencies.json').read_text()),
|
||||
**json.loads((build / 'editor-dependencies.json').read_text())}
|
||||
components = {**{n: (v[0], v[1]) for n, v in COMPONENTS.items()}, **EXTRA}
|
||||
with tempfile.TemporaryDirectory(prefix='editor-source-') as td:
|
||||
stage = Path(td) / 'OpenBMHEditor-poc-source'; stage.mkdir()
|
||||
project = [Path(f.decode()) for f in git(source, 'ls-files', '-z').split(b'\0') if f]
|
||||
manifest = {'project_commit': commit, 'project_files': copy_files(source, stage / 'project', project, required=True), 'dependencies': {}}
|
||||
cache = ['set(OPENBMH_BUILD_EDITOR ON CACHE BOOL "" FORCE)']
|
||||
for name, (ref, url) in components.items():
|
||||
result = copy_dependency(Path(deps[name]), stage / 'dependencies' / name, name, ref)
|
||||
manifest['dependencies'][name] = {'reference': ref, 'upstream': url, **result}
|
||||
cache.append('set(FETCHCONTENT_SOURCE_DIR_' + name.upper() + ' "${CMAKE_CURRENT_LIST_DIR}/dependencies/' + name + '" CACHE PATH "" FORCE)')
|
||||
(stage / 'dependencies.cmake').write_text('\n'.join(cache) + '\n')
|
||||
(stage / 'SOURCE_MANIFEST.json').write_text(json.dumps(manifest, indent=2) + '\n')
|
||||
(stage / 'BUILD_SOURCE.txt').write_text('cmake -S project -B build -C dependencies.cmake -G Ninja -DCMAKE_BUILD_TYPE=Release\n'
|
||||
'cmake --build build --target openbmh_editor editor_core_tests\n'
|
||||
'ctest --test-dir build -R ^editor_core_tests$ --output-on-failure\n'
|
||||
'Native compiler, CMake and OS development libraries: see project/docs/EDITOR.md.\n')
|
||||
zip_tree(stage, args.out / 'OpenBMHEditor-poc-source.zip')
|
||||
print(args.out / 'OpenBMHEditor-poc-source.zip')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -16,7 +16,9 @@ def validate(directory, windows):
|
||||
'SDL2-HIDAPI-options.txt', 'SDL2-HIDAPI-original.txt', 'SDL2-yuv2rgb.txt',
|
||||
'SDL2.txt', 'miniz-source-notices.txt', 'miniz.txt', 'nativefiledialog-extended.txt',
|
||||
'RmlUi.txt', 'RmlUi-containers.txt', 'RmlUi-fonts.txt', 'RmlUi-Khronos.txt',
|
||||
'FreeType.txt', 'FreeType-FTL.txt', 'FreeType-BDF.txt', 'FreeType-PCF.txt', 'FreeType-zlib.txt'}
|
||||
'FreeType.txt', 'FreeType-FTL.txt', 'FreeType-BDF.txt', 'FreeType-PCF.txt', 'FreeType-zlib.txt',
|
||||
'nlohmann-json.txt', 'cpp-httplib.txt', 'SDL2_image.txt', 'stb-image.txt',
|
||||
'libwebp.txt', 'libwebp-PATENTS.txt', 'LunaSVG.txt', 'PlutoVG.txt', 'pugixml.txt'}
|
||||
launcher_assets = {'assets/launcher/' + name for name in
|
||||
('launcher.rml', 'theme.rcss', 'stadium.tga', 'LatoLatin-Regular.ttf', 'LatoLatin-Bold.ttf')}
|
||||
present = set()
|
||||
|
||||
@@ -41,14 +41,56 @@ PRIVATE_DOCUMENTS = {
|
||||
}
|
||||
SOURCE_SUFFIXES = {".cpp", ".hpp", ".h", ".c", ".inc"}
|
||||
SKIP_DIRECTORIES = {".git", "__pycache__", ".cache", "_deps", "node_modules"}
|
||||
# Independently generated launcher artwork already published on the launcher
|
||||
# branch, with provenance in its assets/launcher/provenance.json. History checks
|
||||
# include those branches too. Approve only these exact reviewed bytes and path.
|
||||
# Exact independently generated artwork and synthetic native-editor captures.
|
||||
# The latter are reviewed against docs/qa/editor-poc/README.md; no game material.
|
||||
# Keep prior reviewed hashes if an asset is intentionally revised in history.
|
||||
PROJECT_ARTWORK = {
|
||||
"docs/qa/editor-poc/clubs-midnight-de.png": {
|
||||
"2921aa67a870633c96f46328a82bc3022e5489b38d551c5314f13c7e59446070",
|
||||
"aa53e9cdd9ac8f6bf18b514862ac704ff9003bd1b62466cad2ebc329b09703dc",
|
||||
},
|
||||
"docs/qa/editor-poc/gui-search.png": {
|
||||
"48dc00d03c01d5bbec35683ff65672c12af4be6aecc8a84e5fece243c56643f4",
|
||||
"ef1780e91034dab96a7b23c638cdc8476f09be701b892f77e94e2fc2874cbd19",
|
||||
},
|
||||
"docs/qa/editor-poc/image-editor-midnight-de.png": {
|
||||
"44a89dfd84d7ee5b2acb54ae749e69051ae71ce192885dbe1a9311aba778c8ca",
|
||||
"eb01bd8fd8eaadfbc8e2b3f634bcdafbbb084dc4592d849e102a6f8c70ab0ad4",
|
||||
},
|
||||
"docs/qa/editor-poc/options-midnight-de.png": {
|
||||
"7075957db2d5f5a166bb71adb97d8208cb051a72b555202c212fae4f7e5c402c",
|
||||
"be483ad35a8912766611fd63dcc7cde6f820ed9a78441ad49554102a096633ab",
|
||||
},
|
||||
"docs/qa/editor-poc/players-silver-en.png": {
|
||||
"0d463d74a78072dda5b830c1d8c5e12d7e4588f6a743a95cc2ca4a327278928c",
|
||||
"d965a904663f3a30e5410f5d33539f6247737293625039fb9e3028337bbc088c",
|
||||
},
|
||||
"docs/qa/editor-poc/roster-matchday-de.png": {
|
||||
"547acb1b03ee68a3cee217fc5c96f4b960c64a5e48d1074e4f19045d98559647",
|
||||
"937829bb31b7452aa15d4a54cd03ad5de6a42d630b83cce279f22da09dfe180b",
|
||||
},
|
||||
"assets/launcher/stadium.tga": {
|
||||
"08f82783a357d5b0722f3737de54844150bc14d98036845f1aaee3211608e1c8",
|
||||
"fb8e5f1f86afe60de87b70a2f533690d1ef470241fa24ee4384ff000149edaab",
|
||||
},
|
||||
"docs/qa/editor-poc/clubs-silver-de.png": {
|
||||
"4f5dbe76b86097d306d2c982ce48093cce0fc95e9f35853493779b3116399239",
|
||||
},
|
||||
"docs/qa/editor-poc/options-silver-de.png": {
|
||||
"e406dca9058569f91fb314f0ff548ff349190c13ef1ed90c0051e44899634493",
|
||||
},
|
||||
"docs/qa/editor-poc/image-editor-silver-de.png": {
|
||||
"8d6ead6fd0e2fddc8e23de0a71abe519fa4f19ede0676823892d2568481bf68c",
|
||||
},
|
||||
"docs/qa/editor-poc/clubs-matchday-de.png": {
|
||||
"e74d0b9acd07f6a48537616c28d74e53b8f69e20bb15fc3f6fcd0c10484b4f58",
|
||||
},
|
||||
"docs/qa/editor-poc/options-matchday-de.png": {
|
||||
"c0b2a8b936dccdcbac72169e2985ca91221ec605dd4ad96a624be23f225b608a",
|
||||
},
|
||||
"docs/qa/editor-poc/image-editor-matchday-de.png": {
|
||||
"e0f5fb9f986d01c27ce04da8bd8ac7623ee3b2afcbf8a8677c3580dcb0465c36",
|
||||
},
|
||||
}
|
||||
|
||||
LEGACY_SYMBOLS = re.compile(
|
||||
@@ -244,11 +286,12 @@ def scan_tree(root: Path):
|
||||
return findings, len(names)
|
||||
|
||||
|
||||
def scan_history(root: Path):
|
||||
def scan_history(root: Path, revision=None):
|
||||
findings = []
|
||||
references = subprocess.check_output(["git", "-C", str(root), "for-each-ref", "--format=%(refname)"])
|
||||
findings.extend(scan_blob("ref-names", references))
|
||||
refs = subprocess.check_output(["git", "-C", str(root), "rev-list", "--all"], text=True).splitlines()
|
||||
selection = [revision] if revision else ["--all"]
|
||||
refs = subprocess.check_output(["git", "-C", str(root), "rev-list", *selection], text=True).splitlines()
|
||||
seen = set()
|
||||
checked = 0
|
||||
for revision in refs:
|
||||
@@ -280,15 +323,18 @@ def main(argv=None):
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--root", type=Path, default=Path.cwd())
|
||||
parser.add_argument("--history", action="store_true", help="also check all reachable commits and their blobs")
|
||||
parser.add_argument("--revision", help="with --history, inspect this revision's ancestry instead of unrelated refs")
|
||||
parser.add_argument("--json", type=Path, help="write a report containing rule names and locations only")
|
||||
args = parser.parse_args(argv)
|
||||
if args.revision and (not args.history or args.revision.startswith('-')):
|
||||
parser.error("--revision requires --history and a revision, not an option")
|
||||
if args.history and shutil.which("git") is None:
|
||||
parser.error("Git is required for history checks")
|
||||
root = args.root.resolve(strict=True)
|
||||
findings, files = scan_tree(root)
|
||||
commits = blobs = 0
|
||||
if args.history:
|
||||
extra, commits, blobs = scan_history(root)
|
||||
extra, commits, blobs = scan_history(root, args.revision)
|
||||
findings.extend(extra)
|
||||
findings = sorted(set(findings))
|
||||
def display_path(name):
|
||||
|
||||