Add native OBW editor POC with shared MCP session (by Codex)

This commit is contained in:
Codex committed 2026-10-22 21:41:10 +02:00
1 parent 6e5fa72ed5
commit bde8b10762
48 files changed
+5614 -1

No files matched your search

+81
View File
@@ -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)
+326
View File
@@ -0,0 +1,326 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "editor/archive.hpp"
#include "content/digest.hpp"
#include <algorithm>
#include <chrono>
#include <cwctype>
#include <fstream>
#include <miniz.h>
#include <mutex>
#include <random>
#ifdef _WIN32
#define NOMINMAX
#include <windows.h>
#endif
namespace bmh::editor {
namespace {
constexpr uint64_t max_entry = 64ull * 1024 * 1024;
constexpr uint64_t max_total = 2ull * 1024 * 1024 * 1024;
constexpr size_t max_entries = 100000;
void publish(const fs::path &temporary, const fs::path &destination) {
#ifdef _WIN32
if (!MoveFileExW(temporary.c_str(), destination.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH))
throw Error("save_failed", {{"path", utf8(destination)}, {"system", GetLastError()}});
#else
std::error_code ec;
fs::rename(temporary, destination, ec);
if (ec)
throw Error("save_failed", {{"path", utf8(destination)}, {"system", ec.message()}});
#endif
}
struct Remove {
fs::path target;
~Remove() {
if (!target.empty()) {
std::error_code ec;
fs::remove_all(target, ec);
}
}
};
} // namespace
std::string utf8(const fs::path &value) {
const auto data = value.generic_u8string();
return {data.begin(), data.end()};
}
fs::path path(std::string_view value) { return fs::path(std::u8string(value.begin(), value.end())); }
bool safe_name(std::string_view value) {
if (value.empty() || value.front() == '/' || value.find('\\') != value.npos || value.find(':') != value.npos ||
value.find('\0') != value.npos || value.back() == '/')
return false;
const auto relative = path(value);
for (const auto &part : relative)
if (part == "." || part == ".." || part.empty())
return false;
return !relative.is_absolute();
}
std::string new_id(const std::string &prefix) {
static std::mutex lock;
static std::mt19937_64 random(std::random_device{}());
std::lock_guard guard(lock);
static const char *digits = "0123456789abcdef";
std::string result = prefix;
for (int n = 0; n < 2; ++n) {
auto number = random();
for (int i = 0; i < 16; ++i) {
result += digits[number & 15];
number >>= 4;
}
}
return result;
}
std::string folded(std::string value) {
// UTF-8 byte equality is retained; the small UI search additionally handles
// ASCII case without changing authored spelling or source identity.
for (char &c : value)
if (c >= 'A' && c <= 'Z')
c = char(c + ('a' - 'A'));
return value;
}
std::string read_file(const fs::path &file, uint64_t maximum) {
std::ifstream source(file, std::ios::binary);
if (!source)
throw Error("open_failed", {{"path", utf8(file)}});
source.seekg(0, std::ios::end);
auto size = source.tellg();
if (size < 0 || uint64_t(size) > maximum)
throw Error("size_limit", {{"path", utf8(file)}});
source.seekg(0);
std::string bytes(size_t(size), '\0');
source.read(bytes.data(), std::streamsize(bytes.size()));
if (!source && !bytes.empty())
throw Error("open_failed", {{"path", utf8(file)}});
return bytes;
}
void write_atomic(const fs::path &file, std::string_view data, bool overwrite) {
if (!overwrite && fs::exists(file))
throw Error("destination_exists");
if (fs::is_symlink(fs::symlink_status(file)))
throw Error("unsafe_path");
const auto parent = file.has_parent_path() ? file.parent_path() : fs::path(".");
if (!fs::is_directory(parent))
throw Error("output_parent_missing");
auto temporary = parent / new_id(".openbmh-editor-");
Remove cleanup{temporary};
{
std::ofstream output(temporary, std::ios::binary);
output.write(data.data(), std::streamsize(data.size()));
output.close();
if (!output)
throw Error("save_failed");
}
publish(temporary, file);
}
struct ArchiveStore::Impl {
fs::path cache;
fs::path root;
mutable std::ifstream input;
mutable mz_zip_archive zip{};
struct Item {
uint64_t size;
mz_uint index;
fs::path file;
};
std::map<std::string, Item> entries;
std::map<std::string, std::shared_ptr<const std::string>> changed;
mutable std::mutex mutex;
bool zip_open = false;
static size_t read_at(void *opaque, mz_uint64 offset, void *data, size_t count) {
auto &in = static_cast<Impl *>(opaque)->input;
in.clear();
in.seekg(std::streamoff(offset));
in.read(static_cast<char *>(data), std::streamsize(count));
return size_t(in.gcount());
}
~Impl() {
if (zip_open)
mz_zip_reader_end(&zip);
input.close();
if (!cache.empty()) {
std::error_code ec;
fs::remove_all(cache, ec);
}
}
};
ArchiveStore::ArchiveStore() : impl_(std::make_unique<Impl>()) {}
ArchiveStore::~ArchiveStore() = default;
std::shared_ptr<ArchiveStore> ArchiveStore::open(const fs::path &source) {
auto result = std::make_shared<ArchiveStore>();
auto &s = *result->impl_;
uint64_t total = 0;
auto add = [&](std::string name, Impl::Item item) {
if (!safe_name(name) || item.size > max_entry || total + item.size > max_total ||
s.entries.size() >= max_entries)
throw Error("archive_limit", {{"entry", name}});
if (!s.entries.emplace(name, std::move(item)).second)
throw Error("duplicate_entry", {{"entry", name}});
total += item.size;
};
if (fs::is_symlink(fs::symlink_status(source)))
throw Error("unsafe_path");
if (fs::is_directory(source)) {
const auto original = fs::canonical(source);
s.cache = fs::temp_directory_path() / new_id("openbmh-editor-");
s.root = s.cache / "world";
fs::create_directories(s.root);
for (const auto &entry : fs::recursive_directory_iterator(original)) {
if (entry.is_symlink())
throw Error("unsafe_path");
if (entry.is_regular_file()) {
const auto relative = entry.path().lexically_relative(original);
const auto snapshot = s.root / relative;
add(utf8(relative), {entry.file_size(), 0, snapshot});
fs::create_directories(snapshot.parent_path());
fs::copy_file(entry.path(), snapshot);
}
}
} else {
if (!fs::is_regular_file(source) || fs::file_size(source) > max_total)
throw Error("archive_limit");
s.cache = fs::temp_directory_path() / new_id("openbmh-editor-");
fs::create_directory(s.cache);
const auto snapshot = s.cache / "source.obw";
fs::copy_file(source, snapshot);
s.input.open(snapshot, std::ios::binary);
s.zip.m_pRead = Impl::read_at;
s.zip.m_pIO_opaque = &s;
if (!mz_zip_reader_init(&s.zip, fs::file_size(snapshot), 0))
throw Error("invalid_archive");
s.zip_open = true;
auto count = mz_zip_reader_get_num_files(&s.zip);
if (count > max_entries)
throw Error("archive_limit");
for (mz_uint index = 0; index < count; ++index) {
mz_zip_archive_file_stat stat{};
if (!mz_zip_reader_file_stat(&s.zip, index, &stat))
throw Error("invalid_archive");
if (stat.m_is_directory)
continue;
if (((stat.m_external_attr >> 16) & 0170000) == 0120000)
throw Error("unsafe_path");
if (stat.m_is_encrypted || !stat.m_is_supported)
throw Error("unsupported_archive");
add(stat.m_filename, {stat.m_uncomp_size, index, {}});
}
}
if (!s.entries.contains("manifest.json"))
throw Error("missing_manifest");
return result;
}
bool ArchiveStore::contains(const std::string &name) const {
return impl_->changed.contains(name) || impl_->entries.contains(name);
}
std::vector<std::string> ArchiveStore::names() const {
std::set<std::string> all;
for (const auto &[key, _] : impl_->entries)
all.insert(key);
for (const auto &[key, _] : impl_->changed)
all.insert(key);
return {all.begin(), all.end()};
}
uint64_t ArchiveStore::size(const std::string &name) const {
if (auto i = impl_->changed.find(name); i != impl_->changed.end())
return i->second->size();
if (auto i = impl_->entries.find(name); i != impl_->entries.end())
return i->second.size;
throw Error("missing_asset", {{"path", name}});
}
std::string ArchiveStore::read(const std::string &name) const {
if (auto i = impl_->changed.find(name); i != impl_->changed.end())
return *i->second;
const auto entry = impl_->entries.find(name);
if (entry == impl_->entries.end())
throw Error("missing_asset", {{"path", name}});
if (!entry->second.file.empty()) {
if (fs::is_symlink(fs::symlink_status(entry->second.file)))
throw Error("unsafe_path");
return read_file(entry->second.file, max_entry);
}
std::lock_guard guard(impl_->mutex);
std::string bytes(size_t(entry->second.size), '\0');
if (!mz_zip_reader_extract_to_mem(&impl_->zip, entry->second.index, bytes.data(), bytes.size(), 0))
throw Error("invalid_archive", {{"entry", name}});
return bytes;
}
void ArchiveStore::set(const std::string &name, std::shared_ptr<const std::string> bytes) {
if (!safe_name(name) || !bytes || bytes->size() > max_entry)
throw Error("unsafe_asset");
impl_->changed[name] = std::move(bytes);
}
std::shared_ptr<const std::string> ArchiveStore::overlay(const std::string &name) const {
auto i = impl_->changed.find(name);
return i == impl_->changed.end() ? nullptr : i->second;
}
void ArchiveStore::restore(const std::string &name, std::shared_ptr<const std::string> value) {
if (value)
set(name, std::move(value));
else
impl_->changed.erase(name);
}
void ArchiveStore::save(const fs::path &target, const std::map<std::string, std::string> &docs,
const std::set<std::string> &excluded) const {
if (target.extension() != ".obw")
throw Error("obw_only");
if (fs::is_symlink(fs::symlink_status(target)))
throw Error("unsafe_path");
auto parent = target.has_parent_path() ? target.parent_path() : fs::path(".");
if (!fs::is_directory(parent))
throw Error("output_parent_missing");
auto temporary = parent / new_id(".openbmh-editor-");
Remove cleanup{temporary};
std::ofstream output(temporary, std::ios::binary);
if (!output)
throw Error("save_failed");
mz_zip_archive writer{};
writer.m_pIO_opaque = &output;
writer.m_pWrite = [](void *opaque, mz_uint64 position, const void *data, size_t count) -> size_t {
auto &stream = *static_cast<std::ofstream *>(opaque);
stream.seekp(std::streamoff(position));
stream.write(static_cast<const char *>(data), std::streamsize(count));
return stream ? count : 0;
};
if (!mz_zip_writer_init_v2(&writer, 0, MZ_ZIP_FLAG_WRITE_ZIP64))
throw Error("save_failed");
struct Close {
mz_zip_archive *p;
~Close() { mz_zip_writer_end(p); }
} closer{&writer};
std::set<std::string> all;
for (auto &name : names())
all.insert(name);
for (auto &[name, _] : docs)
all.insert(name);
if (all.size() > max_entries)
throw Error("archive_limit");
uint64_t total = 0;
for (const auto &name : all) {
if (excluded.contains(name))
continue;
if (!safe_name(name))
throw Error("unsafe_path");
auto replacement = docs.find(name);
const auto bytes_size = replacement != docs.end() ? replacement->second.size() : size(name);
if (bytes_size > max_entry || (total += bytes_size) > max_total)
throw Error("archive_limit");
auto existing = impl_->entries.find(name);
if (replacement == docs.end() && !impl_->changed.contains(name) && impl_->zip_open &&
existing != impl_->entries.end()) {
std::lock_guard guard(impl_->mutex);
if (!mz_zip_writer_add_from_zip_reader(&writer, &impl_->zip, existing->second.index))
throw Error("save_failed");
} else {
auto bytes = replacement != docs.end() ? replacement->second : read(name);
const auto level = name.ends_with(".json") ? MZ_BEST_SPEED : MZ_NO_COMPRESSION;
if (!mz_zip_writer_add_mem(&writer, name.c_str(), bytes.data(), bytes.size(), level))
throw Error("save_failed");
}
}
if (!mz_zip_writer_finalize_archive(&writer))
throw Error("save_failed");
output.close();
if (!output)
throw Error("save_failed");
publish(temporary, target);
}
} // namespace bmh::editor
+28
View File
@@ -0,0 +1,28 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "editor/types.hpp"
#include <functional>
namespace bmh::editor {
// Asset bytes are read on demand. A private source snapshot permits replacing
// the user's own editor file atomically on Windows as well as POSIX systems.
class ArchiveStore {
public:
ArchiveStore();
static std::shared_ptr<ArchiveStore> open(const fs::path &);
~ArchiveStore();
bool contains(const std::string &) const;
std::vector<std::string> names() const;
uint64_t size(const std::string &) const;
std::string read(const std::string &) const;
void set(const std::string &, std::shared_ptr<const std::string>);
std::shared_ptr<const std::string> overlay(const std::string &) const;
void restore(const std::string &, std::shared_ptr<const std::string>);
void save(const fs::path &, const std::map<std::string, std::string> &documents,
const std::set<std::string> &excluded = {}) const;
private:
struct Impl;
std::unique_ptr<Impl> impl_;
};
} // namespace bmh::editor
+316
View File
@@ -0,0 +1,316 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "editor/images.hpp"
#include <SDL.h>
#include <SDL_image.h>
#include <algorithm>
#include <array>
#include <cmath>
#include <cstring>
#include <functional>
#include <limits>
#include <lunasvg.h>
#include <miniz.h>
#include <pugixml.hpp>
#include <sstream>
namespace bmh::editor::images {
namespace {
constexpr uint64_t maximum_pixels = 32ull * 1024 * 1024;
void bounds(int w, int h) {
if (w <= 0 || h <= 0 || w > 8192 || h > 8192 || uint64_t(w) * uint64_t(h) > maximum_pixels)
throw Error("image_dimensions");
}
struct Geometry {
double angle = 0, x = 0, y = 0, width = 1, height = 1;
bool flip_x = false, flip_y = false;
explicit Geometry(const Json &input) {
const Json value = input.is_null() ? Json::object() : input;
if (!value.is_object())
throw Error("invalid_transform");
angle = value.value("angle", 0.0);
flip_x = value.value("flip_x", false);
flip_y = value.value("flip_y", false);
if (value.contains("crop")) {
const auto &crop = value["crop"];
x = crop.value("x", 0.0);
y = crop.value("y", 0.0);
width = crop.value("width", 1.0);
height = crop.value("height", 1.0);
}
if (!std::isfinite(angle) || !std::isfinite(x) || !std::isfinite(y) || !std::isfinite(width) ||
!std::isfinite(height) || std::abs(angle) > 360 || x < 0 || y < 0 || width <= 0 || height <= 0 ||
x + width > 1.000001 || y + height > 1.000001)
throw Error("invalid_transform");
}
Json json() const {
return {{"angle", angle},
{"flip_x", flip_x},
{"flip_y", flip_y},
{"crop", {{"x", x}, {"y", y}, {"width", width}, {"height", height}}}};
}
};
std::pair<double, double> canvas(double w, double h, double angle) {
const auto rad = angle * std::acos(-1.0) / 180.0;
auto c = std::abs(std::cos(rad)), s = std::abs(std::sin(rad));
return {std::ceil(w * c + h * s - 1e-9), std::ceil(w * s + h * c - 1e-9)};
}
void validate_svg(pugi::xml_node node) {
for (auto attr : node.attributes()) {
const std::string key = attr.name(), value = attr.value();
const auto lower = folded(value);
if ((key == "href" || key == "xlink:href") && std::string(node.name()) != "a" && !value.empty() &&
value.front() != '#' && !value.starts_with("data:image/"))
throw Error("external_svg_resource");
if (lower.find("url(") != lower.npos && lower.find("url(#") == lower.npos &&
lower.find("url('#") == lower.npos && lower.find("url(\"#") == lower.npos)
throw Error("external_svg_resource");
}
if (std::string(node.name()) == "style") {
const std::string css = folded(node.text().as_string());
if (css.find("@import") != css.npos || css.find("http:") != css.npos || css.find("https:") != css.npos ||
css.find("file:") != css.npos)
throw Error("external_svg_resource");
}
for (auto child : node.children())
validate_svg(child);
}
std::unique_ptr<lunasvg::Document> svg_document(std::string_view bytes) {
pugi::xml_document xml;
if (!xml.load_buffer(bytes.data(), bytes.size()))
throw Error("invalid_image");
validate_svg(xml.document_element());
auto doc = lunasvg::Document::loadFromData(bytes.data(), bytes.size());
if (!doc || doc->width() <= 0 || doc->height() <= 0 || !std::isfinite(doc->width()) ||
!std::isfinite(doc->height()))
throw Error("invalid_image");
return doc;
}
std::string transform_svg(std::string_view bytes, const Geometry &g, int &width, int &height) {
auto source = svg_document(bytes);
const double w = source->width(), h = source->height();
const auto [cw, ch] = canvas(w, h, g.angle);
const auto ow = std::max(1.0, cw * g.width), oh = std::max(1.0, ch * g.height);
if (ow > 1000000 || oh > 1000000)
throw Error("image_dimensions");
width = int(std::round(ow));
height = int(std::round(oh));
pugi::xml_document original, output;
if (!original.load_buffer(bytes.data(), bytes.size()))
throw Error("invalid_image");
auto root = output.append_child("svg");
root.append_attribute("xmlns") = "http://www.w3.org/2000/svg";
root.append_attribute("xmlns:xlink") = "http://www.w3.org/1999/xlink";
root.append_attribute("width") = ow;
root.append_attribute("height") = oh;
const auto view = "0 0 " + std::to_string(ow) + ' ' + std::to_string(oh);
root.append_attribute("viewBox") = view.c_str();
auto group = root.append_child("g");
std::ostringstream matrix;
matrix.imbue(std::locale::classic());
matrix << "translate(" << -g.x * cw << ' ' << -g.y * ch << ") translate(" << cw / 2 << ' ' << ch / 2 << ") rotate("
<< g.angle << ") scale(" << (g.flip_x ? -1 : 1) << ' ' << (g.flip_y ? -1 : 1) << ") translate(" << -w / 2
<< ' ' << -h / 2 << ')';
group.append_attribute("transform") = matrix.str().c_str();
auto child = group.append_copy(original.document_element());
if (!child.attribute("width"))
child.append_attribute("width");
if (!child.attribute("height"))
child.append_attribute("height");
child.attribute("width") = w;
child.attribute("height") = h;
std::ostringstream serialized;
output.save(serialized, "", pugi::format_raw, pugi::encoding_utf8);
return serialized.str();
}
double kernel(double x) {
x = std::abs(x);
if (x <= 1)
return (1.5 * x - 2.5) * x * x + 1;
if (x < 2)
return ((-0.5 * x + 2.5) * x - 4) * x + 2;
return 0;
}
void sample(const Raster &source, double x, double y, uint8_t *destination) {
const int ix = int(std::floor(x)), iy = int(std::floor(y));
double alpha = 0;
std::array<double, 3> color{};
for (int j = iy - 1; j <= iy + 2; ++j)
for (int i = ix - 1; i <= ix + 2; ++i) {
if (i < 0 || j < 0 || i >= source.width || j >= source.height)
continue;
const auto *pixel = source.pixels.data() + (size_t(j) * source.width + i) * 4;
const double weight = kernel(x - i) * kernel(y - j);
const double a = pixel[3] / 255.0;
alpha += weight * a;
for (int c = 0; c < 3; ++c)
color[c] += pixel[c] * a * weight;
}
for (int c = 0; c < 3; ++c)
destination[c] = alpha > 1e-8 ? uint8_t(std::clamp(std::round(color[c] / alpha), 0.0, 255.0)) : 0;
destination[3] = uint8_t(std::clamp(std::round(alpha * 255), 0.0, 255.0));
}
Raster rotate_crop(const Raster &source, const Geometry &g, int maximum = 8192) {
const auto [cw, ch] = canvas(source.width, source.height, g.angle);
double ow = std::max(1.0, std::round(cw * g.width)), oh = std::max(1.0, std::round(ch * g.height));
const double factor = std::min(1.0, maximum / std::max(ow, oh));
Raster result{std::max(1, int(std::round(ow * factor))), std::max(1, int(std::round(oh * factor))), {}};
bounds(result.width, result.height);
result.pixels.resize(size_t(result.width) * result.height * 4);
const auto rad = g.angle * std::acos(-1.0) / 180.0;
const auto cosine = std::cos(rad), sine = std::sin(rad);
for (int y = 0; y < result.height; ++y)
for (int x = 0; x < result.width; ++x) {
double dx = (x + .5) * ow / result.width + g.x * cw - cw / 2;
double dy = (y + .5) * oh / result.height + g.y * ch - ch / 2;
double sx = cosine * dx + sine * dy, sy = -sine * dx + cosine * dy;
if (g.flip_x)
sx = -sx;
if (g.flip_y)
sy = -sy;
sample(source, sx + source.width / 2.0 - .5, sy + source.height / 2.0 - .5,
result.pixels.data() + (size_t(y) * result.width + x) * 4);
}
return result;
}
void be32(std::string &data, uint32_t n) {
for (int shift = 24; shift >= 0; shift -= 8)
data += char(n >> shift);
}
void chunk(std::string &out, const char *type, const std::string &data) {
be32(out, uint32_t(data.size()));
const auto start = out.size();
out.append(type, 4);
out += data;
be32(out, uint32_t(mz_crc32(0, reinterpret_cast<const unsigned char *>(out.data() + start), data.size() + 4)));
}
} // namespace
Raster decode(std::string_view bytes, const std::string &extension, int vector_size) {
if (bytes.size() > 64ull * 1024 * 1024)
throw Error("size_limit");
if (folded(extension) == ".svg" || extension == "svg") {
auto doc = svg_document(bytes);
const double scale = vector_size / std::max(doc->width(), doc->height());
auto bitmap = doc->renderToBitmap(std::max(1, int(std::round(doc->width() * scale))),
std::max(1, int(std::round(doc->height() * scale))));
if (bitmap.isNull())
throw Error("invalid_image");
bitmap.convertToRGBA();
Raster result{bitmap.width(), bitmap.height(), {}};
bounds(result.width, result.height);
result.pixels.resize(size_t(result.width) * result.height * 4);
for (int y = 0; y < result.height; ++y)
std::memcpy(result.pixels.data() + size_t(y) * result.width * 4,
bitmap.data() + size_t(y) * bitmap.stride(), size_t(result.width) * 4);
return result;
}
auto *stream = SDL_RWFromConstMem(bytes.data(), int(bytes.size()));
if (!stream)
throw Error("invalid_image");
SDL_Surface *loaded = IMG_Load_RW(stream, 1);
if (!loaded)
throw Error("invalid_image", {{"detail", IMG_GetError()}});
struct Free {
SDL_Surface *p;
~Free() { SDL_FreeSurface(p); }
} source{loaded};
bounds(loaded->w, loaded->h);
SDL_Surface *converted = SDL_ConvertSurfaceFormat(loaded, SDL_PIXELFORMAT_RGBA32, 0);
if (!converted)
throw Error("invalid_image");
Free rgba{converted};
Raster result{converted->w, converted->h, {}};
result.pixels.resize(size_t(result.width) * result.height * 4);
for (int y = 0; y < result.height; ++y)
std::memcpy(result.pixels.data() + size_t(y) * result.width * 4,
static_cast<const uint8_t *>(converted->pixels) + size_t(y) * converted->pitch,
size_t(result.width) * 4);
return result;
}
std::string encode_png(const Raster &image) {
bounds(image.width, image.height);
if (image.pixels.size() != size_t(image.width) * image.height * 4)
throw Error("invalid_image");
std::string result("\x89PNG\r\n\x1a\n", 8), header;
be32(header, uint32_t(image.width));
be32(header, uint32_t(image.height));
header.append("\x08\x06\0\0\0", 5);
chunk(result, "IHDR", header);
std::string scanlines;
scanlines.reserve((size_t(image.width) * 4 + 1) * image.height);
for (int y = 0; y < image.height; ++y) {
scanlines += '\0';
scanlines.append(reinterpret_cast<const char *>(image.pixels.data() + size_t(y) * image.width * 4),
size_t(image.width) * 4);
}
mz_ulong size = mz_compressBound(scanlines.size());
std::string packed(size, '\0');
if (mz_compress2(reinterpret_cast<unsigned char *>(packed.data()), &size,
reinterpret_cast<const unsigned char *>(scanlines.data()), scanlines.size(),
MZ_BEST_SPEED) != MZ_OK)
throw Error("image_encode_failed");
packed.resize(size);
chunk(result, "IDAT", packed);
chunk(result, "IEND", {});
return result;
}
Result transform(std::string_view original, const std::string &extension, const Json &recipe) {
Geometry g(recipe);
Result result;
result.recipe = g.json();
if (g.angle == 0 && !g.flip_x && !g.flip_y && g.x == 0 && g.y == 0 && g.width == 1 && g.height == 1) {
// Import without an edit preserves the exact source pixels and codec.
auto source = decode(original, extension);
result.bytes = original;
result.extension = extension.starts_with('.') ? extension : '.' + extension;
if (result.extension == ".svg") {
auto svg = svg_document(original);
result.width = int(std::round(svg->width()));
result.height = int(std::round(svg->height()));
} else {
result.width = source.width;
result.height = source.height;
}
return result;
}
if (folded(extension) == ".svg" || extension == "svg") {
result.bytes = transform_svg(original, g, result.width, result.height);
result.extension = ".svg";
} else {
auto source = decode(original, extension);
auto output = rotate_crop(source, g);
result.width = output.width;
result.height = output.height;
result.extension = ".png";
result.bytes = encode_png(output);
}
return result;
}
Raster preview(std::string_view bytes, const std::string &extension, const Json &recipe, int maximum) {
Geometry g(recipe);
if (folded(extension) == ".svg" || extension == "svg") {
int w, h;
auto svg = transform_svg(bytes, g, w, h);
return decode(svg, ".svg", maximum);
}
return rotate_crop(decode(bytes, extension), g, maximum);
}
std::string base64(std::string_view bytes) {
static const char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
std::string result;
for (size_t i = 0; i < bytes.size(); i += 3) {
uint32_t value = uint8_t(bytes[i]) << 16;
if (i + 1 < bytes.size())
value |= uint8_t(bytes[i + 1]) << 8;
if (i + 2 < bytes.size())
value |= uint8_t(bytes[i + 2]);
result += alphabet[(value >> 18) & 63];
result += alphabet[(value >> 12) & 63];
result += i + 1 < bytes.size() ? alphabet[(value >> 6) & 63] : '=';
result += i + 2 < bytes.size() ? alphabet[value & 63] : '=';
}
return result;
}
std::string silhouette() {
return R"(<svg xmlns="http://www.w3.org/2000/svg" width="180" height="180" viewBox="0 0 180 180"><rect width="180" height="180" rx="24" fill="#293c4c"/><circle cx="90" cy="62" r="30" fill="#91acba"/><path d="M26 180v-27c0-35 25-50 64-50s64 15 64 50v27" fill="#91acba"/></svg>)";
}
} // namespace bmh::editor::images
+22
View File
@@ -0,0 +1,22 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "editor/types.hpp"
#include <cstdint>
namespace bmh::editor::images {
struct Raster {
int width = 0, height = 0;
std::vector<uint8_t> pixels;
};
struct Result {
std::string bytes, extension;
int width = 0, height = 0;
Json recipe;
};
Raster decode(std::string_view bytes, const std::string &extension, int vector_size = 1024);
std::string encode_png(const Raster &);
Result transform(std::string_view original, const std::string &extension, const Json &recipe);
Raster preview(std::string_view original, const std::string &extension, const Json &recipe, int maximum = 1024);
std::string base64(std::string_view);
std::string silhouette();
} // namespace bmh::editor::images
+157
View File
@@ -0,0 +1,157 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "editor/ui.hpp"
#include <SDL.h>
#include <atomic>
#include <chrono>
#include <csignal>
#include <iostream>
#include <thread>
namespace {
std::atomic<bool> stopped{false};
void stop(int) { stopped = true; }
} // namespace
int main(int argc, char **argv) {
using namespace bmh::editor;
std::string language = "de";
try {
bool headless = false, serve = false, stdio = false, demo = false, blank = false, validate = false,
print = false;
fs::path input, output, settings, script;
UiConfig ui;
int port = -1;
for (int i = 1; i < argc; ++i) {
std::string arg = argv[i];
auto next = [&]() -> std::string {
if (++i >= argc)
throw Error("invalid_change", {{"argument", arg}});
return argv[i];
};
if (arg == "--headless")
headless = true;
else if (arg == "--serve")
serve = headless = true;
else if (arg == "--stdio-mcp")
stdio = headless = true;
else if (arg == "--open")
input = path(next());
else if (arg == "--output")
output = path(next());
else if (arg == "--settings")
settings = path(next());
else if (arg == "--commands")
script = path(next());
else if (arg == "--mcp-port")
port = std::stoi(next());
else if (arg == "--demo")
demo = true;
else if (arg == "--new")
blank = true;
else if (arg == "--validate")
validate = true;
else if (arg == "--print-mcp-config")
print = true;
else if (arg == "--assets")
ui.assets = path(next());
else if (arg == "--screenshot")
ui.screenshot = path(next());
else if (arg == "--page")
ui.page = next();
else if (arg == "--quit-after-ms")
ui.quit_after_ms = std::stoi(next());
else if (arg == "--help") {
std::cout << "OpenBMHEditor [--open world.obw|installation] [--demo|--new]\n"
" [--settings file] [--assets directory] [--page "
"clubs|players|...]\n"
" [--headless --validate] [--output world.obw] [--commands "
"script.json]\n"
" [--serve --mcp-port 8765] [--stdio-mcp] "
"[--print-mcp-config]\n";
return 0;
} else if (!arg.starts_with('-') && input.empty())
input = path(arg);
else
throw Error("invalid_change", {{"argument", arg}});
}
auto options = Options::load(settings);
language = options.language;
if (port >= 0) {
options.mcp_port = port;
options.mcp_enabled = true;
}
Session session;
if (!input.empty())
session.execute("open", {{"path", utf8(input)}});
else if (demo || blank)
session.execute(demo ? "demo" : "new");
if (!script.empty()) {
const auto actions = Json::parse(read_file(script, 8 * 1024 * 1024));
if (!actions.is_array())
throw Error("invalid_change");
for (const auto &action : actions) {
auto result = session.execute(str(action, "command"), action.value("args", Json::object()));
if (headless && !stdio)
std::cout << result.dump() << '\n';
}
}
bool has_errors = false;
if (validate) {
auto result = session.execute("validate");
for (auto &row : result["diagnostics"])
if (row["severity"] == "error")
has_errors = true;
if (headless && !stdio)
std::cout << result.dump() << '\n';
}
if (!output.empty())
session.execute("save", {{"path", utf8(output)}});
McpServer server(session);
if (stdio) {
std::string line;
while (std::getline(std::cin, line)) {
try {
auto reply = server.dispatch(Json::parse(line));
if (!reply.is_null())
std::cout << reply.dump() << std::endl;
} catch (const std::exception &) {
std::cout << "{\"jsonrpc\":\"2.0\",\"id\":null,\"error\":{\"code\":-"
"32700,\"message\":\"Parse error\"}}"
<< std::endl;
}
}
return 0;
}
if (serve || !headless) {
try {
server.start(options);
} catch (const Error &e) {
std::cerr << tr(language, e.code) << '\n';
if (serve)
throw;
}
}
if (print)
std::cout << server.connection(options).dump(2) << '\n';
if (serve) {
std::cerr << "OpenBMH Editor MCP: http://127.0.0.1:" << server.port() << "/mcp\n";
std::signal(SIGINT, stop);
std::signal(SIGTERM, stop);
while (!stopped)
std::this_thread::sleep_for(std::chrono::milliseconds(80));
} else if (!headless) {
if (ui.assets.empty()) {
char *base = SDL_GetBasePath();
ui.assets = (base ? path(base) : fs::absolute(path(argv[0])).parent_path()) / "assets/editor";
SDL_free(base);
}
return run_ui(session, options, server, ui);
}
return has_errors ? 2 : 0;
} catch (const Error &e) {
std::cerr << Json{{"error", e.code}, {"message", tr(language, e.code)}, {"details", e.details}}.dump() << '\n';
return 1;
} catch (const std::exception &e) {
std::cerr << tr(language, "error") << ": " << e.what() << '\n';
return 1;
}
}
+351
View File
@@ -0,0 +1,351 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "editor/mcp.hpp"
#include <atomic>
#include <httplib.h>
#include <thread>
namespace bmh::editor {
namespace {
Json schema(Json properties = Json::object(), Json required = Json::array()) {
if (properties.is_null())
properties = Json::object();
if (required.is_null())
required = Json::array();
return {{"type", "object"}, {"properties", properties}, {"required", required}, {"additionalProperties", false}};
}
Json field(const char *type, const char *description = "") { return {{"type", type}, {"description", description}}; }
Json rpc_error(const Json &id, int code, const std::string &message, Json data = Json::object()) {
return {{"jsonrpc", "2.0"}, {"id", id}, {"error", {{"code", code}, {"message", message}, {"data", data}}}};
}
bool local_authority(const std::string &host) {
for (auto name : {"127.0.0.1", "localhost", "[::1]"}) {
const std::string base(name);
if (host == base)
return true;
if (host.starts_with(base + ':')) {
const auto port = host.substr(base.size() + 1);
if (!port.empty() && port.find_first_not_of("0123456789") == port.npos)
return true;
}
}
return false;
}
bool local_origin(std::string value) {
if (value.starts_with("http://"))
value.erase(0, 7);
else if (value.starts_with("https://"))
value.erase(0, 8);
else
return false;
return local_authority(value);
}
bool equal_secret(const std::string &a, const std::string &b) {
if (a.size() != b.size())
return false;
unsigned difference = 0;
for (size_t i = 0; i < a.size(); ++i)
difference |= unsigned(a[i] ^ b[i]);
return difference == 0;
}
const std::map<std::string, std::string> commands{{"editor_info", "info"},
{"editor_open", "open"},
{"editor_new", "new"},
{"editor_list", "list"},
{"editor_get", "get"},
{"editor_apply", "apply"},
{"editor_validate", "validate"},
{"editor_rules", "rules"},
{"editor_save", "save"},
{"editor_undo", "undo"},
{"editor_redo", "redo"},
{"editor_history", "history"},
{"editor_roster_move", "roster.move"},
{"editor_roster_swap", "roster.swap"},
{"editor_roster_order", "roster.order"},
{"editor_review_resolve", "review.resolve"},
{"editor_image_import", "asset.import"},
{"editor_image_edit", "asset.edit"},
{"editor_image_preview", "asset.preview"},
{"editor_image_export", "asset.export"}};
} // namespace
struct McpServer::Impl {
explicit Impl(Session &value) : session(value) {}
Session &session;
std::unique_ptr<httplib::Server> http;
std::thread worker;
std::atomic<bool> active{false};
int port = 0;
std::string token;
};
McpServer::McpServer(Session &s) : impl_(std::make_unique<Impl>(s)) {}
McpServer::~McpServer() { stop(); }
int McpServer::port() const { return impl_->port; }
bool McpServer::running() const { return impl_->active; }
void McpServer::stop() {
if (impl_->http)
impl_->http->stop();
if (impl_->worker.joinable())
impl_->worker.join();
impl_->active = false;
impl_->http.reset();
impl_->port = 0;
}
Json McpServer::connection(const Options &options) const {
return {{"mcpServers",
{{"openbmh-editor",
{{"type", "http"},
{"url", "http://127.0.0.1:" + std::to_string(port()) + "/mcp"},
{"headers", {{"Authorization", "Bearer " + options.token}}}}}}}};
}
Json McpServer::tools() {
Json result = Json::array();
const auto revision = field("integer", "Optional optimistic concurrency guard; use revision "
"from editor_info/get.");
const auto id = field("string", "Stable world identifier; never an array index.");
const auto table = field("string", "nations, competitions, clubs, players, stadiums, staff, "
"assets, review, or read-only preserved tables.");
auto add = [&](const char *name, const char *description, Json properties, Json required = Json::array(),
bool read_only = false) {
result.push_back({{"name", name},
{"description", description},
{"inputSchema", schema(properties, required)},
{"annotations",
{{"readOnlyHint", read_only}, {"destructiveHint", !read_only}, {"openWorldHint", false}}}});
};
add("editor_info",
"Current world, counts, dirty flag, monotonic revision and undo/redo "
"state.",
{}, {}, true);
add("editor_open",
"Open OBW archive, unpacked world, or legacy BMH/FLTD installation. "
"Refuses unsaved replacement unless discard=true.",
{{"path", field("string")},
{"start_date", field("string")},
{"discard", field("boolean")},
{"expected_revision", revision}},
{"path"});
add("editor_new", "Create a blank editor world; never writes legacy files.",
{{"title", field("string")}, {"discard", field("boolean")}, {"expected_revision", revision}});
add("editor_list",
"Search, filter, sort and page rows. Maximum page size 200; no data is "
"truncated on disk.",
{{"table", table},
{"search", field("string")},
{"nation", id},
{"competition", id},
{"team", id},
{"role", field("string")},
{"offset", field("integer")},
{"limit", field("integer")},
{"sort", field("string")},
{"descending", field("boolean")},
{"unresolved_only", field("boolean")}},
{"table"}, true);
add("editor_get", "Read a complete row, including preserved extensions and sources.",
{{"table", table}, {"id", id}}, {"table", "id"}, true);
add("editor_apply",
"Atomic undoable transaction, max 5000 changes. Each change: table, "
"op=create/update/delete, id. Create has data/name; update has set {JSON "
"pointer:value}, unset [JSON pointer]. IDs are immutable. References and "
"declared attribute ranges are checked before commit.",
{{"changes", {{"type", "array"}, {"items", {{"type", "object"}}}, {"maxItems", 5000}}},
{"expected_revision", revision}},
{"changes"});
add("editor_validate", "Structural errors plus non-blocking missing/source warnings.", {}, {}, true);
add("editor_rules",
"Read attribute systems and their actual ranges. Do not guess an "
"attribute scale.",
{}, {}, true);
add("editor_history", "Shared GUI/MCP transaction history.", {}, {}, true);
add("editor_save",
"Atomically save only a new-format .obw. A Classic source requires a new "
"filename. This editor profile is not executable in Classic 0.2.",
{{"path", field("string")}, {"expected_revision", revision}});
for (auto name : {"editor_undo", "editor_redo"})
add(name, "Undo/redo one shared transaction.", {{"expected_revision", revision}});
add("editor_roster_move", "Move one player to a club, or null for an explicitly chosen free agent.",
{{"player", id},
{"team", {{"type", {"string", "null"}}}},
{"number", field("integer")},
{"expected_revision", revision}},
{"player", "team"});
add("editor_roster_swap",
"Exchange club, shirt number and squad order between two players "
"atomically.",
{{"first", id}, {"second", id}, {"expected_revision", revision}}, {"first", "second"});
add("editor_roster_order",
"Set complete club squad order; every assigned player must occur exactly "
"once.",
{{"team", id}, {"players", {{"type", "array"}, {"items", field("string")}}}, {"expected_revision", revision}},
{"team", "players"});
add("editor_review_resolve",
"Choose a recorded source alternative and update its linked entity. "
"Original claims remain preserved.",
{{"id", id}, {"choice", field("integer")}, {"expected_revision", revision}}, {"id", "choice"});
const auto crop = schema(
{{"x", field("number")}, {"y", field("number")}, {"width", field("number")}, {"height", field("number")}});
const auto transform = schema(
{{"angle", field("number")}, {"flip_x", field("boolean")}, {"flip_y", field("boolean")}, {"crop", crop}});
add("editor_image_import",
"Import PNG/JPEG/WebP/SVG with optional arbitrary rotation, mirror, crop "
"(normalized on the rotated canvas). Preserves source and recipe; "
"identity import preserves exact bytes. target={table,id,field} "
"optionally assigns the logical key.",
{{"file", field("string")},
{"key", id},
{"target", field("object")},
{"transform", transform},
{"expected_revision", revision}},
{"file"});
add("editor_image_edit",
"Re-edit an existing image using its preserved original. No repeated "
"resampling.",
{{"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<httplib::Server>();
server->set_payload_max_length(8 * 1024 * 1024);
server->set_read_timeout(10, 0);
server->set_write_timeout(30, 0);
server->new_task_queue = [] { return new httplib::ThreadPool(2); };
auto authorized = [this](const httplib::Request &request, httplib::Response &response) {
response.set_header("Cache-Control", "no-store");
if (!local_authority(request.get_header_value("Host")) ||
(request.has_header("Origin") && !local_origin(request.get_header_value("Origin")))) {
response.status = 403;
return false;
}
if (!equal_secret(request.get_header_value("Authorization"), "Bearer " + impl_->token)) {
response.status = 401;
response.set_header("WWW-Authenticate", "Bearer");
return false;
}
return true;
};
server->Post("/mcp", [this, authorized](const httplib::Request &request, httplib::Response &response) {
if (!authorized(request, response))
return;
if (!request.get_header_value("Content-Type").starts_with("application/json")) {
response.status = 415;
return;
}
const auto version = request.get_header_value("MCP-Protocol-Version");
if (!version.empty() && version != "2025-11-25" && version != "2025-06-18" && version != "2025-03-26") {
response.status = 400;
response.set_content(rpc_error(nullptr, -32600, "Supported versions: 2025-11-25, 2025-06-18").dump(),
"application/json");
return;
}
try {
auto input = Json::parse(request.body);
if (!input.is_object()) {
response.status = 400;
response.set_content(rpc_error(nullptr, -32600, "Invalid request").dump(), "application/json");
return;
}
auto output = dispatch(input);
if (output.is_null()) {
response.status = 202;
return;
}
response.set_content(output.dump(), "application/json");
} catch (const Json::exception &) {
response.status = 400;
response.set_content(rpc_error(nullptr, -32700, "Parse error").dump(), "application/json");
} catch (const std::exception &) {
response.status = 500;
response.set_content(rpc_error(nullptr, -32603, "Internal error").dump(), "application/json");
}
});
for (auto method : {0, 1}) {
auto unsupported = [authorized](const httplib::Request &request, httplib::Response &response) {
if (authorized(request, response)) {
response.status = 405;
response.set_header("Allow", "POST");
}
};
if (method == 0)
server->Get("/mcp", unsupported);
else
server->Delete("/mcp", unsupported);
}
impl_->port = options.mcp_port ? (server->bind_to_port("127.0.0.1", options.mcp_port) ? options.mcp_port : -1)
: server->bind_to_any_port("127.0.0.1");
if (impl_->port <= 0) {
impl_->port = 0;
throw Error("server_failed");
}
impl_->http = std::move(server);
impl_->active = true;
impl_->worker = std::thread([this] {
impl_->http->listen_after_bind();
impl_->active = false;
});
}
} // namespace bmh::editor
+28
View File
@@ -0,0 +1,28 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "editor/options.hpp"
#include "editor/session.hpp"
#include <memory>
namespace bmh::editor {
// A local Streamable HTTP MCP endpoint. GUI and MCP own no separate world
// state. Protocol 2025-11-25 (also negotiates 2025-06-18), no optional
// SSE/session state.
class McpServer {
public:
explicit McpServer(Session &);
~McpServer();
McpServer(const McpServer &) = delete;
void start(const Options &);
void stop();
int port() const;
bool running() const;
Json connection(const Options &) const;
static Json tools();
Json dispatch(const Json &request);
private:
struct Impl;
std::unique_ptr<Impl> impl_;
};
} // namespace bmh::editor
+413
View File
@@ -0,0 +1,413 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "editor/options.hpp"
#include <cstdlib>
#include <map>
#include <random>
#ifndef _WIN32
#include <sys/stat.h>
#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<std::string, std::string>;
static const std::map<std::string, Pair> words{
{"data_areas", {"Datenbereiche", "World data"}},
{"invalid_manifest",
{"Die Kennzeichnung der Editorwelt ist ungültig.", "The editor world identification is invalid."}},
{"facilities", {"Ausstattung", "Facilities"}},
{"draft_prompt", {"Eingaben übernehmen?", "Apply these entries?"}},
{"draft_detail",
{"Die Eigenschaften enthalten noch nicht übernommene Eingaben.",
"The inspector contains entries that have not been applied."}},
{"trophy", {"Pokalbild", "Trophy image"}},
{"author", {"Urheber", "Author"}},
{"license", {"Lizenz", "License"}},
{"copy", {"Kopie", "Copy"}},
{"applied", {"Übernommen", "Applied"}},
{"undone", {"Zurückgenommen", "Undone"}},
{"edit", {"Bearbeitung", "Edit"}},
{"image_import", {"Bild importieren", "Import image"}},
{"width", {"Breite", "Width"}},
{"height", {"Höhe", "Height"}},
{"x", {"Links", "Left"}},
{"y", {"Oben", "Top"}},
{"open_folder", {"Entpackte Welt öffnen", "Open unpacked world"}},
{"subtitle_overview", {"Ein Arbeitsplatz für deine Fußballwelt", "A workspace for your football world"}},
{"subtitle_nations", {"Länder, Verbände und Simulation", "Countries, associations and simulation"}},
{"subtitle_competitions", {"Ligen, Zuordnungen und Pokalbilder", "Leagues, membership and trophy images"}},
{"subtitle_clubs", {"Stammdaten, Farben und Spielstätten", "Details, colours and home grounds"}},
{"subtitle_players",
{"Spielerdaten und quellengerechte Spielwerte", "Player details and source-specific attributes"}},
{"subtitle_stadiums", {"Kapazität und Ausstattung", "Capacity and facilities"}},
{"subtitle_staff", {"Schiedsrichter und ihre Eigenschaften", "Referees and their attributes"}},
{"subtitle_assets", {"Wappen, Porträts und Pokale", "Crests, portraits and trophies"}},
{"subtitle_review", {"Quellen vergleichen", "Compare sources"}},
{"subtitle_roster", {"Vollständige Kader ohne Datenverlust", "Complete squads without losing data"}},
{"subtitle_changes", {"Gemeinsame Historie von Oberfläche und MCP", "One history for the interface and MCP"}},
{"preservation_note",
{"Quellen, Bilder und Erweiterungen bleiben erhalten. Bearbeitungen "
"ändern keine Originalinstallation.",
"Sources, images and extensions are retained. Edits do not change the "
"original installation."}},
{"unrated_hint",
{"Keine belegten Spielwerte vorhanden. Es werden keine Stärken "
"erfunden.",
"No sourced attributes available. Ratings are not invented."}},
{"crop_hint",
{"Im Bild einen Rahmen ziehen oder den Ausschnitt als Werte eingeben. "
"Ohne Zuschnitt bleibt die Originalauflösung erhalten.",
"Drag a rectangle on the image or enter crop values. Without cropping, "
"the original resolution is retained."}},
{"video_failed",
{"Die Grafikausgabe benötigt OpenGL 3.3 (macOS: 4.1).", "The interface requires OpenGL 3.3 (macOS: 4.1)."}},
{"ui_assets_missing",
{"Editor-Oberfläche fehlt. Bitte das vollständige Paket entpacken.",
"Editor interface files are missing. Please extract the complete "
"package."}},
{"dialog_failed", {"Der Dateidialog konnte nicht geöffnet werden.", "The file dialog could not be opened."}},
{"invalid_attributes", {"Ungültige Spielwerte.", "Invalid player attributes."}},
{"app", {"OpenBMH Editor", "OpenBMH Editor"}},
{"poc", {"Dateneditor · Vorschau", "World editor · Preview"}},
{"overview", {"Übersicht", "Overview"}},
{"nations", {"Länder", "Countries"}},
{"competitions", {"Ligen & Pokale", "Leagues & cups"}},
{"clubs", {"Vereine", "Clubs"}},
{"players", {"Spieler", "Players"}},
{"roster", {"Kader", "Squads"}},
{"stadiums", {"Stadien", "Stadiums"}},
{"staff", {"Schiedsrichter", "Referees"}},
{"assets", {"Bilder", "Images"}},
{"review", {"Prüfen", "Review"}},
{"changes", {"Änderungen", "Changes"}},
{"options", {"Optionen", "Options"}},
{"open", {"Öffnen", "Open"}},
{"open_world", {"OBW öffnen", "Open OBW"}},
{"import_legacy", {"BMH / FLTD importieren", "Import BMH / FLTD"}},
{"new_world", {"Neue Welt", "New world"}},
{"demo", {"Demo öffnen", "Open demo"}},
{"save", {"Speichern", "Save"}},
{"save_as", {"Speichern unter …", "Save as …"}},
{"undo", {"Rückgängig", "Undo"}},
{"redo", {"Wiederholen", "Redo"}},
{"search", {"Suchen …", "Search …"}},
{"all", {"Alle", "All"}},
{"all_nations", {"Alle Länder", "All countries"}},
{"all_leagues", {"Alle Ligen", "All leagues"}},
{"all_clubs", {"Alle Vereine", "All clubs"}},
{"add", {"Hinzufügen", "Add"}},
{"duplicate", {"Duplizieren", "Duplicate"}},
{"delete", {"Löschen", "Delete"}},
{"apply", {"Anwenden", "Apply"}},
{"cancel", {"Abbrechen", "Cancel"}},
{"close", {"Schließen", "Close"}},
{"confirm", {"Bestätigen", "Confirm"}},
{"discard", {"Verwerfen", "Discard"}},
{"unknown", {"Unbekannt", "Unknown"}},
{"empty", {"Keine Einträge", "No records"}},
{"select_record", {"Datensatz auswählen", "Select a record"}},
{"name", {"Name", "Name"}},
{"short_name", {"Kurzname", "Short name"}},
{"first", {"Vorname", "First name"}},
{"last", {"Nachname", "Last name"}},
{"known_as", {"Anzeigename", "Known as"}},
{"nation", {"Land", "Country"}},
{"nationalities", {"Nationalitätsangaben", "Nationality claims"}},
{"competition", {"Liga", "League"}},
{"team", {"Verein", "Club"}},
{"stadium", {"Stadion", "Stadium"}},
{"born", {"Geburtsdatum", "Date of birth"}},
{"age_at_start", {"Alter zum Saisonbeginn", "Age at season start"}},
{"positions", {"Position", "Position"}},
{"gk", {"Tor", "Goalkeeper"}},
{"def", {"Abwehr", "Defender"}},
{"mid", {"Mittelfeld", "Midfielder"}},
{"fwd", {"Sturm", "Forward"}},
{"squad_number", {"Rückennummer", "Shirt number"}},
{"squad_order", {"Kaderplatz", "Squad order"}},
{"attribute_set", {"Attributsystem", "Attribute set"}},
{"attributes", {"Spielwerte", "Attributes"}},
{"type", {"Art", "Type"}},
{"tier", {"Spielklasse", "Tier"}},
{"visible", {"Sichtbare Liga", "Visible league"}},
{"playable", {"Ligen vollständig simulieren", "Fully simulated leagues"}},
{"confederation", {"Verband", "Confederation"}},
{"founded", {"Gründungsjahr", "Founded"}},
{"capacity", {"Kapazität", "Capacity"}},
{"total", {"Gesamt", "Total"}},
{"standing", {"Stehplätze", "Standing"}},
{"seated", {"Sitzplätze", "Seated"}},
{"boxes", {"Logen", "Boxes"}},
{"owner", {"Eigentümer", "Owner"}},
{"colors", {"Vereinsfarben", "Club colours"}},
{"role", {"Rolle", "Role"}},
{"strictness", {"Strenge", "Strictness"}},
{"strength", {"Stärke", "Strength"}},
{"technique", {"Technik", "Technique"}},
{"condition", {"Kondition", "Condition"}},
{"form", {"Form", "Form"}},
{"overall", {"Gesamtstärke", "Overall"}},
{"potential", {"Potenzial", "Potential"}},
{"acceleration", {"Antritt", "Acceleration"}},
{"sprintspeed", {"Sprinttempo", "Sprint speed"}},
{"positioning", {"Offensivstellung", "Attacking position"}},
{"finishing", {"Abschluss", "Finishing"}},
{"shotpower", {"Schusskraft", "Shot power"}},
{"longshots", {"Fernschüsse", "Long shots"}},
{"volleys", {"Volleys", "Volleys"}},
{"penalties", {"Elfmeter", "Penalties"}},
{"crossing", {"Flanken", "Crossing"}},
{"shortpassing", {"Kurzpass", "Short passing"}},
{"longpassing", {"Langpass", "Long passing"}},
{"curve", {"Effet", "Curve"}},
{"freekickaccuracy", {"Freistöße", "Free kicks"}},
{"vision", {"Übersicht", "Vision"}},
{"dribbling", {"Dribbling", "Dribbling"}},
{"ballcontrol", {"Ballkontrolle", "Ball control"}},
{"agility", {"Beweglichkeit", "Agility"}},
{"balance", {"Balance", "Balance"}},
{"reactions", {"Reaktion", "Reactions"}},
{"composure", {"Ruhe am Ball", "Composure"}},
{"interceptions", {"Abfangen", "Interceptions"}},
{"headingaccuracy", {"Kopfball", "Heading"}},
{"standingtackle", {"Zweikampf", "Standing tackle"}},
{"slidingtackle", {"Grätsche", "Sliding tackle"}},
{"defensiveawareness", {"Defensivstellung", "Defensive awareness"}},
{"jumping", {"Sprungkraft", "Jumping"}},
{"stamina", {"Ausdauer", "Stamina"}},
{"aggression", {"Aggressivität", "Aggression"}},
{"gkdiving", {"TW-Hechten", "GK diving"}},
{"gkhandling", {"TW-Fangen", "GK handling"}},
{"gkkicking", {"TW-Abschlag", "GK kicking"}},
{"gkpositioning", {"TW-Stellung", "GK positioning"}},
{"gkreflexes", {"TW-Reflexe", "GK reflexes"}},
{"bonus", {"Bonus", "Bonus"}},
{"teamplay", {"Teamspiel", "Team play"}},
{"speed", {"Schnelligkeit", "Speed"}},
{"shooting", {"Schuss", "Shooting"}},
{"passing", {"Pass", "Passing"}},
{"tackling", {"Zweikampf", "Tackling"}},
{"free_kick", {"Freistoß", "Free kick"}},
{"corner", {"Ecke", "Corner"}},
{"yes", {"Ja", "Yes"}},
{"no", {"Nein", "No"}},
{"league", {"Liga", "League"}},
{"cup", {"Pokal", "Cup"}},
{"national", {"Nationalmannschaft", "National team"}},
{"club", {"Verein", "Club"}},
{"foreign", {"Auslandsverein", "Foreign club"}},
{"amateur", {"Amateur", "Amateur"}},
{"image_import", {"Bild importieren", "Import image"}},
{"image_edit", {"Bild bearbeiten", "Edit image"}},
{"image_export", {"PNG exportieren", "Export PNG"}},
{"angle", {"Drehwinkel", "Rotation"}},
{"flip_x", {"Horizontal spiegeln", "Flip horizontally"}},
{"flip_y", {"Vertikal spiegeln", "Flip vertically"}},
{"crop", {"Zuschnitt", "Crop"}},
{"free", {"Frei", "Free"}},
{"reset", {"Zurücksetzen", "Reset"}},
{"source", {"Quelle", "Source"}},
{"original", {"Original", "Original"}},
{"preview", {"Vorschau", "Preview"}},
{"language", {"Sprache", "Language"}},
{"theme", {"Darstellung", "Theme"}},
{"mcp_enabled", {"MCP-Server aktivieren", "Enable MCP server"}},
{"mcp_port", {"Port", "Port"}},
{"copy_connection", {"Verbindung kopieren", "Copy connection"}},
{"mcp_local", {"Lokal auf diesem Rechner", "Local to this computer"}},
{"online", {"Aktiv", "Online"}},
{"offline", {"Aus", "Offline"}},
{"saved", {"Gespeichert", "Saved"}},
{"unsaved", {"Ungespeichert", "Unsaved"}},
{"not_playable", {"Editorwelt · noch nicht im Spiel startbar", "Editor world · not yet playable"}},
{"workspace", {"Deine Fußballwelt", "Your football world"}},
{"welcome",
{"Stammdaten bearbeiten. Quellen erhalten. Neues gestalten.",
"Edit the details. Keep the sources. Build something new."}},
{"welcome_hint",
{"Öffne eine OBW-Welt, importiere BMH oder Football Limited oder "
"probiere die Demo aus.",
"Open an OBW world, import BMH or Football Limited, or explore the "
"demo."}},
{"records", {"Einträge", "records"}},
{"previous", {"Zurück", "Previous"}},
{"next", {"Weiter", "Next"}},
{"details", {"Eigenschaften", "Properties"}},
{"provenance", {"Herkunft & Hinweise", "Sources & notes"}},
{"resolve", {"Auswahl übernehmen", "Use selected value"}},
{"resolved", {"Erledigt", "Resolved"}},
{"unresolved", {"Offen", "Open"}},
{"review_hint", {"Quellen vergleichen und eine Angabe auswählen.", "Compare sources and choose a value."}},
{"roster_hint",
{"Verein wählen, Spieler verschieben oder zwei Spieler tauschen.",
"Choose a club, move a player or swap two players."}},
{"move_player", {"Spieler verschieben", "Move player"}},
{"remember_player", {"Zum Tausch merken", "Remember for swap"}},
{"swap_player", {"Mit gemerktem Spieler tauschen", "Swap with remembered player"}},
{"compatibility24", {"24-Spieler-Ansicht", "24-player view"}},
{"validate", {"Welt prüfen", "Validate world"}},
{"warnings", {"Hinweise", "Warnings"}},
{"errors", {"Fehler", "Errors"}},
{"no_changes", {"Noch keine Änderungen", "No changes yet"}},
{"dirty_prompt", {"Änderungen speichern?", "Save changes?"}},
{"dirty_detail", {"Diese Welt enthält ungespeicherte Änderungen.", "This world has unsaved changes."}},
{"delete_prompt", {"Datensatz wirklich löschen?", "Delete this record?"}},
{"new_name", {"Name des neuen Datensatzes", "Name of the new record"}},
{"new_title", {"Neue Fußballwelt", "New football world"}},
{"start_date", {"Saisonbeginn", "Season start"}},
{"title", {"Titel", "Title"}},
{"currency", {"Währung", "Currency"}},
{"loading", {"Wird geladen …", "Loading …"}},
{"saved_ok", {"Welt gespeichert", "World saved"}},
{"copied", {"In die Zwischenablage kopiert", "Copied to clipboard"}},
{"error", {"Fehler", "Error"}},
{"open_failed", {"Die Datei konnte nicht geöffnet werden.", "The file could not be opened."}},
{"save_failed",
{"Speichern fehlgeschlagen. Die bisherige Datei bleibt erhalten.",
"Saving failed. The previous file is retained."}},
{"invalid_archive",
{"Das Archiv ist beschädigt oder wird nicht unterstützt.", "The archive is damaged or unsupported."}},
{"unsupported_archive", {"Dieses Archivformat wird nicht unterstützt.", "This archive format is unsupported."}},
{"archive_limit",
{"Das Datenpaket überschreitet die unterstützten Grenzen.", "The data package exceeds the supported limits."}},
{"unsafe_path", {"Unzulässiger Dateipfad.", "Invalid file path."}},
{"size_limit", {"Die Datei ist zu groß.", "The file is too large."}},
{"missing_manifest", {"Keine OBW-Welt gefunden.", "No OBW world found."}},
{"not_world", {"Bitte eine OBW-Startdatenbank öffnen.", "Please open an OBW starting world."}},
{"unsupported_version", {"Diese Formatversion wird nicht unterstützt.", "This format version is unsupported."}},
{"invalid_json", {"Die JSON-Daten sind ungültig.", "The JSON data is invalid."}},
{"invalid_table", {"Eine Datentabelle ist ungültig.", "A data table is invalid."}},
{"unknown_table", {"Unbekannter Datenbereich.", "Unknown data table."}},
{"missing_asset", {"Das Bild fehlt im Datenpaket.", "The image is missing from the package."}},
{"unsafe_asset", {"Das Bild kann nicht übernommen werden.", "The image cannot be imported."}},
{"invalid_image", {"Das Bild konnte nicht gelesen werden.", "The image could not be decoded."}},
{"image_dimensions", {"Das Bild hat nicht unterstützte Abmessungen.", "The image dimensions are unsupported."}},
{"invalid_transform",
{"Der Bildzuschnitt oder Drehwinkel ist ungültig.", "The image crop or rotation is invalid."}},
{"external_svg_resource",
{"Das SVG verweist auf externe Bilddateien. Bitte ein eigenständiges "
"SVG verwenden.",
"The SVG references external images. Please use a self-contained "
"SVG."}},
{"image_encode_failed",
{"Das bearbeitete Bild konnte nicht erstellt werden.", "The edited image could not be created."}},
{"obw_only", {"Es kann ausschließlich als .obw gespeichert werden.", "Only .obw output is supported."}},
{"preserve_source",
{"Bitte unter einem neuen Namen speichern. Der Classic-Import bleibt "
"erhalten.",
"Please save under a new name. The Classic source is retained."}},
{"validation_failed",
{"Bitte zuerst die angezeigten Datenfehler beheben.", "Please fix the reported data errors first."}},
{"invalid_date",
{"Bitte ein gültiges Datum im Format JJJJ-MM-TT eingeben.",
"Please enter a valid date in YYYY-MM-DD format."}},
{"duplicate_id",
{"Eine Kennung fehlt oder ist mehrfach vorhanden.", "An identifier is missing or duplicated."}},
{"missing_reference", {"Ein verknüpfter Datensatz fehlt.", "A referenced record is missing."}},
{"attribute_range",
{"Ein Spielwert liegt außerhalb seines Wertebereichs.", "An attribute is outside its declared range."}},
{"unknown_attribute_set", {"Das Attributsystem ist nicht definiert.", "The attribute set is not defined."}},
{"missing_name", {"Ein Name fehlt.", "A name is missing."}},
{"missing_birthday", {"Das Geburtsdatum ist unbekannt.", "The date of birth is unknown."}},
{"review_open", {"Eine Quellenfrage ist noch offen.", "A source decision is still open."}},
{"record_referenced",
{"Der Datensatz wird noch verwendet. Bitte zuerst die Verknüpfungen "
"ändern.",
"The record is still referenced. Please update its links first."}},
{"record_missing", {"Der Datensatz wurde nicht gefunden.", "The record was not found."}},
{"immutable_id",
{"Kennungen können nicht nachträglich geändert werden.", "Identifiers cannot be changed after creation."}},
{"stale_revision",
{"Die Daten wurden inzwischen geändert. Bitte die Ansicht "
"aktualisieren.",
"The data has changed. Please refresh the view."}},
{"invalid_change", {"Diese Änderung ist nicht gültig.", "This change is invalid."}},
{"nothing_to_undo", {"Keine Änderung zum Rückgängigmachen.", "There is nothing to undo."}},
{"nothing_to_redo", {"Keine Änderung zum Wiederholen.", "There is nothing to redo."}},
{"no_world", {"Bitte zuerst eine Welt öffnen.", "Please open a world first."}},
{"invalid_settings", {"Die Optionen sind ungültig.", "The options are invalid."}},
{"output_parent_missing", {"Der Zielordner existiert nicht.", "The output folder does not exist."}},
{"destination_exists", {"Die Zieldatei existiert bereits.", "The destination file already exists."}},
{"duplicate_entry", {"Das Archiv enthält doppelte Dateinamen.", "The archive contains duplicate entry names."}},
{"server_failed",
{"MCP konnte nicht gestartet werden. Bitte den Port prüfen.",
"MCP could not be started. Please check the port."}},
{"source_changed",
{"Die Quelldatei wurde außerhalb des Editors geändert. Bitte Speichern "
"unter verwenden.",
"The source file changed outside the editor. Please use Save as."}}};
const auto found = words.find(key);
if (found == words.end())
return key;
return language == "en" ? found->second.second : found->second.first;
}
} // namespace bmh::editor
+16
View File
@@ -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
+554
View File
@@ -0,0 +1,554 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "editor/session.hpp"
#include "content/digest.hpp"
#include "editor/images.hpp"
#include <algorithm>
#include <limits>
namespace bmh::editor {
namespace {
bool editable(const std::string &name) {
return name == "nations" || name == "competitions" || name == "clubs" || name == "players" || name == "stadiums" ||
name == "staff" || name == "assets" || name == "review" || name == "image-edits" || name == "manifest";
}
Json defaults(const std::string &table, const std::string &name) {
auto localized = Json{{"default", name}};
if (table == "players")
return {{"name", {{"first", ""}, {"last", name}}},
{"born", nullptr},
{"nationalities", Json::array()},
{"positions", Json::array()},
{"attributes", Json::object()},
{"attribute_set", "unrated@1"}};
if (table == "clubs")
return {{"name", localized}, {"type", "club"}, {"nation", nullptr}, {"colors", Json::array()}};
if (table == "nations")
return {{"name", localized}, {"confederation", "other"}, {"playable", false}};
if (table == "competitions")
return {{"name", localized}, {"type", "league"}, {"nation", nullptr}, {"tier", 1},
{"visible", true}, {"members", Json::array()}, {"stages", Json::array()}};
if (table == "stadiums")
return {{"name", localized}, {"capacity", Json::object()}, {"facilities", Json::object()}};
if (table == "staff")
return {{"name", localized}, {"role", "referee"}, {"attributes", Json::object()}};
return Json::object();
}
std::string prefix(const std::string &table) {
if (table == "nations")
return "nation:";
if (table == "competitions")
return "comp:";
if (table == "assets")
return "asset:";
if (table == "staff")
return "staff:";
if (table == "image-edits")
return "image-edit:";
return table.substr(0, table.size() - 1) + ':';
}
} // namespace
World &Session::world() {
if (!world_)
throw Error("no_world");
return *world_;
}
bool Session::dirty() const { return world_ && state_ != saved_state_; }
Json Session::info() const {
Json result = world_ ? world_->statistics() : Json{{"title", ""}, {"counts", Json::object()}};
result["loaded"] = bool(world_);
result["revision"] = revision_;
result["dirty"] = dirty();
result["can_undo"] = cursor_ > 0;
result["can_redo"] = cursor_ < history_.size();
result["path"] = utf8(saved_path_);
return result;
}
void Session::replace(World value) {
world_ = std::make_unique<World>(std::move(value));
history_.clear();
cursor_ = 0;
++revision_;
state_ = next_state_++;
saved_state_ = world_->source_path.empty() || world_->imported ? 0 : state_;
saved_path_ = world_->source_path.empty() || world_->imported || !fs::is_regular_file(world_->source_path)
? fs::path{}
: world_->source_path;
if (!saved_path_.empty() && fs::is_regular_file(saved_path_)) {
saved_time_ = fs::last_write_time(saved_path_);
saved_size_ = fs::file_size(saved_path_);
}
}
void Session::frame(const Frame &f, bool forward) {
for (const auto &change : f.changes) {
auto value = forward ? change.after : change.before;
if (change.table == "manifest") {
if (value)
world().manifest = *value;
} else
world().change(change.table, change.id, value);
}
for (const auto &file : f.files)
world().store->restore(file.name, forward ? file.after : file.before);
state_ = forward ? f.after : f.before;
}
Json Session::apply(const Json &args, std::vector<FileDelta> files, const std::string &label) {
auto &w = world();
if (args.contains("expected_revision") && args["expected_revision"].get<uint64_t>() != revision_)
throw Error("stale_revision");
if (!args.contains("changes") || !args["changes"].is_array() || args["changes"].size() > 5000)
throw Error("invalid_change");
Frame transaction;
transaction.label = label;
transaction.files = std::move(files);
transaction.before = state_;
transaction.after = next_state_;
std::map<std::pair<std::string, std::string>, size_t> staged;
Json created = Json::array();
for (const auto &action : args["changes"]) {
const auto name = str(action, "table"), op = str(action, "op", "update");
if (!editable(name))
throw Error("unknown_table");
auto id = str(action, "id");
if (op == "create" && id.empty()) {
id = new_id(prefix(name) + "editor-");
created.push_back(id);
}
if (name == "manifest")
id = "manifest";
auto key = std::make_pair(name, id);
if (!staged.contains(key)) {
const auto *existing = name == "manifest" ? &w.manifest : w.find(name, id);
std::optional<Json> before = existing ? std::optional<Json>(*existing) : std::nullopt;
staged[key] = transaction.changes.size();
transaction.changes.push_back({name, id, before, before});
}
auto &delta = transaction.changes[staged[key]];
if (op == "create") {
if (delta.after || name == "manifest")
throw Error("duplicate_id");
delta.after = defaults(name, str(action, "name"));
if (action.contains("data"))
delta.after->update(action["data"]);
(*delta.after)[name == "assets" ? "key" : "id"] = id;
} else if (op == "delete") {
if (!delta.after)
throw Error("record_missing", {{"table", name}, {"id", id}});
if (name == "manifest")
throw Error("invalid_change");
delta.after.reset();
} else if (op == "update") {
if (!delta.after)
throw Error("record_missing", {{"table", name}, {"id", id}});
const auto set = action.value("set", Json::object());
if (!set.is_object())
throw Error("invalid_change");
for (auto it = set.begin(); it != set.end(); ++it) {
const auto pointer = it.key();
if (pointer.empty() || pointer[0] != '/' || pointer == "/id" || pointer.starts_with("/id/") ||
(name == "assets" && pointer == "/key"))
throw Error("immutable_id");
if (name == "manifest" && pointer != "/title" && !pointer.starts_with("/title/") &&
pointer != "/start_date" && pointer != "/currency" && !pointer.starts_with("/currency/") &&
pointer != "/languages")
throw Error("immutable_id");
(*delta.after)[Json::json_pointer(pointer)] = it.value();
}
for (const auto &field : action.value("unset", Json::array())) {
auto pointer = field.get<std::string>();
if (pointer.empty() || pointer[0] != '/' || pointer == "/id" || (name == "assets" && pointer == "/key"))
throw Error("immutable_id");
if (name == "manifest" && pointer != "/title" && !pointer.starts_with("/title/") &&
pointer != "/start_date" && pointer != "/currency" && !pointer.starts_with("/currency/") &&
pointer != "/languages")
throw Error("immutable_id");
auto split = pointer.rfind('/');
auto parent = Json::json_pointer(pointer.substr(0, split));
if (delta.after->contains(parent)) {
auto leaf_pointer = Json::json_pointer(pointer);
auto &container = (*delta.after)[parent];
const auto leaf = leaf_pointer.back();
if (container.is_object())
container.erase(leaf);
else if (container.is_array()) {
const auto index = std::stoull(leaf);
if (index < container.size())
container.erase(container.begin() + std::ptrdiff_t(index));
}
}
}
} else
throw Error("invalid_change");
}
transaction.changes.erase(std::remove_if(transaction.changes.begin(), transaction.changes.end(),
[](const Delta &d) { return d.before == d.after; }),
transaction.changes.end());
// Membership is edited once, at the club, and stays consistent in each
// affected league. This derived change belongs to the same undo frame.
std::map<std::string, Json> memberships;
for (const auto &d : transaction.changes)
if (d.table == "clubs") {
const auto old_league = d.before ? str(*d.before, "competition") : "";
const auto new_league = d.after ? str(*d.after, "competition") : "";
if (old_league == new_league)
continue;
for (auto league : {old_league, new_league})
if (!league.empty()) {
auto *comp = w.find("competitions", league);
if (!memberships.contains(league)) {
if (comp)
memberships[league] = *comp;
for (const auto &staged_delta : transaction.changes)
if (staged_delta.table == "competitions" && staged_delta.id == league && staged_delta.after)
memberships[league] = *staged_delta.after;
if (!memberships.contains(league))
throw Error("missing_reference");
}
auto &members = memberships[league]["members"];
if (members.is_null())
members = Json::array();
if (!members.is_array())
throw Error("invalid_change");
members.erase(std::remove(members.begin(), members.end(), Json(d.id)), members.end());
if (league == new_league)
members.push_back(d.id);
}
}
for (auto &[id, after] : memberships) {
bool found = false;
for (auto &d : transaction.changes)
if (d.table == "competitions" && d.id == id) {
d.after = after;
found = true;
break;
}
if (!found)
transaction.changes.push_back({"competitions", id, *w.find("competitions", id), after});
}
if (transaction.changes.empty() && transaction.files.empty())
return {{"changed", false}, {"revision", revision_}, {"created", created}};
try {
frame(transaction, true);
for (auto &change : transaction.changes)
if (!change.after) {
auto refs = w.references(change.id);
if (!refs.empty()) {
Json list = Json::array();
for (auto &[table, id] : refs)
list.push_back({{"table", table}, {"id", id}});
throw Error("record_referenced", {{"references", list}});
}
}
for (const auto &problem : w.validate())
if (problem["severity"] == "error")
throw Error("validation_failed", {{"diagnostics", w.validate()}});
} catch (...) {
frame(transaction, false);
throw;
}
history_.resize(cursor_);
history_.push_back(std::move(transaction));
++cursor_;
++next_state_;
++revision_;
if (history_.size() > 100) {
history_.erase(history_.begin());
--cursor_;
}
return {{"changed", true}, {"revision", revision_}, {"created", created}};
}
Json Session::import_image(const Json &args) {
auto &w = world();
std::string original, extension, original_name;
const auto *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<FileDelta> files;
for (auto &[name, data] :
std::vector<std::pair<std::string, std::string>>{{source_file, original}, {output_file, result.bytes}}) {
if (!w.store->contains(name))
files.push_back({name, w.store->overlay(name), std::make_shared<const std::string>(std::move(data))});
}
Json row{
{"key", key},
{"name", {{"default", original_name}}},
{"files", {{result.extension == ".svg" ? "svg" : "native", output_file}}},
{"width", result.width},
{"height", result.height},
{"source", "user-import"},
{"author", "user-supplied"},
{"license", "user-supplied"},
{"kind", result.extension == ".svg" ? "vector" : "raster"},
{"x-editor", {{"original", source_file}, {"original_sha256", original_hash}, {"transform", result.recipe}}}};
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<std::string, std::string> Session::asset_bytes(const std::string &key) const {
std::lock_guard guard(mutex_);
if (!world_)
return {images::silhouette(), ".svg"};
if (key.starts_with("portrait:")) {
const auto *player = world_->find("players", key.substr(9));
if (player) {
auto photo = world_->asset_file(str(*player, "photo"));
if (!photo.empty())
return {world_->store->read(photo), utf8(path(photo).extension())};
auto recipe = player->value("appearance", Json::object());
auto set = str(recipe, "set");
const auto file = "assets/portrait-sets/" + set + "/set.json";
if (safe_name(file) && world_->store->contains(file)) {
const auto parts = Json::parse(world_->store->read(file));
int width = parts.value("width", 0), height = parts.value("height", 0);
if (width <= 0 || height <= 0 || width > 8192 || height > 8192 ||
uint64_t(width) * height > 32ull * 1024 * 1024)
throw Error("image_dimensions");
images::Raster portrait{width, height, std::vector<uint8_t>(size_t(width) * height * 4)};
auto paint = [&](const std::string &asset, int x, int y) {
auto input = world_->asset_file(asset);
if (input.empty())
return;
auto layer = images::decode(world_->store->read(input), utf8(path(input).extension()));
for (int sy = 0; sy < layer.height; ++sy)
for (int sx = 0; sx < layer.width; ++sx) {
int dx = x + sx, dy = y + sy;
if (dx < 0 || dy < 0 || dx >= width || dy >= height)
continue;
const auto *src = layer.pixels.data() + (size_t(sy) * layer.width + sx) * 4;
auto *dst = portrait.pixels.data() + (size_t(dy) * width + dx) * 4;
const unsigned alpha = src[3] * 255u + dst[3] * (255u - src[3]);
for (int c = 0; c < 3; ++c)
dst[c] =
alpha
? uint8_t((src[c] * src[3] * 255u + dst[c] * dst[3] * (255u - src[3])) / alpha)
: 0;
dst[3] = uint8_t((alpha + 127) / 255);
}
};
auto backgrounds = parts.value("backgrounds", Json::array());
auto background = recipe.value("background", size_t(0));
if (background < backgrounds.size()) {
const auto &b = backgrounds[background];
paint(str(b, "asset"), b.value("x", 0), b.value("y", 0));
}
auto layers = parts.value("layers", Json::array()), choices = recipe.value("layers", Json::array());
for (size_t i = 0; i < std::min(layers.size(), choices.size()); ++i) {
auto options = layers[i].value("parts", Json::array());
const auto choice = choices[i].get<size_t>();
if (choice < options.size())
paint(options[choice].get<std::string>(), layers[i].value("x", 0), layers[i].value("y", 0));
}
return {images::encode_png(portrait), ".png"};
}
}
return {images::silhouette(), ".svg"};
}
auto file = key.starts_with("asset:") ? world_->asset_file(key) : key;
if (file.empty() || !world_->store->contains(file))
return {images::silhouette(), ".svg"};
return {world_->store->read(file), utf8(path(file).extension())};
}
Json Session::execute(const std::string &command, const Json &args) {
std::lock_guard guard(mutex_);
if (!args.is_object())
throw Error("invalid_change");
if (args.contains("expected_revision") && args["expected_revision"].get<uint64_t>() != revision_)
throw Error("stale_revision");
if (command == "info")
return info();
if (command == "open" || command == "new" || command == "demo") {
if (dirty() && !args.value("discard", false))
throw Error("unsaved_changes");
if (command == "open")
replace(World::open(path(str(args, "path")), str(args, "start_date", "2026-07-01")));
else
replace(command == "demo" ? World::demo() : World::blank(str(args, "title", "Untitled world")));
return info();
}
auto &w = world();
if (command == "list")
return w.query(args);
if (command == "get") {
auto name = str(args, "table"), id = str(args, "id");
const auto *found = name == "manifest" ? &w.manifest : w.find(name, id);
if (!found)
throw Error("record_missing");
return {{"record", *found}, {"revision", revision_}};
}
if (command == "rules")
return w.rows("rules");
if (command == "validate")
return {{"diagnostics", w.validate()}, {"revision", revision_}};
if (command == "history") {
Json values = Json::array();
for (size_t i = 0; i < history_.size(); ++i) {
Json affected = Json::array();
for (auto &delta : history_[i].changes)
affected.push_back({{"table", delta.table},
{"id", delta.id},
{"before", delta.before ? *delta.before : Json()},
{"after", delta.after ? *delta.after : Json()}});
values.push_back({{"label", history_[i].label}, {"applied", i < cursor_}, {"changes", affected}});
}
return {{"items", values}, {"revision", revision_}};
}
if (command == "apply")
return apply(args);
if (command == "undo" || command == "redo") {
if (args.contains("expected_revision") && args["expected_revision"].get<uint64_t>() != revision_)
throw Error("stale_revision");
if (command == "undo") {
if (!cursor_)
throw Error("nothing_to_undo");
frame(history_[--cursor_], false);
} else {
if (cursor_ >= history_.size())
throw Error("nothing_to_redo");
frame(history_[cursor_++], true);
}
++revision_;
return info();
}
if (command == "save") {
const auto destination = args.contains("path") ? path(str(args, "path")) : saved_path_;
if (destination.empty())
throw Error("output_parent_missing");
if (!saved_path_.empty() && fs::absolute(destination) == fs::absolute(saved_path_) &&
fs::is_regular_file(saved_path_) &&
(fs::last_write_time(saved_path_) != saved_time_ || fs::file_size(saved_path_) != saved_size_))
throw Error("source_changed");
w.save(destination);
saved_path_ = fs::absolute(destination);
saved_time_ = fs::last_write_time(saved_path_);
saved_size_ = fs::file_size(saved_path_);
saved_state_ = state_;
return info();
}
if (command == "roster.move") {
auto person = str(args, "player");
Json set{{"/team", args.value("team", Json())}};
if (args.contains("number"))
set["/squad_number"] = args["number"];
auto change = Json{{"op", "update"}, {"table", "players"}, {"id", person}, {"set", set}};
return apply({{"changes", Json::array({change})}}, {}, "move_player");
}
if (command == "roster.swap") {
auto first = w.find("players", str(args, "first")), second = w.find("players", str(args, "second"));
if (!first || !second || first == second)
throw Error("invalid_change");
Json changes = Json::array();
for (auto pair : {std::pair{first, second}, std::pair{second, first}}) {
Json set;
for (auto field : {"team", "squad_number", "squad_order"})
set['/' + std::string(field)] = pair.second->value(field, Json());
changes.push_back({{"op", "update"}, {"table", "players"}, {"id", (*pair.first)["id"]}, {"set", set}});
}
return apply({{"changes", changes}}, {}, "swap_player");
}
if (command == "roster.order") {
auto team = str(args, "team");
auto order = args.value("players", Json::array());
std::set<std::string> expected, actual;
for (auto &row : w.rows("players"))
if (str(row, "team") == team)
expected.insert(str(row, "id"));
for (auto &row : order)
actual.insert(row.get<std::string>());
if (expected != actual || actual.size() != order.size())
throw Error("invalid_change");
Json changes = Json::array();
for (size_t i = 0; i < order.size(); ++i)
changes.push_back(
{{"op", "update"}, {"table", "players"}, {"id", order[i]}, {"set", {{"/squad_order", i}}}});
return apply({{"changes", changes}}, {}, "roster");
}
if (command == "review.resolve") {
auto record = w.find("review", str(args, "id"));
if (!record)
throw Error("record_missing");
const auto choice = args.value("choice", size_t(0));
auto alternatives = record->value("alternatives", Json::array());
if (choice >= alternatives.size())
throw Error("invalid_change");
const auto chosen = alternatives[choice].at("value");
Json changes =
Json::array({{{"op", "update"},
{"table", "review"},
{"id", str(args, "id")},
{"set", {{"/resolved", true}, {"/selected_index", choice}, {"/chosen_value", chosen}}}}});
if (record->contains("entity") && record->contains("field"))
changes.push_back({{"op", "update"},
{"table", record->value("table", "players")},
{"id", (*record)["entity"]},
{"set", {{str(*record, "field"), chosen}}}});
return apply({{"changes", changes}}, {}, "resolve");
}
if (command == "asset.import" || command == "asset.edit")
return import_image(args);
if (command == "asset.preview") {
auto [bytes, extension] = asset_bytes(str(args, "key"));
auto raster = images::preview(bytes, extension, args.value("transform", Json::object()), 1024);
return {{"mimeType", "image/png"},
{"data", images::base64(images::encode_png(raster))},
{"width", raster.width},
{"height", raster.height}};
}
if (command == "asset.export") {
auto [bytes, extension] = asset_bytes(str(args, "key"));
auto data = images::encode_png(images::decode(bytes, extension, 2048));
auto target = path(str(args, "path"));
if (folded(utf8(target.extension())) != ".png")
throw Error("invalid_image");
write_atomic(target, data);
return {{"path", utf8(target)}};
}
throw Error("invalid_change", {{"command", command}});
}
} // namespace bmh::editor
+45
View File
@@ -0,0 +1,45 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "editor/world.hpp"
#include <mutex>
namespace bmh::editor {
// One command boundary for native widgets, MCP and synthetic tests. No command
// owns game rules or operates on a live career.
class Session {
public:
Json execute(const std::string &command, const Json &args = Json::object());
std::pair<std::string, std::string> asset_bytes(const std::string &key_or_path) const;
private:
struct Delta {
std::string table, id;
std::optional<Json> before, after;
};
struct FileDelta {
std::string name;
std::shared_ptr<const std::string> before, after;
};
struct Frame {
std::string label;
std::vector<Delta> changes;
std::vector<FileDelta> files;
uint64_t before = 0, after = 0;
};
mutable std::recursive_mutex mutex_;
std::unique_ptr<World> world_;
std::vector<Frame> history_;
size_t cursor_ = 0;
uint64_t revision_ = 0, state_ = 0, next_state_ = 1, saved_state_ = 0;
fs::path saved_path_;
fs::file_time_type saved_time_{};
uint64_t saved_size_ = 0;
World &world();
bool dirty() const;
Json info() const;
Json apply(const Json &, std::vector<FileDelta> files = {}, const std::string &label = "edit");
void frame(const Frame &, bool forward);
void replace(World value);
Json import_image(const Json &);
};
} // namespace bmh::editor
+75
View File
@@ -0,0 +1,75 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include <filesystem>
#include <map>
#include <memory>
#include <nlohmann/json.hpp>
#include <optional>
#include <set>
#include <stdexcept>
#include <string>
#include <string_view>
#include <vector>
namespace bmh::editor {
using Json = nlohmann::ordered_json;
namespace fs = std::filesystem;
struct Error : std::runtime_error {
std::string code;
Json details;
explicit Error(std::string key, Json info = Json::object())
: std::runtime_error(key), code(std::move(key)), details(std::move(info)) {}
};
inline std::string text(const Json &value) {
if (value.is_string())
return value.get<std::string>();
if (value.is_null())
return {};
if (value.is_object()) {
for (auto key : {"default", "known_as", "full"})
if (value.contains(key) && value[key].is_string() && !value[key].get<std::string>().empty())
return value[key].get<std::string>();
if (value.contains("first") || value.contains("last")) {
auto first = value.value("first", Json());
auto last = value.value("last", Json());
return text(first) + (text(first).empty() || text(last).empty() ? "" : " ") + text(last);
}
}
return value.dump();
}
inline std::string str(const Json &object, std::string_view key, const std::string &fallback = {}) {
auto it = object.find(std::string(key));
return it == object.end() || !it->is_string() ? fallback : it->get<std::string>();
}
inline std::string escaped(std::string_view value) {
std::string out;
for (auto c : value)
switch (c) {
case '&':
out += "&amp;";
break;
case '<':
out += "&lt;";
break;
case '>':
out += "&gt;";
break;
case '"':
out += "&quot;";
break;
case '\'':
out += "&#39;";
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
+1398
View File
File diff suppressed because it is too large. Load diff
+11
View File
@@ -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
+543
View File
@@ -0,0 +1,543 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "editor/world.hpp"
#include "content/digest.hpp"
#include "content/package.hpp"
#include "import/obw.hpp"
#include "launch/game_data.hpp"
#include <algorithm>
#include <cmath>
#include <functional>
#include <limits>
namespace bmh::editor {
namespace {
Json table(const std::string &name) { return {{"schema", name + "@1.1"}, {"items", Json::array()}}; }
bool date_valid(const Json &value) {
if (value.is_null())
return true;
if (!value.is_string())
return false;
auto s = value.get<std::string>();
if (s.size() != 10 || s[4] != '-' || s[7] != '-')
return false;
for (size_t i = 0; i < s.size(); ++i)
if (i != 4 && i != 7 && (s[i] < '0' || s[i] > '9'))
return false;
int y = std::stoi(s.substr(0, 4)), m = std::stoi(s.substr(5, 2)), d = std::stoi(s.substr(8));
static constexpr int days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
return y >= 1583 && m >= 1 && m <= 12 && d >= 1 &&
d <= days[m - 1] + (m == 2 && (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)));
}
void walk_refs(const Json &node, const std::function<void(const std::string &)> &emit, bool extension = false) {
if (node.is_object()) {
for (auto it = node.begin(); it != node.end(); ++it) {
if (it.key() == "id" || it.key().starts_with("x-") || it.key() == "sources")
continue;
if (it.value().is_string() &&
(it.key() == "nation" || it.key() == "team" || it.key() == "competition" || it.key() == "stadium" ||
it.key() == "owner" || it.key() == "person" || it.key() == "national_team" || it.key() == "photo" ||
it.key() == "crest" || it.key() == "trophy"))
emit(it.value());
else if ((it.key() == "nationalities" || it.key() == "members" || it.key() == "participants" ||
it.key() == "teams") &&
it.value().is_array()) {
for (const auto &value : it.value())
if (value.is_string())
emit(value);
} else if (it.value().is_object() || it.value().is_array())
walk_refs(it.value(), emit, extension);
}
} else if (node.is_array())
for (const auto &child : node)
walk_refs(child, emit, extension);
}
Json parse(const std::string &data, const std::string &file) {
try {
return Json::parse(data);
} catch (const Json::exception &e) {
throw Error("invalid_json", {{"file", file}, {"detail", e.what()}});
}
}
} // namespace
const std::vector<std::string> &World::tables() {
static const std::vector<std::string> names{"nations", "competitions", "clubs", "players", "stadiums",
"staff", "contracts", "finance", "rules", "calendar",
"assets", "review", "image-edits"};
return names;
}
std::string World::file_for(const std::string &name) {
if (name == "assets")
return "assets/index.json";
if (name == "review" || name == "image-edits")
return "x-editor/" + name + ".json";
return "world/" + name + ".json";
}
std::string World::identity(const Json &row, const std::string &name) {
return str(row, name == "assets" ? "key" : "id");
}
World World::blank(const std::string &title_value) {
World w;
w.manifest = {{"format", "openbmh-world"},
{"format_version", "1.1"},
{"min_reader", "1.1"},
{"kind", "world"},
{"title", {{"default", title_value}}},
{"generator", "OpenBMH Editor POC"},
{"provenance", "native"},
{"content_license", "user-supplied"},
{"start_date", "2026-07-01"},
{"currency", {{"code", "EUR"}, {"minor_units", 2}}},
{"languages", {"de", "en"}},
{"requires", {"editor:world-v1"}},
{"extensions", Json::array()},
{"x-editor", {{"profile", "editor-world-v1"}, {"playable", false}}}};
for (auto &name : tables())
w.docs_[file_for(name)] = table(name == "assets" ? "asset-index" : name);
w.docs_[file_for("rules")]["items"].push_back({{"id", "rule:unrated@1"},
{"type", "attribute_set"},
{"attribute_set", "unrated@1"},
{"fields", Json::object()}});
for (auto &[name, _] : w.docs_)
w.dirty_.insert(name);
return w;
}
World World::open(const fs::path &source, const std::string &start_date) {
World w;
const auto input = fs::absolute(source);
bool legacy = false;
if (fs::is_directory(input))
legacy = !fs::exists(input / "manifest.json");
else
legacy = folded(utf8(input.extension())) == ".exe";
if (legacy) {
if (!date_valid(start_date))
throw Error("invalid_date");
bmh::obw::Options options;
options.start_date = start_date;
auto docs = bmh::obw::import_installation(input, options);
for (auto &[name, bytes] : docs)
w.store->set(name, std::make_shared<const std::string>(std::move(bytes)));
w.imported = true;
} else
w.store = ArchiveStore::open(input);
w.manifest = parse(w.store->read("manifest.json"), "manifest.json");
if (str(w.manifest, "format") != "openbmh-world" || str(w.manifest, "kind") != "world")
throw Error("not_world");
auto version = str(w.manifest, "format_version");
if (!version.starts_with("1."))
throw Error("unsupported_version", {{"version", version}});
const bool editor = str(w.manifest.value("x-editor", Json::object()), "profile") == "editor-world-v1";
if (editor && (version != "1.1" || str(w.manifest, "min_reader") != "1.1" ||
w.manifest.value("x-editor", Json::object()).value("playable", true)))
throw Error("unsupported_version");
if (!editor) {
// Only bounded 1.0 Classic packages use the Classic validator. Its
// compatibility and seal checks are not relaxed by the new reader.
if (!w.imported) {
auto docs = bmh::obw::read(input);
if (docs.contains("x-classic/seal.json"))
bmh::content::verify(docs);
}
w.imported = true;
}
w.source_path = input;
w.load();
if (w.imported)
w.editor_profile();
return w;
}
void World::load() {
for (auto &name : tables()) {
auto file = file_for(name);
if (store->contains(file)) {
auto bytes = store->read(file);
auto value = parse(bytes, file);
if (!value.is_object() || !value.contains("items") || !value["items"].is_array())
throw Error("invalid_table", {{"file", file}});
original_[file] = std::move(bytes);
docs_[file] = std::move(value);
} else {
docs_[file] = table(name == "assets" ? "asset-index" : name);
dirty_.insert(file);
}
}
}
void World::editor_profile() {
manifest["x-editor"] = {{"profile", "editor-world-v1"},
{"playable", false},
{"original_manifest", manifest},
{"source_filename", utf8(source_path.filename())}};
manifest["format_version"] = "1.1";
manifest["min_reader"] = "1.1";
manifest["requires"] = Json::array({"editor:world-v1"});
manifest["generator"] = "OpenBMH Editor POC";
// The historical seal remains original evidence only. The editor profile
// deliberately cannot be passed to the Classic runtime as sealed content.
for (auto &comp : rows("competitions")) {
if (!comp.contains("members")) {
comp["members"] = Json::array();
for (auto &stage : comp.value("stages", Json::array()))
for (auto &slot : stage.value("slots", Json::array())) {
auto teams = slot.value("teams", Json::array());
if (slot.contains("team") && slot["team"].is_string())
teams.push_back(slot["team"]);
for (const auto &team : teams)
if (team.is_string()) {
const auto tid = team.get<std::string>();
if (str(comp, "type") == "league")
if (auto club = find("clubs", tid))
(*club)["competition"] = comp["id"];
if (std::find(comp["members"].begin(), comp["members"].end(), tid) == comp["members"].end())
comp["members"].push_back(tid);
}
}
}
}
for (auto &person : rows("players")) {
if (person.contains("x-legacy") && person["x-legacy"].contains("squad_row"))
person["squad_order"] = person["x-legacy"]["squad_row"];
}
touch("competitions");
touch("clubs");
touch("players");
}
Json &World::document(const std::string &name) { return docs_.at(file_for(name)); }
const Json &World::document(const std::string &name) const { return docs_.at(file_for(name)); }
Json &World::rows(const std::string &name) { return document(name)["items"]; }
const Json &World::rows(const std::string &name) const { return document(name).at("items"); }
const Json *World::find(const std::string &name, const std::string &id) const {
for (auto &row : rows(name))
if (identity(row, name) == id)
return &row;
return nullptr;
}
Json *World::find(const std::string &name, const std::string &id) {
return const_cast<Json *>(std::as_const(*this).find(name, id));
}
void World::touch(const std::string &name) { dirty_.insert(file_for(name)); }
void World::change(const std::string &name, const std::string &id, const std::optional<Json> &after) {
auto &values = rows(name);
for (auto i = values.begin(); i != values.end(); ++i)
if (identity(*i, name) == id) {
if (after)
*i = *after;
else
values.erase(i);
touch(name);
return;
}
if (after) {
values.push_back(*after);
touch(name);
}
}
std::string World::title(const Json &value, const std::string &language) const {
if (value.contains("name")) {
const auto &name = value["name"];
if (name.is_object() && name.contains(language) && name[language].is_string())
return name[language];
return text(name);
}
return str(value, "key", str(value, "id"));
}
Json World::statistics() const {
Json counts = Json::object();
for (auto &name : tables())
counts[name] = rows(name).size();
return {{"title", text(manifest.value("title", Json()))},
{"start_date", manifest.value("start_date", Json())},
{"format_version", manifest.value("format_version", Json())},
{"counts", counts},
{"source", utf8(source_path)},
{"imported", imported},
{"profile", "editor-world-v1"},
{"playable", false}};
}
Json World::query(const Json &args) const {
const auto name = str(args, "table", "clubs");
if (std::find(tables().begin(), tables().end(), name) == tables().end())
throw Error("unknown_table");
std::map<std::string, const Json *> clubs;
for (const auto &club : rows("clubs"))
clubs[str(club, "id")] = &club;
std::vector<const Json *> matches;
const auto search = folded(str(args, "search")), nation = str(args, "nation"), comp = str(args, "competition"),
team = str(args, "team");
for (const auto &row : rows(name)) {
const Json *club =
name == "clubs" ? &row : (clubs.contains(str(row, "team")) ? clubs[str(row, "team")] : nullptr);
if (!nation.empty() && str(row, "nation") != nation && (!club || str(*club, "nation") != nation))
continue;
if (!comp.empty() && str(row, "competition") != comp && (!club || str(*club, "competition") != comp))
continue;
if (!team.empty() && str(row, "team") != team && str(row, "owner") != team)
continue;
if (args.contains("role") && str(row, "role") != str(args, "role"))
continue;
if (name == "competitions" && args.value("leagues_only", false) && str(row, "type") != "league")
continue;
if (name == "review" && args.value("unresolved_only", false) && row.value("resolved", false))
continue;
if (!search.empty() && folded(title(row)).find(search) == std::string::npos &&
folded(identity(row, name)).find(search) == std::string::npos &&
(!club || folded(title(*club)).find(search) == std::string::npos))
continue;
matches.push_back(&row);
}
auto sort = str(args, "sort", "name");
bool descending = args.value("descending", false);
std::stable_sort(matches.begin(), matches.end(), [&](auto a, auto b) {
Json av = sort == "name" ? Json(folded(title(*a))) : a->value(sort, Json());
Json bv = sort == "name" ? Json(folded(title(*b))) : b->value(sort, Json());
if (av == bv)
return identity(*a, name) < identity(*b, name);
return descending ? av > bv : av < bv;
});
const auto offset = std::max<int64_t>(0, args.value("offset", int64_t(0)));
const auto limit = std::clamp<int64_t>(args.value("limit", int64_t(200)), 1, 200);
Json result = Json::array();
for (size_t i = size_t(std::min<int64_t>(offset, int64_t(matches.size())));
i < matches.size() && int64_t(result.size()) < limit; ++i)
result.push_back(*matches[i]);
return {{"items", std::move(result)}, {"total", matches.size()}, {"offset", offset}, {"limit", limit}};
}
std::vector<std::pair<std::string, std::string>> World::references(const std::string &id) const {
std::vector<std::pair<std::string, std::string>> found;
for (auto &name : tables())
if (name != "review" && name != "image-edits" && name != "assets")
for (auto &row : rows(name))
if (identity(row, name) != id) {
bool referenced = false;
walk_refs(row, [&](auto &ref) {
if (ref == id)
referenced = true;
});
if (referenced)
found.emplace_back(name, identity(row, name));
}
return found;
}
std::string World::asset_file(const std::string &key) const {
auto row = find("assets", key);
if (!row || !row->contains("files") || !(*row)["files"].is_object())
return {};
for (auto type : {"svg", "native", "default", "original", "512", "256", "128", "64"}) {
auto found = (*row)["files"].find(type);
if (found != (*row)["files"].end() && found->is_string() && store->contains(*found))
return *found;
}
for (auto &value : (*row)["files"])
if (value.is_string() && store->contains(value))
return value;
return {};
}
std::string World::portrait(const Json &person) const {
auto key = str(person, "photo");
auto file = asset_file(key.empty() ? "asset:player/" + str(person, "id") + "/photo" : key);
return file;
}
Json World::validate() const {
Json diagnostics = Json::array();
auto issue = [&](const std::string &severity, const std::string &code, const std::string &name,
const std::string &id, Json details = Json::object()) {
diagnostics.push_back(
{{"severity", severity}, {"code", code}, {"table", name}, {"id", id}, {"details", details}});
};
std::map<std::string, std::string> ids;
const auto editor = manifest.value("x-editor", Json::object());
const auto requirements = manifest.value("requires", Json::array());
if (str(manifest, "format") != "openbmh-world" || str(manifest, "kind") != "world" ||
str(manifest, "format_version") != "1.1" || str(manifest, "min_reader") != "1.1" || !editor.is_object() ||
str(editor, "profile") != "editor-world-v1" || !editor.contains("playable") || editor["playable"] != false ||
!requirements.is_array() ||
std::find(requirements.begin(), requirements.end(), Json("editor:world-v1")) == requirements.end())
issue("error", "invalid_manifest", "manifest", "manifest");
if (!date_valid(manifest.value("start_date", Json())))
issue("error", "invalid_date", "manifest", "manifest");
std::map<std::string, const Json *> attribute_sets;
for (auto &rule : rows("rules"))
if (str(rule, "type") == "attribute_set") {
auto key = str(rule, "attribute_set", str(rule, "id"));
attribute_sets[key] = &rule;
if (key.starts_with("rule:"))
attribute_sets[key.substr(5)] = &rule;
}
for (const auto &name : tables()) {
if (name == "image-edits" || name == "review")
continue;
for (const auto &row : rows(name)) {
auto id = identity(row, name);
if (id.empty() || !ids.emplace(id, name).second)
issue("error", "duplicate_id", name, id);
if (name != "assets" && name != "calendar" && name != "rules" && title(row).empty())
issue("warning", "missing_name", name, id);
if (name == "players") {
if (!date_valid(row.value("born", Json())))
issue("error", "invalid_date", name, id);
if (!row.contains("born") && !row.contains("age_at_start"))
issue("warning", "missing_birthday", name, id);
if (row.contains("born") && row["born"].is_null())
issue("warning", "missing_birthday", name, id);
const auto attrs = row.value("attributes", Json::object());
if (!attrs.is_object()) {
issue("error", "invalid_attributes", name, id);
continue;
}
const auto set = attribute_sets.find(str(row, "attribute_set"));
if (set == attribute_sets.end())
issue("warning", "unknown_attribute_set", name, id);
else {
auto fields = set->second->value("fields", Json::object());
for (auto it = attrs.begin(); it != attrs.end(); ++it) {
if (it->is_null() || !fields.contains(it.key()))
continue;
const auto &field = fields[it.key()];
if (!it->is_number_integer() ||
it->get<int64_t>() < field.value("min", std::numeric_limits<int64_t>::min()) ||
it->get<int64_t>() > field.value("max", std::numeric_limits<int64_t>::max()))
issue("error", "attribute_range", name, id, {{"field", it.key()}});
}
}
}
}
}
for (auto &name : tables())
if (name != "review" && name != "image-edits")
for (auto &row : rows(name))
walk_refs(row, [&](const std::string &ref) {
if (!ref.empty() && !ids.contains(ref) && !ref.starts_with("asset:"))
issue("error", "missing_reference", name, identity(row, name), {{"reference", ref}});
});
const std::map<std::string, std::string> reference_types{{"team", "clubs"}, {"owner", "clubs"},
{"nation", "nations"}, {"competition", "competitions"},
{"stadium", "stadiums"}, {"national_team", "clubs"}};
for (auto &name : tables())
if (name != "review" && name != "image-edits")
for (const auto &row : rows(name)) {
for (const auto &[field, target] : reference_types)
if (row.contains(field) && !row[field].is_null()) {
const auto key = str(row, field);
if (!row[field].is_string() || (!key.empty() && ids.contains(key) && ids.at(key) != target))
issue("error", "missing_reference", name, identity(row, name),
{{"field", field}, {"expected_table", target}});
}
for (const auto &[field, target] :
std::map<std::string, std::string>{{"nationalities", "nations"}, {"members", "clubs"}})
if (row.contains(field)) {
if (!row[field].is_array())
issue("error", "missing_reference", name, identity(row, name), {{"field", field}});
else
for (const auto &key : row[field])
if (!key.is_string() ||
(ids.contains(key.get<std::string>()) && ids.at(key.get<std::string>()) != target))
issue("error", "missing_reference", name, identity(row, name),
{{"field", field}, {"expected_table", target}});
}
}
for (auto &asset : rows("assets")) {
if (asset_file(str(asset, "key")).empty())
issue("warning", "missing_asset", "assets", str(asset, "key"));
}
for (auto &review : rows("review"))
if (!review.value("resolved", false))
issue("warning", "review_open", "review", str(review, "id"));
return diagnostics;
}
void World::save(const fs::path &destination) const {
if (imported && !source_path.empty() &&
fs::absolute(destination).lexically_normal() == source_path.lexically_normal())
throw Error("preserve_source");
const auto problems = validate();
for (auto &row : problems)
if (row["severity"] == "error")
throw Error("validation_failed", {{"diagnostics", problems}});
std::map<std::string, std::string> docs{{"manifest.json", manifest.dump(2)}};
for (const auto &[file, value] : docs_)
docs[file] = !dirty_.contains(file) && original_.contains(file) ? original_.at(file) : value.dump(2);
store->save(destination, docs);
}
World World::demo() {
auto w = blank("OpenBMH Editor – Demo");
w.rows("nations").push_back({{"id", "nation:de"},
{"name", {{"default", "Deutschland"}, {"en", "Germany"}}},
{"confederation", "uefa"},
{"playable", true}});
w.rows("competitions")
.push_back({{"id", "comp:demo"},
{"name", {{"default", "Demo-Liga"}, {"en", "Demo league"}}},
{"nation", "nation:de"},
{"type", "league"},
{"tier", 1},
{"visible", true},
{"members", {"club:north", "club:south"}},
{"stages", Json::array()}});
w.rows("rules").push_back({{"id", "demo@1"},
{"type", "attribute_set"},
{"fields",
{{"strength", {{"min", 0}, {"max", 99}}},
{"technique", {{"min", 0}, {"max", 99}}},
{"condition", {{"min", 0}, {"max", 100}}},
{"form", {{"min", 0}, {"max", 99}}}}}});
for (int i = 0; i < 2; ++i) {
auto id = i ? "club:south" : "club:north";
auto stadium = i ? "stadium:south" : "stadium:north";
const auto key = std::string("asset:demo/") + (i ? "south" : "north");
const auto file = std::string("assets/demo/") + (i ? "south.svg" : "north.svg");
const auto color = i ? "#b44b5c" : "#3698aa";
std::string svg = "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"128\" "
"height=\"144\" viewBox=\"0 0 128 144\"><path d=\"M10 8h108v80q0 26-54 "
"48Q10 114 10 88Z\" fill=\"" +
std::string(color) +
"\" stroke=\"#e5efef\" stroke-width=\"6\"/><path d=\"M34 98V40h15l30 "
"38V40h15v58H79L49 60v38Z\" fill=\"#fff\"/></svg>";
w.store->set(file, std::make_shared<const std::string>(svg));
w.rows("assets").push_back({{"key", key},
{"name", {{"default", i ? "Südstadt" : "Nordstadt"}}},
{"files", {{"svg", file}}},
{"source", "synthetic-demo"},
{"license", "GPL-3.0-only"},
{"kind", "vector"},
{"width", 128},
{"height", 144}});
w.rows("clubs").push_back({{"id", id},
{"name", {{"default", i ? "SV Südstadt" : "FC Nordstadt"}}},
{"short_name", i ? "Südstadt" : "Nordstadt"},
{"type", "club"},
{"nation", "nation:de"},
{"competition", "comp:demo"},
{"stadium", stadium},
{"crest", key},
{"colors", {i ? "#9c3949" : "#277c8b", "#ffffff"}},
{"founded", 1900 + i}});
w.rows("stadiums")
.push_back({{"id", stadium},
{"name", {{"default", i ? "Südpark" : "Nordpark"}}},
{"owner", id},
{"capacity", {{"total", 22000 + 6000 * i}, {"seated", 18000 + 6000 * i}, {"standing", 4000}}}});
for (int n = 0; n < 26; ++n) {
w.rows("players").push_back(
{{"id", "player:demo-" + std::to_string(i * 26 + n)},
{"name", {{"first", n % 2 ? "Alex" : "Robin"}, {"last", "Spieler " + std::to_string(i * 26 + n + 1)}}},
{"born", "2000-03-12"},
{"nationalities", {"nation:de"}},
{"positions",
{n < 2 ? "gk"
: n < 10 ? "def"
: n < 18 ? "mid"
: "fwd"}},
{"team", id},
{"squad_number", n + 1},
{"squad_order", n},
{"attribute_set", "demo@1"},
{"attributes",
{{"strength", 68 + (n % 15)}, {"technique", 65 + n % 20}, {"condition", 90}, {"form", 70}}}});
}
}
w.rows("staff").push_back({{"id", "staff:referee-demo"},
{"name", {{"default", "Kim Beispiel"}}},
{"role", "referee"},
{"nation", "nation:de"},
{"attributes", {{"strictness", 2}}}});
return w;
}
} // namespace bmh::editor
+42
View File
@@ -0,0 +1,42 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "editor/archive.hpp"
namespace bmh::editor {
class World {
public:
Json manifest;
std::shared_ptr<ArchiveStore> store = std::make_shared<ArchiveStore>();
fs::path source_path;
bool imported = false;
static World open(const fs::path &, const std::string &start_date = "2026-07-01");
static World blank(const std::string &title = "Untitled world");
static World demo();
Json &document(const std::string &);
const Json &document(const std::string &) const;
Json &rows(const std::string &);
const Json &rows(const std::string &) const;
const Json *find(const std::string &, const std::string &) const;
Json *find(const std::string &, const std::string &);
void change(const std::string &table, const std::string &id, const std::optional<Json> &);
void touch(const std::string &table);
Json query(const Json &) const;
Json validate() const;
Json statistics() const;
std::string asset_file(const std::string &key) const;
std::string portrait(const Json &) const;
std::string title(const Json &entity, const std::string &language = "de") const;
std::vector<std::pair<std::string, std::string>> references(const std::string &id) const;
void save(const fs::path &) const;
static std::string file_for(const std::string &table);
static std::string identity(const Json &row, const std::string &table);
static const std::vector<std::string> &tables();
private:
std::map<std::string, Json> docs_;
std::map<std::string, std::string> original_;
std::set<std::string> dirty_;
void load();
void editor_profile();
};
} // namespace bmh::editor