"""Dense Commander layout regression, using optional installed Chromium only."""
import json
import re
import shutil
import subprocess
import threading
from dataclasses import replace
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from unittest.mock import Mock
import pygame
import pytest
from commander_web import ASSET_DIR, ENTRY_TAG, client_css, index_html, inject_probe, WEB_ROUTES
from src.commander import local
from src.core.game import Game
from src.core.i18n import Translator, load_catalog, pseudolocale
from src.ui import layout
from test_commander_assets import (ASSETS, PREFIX, Document, browser_contact_analysis,
browser_state, catalogs)
LOBBY_LAYOUT = r"""
const $ = (id) => document.getElementById(id);
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function run() {
for (let i = 0; $("shell").hidden && i < 300; i++) await sleep(20);
$("name").value = "Layout Lobby";
$("code").value = "123ABC";
$("pair-form").requestSubmit();
for (let i = 0; $("lobby").hidden && i < 300; i++) await sleep(20);
const cards = [...$("station-cards").children];
const root = document.documentElement;
const lobby = $("lobby").getBoundingClientRect();
// One unit at a time: the frigate's cards, then the side choice.
const sideControls = [...$("side-choice").querySelectorAll("button")];
const lobbyControls = sideControls.length === 2 && [...cards.filter((card) => !card.hidden), ...sideControls.map((button) => ({querySelector: () => button}))].every((card) => {
const button = card.querySelector("button");
const bounds = button.getBoundingClientRect();
return button.type === "button" && bounds.width >= 44 && bounds.height >= 40;
});
$("lobby").hidden = true;
document.body.dataset.remoteRole = "assigned";
$("role-rail").hidden = false;
$("operations").hidden = false;
$("bridge-orders").hidden = false;
$("station-view").hidden = false;
$("station-sonar").hidden = false;
$("station-sonar").querySelectorAll("[data-sonar-page]").forEach((page) => { page.hidden = false; });
const bridgeBounds = $("bridge-orders").getBoundingClientRect();
const bridgeControls = [...$("bridge-orders").querySelectorAll("input, button")];
const bridge = {
bounds: [bridgeBounds.left, bridgeBounds.top, bridgeBounds.right, bridgeBounds.bottom],
controls: bridgeControls.every((control) => {
const bounds = control.getBoundingClientRect();
return bounds.width >= 24 && bounds.height >= 24;
}),
labels: ["bridge-course", "bridge-speed"].every((id) =>
document.querySelector(`label[for="${id}"]`)?.control === $(id)),
};
const sonarBounds = $("station-sonar").getBoundingClientRect();
const sonarControls = [...$("station-sonar").querySelectorAll("input, select, button")]
.filter((control) => control.type !== "checkbox");
const sonarToggles = [...$("station-sonar").querySelectorAll("label.toggle")];
const sonar = {
bounds: [sonarBounds.left, sonarBounds.top, sonarBounds.right, sonarBounds.bottom],
controls: sonarControls.length >= 16 && [...sonarControls, ...sonarToggles].every((control) => {
const bounds = control.getBoundingClientRect();
return bounds.width >= 24 && bounds.height >= 24;
}),
labels: ["sonar-control-page", "sonar-bearing", "sonar-array-mode", "sonar-depth",
"sonar-gain", "sonar-band", "sonar-harmonic-input"].every((id) =>
document.querySelector(`label[for="${id}"]`)?.control === $(id)),
};
$("station-sonar").hidden = true;
$("station-weapons").hidden = false;
const weaponsBounds = $("station-weapons").getBoundingClientRect();
const fireControls = [...$("station-weapons").querySelectorAll(".direct-fire-controls input, .direct-fire-controls select, .direct-fire-controls button")];
const weapons = {
bounds: [weaponsBounds.left, weaponsBounds.top, weaponsBounds.right, weaponsBounds.bottom],
controls: fireControls.length === 5 && fireControls.every((control) => {
const bounds = control.getBoundingClientRect();
return bounds.width >= 24 && bounds.height >= 24;
}),
labels: ["weapons-fire-target", "weapons-fire-depth"].every((id) =>
document.querySelector(`label[for="${id}"]`)?.control === $(id)),
};
const workstationBounds = (role) => {
const section = $(`station-${role}`), grid = section.querySelector(".station-grid");
for (const candidate of document.querySelectorAll("[data-station-role]")) candidate.hidden = candidate !== section;
section.hidden = false;
$("role-visuals").hidden = false;
const visualFor = {bridge: "map-visual", sonar: "sonar-visual", weapons: "weapons-visual",
damage: "damage-visual", opz: "map-visual", radio: "radio-visual", engine: "engine-visual",
helicopter: "map-visual", eloka: "eloka-visual", uboot: "map-visual"};
for (const panel of document.querySelectorAll("#role-visuals > .visual-panel")) {
panel.hidden = panel.id !== visualFor[role];
}
const trackRoles = new Set(["bridge", "sonar", "weapons", "opz", "helicopter", "eloka", "uboot"]);
const tracks = trackRoles.has(role);
$("cic-grid").dataset.tracks = String(tracks);
$("cic-grid").dataset.layout = role === "radio" ? "radio" : "";
$("bridge-orders").hidden = role !== "bridge";
$("opz-controls").hidden = role !== "opz";
$("helicopter-dipping-controls").hidden = role !== "helicopter";
for (const container of section.querySelectorAll("dl, .station-list")) {
if (container.children.length) continue;
if (container.tagName === "DL") {
container.append(Object.assign(document.createElement("div"), {
innerHTML: "
Sehr lange lokalisierte StatusbezeichnungVollstaendige Einsatzinformation ohne Ueberdeckung",
}));
} else {
const row = document.createElement("div");
row.className = "station-row";
row.textContent = "Ausgefuellte Einsatzinformation mit langem deutschem Text fuer die Layoutpruefung";
container.append(row);
}
}
const box = (element) => element.getBoundingClientRect();
const overlaps = (a, b) => Math.min(a.right, b.right) - Math.max(a.left, b.left) > 1 &&
Math.min(a.bottom, b.bottom) - Math.max(a.top, b.top) > 1;
// The CIC areas (stage, docks, log drawer) never overlap each other.
const areaIds = ["stage", "dock-right", "log-drawer", ...(tracks ? ["dock-left", "dock-detail"] : []),
...(role === "radio" ? ["dock-detail"] : [])];
const areas = areaIds.map((id) => [id, box($(id))]).filter(([, bounds]) => bounds.width > 0 && bounds.height > 0);
let intersects = false;
areas.forEach(([, first], index) => areas.slice(index + 1).forEach(([, second]) => {
if (overlaps(first, second)) intersects = true;
}));
const outer = box($("cic-grid")), visual = box($("stage")), controls = box(grid);
const size = (bounds) => bounds.width * bounds.height;
const stageLargest = areas.every(([id, bounds]) => id === "stage" || size(bounds) <= size(visual));
const children = [...grid.children].filter((element) =>
!element.hidden && getComputedStyle(element).display !== "none");
const childBounds = children.map((element) => element.getBoundingClientRect());
const childIntersections = [];
childBounds.forEach((first, index) => childBounds.slice(index + 1).forEach((second) => {
if (overlaps(first, second)) childIntersections.push(index);
}));
const textOverflow = [...$("dock-right").querySelectorAll("h2, h3, h4, p, dt, dd, label, button, summary, output")]
.filter((element) => !element.hidden && getComputedStyle(element).display !== "none" && element.clientWidth > 1)
.filter((element) => element.scrollWidth > element.clientWidth + 2)
.map((element) => `${element.tagName.toLowerCase()}#${element.id}.${element.className}: ${element.textContent.slice(0, 40)}`);
return {intersects, stageLargest, outer: [outer.left, outer.top, outer.right, outer.bottom],
visual: [visual.left, visual.top, visual.right, visual.bottom],
controls: [controls.left, controls.top, controls.right, controls.bottom],
childIntersections: childIntersections.length, textOverflow,
childrenContained: childBounds.every((bounds) =>
bounds.left >= controls.left - 1 && bounds.right <= controls.right + 1)};
};
document.body.classList.add("workstation-mode");
const roles = ["bridge", "sonar", "weapons", "damage", "opz", "radio", "engine", "helicopter", "uboot", "eloka"];
const workstations = Object.fromEntries(roles.map((role) => [role, workstationBounds(role)]));
const report = {
cards: cards.length,
order: cards.map((card) => card.dataset.station),
pageWidth: root.scrollWidth,
pageHeight: root.scrollHeight,
viewport: [innerWidth, innerHeight],
lobby: [lobby.left, lobby.top, lobby.right, lobby.bottom],
controls: lobbyControls,
bridge, sonar, weapons, workstations,
};
parent.postMessage({lobbyLayout: report}, location.origin);
}
window.addEventListener("DOMContentLoaded", () => run().catch((error) => {
parent.postMessage({lobbyLayout: {error: String(error.stack || error)}}, location.origin);
}));
"""
@pytest.mark.parametrize("width,height", [(1280, 720), (390, 844), (320, 568)])
def test_simlog_and_map_stay_inside_web_viewport(tmp_path, width, height):
chromium = shutil.which("chromium") or shutil.which("chromium-browser")
if not chromium:
pytest.skip("Optional SimLog layout regression: no installed Chromium")
# Styles only: the probe replaces the client entry point.
html = index_html().replace(ENTRY_TAG, '')
probe = r"""
document.body.classList.add("workstation-mode");
document.body.dataset.remoteRole = "assigned";
document.getElementById("shell").hidden = false;
document.getElementById("bootstrap").hidden = true;
document.getElementById("pairing").hidden = true;
const simlog = document.getElementById("simlog-view");
simlog.hidden = false;
const entry = document.createElement("li");
entry.className = "simlog-entry";
entry.innerHTML = '2026-09-22 12:00SONAR'
+ "Long mission name ".repeat(24) + '
';
document.getElementById("simlog-list").append(entry);
const dialog = document.getElementById("simlog-map-dialog");
dialog.hidden = false;
dialog.showModal();
requestAnimationFrame(() => {
const rect = (element) => {
const box = element.getBoundingClientRect();
return {left: box.left, right: box.right, top: box.top, bottom: box.bottom,
width: box.width, height: box.height};
};
parent.postMessage({simlogLayout: {
viewport: {width: innerWidth, height: innerHeight},
shell: rect(document.getElementById("shell")), simlog: rect(simlog),
panel: rect(document.querySelector(".simlog-panel")),
current: rect(document.getElementById("simlog-current")),
entry: rect(entry), list: rect(document.getElementById("simlog-list")),
dialog: rect(dialog), plot: rect(document.querySelector(".simlog-map-plot"))
}}, location.origin);
});
"""
class Handler(BaseHTTPRequestHandler):
def log_message(self, *_args):
pass
def do_GET(self):
if self.path == "/":
outer = (f''
f'')
body, mime = outer.encode(), "text/html"
elif self.path == "/app":
body, mime = html.encode(), "text/html"
elif self.path in WEB_ROUTES and not self.path.endswith(".js"):
mime, body = WEB_ROUTES[self.path]
elif self.path == "/simlog-layout.js":
body, mime = probe.encode(), "text/javascript"
else:
self.send_error(404)
return
self.send_response(200)
self.send_header("Content-Type", mime)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
try:
result = subprocess.run(
[chromium, "--headless", "--no-sandbox", "--disable-gpu",
"--disable-background-networking", "--no-first-run",
"--no-default-browser-check", "--disable-dev-shm-usage",
f"--user-data-dir={tmp_path / 'simlog-browser'}",
f"--window-size={max(width, 500)},{height}", "--virtual-time-budget=1000",
"--dump-dom", f"http://127.0.0.1:{server.server_port}/"],
capture_output=True, text=True, timeout=20,
)
finally:
server.shutdown()
server.server_close()
thread.join(timeout=5)
assert result.returncode == 0, result.stderr
root = next((attrs for tag, attrs in Document(result.stdout).elements if tag == "html"), {})
assert "data-simlog-layout" in root, result.stdout[-1500:] + result.stderr[-1000:]
layout_data = json.loads(root["data-simlog-layout"])
viewport = layout_data["viewport"]
simlog = layout_data["simlog"]
assert simlog["width"] >= viewport["width"] - 2, layout_data
assert simlog["left"] >= -1 and simlog["right"] <= viewport["width"] + 1, layout_data
assert simlog["bottom"] <= viewport["height"] + 1, layout_data
assert layout_data["panel"]["right"] <= simlog["right"] + 1, layout_data
assert layout_data["current"]["right"] <= layout_data["panel"]["right"] + 1, layout_data
assert layout_data["entry"]["right"] <= layout_data["list"]["right"] + 1, layout_data
assert layout_data["dialog"]["right"] <= viewport["width"] + 1, layout_data
assert layout_data["plot"]["width"] > 0 and layout_data["plot"]["height"] > 0, layout_data
assert layout_data["plot"]["right"] <= layout_data["dialog"]["right"] + 1, layout_data
def test_cic_layout_rules_are_grid_based_and_bounded():
css = client_css()
shell = ASSET_DIR.joinpath("css", "shell.css").read_text()
# One grid with named areas; docks collapse to a rail; lists scroll, the page does not.
assert re.search(r"\.cic-grid \{[^}]*display: grid[^}]*grid-template-areas:", shell)
assert re.search(r"\.cic-grid\[data-left=\"closed\"\] \{ --left: var\(--rail-w\)", shell)
assert re.search(r"\.cic-grid\[data-tracks=\"false\"\] \{[^}]*grid-template-areas:", shell)
assert re.search(r"\.dock-body \{[^}]*overflow-y: auto", shell)
assert re.search(r"#shell \{[^}]*overflow: clip", shell)
# Breakpoints: single column below 900 px, a fourth column from 2400 px.
assert "@media (max-width: 899px)" in shell and "@media (min-width: 2400px)" in shell
wide = shell.split("@media (min-width: 2400px)", 1)[1]
assert '"left stage right detail"' in wide
# Critical alerts pulse; reduced motion switches every animation off.
assert re.search(r"\.alert-band \{[^}]*animation: glow", css)
assert "@media (prefers-reduced-motion: reduce)" in css
# Thin scrollbars and the design tokens drive every colour.
assert "scrollbar-width: thin" in css and "::-webkit-scrollbar" in css
assert re.search(r"--font-mono: \"JetBrains Mono\"", css) and re.search(r"--font-ui: \"Inter\"", css)
# Secondary tools open as overlays above the running station.
assert re.search(r"body\.workstation-mode \.tab-panel:not\(#panel-operations\):not\(\[hidden\]\) \{[^}]*position: fixed", css)
@pytest.mark.parametrize("width,height,zoom", [
(3840, 2160, 1), (2560, 1440, 1), (1920, 1080, 1), (1280, 720, 1), (390, 844, 1), (1280, 1024, 4),
])
@pytest.mark.parametrize("language", ["en", "de", "pseudo"])
def test_v2_lobby_layout_is_bounded(tmp_path, width, height, zoom, language):
chromium = shutil.which("chromium") or shutil.which("chromium-browser") or shutil.which("google-chrome")
if not chromium:
pytest.skip("Optional lobby layout regression: no installed Chromium")
css_width, css_height = width // zoom, height // zoom
source = catalogs()[language == "de"]
catalog = pseudolocale(source) if language == "pseudo" else source
html = inject_probe(index_html(), "lobby-layout.js")
stations = ("bridge", "sonar", "weapons", "damage", "opz", "radio",
"engine", "helicopter", "eloka", "uboot", "uboot_sonar",
"uboot_weapons", "uboot_engine", "uboot_esm", "uboot_nav")
empty_grants = {"command": False, "direct_fire": False, "sonar_audio": False}
session = {"protocol": 2, "client_id": "layout-client", "name": "Layout Lobby",
"csrf": "layout-csrf", "ordinal": 0, "presence": 1.0,
"next_command_seq": 0, "observer": False, "active_station": None,
"active_generation": 0, "simlog": False, "host": None,
"station": None, "requested_station": None, "station_generation": 0,
"stations": {
station: {
"status": "occupied" if station == "sonar" else "available",
"requested": False,
"request_generation": 0,
"station_generation": None,
"grants": dict(empty_grants),
} for station in stations
},
"grants": {"command": False, "direct_fire": False, "simlog": False,
"sonar_audio": False}}
class Handler(BaseHTTPRequestHandler):
def log_message(self, *_args):
pass
def reply(self, content, mime="application/json", status=200, cookie=None):
body = content if isinstance(content, bytes) else content.encode() if isinstance(content, str) else json.dumps(content).encode()
self.send_response(status)
self.send_header("Content-Type", mime)
if cookie:
self.send_header("Set-Cookie", cookie)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_GET(self):
if self.path == "/viewport":
self.reply(f''
f'', "text/html")
elif self.path == "/viewport.js":
self.reply('window.addEventListener("message", (event) => {'
'if (event.origin === location.origin && event.data?.lobbyLayout) '
'document.documentElement.dataset.lobbyLayout = JSON.stringify(event.data.lobbyLayout);});', "text/javascript")
elif self.path == "/":
self.reply(html, "text/html")
elif self.path == "/lobby-layout.js":
self.reply(LOBBY_LAYOUT, "text/javascript")
elif self.path in WEB_ROUTES:
self.reply(WEB_ROUTES[self.path][1], WEB_ROUTES[self.path][0])
elif self.path.startswith("/api/v2/ui?"):
self.reply({key: value for key, value in catalog.items() if key.startswith(PREFIX)})
elif self.path == "/api/v2/contacts":
self.reply(browser_contact_analysis())
elif self.path == "/api/v2/session":
self.reply({"error": "unauthorized"}, status=401)
else:
self.reply({"error": "not_found"}, status=404)
def do_POST(self):
body = json.loads(self.rfile.read(int(self.headers.get("Content-Length", "0"))))
if self.path == "/api/v2/pair" and body == {"code": "123ABC", "name": "Layout Lobby"}:
self.reply(session, cookie="ujagd_remote_v2=lobby; Path=/api/v2; HttpOnly; SameSite=Strict")
else:
self.reply({"error": "not_found"}, status=404)
server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
try:
result = subprocess.run(
[chromium, "--headless", "--no-sandbox", "--disable-gpu", "--disable-background-networking",
"--no-first-run", "--no-default-browser-check", "--disable-dev-shm-usage",
f"--user-data-dir={tmp_path / 'lobby-browser'}", f"--window-size={width},{height}",
"--force-device-scale-factor=1", "--virtual-time-budget=5000", "--dump-dom",
f"http://127.0.0.1:{server.server_port}/viewport"],
capture_output=True, text=True, timeout=45)
finally:
server.shutdown()
server.server_close()
thread.join(timeout=5)
assert result.returncode == 0, result.stderr
root = next(attrs for tag, attrs in Document(result.stdout).elements if tag == "html")
report = json.loads(root["data-lobby-layout"])
assert "error" not in report, report
assert report["cards"] == 15 and report["order"] == list(stations)
assert report["viewport"] == [css_width, css_height]
assert report["pageWidth"] <= css_width + 1 and report["pageHeight"] <= css_height + 1, report
assert report["controls"]
assert report["bridge"]["controls"] and report["bridge"]["labels"]
assert report["bridge"]["bounds"][0] >= -1
assert report["bridge"]["bounds"][2] <= css_width + 1
assert report["sonar"]["controls"] and report["sonar"]["labels"]
assert report["sonar"]["bounds"][0] >= -1
assert report["sonar"]["bounds"][2] <= css_width + 1
assert report["weapons"]["controls"] and report["weapons"]["labels"]
assert report["weapons"]["bounds"][0] >= -1
assert report["weapons"]["bounds"][2] <= css_width + 1
assert report["lobby"][0] >= -1 and report["lobby"][2] <= css_width + 1
# The submarine sonar room shares the sonar section, the boat's other
# stations share the submarine panel.
assert set(report["workstations"]) == set(stations) - {
"uboot_sonar", "uboot_weapons", "uboot_engine", "uboot_esm", "uboot_nav"}
for role, dashboard in report["workstations"].items():
assert not dashboard["intersects"], (role, dashboard)
assert dashboard["childIntersections"] == 0, (role, dashboard)
assert dashboard["childrenContained"], (role, dashboard)
assert not dashboard["textOverflow"], (role, dashboard)
assert dashboard["outer"][0] >= -1 and dashboard["outer"][2] <= css_width + 1
assert dashboard["visual"][0] >= dashboard["outer"][0] - 1
assert dashboard["visual"][2] <= dashboard["outer"][2] + 1
assert dashboard["controls"][0] >= dashboard["outer"][0] - 1
assert dashboard["controls"][2] <= dashboard["outer"][2] + 1
# On a desktop the instrument is the centrepiece: no dock is larger.
if css_width >= 900:
assert dashboard["stageLargest"], (role, dashboard)
# The CIC grid fills the viewport height even for sparse stations.
assert dashboard["outer"][3] >= css_height - 2, (role, dashboard)
LAYOUT_SCENARIO = r"""
const $ = (id) => document.getElementById(id);
const failures = [];
window.addEventListener("error", (event) => failures.push(event.message));
window.addEventListener("unhandledrejection", (event) => failures.push(String(event.reason)));
window.requestAnimationFrame = (callback) => setTimeout(() => callback(performance.now()), 16);
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
let sector;
let lookoutArcs = [];
const strokeRect = CanvasRenderingContext2D.prototype.strokeRect;
CanvasRenderingContext2D.prototype.strokeRect = function (x, y, width, height) {
if (this.getLineDash().length) sector = {x, y, width, height};
return strokeRect.call(this, x, y, width, height);
};
const arc = CanvasRenderingContext2D.prototype.arc;
CanvasRenderingContext2D.prototype.arc = function (x, y, radius, start, end, ...rest) {
if (this.canvas.id === "lookout") lookoutArcs.push({x, y, radius, start, end});
return arc.call(this, x, y, radius, start, end, ...rest);
};
async function run() {
for (let i = 0; $("shell").hidden && i < 300; i++) await sleep(20);
$("name").value = "Layout Watch";
$("code").value = "123ABC";
$("pair-form").requestSubmit();
for (let i = 0; $("operations").hidden && i < 300; i++) await sleep(20);
$("track-list").querySelector("button").click();
await sleep(100);
const rect = (element) => {
const r = element.getBoundingClientRect();
return {x: r.x, y: r.y, width: r.width, height: r.height, bottom: r.bottom, right: r.right};
};
const overlap = (a, b) => Math.min(a.right, b.right) - Math.max(a.x, b.x) > 1 &&
Math.min(a.bottom, b.bottom) - Math.max(a.y, b.y) > 1;
const selectors = [".workspace", ".contacts-panel", ".chart-panel", "#chart", ".details-panel", ".support-grid"];
const boxes = Object.fromEntries(selectors.map((selector) => [selector, rect(document.querySelector(selector))]));
const panels = [...document.querySelectorAll(".workspace > .panel, .support-grid > .panel")];
const intersections = [];
panels.forEach((a, i) => panels.slice(i + 1).forEach((b) => {
const x = rect(a), y = rect(b);
if (overlap(x, y)) intersections.push([a.className, b.className]);
}));
const navigationControls = [...$("navigation-form").querySelectorAll("label, input, button")];
const navigationIntersections = [];
navigationControls.forEach((a, i) => navigationControls.slice(i + 1).forEach((b) => {
if (overlap(rect(a), rect(b))) navigationIntersections.push([a.id || a.htmlFor, b.id || b.htmlFor]);
}));
const navigationLabels = ["navigation-course", "navigation-speed"].every((id) =>
document.querySelector(`label[for="${id}"]`)?.control === $(id));
const navigationControlSize = ["navigation-course", "navigation-speed", "propose-navigation"].every((id) => {
const bounds = rect($(id));
return bounds.width > 50 && bounds.height >= parseFloat(getComputedStyle(document.documentElement).fontSize) * 2.5;
});
const scrolls = {};
for (const selector of ["#track-list", ".details-panel", "#damage-list", "#event-list"]) {
const element = document.querySelector(selector);
const before = rect(element);
const owner = rect(element.closest(".panel"));
element.scrollTop = element.scrollHeight;
scrolls[selector] = {
height: element.clientHeight, content: element.scrollHeight, moved: element.scrollTop > 0,
contained: before.y >= owner.y - 1 && before.bottom <= owner.bottom + 1,
overflow: getComputedStyle(element).overflowY,
};
element.scrollTop = 0;
}
const last = $("track-list").lastElementChild;
$("track-list").firstElementChild.focus();
$("track-list").firstElementChild.dispatchEvent(new KeyboardEvent("keydown", {key: "End", bubbles: true}));
const visible = Math.min(rect(last).bottom, rect($("track-list")).bottom) - Math.max(rect(last).y, rect($("track-list")).y);
const keyboardReachable = document.activeElement === last && visible > 50;
$("track-list").scrollTop = 0;
$("propose-navigation").scrollIntoView({block: "nearest"});
$("propose-navigation").focus();
const navigationAction = rect($("propose-navigation"));
const detailBounds = rect(document.querySelector(".details-panel"));
const navigationReachable = document.activeElement === $("propose-navigation") &&
navigationAction.y >= detailBounds.y - 1 && navigationAction.bottom <= detailBounds.bottom + 1;
document.querySelector(".details-panel").scrollTop = 0;
const operationsPanel = $("panel-operations");
const supportReachable = [...document.querySelectorAll(".support-grid > .panel")].every((panel) => {
panel.scrollIntoView({block: "start"});
const bounds = rect(panel);
const owner = rect(operationsPanel);
return bounds.y >= owner.y - 1 && bounds.y < owner.bottom - 40;
});
document.querySelector("footer").scrollIntoView({block: "end"});
const footerBounds = rect(document.querySelector("footer"));
const panelBounds = rect(operationsPanel);
const footerReachable = footerBounds.y < panelBounds.bottom && footerBounds.bottom > panelBounds.y;
operationsPanel.scrollTop = Math.min(123, operationsPanel.scrollHeight - operationsPanel.clientHeight);
const operationScroll = operationsPanel.scrollTop;
$("tab-lookout").click();
await new Promise((resolve) => requestAnimationFrame(resolve));
const inactiveHidden = operationsPanel.hidden && !$("panel-lookout").hidden;
const lookoutPanel = $("panel-lookout");
const lookoutCanvas = $("lookout");
const lookoutChildren = [document.querySelector(".lookout-bar"), $("lookout-scope"), $("lookout-note")];
const lookoutIntersections = [];
lookoutChildren.forEach((a, i) => lookoutChildren.slice(i + 1).forEach((b) => {
if (overlap(rect(a), rect(b))) lookoutIntersections.push([a.className, b.className]);
}));
const lookoutBounds = rect(lookoutPanel);
const lookoutPlot = rect(lookoutCanvas);
const lookoutControls = [$("lookout-zoom-in"), $("lookout-zoom-out"), $("lookout-reset")];
$("lookout-reset").focus();
const lookout = {
panel: lookoutBounds, plot: lookoutPlot,
contained: lookoutChildren.every((element) => {
const bounds = rect(element);
return bounds.x >= lookoutBounds.x - 1 && bounds.right <= lookoutBounds.right + 1 &&
bounds.y >= lookoutBounds.y - 1 && bounds.bottom <= lookoutBounds.bottom + 1;
}),
intersections: lookoutIntersections,
controls: lookoutControls.every((control) => {
const bounds = rect(control);
return bounds.width > 20 && bounds.height >= 24 && !control.disabled;
}),
focus: document.activeElement === $("lookout-reset"),
backing: [lookoutCanvas.width, lookoutCanvas.height],
client: [lookoutCanvas.clientWidth, lookoutCanvas.clientHeight],
overflow: getComputedStyle(lookoutPanel).overflowY,
panelScroll: lookoutPanel.scrollHeight - lookoutPanel.clientHeight,
pageHeight: document.documentElement.scrollHeight,
pageWidth: document.documentElement.scrollWidth,
pageScroll: window.scrollY,
rings: lookoutArcs.filter((entry) => Math.abs(entry.x - lookoutCanvas.clientWidth / 2) < 1 &&
Math.abs(entry.y - lookoutCanvas.clientHeight / 2) < 1).map((entry) => entry.radius),
};
$("tab-guide").click();
const guidePanel = $("panel-guide");
guidePanel.scrollTop = 0;
$("guide-nav").querySelector('a[href="#guide-authority"]').click();
const guideBounds = rect(guidePanel);
const guide = {
overflow: getComputedStyle(guidePanel).overflowY,
moved: guidePanel.scrollTop > 0,
focus: document.activeElement === $("guide-authority"),
contained: [...guidePanel.querySelectorAll(".guide-nav, .guide-copy section")].every((element) => {
const bounds = rect(element);
return bounds.x >= guideBounds.x - 1 && bounds.right <= guideBounds.right + 1;
}),
links: [...$("guide-nav").querySelectorAll("a")].every((link) => {
const bounds = rect(link);
return bounds.width > 30 && bounds.height > 20;
}),
pageHeight: document.documentElement.scrollHeight,
pageWidth: document.documentElement.scrollWidth,
pageScroll: window.scrollY,
};
$("tab-contacts").click();
for (let i = 0; !$('analysis-list').querySelector('button') && i < 300; i++) await sleep(20);
$('analysis-list').querySelector('button')?.click();
const analyzerPanel = $('panel-contacts');
const analyzerList = $('analysis-list');
const analyzerDetail = document.querySelector('.analyzer-detail');
analyzerList.scrollTop = analyzerList.scrollHeight;
analyzerDetail.scrollTop = analyzerDetail.scrollHeight;
const analyzer = {
panelOverflow: getComputedStyle(analyzerPanel).overflowY,
panelScroll: analyzerPanel.scrollHeight - analyzerPanel.clientHeight,
listOverflow: getComputedStyle(analyzerList).overflowY,
listMoved: analyzerList.scrollTop > 0,
detailOverflow: getComputedStyle(analyzerDetail).overflowY,
detailMoved: analyzerDetail.scrollTop > 0,
pageHeight: document.documentElement.scrollHeight,
pageWidth: document.documentElement.scrollWidth,
};
$("tab-operations").click();
await new Promise((resolve) => requestAnimationFrame(resolve));
const panelScrollPreserved = operationsPanel.scrollTop === operationScroll;
const tabs = [...document.querySelectorAll('[role="tab"]')];
const tabIntersections = [];
tabs.forEach((a, i) => tabs.slice(i + 1).forEach((b) => {
if (overlap(rect(a), rect(b))) tabIntersections.push([a.id, b.id]);
}));
const pageHeight = document.documentElement.scrollHeight;
const pageScroll = window.scrollY;
operationsPanel.scrollTop = 0;
parent.scrollTo(0, 0);
const frozen = $("chart").toDataURL();
await sleep(700);
const report = {
width: innerWidth, height: innerHeight, boxes, sector, intersections, scrolls, keyboardReachable,
navigationIntersections, navigationLabels, navigationControlSize, navigationReachable,
supportReachable, footerReachable, pageHeight, pageScroll, operationScroll,
panelHeight: operationsPanel.clientHeight, panelOverflow: getComputedStyle(operationsPanel).overflowY,
panelScrollPreserved, inactiveHidden, tabIntersections, lookout,
pageWidth: document.documentElement.scrollWidth, contacts: $("track-list").children.length,
damage: $("damage-list").children.length, errors: failures,
stable: frozen === $("chart").toDataURL(), guide, analyzer,
};
parent.postMessage({layout: report}, location.origin);
}
window.addEventListener("DOMContentLoaded", () => run().catch((error) => {
parent.postMessage({layout: {error: String(error.stack || error)}}, location.origin);
}));
"""
@pytest.mark.parametrize("width,height", [(1920, 1080), (2560, 1440), (3840, 2160), (1280, 720), (390, 844)])
@pytest.mark.parametrize("zoom", [1, 2], ids=["100pct", "200pct-reflow"])
@pytest.mark.parametrize("language", ["en", "de"])
@pytest.mark.skip(reason="superseded by v2 lobby and nine-station workstation layout contracts")
def test_dense_commander_layout(tmp_path, width, height, zoom, language):
chromium = shutil.which("chromium") or shutil.which("chromium-browser") or shutil.which("google-chrome")
if not chromium:
pytest.skip("Optional layout regression: no installed Chromium")
# Browser zoom halves the CSS viewport and doubles physical pixels. Use a
# same-origin frame for exact reflow, including below Chromium's 500px minimum.
css_width, css_height = width // zoom, height // zoom
state = browser_state()
state["ownship"].update(x=180, y=320)
prototype = state["tracks"][1]
state["tracks"] = [dict(prototype, ref=f"fix-{i}", label=f"Contact-{i}-" + "LongUnbrokenLabel" * 6,
x=30 + i % 12 * 40, y=30 + i // 12 * 40,
source="LongUnbrokenSource" * 6) for i in range(120)]
state["ownship"]["damage"] = [dict(key=f"room-{i}", name=f"Compartment-{i}-" + "LongDamageLabel" * 8,
state="BESCHAEDIGT", flood=12, fire=9, teams=[1, 3]) for i in range(9)]
state["events"] = [dict(seq=i, kind="sensor", severity="warning", message="LongEventMessage" * 20)
for i in range(1, 81)]
state["mission"].update(name="Long mission name " * 6, objective="LongObjective" * 12)
chart = dict(revision=state["chart_revision"], size_nm=500,
landmasses=[dict(points=[[20, 20], [160, 40], [90, 160]])],
disclaimer="Synthetic test geography, not real bathymetry. " * 4)
catalog = catalogs()[language == "de"]
analysis = browser_contact_analysis()
prototype = analysis["profiles"][0]
prototype["reference"]["roles"] = ["LongReferenceRole" * 7 for _ in range(64)]
analysis["profiles"] = [dict(prototype, key=f"reference_{index}",
name=f"Reference profile {index}") for index in range(160)]
html = inject_probe(index_html(), "layout.js")
class Handler(BaseHTTPRequestHandler):
def log_message(self, *_args):
pass
def reply(self, content, mime="application/json"):
body = content if isinstance(content, bytes) else content.encode()
self.send_response(200)
self.send_header("Content-Type", mime)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_GET(self):
if self.path == "/viewport":
self.reply(f''
f'', "text/html")
elif self.path == "/viewport.js":
self.reply('window.addEventListener("message", (event) => {'
'if (event.origin === location.origin && event.data?.layout) '
'document.documentElement.dataset.layout = JSON.stringify(event.data.layout);});', "text/javascript")
elif self.path == "/":
self.reply(html, "text/html")
elif self.path == "/layout.js":
self.reply(LAYOUT_SCENARIO, "text/javascript")
elif self.path in WEB_ROUTES:
self.reply(WEB_ROUTES[self.path][1], WEB_ROUTES[self.path][0])
elif self.path.startswith("/api/v2/ui?"):
self.reply(json.dumps({key: value for key, value in catalog.items() if key.startswith(PREFIX)}))
elif self.path == "/api/v2/state":
state["seq"] += 1
self.reply(json.dumps(state))
elif self.path == "/api/v2/chart":
self.reply(json.dumps(chart))
elif self.path == "/api/v2/contacts":
self.reply(json.dumps(analysis))
else:
self.send_error(404)
def do_POST(self):
self.rfile.read(int(self.headers["Content-Length"]))
if self.path == "/api/v2/pair":
self.reply(json.dumps({}))
else:
self.send_error(405)
server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
try:
result = subprocess.run(
[chromium, "--headless", "--no-sandbox", "--disable-gpu", "--disable-background-networking",
"--no-first-run", "--no-default-browser-check", "--disable-dev-shm-usage",
f"--user-data-dir={tmp_path / 'browser'}", f"--window-size={width},{height}",
"--force-device-scale-factor=1", "--virtual-time-budget=5000", "--dump-dom",
f"http://127.0.0.1:{server.server_port}/viewport"],
capture_output=True, text=True, timeout=45,
)
finally:
server.shutdown()
server.server_close()
thread.join(timeout=5)
assert result.returncode == 0, result.stderr
document = Document(result.stdout)
root = next(attrs for tag, attrs in document.elements if tag == "html")
assert "data-layout" in root, result.stdout[-3000:]
report = json.loads(root["data-layout"])
(tmp_path / "layout.json").write_text(json.dumps(report, indent=2))
print(f"{language} {width}x{height} {zoom}x: {json.dumps(report)}")
assert "error" not in report, report
assert not report["errors"]
assert report["contacts"] == 120 and report["damage"] == 9
assert report["width"] == css_width and report["height"] == css_height
assert report["pageWidth"] <= css_width + 1
assert not report["intersections"]
assert not report["navigationIntersections"]
assert report["navigationLabels"] and report["navigationControlSize"]
assert report["keyboardReachable"] and report["navigationReachable"]
assert report["supportReachable"] and report["footerReachable"]
assert report["pageHeight"] <= css_height + 1
assert report["pageScroll"] == 0
assert report["panelHeight"] > 50 and report["panelOverflow"] == "auto"
assert report["operationScroll"] > 0 and report["panelScrollPreserved"]
assert report["inactiveHidden"] and not report["tabIntersections"]
lookout = report["lookout"]
assert lookout["contained"] and not lookout["intersections"]
assert lookout["controls"] and lookout["focus"]
assert lookout["plot"]["width"] > 50 and lookout["plot"]["height"] > 30
assert lookout["backing"] == lookout["client"]
assert lookout["overflow"] == "hidden" and lookout["panelScroll"] <= 1
assert lookout["pageWidth"] <= css_width + 1 and lookout["pageHeight"] <= css_height + 1
assert lookout["pageScroll"] == 0
rings = sorted(set(round(radius, 3) for radius in lookout["rings"]))
if lookout["client"][1] < 120:
assert len(rings) >= 2 and rings[-1] > 15
assert rings[-1] - rings[-2] > 7
else:
assert len(rings) >= 4
assert max(rings) <= min(lookout["client"]) / 2 + 1
assert report["stable"]
guide = report["guide"]
assert guide["overflow"] == "auto" and guide["moved"] and guide["focus"]
assert guide["contained"] and guide["links"]
assert guide["pageWidth"] <= css_width + 1 and guide["pageHeight"] <= css_height + 1
assert guide["pageScroll"] == 0
analyzer = report["analyzer"]
assert analyzer["panelOverflow"] == "hidden" and analyzer["panelScroll"] <= 1
assert analyzer["listOverflow"] == analyzer["detailOverflow"] == "auto"
assert analyzer["listMoved"] and analyzer["detailMoved"]
assert analyzer["pageWidth"] <= css_width + 1 and analyzer["pageHeight"] <= css_height + 1
for selector, scroll in report["scrolls"].items():
assert scroll["height"] > 50, selector
assert scroll["contained"] and scroll["overflow"] == "auto", (selector, scroll)
assert scroll["moved"] == (scroll["content"] > scroll["height"]), (selector, scroll)
boxes = report["boxes"]
plot = boxes["#chart"]
assert plot["bottom"] <= boxes[".chart-panel"]["bottom"]
assert abs(report["sector"]["width"] - report["sector"]["height"]) < .01
assert abs(report["sector"]["width"] - min(plot["width"], plot["height"]) * .9) < 2
assert abs(report["sector"]["x"] + report["sector"]["width"] / 2 - plot["width"] / 2) < 1
assert abs(report["sector"]["y"] + report["sector"]["height"] / 2 - plot["height"] / 2) < 1
if css_width > 1500:
assert .70 * css_height <= plot["height"] <= .75 * css_height
assert plot["width"] > .60 * css_width
else:
assert boxes[".chart-panel"]["bottom"] <= boxes[".contacts-panel"]["y"]
assert boxes[".chart-panel"]["bottom"] <= boxes[".details-panel"]["y"]
@pytest.mark.parametrize(("width", "height", "zoom"), [
(844, 390, 1), (844, 390, 2), (1280, 1024, 4),
])
@pytest.mark.parametrize("language", ["en", "de"])
@pytest.mark.skip(reason="superseded by v2 lobby and nine-station workstation layout contracts")
def test_short_landscape_and_400_percent_lookout_layout(
tmp_path, width, height, zoom, language):
test_dense_commander_layout(tmp_path, width, height, zoom, language)
@pytest.mark.parametrize("language", ["en", "de", "pseudo"])
@pytest.mark.parametrize("large", [False, True])
def test_native_host_menu_join_code_is_focal_and_bounded(language, large):
game = Game(seed=74, audio_enabled=False, language="en")
try:
game.preferences = replace(game.preferences, large_text=large)
game.translator = Translator("en")
if language == "pseudo":
game.translator.catalog = pseudolocale(load_catalog("en"))
elif language == "de":
game.translator = Translator("de")
game.tr = game.translator.t
game._apply_text_size()
console = game.commander
console.address = ("192.168.100.200", 65535)
console.pairing_code = "123ABC"
console.connected = True
console.bridge._proposal = dict(ref="ref", label="REMOVED-SUMMARY", status="pending")
with layout.capture_text() as text:
console.draw(game)
canvas = pygame.Rect(0, 0, 1280, 720)
assert len(console.row_rects()) == 6
assert all(canvas.contains(entry["bounds"]) for entry in text)
assert all(entry["bounds"].contains(entry["rect"]) for entry in text)
assert game.tr("commander.local.join_code") in {entry["text"] for entry in text}
code = next(entry for entry in text if entry["text"] == "123 ABC")
assert code["rect"].height >= 60
assert all("REMOVED-SUMMARY" not in entry["text"] for entry in text)
finally:
game.commander.stop()
game.audio.shutdown()
layout.configure_for(large_text=False)
@pytest.mark.parametrize("language", ["en", "de", "pseudo"])
@pytest.mark.parametrize("large", [False, True])
@pytest.mark.parametrize("kind", ["target", "navigation"])
def test_native_crew_confirmation_layout_is_bounded(language, large, kind, monkeypatch):
game = Game(seed=73, audio_enabled=False, language="en")
try:
game.preferences = replace(game.preferences, large_text=large)
game.translator = Translator("en")
if language == "pseudo":
game.translator.catalog = pseudolocale(load_catalog("en"))
elif language == "de":
game.translator = Translator("de")
game.tr = game.translator.t
game._apply_text_size()
console = game.commander
console.address = ("192.168.100.200", 65535)
console.server = type("Server", (), {
"connected": True, "stop": lambda self: None,
})()
console.bridge._allowed = True
console.bridge._proposal = dict(
ref="ref", label="{authored} " + "K" * 256, status="pending")
console.bridge._navigation_proposal = dict(
course=359.999, speed_kn=25.0, status="pending")
console.bridge._pending_seq = 9
console._confirm_signature, _ = console._confirmation_state()
console._confirm_identity = (id(game.world), id(game.sonar))
console._confirm_requested = True
console.confirm_kind = kind
monkeypatch.setattr(local, "load_catalog", Mock(
side_effect=AssertionError("draw I/O")))
with layout.capture_text() as text:
console.draw_confirm(game)
canvas = pygame.Rect(0, 0, 1280, 720)
assert text
assert canvas.contains(console.confirm_rect())
assert all(canvas.contains(rect) for rect in console.confirm_button_rects())
for entry in text:
assert canvas.contains(entry["bounds"]), entry
assert entry["bounds"].contains(entry["rect"]), entry
assert "commander.confirm" not in entry["text"], entry
finally:
game.commander.stop()
game.audio.shutdown()
layout.configure_for(large_text=False)
@pytest.mark.parametrize("width", [1280, 1536, 1920])
@pytest.mark.parametrize("language", ["en", "de"])
def test_status_bar_items_never_overlap(tmp_path, width, language):
"""The one-row status bar gives way (hides, truncates) instead of overlapping."""
from commander_web import run_module_probe
source = catalogs()[language == "de"]
probe = r"""
import { loadLanguage } from "./js/core/i18n.js";
import { metrics } from "./js/views/dom.js";
import { duration, t, timeOfDay } from "./js/core/format.js";
const $ = (id) => document.getElementById(id);
await loadLanguage("__LANG__");
$("bootstrap").hidden = true; $("shell").hidden = false; $("pairing").hidden = true;
document.body.classList.add("workstation-mode");
$("operations").hidden = false; $("workstation-station-label").hidden = false;
$("workstation-tools").hidden = false; $("disconnect").hidden = false; $("disabled-control-explain").hidden = false;
for (const [key, name] of [["1", "bridge"], ["2", "sonar"], ["6", "radio"], ["9", "eloka"]]) {
const tab = document.createElement("button"); tab.className = "station-tab";
const badge = document.createElement("span"); badge.className = "station-key"; badge.textContent = key;
tab.append(badge, t(`station_${name}`)); $("station-tabs").append(tab);
}
$("mission-name").textContent = "Doppeljagd im Nordmeer"; $("phase").textContent = t("phase_live");
metrics($("mission-metrics"), [["status_remaining", duration(10794)], ["status_elapsed", duration(3725)],
["status_world", timeOfDay(7.5)]]);
$("utc-clock").textContent = "10:25:18";
$("connection").dataset.state = "connected"; $("connection").textContent = t("connection_connected", {age: 0});
$("sound").textContent = t("sound_off");
requestAnimationFrame(() => {
const items = [...$("statusbar").querySelectorAll(":scope > *, .status-actions > *, .status-clocks > *, .status-mission > *")]
.filter((element) => getComputedStyle(element).display !== "none" && element.getClientRects().length);
const boxes = items.map((element) => [element, element.getBoundingClientRect()]);
const overlaps = [];
boxes.forEach(([a, first], index) => boxes.slice(index + 1).forEach(([b, second]) => {
if (a.contains(b) || b.contains(a)) return;
if (Math.min(first.right, second.right) - Math.max(first.left, second.left) > 1 &&
Math.min(first.bottom, second.bottom) - Math.max(first.top, second.top) > 1)
overlaps.push(`${a.id || a.className} / ${b.id || b.className}`);
}));
const bar = $("statusbar").getBoundingClientRect();
document.documentElement.dataset.result = JSON.stringify({overlaps, height: bar.height,
rightmost: Math.max(...boxes.map(([, box]) => box.right)), width: innerWidth,
remaining: $("mission-metrics").textContent});
});
""".replace("__LANG__", language)
ui = json.dumps({key: value for key, value in source.items() if key.startswith(PREFIX)}).encode()
root = run_module_probe(tmp_path, probe, window=(width, 400),
routes={f"/api/v2/ui?lang={language}": ("application/json", ui)})
assert "data-result" in root, root.get("data-failure")
report = json.loads(root["data-result"])
assert report["overlaps"] == [], report
assert report["rightmost"] <= report["width"] + 1, report
assert report["height"] < 60, report # one row
assert "2:59:54" in report["remaining"] and "1:02:05" in report["remaining"], report
@pytest.mark.parametrize("width,height", [(1280, 720), (1920, 1080), (2560, 1440)])
@pytest.mark.parametrize("tab", ["guide", "contacts", "lookout"])
def test_overlays_stay_inside_the_viewport_with_a_visible_close_button(tmp_path, width, height, tab):
from commander_web import run_module_probe
source = catalogs()[0]
probe = r"""
import { loadLanguage } from "./js/core/i18n.js";
import { activateTab } from "./js/views/lobby.js";
const $ = (id) => document.getElementById(id);
await loadLanguage("en");
$("bootstrap").hidden = true; $("shell").hidden = false; $("pairing").hidden = true;
document.body.classList.add("workstation-mode");
$("operations").hidden = false;
activateTab("__TAB__", false);
requestAnimationFrame(() => {
const box = (element) => element.getBoundingClientRect();
const panel = box($("panel-__TAB__"));
const close = $("panel-__TAB__").querySelector(".overlay-close");
const button = box(close);
const topmost = document.elementFromPoint(button.left + button.width / 2, button.top + button.height / 2);
document.documentElement.dataset.result = JSON.stringify({
panel: [panel.left, panel.top, panel.right, panel.bottom], viewport: [innerWidth, innerHeight],
button: [button.left, button.top, button.right, button.bottom], closeOnTop: topmost === close,
operationsVisible: !$("panel-operations").hidden});
});
""".replace("__TAB__", tab)
ui = json.dumps({key: value for key, value in source.items() if key.startswith(PREFIX)}).encode()
root = run_module_probe(tmp_path, probe, window=(width, height),
routes={"/api/v2/ui?lang=en": ("application/json", ui)})
assert "data-result" in root, root.get("data-failure")
report = json.loads(root["data-result"])
left, top, right, bottom = report["panel"]
assert left >= 0 and top >= 0 and right <= width and bottom <= height, report
bl, bt, br, bb = report["button"]
assert left <= bl and br <= right and top <= bt and bb <= bottom and br - bl >= 24, report
assert report["closeOnTop"] and report["operationsVisible"], report