A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
tools: web_check's start-screen clicks follow the buttons (release blocker for v0.1.3) (#1229)
Eyal Golandbe3ddb7ba39
diff --git a/changelog.d/web-check-start-screen-clicks.md b/changelog.d/web-check-start-screen-clicks.mdnew file mode 100644index 000000000..ccd72d5ab--- /dev/null+++ b/changelog.d/web-check-start-screen-clicks.md@@ -0,0 +1,6 @@+### Fixed+- `tools/web_check.py --startscreen` and `--persistence` pass again: they clicked New game at a fixed point that #1178's+ Star on GitHub button moved it away from. Under `?navlog` the start screen now logs each shown button's centre+ (`NAV ... start buttons start-new-game=0.4167,0.9278 ...`), whenever the layout moves it, and both runs add `navlog`+ and click there; a run whose page never logs the button fails at once instead of stalling. Diagnostic only: without+ `?navlog` nothing changes, and no golden moves.diff --git a/tools/tests/test_web_check.py b/tools/tests/test_web_check.pyindex 15ded98d7..3c53298e2 100644--- a/tools/tests/test_web_check.py+++ b/tools/tests/test_web_check.py@@ -183,16 +183,79 @@ def test_find_chrome_without_chrome_path_picks_the_newest_revision(tmp_path, monassert wc.find_chrome() == found[1]+# A start buttons line as StartScreenPresenter logs it under ?navlog (a save: Continue shows), and the CSS pixels each+# centre maps to in the 1920x1080 viewport.+LAID_OUT = ("NAV f=88 t=9625 start buttons start-continue=0.3750,0.9278 start-new-game=0.4479,0.9278 "+ "start-star=0.5521,0.9278 start-listen=0.4229,0.8704")+AT = {"start-continue": (720, 1002), "start-new-game": (860, 1002), "start-star": (1060, 1002), "start-listen": (812, 940)}+++def _buttons(text=LAID_OUT, wait=0.0):+ buttons = wc.StartButtons((1920, 1080), wait=wait, sleep=lambda s: None)+ buttons.feed(text)+ return buttons+++def test_start_buttons_maps_the_logged_centres_onto_the_viewport():+ buttons = _buttons()+ assert {name: buttons.point(name) for name in AT} == AT+ phone = wc.StartButtons((390, 844))+ phone.feed("NAV f=1 t=2 start buttons start-new-game=0.5,0.75")+ assert phone.point("start-new-game") == (195, 633)+++def test_start_buttons_keeps_only_the_latest_layout_and_forgets_it_on_clear():+ buttons = _buttons()+ buttons.feed("NAV f=90 t=9700 start buttons start-new-game=0.5000,0.9000") # the row moved: Continue is gone+ assert buttons.point("start-new-game") == (960, 972)+ buttons.feed("console: start buttons start-new-game=0.1,0.1") # not a NAV line: ignored+ buttons.feed("RECORDING playing audio/declaration.wav (9.29 s, at 0.20 s)")+ assert buttons.point("start-new-game") == (960, 972)+ with pytest.raises(ValueError, match="START SCREEN FAIL no centre for start-continue .*logged: start-new-game"):+ buttons.point("start-continue")+ buttons.clear()+ with pytest.raises(ValueError, match="no start buttons line; the page needs [?]navlog"):+ buttons.point("start-new-game")+++def test_start_buttons_waits_for_a_line_the_reader_thread_brings():+ t = [0.0]+ buttons = wc.StartButtons((1920, 1080), wait=10, clock=lambda: t[0])++ def sleep(seconds):+ t[0] += seconds+ if t[0] >= 3:+ buttons.feed(LAID_OUT)+ buttons.sleep = sleep+ assert buttons.point("start-new-game") == AT["start-new-game"] and 3 <= t[0] < 3.2+++def test_start_buttons_fails_a_centre_outside_the_window():+ with pytest.raises(ValueError, match="start-star is outside the window"):+ _buttons("NAV f=1 t=2 start buttons start-star=1.0200,0.9000").point("start-star")+++def test_page_query_adds_navlog_only_to_the_start_screen_runs():+ assert wc.page_query(_args("--startscreen", "new")) == "navlog"+ assert wc.page_query(_args("--startscreen", "new", "--query", "lang=he")) == "lang=he&navlog"+ assert wc.page_query(_args("--persistence")) == "navlog"+ assert wc.page_query(_args("--startscreen", "recording", "--query", "navlog&lang=he")) == "navlog&lang=he"+ assert wc.page_query(_args("--query", "golden")) == "golden"++def test_persistence_check_reloads_after_a_settled_and_an_immediate_autosave(capsys):actions, sleeps = [], []- check = wc.PersistenceCheck(actions.append, sleeps.append)+ buttons = _buttons()+ check = wc.PersistenceCheck(actions.append, buttons, sleeps.append)check.feed("GAME OK 1948-05-15 turn 0 hash aa00")check.feed("TURN 1 1948-06-01 turn 1 hash one") # unrelated malformed diagnostic is ignoredcheck.feed("TURN 1 1948-06-01 hash aaa1")+ assert buttons.centres == {}, "a reload forgets the old page's layout"+ buttons.feed(LAID_OUT) # the reloaded page logs its owncheck.feed("GAME OK 1948-06-01 turn 1 hash aaa1")check.feed("TURN 2 1948-07-01 hash aaa2")check.feed("GAME OK 1948-07-01 turn 2 hash aaa2")- new_game, cont, end_turn = (f"click:{x},{y}" for x, y in (wc.NEW_GAME, wc.CONTINUE, wc.END_TURN))+ new_game, cont, end_turn = _clicks(AT["start-new-game"], AT["start-continue"], wc.END_TURN)assert actions == [new_game, end_turn, "reload", cont, end_turn, "reload"]assert sleeps == [3, 2, 2, 3, 2] # no wait between the second TURN and its reloadassert check.done@@ -200,7 +263,8 @@ def test_persistence_check_reloads_after_a_settled_and_an_immediate_autosave(capdef test_persistence_check_fails_when_the_immediate_reload_did_not_load_the_saved_turn():- check = wc.PersistenceCheck(lambda action: None, lambda seconds: None)+ buttons = _buttons()+ check = wc.PersistenceCheck(lambda action: action == "reload" and buttons.feed(LAID_OUT), buttons, lambda seconds: None)for text in ("GAME OK 1948-05-15 turn 0 hash aa", "TURN 1 1948-06-01 hash bb","GAME OK 1948-06-01 turn 1 hash bb", "TURN 2 1948-07-01 hash cc"):check.feed(text)@@ -218,7 +282,7 @@ def _played_to_the_settled_reload(check):def test_persistence_check_fails_when_the_settled_reload_did_not_load_the_saved_turn():- check = wc.PersistenceCheck(lambda action: None, lambda seconds: None)+ check = wc.PersistenceCheck(lambda action: None, _buttons(), lambda seconds: None)_played_to_the_settled_reload(check)with pytest.raises(ValueError, match="PERSISTENCE FAIL settled reload got 1948-05-15 turn 0"):check.feed("GAME OK 1948-05-15 turn 0 hash aa") # the reload came up with no save: a fresh game@@ -228,8 +292,9 @@ def test_persistence_check_fails_when_the_settled_reload_did_not_load_the_saved_def test_persistence_check_fails_when_continue_started_a_new_game():"""A click that misses Continue and starts a new game must not pass: the turn after Continue is the reloadedgame's next turn (2), not a new game's turn 1."""- check = wc.PersistenceCheck(lambda action: None, lambda seconds: None)+ check = wc.PersistenceCheck(lambda action: None, _buttons(), lambda seconds: None)_played_to_the_settled_reload(check)+ check.buttons.feed(LAID_OUT)check.feed("GAME OK 1948-06-15 turn 1 hash bb")with pytest.raises(ValueError, match="PERSISTENCE FAIL End turn after Continue: turn 1 .*expected turn 2"):check.feed("TURN 1 1948-06-15 hash cc")@@ -237,7 +302,7 @@ def test_persistence_check_fails_when_continue_started_a_new_game():def test_persistence_check_fails_when_the_first_boot_is_not_a_fresh_game():- check = wc.PersistenceCheck(lambda action: None, lambda seconds: None)+ check = wc.PersistenceCheck(lambda action: None, _buttons(), lambda seconds: None)with pytest.raises(ValueError, match="PERSISTENCE FAIL first boot"):check.feed("GAME OK 1948-06-15 turn 1 hash bb")@@ -258,32 +323,41 @@ def _clicks(*points):def test_start_screen_check_presses_new_game_then_end_turn_and_needs_turn_1(capsys):actions = []- check = wc.StartScreenCheck(actions.append, recording=False, hebrew=False, settle=lambda s: None)+ check = wc.StartScreenCheck(actions.append, recording=False, hebrew=False, buttons=_buttons(), settle=lambda s: None)check.feed("GAME OK 1948-05-15 turn 0 hash aa")- assert actions == _clicks(wc.NEW_GAME, wc.END_TURN)+ assert actions == _clicks(AT["start-new-game"], wc.END_TURN)assert not check.donecheck.feed("TURN 1 1948-06-15 hash bb")assert check.done- assert "START SCREEN OK New game reached the map: TURN 1" in capsys.readouterr().out+ out = capsys.readouterr().out+ assert "click start-new-game at (860, 1002)" in out and "START SCREEN OK New game reached the map: TURN 1" in out+++def test_start_screen_check_fails_at_once_when_the_game_never_says_where_new_game_is():+ check = wc.StartScreenCheck(lambda a: None, False, False, buttons=_buttons(""), settle=lambda s: None)+ with pytest.raises(ValueError, match="START SCREEN FAIL no centre for start-new-game"):+ check.feed("GAME OK 1948-05-15 turn 0 hash aa")def test_start_screen_check_plays_the_recording_first_and_waits_for_it_hebrew_layout():actions = []- check = wc.StartScreenCheck(actions.append, recording=True, hebrew=True, settle=lambda s: None)+ buttons = _buttons()+ check = wc.StartScreenCheck(actions.append, recording=True, hebrew=True, buttons=buttons, settle=lambda s: None)check.feed("GAME OK 1948-05-15 turn 0 hash aa")- assert actions == _clicks(wc.PLAY_RECORDING_HE)+ assert actions == _clicks(AT["start-listen"])check.feed("TURN 1 1948-06-15 hash bb") # no New game before the recording plays- assert actions == _clicks(wc.PLAY_RECORDING_HE) and not check.done+ assert actions == _clicks(AT["start-listen"]) and not check.done+ buttons.feed("NAV f=300 t=19000 start buttons start-new-game=0.5521,0.8000") # the caption moved the row upcheck.feed("RECORDING playing audio/declaration.wav (9.29 s, at 0.20 s)")- assert actions == _clicks(wc.PLAY_RECORDING_HE, wc.NEW_GAME, wc.END_TURN_HE)+ assert actions == _clicks(AT["start-listen"], (1060, 864), wc.END_TURN_HE)check.feed("TURN 1 1948-06-15 hash bb")assert check.donedef test_start_screen_check_fails_on_a_saved_game_or_a_wrong_turn():with pytest.raises(ValueError, match="START SCREEN FAIL the first boot is turn 3"):- wc.StartScreenCheck(lambda a: None, False, False, lambda s: None).feed("GAME OK 1948-08-15 turn 3 hash aa")- check = wc.StartScreenCheck(lambda a: None, False, False, lambda s: None)+ wc.StartScreenCheck(lambda a: None, False, False, _buttons(), lambda s: None).feed("GAME OK 1948-08-15 turn 3 hash aa")+ check = wc.StartScreenCheck(lambda a: None, False, False, _buttons(), lambda s: None)check.feed("GAME OK 1948-05-15 turn 0 hash aa")with pytest.raises(ValueError, match="START SCREEN FAIL End turn after New game logged turn 2"):check.feed("TURN 2 1948-07-15 hash cc")@@ -298,10 +372,10 @@ def test_query_value():def test_start_screen_check_english_recording_uses_the_english_layout():actions = []- check = wc.StartScreenCheck(actions.append, recording=True, hebrew=False, settle=lambda s: None)+ check = wc.StartScreenCheck(actions.append, recording=True, hebrew=False, buttons=_buttons(), settle=lambda s: None)check.feed("GAME OK 1948-05-15 turn 0 hash aa")check.feed("RECORDING playing audio/declaration.wav (9.29 s, at 0.20 s)")- assert actions == _clicks(wc.PLAY_RECORDING, wc.NEW_GAME, wc.END_TURN)+ assert actions == _clicks(AT["start-listen"], AT["start-new-game"], wc.END_TURN)def _args(*argv):@@ -309,7 +383,7 @@ def _args(*argv):def _plan(*argv):- driver, fail, plan = wc.run_plan(_args(*argv), lambda action: None)+ driver, fail, plan = wc.run_plan(_args(*argv), lambda action: None, _buttons())if driver is not None:driver.settle = lambda seconds: Nonereturn driver, fail, plan@@ -333,8 +407,7 @@ def test_a_start_screen_run_fails_on_boot_fail_exceptions_and_the_recording_whatdef test_the_start_screen_run_takes_the_hebrew_layout_from_the_query():he, _, _ = _plan("--startscreen", "recording", "--query", "lang=he&smoke=0")en, _, _ = _plan("--startscreen", "recording")- assert (he.play, he.end_turn) == (wc.PLAY_RECORDING_HE, wc.END_TURN_HE)- assert (en.play, en.end_turn) == (wc.PLAY_RECORDING, wc.END_TURN)+ assert (he.end_turn, en.end_turn) == (wc.END_TURN_HE, wc.END_TURN)def test_persistence_and_start_screen_are_separate_runs():diff --git a/tools/web_check.py b/tools/web_check.pyindex 95e62b3ab..cd97364d2 100644--- a/tools/web_check.py+++ b/tools/web_check.py@@ -17,7 +17,8 @@ Options: --query Q (page URL query, without '?'), --expect TEXT (repeatable), --immediately; both reloads must report the saved date, turn and hash), --startscreen new|recording (#908: on a freshprofile, the real start screen every player sees first: "new" presses New game, "recording" first presses Play therecording and waits for RECORDING playing; then End turn must log TURN 1; any console Exception, RECORDING failed or-BOOT FAIL fails the run; add --query lang=he for the Hebrew layout).+BOOT FAIL fails the run; add --query lang=he for the Hebrew layout). Both runs add ?navlog and click the start screen's+buttons where its "start buttons" line says they are (StartButtons).The page is opened over the DevTools protocol with its viewport fixed to 1920x1080 at the DPR before it loads(Emulation.setDeviceMetricsOverride: --window-size alone gives a 1920x937 viewport in --headless=new), and the runfails on any "res=" line, or any screenshot, of another size. --viewport WxH checks another window - 390x844 is the@@ -373,24 +374,75 @@ def drain(inbox: queue.Queue) -> list:return batch-# Button centres in CSS pixels of the fixed 1920x1080 viewport, measured on headless captures of this branch's WebGL-# build: the start screen's New game (alone, a fresh profile) and Continue (beside New game, a saved game), and the top-# bar's End turn (clickable while the first event card is open). Keys do not work here: Enter sent over CDP before any-# click reaches no Unity button, and after New game the first event card, not End turn, takes the focus.-NEW_GAME, CONTINUE, END_TURN = (960, 1002), (840, 1002), (1840, 45)-# The same buttons in the Hebrew layout (?lang=he), measured the same way: the top bar is mirrored, so End turn is at the-# left, and Play the recording sits left of its credit line. Play the recording in the English layout too.-PLAY_RECORDING, PLAY_RECORDING_HE, END_TURN_HE = (812, 940), (851, 940), (80, 45)+# The top bar's End turn (clickable while the first event card is open) in CSS pixels of the fixed 1920x1080 viewport,+# measured on headless captures, and in the Hebrew layout (?lang=he: the top bar is mirrored, so End turn is at the left).+# Keys do not work here: Enter sent over CDP before any click reaches no Unity button, and after New game the first event+# card, not End turn, takes the focus.+END_TURN, END_TURN_HE = (1840, 45), (80, 45)+# The start screen's buttons are not measured: their row changes as buttons are added (#1178's Star on GitHub moved New+# game off the viewport's centre), so the game says where they are. Under ?navlog, StartScreenPresenter.ButtonCentres logs+# each shown button's centre as a fraction of the window, again whenever the layout moves it:+# NAV f=4 t=4094 start buttons start-new-game=0.4167,0.9278 start-star=0.5833,0.9278 start-listen=0.4229,0.8704+NEW_GAME, CONTINUE, PLAY_RECORDING = "start-new-game", "start-continue", "start-listen"+START_BUTTONS = re.compile(r"^NAV f=\d+ t=\d+ start buttons (.+)$")+START_BUTTON = re.compile(r"(\S+)=(\d+(?:\.\d+)?),(\d+(?:\.\d+)?)")+NAVLOG = "navlog"GAME_STATE = re.compile(r"^GAME OK (\d{4}-\d{2}-\d{2}) turn (\d+) hash ([0-9a-f]+)$")TURN_STATE = re.compile(r"^TURN (\d+) (\d{4}-\d{2}-\d{2}) hash ([0-9a-f]+)$")+class StartButtons:+ """Where the start screen's buttons are: the latest "start buttons" line (START_BUTTONS), fed from the stderr reader+ thread, so a click uses the layout logged while its driver was waiting. `point` maps a button's centre onto the+ viewport in CSS pixels, waiting up to `wait` seconds for it, and fails at once (not a stall) when it never comes."""++ def __init__(self, viewport: tuple[int, int], wait: float = 10.0, clock=time.monotonic, sleep=time.sleep):+ self.viewport, self.wait, self.clock, self.sleep = viewport, wait, clock, sleep+ self.lock, self.centres = threading.Lock(), {}++ def feed(self, text: str) -> None:+ m = START_BUTTONS.match(text)+ if m:+ centres = {name: (float(x), float(y)) for name, x, y in START_BUTTON.findall(m.group(1))}+ with self.lock:+ self.centres = centres++ def clear(self) -> None:+ """Forgets the layout: before a reload, so the new page's line is waited for."""+ with self.lock:+ self.centres = {}++ def point(self, name: str) -> tuple[int, int]:+ deadline = self.clock() + self.wait+ while True:+ with self.lock:+ centre, known = self.centres.get(name), sorted(self.centres)+ if centre is not None:+ break+ if self.clock() >= deadline:+ raise ValueError(f"START SCREEN FAIL no centre for {name} within {self.wait:.0f} s (logged: "+ f"{', '.join(known) or 'no start buttons line'}; the page needs ?{NAVLOG})")+ self.sleep(0.1)+ fx, fy = centre+ if not (0 < fx < 1 and 0 < fy < 1):+ raise ValueError(f"START SCREEN FAIL {name} is outside the window: centre at {fx:g}, {fy:g} of it")+ return round(fx * self.viewport[0]), round(fy * self.viewport[1])+++def click_button(action, buttons: StartButtons, name: str) -> None:+ """A left click on a start-screen button where the game says it is; printed, so a stalled run shows where it clicked."""+ x, y = buttons.point(name)+ print(f"click {name} at ({x}, {y})")+ action(f"click:{x},{y}")++class PersistenceCheck:"""Drives and checks the two reloads of issue #910. `action` is Page.command (injected, so the unit tests need no- browser); a reload keeps the page's profile and origin, so its IndexedDB autosave."""+ browser); a reload keeps the page's profile and origin, so its IndexedDB autosave. `buttons` says where the start+ screen's buttons are."""- def __init__(self, action, settle=time.sleep):- self.action, self.settle = action, settle+ def __init__(self, action, buttons: StartButtons, settle=time.sleep):+ self.action, self.buttons, self.settle = action, buttons, settleself.stage, self.saved, self.done = "first_boot", None, Falsedef feed(self, text: str) -> None:@@ -412,6 +464,7 @@ class PersistenceCheck:self._turn(state, 1, "first End turn after New game")self.saved = stateself.settle(2) # ordinary reload: give IDBFS autosync time to settle+ self.buttons.clear()self.action("reload")self.stage = "settled_reload"elif self.stage == "settled_reload" and kind == "GAME":@@ -427,6 +480,7 @@ class PersistenceCheck:# button would otherwise pass).self._turn(state, self.saved[1] + 1, "End turn after Continue")self.saved = state+ self.buttons.clear()self.action("reload") # deliberately no settling delay after the TURN acknowledgementself.stage = "immediate_reload"elif self.stage == "immediate_reload" and kind == "GAME":@@ -434,8 +488,11 @@ class PersistenceCheck:print(f"PERSISTENCE immediate reload OK {state[0]} turn {state[1]} hash {state[2]}")self.done = True- def click(self, point: tuple[int, int]) -> None:- self.action(f"click:{point[0]},{point[1]}")+ def click(self, target: str | tuple[int, int]) -> None:+ if isinstance(target, str):+ click_button(self.action, self.buttons, target)+ else:+ self.action(f"click:{target[0]},{target[1]}")@staticmethoddef _turn(state, expected: int, what: str) -> None:@@ -457,11 +514,12 @@ def query_value(query: str, key: str) -> str | None:class StartScreenCheck:"""Issue #908: the start screen of a fresh profile, as a player meets it (no automation flag skips it). New game- (after Play the recording when `recording`) and End turn must reach the map's first turn. `action` is Page.command."""+ (after Play the recording when `recording`) and End turn must reach the map's first turn. `action` is Page.command;+ `buttons` says where the start screen's buttons are."""- def __init__(self, action, recording: bool, hebrew: bool, settle=time.sleep):- self.action, self.recording, self.settle = action, recording, settle- self.play, self.end_turn = (PLAY_RECORDING_HE, END_TURN_HE) if hebrew else (PLAY_RECORDING, END_TURN)+ def __init__(self, action, recording: bool, hebrew: bool, buttons: StartButtons, settle=time.sleep):+ self.action, self.recording, self.buttons, self.settle = action, recording, buttons, settle+ self.end_turn = END_TURN_HE if hebrew else END_TURNself.stage, self.done = "boot", Falsedef feed(self, text: str) -> None:@@ -471,7 +529,7 @@ class StartScreenCheck:raise ValueError(f"START SCREEN FAIL the first boot is turn {game.group(2)}, not a fresh game")self.settle(3) # the start screen lays out and takes inputif self.recording:- self.click(self.play)+ self.click(PLAY_RECORDING)self.stage = "recording"else:self.new_game()@@ -491,8 +549,11 @@ class StartScreenCheck:self.click(self.end_turn)self.stage = "turn"- def click(self, point: tuple[int, int]) -> None:- self.action(f"click:{point[0]},{point[1]}")+ def click(self, target: str | tuple[int, int]) -> None:+ if isinstance(target, str):+ click_button(self.action, self.buttons, target)+ else:+ self.action(f"click:{target[0]},{target[1]}")def watch(inbox, poll, join_reader, expect, fail, timeout, now=time.time, sleep=time.sleep, on_text=None, stall=0,@@ -557,16 +618,24 @@ START_SCREEN_FAILS = r"BOOT FAIL|Exception|RECORDING failed"DRIVER_GRACE = 3.0-def run_plan(a, command):+def page_query(a) -> str:+ """The page's query: --query, plus ?navlog for the runs that click the start screen (StartButtons). navlog only logs:+ it skips nothing, so the start screen is still the one a player meets."""+ if not (a.startscreen or a.persistence) or query_value(a.query, NAVLOG) is not None:+ return a.query+ return f"{a.query}&{NAVLOG}" if a.query else NAVLOG+++def run_plan(a, command, buttons: StartButtons):"""What a run drives and fails on: (driver or None, the failure regex, watch's keyword arguments). `command` is- Page.command."""+ Page.command; `buttons` is fed the console by the caller."""if a.persistence and a.startscreen:raise ValueError("--persistence and --startscreen are separate runs")if a.startscreen:- driver = StartScreenCheck(command, a.startscreen == "recording", query_value(a.query, "lang") == "he")+ driver = StartScreenCheck(command, a.startscreen == "recording", query_value(a.query, "lang") == "he", buttons)fail, what = f"(?:{a.fail})|{START_SCREEN_FAILS}", f"the end of the --startscreen {a.startscreen} run"elif a.persistence:- driver, fail, what = PersistenceCheck(command), a.fail, "the end of the --persistence run"+ driver, fail, what = PersistenceCheck(command, buttons), a.fail, "the end of the --persistence run"else:return None, re.compile(a.fail), {}return driver, re.compile(fail), {"complete": lambda: driver.done, "complete_what": what, "grace": DRIVER_GRACE}@@ -602,6 +671,7 @@ def main() -> int:sys.exit(str(e))res = expected_res(w, h, a.dpr)shots = ShotCollector(a.shots, size=(round(w * a.dpr), round(h * a.dpr)))+ buttons = StartButtons((w, h))def on_text(text: str) -> bool:err = res_error(text, res)@@ -611,7 +681,8 @@ def main() -> int:try:chrome = find_chrome()server = serve(a.build)- url = f"http://localhost:{server.server_address[1]}/index.html" + (f"?{a.query}" if a.query else "")+ query = page_query(a)+ url = f"http://localhost:{server.server_address[1]}/index.html" + (f"?{query}" if query else "")proc = subprocess.Popen([str(chrome), *chrome_flags(profile, a.swiftshader, a.dpr), "about:blank"],stderr=subprocess.PIPE, stdout=subprocess.DEVNULL, text=True, errors="replace")inbox: queue.Queue = queue.Queue()@@ -620,6 +691,9 @@ def main() -> int:def read():for raw in iter(proc.stderr.readline, ""):for line in rejoin.feed(raw):+ console = CONSOLE.search(line)+ if console:+ buttons.feed(console.group(1)) # here, not in watch: a driver waiting in settle() sees itinbox.put(line)for line in rejoin.flush():inbox.put(line)@@ -629,7 +703,7 @@ def main() -> int:page = Page(profile, url, w, h, a.dpr, a.mobile)page.open()print(f"viewport {w}x{h} at DPR {a.dpr:g}{' mobile' if a.mobile else ''} (expect res={res})")- driver, fail, plan = run_plan(a, page.command)+ driver, fail, plan = run_plan(a, page.command, buttons)def handle_text(text: str) -> bool:consumed = on_text(text)diff --git a/unity/Assets/Scripts/UI/StartScreenPresenter.cs b/unity/Assets/Scripts/UI/StartScreenPresenter.csindex dd1ea6351..52e098514 100644--- a/unity/Assets/Scripts/UI/StartScreenPresenter.cs+++ b/unity/Assets/Scripts/UI/StartScreenPresenter.cs@@ -1,5 +1,6 @@#nullable enableusing System;+using System.Collections.Generic;using System.Linq;using Statecraft.Game.Boot;using UnityEngine;@@ -17,7 +18,8 @@ namespace Statecraft.Game.UI/// press never wipes the save (#175, B6). Continue and Escape withdraw an open request./// While it shows, the root has OpenClass (Statecraft.uss hides the HUD under it, so Tab reaches only these buttons)/// and <c>shownChanged</c> is told, so GameRoot can stop the camera keys. The panel's source line says the painting is- /// AI-generated. Beside New game, "Star on GitHub" opens the repository in a new tab (#1168, ExternalLink).</summary>+ /// AI-generated. Beside New game, "Star on GitHub" opens the repository in a new tab (#1168, ExternalLink). Under ?navlog it+ /// logs where its buttons are (ButtonCentres), so tools/web_check.py clicks them wherever the layout puts them.</summary>public sealed class StartScreenPresenter : IDisposable{/// <summary>On the "root" element while the start screen shows.</summary>@@ -53,6 +55,12 @@ namespace Statecraft.Game.UIreadonly PressSource presses;readonly Action unbindStar;readonly Button starButton;+ readonly EventCallback<GeometryChangedEvent> onLaidOut;+ readonly VisualElement[] laidOut;+ string? loggedCentres;++ /// <summary>The buttons ButtonCentres reports, by name.</summary>+ public static readonly string[] Buttons = { "start-continue", "start-new-game", "start-star", "start-listen" };/// <summary>Continue is offered: the session continues the autosave.</summary>public bool Resumed { get; private set; }@@ -97,6 +105,48 @@ namespace Statecraft.Game.UIscreen.RegisterCallback(onGeometry);panel.RegisterCallback(onGeometry); // the panel's height decides where it goespresses = new PressSource(screen);+ // ?navlog: a button moves when it, its row, the panel (bottom-anchored, it grows upward) or the body moves.+ onLaidOut = _ => LogCentres();+ laidOut = new[] { screen, body, panel, screen.Q("start-recording"), screen.Q("start-actions") }+ .Concat(Buttons.Select(n => (VisualElement)screen.Q<Button>(n))).ToArray();+ foreach (var e in laidOut) e.RegisterCallback(onLaidOut);+ }++ /// <summary>Each shown button's centre as a fraction of the panel's width and height, in Buttons' order:+ /// "start buttons start-new-game=0.4167,0.9278 start-star=0.5833,0.9278 ..." (invariant culture). A fraction maps+ /// onto the browser's viewport at any DPR or panel scale; tools/web_check.py clicks there (--startscreen,+ /// --persistence). Null while the screen is closed or not laid out.</summary>+ public string? ButtonCentres()+ {+ var window = screen.panel?.visualTree.worldBound ?? Rect.zero;+ if (!IsOpen || float.IsNaN(window.width) || window.width <= 0 || window.height <= 0) return null;+ var parts = new List<string>();+ foreach (var name in Buttons)+ {+ var b = screen.Q<Button>(name);+ var r = b.worldBound;+ if (!Displayed(b) || float.IsNaN(r.width) || r.width <= 0 || r.height <= 0) continue;+ parts.Add(FormattableString.Invariant(+ $"{name}={(r.center.x - window.xMin) / window.width:0.0000},{(r.center.y - window.yMin) / window.height:0.0000}"));+ }+ return parts.Count == 0 ? null : "start buttons " + string.Join(" ", parts);+ }++ static bool Displayed(VisualElement e)+ {+ for (var v = e; v != null; v = v.hierarchy.parent)+ if (v.resolvedStyle.display == DisplayStyle.None) return false;+ return true;+ }++ /// <summary>Under ?navlog (DiagLog.Nav): logs ButtonCentres on a NAV line whenever it changes while the screen shows.</summary>+ void LogCentres()+ {+ if (!DiagLog.Nav) return;+ var centres = ButtonCentres();+ if (centres == null || centres == loggedCentres) return;+ loggedCentres = centres;+ DiagLog.NavLine(centres);}public bool IsOpen => hudRoot.ClassListContains(OpenClass);@@ -126,6 +176,7 @@ namespace Statecraft.Game.UIif (!IsOpen) return;recording?.Stop();hudRoot.RemoveFromClassList(OpenClass);+ loggedCentres = null;ScreenNav.DisableCovered(hudRoot);var focused = screen.focusController?.focusedElement as VisualElement;if (focused != null && screen.Contains(focused))@@ -215,6 +266,7 @@ namespace Statecraft.Game.UIscreen.UnregisterCallback(onCancel);screen.UnregisterCallback(onGeometry);panel.UnregisterCallback(onGeometry);+ foreach (var e in laidOut) e.UnregisterCallback(onLaidOut);}}}diff --git a/unity/Assets/Tests/EditMode/StartScreenTests.cs b/unity/Assets/Tests/EditMode/StartScreenTests.csindex 61806e716..bf7602ba6 100644--- a/unity/Assets/Tests/EditMode/StartScreenTests.cs+++ b/unity/Assets/Tests/EditMode/StartScreenTests.cs@@ -618,6 +618,54 @@ public class StartScreenTests}}+ /// <summary>tools/web_check.py clicks the screen's buttons where ?navlog says they are (--startscreen, --persistence):+ /// the NAV line names every shown button (Continue only with a save; the recording's button once its row shows), each+ /// at its own centre to half a pixel as a fraction of the window; the last line logged is the current layout; and+ /// without ?navlog nothing is logged.</summary>+ [UnityTest]+ public IEnumerator UnderNavlogItLogsWhereEachShownButtonIs()+ {+ var wasNav = DiagLog.Nav;+ var logged = new List<string>();+ void Capture(string message, string trace, LogType type) { if (message.Contains(" start buttons ")) logged.Add(message); }+ Application.logMessageReceived += Capture;+ try+ {+ foreach (var save in new[] { false, true })+ {+ DiagLog.Nav = true; logged.Clear();+ using var rig = new Rig(save ? WithSave(TempStore(), 1) : TempStore());+ for (int i = 0; i < 6; i++) yield return null;+ var line = rig.Start.ButtonCentres();+ Assert.IsNotNull(line, $"save={save}: the screen is laid out");+ Assert.IsNotEmpty(logged, $"save={save}: a NAV line is logged");+ StringAssert.IsMatch(@"^NAV f=\d+ t=\d+ start buttons ", logged[^1]);+ Assert.AreEqual(line, logged[^1].Substring(logged[^1].IndexOf("start buttons ", StringComparison.Ordinal)), "the last line is the current layout");+ var window = rig.Ui.Root.panel.visualTree.worldBound;+ var centres = Regex.Matches(line!, @"(\S+)=([0-9.]+),([0-9.]+)").Cast<Match>().ToDictionary(m => m.Groups[1].Value,+ m => new Vector2(window.xMin + window.width * float.Parse(m.Groups[2].Value, System.Globalization.CultureInfo.InvariantCulture),+ window.yMin + window.height * float.Parse(m.Groups[3].Value, System.Globalization.CultureInfo.InvariantCulture)));+ var shown = save ? StartScreenPresenter.Buttons : StartScreenPresenter.Buttons.Where(b => b != "start-continue").ToArray();+ CollectionAssert.AreEqual(shown, centres.Keys, $"save={save}: {line}");+ foreach (var (name, at) in centres.Select(kv => (kv.Key, kv.Value)))+ {+ var r = rig.Ui.Q<Button>(name).worldBound;+ Assert.AreEqual(r.center.x, at.x, 0.5f, $"save={save}: {name} x ({r})");+ Assert.AreEqual(r.center.y, at.y, 0.5f, $"save={save}: {name} y ({r})");+ Assert.IsTrue(r.Contains(at) && window.Contains(at), $"save={save}: {name}'s centre {at} is on it and in the window");+ }+ }+ DiagLog.Nav = false; logged.Clear();+ using (var quiet = new Rig(TempStore()))+ {+ for (int i = 0; i < 6; i++) yield return null;+ Assert.IsNotNull(quiet.Start.ButtonCentres(), "precondition: laid out");+ Assert.IsEmpty(logged, "without ?navlog nothing is logged");+ }+ }+ finally { Application.logMessageReceived -= Capture; DiagLog.Nav = wasNav; }+ }+// --- The scene ---------------------------------------------------------------------------------------------------static GameInputs? inputs;