Restore direct-installation Classic baseline for OpenBMH 1.0 (by Codex)

This commit is contained in:
Codex committed 2026-10-30 14:19:25 +01:00
1 parent c8f04d0099
commit c3704878d6
255 files changed
+311 -21131

No files matched your search

-258
View File
@@ -1,258 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "editor/comparison.hpp"
#include "editor/mcp.hpp"
#include "editor/session.hpp"
#include <cmath>
#include <iostream>
#include <limits>
using namespace bmh::editor;
namespace {
int checks = 0;
void check(bool value, const char *message) {
++checks;
if (!value)
throw std::runtime_error(message);
}
template <class Fn> void rejects(const char *code, Fn fn) {
try {
fn();
} catch (const Error &error) {
check(error.code == code, "unexpected rejection");
return;
}
throw std::runtime_error(std::string("accepted: ") + code);
}
Json find(const Json &items, const std::string &id) {
for (const auto &row : items)
if (str(row, "id") == id)
return row;
throw std::runtime_error("missing fixture row " + id);
}
World fixture() {
auto world = World::blank("Synthetic comparison");
world.rows("nations").push_back({{"id", "nation:de"}, {"name", "Testland"}});
world.rows("competitions") = Json::array({{{"id", "comp:first"},
{"name", {{"de", "Testliga"}, {"en", "Test league"}}},
{"nation", "nation:de"},
{"type", "league"},
{"members", {"club:north", "club:south"}}},
{{"id", "comp:empty"},
{"name", "Empty league"},
{"nation", "nation:de"},
{"type", "league"},
{"members", {"club:empty"}}},
{{"id", "comp:cup"},
{"name", "Not a league"},
{"nation", "nation:de"},
{"type", "cup"},
{"members", {"club:north"}}}});
for (const std::string id : {"north", "south", "empty"})
world.rows("clubs").push_back(
{{"id", "club:" + id}, {"name", id}, {"type", "club"}, {"nation", "nation:de"}});
// No club.competition: membership-only imported worlds must work too.
world.rows("rules").push_back(
{{"id", "rule:bmh-classic@1"},
{"type", "attribute_set"},
{"fields", {{"strength", {{"min", 0}, {"max", 99}}}, {"form", {{"min", 0}, {"max", 127}}}}}});
const Json ratings{90, 70, 50, nullptr, 90, 99};
const std::vector<std::string> ids{"a", "b", "c", "d", "free", "duplicate"};
for (size_t i = 0; i < ids.size(); ++i) {
const auto team = i < 2 || i == 5 ? Json("club:north") : i < 4 ? Json("club:south") : Json();
world.rows("players").push_back(
{{"id", "player:" + ids[i]},
{"name", ids[i]},
{"team", team},
{"born", "2000-01-01"},
{"positions", {"mid"}},
{"attribute_set", "bmh-classic@1"},
{"attributes", {{"strength", ratings[i]}, {"form", i ? Json(100) : Json()}}}});
}
world.rows("players")[1]["x-simulation"]["squad_role"] = "source-reserve";
world.rows("players")[5]["x-simulation"]["squad_role"] = "source-only-duplicate";
auto contract = [&](std::string id, std::string person, std::string team, int64_t salary,
std::string start = "2026-07-01", std::string end = "2027-06-30") {
world.rows("contracts")
.push_back({{"id", "contract:" + id},
{"name", id},
{"person", "player:" + person},
{"team", "club:" + team},
{"salary", salary},
{"start", start},
{"end", end}});
};
contract("a", "a", "north", 9000);
contract("b", "b", "north", 10000);
contract("c", "c", "south", 50000);
contract("c-conflict", "c", "south", 60000);
contract("d", "d", "south", 0); // Explicit zero is known, not missing.
contract("duplicate", "duplicate", "north", 99999999);
contract("a-expired", "a", "north", 1000000, "2025-07-01", "2026-06-30");
contract("a-future", "a", "north", 2000000, "2026-07-02", "2027-06-30");
contract("a-old-team", "a", "south", 3000000);
world.rows("staff").push_back({{"id", "staff:test"}, {"name", "Staff"}});
world.rows("contracts")
.push_back({{"id", "contract:staff"},
{"name", "Staff contract"},
{"person", "staff:test"},
{"team", "club:north"},
{"salary", 9999999}});
return world;
}
Json compare(const World &world, Json args = Json::object()) {
return query_comparison(comparison_data(world, args), args);
}
} // namespace
int main() {
const auto root = fs::temp_directory_path() / new_id("comparison-tests-");
fs::create_directory(root);
struct Cleanup {
fs::path root;
~Cleanup() {
std::error_code ec;
fs::remove_all(root, ec);
}
} cleanup{root};
try {
auto world = fixture();
const auto original_players = world.rows("players"), original_contracts = world.rows("contracts");
auto players = compare(world, {{"sort", "salary"}, {"descending", true}});
check(players["total"] == 5 && players["excluded_players"] == 1,
"all real rows, reserve included, source duplicate excluded");
check(players["items"][0]["id"] == "player:b" && players["items"][1]["salary"] == 9000,
"numeric salary sort and active current-team contracts");
check(players["items"][2]["salary"] == 0 && players["items"][3]["salary"].is_null(),
"zero before missing salary descending");
check(find(players["items"], "player:c")["salary_ambiguous"] == 1,
"conflicting active contracts stay unknown");
check(players["currency"]["minor_units"] == 2, "integer currency units retained");
players = compare(world, {{"sort", "salary"}});
check(players["items"][0]["id"] == "player:d" && players["items"][4]["salary"].is_null(),
"missing salary last ascending too");
auto rating = compare(
world, {{"sort", "attributes.strength"}, {"descending", true}, {"offset", 1}, {"limit", 1}});
check(rating["items"][0]["id"] == "player:free" && rating["total"] == 5,
"stable tie by ID and full-result sort before paging");
check(compare(world, {{"team", "club:north"}})["total"] == 2,
"team filter excludes source duplicate");
check(compare(world, {{"nation", "nation:de"}, {"competition", "comp:first"}})["total"] == 4,
"league and nation follow membership fallback");
auto teams =
compare(world, {{"table", "clubs"}, {"sort", "attributes.strength"}, {"descending", true}});
auto north = find(teams["items"], "club:north"), south = find(teams["items"], "club:south");
check(north["attributes"]["strength"] == 80 && north["salary_total"] == 19000,
"club means and player-only payroll");
check(north["salary_average"] == 9500 && north["salary_complete"] == true,
"mean wage and coverage complete");
check(south["attributes"]["strength"] == 50 && south["attribute_counts"]["strength"] == 1,
"unknown attributes excluded from mean denominator");
check(south["salary_total"] == 0 && south["salary_known"] == 1 && south["salary_unknown"] == 1 &&
south["salary_complete"] == false,
"partial payroll distinguished from complete zero");
check(find(teams["items"], "club:empty")["salary_total"].is_null(),
"empty team is not a zero-payroll team");
auto leagues = compare(world, {{"table", "leagues"}, {"language", "en"}});
auto league = find(leagues["items"], "comp:first");
check(leagues["total"] == 2 && league["club_count"] == 2 && league["player_count"] == 4,
"cups excluded; exact unique league population");
check(league["attributes"]["strength"] == 70,
"league strength is player-weighted, not a mean of club means");
check(league["salary_total"] == 19000 && league["salary_average"] == 6333 &&
league["salary_known"] == 3,
"league payroll uses known contracts once and integer rounded mean");
check(league["name"] == "Test league", "localized names");
check(world.rows("players") == original_players && world.rows("contracts") == original_contracts,
"comparison never changes source records");
auto classic = world;
classic.rows("contracts") = Json::array();
classic.manifest["currency"] = {{"code", "GBP"}, {"minor_units", 0}};
check(compare(classic)["items"][0]["salary"].is_null() &&
compare(classic)["currency"]["code"] == "GBP",
"Classic without contracts remains unknown in its actual currency");
world.rows("rules").push_back(
{{"id", "rule:fc@1"},
{"type", "attribute_set"},
{"attribute_set", "fc@1"},
{"fields", {{"overall", {{"min", 0}, {"max", 99}}}, {"strength", {{"min", 0}, {"max", 99}}}}}});
auto &modern = world.rows("players")[1];
modern["attribute_set"] = "fc@1";
modern["attributes"] = {{"overall", 85}, {"strength", 35}};
check(compare(world)["mixed_attribute_sets"] == true && compare(world)["attributes"].empty(),
"different strength systems are never implicitly combined");
rejects("invalid_comparison_sort", [&] { compare(world, {{"sort", "attributes.strength"}}); });
auto fc = compare(world, {{"table", "clubs"}, {"attribute_set", "fc@1"}});
check(find(fc["items"], "club:north")["attributes"]["overall"] == 85 &&
find(fc["items"], "club:north")["player_count"] == 1,
"attribute system filter also defines aggregation population");
rejects("invalid_attribute_set", [&] { compare(world, {{"attribute_set", "unknown@1"}}); });
rejects("unknown_table", [&] { compare(world, {{"table", "staff"}}); });
auto many = fixture();
many.rows("players") = Json::array();
many.rows("contracts") = Json::array();
for (int i = 0; i < 231; ++i)
many.rows("players").push_back({{"id", "player:" + std::to_string(i)},
{"name", std::to_string(i)},
{"attribute_set", "synthetic@1"},
{"attributes", {{"rating", i}}}});
const auto second_page =
compare(many, {{"sort", "attributes.rating"}, {"descending", true}, {"offset", 200}});
check(second_page["total"] == 231 && second_page["items"].size() == 31 &&
second_page["items"][0]["attributes"]["rating"] == 30,
"sorting spans all pages, no 200-row truncation");
auto overflow = fixture();
overflow.rows("contracts")[0]["salary"] = std::numeric_limits<int64_t>::max();
const auto extreme = find(compare(overflow, {{"table", "clubs"}})["items"], "club:north");
check(extreme["salary_overflow"] == true && extreme["salary_total"].is_null(),
"payroll overflow never wraps into a plausible negative value");
auto invalid = fixture();
invalid.rows("contracts")[0]["start"] = 20260701;
check(find(compare(invalid)["items"], "player:a")["salary"].is_null(),
"malformed contract dates are not silently treated as open bounds");
invalid.rows("contracts")[1]["salary"] = -1;
check(find(compare(invalid)["items"], "player:b")["salary"].is_null(),
"invalid salary is unknown, not a negative payroll credit");
invalid.manifest["start_date"] = nullptr;
check(find(compare(invalid)["items"], "player:d")["salary"].is_null(),
"unknown world date does not substitute the wall clock");
invalid.manifest["x-simulation"] = nullptr;
check(compare(invalid)["fictional_completion"] == false,
"unrecognized optional extension metadata does not break comparisons");
auto saved = fixture();
saved.save(root / "fixture.obw");
Session session;
session.execute("open", {{"path", utf8(root / "fixture.obw")}});
const auto info = session.execute("info");
const auto projection = session.execute("compare", {{"table", "clubs"}});
check(info == session.execute("info") && info["dirty"] == false,
"session comparison is read-only including revision and undo state");
session.execute("apply", {{"changes", Json::array({{{"table", "players"},
{"id", "player:a"},
{"set", {{"/attributes/strength", 80}}}}})}});
check(find(session.execute("compare", {{"table", "clubs"}})["items"],
"club:north")["attributes"]["strength"] == 75,
"cached comparison refreshes after an edit");
session.execute("undo");
check(session.execute("compare", {{"table", "clubs"}})["items"] == projection["items"],
"cached comparison refreshes after undo");
McpServer server(session);
const auto reply =
server.dispatch({{"jsonrpc", "2.0"},
{"id", 1},
{"method", "tools/call"},
{"params",
{{"name", "editor_compare"},
{"arguments", {{"table", "leagues"}, {"sort", "salary_total"}}}}}});
check(!reply["result"].value("isError", false) && reply["result"]["structuredContent"]["total"] == 2,
"MCP uses the same comparison projection");
bool read_only = false;
for (const auto &tool : McpServer::tools())
if (tool["name"] == "editor_compare")
read_only = tool["annotations"]["readOnlyHint"] == true;
check(read_only, "MCP comparison advertises read-only semantics");
std::cout << checks << " editor comparison checks passed\n";
return 0;
} catch (const std::exception &error) {
std::cerr << error.what() << '\n';
return 1;
}
}
-292
View File
@@ -1,292 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "editor/images.hpp"
#include "editor/mcp.hpp"
#include "editor/session.hpp"
#include <httplib.h>
#include <cstdlib>
#include <iostream>
#include <thread>
#ifdef _WIN32
#define NOMINMAX
#include <windows.h>
#endif
using namespace bmh::editor;
namespace {
int checks = 0;
void check(bool result, const char *message) {
++checks;
if (!result)
throw std::runtime_error(message);
}
template <class Fn> void rejects(const char *code, Fn fn) {
try {
fn();
} catch (const Error &error) {
check(error.code == code, "unexpected rejection code");
return;
}
throw std::runtime_error(std::string("accepted: ") + code);
}
Json update(const char *table, const char *id, Json set) {
return {{"changes", Json::array({{{"table", table}, {"id", id}, {"set", set}}})}};
}
Json row(Session &session, const char *table, const char *id) {
return session.execute("get", {{"table", table}, {"id", id}})["record"];
}
} // namespace
int main() {
auto root = fs::temp_directory_path() / new_id("editor-test-");
fs::create_directory(root);
struct Cleanup {
fs::path root;
~Cleanup() {
std::error_code ec;
fs::remove_all(root, ec);
}
} cleanup{root};
try {
Session s;
s.execute("demo");
const auto generation = s.execute("info")["world_generation"];
check(s.execute("list", {{"table", "players"}})["total"] == 52, "all squads retained");
check(s.execute("list", {{"table", "players"}, {"team", "club:north"}, {"limit", 24}})["items"].size() == 24,
"24 view");
check(s.execute("list", {{"table", "players"}, {"team", "club:north"}, {"offset", 24}})["items"].size() == 2,
"remaining squad not discarded");
auto initial = row(s, "players", "player:demo-0");
const auto revision = s.execute("info")["revision"];
auto change = update("players", "player:demo-0", {{"/name/last", "Änderung"}, {"/attributes/strength", 99}});
change["expected_revision"] = revision;
s.execute("apply", change);
check(row(s, "players", "player:demo-0")["name"]["last"] == "Änderung", "edit applied");
rejects("stale_revision", [&] { s.execute("apply", change); });
s.execute("undo");
check(row(s, "players", "player:demo-0") == initial, "undo complete row");
check(s.execute("info")["revision"] > revision, "revision monotonic across undo");
check(s.execute("info")["world_generation"] == generation,
"edits and undo keep navigation world identity");
s.execute("redo");
check(row(s, "players", "player:demo-0")["attributes"]["strength"] == 99, "redo");
rejects("validation_failed",
[&] { s.execute("apply", update("players", "player:demo-0", {{"/attributes/strength", 999}})); });
check(row(s, "players", "player:demo-0")["attributes"]["strength"] == 99, "failed edit rolled back");
rejects("validation_failed",
[&] { s.execute("apply", update("players", "player:demo-0", {{"/born", "2001-02-29"}})); });
rejects("record_referenced", [&] {
s.execute("apply",
{{"changes", Json::array({{{"op", "delete"}, {"table", "clubs"}, {"id", "club:north"}}})}});
});
check(!row(s, "clubs", "club:north").empty(), "delete rolled back");
s.execute("roster.swap", {{"first", "player:demo-0"}, {"second", "player:demo-26"}});
check(row(s, "players", "player:demo-0")["team"] == "club:south", "roster swap first");
check(row(s, "players", "player:demo-26")["team"] == "club:north", "roster swap second");
s.execute("undo");
auto squad =
s.execute("list", {{"table", "players"}, {"team", "club:north"}, {"sort", "squad_order"}})["items"];
Json reversed = Json::array();
for (auto it = squad.rbegin(); it != squad.rend(); ++it)
reversed.push_back((*it)["id"]);
s.execute("roster.order", {{"team", "club:north"}, {"players", reversed}});
check(row(s, "players", "player:demo-25")["squad_order"] == 0, "complete squad reorder");
s.execute("undo");
check(row(s, "players", "player:demo-0")["squad_order"] == 0, "squad order undo");
rejects("invalid_change", [&] {
s.execute("roster.order", {{"team", "club:north"}, {"players", Json::array({"player:demo-0"})}});
});
rejects("validation_failed",
[&] { s.execute("apply", update("players", "player:demo-0", {{"/team", "nation:de"}})); });
rejects("immutable_id",
[&] { s.execute("apply", update("manifest", "manifest", {{"/x-editor/playable", true}})); });
s.execute("apply",
{{"changes",
Json::array(
{{{"op", "create"}, {"table", "competitions"}, {"id", "comp:second"}, {"name", "Second"}}})}});
s.execute("apply", update("clubs", "club:north", {{"/competition", "comp:second"}}));
check(row(s, "competitions", "comp:second")["members"] == Json::array({"club:north"}), "new league membership");
check(row(s, "competitions", "comp:demo")["members"] == Json::array({"club:south"}),
"old league membership removed");
s.execute("undo");
check(row(s, "competitions", "comp:demo")["members"].size() == 2, "membership undo atomic");
const auto image = images::Raster{2, 2, {255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 128}};
const auto png = images::encode_png(image);
write_atomic(root / "input.png", png);
check(images::decode(png, ".png").pixels == image.pixels, "PNG lossless RGBA");
// Authored synthetic pixels: a solid teal 17x19 VP8 image and the
// same four RGBA pixels as above encoded as VP8L, including alpha.
const std::string webp_lossy(
"\x52\x49\x46\x46\x4a\x00\x00\x00\x57\x45\x42\x50\x56\x50\x38\x20"
"\x3e\x00\x00\x00\x90\x03\x00\x9d\x01\x2a\x11\x00\x13\x00\x3e\x31"
"\x18\x8a\x43\xa2\x21\xa1\x14\x04\x00\x20\x03\x04\xb2\x80\x3b\x00"
"\x7e\x00\x7e\x00\x00\x49\x95\x7c\x00\x00\xfe\xe8\x38\xbf\xff\xf6"
"\x96\x42\x15\xd7\xfc\x95\x7f\xff\xee\x9e\x90\x81\xa3\xfe\x4a\x00\x00\x00", 82);
const std::string webp_lossless(
"\x52\x49\x46\x46\x30\x00\x00\x00\x57\x45\x42\x50\x56\x50\x38\x4c"
"\x23\x00\x00\x00\x2f\x01\x40\x00\x10\x1f\x20\x10\x48\xde\x1f\x3a"
"\x8d\xf9\x17\x10\x14\xfc\x1f\x9d\x80\xa0\xe8\xba\xe5\x22\x66\x0f"
"\xc2\x0d\x18\x22\xfa\x1f\x02\x00", 56);
const auto webp = images::decode(webp_lossy, ".webp");
check(webp.width == 17 && webp.height == 19 && webp.pixels.size() == 17 * 19 * 4 &&
std::abs(int(webp.pixels[0]) - 40) <= 4 && std::abs(int(webp.pixels[1]) - 140) <= 4 &&
std::abs(int(webp.pixels[2]) - 200) <= 4 && webp.pixels[3] == 255,
"WebP lossy colour and dimensions");
check(images::decode(webp_lossless, ".webp").pixels == image.pixels, "WebP lossless RGBA");
check(images::transform(png, ".png", Json::object()).bytes == png, "identity preserves exact bytes");
auto flip = images::decode(images::transform(png, ".png", {{"flip_x", true}}).bytes, ".png");
check(flip.pixels[1] == 255 && flip.pixels[4] == 255, "horizontal mirror pixels");
auto rotation = images::transform(png, ".png", {{"angle", 90.0}});
check(rotation.width == 2 && rotation.height == 2, "rotation bounds");
auto svg = images::silhouette();
check(images::transform(svg, ".svg", {}).bytes == svg, "identity keeps SVG");
auto vector =
images::transform(svg, ".svg", {{"angle", 17.25}, {"flip_y", true}, {"crop", {{"x", .1}, {"width", .8}}}});
check(vector.extension == ".svg" && vector.bytes.find("17.25") != std::string::npos,
"arbitrary transform remains SVG");
rejects("external_svg_resource", [&] {
images::decode("<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"10\" "
"height=\"10\"><image href=\"file:///tmp/test.png\"/></svg>",
".svg");
});
auto imported = s.execute("asset.import", {{"file", utf8(root / "input.png")},
{"key", "asset:test"},
{"target", {{"table", "players"}, {"id", "player:demo-0"}}}});
check(row(s, "players", "player:demo-0")["photo"] == "asset:test", "image assigned");
check(s.asset_bytes("asset:test").first == png, "source exact on import");
rejects("record_referenced", [&] {
s.execute("apply",
{{"changes", Json::array({{{"table", "assets"}, {"id", "asset:test"}, {"op", "delete"}}})}});
});
s.execute("apply", update("players", "player:demo-1", {{"/photo", "asset:test"}}));
s.execute("asset.edit", {{"key", "asset:individual"},
{"source_key", "asset:test"},
{"transform", {{"angle", 18.0}}},
{"target", {{"table", "players"}, {"id", "player:demo-0"}, {"field", "photo"}}}});
check(row(s, "players", "player:demo-0")["photo"] == "asset:individual", "individual image assigned");
check(row(s, "players", "player:demo-1")["photo"] == "asset:test" && s.asset_bytes("asset:test").first == png,
"shared fallback and other person remain unchanged");
s.execute("undo");
check(row(s, "players", "player:demo-0")["photo"] == "asset:test", "image assignment undo atomic");
const auto isolated = s.execute(
"asset.import", {{"file", utf8(root / "input.png")},
{"key", "asset:test"},
{"transform", {{"flip_y", true}}},
{"target", {{"table", "players"}, {"id", "player:demo-0"}, {"field", "photo"}}}});
check(isolated["key"] != "asset:test" && s.asset_bytes("asset:test").first == png,
"targeted import cannot overwrite another entity's shared image");
s.execute("undo");
s.execute("asset.edit", {{"key", "asset:test"}, {"transform", {{"angle", 30.5}}}});
auto metadata = row(s, "assets", "asset:test")["x-editor"];
check(metadata["transform"]["angle"] == 30.5, "float angle metadata");
check(s.asset_bytes(metadata["original"].get<std::string>()).first == png, "original retained");
s.execute("undo");
check(s.asset_bytes("asset:test").first == png, "image undo restores native");
s.execute("redo");
s.execute("save", {{"path", utf8(root / "world.obw")}});
check(s.execute("info")["dirty"] == false, "save checkpoint");
s.execute("undo");
check(s.execute("info")["dirty"] == true, "undo away from save dirty");
s.execute("redo");
check(s.execute("info")["dirty"] == false, "redo back to save clean");
Session reopened;
reopened.execute("open", {{"path", utf8(root / "world.obw")}});
check(row(reopened, "assets", "asset:test")["x-editor"]["transform"]["angle"] == 30.5,
"roundtrip float transform");
reopened.execute("save"); // Snapshot permits atomic overwrite on every platform.
auto w = World::open(root / "world.obw");
const std::string opaque = "{\"future\":1.125,\"ignored\":{\"preserve\":true}}\n";
w.store->set("x-future/notes.json", std::make_shared<const std::string>(opaque));
w.save(root / "future.obw");
auto future = World::open(root / "future.obw");
future.save(root / "future2.obw");
check(ArchiveStore::open(root / "future2.obw")->read("x-future/notes.json") == opaque,
"unknown extension byte preservation");
const auto unpacked = root / "unpacked";
fs::create_directory(unpacked);
auto original_store = ArchiveStore::open(root / "future.obw");
for (const auto &name : original_store->names()) {
const auto file = unpacked / path(name);
fs::create_directories(file.parent_path());
write_atomic(file, original_store->read(name));
}
auto snapshot = ArchiveStore::open(unpacked);
write_atomic(unpacked / "x-future/notes.json", "external modification");
check(snapshot->read("x-future/notes.json") == opaque, "unpacked source snapshot stable");
check(!safe_name("../bad") && !safe_name("/bad") && !safe_name("C:/bad") && safe_name("assets/a.svg"),
"archive paths");
rejects("obw_only", [&] { future.save(root / "legacy.dat"); });
auto options = Options::load(root / "settings.json");
check(options.token.size() >= 64 && options.mcp_enabled, "local MCP enabled with token");
options.apply({{"language", "en"}, {"theme", "silver"}, {"mcp_port", 0}});
options.save();
check(Options::load(root / "settings.json").language == "en", "persistent language");
#ifdef _WIN32
{
wchar_t old_value[32768]{};
const auto length = GetEnvironmentVariableW(L"APPDATA", old_value, 32768);
struct Restore {
std::wstring value;
bool present;
~Restore() { SetEnvironmentVariableW(L"APPDATA", present ? value.c_str() : nullptr); }
} restore{old_value, length > 0};
const auto profile = root / L"Profil-ÄÖÜ";
SetEnvironmentVariableW(L"APPDATA", profile.c_str());
const auto native_options = Options::load();
check(native_options.settings_file == profile / "OpenBMH/editor.json", "Unicode Windows profile path");
check(fs::is_regular_file(native_options.settings_file), "Unicode Windows settings saved");
}
#endif
check(tr("de", "clubs") != tr("en", "clubs"), "bilingual labels");
{
Session reopened;
reopened.execute("demo");
const auto identity = reopened.execute("info")["world_generation"];
reopened.execute("save", {{"path", utf8(root / "navigation-world.obw")}});
check(reopened.execute("info")["world_generation"] == identity,
"saving keeps navigation world identity");
reopened.execute("open", {{"path", utf8(root / "navigation-world.obw")}});
check(reopened.execute("info")["world_generation"] > identity,
"reopening identical IDs resets navigation identity");
}
McpServer mcp(s);
mcp.start(options);
httplib::Client client("127.0.0.1", mcp.port());
client.set_connection_timeout(5);
client.set_read_timeout(10);
httplib::Headers headers{{"Authorization", "Bearer " + options.token},
{"Accept", "application/json, text/event-stream"}};
auto request = Json{{"jsonrpc", "2.0"},
{"id", 1},
{"method", "initialize"},
{"params",
{{"protocolVersion", "2025-11-25"},
{"capabilities", Json::object()},
{"clientInfo", {{"name", "test"}, {"version", "1"}}}}}};
auto result = client.Post("/mcp", headers, request.dump(), "application/json");
check(result && result->status == 200 && Json::parse(result->body)["result"]["protocolVersion"] == "2025-11-25",
"MCP initialize HTTP");
request["method"] = "tools/list";
request["params"] = Json::object();
result = client.Post("/mcp", headers, request.dump(), "application/json");
check(result && Json::parse(result->body)["result"]["tools"].size() >= 18, "MCP tool catalog");
request["method"] = "tools/call";
request["params"] = {{"name", "editor_roster_move"},
{"arguments", {{"player", "player:demo-0"}, {"team", "club:south"}}}};
result = client.Post("/mcp", headers, request.dump(), "application/json");
check(result && Json::parse(result->body)["result"]["isError"] == false, "MCP edit");
check(row(s, "players", "player:demo-0")["team"] == "club:south", "MCP shares GUI session");
s.execute("undo");
check(row(s, "players", "player:demo-0")["team"] == "club:north", "shared undo");
auto no_token = client.Post("/mcp", request.dump(), "application/json");
check(no_token && no_token->status == 401, "reject unauthenticated MCP");
headers.emplace("Origin", "https://example.org");
result = client.Post("/mcp", headers, request.dump(), "application/json");
check(result && result->status == 403, "reject foreign origin");
mcp.stop();
check(!mcp.running(), "server shutdown");
std::cout << checks << " editor checks passed\n";
return 0;
} catch (const std::exception &e) {
std::cerr << "Editor check failed after " << checks << ": " << e.what() << '\n';
return 1;
}
}
-315
View File
@@ -1,315 +0,0 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-only
"""Linux native RmlUI integration check; run inside Xvfb with xdotool.
Tests an actual mouse/keyboard inspector edit and shared MCP undo/save. Uses
only generated demo data. No game installation or personal profile is read.
"""
import argparse
import json
import os
from pathlib import Path
import socket
import subprocess
import tempfile
import time
import urllib.request
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('executable', type=Path)
args = parser.parse_args()
with tempfile.TemporaryDirectory(prefix='editor-gui-') as temporary:
root = Path(temporary)
with socket.socket() as probe:
probe.bind(('127.0.0.1', 0)); port = probe.getsockname()[1]
settings = root / 'settings.json'
settings.write_text(json.dumps({'language': 'de', 'theme': 'midnight', 'mcp_enabled': True, 'mcp_port': port}))
with (root / 'app.log').open('w') as log:
app = subprocess.Popen([str(args.executable.resolve()), '--demo', '--page', 'clubs', '--settings', str(settings)],
stdout=log, stderr=log, env={**os.environ, 'LIBGL_ALWAYS_SOFTWARE': '1'})
try:
request_id = 0
def rpc(method, params):
nonlocal request_id
request_id += 1
token = json.loads(settings.read_text()).get('mcp_token', '')
request = urllib.request.Request(f'http://127.0.0.1:{port}/mcp',
data=json.dumps({'jsonrpc': '2.0', 'id': request_id, 'method': method, 'params': params}).encode(),
headers={'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json',
'Accept': 'application/json, text/event-stream', 'MCP-Protocol-Version': '2025-11-25'})
with urllib.request.urlopen(request, timeout=5) as response:
value = json.load(response)
if 'error' in value:
raise AssertionError(value['error'])
return value['result']
deadline = time.monotonic() + 15
while True:
try:
rpc('initialize', {'protocolVersion': '2025-11-25', 'capabilities': {},
'clientInfo': {'name': 'synthetic-gui-smoke', 'version': '1'}})
break
except (OSError, ValueError):
if app.poll() is not None or time.monotonic() > deadline:
raise RuntimeError('Editor did not start')
time.sleep(.05)
def tool(name, arguments=None):
result = rpc('tools/call', {'name': name, 'arguments': arguments or {}})
if result.get('isError'):
raise AssertionError(result)
return result['structuredContent']
window = subprocess.check_output(['xdotool', 'search', '--sync', '--onlyvisible', '--pid', str(app.pid)],
text=True, timeout=10).splitlines()[-1]
def x(*arguments):
subprocess.run(['xdotool', *map(str, arguments)], check=True, timeout=5, stdout=subprocess.DEVNULL)
def click(a, b):
x('mousemove', '--window', window, a, b, 'click', 1); time.sleep(.15)
def wait_name(expected):
for _ in range(40):
row = tool('editor_get', {'table': 'clubs', 'id': 'club:north'})['record']
if row['name']['default'] == expected:
return
time.sleep(.05)
raise AssertionError('Native inspector edit not observed: ' + expected)
time.sleep(.4); x('windowfocus', window)
click(1150, 443); x('key', 'ctrl+a'); x('type', '--clearmodifiers', 'FC Native QA')
click(1300, 741); wait_name('FC Native QA')
# Exercises textarea values elsewhere in the form as well: the
# untouched colours must remain real JSON, not escaped markup.
row = tool('editor_get', {'table': 'clubs', 'id': 'club:north'})['record']
assert row['colors'] == ['#277c8b', '#ffffff']
tool('editor_undo'); wait_name('FC Nordstadt')
time.sleep(.6)
click(380, 233); x('type', '--clearmodifiers', '--delay', 80, 'Nord')
time.sleep(.3)
x('key', 'ctrl+a'); x('key', 'BackSpace'); time.sleep(.3)
# Native Undo/Redo buttons operate on the same transaction.
click(1268, 872); wait_name('FC Native QA')
tool('editor_save', {'path': str(root / 'world.obw')})
assert (root / 'world.obw').is_file()
assert tool('editor_info')['dirty'] is False
# Exercise the native comparison, not just its MCP projection:
# sort, open the first displayed row, edit its first property,
# and observe which stable record actually changed via MCP.
def compare_open():
click(100, 460); time.sleep(.25)
def first_property(table, identifier, expected, first_name=False):
click(330, 402); time.sleep(.2)
click(1150, 443); x('key', 'ctrl+a'); x('type', '--clearmodifiers', expected)
click(1300, 741)
for _ in range(40):
record = tool('editor_get', {'table': table, 'id': identifier})['record']
if record['name']['first' if first_name else 'default'] == expected:
break
time.sleep(.05)
else:
raise AssertionError('Comparison opened the wrong row: ' + identifier)
tool('editor_undo'); time.sleep(.3)
compare_open()
click(730, 288) # Attribute chooser: hide all, select Strength via its label.
click(495, 405)
click(900, 461)
click(1080, 575)
click(835, 345) # Sort the remaining rating column descending.
first_property('players', 'player:demo-14', 'Rating Descending', True)
compare_open()
click(978, 345) # Salary descending: highest known demo wage.
first_property('players', 'player:demo-50', 'Salary Descending', True)
compare_open()
click(978, 345) # Ascending; missing salary must remain last.
first_property('players', 'player:demo-0', 'Salary Ascending', True)
compare_open()
click(1274, 153) # Teams.
click(946, 345) # Total salary descending.
first_property('clubs', 'club:south', 'Payroll Descending')
compare_open()
click(1378, 153) # Leagues; its row opens the competition editor.
first_property('competitions', 'comp:demo', 'League Comparison')
assert tool('editor_info')['dirty'] is False
before_rules = tool('editor_info')
click(100, 509) # New read-only Regulations page.
click(475, 232) # Game rules.
click(325, 232) # Leagues & competitions.
click(650, 233); x('type', '--clearmodifiers', 'League')
time.sleep(.2); x('key', 'ctrl+a'); x('key', 'BackSpace')
rules = tool('editor_regulations', {'competition': 'comp:demo', 'language': 'en'})
assert rules['read_only'] is True and len(rules['items']) == 1
assert rules['items'][0]['movement_defined'] is False
assert tool('editor_info') == before_rules
# Two distinct leagues ensure drilling filters rows rather than
# merely opening the first club/player from the whole world.
tool('editor_apply', {'changes': [
{'op': 'create', 'table': 'competitions', 'id': 'comp:second',
'name': 'Zweite Demo-Liga', 'data': {'nation': 'nation:de', 'tier': 2}},
{'op': 'create', 'table': 'competitions', 'id': 'comp:cup',
'name': 'Zzz-Testpokal', 'data': {'nation': 'nation:de', 'type': 'cup'}},
{'op': 'update', 'table': 'clubs', 'id': 'club:south',
'set': {'/competition': 'comp:second'}}]})
tool('editor_save', {'path': str(root / 'world.obw')})
time.sleep(.6)
def double_click(a, b):
before = tool('editor_info')
x('mousemove', '--window', window, a, b, 'click', '--repeat', 2, '--delay', 120, 1)
time.sleep(.4)
assert tool('editor_info') == before, 'Navigation must not mutate the world'
def edit_selected(table, identifier, expected, first=False):
click(1150, 443); x('key', 'ctrl+a'); x('type', '--clearmodifiers', expected)
click(1300, 741)
for _ in range(40):
name = tool('editor_get', {'table': table, 'id': identifier})['record']['name']
if name['first' if first else 'default'] == expected:
break
time.sleep(.05)
else:
raise AssertionError('Double click did not filter the expected destination: ' + identifier)
tool('editor_undo'); time.sleep(.5)
south_player = tool('editor_list', {'table': 'players', 'team': 'club:south',
'sort': 'name', 'limit': 1})['items'][0]['id']
click(100, 264) # Leagues, then the unselected second row.
double_click(350, 385)
edit_selected('clubs', 'club:south', 'Filtered South')
double_click(350, 335) # That club's players, all nationalities.
edit_selected('players', south_player, 'Filtered Player', True)
click(100, 264) # Root navigation clears hidden team filters.
double_click(350, 335)
edit_selected('clubs', 'club:north', 'Filtered North')
click(100, 313) # Double click a club that was not already selected.
double_click(350, 385)
edit_selected('players', south_player, 'Second Club', True)
click(100, 313)
click(1150, 443); x('key', 'ctrl+a'); x('type', '--clearmodifiers', 'Keep Draft')
double_click(350, 385)
x('key', 'Escape'); time.sleep(.2)
click(1300, 741); wait_name('Keep Draft')
tool('editor_undo'); time.sleep(.5)
click(100, 215); double_click(350, 335) # Country -> its competitions.
double_click(350, 434) # A cup keeps its own inspector.
edit_selected('competitions', 'comp:cup', 'Cup Inspector')
# Viewing a linked image is read only and must preserve a
# pending property draft until the user chooses to apply it.
click(100, 313)
before_view = tool('editor_info')
click(1150, 443); x('key', 'ctrl+a'); x('type', '--clearmodifiers', 'Preview Draft')
click(1100, 326)
assert tool('editor_info') == before_view
click(985, 757) # A jump with a pending draft asks before leaving.
assert tool('editor_info') == before_view
x('key', 'Escape'); time.sleep(.2)
click(1300, 741); wait_name('Preview Draft')
tool('editor_undo'); time.sleep(.5)
click(1100, 326); click(985, 757) # Exact linked asset, not the first world row.
edit_selected('assets', 'asset:demo/north', 'Preview Asset')
# A thumbnail on an unselected row previews that row's image.
click(100, 313); click(280, 385); click(985, 757)
edit_selected('assets', 'asset:demo/south', 'Second Preview Asset')
# Missing/composed portraits still open, with a library link
# instead of inventing a single backing asset.
click(100, 361)
before_view = tool('editor_info')
click(1100, 326); x('key', 'Escape'); time.sleep(.2)
assert tool('editor_info') == before_view
# Browser navigation restores the selected league and its
# filters without editing data or advancing the undo cursor.
def history(direction):
before = tool('editor_info')
x('mousemove', '--window', window, 760, 300, 'click', 3)
time.sleep(.15)
click(850, 330 if direction == 'back' else 375)
time.sleep(.2)
assert tool('editor_info') == before, 'History must be read only'
click(100, 264); double_click(350, 385)
double_click(350, 335)
history('back')
edit_selected('clubs', 'club:south', 'History Team')
history('back')
edit_selected('competitions', 'comp:second', 'History League')
history('forward')
edit_selected('clubs', 'club:south', 'History Forward Team')
history('forward')
edit_selected('players', south_player, 'History Forward Player', True)
# Cancelling a pending property edit must keep the history
# cursor in place, so the next Back still visits the team.
click(1150, 443); x('key', 'ctrl+a'); x('type', '--clearmodifiers', 'History Draft')
history('back'); x('key', 'Escape'); time.sleep(.2)
click(1300, 741)
assert tool('editor_get', {'table': 'players', 'id': south_player})['record']['name']['first'] == 'History Draft'
tool('editor_undo'); time.sleep(.5)
history('back')
edit_selected('clubs', 'club:south', 'History After Cancel')
# A different destination after Back removes the forward
# branch. Alt+arrows and mouse side buttons share this history.
click(100, 313)
x('key', 'alt+Right'); time.sleep(.2)
edit_selected('clubs', 'club:north', 'History New Branch')
x('click', 8); time.sleep(.3)
edit_selected('clubs', 'club:south', 'History Side Back')
x('click', 9); time.sleep(.3)
edit_selected('clubs', 'club:north', 'History Side Forward')
# Preview -> exact asset is also a visit, not a data undo.
click(280, 385); click(985, 757)
history('back')
edit_selected('clubs', 'club:north', 'History Preview Back')
history('forward')
edit_selected('assets', 'asset:demo/south', 'History Preview Forward')
# External MCP opens invalidate navigation, including when the
# filename and all record IDs are unchanged.
click(100, 361); click(100, 313)
generation = tool('editor_info')['world_generation']
tool('editor_open', {'path': str(root / 'world.obw'), 'discard': True})
time.sleep(.6)
assert tool('editor_info')['world_generation'] > generation
x('key', 'alt+Left'); time.sleep(.2)
edit_selected('clubs', 'club:north', 'History New World')
# Modern dropdowns retain native values and keyboard input.
# Escape cancels just the open list, keeping Options open and
# restoring its prior value. Nothing applies before Apply.
before_options = tool('editor_info')
click(1370, 44)
click(690, 258); x('key', 'Down'); x('key', 'Escape')
time.sleep(.15)
assert json.loads(settings.read_text())['language'] == 'de'
click(690, 343); x('key', 'Down'); x('key', 'Return')
assert json.loads(settings.read_text())['theme'] == 'midnight'
click(950, 725)
assert json.loads(settings.read_text())['theme'] == 'silver'
assert json.loads(settings.read_text())['language'] == 'de'
click(1370, 44)
click(690, 258); x('key', 'Down'); x('key', 'Return')
click(690, 343); x('key', 'Down'); x('key', 'Return')
click(950, 725)
assert json.loads(settings.read_text())['theme'] == 'matchday'
assert json.loads(settings.read_text())['language'] == 'en'
click(1370, 44)
click(690, 258); x('key', 'Up'); x('key', 'Return')
click(690, 343); x('key', 'Up'); x('key', 'Up'); x('key', 'Return')
click(950, 725)
assert json.loads(settings.read_text())['theme'] == 'midnight'
assert json.loads(settings.read_text())['language'] == 'de'
assert tool('editor_info') == before_options
# An idle, unfocused form must not continuously render. The
# generous one-core CPU budget catches a software-render loop
# while allowing timer/MCP polling and slow CI machines.
click(700, 153); time.sleep(.5)
def cpu_seconds():
fields = Path(f'/proc/{app.pid}/stat').read_text().rsplit(')', 1)[1].split()
return (int(fields[11]) + int(fields[12])) / os.sysconf('SC_CLK_TCK')
before_idle = tool('editor_info')
cpu_start, wall_start = cpu_seconds(), time.monotonic()
time.sleep(3)
cpu_used, wall_used = cpu_seconds() - cpu_start, time.monotonic() - wall_start
assert cpu_used < .20 * wall_used, f'Idle CPU exceeded 20% of one core: {cpu_used / wall_used:.1%}'
assert tool('editor_info') == before_idle
assert 'Syntax error parsing property' not in (root / 'app.log').read_text()
print(f'Idle CPU: {cpu_used / wall_used:.1%} of one core.')
print('Native edits, comparisons, rules, drill-down, image previews, browser history and idle CPU passed.')
except Exception:
log.flush()
print((root / 'app.log').read_text())
raise
finally:
app.kill(); app.wait(timeout=5)
if __name__ == '__main__':
main()
-164
View File
@@ -1,164 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "editor/mcp.hpp"
#include "editor/regulations.hpp"
#include "editor/session.hpp"
#include <iostream>
using namespace bmh::editor;
namespace {
int checks = 0;
void check(bool result, const char *message) {
++checks;
if (!result)
throw std::runtime_error(message);
}
Json find(const Json &items, const std::string &id) {
for (const auto &row : items)
if (str(row, "id") == id)
return row;
throw std::runtime_error("missing fixture " + id);
}
Json view(const World &world, const std::string &id) {
return find(regulation_view(world, Json::object())["items"], id);
}
World fixture() {
auto world = World::blank("Synthetic regulations");
world.rows("nations").push_back({{"id", "nation:test"}, {"name", "Testland"}});
for (int i = 0; i < 9; ++i)
world.rows("competitions")
.push_back(
{{"id", "comp:league-" + std::to_string(i)},
{"name", {{"default", "League " + std::to_string(i)}, {"de", "Liga " + std::to_string(i)}}},
{"nation", "nation:test"},
{"type", "league"},
{"tier", i + 1},
{"stages",
Json::array({{{"id", "regular"}, {"format", "league"}, {"teams", 18}, {"legs", 2}}})}});
world.rows("competitions")
.push_back({{"id", "comp:cup"}, {"name", "Test Cup"}, {"type", "club_international"}});
return world;
}
} // namespace
int main() {
const auto root = fs::temp_directory_path() / new_id("regulations-tests-");
fs::create_directory(root);
struct Cleanup {
fs::path root;
~Cleanup() {
std::error_code ec;
fs::remove_all(root, ec);
}
} cleanup{root};
try {
auto world = fixture();
auto &league = world.rows("competitions")[1];
league["movement"] = Json::array({{{"ranks", {1, 2}}, {"to", "comp:league-0"}},
{{"ranks", {3}}, {"to", "comp:playoff"}, {"role", "challenger"}},
{{"ranks", {16, 18}}, {"to", "comp:league-2"}}});
const Json selector{{"from", "comp:league-1"},
{"ranks", {1, 4}},
{"stage", "main"},
{"fallback", {{"from", "comp:league-0"}, {"next_unqualified", true}}}};
world.rows("competitions").back()["slots"] =
Json::array({selector,
{{"holder", "comp:cup"}},
{{"from", "coefficient"}, {"nation_rank", {1, 4}}, {"places", 4}}});
const Json cup_winner{{"from", "comp:league-0"}, {"winner", true}, {"to", "comp:cup"}};
world.rows("competitions")[0]["stages"][0]["slots"] = Json::array({cup_winner});
auto row = view(world, "comp:league-1");
check(row["movement"][0]["kind"] == "promotion" && row["movement"][0]["ranks"] == Json({1, 2}),
"rank ranges preserved");
check(row["movement"][1]["kind"] == "playoff" && row["movement"][2]["kind"] == "relegation",
"explicit movement kinds");
check(row["qualification"][0]["definition"] == selector && row["qualification"][0]["stage"] == "main",
"outbound qualification retains fallback and stage");
const auto cup = view(world, "comp:cup");
check(cup["qualification"].size() == 4 && cup["qualification"][3]["definition"] == cup_winner,
"competition and stage slots; explicit destination");
check(!view(world, "comp:league-2")["movement_defined"].get<bool>() &&
view(world, "comp:league-2")["classic_qualification"].is_null(),
"no invented modern rules");
const auto filtered =
regulation_view(world, {{"language", "de"}, {"nation", "nation:test"}, {"search", "Liga 1"}});
check(filtered["items"].size() == 1 && filtered["items"][0]["name"] == "Liga 1",
"localized search and country filter");
const auto classic = fixture();
world = classic;
const int down[] = {3, 4, 2, 2, 3, 0, 0, 0, 0};
for (int i = 0; i < 9; ++i)
world.rows("competitions")[i]["x-legacy"] = {
{"league_index", i}, {"relegation_places", down[i]}, {"europe_places", 99}};
world.rows("rules").push_back({{"id", "rule:ladder"},
{"type", "legacy_ladder"},
{"first_league", {0, 1, 2, 4}},
{"league_count", {1, 1, 2, 1}},
{"below", {1, 2, 4, 5}},
{"below_count", {1, 2, 1, 1}},
{"newcomer_count", 30}});
world.rows("rules").push_back({{"id", "rule:runtime"},
{"type", "classic_runtime"},
{"qualifications", "classic-season-entrants@1"}});
auto first = view(world, "comp:league-0"), second = view(world, "comp:league-1");
check(first["movement"][0]["ranks"] == Json({16, 18}), "classic relegation reads loaded counts");
check(first["classic_qualification"]["uefa_base_places"] == 4 &&
view(world, "comp:league-8")["classic_qualification"]["uefa_base_places"] == 3,
"classic quotas use named policy, not europe_places");
check(second["movement"][0]["kind"] == "promotion" && second["movement"][1]["targets"].size() == 2 &&
second["movement"][1]["conditional_playoffs"] == true,
"parallel lower leagues and conditional playoff exchange");
auto third = view(world, "comp:league-2");
check(third["movement"][0]["ranks"] == Json({1, 1}) &&
third["movement"][1]["selector"] == "classic-playoff-winner",
"parallel league champion plus playoff; no invented automatic runner-up");
auto bottom = view(world, "comp:league-4");
check(bottom["movement"].back()["newcomer_pool"] == true &&
bottom["movement"].back()["targets"].empty(),
"bottom uses newcomer pool, never the foreign below index");
check(view(world, "comp:league-5")["movement_defined"] == true &&
view(world, "comp:league-5")["movement"].empty(),
"classic foreign league closed");
world.rows("competitions")[0]["movement"] = Json::array();
world.rows("competitions")[0]["slots"] =
Json::array({{{"from", "comp:league-0"}, {"to", "comp:cup"}, {"ranks", {1, 2}}}});
check(view(world, "comp:league-0")["movement"].empty() &&
view(world, "comp:league-0")["classic_qualification"].is_null(),
"declared rules take precedence over Classic summaries");
world.rows("competitions")[8]["x-legacy"] = nullptr;
world.rows("competitions")[8]["classic"] = nullptr;
world.rows("competitions")[8]["stages"] = nullptr;
check(view(world, "comp:league-8")["classic_qualification"].is_null(), "null optional metadata safe");
// Only synthetic data enters public archives or tests.
world = fixture();
const auto records = world.rows("competitions"), rules = world.rows("rules");
regulation_view(world, Json::object());
check(records == world.rows("competitions") && rules == world.rows("rules"),
"projection leaves documents untouched");
world.save(root / "fixture.obw");
Session session;
session.execute("open", {{"path", utf8(root / "fixture.obw")}});
const auto info = session.execute("info"), history = session.execute("history");
session.execute("regulations");
check(info == session.execute("info") && history == session.execute("history"),
"session read-only including revision and undo");
McpServer server(session);
const auto reply =
server.dispatch({{"jsonrpc", "2.0"},
{"id", 1},
{"method", "tools/call"},
{"params",
{{"name", "editor_regulations"},
{"arguments", {{"competition", "comp:league-1"}, {"language", "en"}}}}}});
check(reply["result"]["structuredContent"]["items"].size() == 1 &&
reply["result"]["structuredContent"]["read_only"] == true,
"MCP shares projection");
bool readonly = false;
for (const auto &tool : McpServer::tools())
if (tool["name"] == "editor_regulations")
readonly = tool["annotations"]["readOnlyHint"] == true;
check(readonly, "MCP read-only annotation");
std::cout << checks << " editor regulations checks passed\n";
} catch (const std::exception &error) {
std::cerr << error.what() << '\n';
return 1;
}
}
-72
View File
@@ -1,72 +0,0 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-only
"""Native graphics startup, including Windows Server/WARP and missing assets.
Use an actual display (Xvfb on Linux). Never reads a user profile or game data.
Optionally opens the actual launcher UI too. Windows CI runs on Server 2022.
"""
import argparse
import json
import os
from pathlib import Path
import shutil
import struct
import subprocess
import tempfile
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('editor', type=Path)
parser.add_argument('--launcher', type=Path)
args = parser.parse_args()
# Non-ASCII + spaces exercise UTF-8 native loading and RmlUI URL paths.
with tempfile.TemporaryDirectory(prefix='OpenBMH Pr\u00fcfung ') as temporary:
root = Path(temporary)
executable = args.editor.resolve()
env = {**os.environ, 'OPENBMH_RML_DRIVER': 'warp', 'OPENBMH_NO_ERROR_DIALOG': '1',
'LIBGL_ALWAYS_SOFTWARE': '1', 'SDL_AUDIODRIVER': 'dummy'}
if os.name == 'nt':
env['SDL_VIDEODRIVER'] = 'windows'
# Copy the GUI and its own assets, rather than finding files via cwd.
installed = root / 'Programme'; installed.mkdir()
exe = installed / executable.name
shutil.copy2(executable, exe)
shutil.copytree(executable.parent / 'assets/editor', installed / 'assets/editor')
for dll in executable.parent.glob('*.dll'):
shutil.copy2(dll, installed / dll.name)
settings = root / 'settings.json'
settings.write_text(json.dumps({'language': 'de', 'theme': 'midnight', 'mcp_enabled': False}))
for name, options in [('first-start', []), ('demo', ['--demo', '--page', 'regulations'])]:
screenshot = root / (name + '.png')
result = subprocess.run([str(exe), '--settings', str(settings), '--quit-after-ms', '1800',
'--screenshot', str(screenshot), *options],
cwd=root, env=env, capture_output=True, timeout=35)
assert result.returncode == 0, (name, result.returncode, result.stderr.decode(errors='replace'))
image = screenshot.read_bytes()
assert image[:8] == b'\x89PNG\r\n\x1a\n' and len(image) > 15000, name
width, height = struct.unpack_from('>II', image, 16)
assert width >= 1080 and height >= 720, (width, height)
if os.name == 'nt':
assert b'Direct3D 11 (WARP software)' in result.stderr, result.stderr
result = subprocess.run([str(exe), '--settings', str(settings), '--assets', str(root / 'missing-assets')],
cwd=root, env=env, capture_output=True, timeout=20)
assert result.returncode == 1 and b'ui_assets_missing' in result.stderr, result.stderr
# Also render and close the real launcher, without needing installed mods.
if args.launcher:
original = args.launcher.resolve()
launcher = installed / original.name
shutil.copy2(original, launcher)
shutil.copytree(original.parent / 'assets/launcher', installed / 'assets/launcher')
for dll in original.parent.glob('*.dll'):
shutil.copy2(dll, installed / dll.name)
result = subprocess.run([str(launcher)], cwd=root, env=env, capture_output=True, timeout=25)
assert result.returncode == 0, result.stderr
assert b'Native launcher rendered' in result.stdout, result.stdout
if os.name == 'nt':
assert b'Direct3D 11 (WARP software)' in result.stderr, result.stderr
print('Native first start, demo, Unicode asset paths, failure reporting and launcher startup passed')
if __name__ == '__main__':
main()
-51
View File
@@ -1,51 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "launch/fltd.hpp"
#include <chrono>
#include <fstream>
#include <iostream>
#include <stdexcept>
int main() {
using namespace bmh;
std::filesystem::path root;
try {
root = std::filesystem::temp_directory_path() / ("openbmh-fltd-map-" +
std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()));
std::filesystem::create_directory(root);
// Authored X-32-shaped data: only tested source slots have nonzero bytes.
Bytes source(507925);
source[0] = 'M'; source[1] = 'Z';
const auto put = [&](uint32_t address, uint8_t value) { source.at(address + 0x496d) = value; };
const auto check = [](bool value, const char* message) { if (!value) throw std::runtime_error(message); };
const uint8_t toggle_rows[] = {3, 7, 11, 13, 17, 19};
put(layout::EnglishLayoutTranslation16 - 1, 99); // alignment padding is not a toggle row
for (uint32_t i = 0; i < 6; ++i) put(layout::EnglishLayoutTranslation16 + i, toggle_rows[i]);
put(layout::EnglishLayoutTranslation73 - 1, 0xfb); // negative colour precedes positive colour
put(layout::EnglishLayoutTranslation73, 0x47);
for (uint32_t i = 0; i < 2; ++i) {
put(layout::EnglishDesktopBinSourceX + i, uint8_t(10 + i));
put(layout::EnglishDesktopBinSourceY + i, uint8_t(20 + i));
put(layout::EnglishDesktopSocketSourceX + i, uint8_t(30 + i));
}
const auto path = root / "FLTD.EXE";
{ std::ofstream out(path, std::ios::binary); out.write(reinterpret_cast<const char*>(source.data()), std::streamsize(source.size())); }
const auto image = launch::translate_fltd(path);
for (uint32_t i = 0; i < 6; ++i)
check(image.u8(layout::Setup_FormatError_RuntimeField8 + i) == toggle_rows[i], "toggle mapping includes alignment padding");
check(image.u8(layout::Desktop_Copy_TextPointer) == 0xfb, "negative balance colour");
check(image.u8(layout::Desktop_Copy_TextPointer + 1) == 0x47, "positive balance must use the next source byte");
for (uint32_t i = 0; i < 2; ++i) {
check(image.u8(layout::Desktop_Render_RuntimeField + i) == 10 + i, "bin source x");
check(image.u8(layout::Desktop_Render_RuntimeField2 + i) == 20 + i, "bin source y");
check(image.u8(layout::Desktop_Render_RuntimeField3 + i) == 30 + i, "socket source x");
}
std::filesystem::remove_all(root);
std::cout << "FLTD setup, colour and desktop-control mappings passed\n";
return 0;
} catch (const std::exception& error) {
if (!root.empty()) { std::error_code ec; std::filesystem::remove_all(root, ec); }
std::cerr << error.what() << '\n'; return 1;
}
}
-25
View File
@@ -1,25 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "ui/host_path.hpp"
#include <iostream>
#include <stdexcept>
int main() {
try {
// make_preferred produces actual backslashes on Windows. No installed
// game assets or existing directory are needed for this native test.
auto native = std::filesystem::path(u8"C:/Example/Profile/Save Games").make_preferred();
const auto label = bmh::ui::save_directory_label(native);
if (label != "C:/Example/Profile/Save Games" || label.find('\\') != std::string::npos)
throw std::runtime_error("native path separators leak into the ISO 646-DE label");
if (std::filesystem::path(std::u8string(label.begin(), label.end())) != native)
throw std::runtime_error("displayed path does not identify the original host path");
native = std::filesystem::path(u8"C:/Example/Büro/Spielstände").make_preferred();
if (bmh::ui::save_directory_label(native) != "C:/Example/Büro/Spielstände")
throw std::runtime_error("Unicode host path changed during separator normalization");
std::cout << "Host path labels preserve Unicode and portable separators\n";
return 0;
} catch (const std::exception& error) {
std::cerr << error.what() << '\n'; return 1;
}
}
-115
View File
@@ -1,115 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#include <RmlUi/Core.h>
#include "launch/rml_path.hpp"
#include <chrono>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <stdexcept>
namespace {
struct System : Rml::SystemInterface {
std::string errors;
bool LogMessage(Rml::Log::Type type, const Rml::String &text) override {
if (type <= Rml::Log::LT_WARNING)
errors += text + "\n";
return true;
}
};
struct Renderer : Rml::RenderInterface {
size_t rendered_vertices = 0;
Rml::CompiledGeometryHandle CompileGeometry(Rml::Span<const Rml::Vertex> vertices,
Rml::Span<const int>) override {
return Rml::CompiledGeometryHandle(vertices.size());
}
void ReleaseGeometry(Rml::CompiledGeometryHandle) override {}
void RenderGeometry(Rml::CompiledGeometryHandle geometry, Rml::Vector2f, Rml::TextureHandle) override {
rendered_vertices += size_t(geometry);
}
void EnableScissorRegion(bool) override {}
void SetScissorRegion(Rml::Rectanglei) override {}
Rml::TextureHandle LoadTexture(Rml::Vector2i &dimensions, const Rml::String &name) override {
auto *files = Rml::GetFileInterface();
const auto input = files->Open(name);
if (!input)
throw std::runtime_error("Stadium asset unavailable: " + name);
unsigned char header[18]{};
const auto read = files->Read(header, sizeof(header), input);
files->Close(input);
// The pinned DX11 loader requires bottom-origin rows for 24-bit input.
if (read != sizeof(header) || header[2] != 2 || header[16] != 24 || (header[17] & 32))
throw std::runtime_error("Invalid stadium asset: " + name);
dimensions = {header[12] + 256 * header[13], header[14] + 256 * header[15]};
return 1;
}
Rml::TextureHandle GenerateTexture(Rml::Span<const Rml::byte>, Rml::Vector2i) override { return 2; }
void ReleaseTexture(Rml::TextureHandle) override {}
};
void require(bool value, const std::string &error) {
if (!value)
throw std::runtime_error(error);
}
} // namespace
int main(int argc, char **argv) try {
require(argc == 2 || (argc == 3 && std::string(argv[2]) == "unicode"), "launcher asset directory required");
std::filesystem::path assets(argv[1]);
struct Cleanup {
std::filesystem::path path;
~Cleanup() {
if (!path.empty()) {
std::error_code error;
std::filesystem::remove_all(path, error);
}
}
} cleanup;
if (argc == 3) {
cleanup.path = std::filesystem::temp_directory_path() /
("openbmh-rml-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()));
std::filesystem::create_directory(cleanup.path);
const auto unicode = cleanup.path / std::filesystem::path(u8"Fußball 日本語") / "launcher";
std::filesystem::create_directories(unicode);
std::filesystem::copy(assets, unicode, std::filesystem::copy_options::recursive);
assets = unicode;
}
System system;
Renderer renderer;
bmh::rml::AssetFiles files;
Rml::SetSystemInterface(&system);
Rml::SetRenderInterface(&renderer);
Rml::SetFileInterface(&files);
require(Rml::Initialise(), "RmlUI initialization");
struct Shutdown {
~Shutdown() { Rml::Shutdown(); }
} shutdown;
for (const auto *weight : {"Regular", "Bold"})
require(Rml::LoadFontFace(bmh::rml::asset_path(assets / (std::string("LatoLatin-") + weight + ".ttf"))),
"font load");
auto *context = Rml::CreateContext("test", {1100, 688});
auto *document = context->LoadDocument(bmh::rml::asset_path(assets / "launcher.rml"));
require(document != nullptr, "launcher document load");
document->Show();
for (const auto size : {Rml::Vector2i(1100, 688), Rml::Vector2i(800, 540), Rml::Vector2i(2200, 1376)}) {
context->SetDimensions(size);
context->SetDensityIndependentPixelRatio(float(size.x) / 1100);
context->Update();
context->Render();
for (const auto *id : {"start", "add", "delete", "rename", "end"}) {
auto *button = document->GetElementById(id);
require(button != nullptr, "missing launcher action");
const auto origin = button->GetAbsoluteOffset(Rml::BoxArea::Border);
const auto dimensions = button->GetBox().GetSize(Rml::BoxArea::Border);
require(origin.x >= 0 && origin.y >= 0 && origin.x + dimensions.x <= size.x + 1 &&
origin.y + dimensions.y <= size.y + 1 && dimensions.y >= 30,
"action outside viewport or too small");
require(button->GetNumChildren() >= 2, "action lost its visible text label");
}
require(!document->GetElementById("overlay")->IsVisible(), "modal unexpectedly visible");
}
require(renderer.rendered_vertices > 100, "launcher did not render");
require(system.errors.empty(), system.errors);
std::cout << "Launcher RML/RCSS, fonts, background, visible labels and responsive layout passed\n";
return 0;
} catch (const std::exception &error) {
std::cerr << error.what() << '\n';
return 1;
}
-33
View File
@@ -1,33 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "launch/launcher_ui.hpp"
#include <SDL.h>
#include <cstdio>
#include <stdexcept>
// Run explicitly on a real display (Windows CI also forces the WARP device),
// outside the dummy-video CTest suite. This constructs the actual launcher UI.
int main(int, char **) {
try {
auto ui = bmh::launch::make_launcher_ui();
const auto timer = SDL_AddTimer(
1600,
[](Uint32, void *) -> Uint32 {
SDL_Event event{};
event.type = SDL_QUIT;
SDL_PushEvent(&event);
return 0;
},
nullptr);
if (!timer)
throw std::runtime_error(SDL_GetError());
const auto result = ui->next({});
SDL_RemoveTimer(timer);
if (result.action != bmh::launch::LauncherAction::end)
return 1;
std::puts("Native launcher rendered and exited successfully");
return 0;
} catch (const std::exception &error) {
std::fprintf(stderr, "%s\n", error.what());
return 1;
}
}
-160
View File
@@ -1,160 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "content/package.hpp"
#include "content/save.hpp"
#include "launch/mods.hpp"
#include "launch/process.hpp"
#include "launch/archive.hpp"
#include "formats/content.hpp"
#include "formats/native_state.hpp"
#include "formats/vga.hpp"
#include <chrono>
#include <iostream>
using namespace bmh;
namespace fs = std::filesystem;
void check(bool value, const char *message) {
if (!value)
throw std::runtime_error(message);
}
template <class F> void rejects(F f, const char *message) {
bool failed = false;
try {
f();
} catch (const std::exception &) {
failed = true;
}
check(failed, message);
}
int main(int argc, char **argv) try {
const auto arguments = launch::utf8_arguments(argc, argv);
if (arguments.size() > 1 && arguments[1] == "--child-check") {
return arguments == std::vector<std::string>{arguments[0], "--child-check", "Grüße with spaces",
"quote\" and trailing\\", ""}
? 42
: 43;
}
const auto executable = launch::executable_path("not-the-executable");
check(fs::is_regular_file(executable),
"portable root uses the actual process path rather than argv or current directory");
check(launch::run_child(executable, {"--child-check", "Grüße with spaces", "quote\" and trailing\\", ""},
{}) == 42,
"child startup preserves Unicode, spaces, quotes, trailing slashes and empty arguments");
check(content::sha256("") == "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"SHA256 empty vector");
check(content::sha256("abc") == "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
"SHA256 short vector");
check(content::sha256(std::string(1000000, 'a')) ==
"cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0",
"SHA256 multi-block vector");
const auto root = fs::temp_directory_path() /
("openbmh-native-test-" +
std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()));
fs::create_directories(root);
struct Cleanup {
fs::path p;
~Cleanup() {
std::error_code ec;
fs::remove_all(p, ec);
}
} cleanup{root};
auto classic = std::make_shared<content::Classic>();
classic->images.emplace("kb/7", Image(2, 2, 19));
classic->audio["2000"] = {1, 2, 3};
classic->desktops = {4, 5};
classic->palette.argb[9] = 0xffabcdef;
{
content::Mount mount(root / "content.obw", classic);
check(!fs::exists(mount.root()), "mounted contents need no materialized legacy files");
check(load_vga(mount.root() / "KB/7.VGA").pixels == Bytes(4, 19),
"indexed OBW image reaches existing renderer");
check(read_file(mount.root() / "S/2000") == Bytes({1, 2, 3}),
"audio bank comes from immutable store");
check(read_file(mount.root() / "M3.MEN") == Bytes({4, 5}),
"startup input comes from immutable store");
check(load_palette(mount.root() / "M3PC.COL").argb[9] == 0xffabcdef,
"palette keeps exact imported RGB8");
rejects([&] { load_vga(mount.root() / "KB/999.VGA"); },
"missing content must not fall through to disk");
rejects([&] { content::Mount duplicate(mount.root(), classic); },
"duplicate mounts must not replace live contents");
}
check(!content::find(root / "content.obw/KB/7.VGA"), "mount lifetime is bounded");
GameState state;
state.date = 99;
state.season_start = 12;
state.display_start_year = 1994;
state.squad_slots = {0x8fff, 42};
state.manager_teams = {-1, 12};
state.manager_records = {1, 2, 3};
state.player_names = {0, 0xff};
state.memory.add_block(0x1000, 4);
state.memory.set32(0x1000, 0xff123456);
state.players.push_back({std::string("A\xff", 2), 0xdeadbeef, 0x12345678, 0xffffffff});
state.autosave_month = 4;
state.list_toggle = 1;
state.sportschau_homes[9] = 41;
state.reality.initialized = true;
state.reality.grid.place(0, 5, 7, 0);
state.reality.cue_actors[3] = 19;
const auto encoded = encode_native_state(state);
const auto restored = decode_native_state(cli::parse_json(cli::dump_json(encoded)));
check(cli::dump_json(encoded) == cli::dump_json(encode_native_state(restored)),
"all native fields round-trip without host padding/pointers");
check(restored.reality == state.reality, "Reality residues survive exactly");
auto damaged = encoded;
damaged.object()->at("schema") = "classic-state@99.0";
rejects([&] { decode_native_state(damaged); }, "unsupported checkpoint schema rejected");
TurnDriver driver;
driver.referees = {1, 0x81};
driver.next_event_id = UINT64_MAX;
TurnDriver copy;
content::restore_driver(copy, content::driver_checkpoint(driver));
check(copy.next_event_id == UINT64_MAX && copy.referees == driver.referees,
"driver counters and referees round-trip");
WatcomRandom random(7);
random.rand();
WatcomRandom continued;
continued.restore(random.seed(), random.calls());
check(continued.rand() == random.rand() && continued.calls() == random.calls(),
"Watcom stream resumes including counter");
content::Documents docs{{"manifest.json", "{}"}, {"assets/test.pixels", std::string("a\0b", 3)}};
const auto archive = root / "sample.obs";
content::write_archive(docs, archive);
check(content::read_archive(archive) == docs, "binary native archive round-trip");
{
content::Mount mount(archive, std::make_shared<content::Classic>());
check(content::read_archive(archive) == docs,
"archive reads bypass the mounted virtual resource namespace");
}
rejects([&] { content::write_archive({{"../outside", "x"}}, root / "unsafe.obs"); },
"archive traversal rejected");
rejects([&] { content::write_archive({}, archive); }, "existing saves require explicit overwrite");
check(content::read_archive(archive) == docs, "rejected overwrite retains existing save");
content::write_archive({{"new", "value"}}, archive, true);
check(content::read_archive(archive).contains("new"), "atomic replacement publishes complete archive");
content::save_preferences(root / "test.obsettings", "settings", Bytes(180, 0x82), false);
check(content::load_preferences(root / "test.obsettings", "settings", 180) == Bytes(180, 0x82),
"native settings retain availability bits");
rejects([&] { content::load_preferences(root / "test.obsettings", "layout", 180); },
"preferences kinds cannot be confused");
launch::ModLibrary library(root);
check(library.list().empty(), "first launch has no implicit installation");
for (const char *name : {"../escape", "CON", "lpt1.txt", "trailing.", "bad/name", ""})
rejects([&] { launch::ModLibrary::validate_name(name); }, "portable mod name validation");
fs::create_directories(root / "mods/BMH-classic");
auto entries = library.list();
check(entries.size() == 1 && !entries[0].error.empty(), "damaged mods remain visible with error");
rejects([&] { library.rename(entries[0], "bmh-CLASSIC"); }, "case-insensitive duplicate name rejected");
library.rename(entries[0], "Renamed");
entries = library.list();
check(entries[0].name == "Renamed", "rename changes directory name");
entries[0].content_id = std::string(64, 'a');
const auto personal = library.user_directory(entries[0]);
content::write_atomic(personal / "keep.obs", "saved", false);
library.remove(entries[0]);
check(library.list().empty() && fs::exists(personal / "keep.obs"), "delete retains personal saves");
std::cout << "native content, checkpoints and portable mod lifecycle passed\n";
return 0;
} catch (const std::exception &e) {
std::cerr << e.what() << '\n';
return 1;
}
-230
View File
@@ -1,230 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "app/career_session.hpp"
#include "app/controller.hpp"
#include "content/save.hpp"
#include "launch/mods.hpp"
#include "launch/game_data.hpp"
#include "ui/setup.hpp"
#include "ui/sportschau.hpp"
#include "game/save.hpp"
#include "audio/original.hpp"
#include <algorithm>
#include <chrono>
#include <iostream>
using namespace bmh;
namespace fs = std::filesystem;
void check(bool value, const std::string &text) {
if (!value)
throw std::runtime_error(text);
}
int main(int argc, char **argv) try {
if (argc < 2)
return 77;
const auto root = fs::temp_directory_path() /
("openbmh-native-career-" +
std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()));
fs::create_directories(root);
struct Cleanup {
fs::path p;
~Cleanup() {
std::error_code ec;
fs::remove_all(p, ec);
}
} cleanup{root};
launch::ModLibrary library(root);
launch::AddMod request;
request.source = argv[1];
request.name = "Test Classic";
request.start_year = 1994;
request.migrate = false;
const auto result = library.add(request, {});
const auto package = result.mod.directory / "content.obw";
auto content = content::open(package);
content::Mount mount(package, content);
check(content::open(package)->content_id == content->content_id,
"mounted container can be reopened without resolving it as an asset");
openbmh::audio::OriginalAssets sound;
for (size_t i = 0; i < 4; ++i)
sound.containers[i] = read_file(mount.root() / "S" / std::to_string(2000 + i));
for (size_t i = 0; i < 96; ++i)
sound.tables.frequencies[i] =
content->executable.u16(layout::Audio_OriginalAudioAssets_RuntimeField2 + uint32_t(i) * 2);
for (size_t i = 0; i < 9; ++i)
sound.tables.operators[i] =
content->executable.u8(layout::Audio_OriginalAudioAssets_RuntimeField + uint32_t(i) * 16);
openbmh::audio::OriginalSynth synth;
std::string sound_error;
check(synth.load(std::move(sound), 22050, sound_error), sound_error);
// Exercise renderers through aliases while the mod contains only content.obw.
check(ui::SetupScreen(mount.root()).render().pixels.size() == 320 * 240, "OBW-only setup renderer");
(void)ui::SportschauIntro(mount.root()).render_frame(0);
const auto resolved = launch::resolve_game(request.source, root / "legacy-test-cache");
check(resolved.error.empty(), resolved.error);
auto legacy_directory = resolved.check.directory;
if (!fs::exists(legacy_directory / "BMH.exe")) {
// The legacy oracle uses fixed filename casing. Only its private test
// copy needs aliases on case-sensitive filesystems; OBW does not.
const auto aliases = root / "legacy-case-reference";
fs::create_directory(aliases);
for (const char *name : {"BMH.exe", "M3D.MAN", "TEXTD.BLK", "M3.MEN", "M3.DAT"}) {
const auto source = launch::find_file(legacy_directory, name);
check(bool(source), "legacy reference file missing");
fs::copy_file(*source, aliases / name);
}
legacy_directory = aliases;
}
app::CareerSession old(legacy_directory, 12345);
app::CareerSession session(mount.root(), 12345);
check(save_stream(old.state()) == save_stream(session.state()) &&
old.rand().seed() == session.rand().seed() && old.game().seed() == session.game().seed(),
"OBW bootstrap matches legacy state and RNG");
ui::SetupOptions options;
options.managers = 1;
ui::ManagerChoice manager;
manager.slot = 0;
manager.master_club = 0;
manager.start_league = 0;
manager.strength = 1;
manager.portrait = 0;
manager.name = "Native QA";
std::string error;
check(session.confirm_manager(options, manager, error), error);
const auto personal = library.user_directory(result.mod);
session.configure_autosave_directory(personal);
session.state().memory.set8(layout::Desk_EnterDesk_RuntimeField, 1);
ui::CareerInitializationResult initial;
check(session.finish(initial, error), error);
check(initial.desktop.date.year == 1994 && initial.desktop.date.weekday == 2,
"selected start year changes the year display while retaining the Classic Wednesday epoch");
const auto before = cli::dump_json(encode_native_state(session.state()));
const auto random = session.rand();
const auto game = session.game();
const auto save = library.user_directory(result.mod) / "QA.obs";
check(session.save_game(save, 0, false, error), error);
check(session.rand().seed() == random.seed() && session.rand().calls() == random.calls() &&
session.game().seed() == game.seed() && session.game().calls() == game.calls(),
"native saving is RNG-neutral");
app::CareerSession loaded(mount.root(), 999, save);
check(cli::dump_json(encode_native_state(loaded.state())) == before, "native career state round-trip");
check(loaded.rand().seed() == random.seed() && loaded.rand().calls() == random.calls() &&
loaded.game().seed() == game.seed() && loaded.game().calls() == game.calls(),
"both RNG states and counters restored");
check(cli::dump_json(content::driver_checkpoint(session.manager_join_checkpoint().driver)) ==
cli::dump_json(content::driver_checkpoint(loaded.manager_join_checkpoint().driver)),
"native turn cursor round-trip");
{
ui::StartupFlow flow(mount.root(), personal);
check(flow.click(215, 220).request == ui::FlowRequest::submenu_opened,
"GUI opens native load browser from setup");
const auto request = flow.send_key("ENTER");
check(request.request == ui::FlowRequest::file_action && request.file_action.path == save,
"GUI selects native save from personal directory");
std::unique_ptr<app::CareerSession> gui_session;
uint64_t gui_revision = 0;
openbmh::audio::Playback playback;
std::optional<uint64_t> audio_session;
check(app::serve_flow_request(flow, request, gui_session, mount.root(), personal, 999, gui_revision,
playback, audio_session, false)
.empty(),
"GUI controller accepts native save path");
check(gui_session && flow.screen_name() == "desktop" && gui_revision == 1,
"GUI controller attaches loaded native desktop: " + flow.state_json());
const auto save_item =
std::find_if(flow.desktop()->state().items.begin(), flow.desktop()->state().items.end(),
[](const ui::DeskItem &item) { return item.kind == 11 && !item.disabled; });
check(save_item != flow.desktop()->state().items.end(), "native desktop exposes Save");
const auto serve = [&](const ui::FlowResult &event) {
check(app::serve_flow_request(flow, event, gui_session, mount.root(), personal, 999, gui_revision,
playback, audio_session, false)
.empty(),
"native GUI file action dispatch");
};
serve(flow.click(save_item->x + save_item->width / 2, save_item->y + save_item->height / 2));
check(flow.screen_name() == "save_load" && flow.text("GUI Roundtrip"),
"native GUI Save accepts a new filename");
const auto gui_random = gui_session->rand();
serve(flow.send_key("ENTER"));
check(flow.screen_name() == "desktop" && fs::exists(personal / "GUI Roundtrip.obs"),
"native GUI Save publishes OBS and returns to desktop: " + flow.state_json());
check(gui_session->rand().seed() == gui_random.seed() &&
gui_session->rand().calls() == gui_random.calls(),
"GUI saving preserves random state");
}
session.state().memory.set8(layout::Desk_EnterDesk_RuntimeField, 1);
loaded.state().memory.set8(layout::Desk_EnterDesk_RuntimeField, 1);
session.state().autosave_month = 0;
loaded.state().autosave_month = 0;
uint64_t first_revision = 1, second_revision = 1;
for (int step = 0; step < 8; ++step) {
const auto first_desk = session.desktop_projection(first_revision),
second_desk = loaded.desktop_projection(second_revision);
ui::DeskRequest first_request;
first_request.kind = ui::DeskRequestKind::advance_turn;
first_request.manager_slot = first_desk.manager_slot;
first_request.revision = first_revision;
auto second_request = first_request;
second_request.manager_slot = second_desk.manager_slot;
second_request.revision = second_revision;
std::string first_error, second_error;
const auto first = session.dispatch_kickoff(first_request, first_revision, first_error);
const auto second = loaded.dispatch_kickoff(second_request, second_revision, second_error);
check(first.kind == second.kind && first_error == second_error,
"native continuation has identical outcome");
check(cli::dump_json(encode_native_state(session.state())) ==
cli::dump_json(encode_native_state(loaded.state())),
"native continuation preserves every game-state field");
check(session.rand().seed() == loaded.rand().seed() &&
session.rand().calls() == loaded.rand().calls() &&
session.game().seed() == loaded.game().seed() &&
session.game().calls() == loaded.game().calls(),
"native continuation preserves both random streams");
if (first.kind == TurnDeskKind::Failed || first.kind == TurnDeskKind::WaitingAtDesk)
break;
if (step == 0) {
const auto autosave_error = session.take_autosave_error();
check(fs::exists(personal / "AUTOSAVE.obs"), "native autosave at stable desk: " + autosave_error);
app::CareerSession autosaved(mount.root(), 0, personal / "AUTOSAVE.obs");
check(cli::dump_json(encode_native_state(autosaved.state())) ==
cli::dump_json(encode_native_state(session.state())),
"autosave matches completed desk, including runtime flags");
}
check(session.save_game(save, first.manager_slot, true, error), error);
auto fresh = std::make_unique<app::CareerSession>(mount.root(), 0, save);
check(cli::dump_json(content::driver_checkpoint(session.manager_join_checkpoint().driver)) ==
cli::dump_json(content::driver_checkpoint(fresh->manager_join_checkpoint().driver)),
"prepared match groups and previous results survive saving");
}
// Original save migration must not require the original installation afterwards.
auto old_save = make_savegame(session.state(), session.rand());
write_savegame(root / "legacy.FBM", old_save);
app::CareerSession migrated(mount.root(), 4321, root / "legacy.FBM", true);
check(migrated.save_game(root / "migrated.obs", 0, false, error), error);
app::CareerSession continued(mount.root(), 1, root / "migrated.obs");
check(continued.state().players.size() == session.state().players.size(),
"legacy save migrates to native continuation");
if (argc > 2) {
app::CareerSession original(mount.root(), 0x12345678, argv[2], true);
check(original.save_game(root / "original-import.obs",
original.state().memory.u8(layout::ActiveManager), false, error),
error);
app::CareerSession resumed(mount.root(), 0, root / "original-import.obs");
check(cli::dump_json(encode_native_state(original.state())) ==
cli::dump_json(encode_native_state(resumed.state())),
"original edition save migration round-trip");
}
auto changed = content->documents;
changed["assets/classic/images/kb/29.pixels"][0] ^= 1;
bool rejected = false;
try {
content::verify(changed);
} catch (const std::exception &) {
rejected = true;
}
check(rejected, "modified Classic assets rejected");
std::cout << "OBW-only GUI/bootstrap, career/RNG round-trip and migration passed\n";
return 0;
} catch (const std::exception &e) {
std::cerr << e.what() << '\n';
return 1;
}
-124
View File
@@ -1,124 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "import/classic.hpp"
#include "formats/executable_layout.hpp"
#include "launch/game_data.hpp"
#include "launch/fltd.hpp"
#include "game/career.hpp"
#include "game/season.hpp"
#include "game/save.hpp"
#include "game/schedule.hpp"
#include "game/desk_actions.hpp"
#include <bit>
#include <chrono>
#include <iostream>
using namespace bmh;
namespace fs = std::filesystem;
namespace {
void check(bool ok, const std::string& why) { if (!ok) throw std::runtime_error(why); }
fs::path file(const fs::path& root, const std::string& name) {
const auto value = launch::find_file(root, name);
if (!value) throw std::runtime_error("missing " + name);
return *value;
}
void install(const LeImage& exe) {
install_fixture_tables(exe);
uint8_t sizes[9], first[8], counts[8];
for (uint32_t i = 0; i < 9; ++i) sizes[i] = exe.u8(layout::LeagueSizes + i);
set_league_sizes(sizes); kEnglishCompetitions = sizes[0] == 20;
for (uint32_t i = 0; i < 8; ++i) {
first[i] = exe.u8(layout::CalendarFirstLeague + i); counts[i] = exe.u8(layout::CalendarLeagueCounts + i);
kGroupBelow[i] = exe.u8(layout::CareerSession_InstallLeagueSizes_RuntimeField5 + i);
kGroupBelowCount[i] = exe.u8(layout::CareerSession_InstallLeagueSizes_RuntimeField4 + i);
}
set_league_groups(first, counts);
for (uint32_t i = 0; i < 9; ++i) {
kLeagueRelegation[i] = exe.u8(layout::CareerSession_InstallLeagueSizes_RuntimeField2 + i);
kLeagueEurope[i] = exe.u8(layout::CareerSession_InstallLeagueSizes_RuntimeField + i);
kLeagueSuffix[i] = i < 5 ? char(exe.u8(layout::CareerSession_InstallLeagueSizes_RuntimeField3 + i * 2)) : 0;
}
kNewcomerFirst = exe.u16(layout::CareerSession_DispatchLineup_RuntimeField);
kNewcomerCount = exe.u16(layout::CareerSession_InstallLeagueSizes_RuntimeField6);
}
struct Run { Bytes state; int32_t game; uint32_t watcom; uint64_t game_calls, watcom_calls; };
Run start(const LeImage& exe, const Database& db, const TextDb& texts, const Bytes& men, const Bytes& dat) {
install(exe);
auto state = startup_state(exe, db, men, dat);
state.texts = &texts;
state.currency_suffix = exe.cstring(layout::CurrencySuffixText);
configure_training_camp_data(state, exe);
for (size_t i = 0; i < state.credit_rate_table.size(); ++i) state.credit_rate_table[i] = exe.u8(layout::BankCredit_BankCreditContext_RuntimeField3 + uint32_t(i));
state.credit_divisor = std::bit_cast<double>(uint64_t(exe.u32(layout::BankCredit_BankCreditContext_RuntimeField)) |
uint64_t(exe.u32(layout::BankCredit_BankCreditContext_RuntimeField2)) << 32);
state.credit_rate_table_available = true;
GameRandom game; WatcomRandom watcom(8128); MinuteReport report;
startup_players(state, game, watcom);
check(new_career_before_dialog(state, game, watcom, report), "pre-dialog initialization: " + report.reason);
state.memory.set8(layout::CareerDuration, 20);
state.memory.set8(layout::Difficulty, 1); state.level = 1;
state.memory.set8(layout::ManagerCount, 1);
state.memory.set8(layout::GameMode, 3);
state.memory.set32(layout::CompetitionSelection, 3);
state.manager_records.at(0x21c) = 1;
career_managers_begin(state);
check(career_add_manager(state, exe, 0, {"IMPORT QA", 0, 0, 1, 0}, false, game, watcom, report), "manager initialization: " + report.reason);
career_managers_end(state, false);
check(career_season_setup(state, game, watcom, report), "season setup: " + report.reason);
check(career_first_steps(state, game, watcom, report), "first steps: " + report.reason);
// Compare in RAM only: this is an installation test, never an FBM converter.
return {save_stream(state), game.seed(), watcom.seed(), game.calls(), watcom.calls()};
}
} // namespace
int main(int argc, char** argv) {
fs::path temp;
try {
if (argc < 2 || std::string(argv[1]).empty()) return 77;
const fs::path root = argv[1];
const bool english = bool(launch::find_file(root, "FLTD.EXE")) && !launch::find_file(root, "BMH.EXE");
const auto exe = english ? launch::translate_fltd(file(root, "FLTD.EXE")) : load_le(file(root, "BMH.EXE"));
const auto source = english ? launch::translate_fltd(file(root, "FLTD.EXE"), false) : load_le(file(root, "BMH.EXE"), false);
const auto db = load_database(file(root, english ? "M3E.MAN" : "M3D.MAN"));
const auto texts = load_textd(file(root, english ? "TEXTE.BLK" : "TEXTD.BLK"));
const auto men = read_file(file(root, "M3.MEN")), dat = read_file(file(root, "M3.DAT"));
const auto original_run = start(exe, db, texts, men, dat);
const auto converted = obw::import_installation(root, {"2026-07-01", "Private installation test"});
temp = fs::temp_directory_path() / ("openbmh-classic-qa-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()));
fs::create_directory(temp);
obw::write(converted, temp / "world.obw", false);
auto imported = obw::load_classic(obw::read(temp / "world.obw"));
const auto imported_run = start(imported.executable, imported.database, imported.texts, imported.desktops, imported.formations);
check(original_run.state == imported_run.state, "new-career first-season state differs after OBW round trip");
check(original_run.game == imported_run.game && original_run.watcom == imported_run.watcom &&
original_run.game_calls == imported_run.game_calls && original_run.watcom_calls == imported_run.watcom_calls,
"initialization random sequence differs");
for (uint32_t at = layout::GermanDataSegmentBegin; at < layout::GermanImageEnd; ++at) {
check(exe.u8(at) == imported.executable.u8(at), "effective data-table byte changed");
check(source.u8(at) == imported.source_tables.u8(at), "source data-table byte changed");
}
if (english) for (uint32_t at = layout::EnDataStart; at < layout::Career_CompetitionPointersEnglish_RuntimeField; ++at)
check(exe.u8(at) == imported.executable.u8(at) && source.u8(at) == imported.source_tables.u8(at), "English data-table byte changed");
for (const auto address : {layout::FreeKickTakerLabel, layout::PenaltyTakerLabel, layout::CornerTakerLabel, layout::AutomaticTakersLabel})
check(exe.cstring(address) == imported.executable.cstring(address) && source.cstring(address) == imported.source_tables.cstring(address), "embedded literal changed");
for (const auto& [name, image] : imported.images) {
if (!name.starts_with("kb/") && !name.starts_with("w/")) continue;
const auto folder = file(root, name.starts_with("kb/") ? "KB" : "W");
const auto original = load_vga(file(folder, name.substr(name.find('/') + 1) + ".VGA"));
check(original.width == image.width && original.height == image.height && original.pixels == image.pixels, "original atlas pixels changed");
}
const auto pal = load_palette(file(root, "M3PC.COL"));
check(imported.palette.argb == pal.argb, "palette changed");
for (const auto& [name, font] : imported.fonts) {
const auto original = load_font(file(file(root, "F"), name));
check(original.bitmap == font.bitmap && original.height == font.height && original.glyphs.size() == font.glyphs.size(), "font changed");
}
for (const auto& [name, bytes] : imported.audio) check(bytes == read_file(file(file(root, "S"), name)), "audio bytes changed");
std::cout << (english ? "FLTD" : "BMH") << " Classic: " << converted.size() << " entries; " << original_run.state.size()
<< " first-season bytes identical; RNG draws G=" << original_run.game_calls << " W=" << original_run.watcom_calls
<< "; source/effective data regions, pixels, palette, fonts and audio retained\n";
fs::remove_all(temp);
return 0;
} catch (const std::exception& error) {
if (!temp.empty()) { std::error_code ec; fs::remove_all(temp, ec); }
std::cerr << error.what() << '\n'; return 1;
}
}
-355
View File
@@ -1,355 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "import/obw.hpp"
#include "import/classic.hpp"
#include "content/package.hpp"
#include "import/assets.hpp"
#include "formats/executable_layout.hpp"
#include "launch/archive.hpp"
#include <algorithm>
#include <chrono>
#include <fstream>
#include <iostream>
#include <stdexcept>
namespace fs = std::filesystem;
using namespace bmh;
using J = bmh::cli::Json;
namespace {
void check(bool condition, const std::string& message) {
if (!condition) throw std::runtime_error(message);
}
template<class F> void rejects(F&& action, const std::string& message) {
bool rejected = false;
try { action(); } catch (const std::exception&) { rejected = true; }
check(rejected, message);
}
void word(Bytes& data, size_t at, uint32_t value, size_t width = 2) {
for (size_t i = 0; i < width; ++i) data.at(at + i) = uint8_t(value >> (i * 8));
}
void append(Bytes& data, uint32_t value, size_t width = 2) {
for (size_t i = 0; i < width; ++i) data.push_back(uint8_t(value >> (i * 8)));
}
void save(const fs::path& path, const Bytes& bytes) {
std::ofstream out(path, std::ios::binary);
out.write(reinterpret_cast<const char*>(bytes.data()), std::streamsize(bytes.size()));
check(bool(out), "write synthetic fixture");
}
const J& f(const J& object, const char* name) { return object.object()->at(name); }
J document(const obw::Documents& documents, const char* path) { return cli::parse_json(documents.at(path)); }
Database database(bool english) {
Database db;
db.club_names.resize(419);
for (size_t i = 0; i < db.club_names.size(); ++i) db.club_names[i] = "Synthetic team " + std::to_string(i);
db.club_names[0] = "Test M}nchen";
db.club_names[357] = english ? "ENGLAND" : "DEUTSCHLAND";
db.club_names[358] = english ? "GERMANY" : "SPANIEN";
db.club_names[359] = english ? "ITALY" : "ENGLAND";
db.club_names[360] = "FRANCE";
db.club_names[361] = english ? "SPAIN" : "ITALIEN";
if (english) db.club_names[150] = " ";
db.players.resize(2574);
for (size_t i = 0; i < db.players.size(); ++i)
db.players[i] = {"Synthetic Player " + std::to_string(i), 60u | (90u << 7) | (80u << 14), 0x321, (6u << 21) | uint32_t(i % 4)};
db.players[0].name = "T{st \"Name\"";
db.players[1].w368 |= 1u << 27;
db.raw_player_bonus_values.resize(3146);
db.raw_player_bonus_values[1] = 128 | 17; // nationality 33, plus a bonus of 17
db.raw_database_metadata.resize(100);
db.raw_club_auxiliary_words.resize(168 * 2);
db.raw_club_badge_selectors.resize(419 * 2);
db.raw_foreign_club_strength.resize(251, 60);
db.raw_league_auxiliary_bytes.resize(189);
db.raw_referee_properties.resize(50);
db.raw_club_kit_selectors.resize(419);
db.raw_club_short_name_offsets.resize(168);
db.squad_list.resize((3096 - 4) * 2 + 108);
for (size_t i = 0; i < db.squad_list.size(); i += 2) word(db.squad_list, i, 4095);
word(db.squad_list, 0, 0x8000); word(db.squad_list, 2, 1);
word(db.squad_list, 90 * 24 * 2, 2); // first foreign squad, 16-slot stride
word(db.squad_list, (2928 - 1) * 2, 3); // last squad
db.referees = {"Synthetic Referee"};
db.stadiums = {"Synthetic Stadium"};
const auto pool = [](const std::vector<std::string>& names, Bytes& offsets) {
Bytes result;
for (const auto& name : names) {
append(offsets, uint32_t(result.size()));
result.insert(result.end(), name.begin(), name.end()); result.push_back(0);
}
return result;
};
db.pools[0] = pool(db.club_names, db.raw_club_name_offsets);
std::vector<std::string> names;
for (const auto& player : db.players) names.push_back(player.name);
db.pools[1] = pool(names, db.raw_player_name_offsets);
Bytes unused;
db.pools[2] = pool(db.referees, unused); db.pools[3] = pool(db.stadiums, unused);
return db;
}
LeImage executable(bool english) {
constexpr uint32_t base = 0x10000;
Bytes bytes(layout::GermanImageEnd - base);
const auto put = [&](uint32_t address, uint32_t value, size_t width = 1) { word(bytes, address - base, value, width); };
const int sizes[] = {english ? 20 : 18, english ? 20 : 18, english ? 20 : 18, english ? 20 : 18, english ? 10 : 18, 12, 12, 12, 12};
for (uint32_t i = 0; i < 9; ++i) {
put(layout::LeagueSizes + i, uint32_t(sizes[i]));
put(layout::LeagueCalendarBits + i, english && i == 4 ? 31 : i);
}
if (!english) { put(layout::CareerSession_InstallLeagueSizes_RuntimeField3 + 4, 'A'); put(layout::CareerSession_InstallLeagueSizes_RuntimeField3 + 6, 'B'); }
const std::vector<std::pair<int, uint32_t>> bindings = english ?
std::vector<std::pair<int, uint32_t>>{{4, layout::EnglishFourTeamFixtureTable}, {6, layout::EnglishSixTeamFixtureTable},
{12, layout::EnglishTwelveTeamFixtureTable}, {20, layout::EnglishTwentyTeamFixtureTable}} :
std::vector<std::pair<int, uint32_t>>{{4, layout::CareerSession_RuntimeError_RuntimeField}, {6, layout::CareerSession_RuntimeError_RuntimeField2},
{12, layout::CareerSession_RuntimeError_RuntimeField3}, {16, layout::CareerSession_RuntimeError_ExecutableField3},
{18, layout::CareerSession_RuntimeError_ExecutableField}, {20, layout::CareerSession_RuntimeError_ExecutableField2}};
uint32_t cursor = layout::GermanImageEnd - 4096; // synthetic data storage, outside pointer tables
for (const auto& [teams, address] : bindings) {
put(address, cursor, 4); ++cursor;
std::vector<int> order;
for (int i = 0; i < teams; ++i) order.push_back(i);
for (int round = 1; round < teams; ++round) {
put(address + uint32_t(round * 4), cursor, 4);
for (int i = 0; i < teams / 2; ++i) {
put(cursor++, uint32_t('a' + order[size_t(i)]));
put(cursor++, uint32_t('a' + order[size_t(teams - 1 - i)]));
}
++cursor;
std::rotate(order.begin() + 1, order.end() - 1, order.end());
}
}
put(layout::Career_BuildStadium_RuntimeField4 - 1, 2);
put(base, 0xdeadbeef, 4); // an executable instruction region must never be exported
for (uint32_t i = 0; i < 5; ++i) {
put(layout::ClubPlayerDetail_ClubPlayerDetailRedraw_RuntimeField2 + i, 4);
put(layout::ClubPlayerDetail_DrawPortrait_RuntimeField + i, 2 + i);
put(layout::ClubPlayerDetail_DrawPortrait_RuntimeField2 + i, 3 + i);
put(layout::ClubPlayerDetail_DrawPortrait_RuntimeField3 + i, 3);
put(layout::ClubPlayerDetail_DrawPortrait_RuntimeField4 + i, 2);
put(layout::ClubPlayerDetail_DrawPortrait_RuntimeField7 + i * 2, 20, 2);
}
put(layout::ClubPlayerDetail_DrawPortrait_RuntimeField, 253);
put(layout::ClubPlayerDetail_DrawPortrait_RuntimeField3, 70);
put(layout::ClubPlayerDetail_DrawPortrait_RuntimeField7, 319, 2);
const std::string suffix = english ? " &" : " DM";
for (size_t i = 0; i < suffix.size(); ++i) put(layout::CurrencySuffixText + uint32_t(i), uint8_t(suffix[i]));
return LeImage::from_bytes(base, std::move(bytes));
}
Bytes serialize(const Database& db) {
Bytes bytes;
for (const auto& pool : db.pools) append(bytes, uint32_t(pool.size()));
const auto add = [&](const Bytes& data) { bytes.insert(bytes.end(), data.begin(), data.end()); };
add(db.raw_player_bonus_values);
for (const auto& pool : db.pools) add(pool);
for (const auto* table : {&db.raw_club_name_offsets, &db.raw_player_name_offsets, &db.raw_database_metadata,
&db.raw_club_auxiliary_words, &db.raw_club_badge_selectors, &db.raw_foreign_club_strength,
&db.raw_league_auxiliary_bytes, &db.raw_referee_properties, &db.raw_club_kit_selectors, &db.raw_club_short_name_offsets, &db.squad_list}) add(*table);
for (int table = 0; table < 3; ++table)
for (const auto& player : db.players) append(bytes, table == 0 ? player.w35c : table == 1 ? player.w368 : player.w364, 4);
return bytes;
}
} // namespace
int main() {
fs::path root;
try {
root = fs::temp_directory_path() / ("openbmh-obw-test-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()));
fs::create_directory(root);
const obw::Options options{"2026-07-01", "Synthetic world"};
TextDb texts;
texts.strings.resize(TEXT_COUNT, "Synthetic text\n\"quote\"\\slash");
texts.strings[0] += char(0xa7);
const auto db = database(false);
const auto exe = executable(false);
const auto documents = obw::convert_database(db, texts, exe, false, options);
check(documents == obw::convert_database(db, texts, exe, false, options), "conversion must be deterministic");
const auto clubs = document(documents, "world/clubs.json");
check(*f(f(f(clubs, "items").array()->at(0), "name"), "default").string() == "Test München", "decode German names");
const auto players = document(documents, "world/players.json");
const auto& rows = *f(players, "items").array();
check(rows.size() == 2574, "all player identities retained");
check(*f(rows[0], "team").string() == "club:00000", "lineup flag must not change player id");
check(*f(rows[2], "team").string() == "club:00090", "foreign squad stride");
check(*f(rows[3], "team").string() == "club:00137", "last squad assignment");
check(!rows[4].object()->contains("team"), "unassigned player remains free");
check(!rows[0].object()->contains("born"), "do not invent birthdays");
check(*f(f(rows[0], "name"), "last").string() == "Täst \"Name\"", "escaped player name survives JSON");
check(*f(f(rows[1], "attributes"), "bonus").integer() == 17, "bonus high bit is nationality, not rating");
check(*f(rows[1], "nationalities").array()->at(0).string() == "nation:x-legacy-33", "nationality extension bit");
check(*f(rows.back(), "nationalities").array()->at(0).string() == "nation:de", "database nationalities are preserved before career rewrites");
check(documents.at("locale/de-original/openbmh.po").find("\\\"quote\\\"") != std::string::npos, "gettext quoting");
const auto english = obw::convert_database(database(true), texts, executable(true), true, options);
const auto manifest = document(english, "manifest.json");
check(*f(manifest, "provenance").string() == "import:fltd", "English provenance");
check(*f(f(manifest, "currency"), "code").string() == "GBP", "English currency");
const auto comps = document(english, "world/competitions.json");
const auto& leagues = *f(comps, "items").array();
check(*f(leagues[3], "tier").integer() == 4, "English fourth tier");
check(!*f(leagues[4], "played").boolean(), "English fifth league is not simulated");
check(!f(leagues[4], "stages").array()->at(0).object()->contains("generator"), "no fabricated ten-team fixture table");
check(*f(leagues[0], "trophy").string() == "asset:comp/" +
f(leagues[0], "id").string()->substr(5) + "/trophy", "stable default trophy reference");
const auto with_trophy = [&](const J& value) {
auto copy = documents;
auto competitions = document(copy, "world/competitions.json");
std::get<J::Array>(competitions.object()->at("items").value)[0].object()->at("trophy") = value;
copy["world/competitions.json"] = cli::dump_json(competitions);
return copy;
};
// Artwork may be supplied by a future pack, including a shared generic key.
obw::validate(with_trophy(J("asset:comp/generic/trophy")));
obw::validate(with_trophy(J("asset:comp/future-international_42.v2/trophy")));
for (const auto& key : {"", "assets/cup.png", "https://example.invalid/cup.png",
"asset:comp//trophy", "asset:comp/../trophy", "asset:comp/a/b/trophy"})
rejects([&] { obw::validate(with_trophy(J(key))); }, "reject invalid trophy reference");
rejects([&] { obw::validate(with_trophy(J(12))); }, "reject non-string trophy reference");
auto no_trophy = documents;
auto old_competitions = document(no_trophy, "world/competitions.json");
for (auto& row : std::get<J::Array>(old_competitions.object()->at("items").value)) row.object()->erase("trophy");
no_trophy["world/competitions.json"] = cli::dump_json(old_competitions);
obw::validate(no_trophy); // Existing 1.0 documents retain implicit trophy defaults.
check(f(document(english, "world/clubs.json"), "items").array()->size() == 418, "ignore unnamed English slot");
const auto zip = root / "test.obw";
obw::write(documents, zip, false);
auto archive = launch::Archive::open(zip);
check(archive.entries().size() == documents.size(), "complete ZIP container");
for (size_t i = 0; i < archive.entries().size(); ++i) {
const auto& entry = archive.entries()[i];
const auto bytes = archive.read(i);
check(std::string(bytes.begin(), bytes.end()) == documents.at(entry.name), "ZIP document round trip");
}
const auto folder = root / "unpacked";
obw::write(documents, folder, true);
for (const auto& [name, contents] : documents) {
const auto bytes = read_file(folder / name);
check(std::string(bytes.begin(), bytes.end()) == contents, "unpacked document round trip");
}
const auto saved_zip = read_file(zip);
rejects([&] { obw::write(english, zip, false); }, "refuse to overwrite archive");
check(read_file(zip) == saved_zip, "existing output untouched");
rejects([&] { obw::write(documents, folder, true); }, "refuse to overwrite directory");
rejects([&] { obw::convert_database(db, texts, exe, false, {"2026-02-30", "bad"}); }, "reject invalid date");
auto bad_db = db;
word(bad_db.squad_list, 2, 0);
rejects([&] { obw::convert_database(bad_db, texts, exe, false, options); }, "reject duplicate squad ownership");
word(bad_db.squad_list, 2, 4000);
rejects([&] { obw::convert_database(bad_db, texts, exe, false, options); }, "reject unknown player");
auto bad = documents;
bad.erase("world/players.json");
rejects([&] { obw::write(bad, root / "bad.obw", false); }, "reject incomplete archive");
check(!fs::exists(root / "bad.obw"), "failure leaves no published output");
bad = documents;
auto changed = players;
std::get<J::Array>(changed.object()->at("items").value)[0].object()->at("team") = "club:99999";
bad["world/players.json"] = cli::dump_json(changed);
rejects([&] { obw::validate(bad); }, "reject dangling player team");
bad = documents;
bad["../escape.json"] = "{}";
rejects([&] { obw::write(bad, root / "escape.obw", false); }, "reject path traversal");
check(!fs::exists(root / "escape.obw"), "bad archive path leaves no output");
// Exercise the actual on-disk legacy readers and case-insensitive discovery.
const auto input = root / "synthetic-installation";
fs::create_directory(input);
const auto raw_database = serialize(db);
save(input / "m3d.man", raw_database);
save_image(exe, input / "bmh.EXE");
Bytes raw_texts(7);
for (const auto& value : texts.strings) { raw_texts.insert(raw_texts.end(), value.begin(), value.end()); raw_texts.push_back(0); }
save(input / "textd.blk", raw_texts);
auto partial_options = options;
partial_options.database_only = true;
const auto converted = obw::import_installation(input, partial_options);
check(converted.contains("x-legacy/source-database.json"), "retain exact database for future mappings");
check(read_file(input / "m3d.man") == raw_database, "source database unchanged");
check(obw::import_installation(root, partial_options) == converted, "follow one nested installation");
rejects([&] { obw::import_installation(input, options); }, "full mod requires its media and startup data");
// Complete synthetic content profile, including embedded NULs and media.
for (const auto* dir : {"KB", "W", "F", "S"}) fs::create_directory(input / dir);
save(input / "M3.MEN", Bytes(864, 7)); save(input / "M3.DAT", Bytes(1408, 9));
save(input / "M3PC.COL", Bytes(768, 31));
Bytes font(37, 0);
word(font, 0, 1); font[3] = 2; word(font, 4, 1); font[8] = font[9] = 'A'; word(font, 16, 1);
font[28] = 0x80; word(font, 31, 1); word(font, 35, 1);
save(input / "F/BMH2.FNT", font); save(input / "F/BMH3.FNT", font);
Bytes bank{'F','O','R','M',8,0,0,0,'A','L','P','T','R','A','U','M'};
for (const char* name : {"2000", "2001", "2002", "2003"}) save(input / "S" / name, bank);
const auto image = [&](const fs::path& path) {
Bytes vga(8, 0), rle;
constexpr int width = 320, height = 240;
for (int i = 0; i < width * height; i += 128) {
rle.push_back(127);
for (int k = 0; k < 128; ++k) rle.push_back(uint8_t((i + k) % 251));
}
rle.push_back(0); word(vga, 0, width); word(vga, 2, height); word(vga, 4, uint32_t(rle.size()), 4);
vga.insert(vga.end(), rle.begin(), rle.end()); save(path, vga);
};
image(input / "KB/0.VGA"); image(input / "KB/29.VGA"); image(input / "W/0.VGA");
auto classic = converted;
obw::complete_classic(classic, input, db, exe, exe, false, options);
obw::validate(classic);
const auto loaded = obw::load_classic(classic);
check(loaded.desktops == Bytes(864, 7) && loaded.formations == Bytes(1408, 9), "all startup seed bytes survive");
check(loaded.database.players[0].name == db.players[0].name && loaded.texts.blob == Bytes(raw_texts.begin() + 7, raw_texts.end()), "source records and text blob survive");
check(loaded.images.at("kb/29").pixels.at(12 * 320 + 17) == uint8_t((12 * 320 + 17) % 251), "indexed media round trip");
check(loaded.images.at("portraits/layer-0-0").pixels.at(67) == uint8_t((3 * 320 + 320) % 251), "portrait feature preserves packed row wrap");
check(loaded.fonts.at("bmh2.fnt").glyph('A').bit_width == 1 && loaded.audio.at("2000") == bank, "font and audio round trip");
check(loaded.executable.u32(0x10000) == 0, "no executable code in compatibility image");
const auto portrait = obw::portrait_recipe("ABC", exe);
check(*f(portrait, "background").integer() >= 0 && f(portrait, "layers").array()->size() == 5, "frozen part recipe");
const auto classic_zip = root / "classic.obw";
obw::write(classic, classic_zip, false);
check(obw::read(classic_zip) == classic, "binary Classic ZIP round trip");
auto sealed=classic;
const auto identity=content::seal(sealed);
const auto runtime_zip=root/"runtime.obw";
content::write_archive(sealed,runtime_zip);
const auto runtime=content::open(runtime_zip);
check(runtime->content_id==identity&&runtime->database.squad_list==db.squad_list,
"sealed native runtime reconstructs typed database without the source codec");
auto changed_title=sealed;
auto changed_manifest=cli::parse_json(changed_title.at("manifest.json"));
(*changed_manifest.object())["generator"]="new importer version";
(*changed_manifest.object())["title"]=J::Object{{"default","Renamed title"}};
changed_title["manifest.json"]=cli::dump_json(changed_manifest)+"\n";
obw::refresh_classic_inventory(changed_title);
check(content::seal(changed_title)==identity,"reimport identity ignores presentation title and generator version");
auto edited=sealed;edited.at("x-classic/desktop-seed.bin")[0]^=1;
obw::refresh_classic_inventory(edited);
rejects([&]{content::verify(edited);},"refreshing old CRC inventory cannot bypass the Classic seal");
auto damaged = classic;
damaged.at("x-classic/desktop-seed.bin")[0] ^= 1;
rejects([&] { obw::validate(damaged); }, "inventory catches binary corruption");
damaged = classic; damaged["state/rng.json"] = "{}";
rejects([&] { obw::validate(damaged); }, "reject injected save state");
damaged = classic;
auto renamed = document(damaged, "world/players.json");
auto& renamed_rows = std::get<J::Array>(renamed.object()->at("items").value);
const auto appearance = f(renamed_rows[0], "appearance");
renamed_rows[0].object()->at("name").object()->at("last") = "Renamed";
damaged["world/players.json"] = cli::dump_json(renamed);
obw::refresh_classic_inventory(damaged);
obw::validate(damaged);
check(cli::dump_json(f(renamed_rows[0], "appearance")) == cli::dump_json(appearance), "rename keeps frozen face");
renamed_rows[0].object()->at("appearance").object()->at("background") = 4;
damaged["world/players.json"] = cli::dump_json(renamed);
obw::refresh_classic_inventory(damaged);
rejects([&] { obw::validate(damaged); }, "reject invalid appearance even with updated inventory");
auto wrong_options = options; wrong_options.mod = "FLTD-classic";
rejects([&] { obw::complete_classic(damaged, input, db, exe, exe, false, wrong_options); }, "mod/edition mismatch rejected");
save(input / "m3d.man", Bytes{0, 1});
rejects([&] { obw::import_installation(input, options); }, "reject truncated legacy database");
fs::remove_all(root);
std::cout << "OBW importer: synthetic DE/EN mappings, containers and rejection paths passed\n";
return 0;
} catch (const std::exception& error) {
if (!root.empty()) { std::error_code ec; fs::remove_all(root, ec); }
std::cerr << error.what() << '\n';
return 1;
}
}
+2 -29
View File
@@ -22,16 +22,12 @@ class PackageAllowlistTests(unittest.TestCase):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
# Empty authored placeholders test names/structure, not executable behavior.
for name in ['OpenBMH', 'openbmh_cli', 'openbmh_import', 'README.md', 'LICENSE',
for name in ['openbmh_play', 'openbmh_cli', 'README.md', 'LICENSE',
'THIRD_PARTY_NOTICES.md', 'ACKNOWLEDGEMENTS.md', 'CONTRIBUTING.md']:
(root / name).write_text('synthetic')
notes = root / 'docs/release/0.2/RELEASE_NOTES.md'
notes = root / 'docs/release/0.1/RELEASE_NOTES.md'
notes.parent.mkdir(parents=True)
notes.write_text('synthetic release notes')
for name in ['launcher.rml', 'theme.rcss', 'stadium.tga', 'LatoLatin-Regular.ttf', 'LatoLatin-Bold.ttf']:
asset = root / 'assets' / 'launcher' / name
asset.parent.mkdir(parents=True, exist_ok=True)
asset.write_text('synthetic packaged UI asset')
licenses = Path(__file__).resolve().parents[1] / 'docs' / 'licenses'
for source in licenses.iterdir():
if source.is_file():
@@ -39,20 +35,6 @@ class PackageAllowlistTests(unittest.TestCase):
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text('synthetic license placeholder')
package.validate(root, False)
missing = root / 'assets/launcher/LatoLatin-Bold.ttf'
missing.unlink()
with self.assertRaises(RuntimeError):
package.validate(root, False)
missing.write_text('synthetic font')
schema = root / 'docs/formats/obw/schema/1.0/manifest.json'
schema.parent.mkdir(parents=True)
schema.write_text('{"type":"object"}')
package.validate(root, False)
unexpected_json = root / 'docs/world.json'
unexpected_json.write_text('{"synthetic":true}')
with self.assertRaises(RuntimeError):
package.validate(root, False)
unexpected_json.unlink()
for name in ['game.fbm', 'BMH.EXE', 'unit_tests', 'secret.txt']:
(root / name).write_text('synthetic refusal fixture')
with self.assertRaises(RuntimeError):
@@ -64,15 +46,6 @@ class PackageAllowlistTests(unittest.TestCase):
class SourceInventoryTests(unittest.TestCase):
def test_only_pinned_unused_freetype_logging_submodule_is_omitted(self):
record = b'160000 72dfcc858c040c54a6a0b88fcb7e70ee186d3167 0\tsubprojects/dlg\0'
self.assertEqual(source_package.unbuilt_submodules('freetype', record),
{'subprojects/dlg': '72dfcc858c040c54a6a0b88fcb7e70ee186d3167'})
for component, entry in [('SDL2', record), ('freetype', record.replace(b'subprojects/dlg', b'other')),
('freetype', record.replace(b'72df', b'0000'))]:
with self.assertRaises(RuntimeError):
source_package.unbuilt_submodules(component, entry)
def setUp(self):
self.temporary = tempfile.TemporaryDirectory()
self.addCleanup(self.temporary.cleanup)
-60
View File
@@ -1,60 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "app/quit_confirmation.hpp"
#include <iostream>
#include <stdexcept>
#include <string>
namespace {
void check(bool value, const char* message) { if (!value) throw std::runtime_error(message); }
void push(Uint32 type) {
SDL_Event event{}; event.type = type;
check(SDL_PushEvent(&event) == 1, "cannot enqueue authored event");
}
}
int main(int, char**) {
using bmh::app::QuitConfirmation;
try {
check(SDL_Init(SDL_INIT_EVENTS) == 0, "SDL events initialization");
SDL_FlushEvents(SDL_FIRSTEVENT, SDL_LASTEVENT);
int presentations = 0, answer = 0;
const auto present = [&](const SDL_MessageBoxData* data, int* selected) {
++presentations;
check(std::string(data->title) == "OpenBMH beenden?", "German prompt");
check(std::string(data->message).find("gespeicherte") != std::string::npos, "unsaved-state warning");
check(data->numbuttons == 2 && std::string(data->buttons[0].text) == "Abbrechen", "German buttons");
check((data->buttons[0].flags & SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT) &&
(data->buttons[0].flags & SDL_MESSAGEBOX_BUTTON_ESCAPEKEY_DEFAULT), "Enter and Escape must default to cancellation");
*selected = answer; return 0;
};
QuitConfirmation german(nullptr, false, present);
push(SDL_QUIT); push(SDL_USEREVENT);
SDL_Event event{};
check(german.poll(&event) == 1 && event.type == SDL_USEREVENT && presentations == 1,
"cancelled window close must preserve subsequent UI input");
push(SDL_QUIT);
check(german.peep(&event, 1, SDL_PEEKEVENT, SDL_QUIT, SDL_QUIT) == 1 && presentations == 1,
"peeking must not open or consume a dialog");
check(german.peep(&event, 1, SDL_GETEVENT, SDL_QUIT, SDL_QUIT) == 0 && presentations == 2,
"cancelled animation/live close must not abort its owner");
answer = 1; push(SDL_QUIT);
check(german.peep(&event, 1, SDL_GETEVENT, SDL_QUIT, SDL_QUIT) == 1 && event.type == SDL_QUIT,
"confirmed close must reach existing shutdown handling");
check(german.confirm() && presentations == 3, "confirmed shutdown must not ask twice");
bool english_seen = false;
QuitConfirmation english(nullptr, true, [&](const SDL_MessageBoxData* data, int* selected) {
english_seen = std::string(data->title) == "Quit OpenBMH?" &&
std::string(data->buttons[0].text) == "Cancel" && std::string(data->buttons[1].text) == "Quit";
*selected = 1; return 0;
});
check(english.confirm() && english_seen, "Football Limited uses English confirmation");
QuitConfirmation failed(nullptr, false, [](const SDL_MessageBoxData*, int*) { return -1; });
check(!failed.confirm(), "failed native dialog must keep the application alive");
SDL_Quit();
std::cout << "Quit confirmation language, defaults, cancel, accept and event ownership passed\n";
return 0;
} catch (const std::exception& error) {
SDL_Quit(); std::cerr << error.what() << '\n'; return 1;
}
}
-5
View File
@@ -76,11 +76,6 @@ void reschedule_test(GameState g) {
check(undone.memory.u16(at) == 0 && undone.results.at(size_t(m.match) + size_t(m.round) * 10 + size_t(league) * 0x17c) == kNotPlayed,
"undo frees the entry and restores 0xCC");
check(reschedulable_matches(undone, 0).size() == matches.size(), "the match is movable again");
// UndoReschedule clears the replay bit when no other replay stays on the day: the same
// target days as before the move (issue 16)
check((undone.memory.u16(::bmh::layout::CompetitionCalendar + uint32_t(target) * 2) & 0x4000) == 0,
"undo clears the calendar replay bit");
check(reschedule_target_days(undone, 0, m) == days, "the same target days after the undo");
std::cout << "moved round " << m.round + 1 << " from day " << m.day << " to day " << target << " (" << days.size()
<< " days offered)\n";
}
+1 -4
View File
@@ -1,17 +1,14 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "formats/le.hpp"
#include "game/messages.hpp"
#include "game/schedule.hpp"
namespace bmh::test {
// Standalone engine tests explicitly install the supplied edition's scheduling
// content and the message texts. CareerSession performs the same installation for
// normal app callers.
// content. CareerSession performs the same installation for normal app callers.
inline LeImage load_executable(const std::filesystem::path& path) {
auto executable = bmh::load_le(path);
install_fixture_tables(executable);
install_message_texts(executable);
return executable;
}
}