"""Capture deterministic protocol-v2 Remote Crew workstation screenshots. Requires an installed Chromium, not Node, Playwright or a browser download. The production Game, CommanderBridge, CommanderServer, packaged browser assets, v2 session endpoint, HttpOnly cookie, and host station APIs are used throughout. The seeded simulation is advanced by a fixed amount and then frozen, so browser startup and polling timing cannot change the projected tactical state. Only an unguessable, capture-only in-memory page and script are augmented with capture checks. The pairing code is never added to a production asset, DOM, URL, browser profile output, screenshot name, or tool log, and is rotated immediately after the expected client pairs. Temporary HOME and Chromium profiles isolate preferences, saves, cookies, and caches. All captures are validated and the server is stopped before any image is copied to the requested output directory. """ from __future__ import annotations import argparse from concurrent.futures import ThreadPoolExecutor from dataclasses import dataclass from html.parser import HTMLParser import json import os from pathlib import Path import secrets import shutil import subprocess import sys import tempfile import time ROOT = Path(__file__).resolve().parents[1] ROLES = ("bridge", "sonar", "weapons", "damage", "opz", "radio", "engine", "helicopter", "eloka") UBOOT_ROLES = ("uboot", "uboot_sonar", "uboot_weapons", "uboot_engine", "uboot_esm", "uboot_nav", "uboot_radio") DESKTOP = (1920, 1080) HEADLESS_CHROME_PAD = 87 MOBILE = (500, 844) @dataclass(frozen=True) class Capture: name: str language: str width: int height: int role: str | None scene: str = "role" extra_roles: tuple[str, ...] = () aliases: tuple[str, ...] = () # Eyepiece pictures run in their own arranged world (``sight_capture``). sight: str | None = None def capture_specs() -> tuple[Capture, ...]: captures = [] for language in ("en", "de"): for role in ROLES: aliases = ("commander-overview.png",) if (language, role) == ("en", "opz") else () captures.append(Capture( f"commander-v2-{language}-{role}-desktop.png", language, *DESKTOP, role, aliases=aliases)) captures.extend(( Capture("commander-v2-en-lobby-mobile.png", "en", *MOBILE, None, scene="lobby"), Capture("commander-v2-en-sonar-mobile.png", "en", *MOBILE, "sonar", scene="sonar"), Capture("commander-v2-de-radio-mobile.png", "de", *MOBILE, "radio", scene="radio"), Capture("commander-v2-de-multi-station-mobile.png", "de", *MOBILE, "bridge", scene="multi", extra_roles=("sonar", "radio")), Capture("commander-wide.png", "en", 2560, 1440, "sonar"), Capture("commander-4k.png", "en", 3840, 2160, "bridge"), )) # The bridge lookout's binoculars and the submarine's periscope by day # and by night (the Mast & ESM station owns the periscope card). for language in ("en", "de"): for sight in ("day", "night"): captures.extend(( Capture(f"commander-v2-{language}-binoculars-{sight}.png", language, *DESKTOP, "bridge", scene="glasses", sight=sight), Capture(f"commander-v2-{language}-periscope-{sight}.png", language, *DESKTOP, "uboot_esm", scene="periscope", sight=sight), )) # The submarine's stations in one world (a crewed diesel boat # snorkelling; the engine room shows its console). for role in UBOOT_ROLES: captures.append(Capture( f"commander-v2-{language}-{role.replace('_', '-')}-desktop.png", language, *DESKTOP, role, sight="engine")) return tuple(captures) AUTOMATION = r""" (() => { "use strict"; let credential = __PAIRING_CODE__; const captureName = __CAPTURE_NAME__; const expectedLanguage = __LANGUAGE__; const expectedRole = __ROLE__; const scene = __SCENE__; // The colour theme to show (a theme name only; the client reads it from // the browser's storage like a player's own choice). const theme = __THEME__; if (theme) { try { localStorage.setItem("u-jagd-theme", theme); } catch (_) { errors++; } } // A theme capture shows the theme itself, not the red light over it. if (theme) addEventListener("DOMContentLoaded", () => { const red = $("red-light"); if (red && red.checked) { red.checked = false; red.dispatchEvent(new Event("change")); } }); let pairing = false; let errors = 0; let positioned = false; const $ = (id) => document.getElementById(id); console.error = () => { errors++; }; addEventListener("error", () => { errors++; }); addEventListener("unhandledrejection", () => { errors++; }); async function pairWithoutDom() { pairing = true; const code = credential; credential = ""; try { const response = await fetch("/api/v2/pair", { method: "POST", credentials: "same-origin", headers: {"Content-Type": "application/json"}, body: JSON.stringify({code, name: captureName}), }); if (!response.ok) throw new Error("capture_pairing_failed"); await response.text(); location.reload(); } catch (_) { errors++; } } function painted(canvas) { if (!canvas || canvas.closest("[hidden]") || canvas.width < 300 || canvas.height < 100) return false; const data = canvas.getContext("2d").getImageData(0, 0, canvas.width, canvas.height).data; for (let index = 0; index < data.length; index += 52) { if (data[index + 3] && (data[index] !== 7 || data[index + 1] !== 21 || data[index + 2] !== 28)) return true; } return false; } function instrumentFor(role) { if (scene === "glasses") return $("bridge-glasses-canvas"); if (scene === "periscope") return $("uboot-scope-canvas"); if (["bridge", "weapons", "opz", "helicopter"].includes(role)) return $("role-map"); if (role === "radio") return $("radio-df-scope"); if (role === "uboot_engine") return $("uboot-engine-dials"); if (role === "uboot") return $("uboot-depth-canvas"); if (role === "uboot_nav") return $("uboot-sounder-canvas"); if (role === "uboot_esm") return $("uboot-esm-canvas"); return $({sonar: "sonar-broadband", damage: "damage-schematic", engine: "engine-instruments", eloka: "eloka-scope"}[role]); } function positionMobileScene() { if (positioned) return; let target = null; if (scene === "sonar") target = $("sonar-audition-mode"); if (scene === "radio") target = $("radio-messages").lastElementChild || $("radio-messages"); if (scene === "multi") target = $("station-tabs"); if (scene === "glasses") target = $("bridge-glasses-canvas").closest("article"); if (scene === "periscope") target = $("uboot-scope-canvas").closest("article"); if (target) target.scrollIntoView({block: ["multi", "glasses", "periscope"].includes(scene) ? "start" : "center"}); else scrollTo(0, 0); positioned = true; } const timer = setInterval(() => { const report = document.documentElement.dataset; report.captureReady = "false"; if ($("shell").hidden) return; if (document.documentElement.lang !== expectedLanguage) { if (!$('language').disabled) { $("language").value = expectedLanguage; $("language").dispatchEvent(new Event("change")); } return; } if (!pairing && !$('pairing').hidden) { void pairWithoutDom(); return; } const connection = $("connection").dataset.state; const overflow = document.documentElement.scrollWidth > innerWidth; report.captureLanguage = document.documentElement.lang; report.captureConnection = connection; report.captureWidth = String(innerWidth); report.captureHeight = String(innerHeight); report.captureOverflow = String(overflow); report.captureErrors = String(errors); report.captureCredentialDom = String($("code").value !== ""); report.captureCookieHidden = String(!document.cookie.includes("ujagd_remote_v2")); if (scene === "lobby") { // Every station has a card; the lobby shows the frigate side's nine. const cards = [...$("station-cards").children].filter((card) => !card.hidden); report.captureRole = "lobby"; report.capturePainted = String(cards.length === 9 && cards.every((card) => card.querySelector("button"))); report.captureSelector = "true"; report.captureMessage = "true"; report.captureReady = String(connection === "lobby" && !$("lobby").hidden && cards.length === 9 && !overflow && !errors && !$("code").value); positionMobileScene(); return; } const section = expectedRole === "uboot_sonar" ? $("station-sonar") : $(`station-${expectedRole}`) || $("station-uboot"); const selectedRole = document.querySelector(".station-tab[aria-selected='true']")?.dataset.station || ""; const selectorCount = $("station-tabs").children.length; // An eyepiece card sizes and paints its canvas only once it is in view. if (["glasses", "periscope"].includes(scene) && section && !section.hidden && selectedRole === expectedRole) positionMobileScene(); const canvas = instrumentFor(expectedRole); // The binoculars redraw on a new state or a training press; a frozen // simulation sends no new state, so "Bow" (already the bearing) draws them. if (scene === "glasses" && positioned && canvas && canvas.width < 300) $("bridge-glasses-bow").click(); // Sonar and the helicopter (which opens on its acoustic page) show // waterfalls painted on an animation clock that headless Chromium's // virtual time does not advance; their controls are checked below. // The submarine's weapons and radio room are lists and forms, no canvas. const isPainted = ["sonar", "helicopter", "uboot_sonar", "uboot_weapons", "uboot_radio"] .includes(expectedRole) || painted(canvas); const sonarControls = scene !== "sonar" || ["sonar-audition-mode", "sonar-listen-band", "sonar-listen-notch"] .every((id) => $(id).getClientRects().length) && $("sonar-audition-mode").value === "FILTERED"; const radioMessage = scene !== "radio" || $("radio-messages").children.length >= 3; const selector = scene !== "multi" || selectorCount >= 3; report.captureRole = selectedRole; report.capturePainted = String(isPainted); report.captureSelector = String(selector); report.captureMessage = String(radioMessage); if (connection !== "connected" || $("operations").hidden || section.hidden || selectedRole !== expectedRole || !isPainted || !sonarControls || !radioMessage || !selector) return; positionMobileScene(); report.captureReady = String(!overflow && !errors && !$("code").value); }, 50); addEventListener("pagehide", () => { credential = ""; clearInterval(timer); }); })(); """ class CaptureReport(HTMLParser): def __init__(self, html: str): super().__init__() self.values = {} self.feed(html) def handle_starttag(self, tag, attrs): if tag == "html": self.values = { key.removeprefix("data-capture-"): value for key, value in attrs if key.startswith("data-capture-") } def _grant_capture(server, client_id: str, spec: Capture) -> None: if spec.role is None: return for station in (spec.role, *spec.extra_roles): if not server.grant_station(client_id, station): raise RuntimeError("host station grant failed") if not server.set_client_grant(client_id, station, "command", True): raise RuntimeError("host command grant failed") status = next(row for row in server.client_statuses() if row["client_id"] == client_id) generation = status["stations"][spec.role]["station_generation"] if not server.activate_station(client_id, spec.role, generation): raise RuntimeError("host station activation failed") def _capture_one(spec: Capture, temporary: Path, chromium: str, server, game, bridge, pygame, production_index, capture_clock, budget_ms: int, theme: str | None = None): index_type, production_html = production_index nonce = secrets.token_urlsafe(24) capture_name = f"Screenshot {nonce[:12]}" script_path = f"/.capture-{nonce}.js" page_path = f"/.capture-{nonce}.html" automation = (AUTOMATION .replace("__PAIRING_CODE__", json.dumps(server.pairing_code)) .replace("__CAPTURE_NAME__", json.dumps(capture_name)) .replace("__LANGUAGE__", json.dumps(spec.language)) .replace("__ROLE__", json.dumps(spec.role)) .replace("__SCENE__", json.dumps(spec.scene)) .replace("__THEME__", json.dumps(theme))) # The automation is its own classic script, run before the module client. entry = b'' assert entry in production_html server._http.assets[script_path] = ( "text/javascript; charset=utf-8", automation.encode("ascii")) server._http.assets[page_path] = ( index_type, production_html.replace( entry, b'' + entry, 1)) del automation image = temporary / spec.name profile = temporary / f"profile-{spec.name}" host, port = server.address process = subprocess.Popen( [chromium, "--headless", "--no-sandbox", "--disable-gpu", "--incognito", "--disable-background-networking", "--disable-sync", "--no-first-run", "--no-default-browser-check", "--disable-dev-shm-usage", "--no-proxy-server", "--host-resolver-rules=MAP * ~NOTFOUND, EXCLUDE 127.0.0.1", f"--lang={'de-DE' if spec.language == 'de' else 'en-US'}", "--force-device-scale-factor=1", f"--user-data-dir={profile}", # Headless Chromium keeps ~88 px of the window for browser chrome, so # the page would end above the screenshot's foot; open it taller and # crop to the requested size below. f"--window-size={spec.width},{spec.height + HEADLESS_CHROME_PAD}", f"--virtual-time-budget={budget_ms}", f"--screenshot={image}", "--dump-dom", f"http://{host}:{port}{page_path}"], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, ) client_id = None code_rotated = False try: with ThreadPoolExecutor(max_workers=1) as reader: result = reader.submit(process.communicate, timeout=40 + spec.width * spec.height // 150_000) while not result.done(): # Chromium advances performance.now() using virtual time. Advance # publication time too so a frozen simulation does not look stale. capture_clock[0] += 0.5 bridge.pump(game, server, now=capture_clock[0]) roster = server.client_statuses() expected = next((row for row in roster if row["name"] == capture_name), None) if expected is not None and client_id is None: client_id = expected["client_id"] _grant_capture(server, client_id, spec) if client_id is not None and not code_rotated: with server._lock: server._rotate_code_locked() code_rotated = True pygame.event.pump() time.sleep(.005) stdout, _ = result.result() report = CaptureReport(stdout.decode("utf-8", errors="replace")).values expected_role = spec.role or "lobby" expected = { "ready": "true", "language": spec.language, "connection": "lobby" if spec.role is None else "connected", "role": expected_role, "painted": "true", "selector": "true", "message": "true", "overflow": "false", "errors": "0", "credential-dom": "false", "cookie-hidden": "true", "width": str(spec.width), } failed = [key for key, value in expected.items() if report.get(key) != value] if (process.returncode != 0 or not image.is_file() or failed or client_id is None): print(f"{spec.name}: failed checks={','.join(failed)}, exit={process.returncode}, " f"image={image.is_file()}, paired={client_id is not None}, " f"connection={report.get('connection', 'missing')}, " f"role={report.get('role', 'missing')}, " f"painted={report.get('painted', 'missing')}, " f"selector={report.get('selector', 'missing')}, " f"message={report.get('message', 'missing')}, " f"overflow={report.get('overflow', 'missing')}, " f"errors={report.get('errors', 'missing')}, " f"viewport_width={int(report.get('width', 0))}, " f"viewport_height={int(report.get('height', 0))}", file=sys.stderr) raise RuntimeError(f"{spec.name}: browser did not reach a healthy v2 capture state") shot = pygame.image.load(image) if shot.get_size() != (spec.width, spec.height + HEADLESS_CHROME_PAD): raise RuntimeError(f"{spec.name}: unexpected screenshot dimensions") pygame.image.save(shot.subsurface((0, 0, spec.width, spec.height)).copy(), image) return image, report finally: if process.poll() is None: process.kill() process.communicate(timeout=5) if client_id is not None: server.revoke_client(client_id) server._http.assets.pop(script_path, None) server._http.assets.pop(page_path, None) def _workstation_world(game) -> None: """The seeded patrol the nine workstation captures show.""" game.set_sonar_audition_mode("FILTERED") game.set_sonar_band_preset("SHAFT") game.set_sonar_notch(True) # Two minutes on watch, so the sonar waterfalls carry a history; the # helicopter flies out and dips (its receiver runs while its deck is shown). game.launch_helicopter() game.helo.prep_s = 0.0 # the capture skips the 5-minute start preparation game.set_helicopter_waypoint(game.ship.x + 5.9, game.ship.y - 1.0) shown = game.station from src.core.station import Station game.station = Station.HELICOPTER for step in range(1200): if step == 600: game.set_helicopter_dipping(True) game.update(0.1) game.station = shown for _ in range(360): game.update(1 / 60) # Authored own-ship damage demonstrates the real damage UI; # contacts and mission intelligence still come from Game. for key, flood, fire in (("sonar", 12.0, 0.0), ("engine", 7.0, 9.0)): compartment = game.damage.compartments[key] compartment.state = "BESCHAEDIGT" compartment.flood, compartment.fire = flood, fire game.damage.teams = {1: "sonar", 2: "engine", 3: "engine"} ENGINE_SCENARIO = "s7_geleitzug" # a diesel-electric boat on seed 1234 def _engine_world(game, seed: int) -> None: """A crewed diesel boat snorkelling at slow ahead and charging, with a small authored leak aft, for the engine-room console capture.""" game.reset(seed, ENGINE_SCENARIO) game.local_side = "uboot" boat = game.claim_opfor_sub() if boat is None or boat.sub.endurance is None: raise RuntimeError("no diesel submarine for the engine-room picture") sub = boat.sub sub.set_orders(speed=6.0, depth=float(sub.endurance.profile.snorkel_depth_m)) # Authored stores: a battery worth charging. sub.endurance.battery_kwh = sub.endurance.profile.battery_capacity_kwh * 0.62 def run(seconds: float) -> None: for _ in range(round(seconds * 10)): game._opfor_hold_s = 3600.0 game.update(0.1) run(90.0) if sub.command_snorkel(True) is not True: raise RuntimeError("the engine-room boat did not start snorkelling") sub.damage_control.hull_leak(0.4, seed, where="stern") sub.command_dc_team(0, "stern", "seal") sub.command_bulkhead("engine", True) run(30.0) def capture_all(output: Path, seed: int, chromium: str, budget_ms: int = 8000, theme: str | None = None, only: tuple[str, ...] = ()) -> None: os.environ["SDL_VIDEODRIVER"] = "dummy" os.environ["SDL_AUDIODRIVER"] = "dummy" os.environ["PYGAME_HIDE_SUPPORT_PROMPT"] = "1" previous_home = os.environ.get("HOME") with tempfile.TemporaryDirectory(prefix="u-jagd-commander-v2-capture-") as directory: temporary = Path(directory) os.environ["HOME"] = str(temporary) sys.path.insert(0, str(ROOT)) staged = [] try: import pygame from src.commander.bridge import CommanderBridge from src.commander.server import CommanderServer from src.core.game import Game from src.core.i18n import load_catalog from src.core.preferences import Preferences from sight_capture import SIGHT_TIMES, sight_world translations = {lang: load_catalog(lang) for lang in ("en", "de")} hours = dict(SIGHT_TIMES) for language, sight in ((language, sight) for language in ("en", "de") for sight in (None, "engine", *hours)): specs = [item for item in capture_specs() if item.language == language and item.sight == sight and (not only or any(part in item.name for part in only))] if not specs: continue game = Game(seed=seed, start_menu=False, show_splash=False, preferences=Preferences(language=language, fullscreen=False, audio=False)) server = CommanderServer(translations) bridge = CommanderBridge() try: if sight is None: _workstation_world(game) elif sight == "engine": _engine_world(game, seed) else: sight_world(game, hours[sight]) # Keep browser rendering independent of performance.now(); # the OPZ sweep is otherwise the only continuously animated # workstation instrument after the simulation is frozen. game.surface_radar_on = False game.air_radar_on = False capture_clock = [time.monotonic()] bridge.pump(game, server, now=capture_clock[0]) server.start("127.0.0.1", 0) production_index = server._http.assets["/"] css_type, css = server._http.assets["/css/base.css"] server._http.assets["/css/base.css"] = (css_type, css + ( b"\n*,*::before,*::after{animation:none!important;" b"transition:none!important;caret-color:transparent!important}\n")) for spec in specs: image, report = _capture_one( spec, temporary, chromium, server, game, bridge, pygame, production_index, capture_clock, budget_ms, theme) staged.append((image, (spec.name, *spec.aliases), report)) finally: http, listener = server._http, server._thread workers = [] if http is not None: with http.work_lock: workers = list(http.workers) server.stop() if http is not None: http.assets.clear() if (server.connected or server.client_statuses() or server._thread is not None or server._http is not None or (listener is not None and listener.is_alive()) or any(worker.is_alive() for worker in workers)): raise RuntimeError("Commander capture service did not stop") game.commander.stop() game.audio.shutdown() pygame.quit() output.mkdir(parents=True, exist_ok=True) for image, names, report in staged: for name in names: destination = output / name shutil.copyfile(image, destination) print(f"{destination}: protocol=v2, language={report['language']}, " f"role={report['role']}, connected={report['connection']}, " "painted=true, overflow=false, js_errors=0, server_stopped=true") finally: if previous_home is None: os.environ.pop("HOME", None) else: os.environ["HOME"] = previous_home def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--output", type=Path, default=ROOT / "docs" / "screenshots") parser.add_argument("--seed", type=int, default=1234) parser.add_argument("--budget-ms", type=int, default=8000, help="Chromium virtual-time budget per capture (2000..15000; default: 8000)") parser.add_argument("--theme", choices=("night", "day", "contrast"), default=None, help="colour theme of the browser stations (default: the client's own, night)") parser.add_argument("--only", action="append", default=[], metavar="TEXT", help="capture only the screenshots whose file name contains TEXT (repeatable)") args = parser.parse_args() chromium = (shutil.which("chromium") or shutil.which("chromium-browser") or shutil.which("google-chrome")) if not chromium: parser.error("An installed Chromium is required; no browser will be downloaded") if not 2000 <= args.budget_ms <= 15000: parser.error("--budget-ms must be between 2000 and 15000") try: capture_all(args.output.resolve(), args.seed, chromium, args.budget_ms, args.theme, tuple(args.only)) except (OSError, RuntimeError, subprocess.TimeoutExpired) as error: # Never print browser output, injected JavaScript, request bodies, or credentials. print(f"Commander capture failed: {type(error).__name__}", file=sys.stderr) return 1 return 0 if __name__ == "__main__": raise SystemExit(main())