diff --git a/.github/workflows/editor.yml b/.github/workflows/editor.yml new file mode 100644 index 0000000..9dcf3a4 --- /dev/null +++ b/.github/workflows/editor.yml @@ -0,0 +1,70 @@ +# SPDX-License-Identifier: GPL-3.0-only +name: OBW Editor POC +on: + push: + branches: [feat/obw-editor-poc] + workflow_dispatch: +permissions: + contents: read +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 + - 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 diff --git a/CMakeLists.txt b/CMakeLists.txt index e6560e9..662b24d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -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) diff --git a/README.md b/README.md index f6366af..d1ecd8b 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 2b479bc..0190308 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -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. diff --git a/assets/editor/editor.rml b/assets/editor/editor.rml new file mode 100644 index 0000000..d4e9fda --- /dev/null +++ b/assets/editor/editor.rml @@ -0,0 +1,14 @@ + + +OpenBMH Editor + +
+
OB

OpenBMH Editor

+
+

+
+
+
+
+
+
diff --git a/assets/editor/theme.rcss b/assets/editor/theme.rcss new file mode 100644 index 0000000..74af312 --- /dev/null +++ b/assets/editor/theme.rcss @@ -0,0 +1,166 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ +body { margin: 0; width: 100%; height: 100%; overflow: hidden; font-family: LatoLatin; font-size: 15dp; color: #e7eff4; background-color: #101c2b; } +* { 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: #142438; border-bottom: 1dp #ffffff16; } +.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 #71d4b568; border-radius: 13dp; color: #83ddc4; background-color: #71d4b50c; margin-right: 13dp; } +.brand-mark span { color: #dceee9; } +h1, h2, p { margin: 0; } +h2 { font-size: 20dp; font-weight: bold; } +h2 span { font-weight: normal; color: #96aebf; } +small { display: block; font-size: 12dp; color: #94aabd; margin-top: 4dp; } +#world-caption { flex: 1; font-size: 14dp; color: #c3d2dc; 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: #dce7ef; background-color: #ffffff09; border: 1dp #9eafbf32; border-radius: 8dp; padding: 9dp 14dp; cursor: pointer; text-align: center; white-space: nowrap; tab-index: auto; } +button:hover { background-color: #ffffff16; border-color: #acccdc80; } +button:focus, input:focus, select:focus, textarea:focus { border-color: #7cdbbf; } +button.primary { background-color: #8dd6bf; color: #102b2b; border-color: #8dd6bf; font-weight: bold; } +button.primary:hover { background-color: #afe5d3; } +button.danger { color: #f4a5a3; border-color: #dc777d66; } +button:disabled { opacity: 0.35; cursor: unavailable; } +button.quiet { border-color: transparent; background-color: transparent; } +#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: #122033; border-right: 1dp #ffffff12; } +.eyebrow { font-size: 11dp; font-weight: bold; letter-spacing: 1.5dp; color: #91a9b9; 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; font-size: 15dp; } +.nav .glyph { width: 20dp; height: 20dp; margin-right: 16dp; flex-shrink: 0; } +.nav.selected { background-color: #80cfb51c; color: #a6e6d3; border-color: #80cfb53a; } +.nav.selected .glyph { color: #a6e6d3; } +.aside-foot { margin-top: auto; padding: 24dp 14dp 0; font-size: 12dp; color: #92aabb; } +.aside-foot small { line-height: 1.45; } +.small-pitch { height: 50dp; width: 84dp; border: 1dp #91a9b933; border-radius: 4dp; margin-bottom: 15dp; position: relative; } +.small-pitch div { position: absolute; width: 20dp; height: 20dp; border: 1dp #91a9b933; 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: #9fb3c2; 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: #0d1a29; color: #e6eef3; border: 1dp #7c9bb23b; border-radius: 7dp; padding: 9dp 10dp; height: 38dp; tab-index: auto; } +input[type=checkbox] { width: 18dp; height: 18dp; padding: 2dp; background-color: #1e3448; } +input[type=checkbox]:checked { background-color: #80cfb5; decorator: none; } +input[type=range] { height: 24dp; padding: 0; } +input[type=range] track { height: 4dp; background-color: #6c8c9c55; margin: 9dp 0; border-radius: 2dp; } +input[type=range] bar { width: 16dp; height: 16dp; border-radius: 8dp; background-color: #9bdac8; 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 #94b1c4; border-right: 2dp #94b1c4; transform: rotate(45deg); } +select selectbox { background-color: #1b2d40; color: #edf4f8; border: 1dp #66869f; 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: #537c9666; } +#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 #9db7cb23; border-radius: 12dp; overflow: hidden; background-color: #18283b99; display: flex; flex-direction: column; } +.table-header { display: flex; align-items: center; height: 42dp; flex-shrink: 0; padding: 0 16dp; background-color: #ffffff08; border-bottom: 1dp #91aabd22; } +.table-header button { flex: 1; text-align: left; padding: 0; border: 0; background-color: transparent; font-size: 12dp; color: #9eb4c4; } +.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 #9db7cb12; border-radius: 0; background-color: transparent; text-align: left; } +.record:hover { background-color: #ffffff08; } +.record.selected { background-color: #70cdb225; border-left: 3dp #90ddc5; padding-left: 13dp; } +.record .cell { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; padding-right: 10dp; font-size: 13dp; color: #a9c0cf; } +.record .cell:first-child { flex: 2; font-size: 14dp; color: #e2edf3; display: flex; align-items: center; } +.mini-logo { width: 27dp; height: 27dp; margin-right: 12dp; flex-shrink: 0; } +.inspector { width: 370dp; flex-shrink: 0; border: 1dp #9db7cb23; border-radius: 12dp; background-color: #1c2d4088; display: flex; flex-direction: column; overflow: hidden; } +.inspector-head { padding: 22dp; border-bottom: 1dp #91aabd22; 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: #a7bdca; 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: #80cfb5; } +.form-help { font-size: 11dp; color: #8da8b9; line-height: 1.5; margin-top: 6dp; } +.inspector-actions { padding: 16dp 20dp; border-top: 1dp #91aabd22; display: flex; gap: 8dp; flex-shrink: 0; } +.inspector-actions button { flex: 1; } +.empty { margin: auto; padding: 45dp; text-align: center; color: #8fa8b9; line-height: 1.7; } +#pagination { display: flex; justify-content: space-between; align-items: center; flex-shrink: 0; padding-top: 14dp; color: #97b1c2; font-size: 12dp; } +footer { height: 57dp; padding: 0 28dp; display: flex; align-items: center; gap: 20dp; flex-shrink: 0; border-top: 1dp #ffffff18; background-color: #122033; font-size: 12dp; } +#state { width: 210dp; color: #9dcab9; } +#status-message { flex: 1; color: #9aafbd; } +#bottom-actions button { font-size: 12dp; padding: 7dp 11dp; } +.dashboard { width: 100%; overflow-y: auto; padding-right: 7dp; } +.hero { padding: 32dp; border: 1dp #9db7cb26; border-radius: 16dp; background-color: #1d3447; margin-bottom: 22dp; } +.hero h1 { font-size: 32dp; margin: 0 0 12dp; } +.hero p { color: #afc5d1; 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 #9db7cb28; border-radius: 12dp; background-color: #1b2c3e; text-align: left; } +.metric span { display: block; font-size: 28dp; font-weight: bold; color: #e4f4ee; margin-top: 9dp; } +.note { margin-top: 22dp; padding: 18dp 20dp; background-color: #9cba6a0e; border: 1dp #b1c68730; border-radius: 10dp; color: #b4c4b9; font-size: 13dp; line-height: 1.6; } +.source-json { font-size: 11dp; line-height: 1.5; white-space: pre-wrap; color: #98b1c3; margin: 14dp 0; } +.history-row, .diagnostic { padding: 15dp 20dp; border-bottom: 1dp #9db7cb22; line-height: 1.6; } +.diagnostic.error { color: #edaaa6; } +.diagnostic.warning { color: #c8c19a; } +.badge { display: inline-block; font-size: 11dp; border: 1dp #7acfa83d; color: #9cdbb7; border-radius: 5dp; padding: 3dp 6dp; } +#overlay { display: none; position: absolute; left: 0; top: 0; width: 100%; height: 100%; background-color: #050c17b3; align-items: center; justify-content: center; } +#modal { width: 620dp; max-height: 91%; padding: 27dp; border: 1dp #9db7cb55; border-radius: 18dp; background-color: #1c2c40; 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; 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: #f0aaa7; font-size: 13dp; margin-top: 10dp; } +.image-layout { display: flex; gap: 24dp; } +.image-stage { flex: 1; min-height: 360dp; background-color: #101b2b; border: 1dp #9db7cb33; 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 #a6e8d5; background-color: #a6e8d512; 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: #93aabd55; border-radius: 4dp; min-height: 30dp; } +scrollbarvertical sliderarrowdec, scrollbarvertical sliderarrowinc { height: 0; } +/* These are semantic theme overrides, including dialogs, inputs and lists. */ +body.silver { color: #25394a; background-color: #e7eef3; } +.silver header, .silver aside, .silver footer { background-color: #dbe5ec; border-color: #26465c20; } +.silver h2 span, .silver small, .silver .eyebrow, .silver #page-subtitle, .silver #status-message, .silver #pagination { color: #577081; } +.silver #world-caption, .silver .record .cell, .silver .form-field label { color: #476274; } +.silver button { color: #2c475b; background-color: #ffffff60; border-color: #496d8b38; } +.silver button:hover { background-color: #ffffffdd; } +.silver button.primary { background-color: #276982; color: #ffffff; border-color: #276982; } +.silver .nav { background-color: transparent; border-color: transparent; } +.silver .nav.selected { color: #215e78; background-color: #4c88a12a; border-color: #4c88a13a; } +.silver .nav .glyph, .silver .form-section { color: #326f87; } +.silver input, .silver select, .silver textarea { background-color: #f8fbfd; color: #223d4e; border-color: #5779934a; } +.silver select selectbox { background-color: #f1f6f9; color: #223d4e; } +.silver .list-panel, .silver .inspector { background-color: #f7fafb99; border-color: #55718730; } +.silver .record { background-color: transparent; border-color: #55718715; } +.silver .record .cell:first-child, .silver .metric span { color: #233f50; } +.silver .record.selected { background-color: #4c88a126; border-left-color: #326f87; } +.silver .table-header { background-color: #cad9e366; } +.silver .table-header button { color: #4c687a; } +.silver .table-header button, .silver button.quiet { background-color: transparent; border-color: transparent; } +.silver .brand-mark { color: #276982; border-color: #27698255; } +.silver .brand-mark span { color: #365568; } +.silver .hero, .silver .metric { background-color: #f4f8fb; border-color: #567b9630; } +.silver .hero p, .silver .empty, .silver .source-json, .silver .form-help { color: #577486; } +.silver .note { background-color: #3d806b0c; border-color: #4a826233; color: #46634f; } +.silver #modal { background-color: #eaf0f5; border-color: #849eaf; } +.silver .image-stage { background-color: #d0dce6; } +.silver .badge, .silver #state { color: #3c775a; } +body.matchday { background-color: #222328; color: #efe9e8; } +.matchday header, .matchday aside, .matchday footer { background-color: #2c2b30; } +.matchday .brand-mark { color: #efb2aa; background-color: #efb2aa0e; border-color: #efb2aa55; } +.matchday button.primary { background-color: #efb2aa; border-color: #efb2aa; color: #362a2b; } +.matchday .nav.selected { background-color: #efb2aa16; color: #efb2aa; border-color: #efb2aa30; } +.matchday .nav.selected .glyph, .matchday .form-section { color: #efb2aa; } +.matchday .list-panel, .matchday .inspector { background-color: #33323988; } +.matchday .record.selected { background-color: #efb2aa18; border-left-color: #efb2aa; } +.matchday input, .matchday select, .matchday textarea { background-color: #26262d; border-color: #a5a1b244; } +.matchday select selectbox { background-color: #35343d; } +.matchday .hero, .matchday .metric { background-color: #333238; } +.matchday #modal { background-color: #333238; } +.matchday #state, .matchday .badge { color: #efb2aa; } +.matchday .image-stage { background-color: #23232b; } diff --git a/docs/EDITOR.md b/docs/EDITOR.md new file mode 100644 index 0000000..d93076a --- /dev/null +++ b/docs/EDITOR.md @@ -0,0 +1,69 @@ +# 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. + +**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. + +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. diff --git a/docs/formats/OBW.md b/docs/formats/OBW.md index a02ff6a..bb736a0 100644 --- a/docs/formats/OBW.md +++ b/docs/formats/OBW.md @@ -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 diff --git a/docs/formats/obw/editor-v1.md b/docs/formats/obw/editor-v1.md new file mode 100644 index 0000000..a9ba7b7 --- /dev/null +++ b/docs/formats/obw/editor-v1.md @@ -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. diff --git a/docs/formats/obw/schema/1.1/editor-world.json b/docs/formats/obw/schema/1.1/editor-world.json new file mode 100644 index 0000000..093b215 --- /dev/null +++ b/docs/formats/obw/schema/1.1/editor-world.json @@ -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} + } +} diff --git a/docs/licenses/LunaSVG.txt b/docs/licenses/LunaSVG.txt new file mode 100644 index 0000000..62a964e --- /dev/null +++ b/docs/licenses/LunaSVG.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020-2025 Samuel Ugochukwu + +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. diff --git a/docs/licenses/PlutoVG.txt b/docs/licenses/PlutoVG.txt new file mode 100644 index 0000000..62a964e --- /dev/null +++ b/docs/licenses/PlutoVG.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020-2025 Samuel Ugochukwu + +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. diff --git a/docs/licenses/README.md b/docs/licenses/README.md index cdd6447..556b28b 100644 --- a/docs/licenses/README.md +++ b/docs/licenses/README.md @@ -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. diff --git a/docs/licenses/SDL2_image.txt b/docs/licenses/SDL2_image.txt new file mode 100644 index 0000000..52d0ed3 --- /dev/null +++ b/docs/licenses/SDL2_image.txt @@ -0,0 +1,17 @@ +Copyright (C) 1997-2025 Sam Lantinga + +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. diff --git a/docs/licenses/cpp-httplib.txt b/docs/licenses/cpp-httplib.txt new file mode 100644 index 0000000..3e5ed35 --- /dev/null +++ b/docs/licenses/cpp-httplib.txt @@ -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. + diff --git a/docs/licenses/libwebp-PATENTS.txt b/docs/licenses/libwebp-PATENTS.txt new file mode 100644 index 0000000..caedf60 --- /dev/null +++ b/docs/licenses/libwebp-PATENTS.txt @@ -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. diff --git a/docs/licenses/libwebp.txt b/docs/licenses/libwebp.txt new file mode 100644 index 0000000..7a6f995 --- /dev/null +++ b/docs/licenses/libwebp.txt @@ -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. + diff --git a/docs/licenses/nlohmann-json.txt b/docs/licenses/nlohmann-json.txt new file mode 100644 index 0000000..a1dacc8 --- /dev/null +++ b/docs/licenses/nlohmann-json.txt @@ -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. diff --git a/docs/licenses/pugixml.txt b/docs/licenses/pugixml.txt new file mode 100644 index 0000000..1ea0d5e --- /dev/null +++ b/docs/licenses/pugixml.txt @@ -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. diff --git a/docs/licenses/stb-image.txt b/docs/licenses/stb-image.txt new file mode 100644 index 0000000..6c9b619 --- /dev/null +++ b/docs/licenses/stb-image.txt @@ -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. +------------------------------------------------------------------------------ diff --git a/docs/qa/editor-poc/README.md b/docs/qa/editor-poc/README.md new file mode 100644 index 0000000..993058c --- /dev/null +++ b/docs/qa/editor-poc/README.md @@ -0,0 +1,52 @@ +# 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; a simple synthetic vector portrait | + +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`: 55 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. +- `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. +- 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 vector +portrait uses a blue rectangle, a circular head and a rounded shoulder shape; +it is an image-editor fixture, not a real or AI-generated player. + +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. diff --git a/docs/qa/editor-poc/clubs-midnight-de.png b/docs/qa/editor-poc/clubs-midnight-de.png new file mode 100644 index 0000000..acaef81 Binary files /dev/null and b/docs/qa/editor-poc/clubs-midnight-de.png differ diff --git a/docs/qa/editor-poc/gui-search.png b/docs/qa/editor-poc/gui-search.png new file mode 100644 index 0000000..11dfd95 Binary files /dev/null and b/docs/qa/editor-poc/gui-search.png differ diff --git a/docs/qa/editor-poc/image-editor-midnight-de.png b/docs/qa/editor-poc/image-editor-midnight-de.png new file mode 100644 index 0000000..33b6278 Binary files /dev/null and b/docs/qa/editor-poc/image-editor-midnight-de.png differ diff --git a/docs/qa/editor-poc/options-midnight-de.png b/docs/qa/editor-poc/options-midnight-de.png new file mode 100644 index 0000000..0d9c30e Binary files /dev/null and b/docs/qa/editor-poc/options-midnight-de.png differ diff --git a/docs/qa/editor-poc/players-silver-en.png b/docs/qa/editor-poc/players-silver-en.png new file mode 100644 index 0000000..4056e48 Binary files /dev/null and b/docs/qa/editor-poc/players-silver-en.png differ diff --git a/docs/qa/editor-poc/roster-matchday-de.png b/docs/qa/editor-poc/roster-matchday-de.png new file mode 100644 index 0000000..fdee936 Binary files /dev/null and b/docs/qa/editor-poc/roster-matchday-de.png differ diff --git a/src/editor/CMakeLists.txt b/src/editor/CMakeLists.txt new file mode 100644 index 0000000..99ce7a2 --- /dev/null +++ b/src/editor/CMakeLists.txt @@ -0,0 +1,81 @@ +# 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) +add_test(NAME editor_core_tests COMMAND editor_core_tests) diff --git a/src/editor/archive.cpp b/src/editor/archive.cpp new file mode 100644 index 0000000..d5e0306 --- /dev/null +++ b/src/editor/archive.cpp @@ -0,0 +1,326 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "editor/archive.hpp" +#include "content/digest.hpp" +#include +#include +#include +#include +#include +#include +#include +#ifdef _WIN32 +#define NOMINMAX +#include +#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 entries; + std::map> 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(opaque)->input; + in.clear(); + in.seekg(std::streamoff(offset)); + in.read(static_cast(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()) {} +ArchiveStore::~ArchiveStore() = default; +std::shared_ptr ArchiveStore::open(const fs::path &source) { + auto result = std::make_shared(); + 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 ArchiveStore::names() const { + std::set 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 bytes) { + if (!safe_name(name) || !bytes || bytes->size() > max_entry) + throw Error("unsafe_asset"); + impl_->changed[name] = std::move(bytes); +} +std::shared_ptr 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 value) { + if (value) + set(name, std::move(value)); + else + impl_->changed.erase(name); +} +void ArchiveStore::save(const fs::path &target, const std::map &docs, + const std::set &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(opaque); + stream.seekp(std::streamoff(position)); + stream.write(static_cast(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 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 diff --git a/src/editor/archive.hpp b/src/editor/archive.hpp new file mode 100644 index 0000000..ab69490 --- /dev/null +++ b/src/editor/archive.hpp @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +#include "editor/types.hpp" +#include + +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 open(const fs::path &); + ~ArchiveStore(); + bool contains(const std::string &) const; + std::vector names() const; + uint64_t size(const std::string &) const; + std::string read(const std::string &) const; + void set(const std::string &, std::shared_ptr); + std::shared_ptr overlay(const std::string &) const; + void restore(const std::string &, std::shared_ptr); + void save(const fs::path &, const std::map &documents, + const std::set &excluded = {}) const; + + private: + struct Impl; + std::unique_ptr impl_; +}; +} // namespace bmh::editor diff --git a/src/editor/images.cpp b/src/editor/images.cpp new file mode 100644 index 0000000..3fc5b71 --- /dev/null +++ b/src/editor/images.cpp @@ -0,0 +1,316 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "editor/images.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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 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 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 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(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(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(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(packed.data()), &size, + reinterpret_cast(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"()"; +} +} // namespace bmh::editor::images diff --git a/src/editor/images.hpp b/src/editor/images.hpp new file mode 100644 index 0000000..0a723ef --- /dev/null +++ b/src/editor/images.hpp @@ -0,0 +1,22 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +#include "editor/types.hpp" +#include + +namespace bmh::editor::images { +struct Raster { + int width = 0, height = 0; + std::vector 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 diff --git a/src/editor/main.cpp b/src/editor/main.cpp new file mode 100644 index 0000000..51e2de3 --- /dev/null +++ b/src/editor/main.cpp @@ -0,0 +1,157 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "editor/ui.hpp" +#include +#include +#include +#include +#include +#include + +namespace { +std::atomic 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; + } +} diff --git a/src/editor/mcp.cpp b/src/editor/mcp.cpp new file mode 100644 index 0000000..a5d59cd --- /dev/null +++ b/src/editor/mcp.cpp @@ -0,0 +1,351 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "editor/mcp.hpp" +#include +#include +#include + +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 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 http; + std::thread worker; + std::atomic active{false}; + int port = 0; + std::string token; +}; +McpServer::McpServer(Session &s) : impl_(std::make_unique(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.", + {{"key", id}, {"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(); + 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 diff --git a/src/editor/mcp.hpp b/src/editor/mcp.hpp new file mode 100644 index 0000000..9001ee1 --- /dev/null +++ b/src/editor/mcp.hpp @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +#include "editor/options.hpp" +#include "editor/session.hpp" +#include + +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_; +}; +} // namespace bmh::editor diff --git a/src/editor/options.cpp b/src/editor/options.cpp new file mode 100644 index 0000000..76d93a3 --- /dev/null +++ b/src/editor/options.cpp @@ -0,0 +1,413 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "editor/options.hpp" +#include +#include +#include +#ifndef _WIN32 +#include +#endif +namespace bmh::editor { +Options Options::load(fs::path override_path) { + Options result; + if (override_path.empty()) { +#ifdef _WIN32 + auto base = std::getenv("APPDATA"); + override_path = (base ? 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; + static const std::map 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 diff --git a/src/editor/options.hpp b/src/editor/options.hpp new file mode 100644 index 0000000..8053e52 --- /dev/null +++ b/src/editor/options.hpp @@ -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 diff --git a/src/editor/session.cpp b/src/editor/session.cpp new file mode 100644 index 0000000..6a4bbc2 --- /dev/null +++ b/src/editor/session.cpp @@ -0,0 +1,554 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "editor/session.hpp" +#include "content/digest.hpp" +#include "editor/images.hpp" +#include +#include + +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(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 files, const std::string &label) { + auto &w = world(); + if (args.contains("expected_revision") && args["expected_revision"].get() != 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, 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 before = existing ? std::optional(*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(); + 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 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 *existing = w.find("assets", str(args, "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 (!existing) + throw Error("record_missing"); + auto source = str(existing->value("x-editor", Json::object()), "original"); + if (source.empty()) + source = w.asset_file(str(args, "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()); + if (key.empty()) { + if (!target.empty()) { + auto id = str(target, "id"); + auto table = str(target, "table"); + key = "asset:" + table + '/' + id + '/' + str(target, "field", table == "players" ? "photo" : "crest"); + } else + key = new_id("asset:uploaded/"); + } + 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 files; + for (auto &[name, data] : + std::vector>{{source_file, original}, {output_file, result.bytes}}) { + if (!w.store->contains(name)) + files.push_back({name, w.store->overlay(name), std::make_shared(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}}}}; + 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", {{'/' + str(target, "field", "crest"), 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 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(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(); + if (choice < options.size()) + paint(options[choice].get(), 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() != 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() != 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 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()); + 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 diff --git a/src/editor/session.hpp b/src/editor/session.hpp new file mode 100644 index 0000000..f569945 --- /dev/null +++ b/src/editor/session.hpp @@ -0,0 +1,45 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +#include "editor/world.hpp" +#include + +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 asset_bytes(const std::string &key_or_path) const; + + private: + struct Delta { + std::string table, id; + std::optional before, after; + }; + struct FileDelta { + std::string name; + std::shared_ptr before, after; + }; + struct Frame { + std::string label; + std::vector changes; + std::vector files; + uint64_t before = 0, after = 0; + }; + mutable std::recursive_mutex mutex_; + std::unique_ptr world_; + std::vector 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 files = {}, const std::string &label = "edit"); + void frame(const Frame &, bool forward); + void replace(World value); + Json import_image(const Json &); +}; +} // namespace bmh::editor diff --git a/src/editor/types.hpp b/src/editor/types.hpp new file mode 100644 index 0000000..f00b931 --- /dev/null +++ b/src/editor/types.hpp @@ -0,0 +1,75 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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(); + 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().empty()) + return value[key].get(); + 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(); +} +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 diff --git a/src/editor/ui.cpp b/src/editor/ui.cpp new file mode 100644 index 0000000..bd9482d --- /dev/null +++ b/src/editor/ui.cpp @@ -0,0 +1,1398 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "editor/ui.hpp" +#include "editor/images.hpp" +#include "launch/rml_path.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace bmh::editor { +namespace { +std::string number(double n) { + std::ostringstream s; + s.imbue(std::locale::classic()); + s << n; + return s.str(); +} +std::string button(const std::string &action, const std::string &label, const std::string &css = "", + const std::string &attributes = "") { + return ""; +} +struct Video { + SDL_Window *window = nullptr; + SDL_GLContext gl = nullptr; + bool loader = false; + Video() { + if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS | SDL_INIT_TIMER) != 0) + throw Error("video_failed"); + SDL_SetHint(SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, "1"); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); +#ifdef __APPLE__ + SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1); +#else + SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3); +#endif + SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); + window = + SDL_CreateWindow("OpenBMH Editor", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1440, 900, + SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI | SDL_WINDOW_HIDDEN); + if (!window) + throw Error("video_failed"); + SDL_SetWindowMinimumSize(window, 1080, 720); + gl = SDL_GL_CreateContext(window); + if (!gl) + throw Error("video_failed"); + SDL_GL_MakeCurrent(window, gl); + SDL_GL_SetSwapInterval(1); + std::string error; + if (!RmlGL3::Initialize(&error)) + throw Error("video_failed", {{"detail", error}}); + loader = true; + SDL_StartTextInput(); + } + ~Video() { + if (loader) + RmlGL3::Shutdown(); + if (gl) + SDL_GL_DeleteContext(gl); + if (window) + SDL_DestroyWindow(window); + SDL_Quit(); + } +}; +class Renderer final : public RenderInterface_GL3 { + public: + Session &session; + std::map> memory; + std::map logical; + uint64_t serial = 0; + explicit Renderer(Session &s) : session(s) {} + std::string asset(const std::string &key) { + auto token = "world-image-" + std::to_string(serial++) + ".png"; + logical[token] = key; + return token; + } + std::string bytes(std::string data, const std::string &extension) { + auto token = "memory-image-" + std::to_string(serial++) + ".png"; + memory[token] = {std::move(data), extension}; + return token; + } + void clear() { + Rml::ReleaseTextures(this); + logical.clear(); + memory.clear(); + } + Rml::TextureHandle LoadTexture(Rml::Vector2i &dimensions, const Rml::String &source) override { + const auto token = utf8(path(source).filename()); + if (!memory.contains(token) && !logical.contains(token)) + return RenderInterface_GL3::LoadTexture(dimensions, source); + try { + auto value = memory.contains(token) ? memory.at(token) : session.asset_bytes(logical.at(token)); + auto raster = images::decode(value.first, value.second, token.starts_with("icon-") ? 64 : 512); + if (logical.contains(token) && raster.width != raster.height) { + const int side = std::max(raster.width, raster.height); + images::Raster square{side, side, std::vector(size_t(side) * side * 4)}; + for (int y = 0; y < raster.height; ++y) + std::copy_n(raster.pixels.data() + size_t(y) * raster.width * 4, raster.width * 4, + square.pixels.data() + + (size_t(y + (side - raster.height) / 2) * side + (side - raster.width) / 2) * 4); + raster = std::move(square); + } + for (size_t i = 0; i < raster.pixels.size(); i += 4) + for (int c = 0; c < 3; ++c) + raster.pixels[i + c] = uint8_t((unsigned(raster.pixels[i + c]) * raster.pixels[i + 3] + 127) / 255); + dimensions = {raster.width, raster.height}; + return GenerateTexture(raster.pixels, dimensions); + } catch (const std::exception &) { + return {}; + } + } +}; +class EditorUi final : public Rml::EventListener { + Session &session_; + Options &options_; + McpServer &server_; + UiConfig config_; + Video video_; + bmh::rml::AssetFiles files_; + SystemInterface_SDL system_{video_.window}; + Renderer renderer_; + TextInputMethodEditor_SDL ime_; + Rml::Context *context_ = nullptr; + Rml::ElementDocument *doc_ = nullptr; + bool initialized_ = false, closed_ = false, busy_ = false, modal_ = false; + bool roster24_ = false, show_source_ = false, needs_refresh_ = true; + uint64_t revision_ = uint64_t(-1); + Json info_, selected_ = Json::object(), listed_ = Json::array(); + std::map lookup_; + std::string page_ = "overview", selected_id_, search_, nation_, league_, team_, sort_ = "name", remembered_; + bool descending_ = false; + int offset_ = 0; + size_t total_ = 0; + struct Field { + std::string id, pointer, kind, initial; + Json original; + }; + std::vector fields_; + std::deque> pending_; + std::future work_; + std::function completed_; + std::function modal_accept_, discard_continuation_; + std::string image_bytes_, image_extension_, image_file_, image_key_; + Json image_target_, image_recipe_; + double drag_x_ = 0, drag_y_ = 0; + bool dragging_ = false; + std::chrono::steady_clock::time_point start_ = std::chrono::steady_clock::now(); + std::string t(const std::string &key) const { return tr(options_.language, key); } + Rml::Element *el(const std::string &id) const { + auto *value = doc_->GetElementById(id); + if (!value) + throw std::runtime_error("Missing editor element: " + id); + return value; + } + void html(const std::string &id, const std::string &value) { el(id)->SetInnerRML(value); } + void label(const std::string &id, const std::string &value) { html(id, escaped(value)); } + std::string value(const std::string &id) const { + auto *field = dynamic_cast(el(id)); + return field ? field->GetValue() : ""; + } + void set_value(const std::string &id, const std::string &value) { + if (auto *field = dynamic_cast(el(id))) + field->SetValue(value); + } + std::string table() const { return page_ == "roster" ? "players" : page_; } + static std::string identity(const Json &row, const std::string &table) { + return str(row, table == "assets" ? "key" : "id"); + } + std::string title(const Json &row) const { + auto name = row.value("name", Json()); + if (name.is_object() && name.contains(options_.language) && name[options_.language].is_string()) + return name[options_.language]; + auto result = text(name); + return result.empty() ? str(row, "key", str(row, "id")) : result; + } + std::string ref(const Json &row, const std::string &key) const { + const auto id = str(row, key); + auto found = lookup_.find(id); + return found == lookup_.end() ? id : title(found->second); + } + std::string img(const std::string &key, const std::string &css) { + return ""; + } + std::string icon(const std::string &name) { + static const std::map paths{ + {"overview", "M3 3h7v7H3zM14 3h7v7h-7zM3 14h7v7H3zM14 14h7v7h-7z"}, + {"nations", "M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0M3 12h18M12 3c-5 5-5 " + "13 0 18M12 3c5 5 5 13 0 18"}, + {"competitions", "M7 3h10v6c0 6-10 6-10 0zM7 5H3v3c0 3 4 4 4 4M17 " + "5h4v3c0 3-4 4-4 4M12 14v6M7 21h10"}, + {"clubs", "M4 3h16v10c0 5-8 9-8 9S4 18 4 13zM8 8h8M8 12h8"}, + {"players", "M16 7a4 4 0 1 1-8 0 4 4 0 0 1 8 0M4 22v-3c0-8 16-8 16 0v3"}, + {"roster", "M3 3h18v18H3zM9 3v18M3 9h18M3 15h18"}, + {"stadiums", "M3 8c0-7 18-7 18 0v8c0 7-18 7-18 0zM3 8c0 7 18 7 18 0M8 " + "13v7M16 13v7"}, + {"staff", "M5 22V3h13l-4 5 4 5H5"}, + {"assets", "M3 3h18v18H3zM3 18l6-7 5 5 3-3 4 5M17 6v2"}, + {"review", "M12 2 1 21h22zM12 8v6M12 17v1"}, + {"changes", "M4 5v6h6M4 11a9 9 0 1 1 1 7"}}; + const auto token = "icon-" + options_.theme + '-' + name + ".png"; + if (!renderer_.memory.contains(token)) { + auto color = options_.theme == "silver" ? "#537588" : options_.theme == "matchday" ? "#d3b3b0" : "#9cb9c8"; + renderer_.memory[token] = {"", + ".svg"}; + } + return ""; + } + std::string image_key(const Json &row) const { + if (table() == "assets") + return str(row, "key"); + if (table() == "players" || table() == "staff") + return str(row, "photo", "asset:player/" + str(row, "id") + "/photo"); + if (table() == "competitions") + return str(row, "trophy", "asset:trophy/generic"); + return str(row, "crest", "asset:club/" + str(row, "id") + "/crest"); + } + Json all(const std::string &table) { + Json rows = Json::array(); + size_t offset = 0; + do { + auto page = session_.execute("list", {{"table", table}, {"offset", offset}, {"limit", 200}}); + for (auto &row : page["items"]) + rows.push_back(row); + offset += page["items"].size(); + if (offset >= page["total"].get()) + break; + } while (true); + return rows; + } + void refresh_lookup() { + lookup_.clear(); + if (!info_.value("loaded", false)) + return; + for (auto name : {"nations", "competitions", "clubs", "stadiums"}) + for (auto &row : all(name)) + lookup_[str(row, "id")] = row; + } + std::string choices(const std::string &name, const std::string &chosen, const std::string &empty = "", + const std::string &nation = "") const { + std::string result = + ""; + std::vector> values; + bool found = chosen.empty(); + for (auto &[id, row] : lookup_) { + bool matches = name == "nations" ? id.starts_with("nation:") + : name == "competitions" ? id.starts_with("comp:") && str(row, "type") == "league" + : name == "clubs" ? id.starts_with("club:") || id.starts_with("team:") + : id.starts_with("stadium:"); + if (!matches || (!nation.empty() && str(row, "nation") != nation && id != chosen)) + continue; + values.emplace_back(id, title(row)); + } + std::stable_sort(values.begin(), values.end(), + [](auto &a, auto &b) { return folded(a.second) < folded(b.second); }); + for (auto &[id, name] : values) { + found |= id == chosen; + result += ""; + } + if (!found) + result += ""; + return result; + } + void resize() { + int w, h, pw, ph; + SDL_GetWindowSize(video_.window, &w, &h); + SDL_GL_GetDrawableSize(video_.window, &pw, &ph); + if (!w || !h) + return; + renderer_.SetViewport(pw, ph); + context_->SetDimensions({pw, ph}); + context_->SetDensityIndependentPixelRatio(float(pw) / w * + std::clamp(std::min(w / 1440.f, h / 900.f), .78f, 1.8f)); + } + void close_modal() { + el("overlay")->SetProperty("display", "none"); + modal_ = dragging_ = false; + modal_accept_ = {}; + } + void modal(const std::string &title, const std::string &body, const std::string &accept, + std::function callback, bool cancel = true, bool wide = false) { + label("modal-title", title); + html("modal-content", body); + label("modal-error", ""); + el("modal")->SetClass("wide", wide); + html("modal-buttons", (cancel ? button("cancel-modal", t("cancel")) : "") + + (accept.empty() ? "" : button("accept-modal", accept, "primary"))); + modal_accept_ = std::move(callback); + modal_ = true; + el("overlay")->SetProperty("display", "flex"); + context_->Update(); + } + void error(const std::exception &e) { + const auto *typed = dynamic_cast(&e); + auto message = t(typed ? typed->code : "invalid_change"); + if (typed && !typed->details.empty()) + message += "\n" + typed->details.dump(2).substr(0, 4000); + if (modal_) + label("modal-error", message); + else + modal(t("error"), "

" + escaped(message) + "

", t("close"), [this] { close_modal(); }, false); + } + void background(const std::string &command, Json args, std::function callback = {}) { + if (busy_) + return; + busy_ = true; + completed_ = std::move(callback); + label("status-message", t("loading")); + work_ = std::async(std::launch::async, [this, command, args] { return session_.execute(command, args); }); + } + std::string native_dialog(const std::string &kind) { + NFD::Guard guard; + NFD::UniquePathU8 result; + nfdresult_t status; + if (kind == "folder") + status = NFD::PickFolder(result); + else if (kind == "save") { + const nfdu8filteritem_t filter[] = {{"OpenBMH world", "obw"}}; + status = NFD::SaveDialog(result, filter, 1, nullptr, "world.obw"); + } else if (kind == "image") { + const nfdu8filteritem_t filter[] = {{"Images", "png,jpg,jpeg,webp,svg"}}; + status = NFD::OpenDialog(result, filter, 1); + } else if (kind == "export") { + const nfdu8filteritem_t filter[] = {{"PNG", "png"}}; + status = NFD::SaveDialog(result, filter, 1, nullptr, "image.png"); + } else { + const nfdu8filteritem_t filter[] = {{"OpenBMH world", "obw"}}; + status = NFD::OpenDialog(result, filter, 1); + } + if (status == NFD_CANCEL) + return ""; + if (status != NFD_OKAY) + throw Error("dialog_failed"); + return result.get(); + } + void save(bool save_as = false, std::function after = {}) { + auto file = save_as ? "" : str(session_.execute("info"), "path"); + if (file.empty()) + file = native_dialog("save"); + if (file.empty()) + return; + if (folded(utf8(path(file).extension())) != ".obw") + file += ".obw"; + background("save", {{"path", file}}, [this, after](const Json &) { + close_modal(); + label("status-message", t("saved_ok")); + if (after) + after(); + }); + } + void leaving(std::function after) { + if (has_draft()) + apply_fields(); + if (!session_.execute("info").value("dirty", false)) { + after(); + return; + } + discard_continuation_ = after; + modal(t("dirty_prompt"), "

" + escaped(t("dirty_detail")) + "

", t("save"), + [this, after] { save(false, after); }); + html("modal-buttons", button("cancel-modal", t("cancel")) + button("discard-world", t("discard")) + + button("accept-modal", t("save"), "primary")); + } + void chrome() { + doc_->SetClassNames(options_.theme); + label("tagline", t("poc")); + label("nav-label", t("data_areas")); + label("profile-note", t("not_playable")); + label("world-caption", info_.value("loaded", false) ? str(info_, "title") : ""); + html("top-actions", button("new", t("new_world"), "quiet") + button("open", t("open")) + + button("save", t("save"), "primary", info_.value("loaded", false) ? "" : "disabled") + + button("options", t("options"), "quiet")); + std::string nav; + for (const std::string name : {"overview", "nations", "competitions", "clubs", "players", "roster", "stadiums", + "staff", "assets", "review", "changes"}) + nav += ""; + html("navigation", nav); + label("page-kicker", "OpenBMH / " + t(page_)); + label("page-title", t(page_)); + label("page-subtitle", page_ == "roster" ? t("roster_hint") + : page_ == "review" ? t("review_hint") + : t("subtitle_" + page_)); + label("state", info_.value("dirty", false) ? "* " + t("unsaved") : t("saved")); + html("bottom-actions", + button("undo", t("undo"), "quiet", info_.value("can_undo", false) ? "" : "disabled") + + button("redo", t("redo"), "quiet", info_.value("can_redo", false) ? "" : "disabled") + + button("options", "MCP · " + t(server_.running() ? "online" : "offline"), "quiet")); + } + void overview() { + html("toolbar", ""); + html("pagination", ""); + html("page-actions", + info_.value("loaded", false) ? button("validate", t("validate")) + button("save-as", t("save_as")) : ""); + std::string body = "
OPENBMH WORLD STUDIO

" + + escaped(t("workspace")) + "

" + + escaped(info_.value("loaded", false) ? str(info_, "title") : t("welcome_hint")) + + "

" + button("open-file", t("open_world"), "primary") + + button("import-folder", t("import_legacy")) + button("demo", t("demo"), "quiet") + + "
"; + if (info_.value("loaded", false)) { + body += "
"; + for (auto name : {"nations", "competitions", "clubs", "players", "stadiums", "staff", "assets", "review"}) + body += ""; + body += "
" + escaped(t("not_playable")) + "
" + + escaped(t("preservation_note")) + "
"; + } + body += "
"; + html("page-content", body); + } + void field(std::string &html, const std::string &pointer, const std::string &caption, + const std::string &kind = "text", const std::string &choice_table = "") { + const auto id = "property-" + std::to_string(fields_.size()); + const auto jp = Json::json_pointer(pointer); + Json original = selected_.contains(jp) ? selected_[jp] : Json(); + std::string val = original.is_null() ? "" + : original.is_string() ? original.get() + : original.dump(); + fields_.push_back({id, pointer, kind, val, original}); + html += "
"; + if (kind == "select") + html += ""; + else if (kind == "bool") + html += ""; + else if (kind == "json") + html += ""; + else + html += ""; + html += "
"; + } + void name_field(std::string &body) { + if (selected_.value("name", Json()).is_object()) { + if (selected_["name"].contains("first") || selected_["name"].contains("last")) { + field(body, "/name/first", t("first")); + field(body, "/name/last", t("last")); + field(body, "/name/known_as", t("known_as")); + } else + field(body, "/name/default", t("name")); + } else + field(body, "/name", t("name")); + } + std::string inspector() { + fields_.clear(); + if (selected_.empty()) + return "
" + escaped(t("select_record")) + "
"; + std::string body = "
"; + if (table() == "players" || table() == "clubs" || table() == "competitions" || table() == "assets") + body += img(table() == "players" && selected_.contains("appearance") ? "portrait:" + selected_id_ + : image_key(selected_), + "hero-image"); + body += "

" + escaped(title(selected_)) + "

" + escaped(selected_id_) + + "
"; + if (page_ == "review") { + body += "

" + escaped(str(selected_, "reason", str(selected_, "field"))) + + "

" + button("resolve", t("resolve"), "primary") + "
" + + escaped(selected_.dump(2)) + "
"; + } else { + name_field(body); + if (table() == "nations") { + field(body, "/confederation", t("confederation")); + field(body, "/playable", t("playable"), "bool"); + } else if (table() == "competitions") { + field(body, "/nation", t("nation"), "select", "nations"); + field(body, "/type", t("type")); + field(body, "/tier", t("tier"), "integer"); + field(body, "/visible", t("visible"), "bool"); + field(body, "/trophy", t("trophy")); + } else if (table() == "clubs") { + field(body, "/short_name", t("short_name")); + field(body, "/nation", t("nation"), "select", "nations"); + field(body, "/competition", t("competition"), "select", "competitions"); + field(body, "/stadium", t("stadium"), "select", "stadiums"); + field(body, "/founded", t("founded"), "integer"); + field(body, "/colors", t("colors"), "json"); + } else if (table() == "players") { + field(body, "/born", t("born")); + if (selected_.contains("age_at_start")) + field(body, "/age_at_start", t("age_at_start"), + selected_["age_at_start"].is_object() ? "json" : "integer"); + field(body, "/nationalities", t("nationalities"), "json"); + field(body, "/positions", t("positions"), "json"); + field(body, "/team", t("team"), "select", "clubs"); + field(body, "/squad_number", t("squad_number"), "integer"); + if (page_ == "roster") { + body += "
" + button("remember", t("remember_player")) + "
"; + if (!remembered_.empty() && remembered_ != selected_id_) + body += button("swap", t("swap_player")); + body += + "
" + button("order-up", "↑") + button("order-down", "↓") + "
"; + } + body += "
" + escaped(t("attributes")) + " · " + + escaped(str(selected_, "attribute_set")) + "
"; + auto attributes = selected_.value("attributes", Json::object()); + Json definitions = Json::object(); + for (const auto &rule : session_.execute("rules")) { + auto id = str(rule, "attribute_set", str(rule, "id")); + if (id == str(selected_, "attribute_set") || id == "rule:" + str(selected_, "attribute_set")) + definitions = rule.value("fields", Json::object()); + } + for (auto it = attributes.begin(); it != attributes.end(); ++it) { + auto range = definitions.value(it.key(), Json::object()); + const auto bounds = range.contains("min") && range.contains("max") + ? " (" + range["min"].dump() + "–" + range["max"].dump() + ")" + : ""; + field(body, "/attributes/" + it.key(), t(it.key()) + bounds, "integer"); + } + if (attributes.empty()) + body += "

" + escaped(t("unrated_hint")) + "

"; + field(body, "/attribute_set", t("attribute_set")); + if (attributes.empty() || show_source_) + field(body, "/attributes", t("attributes"), "json"); + } else if (table() == "stadiums") { + field(body, "/owner", t("owner"), "select", "clubs"); + for (auto key : {"total", "seated", "standing", "boxes"}) + field(body, "/capacity/" + std::string(key), t(key), "integer"); + field(body, "/facilities", t("facilities"), "json"); + } else if (table() == "staff") { + field(body, "/nation", t("nation"), "select", "nations"); + field(body, "/role", t("role")); + field(body, "/attributes", t("attributes"), "json"); + } else if (table() == "assets") { + field(body, "/source", t("source")); + field(body, "/author", t("author")); + field(body, "/license", t("license")); + body += "
" + + escaped(selected_.value("width", Json()).dump() + " × " + + selected_.value("height", Json()).dump()) + + "
"; + } + if (table() == "players" || table() == "clubs" || table() == "competitions" || table() == "assets") { + body += "
" + escaped(t("assets")) + "
" + + button("image-import", t("image_import")) + button("image-edit", t("image_edit")) + "
" + + button("image-export", t("image_export"), "quiet"); + } + body += "
" + button("toggle-source", t("provenance"), "quiet") + "
"; + if (show_source_) + body += "
" + escaped(selected_.dump(2)) + "
"; + } + body += "
"; + if (page_ != "review") + body += "
" + button("delete", t("delete"), "danger") + + button("apply", t("apply"), "primary") + "
"; + return body + "
"; + } + void records() { + if (!info_.value("loaded", false)) { + overview(); + return; + } + html("page-actions", page_ == "review" + ? button("validate", t("validate")) + : button("duplicate", t("duplicate")) + button("add", t("add"), "primary")); + std::string toolbar = ""; + if (table() == "clubs" || table() == "players" || table() == "competitions") + toolbar += ""; + if (table() == "clubs" || table() == "players") + toolbar += ""; + if (table() == "players") + toolbar += ""; + if (page_ == "roster") + toolbar += button("view24", "24", roster24_ ? "primary" : ""); + html("toolbar", toolbar); + Json args{{"table", table()}, {"search", search_}, {"nation", nation_}, + {"competition", league_}, {"team", team_}, {"sort", sort_}, + {"descending", descending_}, {"offset", offset_}, {"limit", roster24_ ? 24 : 200}}; + if (page_ == "staff") + args["role"] = "referee"; + auto page = session_.execute("list", args); + listed_ = page["items"]; + total_ = page["total"].get(); + if (selected_id_.empty() && !listed_.empty()) + selected_id_ = identity(listed_[0], table()); + selected_ = Json::object(); + if (!selected_id_.empty()) { + try { + selected_ = session_.execute("get", {{"table", table()}, {"id", selected_id_}})["record"]; + } catch (const Error &) { + selected_id_.clear(); + } + } + std::string columns = + button("sort", t("name") + (sort_ == "name" ? (descending_ ? " -" : " +") : ""), "", "data-value=\"name\""); + const bool players = table() == "players", clubs = table() == "clubs"; + columns += button("sort", + t(players ? "team" + : clubs || table() == "competitions" ? "nation" + : "type"), + "", "data-value=\"" + std::string(players ? "team" : "nation") + "\""); + columns += button("sort", + t(players ? "positions" + : clubs ? "competition" + : "details"), + "", "data-value=\"" + std::string(players ? "positions" : "competition") + "\""); + std::string rows; + for (auto &row : listed_) { + auto id = identity(row, table()); + std::string detail = players ? "" + : clubs ? ref(row, "competition") + : str(row, "confederation", str(row, "kind")); + if (players) + for (auto &p : row.value("positions", Json::array())) { + if (!detail.empty()) + detail += " / "; + detail += p.is_string() ? t(p.get()) : "?"; + } + if (page_ == "review") + detail = t(row.value("resolved", false) ? "resolved" : "unresolved"); + std::string second = players ? ref(row, "team") + : clubs || table() == "competitions" ? ref(row, "nation") + : str(row, "type", str(row, "role")); + std::string image; + if (clubs || table() == "assets") + image = img(image_key(row), "mini-logo"); + rows += ""; + } + if (rows.empty()) + rows = "
" + escaped(t("empty")) + "
"; + html("page-content", "
" + + columns + "
" + rows + + "
" + inspector() + "
"); + // RmlUI's textarea parser retains its raw body rather than decoding + // HTML entities. Assign native values after constructing the controls. + for (auto &f : fields_) { + set_value(f.id, f.kind == "bool" && f.initial.empty() ? "false" : f.initial); + f.initial = value(f.id); + } + html("pagination", + "" + std::to_string(total_) + " " + escaped(t("records")) + + (roster24_ ? " · " + escaped(t("compatibility24")) : "") + "
" + + button("previous", t("previous"), "quiet", offset_ > 0 ? "" : "disabled") + "" + + std::to_string(offset_ + (total_ ? 1 : 0)) + "–" + std::to_string(offset_ + listed_.size()) + + "" + + button("next", t("next"), "quiet", size_t(offset_) + listed_.size() < total_ ? "" : "disabled") + + "
"); + } + void changes() { + html("toolbar", ""); + html("pagination", ""); + html("page-actions", button("validate", t("validate"))); + std::string body = "
"; + auto frames = info_.value("loaded", false) ? session_.execute("history") : Json::array(); + for (auto &frame : frames) { + body += "
" + + escaped(t(frame.value("applied", false) ? "applied" : "undone")) + " " + + escaped(t(str(frame, "label"))) + ""; + for (auto &delta : frame["changes"]) + body += escaped(str(delta, "table") + " / " + str(delta, "id")) + "
"; + body += "
"; + } + if (frames.empty()) + body += "
" + escaped(t("no_changes")) + "
"; + html("page-content", body + "
"); + } + void refresh() { + const auto *focus = context_->GetFocusElement(); + const bool search_focused = focus && focus->GetId() == "search"; + int selection_start = 0, selection_end = 0; + if (search_focused) + if (auto *input = dynamic_cast(context_->GetFocusElement())) + input->GetSelection(&selection_start, &selection_end, nullptr); + info_ = session_.execute("info"); + auto rev = info_.value("revision", uint64_t(0)); + renderer_.clear(); + if (revision_ != rev) { + refresh_lookup(); + revision_ = rev; + } + chrome(); + if (page_ == "overview") + overview(); + else if (page_ == "changes") + changes(); + else + records(); + if (search_focused && doc_->GetElementById("search")) { + auto *input = dynamic_cast(el("search")); + input->Focus(); + input->SetSelectionRange(selection_start, selection_end); + } + needs_refresh_ = false; + } + bool has_draft() const { + if (!doc_) + return false; + for (const auto &field : fields_) + if (doc_->GetElementById(field.id) && value(field.id) != field.initial) + return true; + return false; + } + void leave_fields(std::function next) { + if (!has_draft()) { + next(); + return; + } + discard_continuation_ = next; + modal(t("draft_prompt"), "

" + escaped(t("draft_detail")) + "

", t("apply"), [this, next] { + apply_fields(); + close_modal(); + next(); + }); + html("modal-buttons", button("cancel-modal", t("cancel")) + button("discard-world", t("discard")) + + button("accept-modal", t("apply"), "primary")); + } + void apply_fields() { + if (selected_.empty()) + return; + Json set = Json::object(); + for (const auto &f : fields_) { + const auto input = value(f.id); + if (input == f.initial) + continue; + Json parsed; + if (input.empty()) + parsed = nullptr; + else if (f.kind == "integer" || f.kind == "json" || f.kind == "bool") { + try { + parsed = Json::parse(input); + } catch (const Json::exception &) { + throw Error("invalid_change", {{"field", f.pointer}}); + } + if (f.kind == "integer" && !parsed.is_number_integer()) + throw Error("invalid_change", {{"field", f.pointer}}); + } else + parsed = input; + set[f.pointer] = parsed; + } + auto result = session_.execute( + "apply", {{"expected_revision", revision_}, + {"changes", Json::array({{{"table", table()}, {"id", selected_id_}, {"set", set}}})}}); + if (result.value("changed", false)) + needs_refresh_ = true; + } + void options() { + std::string body = "
"; + body += "
MCP
"; + body += "
"; + body += "

" + t("mcp_local") + " · " + t(server_.running() ? "online" : "offline") + + (server_.running() ? "
http://127.0.0.1:" + std::to_string(server_.port()) + "/mcp" : "") + "

"; + if (server_.running()) + body += button("copy-connection", t("copy_connection")); + modal(t("options"), body, t("apply"), [this] { + auto next = options_; + next.apply({{"language", value("option-language")}, + {"theme", value("option-theme")}, + {"mcp_port", std::stoi(value("option-port"))}, + {"mcp_enabled", value("option-mcp") == "true"}}); + const bool restart = next.mcp_port != options_.mcp_port || next.mcp_enabled != options_.mcp_enabled || + (next.mcp_enabled && !server_.running()); + next.save(); + options_ = next; + if (restart) + server_.start(options_); + close_modal(); + needs_refresh_ = true; + }); + } + Json crop_recipe() { + Json recipe{{"angle", std::stod(value("image-angle"))}, + {"flip_x", value("image-flip-x") == "true"}, + {"flip_y", value("image-flip-y") == "true"}}; + Json crop; + for (auto key : {"x", "y", "width", "height"}) + crop[key] = std::stod(value("crop-" + std::string(key))); + recipe["crop"] = crop; + return recipe; + } + void crop_box() { + const auto crop = image_recipe_.value("crop", Json{{"x", 0}, {"y", 0}, {"width", 1}, {"height", 1}}); + for (auto [name, key] : std::vector>{ + {"left", "x"}, {"top", "y"}, {"width", "width"}, {"height", "height"}}) + el("crop-box")->SetProperty(name, number(crop.value(key, 0.0) * 100) + '%'); + } + void preview_image(bool from_controls = true) { + if (from_controls) + image_recipe_ = crop_recipe(); + Json full = image_recipe_; + full.erase("crop"); + auto raster = images::preview(image_bytes_, image_extension_, full, 460); + const double scale = std::min(400.0 / raster.width, 360.0 / raster.height); + const auto w = int(std::round(raster.width * scale)), h = int(std::round(raster.height * scale)); + auto token = renderer_.bytes(images::encode_png(raster), ".png"); + el("edit-preview")->SetAttribute("src", token); + el("edit-preview")->SetProperty("width", std::to_string(w) + "dp"); + el("edit-preview")->SetProperty("height", std::to_string(h) + "dp"); + el("crop-canvas")->SetProperty("width", std::to_string(w) + "dp"); + el("crop-canvas")->SetProperty("height", std::to_string(h) + "dp"); + crop_box(); + } + void edit_image(bool existing, bool fresh = false) { + image_file_.clear(); + image_key_ = fresh ? "" : image_key(selected_); + image_target_ = Json::object(); + image_recipe_ = {{"angle", 0}, + {"flip_x", false}, + {"flip_y", false}, + {"crop", {{"x", 0}, {"y", 0}, {"width", 1}, {"height", 1}}}}; + if (table() != "assets") + image_target_ = {{"table", table()}, + {"id", selected_id_}, + {"field", table() == "players" ? "photo" + : table() == "competitions" ? "trophy" + : "crest"}}; + if (!existing) { + image_file_ = native_dialog("image"); + if (image_file_.empty()) + return; + image_bytes_ = read_file(path(image_file_)); + image_extension_ = folded(utf8(path(image_file_).extension())); + if (table() == "assets" && selected_id_.empty()) + image_key_.clear(); + } else { + auto row = session_.execute("get", {{"table", "assets"}, {"id", image_key_}})["record"]; + auto metadata = row.value("x-editor", Json::object()); + auto source = str(metadata, "original"); + auto pair = session_.asset_bytes(source.empty() ? image_key_ : source); + image_bytes_ = std::move(pair.first); + image_extension_ = pair.second; + if (metadata.contains("transform")) + image_recipe_ = metadata["transform"]; + } + std::string body = "
"; + body += "
"; + for (auto key : {"x", "y"}) + body += "
"; + body += "
" + t("crop") + + "
"; + for (auto key : {"x", "y", "width", "height"}) + body += "
"; + body += button("image-preview", t("preview")) + button("image-reset", t("reset"), "quiet") + + "

" + t("crop_hint") + "

"; + modal( + t(existing ? "image_edit" : "image_import"), body, t("apply"), + [this] { + image_recipe_ = crop_recipe(); + Json args{{"key", image_key_}, {"transform", image_recipe_}, {"expected_revision", revision_}}; + if (!image_file_.empty()) + args["file"] = image_file_; + if (!image_target_.empty()) + args["target"] = image_target_; + session_.execute(image_file_.empty() ? "asset.edit" : "asset.import", args); + close_modal(); + needs_refresh_ = true; + }, + true, true); + preview_image(false); + } + void new_record(bool duplicate) { + if (table() == "assets") { + edit_image(false, true); + return; + } + if (selected_.empty() && duplicate) + return; + modal(t(duplicate ? "duplicate" : "add"), + "
", + t("add"), [this, duplicate] { + if (value("new-name").empty()) + throw Error("missing_name"); + Json action{{"op", "create"}, {"table", table()}, {"name", value("new-name")}}; + if (duplicate) { + Json copy = selected_; + copy.erase("id"); + copy.erase("x-legacy"); + if (table() == "players") + copy["name"] = {{"first", ""}, {"last", value("new-name")}}; + else + copy["name"] = {{"default", value("new-name")}}; + if (table() == "competitions") { + copy["members"] = Json::array(); + copy["stages"] = Json::array(); + } + action["data"] = copy; + } + auto result = + session_.execute("apply", {{"expected_revision", revision_}, {"changes", Json::array({action})}}); + selected_id_ = result["created"][0]; + close_modal(); + needs_refresh_ = true; + }); + } + void dispatch(const std::string &action, const std::string &arg) { + if (busy_) + return; + if (action == "navigate") + leave_fields([this, arg] { + page_ = arg; + fields_.clear(); + selected_id_.clear(); + offset_ = 0; + search_.clear(); + needs_refresh_ = true; + }); + else if (action == "select") + leave_fields([this, arg] { + selected_id_ = arg; + needs_refresh_ = true; + }); + else if (action == "cancel-modal") + close_modal(); + else if (action == "accept-modal") { + if (modal_accept_) { + auto callback = modal_accept_; + callback(); + } + } else if (action == "discard-world") { + close_modal(); + if (discard_continuation_) + discard_continuation_(); + } else if (action == "options") + options(); + else if (action == "copy-connection") { + SDL_SetClipboardText(server_.connection(options_).dump(2).c_str()); + label("modal-error", t("copied")); + } else if (action == "save" || action == "save-as") { + if (has_draft()) + apply_fields(); + save(action == "save-as"); + } else if (action == "open") { + modal(t("open"), + "
" + button("open-file", t("open_world")) + + button("open-folder", t("open_folder")) + button("import-folder", t("import_legacy")) + "
", + "", {}); + } else if (action == "open-file" || action == "open-folder" || action == "import-folder") { + const auto file = native_dialog(action == "open-file" ? "open" : "folder"); + if (!file.empty()) + leaving([this, file] { + close_modal(); + background("open", {{"path", file}, {"discard", true}}, [this](const Json &) { + selected_id_.clear(); + offset_ = 0; + }); + }); + } else if (action == "demo") + leaving([this] { + close_modal(); + background("demo", {{"discard", true}}); + }); + else if (action == "new") + leaving([this] { + modal(t("new_world"), + "
", + t("confirm"), [this] { + auto title = value("new-title"); + close_modal(); + background("new", {{"title", title}, {"discard", true}}); + }); + }); + else if (action == "apply") + apply_fields(); + else if (action == "undo" || action == "redo") { + session_.execute(action, {{"expected_revision", revision_}}); + needs_refresh_ = true; + } else if (action == "add" || action == "duplicate") + new_record(action == "duplicate"); + else if (action == "delete" && !selected_.empty()) { + modal(t("delete_prompt"), "

" + escaped(title(selected_)) + "

", t("delete"), [this] { + session_.execute( + "apply", + {{"expected_revision", revision_}, + {"changes", Json::array({{{"op", "delete"}, {"table", table()}, {"id", selected_id_}}})}}); + selected_id_.clear(); + close_modal(); + needs_refresh_ = true; + }); + } else if (action == "sort") { + descending_ = arg == sort_ ? !descending_ : false; + sort_ = arg; + needs_refresh_ = true; + } else if (action == "next" || action == "previous") { + offset_ = std::max(0, offset_ + (action == "next" ? 1 : -1) * (roster24_ ? 24 : 200)); + needs_refresh_ = true; + } else if (action == "filters") { + const auto next_nation = doc_->GetElementById("filter-nation") ? value("filter-nation") : ""; + const auto next_league = doc_->GetElementById("filter-league") ? value("filter-league") : ""; + const auto next_team = doc_->GetElementById("filter-team") ? value("filter-team") : ""; + const auto next_search = value("search"); + // Native select initialization also emits change. Rebuilding the + // controls for an unchanged value would reset focus every frame. + if (next_nation == nation_ && next_league == league_ && next_team == team_ && next_search == search_) + return; + auto old_nation = nation_; + nation_ = next_nation; + league_ = next_league; + team_ = next_team; + search_ = next_search; + if (old_nation != nation_) { + league_.clear(); + team_.clear(); + } + selected_id_.clear(); + offset_ = 0; + needs_refresh_ = true; + } else if (action == "view24") { + roster24_ = !roster24_; + offset_ = 0; + needs_refresh_ = true; + } else if (action == "remember") { + remembered_ = selected_id_; + label("status-message", t("remember_player") + ": " + title(selected_)); + needs_refresh_ = true; + } else if (action == "swap") { + session_.execute("roster.swap", + {{"first", remembered_}, {"second", selected_id_}, {"expected_revision", revision_}}); + remembered_.clear(); + needs_refresh_ = true; + } else if (action == "order-up" || action == "order-down") { + auto club = str(selected_, "team"); + if (club.empty()) + return; + auto rows = all("players"); + std::vector squad; + for (auto &row : rows) + if (str(row, "team") == club) + squad.push_back(row); + std::stable_sort(squad.begin(), squad.end(), [](auto &a, auto &b) { + return a.value("squad_order", Json(9999)) < b.value("squad_order", Json(9999)); + }); + for (int i = 0; i < int(squad.size()); ++i) + if (str(squad[size_t(i)], "id") == selected_id_) { + int to = i + (action == "order-up" ? -1 : 1); + if (to >= 0 && to < int(squad.size())) + std::swap(squad[size_t(i)], squad[size_t(to)]); + break; + } + Json ids = Json::array(); + for (auto &row : squad) + ids.push_back(row["id"]); + session_.execute("roster.order", {{"team", club}, {"players", ids}, {"expected_revision", revision_}}); + sort_ = "squad_order"; + needs_refresh_ = true; + } else if (action == "toggle-source") { + show_source_ = !show_source_; + needs_refresh_ = true; + } else if (action == "resolve") { + session_.execute("review.resolve", {{"id", selected_id_}, + {"choice", std::stoi(value("review-choice"))}, + {"expected_revision", revision_}}); + needs_refresh_ = true; + } else if (action == "image-import" || action == "image-edit") { + if (has_draft()) { + apply_fields(); + refresh(); + } + edit_image(action == "image-edit"); + } else if (action == "image-export") { + auto file = native_dialog("export"); + if (!file.empty()) + session_.execute("asset.export", {{"key", image_key(selected_)}, {"path", file}}); + } else if (action == "image-preview") + preview_image(); + else if (action == "image-reset") { + set_value("image-angle", "0"); + set_value("image-flip-x", "false"); + set_value("image-flip-y", "false"); + for (auto key : {"x", "y", "width", "height"}) + set_value("crop-" + std::string(key), std::string(key) == "x" || std::string(key) == "y" ? "0" : "1"); + preview_image(); + } else if (action == "aspect") { + auto aspect = value("image-aspect"); + if (aspect == "free") + return; + auto *canvas = el("crop-canvas"); + double ratio = std::stod(aspect) * canvas->GetOffsetHeight() / canvas->GetOffsetWidth(); + double w = std::min(1.0, ratio), h = std::min(1.0, 1 / ratio); + set_value("crop-width", number(w)); + set_value("crop-height", number(h)); + set_value("crop-x", number((1 - w) / 2)); + set_value("crop-y", number((1 - h) / 2)); + image_recipe_ = crop_recipe(); + crop_box(); + } else if (action == "validate") { + auto diagnostics = session_.execute("validate")["diagnostics"]; + std::string body; + int errors = 0; + for (auto &row : diagnostics) { + if (row["severity"] == "error") + ++errors; + if (body.size() < 100000) + body += "
" + escaped(t(str(row, "code"))) + + "" + escaped(str(row, "table") + " / " + str(row, "id")) + "
"; + } + body = "

" + std::to_string(errors) + " " + t("errors") + " · " + + std::to_string(diagnostics.size() - size_t(errors)) + " " + t("warnings") + "

" + body; + modal(t("validate"), body, t("close"), [this] { close_modal(); }, false); + } + } + void crop_drag(double x, double y, bool begin) { + auto *canvas = el("crop-canvas"); + const double nx = std::clamp((x - canvas->GetAbsoluteLeft()) / canvas->GetOffsetWidth(), 0.0, 1.0); + const double ny = std::clamp((y - canvas->GetAbsoluteTop()) / canvas->GetOffsetHeight(), 0.0, 1.0); + if (begin) { + drag_x_ = nx; + drag_y_ = ny; + dragging_ = true; + return; + } + const auto left = std::min(.995, std::min(drag_x_, nx)), top = std::min(.995, std::min(drag_y_, ny)); + image_recipe_["crop"] = {{"x", left}, + {"y", top}, + {"width", std::max(.005, std::abs(nx - drag_x_))}, + {"height", std::max(.005, std::abs(ny - drag_y_))}}; + for (auto key : {"x", "y", "width", "height"}) + set_value("crop-" + std::string(key), number(image_recipe_["crop"][key].get())); + crop_box(); + } + void screenshot() { + if (config_.screenshot.empty()) + return; + int w, h; + SDL_GL_GetDrawableSize(video_.window, &w, &h); + images::Raster raster{w, h, std::vector(size_t(w) * h * 4)}; + using ReadPixels = void (*)(int, int, int, int, unsigned, unsigned, void *); + auto read = reinterpret_cast(SDL_GL_GetProcAddress("glReadPixels")); + if (!read) + throw Error("video_failed"); + read(0, 0, w, h, 0x1908 /* RGBA */, 0x1401 /* UNSIGNED_BYTE */, raster.pixels.data()); + for (int y = 0; y < h / 2; ++y) + for (int x = 0; x < w * 4; ++x) + std::swap(raster.pixels[size_t(y) * w * 4 + x], raster.pixels[size_t(h - y - 1) * w * 4 + x]); + write_atomic(config_.screenshot, images::encode_png(raster)); + config_.screenshot.clear(); + } + + public: + EditorUi(Session &s, Options &o, McpServer &server, UiConfig config) + : session_(s), options_(o), server_(server), config_(std::move(config)), renderer_(s) { + page_ = config_.page; + Rml::SetSystemInterface(&system_); + Rml::SetFileInterface(&files_); + Rml::SetRenderInterface(&renderer_); + Rml::SetTextInputHandler(&ime_); + initialized_ = Rml::Initialise(); + if (!initialized_) + throw Error("video_failed"); + for (auto weight : {"Regular", "Bold"}) + if (!Rml::LoadFontFace(utf8(config_.assets / (std::string("LatoLatin-") + weight + ".ttf")))) + throw Error("ui_assets_missing"); + context_ = Rml::CreateContext("editor", {1440, 900}); + doc_ = context_->LoadDocument(utf8(config_.assets / "editor.rml")); + if (!doc_) + throw Error("ui_assets_missing"); + for (auto event : {"click", "change", "mousedown", "mouseup", "mousemove"}) + doc_->AddEventListener(event, this); + resize(); + refresh(); + doc_->Show(); + SDL_ShowWindow(video_.window); + } + ~EditorUi() override { + if (work_.valid()) + work_.wait(); + if (initialized_) + Rml::Shutdown(); + } + void ProcessEvent(Rml::Event &event) override { + auto *target = event.GetTargetElement(); + const auto type = event.GetType(); + if (type == "mousedown" && modal_ && doc_->GetElementById("crop-canvas")) { + for (auto *node = target; node; node = node->GetParentNode()) + if (node->GetId() == "crop-canvas") { + crop_drag(event.GetParameter("mouse_x", 0), event.GetParameter("mouse_y", 0), true); + return; + } + } + if (type == "mousemove" && dragging_) { + crop_drag(event.GetParameter("mouse_x", 0), event.GetParameter("mouse_y", 0), false); + return; + } + if (type == "mouseup") { + dragging_ = false; + return; + } + if (type == "change") { + auto id = target->GetId(); + if (id.starts_with("filter-") || id == "search") + pending_.emplace_back("filters", ""); + else if (id == "image-aspect") + pending_.emplace_back("aspect", ""); + else if (id.starts_with("image-") && id != "edit-preview") + pending_.emplace_back("image-preview", ""); + return; + } + if (type != "click") + return; + for (auto *node = target; node; node = node->GetParentNode()) + if (node->HasAttribute("data-action") && !node->HasAttribute("disabled")) { + pending_.emplace_back(node->GetAttribute("data-action", ""), + node->GetAttribute("data-value", "")); + return; + } + } + int run() { + auto last_poll = start_; + while (!closed_) { + SDL_Event event; + while (SDL_PollEvent(&event)) { + if (event.type == SDL_QUIT) { + try { + leaving([this] { closed_ = true; }); + } catch (const std::exception &e) { + error(e); + } + continue; + } + if (event.type == SDL_WINDOWEVENT && (event.window.event == SDL_WINDOWEVENT_SIZE_CHANGED || + event.window.event == SDL_WINDOWEVENT_DISPLAY_CHANGED)) + resize(); + if (event.type == SDL_KEYDOWN && !event.key.repeat) { + const bool command = event.key.keysym.mod & (KMOD_CTRL | KMOD_GUI); + if (command && event.key.keysym.sym == SDLK_s) { + pending_.emplace_back(event.key.keysym.mod & KMOD_SHIFT ? "save-as" : "save", ""); + continue; + } + auto *focused = context_->GetFocusElement(); + const bool text_input = + focused && (focused->GetTagName() == "input" || focused->GetTagName() == "textarea"); + if (command && event.key.keysym.sym == SDLK_z && !text_input) { + pending_.emplace_back(event.key.keysym.mod & KMOD_SHIFT ? "redo" : "undo", ""); + continue; + } + if (command && event.key.keysym.sym == SDLK_o) { + pending_.emplace_back("open", ""); + continue; + } + if (event.key.keysym.sym == SDLK_ESCAPE && modal_) { + close_modal(); + continue; + } + } + if (event.type == SDL_KEYDOWN || event.type == SDL_KEYUP) { + int mods = 0; + auto state = event.key.keysym.mod; + if (state & (KMOD_CTRL | KMOD_GUI)) + mods |= Rml::Input::KM_CTRL; + if (state & KMOD_SHIFT) + mods |= Rml::Input::KM_SHIFT; + if (state & KMOD_ALT) + mods |= Rml::Input::KM_ALT; + if (event.type == SDL_KEYDOWN) + context_->ProcessKeyDown(RmlSDL::ConvertKey(event.key.keysym.sym), mods); + else + context_->ProcessKeyUp(RmlSDL::ConvertKey(event.key.keysym.sym), mods); + } else { + if (event.type == SDL_TEXTEDITING) + ime_.HandleEdit(event.edit); + int w, h, pw, ph; + SDL_GetWindowSize(video_.window, &w, &h); + SDL_GL_GetDrawableSize(video_.window, &pw, &ph); + if (w && h) { + if (event.type == SDL_MOUSEMOTION) { + event.motion.x = int(double(event.motion.x) * pw / w); + event.motion.y = int(double(event.motion.y) * ph / h); + } + if (event.type == SDL_MOUSEBUTTONDOWN || event.type == SDL_MOUSEBUTTONUP) { + event.button.x = int(double(event.button.x) * pw / w); + event.button.y = int(double(event.button.y) * ph / h); + context_->ProcessMouseMove(event.button.x, event.button.y, RmlSDL::GetKeyModifierState()); + } + } + RmlSDL::InputEventHandler(context_, video_.window, event); + } + } + while (!pending_.empty()) { + auto [action, arg] = pending_.front(); + pending_.pop_front(); + try { + dispatch(action, arg); + } catch (const std::exception &e) { + error(e); + } + } + if (busy_ && work_.wait_for(std::chrono::seconds(0)) == std::future_status::ready) { + busy_ = false; + try { + auto result = work_.get(); + if (completed_) + completed_(result); + needs_refresh_ = true; + } catch (const std::exception &e) { + error(e); + } + completed_ = {}; + } + const auto now = std::chrono::steady_clock::now(); + if (!busy_ && now - last_poll > std::chrono::milliseconds(400)) { + auto info = session_.execute("info"); + if (info.value("revision", uint64_t(0)) != revision_) { + if (!has_draft() && !modal_) + needs_refresh_ = true; + else + label("status-message", t("stale_revision")); + } + last_poll = now; + } + if (needs_refresh_ && !busy_) { + try { + refresh(); + } catch (const std::exception &e) { + needs_refresh_ = false; + error(e); + } + } + context_->Update(); + renderer_.BeginFrame(); + renderer_.Clear(); + context_->Render(); + renderer_.EndFrame(); + auto elapsed = std::chrono::duration_cast(now - start_).count(); + if (!busy_ && elapsed > 1200 && !config_.screenshot.empty()) + screenshot(); + SDL_GL_SwapWindow(video_.window); + SDL_Delay(10); + if (config_.quit_after_ms > 0 && elapsed >= config_.quit_after_ms) + closed_ = true; + } + return 0; + } +}; +} // namespace +int run_ui(Session &session, Options &options, McpServer &server, const UiConfig &config) { + EditorUi ui(session, options, server, config); + return ui.run(); +} +} // namespace bmh::editor diff --git a/src/editor/ui.hpp b/src/editor/ui.hpp new file mode 100644 index 0000000..b2f9d1d --- /dev/null +++ b/src/editor/ui.hpp @@ -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 diff --git a/src/editor/world.cpp b/src/editor/world.cpp new file mode 100644 index 0000000..16e2c64 --- /dev/null +++ b/src/editor/world.cpp @@ -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 +#include +#include +#include + +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(); + 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 &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 &World::tables() { + static const std::vector 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(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(); + 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(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 &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 clubs; + for (const auto &club : rows("clubs")) + clubs[str(club, "id")] = &club; + std::vector 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(0, args.value("offset", int64_t(0))); + const auto limit = std::clamp(args.value("limit", int64_t(200)), 1, 200); + Json result = Json::array(); + for (size_t i = size_t(std::min(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> World::references(const std::string &id) const { + std::vector> 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 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 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() < field.value("min", std::numeric_limits::min()) || + it->get() > field.value("max", std::numeric_limits::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 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{{"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()) && ids.at(key.get()) != 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 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 = ""; + w.store->set(file, std::make_shared(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 diff --git a/src/editor/world.hpp b/src/editor/world.hpp new file mode 100644 index 0000000..34858a9 --- /dev/null +++ b/src/editor/world.hpp @@ -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 store = std::make_shared(); + 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 &); + 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> 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 &tables(); + + private: + std::map docs_; + std::map original_; + std::set dirty_; + void load(); + void editor_profile(); +}; +} // namespace bmh::editor diff --git a/tests/editor_core_tests.cpp b/tests/editor_core_tests.cpp new file mode 100644 index 0000000..2e8d154 --- /dev/null +++ b/tests/editor_core_tests.cpp @@ -0,0 +1,221 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "editor/images.hpp" +#include "editor/mcp.hpp" +#include "editor/session.hpp" +#include +#include +#include + +using namespace bmh::editor; +namespace { +int checks = 0; +void check(bool result, const char *message) { + ++checks; + if (!result) + throw std::runtime_error(message); +} +template 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"); + }); + auto imported = s.execute("asset.import", + {{"file", utf8(root / "input.png")}, + {"key", "asset:test"}, + {"target", {{"table", "players"}, {"id", "player:demo-0"}, {"field", "photo"}}}}); + 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("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()).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(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"); + 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; + } +} diff --git a/tests/editor_gui_smoke.py b/tests/editor_gui_smoke.py new file mode 100644 index 0000000..cd58b21 --- /dev/null +++ b/tests/editor_gui_smoke.py @@ -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() diff --git a/tools/package/make_editor_package.py b/tools/package/make_editor_package.py new file mode 100644 index 0000000..047c680 --- /dev/null +++ b/tools/package/make_editor_package.py @@ -0,0 +1,122 @@ +#!/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' + executable = build / exe + if not executable.exists(): + executable = build / 'Release' / exe + shutil.copy2(executable, stage / exe) + shutil.copytree(build / 'assets/editor', stage / 'assets/editor') + 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'): + # Only runtime DLLs produced beside this editor are eligible. + for dll in executable.parent.glob('*.dll'): + shutil.copy2(dll, stage / dll.name) + (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() diff --git a/tools/public_release/check_public_tree.py b/tools/public_release/check_public_tree.py index fcc0f20..a6ad244 100644 --- a/tools/public_release/check_public_tree.py +++ b/tools/public_release/check_public_tree.py @@ -41,9 +41,16 @@ PRIVATE_DOCUMENTS = { } SOURCE_SUFFIXES = {".cpp", ".hpp", ".h", ".c", ".inc"} SKIP_DIRECTORIES = {".git", "__pycache__", ".cache", "_deps", "node_modules"} -# Exact independently generated launcher artwork, not imported game material. +# 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": {"aa53e9cdd9ac8f6bf18b514862ac704ff9003bd1b62466cad2ebc329b09703dc"}, + "docs/qa/editor-poc/gui-search.png": {"48dc00d03c01d5bbec35683ff65672c12af4be6aecc8a84e5fece243c56643f4"}, + "docs/qa/editor-poc/image-editor-midnight-de.png": {"eb01bd8fd8eaadfbc8e2b3f634bcdafbbb084dc4592d849e102a6f8c70ab0ad4"}, + "docs/qa/editor-poc/options-midnight-de.png": {"7075957db2d5f5a166bb71adb97d8208cb051a72b555202c212fae4f7e5c402c"}, + "docs/qa/editor-poc/players-silver-en.png": {"d965a904663f3a30e5410f5d33539f6247737293625039fb9e3028337bbc088c"}, + "docs/qa/editor-poc/roster-matchday-de.png": {"937829bb31b7452aa15d4a54cd03ad5de6a42d630b83cce279f22da09dfe180b"}, "assets/launcher/stadium.tga": { "08f82783a357d5b0722f3737de54844150bc14d98036845f1aaee3211608e1c8", "fb8e5f1f86afe60de87b70a2f533690d1ef470241fa24ee4384ff000149edaab",