Files
2026-11-23 03:28:32 +02:00

326 lines
14 KiB
Python

#!/usr/bin/env python3
"""Use the already-active S5 local test window to enter the single reviewed roster fixture."""
import argparse
import hashlib
import io
from itertools import groupby
import json
import os
import re
import subprocess
import time
from pathlib import Path
from PIL import Image, ImageChops, ImageStat
from Xlib import X, display
import client_ui as ui
from owned_account_relogin import ACCOUNT_FIXTURE, fixture_row, fixture_row_ink, fixture_selected, require_fixture
JOBS = ui.ROOT / 'runtime/continuation-20261113/codex'
REFERENCE = JOBS / 's5-ac99-grouped-local-20261121'
LOCAL_TREE = Path('/mnt/Games/@wowhybrid/builds/Forever-Local-Disposable-20261110/runtime/s5-ac99-grouped-local-20261121/_classic_beta_')
LOCAL_PINS = {
'GWNativeBridge.dll': 'fd7543b146e305f7d340583e75aa7fe76d0f5d7b67d240febe75c6b6f71d60c5',
'GWNativeWire.dll': '70e81fe325e96084e9ec3204b7316250b4f8e0b9022da03ba9f4dbabfc8e3bde',
}
HUD_WIRE_SHA256 = '733d08c0796e6f60d17f3c4f0e9f5e6d1f9bace5b3f12f284025243a25acacec'
# Bright-pixel coverage on a 12-by-2 grid over the chooser title and its
# explanation, measured from the private 768x432 capture 225d8d78874e.
RULESET_LABELS = (
((314, 88, 454, 99), 90,
(50, 46, 53, 53, 50, 43, 57, 77, 28, 60, 62, 42, 47, 65, 59, 47, 65, 64, 68, 74, 59, 59, 60, 43)),
((262, 102, 506, 112), 65,
(41, 41, 36, 43, 39, 36, 41, 34, 43, 51, 39, 28, 41, 49, 59, 51, 61, 51, 61, 54, 61, 46, 51, 33)),
)
FORM_AREAS = ((451, 253, 509, 266), (448, 289, 511, 303), (456, 350, 503, 367), (385, 74, 575, 124))
WORLD_LABEL = (500, 58, 600, 84)
def verified_reference(name, expected):
data = (REFERENCE / name).read_bytes()
if hashlib.sha256(data).hexdigest() != expected:
raise RuntimeError('The S5 reference control image changed')
with Image.open(io.BytesIO(data)) as image:
return image.convert('RGB')
def matches(image, reference, tolerance=30):
return max(ImageStat.Stat(ImageChops.difference(image, reference)).mean) <= tolerance
class Controls:
def __init__(self):
form = verified_reference('prelogin-safe.png', '50dd527734fc2227a0c1273621134ede4071f2cda941bbf1df9895be9c3cc2c7')
self.form = [form.crop(box) for box in FORM_AREAS]
button = verified_reference('roster-actions-only.png', '4f3619d9e101b26f59434c74ec83040b8df43ea414aa928dec3c8fa9cbe455de')
self.button = button.crop(WORLD_LABEL)
self.last_roster = None
self.last_row = None
def login(self, frame):
small = frame.resize((960, 540), Image.Resampling.LANCZOS)
# Account, Password and enabled Log In are separate glyph crops. The
# fourth region must also be visibly clear of the normal login modal.
return all(matches(small.crop(box), image) for box, image in zip(FORM_AREAS, self.form))
def ruleset(self, frame):
# Only the two fixed headings matter. A dark background or a single
# modal title cannot match both, regardless of the realm list repaint.
small = frame.resize((768, 432), Image.Resampling.LANCZOS).convert('L')
for box, threshold, expected in RULESET_LABELS:
ink = small.crop(box).point(lambda value: 255 if value > threshold else 0)
actual = ink.resize((12, 2), Image.Resampling.BOX).tobytes()
if sum(abs(a - b) for a, b in zip(actual, expected)) > sum(expected) // 3:
return False
return True
def roster(self, frame):
button = frame.crop((0, 1180, 2560, 1440)).resize((1100, 112)).crop(WORLD_LABEL)
if not matches(button, self.button):
self.last_roster = self.last_row = None
return None
ref = ui.reference_ui_pixels(frame)
# The exact fixture name and selection border are the only roster facts
# consumed. World animation outside the list never schedules more OCR.
ink = fixture_row_ink(ref)
key = hashlib.sha256(ink.tobytes()).digest()
if self.last_roster != key:
self.last_row = fixture_row(ref, 'Gatewayref', ink=ink)
self.last_roster = key
if self.last_row:
x, y, _ = self.last_row
# The selection border can repaint without changing the glyph mask.
return x, y, fixture_selected(ref, y)
return None
def wait_visible(frame, check, timeout, label, clock=time.monotonic, pause=time.sleep):
end = clock() + timeout
while True:
with frame() as image:
observed = check(image)
if observed:
return observed
left = end - clock()
if left <= 0:
raise RuntimeError('Timed out waiting for ' + label)
pause(min(.08, left))
def lifetime(pid):
proc = Path('/proc') / str(pid)
raw = (proc / 'stat').read_text()
if (proc / 'comm').read_text().strip() != 'WowB.exe' or (proc / 'cwd').resolve() != LOCAL_TREE:
raise RuntimeError('The process does not own the S5 local test tree')
return raw[raw.rindex(')') + 2:].split()[19]
def existing_pid(job):
recorded = job / 'pid.txt'
if recorded.exists():
pid = int(recorded.read_text())
lifetime(pid)
return pid
found = []
for proc in Path('/proc').glob('[0-9]*'):
try:
if (proc / 'comm').read_text().strip() == 'WowB.exe' and (proc / 'cwd').resolve() == LOCAL_TREE:
found.append(int(proc.name))
except (FileNotFoundError, PermissionError, ProcessLookupError):
continue
if len(found) != 1:
raise RuntimeError('Expected one already-running S5 local process')
return found[0]
def bind_stage(job):
data = json.loads((job / 'staged.json').read_bytes())
if (Path(data['root']) / '_classic_beta_').resolve() != LOCAL_TREE:
raise RuntimeError('Expected the pinned S5 LOCAL stage')
# The signed HUD build retains the same LOCAL bridge and updates its wire.
pins = LOCAL_PINS
if data['dlls'].get('GWNativeWire.dll') == HUD_WIRE_SHA256:
pins = {**LOCAL_PINS, 'GWNativeWire.dll': HUD_WIRE_SHA256}
for name, expected in pins.items():
if data['dlls'].get(name) != expected or hashlib.sha256((LOCAL_TREE / name).read_bytes()).hexdigest() != expected:
raise RuntimeError('The existing S5 stage differs from its local receipt')
PASSWORD_FIELD = (822, 600, 1095, 642)
def password_mask_count(pixels):
"""Count complete S5 masks on the normalized 1920x1080 login form."""
with pixels.crop(PASSWORD_FIELD) as field:
rgb = field.load()
# The seven central rows cover each glyph. A focused caret extends
# below this band and is at most two pixels wide.
ink = [any(min(rgb[x, y][:3]) > 155 for y in range(14, 21)) for x in range(field.width)]
starts = []
for bright, columns in groupby(enumerate(ink), key=lambda item: item[1]):
if not bright:
continue
run = [x for x, _ in columns]
if len(run) <= 2 and any(min(rgb[x, 26][:3]) > 155 for x in run):
continue
if len(run) not in (5, 6):
return None
starts.append(run[0])
# S5 positions the first mark seven pixels from the inset, then alternates
# seven- and eight-pixel advances. Refuse partial or unexpected artwork.
if starts and (starts[0] != 7 or any(b-a not in (7, 8) for a, b in zip(starts, starts[1:]))):
return None
return len(starts)
class ActiveWindow:
def __init__(self, d, pid):
self.d, self.pid, self.start = d, pid, lifetime(pid)
row = ui.choose_main_window(ui.window_rows(d), pid)
self.win = d.create_resource_object('window', row['id'])
self.check()
def check(self):
if lifetime(self.pid) != self.start or not ui.owns_input(self.d, self.win.id):
raise RuntimeError('The S5 window lost focus or its process lifetime changed')
kde_pid = subprocess.check_output(['kdotool', 'getactivewindow', 'getwindowpid'],
text=True, stderr=subprocess.DEVNULL, timeout=2).strip()
if kde_pid != str(self.pid):
raise RuntimeError('The compositor no longer has the S5 local window focused')
row = ui.choose_main_window(ui.window_rows(self.d), self.pid)
if (row['id'], row['width'], row['height'], row['mapped']) != (self.win.id, 2560, 1440, True):
raise RuntimeError('The S5 local window or layout changed')
def frame(self):
self.check()
data = self.win.get_image(0, 0, 2560, 1440, X.ZPixmap, 0xffffffff)
frame = Image.frombytes('RGB', (2560, 1440), data.data, 'raw', 'BGRX')
self.check()
return frame
def fields(self, controls):
with self.frame() as frame:
if not controls.login(frame):
raise RuntimeError('The local form disappeared during credential entry')
pixels = ui.reference_ui_pixels(frame)
# Ignore the illuminated field borders in the normalized 1440p UI.
for box in ((804, 538, 821, 566), (1097, 538, 1118, 566), (804, 615, 821, 648),
(1097, 615, 1118, 648), (821, 642, 1097, 648)):
pixels.paste(0, box)
return pixels
def click(self, x, y):
self.check()
ui.click_at(self.d, self.win, x, y)
def local_values():
first = dict(guid=4514, account=513, original_rank=4, runtime_rank=4, fixture=str(ACCOUNT_FIXTURE))
require_fixture('gatewayref', first, None, None)
secret = ACCOUNT_FIXTURE.parent / 'password.txt'
for path in (ACCOUNT_FIXTURE, secret):
if path.is_symlink() or not path.is_file() or path.stat().st_mode & 0o077:
raise RuntimeError('Expected the private local test fixture')
fixture = json.loads(ACCOUNT_FIXTURE.read_bytes())
if (int(fixture['account_id']), int(fixture['auth_port']), int(fixture['world_port'])) != (513, 3724, 8090):
raise RuntimeError('The fixture differs from the S5 local binding')
return fixture['username'], lambda: secret.read_text().rstrip('\r\n')
def enter_roster(window, controls, job):
submitted = (job / 'local-realm-pin-entry-attempted').exists()
saw_ruleset = False
def roster_after_submission(image):
nonlocal saw_ruleset
row = controls.roster(image)
if row or not submitted:
return row
if saw_ruleset:
if controls.login(image):
raise RuntimeError('The gameplay ruleset chooser returned to the local login form before the roster')
else:
saw_ruleset = controls.ruleset(image)
return None
row = wait_visible(window.frame, roster_after_submission, 120, 'the exact local roster row and Enter World control')
if not row[2]:
window.click(round(row[0] * 4 / 3), round(row[1] * 4 / 3))
def selected(image):
current = controls.roster(image)
return current and current[2] and abs(current[1] - row[1]) <= 8
wait_visible(window.frame, selected, 5, 'selection of the same named roster row')
window.check()
(job / 'world-entry-from-roster').touch(exist_ok=False)
window.click(1280, 1347)
print('Entered the selected local roster row through the stock Enter World control.')
def run(stage, window, controls, job):
if stage in ('form', 'submit', 'enter'):
wait_visible(window.frame, controls.login, 55, 'the unobstructed local login form')
if stage == 'form':
print('Observed the local login form on the owned window.')
return
(job / 'one-form-attempt.lock').touch(exist_ok=False)
receipt = dict(screen_verified=True, submitted=False)
try:
username, supply = local_values()
result = ui.streamlined_owned_login_values(
window.d, window.win, username, supply, login_screen_ready=True,
account_has_focus=False, before_password=window.check,
field_frame=lambda:window.fields(controls), check_window=window.check, account_click=window.click,
password_mask_count=password_mask_count)
receipt.update(clipboard=result['clipboard'], account_paste_evidence_reused=result['account_paste_evidence_reused'],
masked=result['password_mask_verified'])
if not receipt['clipboard'] or not receipt['masked']:
raise RuntimeError('The local credential fields were not confirmed')
with window.frame() as image:
if not controls.login(image):
raise RuntimeError('The confirmed local form disappeared before submission')
window.check()
(job / 'local-realm-pin-entry-attempted').touch(exist_ok=False)
ui.key(window.d, 'Return')
receipt['submitted'] = True
finally:
(job / 'local-realm-pin-entry-receipt.json').write_text(json.dumps(receipt) + '\n')
if stage == 'submit':
print('Submitted the observed local form once.')
return
enter_roster(window, controls, job)
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('stage', choices=('form', 'submit', 'roster', 'enter'))
parser.add_argument('--job', type=Path, required=True)
parser.add_argument('--pid', type=int, help='Already running S5 process, otherwise use the existing job pid.txt')
args = parser.parse_args(argv)
os.umask(0o077)
job = args.job.resolve()
if job.parent != JOBS.resolve() or not re.fullmatch(r's5-[a-z\d-]+-\d{8}', job.name):
parser.error('Expected an existing S5 job directory')
bind_stage(job)
pid = args.pid if args.pid is not None else existing_pid(job)
controls = Controls()
d = display.Display()
previous_input, previous_window = ui.UI, ui.INPUT_WINDOW
try:
window = ActiveWindow(d, pid)
# This local Wayland/XWayland session accepted the complete normal
# form with XTest for both keyboard and absolute pointer events.
ui.UI = None
ui.INPUT_WINDOW = window.win.id
run(args.stage, window, controls, job)
if args.stage == 'form':
(job / 'pid.txt').write_text(str(pid) + '\n')
finally:
ui.UI, ui.INPUT_WINDOW = previous_input, previous_window
d.close()
if __name__ == '__main__':
main()