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

1146 lines
70 KiB
Python

#!/usr/bin/env python3
"""Window-scoped X11 automation for the real authorized WowB.exe test client."""
import argparse
import ctypes
import io
import json
import os
from pathlib import Path
import re
import select
import subprocess
import sys
import time
from contextlib import contextmanager
from Xlib import X, XK, display
from Xlib.ext import xtest
from PIL import Image, ImageChops, ImageOps
from evdev import UInput, ecodes
UI = None
INPUT_WINDOW = None
# Installed only by an owned runner after binding its exact PID/lifetime/window.
# Standalone helpers do not acquire focus permission from environment alone.
OWNED_FOCUS_AUTHORIZATION = None
KEYMAP = None
KEY_DELAY = .008
ROOT=Path(__file__).resolve().parents[1]
CLIENT=Path('/mnt/Games/Games/WoW-Forever/_classic_beta_')
PREFIX=Path('/home/praxis/Projects/WoW-Hybrid/wine-forever')
class ClientWindowBlocked(RuntimeError):
def __init__(self,kind):
self.kind=kind
super().__init__('WowB '+kind+' dialog blocks automation; no input sent')
def focus_id(d):
# X11 may return PointerRoot/None rather than a Window while focus changes.
return getattr(d.get_input_focus().focus,'id',None)
def active_id(d):
# uinput keys follow the compositor's active window, not X input focus: a forced
# X focus once passed the guard while KWin still routed keys to official Octo.
prop=d.screen().root.get_full_property(d.intern_atom('_NET_ACTIVE_WINDOW'),X.AnyPropertyType)
return int(prop.value[0]) if prop is not None and len(prop.value) else None
def owns_input(d,wid):
return focus_id(d)==wid and active_id(d)==wid
def choose_main_window(rows,expected_pid=None):
"""Metadata only: never confuse a same-class fatal dialog with the game."""
candidates=[r for r in rows if any('wowb' in c.lower() for c in r['classes']) and
(expected_pid is None or r['pid']==expected_pid) and r['width']>=640 and r['height']>=400]
if not candidates:raise RuntimeError('No real WowB.exe main window found')
if expected_pid is None and len({r['pid'] for r in candidates})>1:raise RuntimeError('Multiple client processes; no ambiguous window selected')
main=max(candidates,key=lambda r:r['width']*r['height'])
others=[r for r in rows if r['mapped'] and r['id']!=main['id'] and
(r['pid']==main['pid'] or r.get('transient')==main['id']) and any('wowb' in c.lower() for c in r['classes'])]
if others:
fatal=any(any('blizzarderror' in c.lower() for c in r['classes']) and r['mapped'] for r in rows)
raise ClientWindowBlocked('crashed' if fatal else 'native-modal')
return main
def window_rows(d):
root=d.screen().root
prop=root.get_full_property(d.intern_atom('_NET_CLIENT_LIST'),X.AnyPropertyType)
rows=[]
for wid in ([] if prop is None else prop.value):
try:
win=d.create_resource_object('window',int(wid));classes=win.get_wm_class() or ()
pid=win.get_full_property(d.intern_atom('_NET_WM_PID'),X.AnyPropertyType)
if not any('wowb' in c.lower() or 'blizzarderror' in c.lower() for c in classes):
if 'steam_app_0' not in classes or pid is None or not len(pid.value):continue
process=Path('/proc')/str(int(pid.value[0]))/'comm'
if process.read_text().strip().lower()!='wowb.exe':continue
classes=(*classes,'WowB.exe')
geom=win.get_geometry();transient=win.get_wm_transient_for()
rows.append({'id':int(wid),'pid':int(pid.value[0]) if pid is not None and len(pid.value) else None,
'classes':classes,'width':geom.width,'height':geom.height,
'mapped':win.get_attributes().map_state==X.IsViewable,'transient':transient.id if transient else None})
except Exception:continue # A window can disappear during enumeration.
return rows
def known_client_startup_pid(runtime=None,proc=None):
"""Honor a live, exact-path recorded launch while Wine precedes WowB comm.
PID files alone are insufficient: stale/reused or unrelated PIDs are ignored.
Never return, log or copy command-line contents.
"""
runtime=runtime or ROOT/'runtime';proc=proc or Path('/proc')
paths=(str(CLIENT/'WowB.exe'),str(ROOT/'runtime/native-client/_classic_beta_/WowB.exe'))
expected={value.encode() for path in paths for value in (path,'Z:'+path.replace('/','\\'))}
for name in ('client-launch.pid','native-client.pid','pristine-startup-owner.pid'):
try:
pid=int((runtime/name).read_text())
if pid<=0:continue
arguments=(proc/str(pid)/'cmdline').read_bytes().split(b'\0')
if any(arg in expected for arg in arguments):return pid
except (OSError,ValueError):pass
return None
@contextmanager
def timed(stage):
"""Only fixed stage labels and durations: no typed text or authentication data."""
start=time.monotonic();ok=False
try:
yield
ok=True
finally:
path=ROOT/'runtime/ui-timings.jsonl'
path.parent.mkdir(exist_ok=True)
with path.open('a') as output:
output.write(json.dumps({'stage':stage,'seconds':round(time.monotonic()-start,4),'ok':ok,'unix':time.time()})+'\n')
path.chmod(0o600)
def target(d):
row=choose_main_window(window_rows(d),known_client_startup_pid())
return d.create_resource_object('window',row['id'])
def official_octo_focused(d):
"""Read process identity only; never inspect chat or window titles."""
prop=d.screen().root.get_full_property(d.intern_atom('_NET_ACTIVE_WINDOW'),X.AnyPropertyType)
if prop is None or not len(prop.value):return False
try:
active=d.create_resource_object('window',int(prop.value[0]))
pid=active.get_full_property(d.intern_atom('_NET_WM_PID'),X.AnyPropertyType)
return bool(pid is not None and len(pid.value) and
(Path('/proc')/str(int(pid.value[0]))/'cwd').resolve()==Path('/home/praxis/Games/octo/drive_c/Octowow'))
except (OSError,ValueError):return False
def activate(d=None,win=None,*,after_octo_notice=False):
owns=d is None
if owns:d=display.Display()
try:
if official_octo_focused(d) and not after_octo_notice:
if OWNED_FOCUS_AUTHORIZATION is None:
raise RuntimeError('Official Octo is focused; pause automation until a fresh ten-second notice and explicit focus transfer')
win=win or target(d)
if not OWNED_FOCUS_AUTHORIZATION(d,win):
raise RuntimeError('Standing focus permission lacks the exact owned client lifetime/window; no input allowed')
after_octo_notice=True
win=win or target(d)
rows=window_rows(d);row=next((r for r in rows if r['id']==win.id),None)
if row is None:raise RuntimeError('WowB main window disappeared')
choose_main_window(rows,row['pid'])
# Proton can publish steam_proton even for the exact owned WowB PID.
# Use the observed class; retain the PID and single-window guards.
resource_class='steam_proton' if 'steam_proton' in [c.lower() for c in row.get('classes',())] else 'wowb'
command=['kdotool','search','--all','--class',resource_class]
if row['pid'] is not None:command.extend(['--pid',str(row['pid'])])
p=subprocess.run(command,capture_output=True,text=True,timeout=2)
ids=p.stdout.splitlines()
if not ids:raise RuntimeError('WowB.exe window not found by KWin')
if len(ids)!=1:raise RuntimeError('Multiple KWin windows; refusing ambiguous activation')
subprocess.run(['kdotool','windowactivate',ids[0]],check=True,stdout=subprocess.DEVNULL,timeout=2)
if after_octo_notice:
# KWin may acknowledge activation without moving X input focus.
# Complete only the explicitly authorized transfer to the owned window.
win.set_input_focus(X.RevertToParent,X.CurrentTime);d.sync()
until=time.monotonic()+2
while not owns_input(d,win.id) and time.monotonic()<until:time.sleep(.1)
if not owns_input(d,win.id) or official_octo_focused(d):
raise RuntimeError('Explicit owned focus was not established; no input allowed')
finally:
if owns:d.close()
def ensure_focus(d,win,timeout=3):
deadline=time.monotonic()+timeout;next_request=0
while True:
# Native fatal modals must fail immediately, not consume the focus
# timeout and then misclassify their login-screen underlay as ready.
selected=target(d)
if selected.id!=win.id:raise RuntimeError('WowB main window changed; no input sent')
if owns_input(d,win.id):return
if time.monotonic()>=deadline:raise RuntimeError('WowB focus unavailable; no input sent')
if time.monotonic()>=next_request:
activate(d,win);next_request=time.monotonic()+.3
d.sync();time.sleep(.03)
def fake(d,event,code):
if event==X.KeyPress and INPUT_WINDOW is not None and not owns_input(d,INPUT_WINDOW):
raise RuntimeError('WowB lost focus; input stopped')
if UI is None: xtest.fake_input(d,event,code)
else:
UI.write(ecodes.EV_KEY,code-8,1 if event==X.KeyPress else 0); UI.syn(); time.sleep(KEY_DELAY)
def key(d,name):
sym=XK.string_to_keysym(name)
code=d.keysym_to_keycode(sym)
if not code: raise RuntimeError('Unknown keysym')
try:
fake(d,X.KeyPress,code)
# The real client can miss8ms control-key taps: a captured /turtletalents
# remained in its edit box after Return. Expose the key for at least40ms
# while keeping character typing at its measured faster rate.
time.sleep(max(0,.04-KEY_DELAY))
finally:
fake(d,X.KeyRelease,code);d.sync()
def type_text(d,text):
# Use the local keymap, with Shift for uppercase and punctuation; no clipboard.
global KEYMAP
if KEYMAP is None:
KEYMAP={}
for code in range(8,256):
for level in (0,1):
KEYMAP.setdefault(d.keycode_to_keysym(code,level),(code,level))
# Validate the complete string before emitting input; never leave a partial
# credential or command because a later character has no supported key.
keys=[KEYMAP.get(ord(c)) for c in text]
if any(found is None for found in keys):raise RuntimeError('Unmapped input character')
shift_code=d.keysym_to_keycode(XK.XK_Shift_L)
if any(shift for _,shift in keys) and not shift_code:raise RuntimeError('Shift key is unavailable')
for code,shift in keys:
try:
if shift:fake(d,X.KeyPress,shift_code)
try:fake(d,X.KeyPress,code)
finally:fake(d,X.KeyRelease,code)
finally:
if shift:fake(d,X.KeyRelease,shift_code)
d.sync()
def clear(d):
global KEY_DELAY
# WoW's custom EditBox does not reliably implement Ctrl+A as select-all.
key(d,'End')
previous=KEY_DELAY;KEY_DELAY=.008
try:
for _ in range(256):key(d,'BackSpace')
finally:KEY_DELAY=previous
def pointer_step(delta):
# An aligned axis must remain still. The former `int(delta/3) or ...`
# emitted -1 for delta0, repeatedly moving away from the target while the
# other axis converged and sometimes preventing the strict2px guard.
return max(-12,min(12,int(delta/3) or (1 if delta>0 else -1)))if delta else 0
def click_at(d,win,x,y,button=ecodes.BTN_LEFT):
geom=win.get_geometry()
if not 0<=x<geom.width or not 0<=y<geom.height:raise RuntimeError('Click outside client window')
pos=d.screen().root.translate_coords(win,0,0);wanted_x,wanted_y=pos.x+x,pos.y+y
for attempt in range(240):
if not owns_input(d,win.id):raise RuntimeError('WowB lost focus; pointer action stopped')
pointer=d.screen().root.query_pointer();dx=wanted_x-pointer.root_x;dy=wanted_y-pointer.root_y
# Gossip rows are only~16px apart. The former12px tolerance could
# select the adjacent service despite a correct requested coordinate.
if abs(dx)+abs(dy)<2:break
if UI is None:
# XTEST supports absolute motion. Small synthetic steps can fail
# to converge under XWayland; retain observed2px/focus checks before
# pressing, without emulating a relative hardware pointer here.
xtest.fake_input(d,X.MotionNotify,x=wanted_x,y=wanted_y);d.sync()
else:
UI.write(ecodes.EV_REL,ecodes.REL_X,pointer_step(dx))
UI.write(ecodes.EV_REL,ecodes.REL_Y,pointer_step(dy));UI.syn()
time.sleep(.02)
else:raise RuntimeError('Pointer did not reach target window coordinate')
if button is not None:
if not owns_input(d,win.id):raise RuntimeError('WowB lost focus before click; no press sent')
if UI is None:
number={ecodes.BTN_LEFT:1,ecodes.BTN_RIGHT:3}.get(button)
if number is None:raise RuntimeError('Unsupported X11 pointer button')
try:xtest.fake_input(d,X.ButtonPress,number);d.sync();time.sleep(.03)
finally:xtest.fake_input(d,X.ButtonRelease,number);d.sync()
else:
UI.write(ecodes.EV_KEY,button,1);UI.syn();time.sleep(.03)
UI.write(ecodes.EV_KEY,button,0);UI.syn()
def is_world_screen(text):
# Labels observed in the actual local client. Credential/modal detection
# still takes precedence in the session controller and screenshot guard.
words=re.sub(r'[^a-z]','',text.lower())
return any(zone in words for zone in ('northshire','hallofarms','mainhall','elwynnforest','goldshire','gmisland','bootybay','thecapeofstrangl','valleyofhonor','valleyofstrength','thedrag','cenarionhold','twilightbasecamp','silithus','redcloudmesa','utherstomb','ruinsofandorhal'))
def native_world_label(pixels):
if pixels.size!=(2560,1440):return None
crop=pixels.convert('RGB').crop((2245,0,2500,26));r,g,b=crop.split()
mask=ImageChops.multiply(r.point(lambda v:255 if v>170 else 0),g.point(lambda v:255 if v>130 else 0))
mask=ImageChops.multiply(mask,b.point(lambda v:255 if v<130 else 0))
return ImageOps.expand(ImageOps.invert(mask).resize((crop.width*6,crop.height*6)),border=20,fill=255)
def native_compact_world_label(pixels,*,grayscale=False):
# Captured1440p compact Cenarion Hold header: broad gold thresholds merge
# the glyphs with its ochre bar/bright sky and include the adjacent clock.
# Keep actual ink pixels and font height, never repair recognized letters.
if pixels.size!=(2560,1440):return None
if grayscale:
# A captured shaded Cenarion Hold header loses the final glyph under
# the gold threshold. Preserve the actual complete glyphs instead;
# keep the same exact-label classifier and exclude the clock.
crop=ImageOps.autocontrast(pixels.convert('L').crop((2310,5,2440,22)))
return ImageOps.expand(crop.resize((1040,136),Image.Resampling.LANCZOS),border=24,fill=255)
r,g,b=pixels.convert('RGB').crop((2310,5,2425,22)).split()
mask=ImageChops.multiply(r.point(lambda v:255 if v>200 else 0),b.point(lambda v:255 if v<25 else 0))
return ImageOps.expand(ImageOps.invert(mask).resize((920,136),Image.Resampling.LANCZOS),border=24,fill=255)
def reference_ui_pixels(pixels):
"""Use the measured16:9 UI reference for the requested1440p mode.
Unknown dimensions retain their existing fail-closed behavior. Readback,
modal, focus and password-mask checks remain mandatory before submission.
"""
if pixels.size==(2560,1440):return pixels.resize((1920,1080),Image.Resampling.LANCZOS)
return pixels
def chat_edit_pixel_observation(pixels):
"""Original EditBox has two long bright borders in its chat-channel color.
Calibrated against captured pending-command and closed world/menu frames.
Never reads chat text, credentials, spell state or an inferred Lua pointer.
A different layout fails closed at readiness rather than receiving typing.
"""
if pixels.size==(1920,1080):left,right,rows,minimum=40,460,(945,961),350
elif pixels.size==(2560,1440):
# Measured empty original EditBox at1440p:512/511 neutral pixels.
# Inspect native pixels, since downsampling a one-pixel border loses
# brightness and cannot reliably authorize typing.
left,right,rows,minimum=53,613,(1278,1297),466
else:raise RuntimeError('Unverified chat-edit geometry')
# The observed 1440p guild EditBox uses green borders (e.g.61,197,61),
# not the neutral Say border. Keep the same two measured full-length
# lines; a guild-colored border must not be mistaken for a closed edit.
def border(rgb):
neutral=min(rgb)>150 and max(rgb)-min(rgb)<35
guild=(pixels.size==(2560,1440) and rgb[1]>150 and
abs(rgb[0]-rgb[2])<35 and rgb[1]-max(rgb[0],rgb[2])>80)
return neutral or guild
counts=[sum(border(rgb)
for rgb in (pixels.getpixel((x,y))[:3]for x in range(left,right)))for y in rows]
return dict(opened=all(n>minimum for n in counts),width=pixels.width,height=pixels.height,
left=left,right=right,rows=list(rows),counts=counts,minimum_exclusive=minimum)
def chat_edit_pixels_open(pixels):
return chat_edit_pixel_observation(pixels)['opened']
def _chat_edit_observation(d,win):
path=ROOT/'runtime/private-chat-edit-check.png'
try:
capture_frame(d,win,path)
with Image.open(path)as captured:pixels=captured.convert('RGB')
try:return chat_edit_pixel_observation(pixels),pixels
except Exception:pixels.close();raise
finally:path.unlink(missing_ok=True)
def chat_edit_open(d,win):
observed,pixels=_chat_edit_observation(d,win)
try:return observed['opened']
finally:pixels.close()
def wait_chat_edit(d,win,opened,timeout=2):
started=time.monotonic();until=started+timeout;attempts=0
while True:
observed,pixels=_chat_edit_observation(d,win);attempts+=1
try:
if observed['opened']==opened:return
now=time.monotonic()
if now>=until:
# Preserve the exact frame that failed this gate, not a later
# screenshot. No text/credential OCR, input, retries or replay.
phase='opening' if opened else 'submission'
expected='open' if opened else 'closed';actual='open' if observed['opened'] else 'closed'
stem=ROOT/'runtime'/('private-chat-edit-failure-'+str(os.getpid())+'-'+str(time.time_ns()))
try:
with stem.with_suffix('.png').open('xb')as output:
os.fchmod(output.fileno(),0o600);pixels.save(output,format='PNG')
record=dict(expected_open=bool(opened),phase=phase,observation=observed,
attempts=attempts,elapsed_ms=round((now-started)*1000),
owner_window_id=getattr(win,'id',None),frame=str(stem.with_suffix('.png')))
with stem.with_suffix('.json').open('x')as output:
os.fchmod(output.fileno(),0o600);json.dump(record,output,indent=2)
diagnostic=str(stem.with_suffix('.json'))
except Exception as error:diagnostic='save-failed('+type(error).__name__+')'
raise RuntimeError('Chat edit '+phase+' unconfirmed; expected='+expected+' observed='+actual+
'; no automatic replay; diagnostics='+diagnostic)
finally:pixels.close()
time.sleep(.03)
def tight_world_label(pixels):
# Verified Northshire failure: yellow foliage pollutes the broad color
# mask. Keep the original tiny glyphs with nearest-neighbour scaling;
# exclude the clock/border. Classification still requires an exact label.
if pixels.size!=(1920,1080):return None
return pixels.crop((1717,4,1830,20)).convert('L').resize((904,128),Image.Resampling.NEAREST)
def compact_world_label(pixels):
# Actual Booty Bay capture: clipping the top of the outlined y makes OCR
# return "Booty Ba". Preserve the whole font height and exclude the clock.
# This adds a view, never a fuzzy alias or replacement for existing views.
if pixels.size!=(1920,1080):return None
return ImageOps.autocontrast(pixels.crop((1712,0,1810,21)).convert('L')).resize((588,126),Image.Resampling.LANCZOS)
def raw_world_label(pixels):
# Actual post-reload Booty Bay: smoothed tiny gold glyphs become "Boory".
# Preserve their pixels/complete height, add OCR page margins and use the
# raw-line recognizer. No zone dictionary, fuzzy alias or character repair.
if pixels.size!=(1920,1080):return None
r,g,b=pixels.convert('RGB').crop((1710,0,1805,22)).split()
mask=ImageChops.multiply(r.point(lambda v:255 if v>170 else 0),g.point(lambda v:255 if v>130 else 0))
mask=ImageChops.multiply(mask,b.point(lambda v:255 if v<130 else 0))
# A bright outdoor background can satisfy those absolute thresholds too.
# Require gold chroma, keeping beige scenery out of the glyph mask.
mask=ImageChops.multiply(mask,ImageChops.subtract(r,b).point(lambda v:255 if v>100 else 0))
mask=ImageChops.multiply(mask,ImageChops.subtract(g,b).point(lambda v:255 if v>70 else 0))
# Native gold glyphs start below row4. A changing sky flare above the
# text baseline was recognized as an accent; retain the original canvas
# and margins so the earlier exact glyph fixtures remain unchanged.
mask.paste(0,(0,0,mask.width,4))
return ImageOps.expand(ImageOps.invert(mask).resize((760,176),Image.Resampling.NEAREST),border=24,fill=255)
CHARACTER_CONTROL_BOXES={'Enter World':(886,986,1038,1016),'Create Character':(1591,957,1730,983)}
def character_select_control_images(pixels,*,layout_size=None):
# Actual70334 outlined gold controls defeat the broad grayscale crop.
# Isolate only their public glyphs; never recognize a character by name.
if pixels.size!=(1920,1080):return {}
result={}
boxes=dict(CHARACTER_CONTROL_BOXES)
if layout_size==(2560,1440):boxes['Enter World']=(870,995,1055,1030)
for label,box in boxes.items():
crop=pixels.convert('RGB').crop(box);r,g,b=crop.split()
mask=ImageChops.multiply(r.point(lambda v:255 if v>170 else 0),g.point(lambda v:255 if v>130 else 0))
mask=ImageChops.multiply(mask,b.point(lambda v:255 if v<130 else 0))
result[label]=ImageOps.invert(mask).resize((crop.width*6,crop.height*6),Image.Resampling.NEAREST)
if layout_size==(2560,1440):result[label]=ImageOps.expand(result[label],border=20,fill=255)
return result
def native_character_select_control_images(pixels):
# Original ghost selection uses a very bright background; reference-image
# resampling and the old gold mask erase strokes in "Create Character".
if pixels.size!=(2560,1440):return {}
crop=ImageOps.autocontrast(pixels.crop((2160,1294,2344,1320)).convert('L'))
return {'Create Character':ImageOps.expand(crop.resize((1104,156)),border=20,fill=255)}
def is_character_select_screen(text):
words=re.sub(r'[^a-z]','',text.lower())
return 'enterworld' in words and any(marker in words for marker in ('createcharacter','createnewcharacter','togglecharacterlist'))
def capture_frame(d,win,path):
if focus_id(d)!=win.id:raise RuntimeError('Refusing capture without WowB focus')
if not path.resolve().is_relative_to(ROOT/'runtime'):raise RuntimeError('Diagnostic screenshots must stay in runtime')
path.unlink(missing_ok=True)
time.sleep(.15) # Let input changes reach the compositor before the fresh capture.
subprocess.run(['spectacle','-i','-a','-b','-n','-e','-S',*(['-p'] if path.name!='private-ui-check.png' else []),'-o',str(path.resolve())],check=True)
deadline=time.monotonic()+5;last_size=None
while time.monotonic()<deadline:
try:
size=path.stat().st_size
if size and size==last_size:
with Image.open(path) as pixels:pixels.verify()
break
last_size=size
except (FileNotFoundError,OSError):pass
time.sleep(.1)
else:raise RuntimeError('Fresh compositor capture did not complete')
path.chmod(0o600)
if focus_id(d)!=win.id:
path.unlink(missing_ok=True);raise RuntimeError('Focus changed during capture; image discarded')
def capture_text(d,win,path,world_first=False):
capture_frame(d,win,path)
env=dict(os.environ,OMP_THREAD_LIMIT='1')
if world_first:
with Image.open(path) as pixels:
layout_size=pixels.size
if layout_size==(2560,1440):
# Preserve original glyph resolution before reference scaling;
# small gold graveyard/zone text otherwise loses whole letters.
label=native_world_label(pixels)
encoded=io.BytesIO();label.save(encoded,format='PNG')
result=subprocess.run(['tesseract','stdin','stdout','--psm','7'],input=encoded.getvalue(),capture_output=True,env=env,check=True).stdout.decode()
if is_world_screen(result):return result
label=native_compact_world_label(pixels)
encoded=io.BytesIO();label.save(encoded,format='PNG')
result=subprocess.run(['tesseract','stdin','stdout','--psm','7'],input=encoded.getvalue(),capture_output=True,env=env,check=True).stdout.decode()
if is_world_screen(result):return result
label=native_compact_world_label(pixels,grayscale=True)
encoded=io.BytesIO();label.save(encoded,format='PNG')
result=subprocess.run(['tesseract','stdin','stdout','--psm','7'],input=encoded.getvalue(),capture_output=True,env=env,check=True).stdout.decode()
if is_world_screen(result):return result
pixels=reference_ui_pixels(pixels)
if pixels.size==(1920,1080):
if layout_size==(2560,1440):
# Actual fullscreen Valley of Strength label is green and
# smaller than the old gold-font view. Keep full glyphs,
# exclude the clock, and still require an exact zone label.
zone=ImageOps.autocontrast(pixels.crop((1710,0,1860,22)).convert('L'))
zone=ImageOps.expand(zone.resize((900,132),Image.Resampling.NEAREST),border=20,fill=255)
encoded=io.BytesIO();zone.save(encoded,format='PNG')
result=subprocess.run(['tesseract','stdin','stdout','--psm','7'],input=encoded.getvalue(),capture_output=True,env=env,check=True).stdout.decode()
if is_world_screen(result):return result
zone=ImageOps.autocontrast(pixels.crop((1690,0,1919,35)).convert('L')).resize((916,140))
encoded=io.BytesIO();zone.save(encoded,format='PNG')
result=subprocess.run(['tesseract','stdin','stdout','--psm','7'],input=encoded.getvalue(),capture_output=True,env=env,check=True).stdout.decode()
# Actual minimap label proves a world view, not a credential form.
# Fall back to the complete private classification at every transition.
if is_world_screen(result):return result
# Abbey's yellow window behind the minimap defeats grayscale
# OCR. Isolate the actual yellow label and exclude its clock.
r,g,b=pixels.convert('RGB').crop((1712,0,1840,21)).split()
mask=ImageChops.multiply(r.point(lambda v:255 if v>170 else 0),g.point(lambda v:255 if v>130 else 0))
mask=ImageChops.multiply(mask,b.point(lambda v:255 if v<130 else 0))
label=ImageOps.invert(mask).resize((768,126));encoded=io.BytesIO();label.save(encoded,format='PNG')
result=subprocess.run(['tesseract','stdin','stdout','--psm','7'],input=encoded.getvalue(),capture_output=True,env=env,check=True).stdout.decode()
if is_world_screen(result):return result
label=compact_world_label(pixels);encoded=io.BytesIO();label.save(encoded,format='PNG')
result=subprocess.run(['tesseract','stdin','stdout','--psm','6'],input=encoded.getvalue(),capture_output=True,env=env,check=True).stdout.decode()
if is_world_screen(result):return result
# The actual bank interior makes block segmentation drop this
# short outlined label. A single-word view recovers its exact
# text; do not add fuzzy zone aliases or repair OCR characters.
result=subprocess.run(['tesseract','stdin','stdout','--psm','8'],input=encoded.getvalue(),capture_output=True,env=env,check=True).stdout.decode()
if is_world_screen(result):return result
label=tight_world_label(pixels);encoded=io.BytesIO();label.save(encoded,format='PNG')
result=subprocess.run(['tesseract','stdin','stdout','--psm','7'],input=encoded.getvalue(),capture_output=True,env=env,check=True).stdout.decode()
if is_world_screen(result):return result
label=raw_world_label(pixels);encoded=io.BytesIO();label.save(encoded,format='PNG')
result=subprocess.run(['tesseract','stdin','stdout','--psm','13'],input=encoded.getvalue(),capture_output=True,env=env,check=True).stdout.decode()
if is_world_screen(result):return result
# The actual post-login bank frame retains exact "Booty Bay"
# in this gold mask under single-line segmentation, while
# raw-line segmentation misreads it. Keep exact classification;
# no fuzzy labels or network-state-only input authorization.
result=subprocess.run(['tesseract','stdin','stdout','--psm','7'],input=encoded.getvalue(),capture_output=True,env=env,check=True).stdout.decode()
if is_world_screen(result):return result
text=subprocess.run(['tesseract',str(path),'stdout','--psm','11'],capture_output=True,text=True,check=True,env=env).stdout
with Image.open(path) as pixels:
layout_size=pixels.size
native_controls=native_character_select_control_images(pixels)
pixels=reference_ui_pixels(pixels)
if pixels.size==(1920,1080):
# Extract public yellow form labels separately from the textured background.
r,g,b=pixels.convert('RGB').crop((760,430,1160,780)).split()
mask=ImageChops.multiply(r.point(lambda v:255 if v>170 else 0),g.point(lambda v:255 if v>130 else 0))
mask=ImageChops.multiply(mask,b.point(lambda v:255 if v<130 else 0))
label=ImageOps.invert(mask).resize((1200,1050))
field=ImageOps.autocontrast(pixels.crop((792,529,1130,582)).convert('L')).resize((1352,212))
zone=ImageOps.autocontrast(pixels.crop((1690,0,1919,35)).convert('L')).resize((916,140))
dialog=ImageOps.autocontrast(pixels.crop((754,140,1169,252)).convert('L')).resize((1245,336))
enter_world=ImageOps.autocontrast(pixels.crop((820,975,1100,1030)).convert('L')).resize((1120,220))
roster=ImageOps.autocontrast(pixels.crop((1555,175,1865,265)).convert('L')).resize((930,270))
# Check the public form labels AND modal region first. Once the
# complete login form is recognized, account-value, minimap and
# roster OCR add no state evidence. Credential readback remains a
# separate exact comparison immediately before password input.
for index,(region,mode) in enumerate(((label,6),(dialog,6),(field,7),(field,8),(zone,7),(enter_world,7),(roster,6))):
encoded=io.BytesIO();region.save(encoded,format='PNG')
region_ocr=subprocess.run(['tesseract','stdin','stdout','--psm',str(mode)],input=encoded.getvalue(),capture_output=True,env=env)
if region_ocr.returncode==0:text+='\n'+region_ocr.stdout.decode()
if index==1 and is_login_screen(text):return text
if not is_character_select_screen(text):
for expected,region in character_select_control_images(pixels,layout_size=layout_size).items():
encoded=io.BytesIO();region.save(encoded,format='PNG')
control=subprocess.run(['tesseract','stdin','stdout','--psm','7'],input=encoded.getvalue(),capture_output=True,env=env)
if control.returncode==0 and re.sub(r'[^a-z]','',control.stdout.decode().lower())==re.sub(r'[^a-z]','',expected.lower()):text+='\n'+expected
if not is_character_select_screen(text):
for expected,region in native_controls.items():
encoded=io.BytesIO();region.save(encoded,format='PNG')
control=subprocess.run(['tesseract','stdin','stdout','--psm','7'],input=encoded.getvalue(),capture_output=True,env=env,check=True)
if re.sub(r'[^a-z]','',control.stdout.decode().lower())==re.sub(r'[^a-z]','',expected.lower()):text+='\n'+expected
return text
def private_screen(d,win,world_first=True):
path=ROOT/'runtime/private-ui-check.png'
try:
with timed('private-world-check' if world_first else 'private-full-check'):
return capture_text(d,win,path,world_first=world_first)
finally:path.unlink(missing_ok=True)
def is_login_screen(text):
words=re.sub(r'[^a-z]','',text.lower())
# Full-window OCR sometimes misses outlined labels; combine independent form markers.
return (any(marker in words for marker in ('emailorphone','account')) and 'password' in words) or ('login' in words and any(marker in words for marker in ('phone','password','rememberaccount')))
def verify_console(d,win):
"""Require the actual console's Filter header, not just a focused WoW window."""
if (win.get_geometry().width,win.get_geometry().height)!=(1920,1080):
raise RuntimeError('Console coordinates require the verified 1920x1080 window')
screen=private_screen(d,win,world_first=False)
if is_login_screen(screen) or 'filter' not in screen.lower():
raise RuntimeError('Console input requires its visible Filter header and WowB focus')
def verify_account_segment(d,win,segment):
# Wine input dispatch and the blinking caret can obscure the first OCR frame.
for attempt in range(3):
time.sleep(.5)
screen=private_screen(d,win,world_first=False).upper().replace(' ','')
if segment in screen:return
raise RuntimeError('Account field verification failed; password was not entered')
def clear_edit_selection(d):
"""Native EditBox selection, never Enter or a guessed console command."""
key(d,'End');shift=d.keysym_to_keycode(XK.string_to_keysym('Shift_L'))
fake(d,X.KeyPress,shift)
try:key(d,'Home')
finally:fake(d,X.KeyRelease,shift)
key(d,'BackSpace')
def login_field_image(d,win):
path=ROOT/'runtime/private-ui-check.png'
try:
capture_frame(d,win,path)
with Image.open(path) as pixels:return reference_ui_pixels(pixels.convert('RGB')).copy()
finally:path.unlink(missing_ok=True)
def field_ocr(pixels,box):
# Field-local, private, bounded readback; never returns text to logs or a
# command argument. Blurring the account field removes its blinking caret.
region=ImageOps.autocontrast(pixels.crop(box).convert('L')).resize((1280,160))
encoded=io.BytesIO();region.save(encoded,format='PNG')
values=[]
for mode in (7,8):
result=subprocess.run(['tesseract','stdin','stdout','--psm',str(mode)],input=encoded.getvalue(),capture_output=True,check=True,env=dict(os.environ,OMP_THREAD_LIMIT='1'))
values.append(''.join(result.stdout.decode().upper().split()))
return values
def account_field_ocr(pixels):
values=field_ocr(pixels,(804,538,1118,572))
# Border-free alternative for the native account font: preserve aspect
# ratio and use a general account alphabet, never the expected account as
# a character whitelist. No fuzzy B/8 or I/1 substitutions are accepted.
region=pixels.crop((814,538,1114,566)).convert('L')
region=ImageOps.expand(region.resize((1200,112),Image.Resampling.LANCZOS),border=10,fill=0)
encoded=io.BytesIO();region.save(encoded,format='PNG')
result=subprocess.run(['tesseract','stdin','stdout','--psm','7','-c',
'tessedit_char_whitelist=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@._+-'],
input=encoded.getvalue(),capture_output=True,check=True,env=dict(os.environ,OMP_THREAD_LIMIT='1'))
values.append(''.join(result.stdout.decode().upper().split()))
# Actual outlined account glyphs can merge into the textured background.
# A measured binary luminance view recovered exact readback on70334;
# no expected-account whitelist or ambiguous-character substitution.
binary=pixels.crop((804,538,1118,572)).convert('L').point(lambda v:255 if v>190 else 0)
binary=binary.resize((1256,136));encoded=io.BytesIO();binary.save(encoded,format='PNG')
result=subprocess.run(['tesseract','stdin','stdout','--psm','7'],input=encoded.getvalue(),capture_output=True,check=True,env=dict(os.environ,OMP_THREAD_LIMIT='1'))
values.append(''.join(result.stdout.decode().upper().split()))
return values
def verify_blurred_account(d,win,segment):
# A busy client (fresh hotfix/codec load) can repaint the blurred field late.
until=time.monotonic()+15
while True:
pixels=login_field_image(d,win)
if any(segment in value for value in account_field_ocr(pixels)):return
if time.monotonic()>=until:raise RuntimeError('Account readback failed before password input; no password requested')
time.sleep(.05)
def password_mask_shapes(pixels):
region=pixels.crop((804,615,1118,648)).convert('RGB');w,h=region.size
active={(x,y) for y in range(h) for x in range(w) if min(region.getpixel((x,y)))>155}
shapes=[]
while active:
seed=active.pop();group={seed};pending=[seed]
while pending:
x,y=pending.pop()
for neighbor in ((x-1,y),(x+1,y),(x,y-1),(x,y+1)):
if neighbor in active:active.remove(neighbor);group.add(neighbor);pending.append(neighbor)
left=min(x for x,y in group);right=max(x for x,y in group);top=min(y for x,y in group);bottom=max(y for x,y in group)
if 3<=right-left+1<=16 and 3<=bottom-top+1<=16 and 5<=len(group)<=160:
shapes.append((right-left+1,bottom-top+1))
# Mask dots land on different sub-pixel offsets, so their antialiased pixel sets are
# rarely identical; count dot-like blobs of the same size (+-1 px) instead. Plaintext
# exposure is checked separately by OCR.
return max((sum(1 for w,h in shapes if abs(w-w0)<=1 and abs(h-h0)<=1) for w0,h0 in set(shapes)),default=0)
def verified_login_fields(d,win):
# The login web widget has different input dispatch from in-world chat.
# Preserve its proven pacing; retain faster bounded credential erasure.
global KEY_DELAY
previous=KEY_DELAY;KEY_DELAY=.03
try:
with timed('verified-login-fields'):_verified_login_fields(d,win)
finally:KEY_DELAY=previous
def _verified_login_fields(d,win):
info=json.loads((ROOT/'secrets/forever-local/account.json').read_text())
_verified_login_values(d,win,info['email'],lambda:(ROOT/'secrets/forever-local/password.txt').read_text())
# A separate Qt event loop serves X11 selection requests even while the owned
# runner waits on the Bridge. Only this static program appears in argv; values
# travel over private pipes. No file or clipboard-history entry is intentional.
_CLIPBOARD_OWNER = r'''
import json, os, resource, select, sys
from PyQt6.QtCore import QByteArray, QMimeData, QTimer
from PyQt6.QtGui import QGuiApplication, QClipboard
resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
app = QGuiApplication(['owned-login-clipboard', '-platform', 'xcb'])
cb = app.clipboard()
mode = QClipboard.Mode.Clipboard
original = QMimeData()
current = cb.mimeData(mode)
if current is not None:
for kind in current.formats():
original.setData(kind, QByteArray(current.data(kind)))
restored = False
credential_owned = False
def ack():
print('ok', flush=True)
def restore():
global restored, original
if not restored:
restored = True
# Never overwrite an independent copy made since our last paste.
if cb.ownsClipboard():
cb.setMimeData(original, mode)
original = None
def tick():
global credential_owned
try:
if restored:
# Like a normal X11 clipboard owner, retain the restored MIME data
# until another owner takes it. No keyboard/window access exists.
if not cb.ownsClipboard(): app.quit()
return
if not select.select([sys.stdin], [], [], 0)[0]: return
line = sys.stdin.readline()
if not line:
restore()
return
command = json.loads(line)
if command[0] == 'set':
if len(command) != 2 or not isinstance(command[1], str): raise ValueError()
if credential_owned and not cb.ownsClipboard(): raise ValueError()
value = QMimeData()
value.setText(command[1])
value.setData('x-kde-passwordManagerHint', QByteArray(b'secret'))
cb.setMimeData(value, mode)
credential_owned = True
command = None
elif command == ['restore']:
restore()
else: raise ValueError()
ack()
except Exception:
restore()
# Deliberately omit exception text: IPC may have contained credentials.
try: print('failed', flush=True)
except Exception: pass
timer = QTimer()
timer.timeout.connect(tick)
timer.start(10)
ack()
app.exec()
'''
@contextmanager
def private_login_clipboard():
"""Literal clipboard transaction, preserving all original MIME formats."""
worker=subprocess.Popen([sys.executable,'-c',_CLIPBOARD_OWNER],stdin=subprocess.PIPE,
stdout=subprocess.PIPE,stderr=subprocess.DEVNULL,text=True,
start_new_session=True)
def acknowledged():
# The helper first copies every MIME format of the owner's current
# clipboard (restored afterwards); a large image there took over 5 s
# on 2026-11-19 and aborted three runs before any input was sent.
if not select.select([worker.stdout],[],[],30)[0] or worker.stdout.readline().strip()!='ok':
raise RuntimeError('Private clipboard unavailable; no input replay')
def command(parts):
try:
worker.stdin.write(json.dumps(parts)+'\n');worker.stdin.flush()
acknowledged()
except (OSError,ValueError):
raise RuntimeError('Private clipboard unavailable; no input replay') from None
try:
acknowledged()
yield lambda value:command(['set',value])
finally:
try:command(['restore'])
finally:
worker.stdin.close();worker.stdout.close()
# The worker only serves restored clipboard data until ownership
# changes. It cannot retain a credential selection on pipe EOF.
def paste_login_clipboard(d,win,set_clipboard,value,*,after_paste=None,check_window=None):
(check_window or (lambda:ensure_focus(d,win)))()
if official_octo_focused(d):raise RuntimeError('Official Octo is focused; no credential input')
set_clipboard(value)
control=d.keysym_to_keycode(XK.string_to_keysym('Control_L'))
fake(d,X.KeyPress,control)
try:key(d,'v')
finally:fake(d,X.KeyRelease,control);d.sync()
# An owned window can confirm actual EditBox consumption before changing
# selection ownership. Keep the previous pacing for callers without a frame reader.
if after_paste is None:time.sleep(.15)
else:after_paste()
def streamlined_owned_login_values(d,win,username,password_provider,*,login_screen_ready=False,
before_password=None,account_has_focus=True,account_observer=None,
diagnose_account_paste=False,field_frame=None,check_window=None,account_click=None,
password_mask_count=None):
"""One clipboard fill, one Tab, capture gate before password; never replay.
Caller owns the exact process and establishes login-screen readiness once.
The existing uinput path and focus guards apply to every emitted press.
"""
if not login_screen_ready:raise RuntimeError('Prior local login-screen readiness required')
geometry=win.get_geometry()
if (geometry.width,geometry.height) not in ((1920,1080),(2560,1440)):
raise RuntimeError('Reviewed login window geometry required')
if not isinstance(username,str) or not username.isascii() or not 1<=len(username)<=16 or any(ord(c)<33 or ord(c)>126 for c in username):
raise RuntimeError('Reviewed short local account required')
validate_window=check_window or (lambda:ensure_focus(d,win))
read_fields=field_frame or (lambda:login_field_image(d,win))
def wait_field(predicate):
until=time.monotonic()+3
while True:
validate_window()
with read_fields() as frame:
if predicate(frame):return
left=until-time.monotonic()
if left<=0:raise RuntimeError('The local login field did not repaint')
time.sleep(min(.05,left))
def has_account(frame):
red,green,blue=frame.crop((814,538,1114,566)).convert('RGB').split()
darkest=ImageChops.darker(ImageChops.darker(red,green),blue)
return sum(darkest.histogram()[156:])>=24
validate_window()
if official_octo_focused(d):raise RuntimeError('Official Octo is focused; no credential input')
pixels=read_fields()
try:
# Interior excludes the textured field border; a lone blinking caret
# cannot satisfy the ink count. Replace only existing field contents.
populated=has_account(pixels)
initial_mask=(password_mask_count or password_mask_shapes)(pixels)
password_present=initial_mask is not None and initial_mask>0
finally:pixels.close()
# Original UpdateSavedData focuses Password for a saved account. An empty
# initial form keeps the user's observed Account focus; otherwise select
# Account explicitly before changing it with the existing reviewed click.
if populated or not account_has_focus:
x,y=round(960*geometry.width/1920),round(550*geometry.height/1080)
if account_click is not None:account_click(x,y)
else:click_at(d,win,x,y)
with private_login_clipboard() as clipboard:
if populated:
clear_edit_selection(d)
if field_frame:wait_field(lambda frame:not has_account(frame))
if field_frame:
paste_login_clipboard(d,win,clipboard,username,check_window=validate_window,
after_paste=lambda:wait_field(has_account))
else:paste_login_clipboard(d,win,clipboard,username)
key(d,'Tab')
if before_password is not None:before_password()
# Native Account paste was visually qualified in C53ShopClipboardGM.
# Reuse that evidence; weaker OCR is now an explicit diagnostic only.
if diagnose_account_paste:
pixels=read_fields()
account_matches=False
facts={'account_matches':False,'ocr_completed':False,'password_requested':False,
'account_was_populated':populated,'window_dimensions':[geometry.width,geometry.height],
'reference_dimensions':list(pixels.size),'owned_window_has_focus':owns_input(d,win.id),
'expected_field_after_tab':'PasswordEditBox','widget_focus_observed':False}
observation_started=time.monotonic()
try:
region=pixels.crop((814,538,1114,566)).convert('RGB')
try:facts['account_ink_pixels']=sum(1 for rgb in region.getdata() if min(rgb)>155)
finally:region.close()
observations=account_field_ocr(pixels)
account_matches=username.upper() in observations
facts.update(account_matches=account_matches,ocr_completed=True,
ocr_variant_count=len(observations))
finally:
facts['observation_seconds']=round(time.monotonic()-observation_started,3)
try:
if account_observer is not None:
# This bounded normalized crop ends above Password (y615).
# Never give the observer the full form or OCR strings.
account_crop=pixels.crop((790,510,1130,590))
try:account_observer(account_crop,facts)
finally:account_crop.close()
finally:pixels.close()
if not account_matches:raise RuntimeError('Account clipboard paste unconfirmed; password withheld')
password=password_provider()
if not isinstance(password,str) or not password or len(password)>128 or any(ord(c)<32 or ord(c)>126 for c in password):
raise RuntimeError('Unsupported password input; not submitted')
validate_window()
if password_mask_count is not None:
# A saved field can already have exactly the required number of masks.
# Observe a blank repaint before accepting the newly pasted value.
clear_edit_selection(d)
wait_field(lambda frame:password_mask_count(frame)==0)
expected=len(password)
paste_login_clipboard(d,win,clipboard,password,check_window=validate_window,
after_paste=lambda:wait_field(lambda frame:password_mask_count(frame)==expected))
elif field_frame:
if password_present:
clear_edit_selection(d)
wait_field(lambda frame:password_mask_shapes(frame)==0)
paste_login_clipboard(d,win,clipboard,password,check_window=validate_window,
after_paste=lambda:wait_field(lambda frame:password_mask_shapes(frame)>0))
else:
if password_present:clear_edit_selection(d)
paste_login_clipboard(d,win,clipboard,password)
with read_fields() as pixels:
if not password_mask_shapes(pixels):raise RuntimeError('Password clipboard paste unconfirmed; not submitted')
password=None
return {'account_preserved':False,'account_was_populated':populated,
'password_was_populated':password_present,'post_fill_ocr':False,
'clipboard':True,'account_paste_verified':diagnose_account_paste,
'account_paste_evidence_reused':not diagnose_account_paste,'password_mask_verified':True}
def _verified_login_values(d,win,username,password_provider):
"""Shared focus/form/account/mask guards; never report supplied values."""
geometry=win.get_geometry();dimensions=(geometry.width,geometry.height)
if dimensions not in ((1920,1080),(2560,1440)):raise RuntimeError('Login coordinates require the verified 1920x1080 or2560x1440 client window')
screen=private_screen(d,win,world_first=False)
if 'disconnected' in screen.lower() or not is_login_screen(screen):raise RuntimeError('Refusing credentials outside the local login screen or behind a disconnect modal')
expected=username.upper();visible=min(16,len(expected))
if not expected or len(expected)>2*visible:raise RuntimeError('Account address exceeds complete two-view verification coverage')
click_at(d,win,round(960*geometry.width/1920),round(550*geometry.height/1080));clear_edit_selection(d);type_text(d,username)
# This login widget can move Home/End without refreshing its horizontal viewport.
# An adjacent arrow pair updates that view while leaving the cursor at the endpoint.
key(d,'Home');key(d,'Right');key(d,'Left');key(d,'Tab')
verify_blurred_account(d,win,expected[:visible])
# A short native Turtle account is already completely verified in the
# first view. A redundant End-view OCR can misread the blinking caret;
# preserve the second view for longer modern frontend account addresses.
if len(expected)>visible:
key(d,'Tab');key(d,'End');key(d,'Left');key(d,'Right');key(d,'Tab')
verify_blurred_account(d,win,expected[-visible:])
# Native XML binds account Tab directly to PasswordEditBox:SetFocus().
# No second blind coordinate click or assumed standard Win32 Edit control.
# Focus the password box directly as well: a single missed Tab left the
# password in no field (mask_verified false) and aborted the login.
click_at(d,win,round(960*geometry.width/1920),round(631*geometry.height/1080))
clear_edit_selection(d);before=login_field_image(d,win).crop((804,615,1118,648)).convert('L');password=password_provider()
if not password or len(password)>128 or any(ord(c)<32 or ord(c)>126 for c in password):raise RuntimeError('Unsupported password input; nothing typed or submitted')
type_text(d,password)
# The mask dots repaint a frame or two after the last key; re-capture (no new input).
until=time.monotonic()+3
while True:
pixels=login_field_image(d,win)
if password_mask_shapes(pixels)>=min(3,len(password)) or time.monotonic()>=until:break
time.sleep(.1)
account_ok=any(expected[-visible:] in value for value in account_field_ocr(pixels))
password_values=field_ocr(pixels,(804,615,1118,648));chunk=min(8,len(password))
exposed=any(password.upper()[i:i+chunk] in value for i in range(len(password)-chunk+1) for value in password_values)
# Dot-shape counting misses this build's mask glyphs intermittently (the
# user saw both fields filled, then the guard cleared them). Masked text
# also shows as a large pixel change inside the password box; plaintext
# exposure stays separately OCR-guarded above.
after=pixels.crop((804,615,1118,648)).convert('L')
changed=sum(1 for a,b in zip(before.getdata(),after.getdata()) if abs(a-b)>40)
masked=password_mask_shapes(pixels)>=min(3,len(password)) or changed>=120
(ROOT/'runtime/login-field-verification.json').write_text(json.dumps({'account_unchanged':account_ok,'plaintext_detected':exposed,'mask_verified':masked,'password_box_changed_px':changed})+'\n')
if not account_ok or exposed or not masked:
click_at(d,win,round(960*geometry.width/1920),round(550*geometry.height/1080));clear_edit_selection(d);key(d,'Tab');clear_edit_selection(d)
raise RuntimeError('Login field or password-mask verification failed; inputs cleared, no submission')
print('Local login fields verified; password-screen capture discarded; values omitted.')
def launch(renderer=None):
# Wine's process name is observable without reading/printing credential argv.
existing=[]
for proc in Path('/proc').iterdir():
if not proc.name.isdigit():continue
try:
if (proc/'comm').read_text().strip().lower()=='wowb.exe':existing.append(int(proc.name))
except (FileNotFoundError,PermissionError,ProcessLookupError):pass
if existing:
print('Existing WowB.exe process preserved; use client_session.py ensure-world. Count:',len(existing))
return
info=json.loads((ROOT/'secrets/forever-local/account.json').read_text())
config=CLIENT/'WTF/Config.wtf'
if not (Path(info['recovery'])/'Config.wtf').exists(): raise RuntimeError('Client recovery point missing')
text=config.read_text(); text=re.sub(r'^SET portal .*$', 'SET portal "trinity.actual.battle.net"',text,flags=re.M)
config.write_text(text)
env=os.environ.copy(); env['WINEPREFIX']=str(PREFIX); env['WINEDEBUG']='-all'
log=ROOT/'runtime/client-wine.log'; fd=os.open(log,os.O_WRONLY|os.O_CREAT|os.O_APPEND,0o600)
with os.fdopen(fd,'ab') as output:
command=['wine',str(CLIENT/'WowB.exe'),'-console','-windowed']
if renderer: command.append('-'+renderer)
p=subprocess.Popen(command,cwd=CLIENT,env=env,stdout=output,stderr=subprocess.STDOUT,start_new_session=True)
(ROOT/'runtime/client-launch.pid').write_text(str(p.pid))
print('Launched real WowB.exe through Wine; launcher pid',p.pid,'; private log:',log)
return p
def main():
global UI,INPUT_WINDOW
os.umask(0o077)
p=argparse.ArgumentParser(); p.add_argument('action',choices=['launch','shot','state','key','click','login','geometry','type-test','fill-login','say-test','teleport-test','gps-test','mailbox-position-test','temporary-mailbox-test','npc-position-test','visibility-away-test','camera-pan','target-object','hover','logout','gm-mode','combat-start','combat-stop','vendor-api','allow-readonly-api','gm-command','melee-capture','combat-api','power-api','reputation-api','bindings-api','talent-api','talent-spec-api','spellbook-api','console-query','console-autocomplete','console-api','console-catalog-api','console-echo','console-build-api','console-event-api','console-frame-api','reload-ui','diagnostics-addon','turtle-talents','dismiss-lua-error'])
p.add_argument('--output',type=Path,default=ROOT/'runtime/forever-window.png')
p.add_argument('--command')
p.add_argument('--gm-mode',choices=['on','off'])
p.add_argument('--hold',type=float,default=0)
p.add_argument('--yaw-pixels',type=int,default=300)
p.add_argument('--name')
p.add_argument('--button',choices=['left','right'],default='left')
p.add_argument('--renderer',choices=['d3d11','d3d12'])
p.add_argument('--key',default='Return'); p.add_argument('--x',type=int); p.add_argument('--y',type=int)
args=p.parse_args()
if args.action=='launch': launch(args.renderer); return
d=display.Display()
try:win=target(d);ensure_focus(d,win)
except ClientWindowBlocked as error:
d.close()
if args.action=='state':print('Actual WowB UI state:',error.kind);return
raise
geom=win.get_geometry()
if args.action not in ('shot','geometry','state'):
if not owns_input(d,win.id): raise RuntimeError('Refusing input without WowB focus')
UI=UInput({ecodes.EV_KEY:list(range(1,248))+[ecodes.BTN_LEFT,ecodes.BTN_RIGHT],ecodes.EV_REL:[ecodes.REL_X,ecodes.REL_Y]},name='Gateway local WowB test input')
INPUT_WINDOW=win.id
time.sleep(.5)
if args.action=='shot':
try:
with timed('screenshot'):screen=capture_text(d,win,args.output,world_first=True)
except Exception:
args.output.unlink(missing_ok=True);raise
if is_login_screen(screen):
args.output.unlink(missing_ok=True);raise RuntimeError('Credential-screen capture discarded; use state for private classification')
print('Captured compositor view of real WowB.exe:',args.output)
elif args.action=='state':
screen=private_screen(d,win)
print('Actual WowB UI state:', 'login' if is_login_screen(screen) else ' '.join(token for token in ('Normal','Select','Gatewaytest','Enter World','Northshire','Disconnected','Okay','Please enter') if token.lower() in screen.lower()) or 'unclassified')
elif args.action=='geometry': print('WowB client size:',geom.width,geom.height)
elif args.action=='dismiss-lua-error':
text=private_screen(d,win,world_first=False).lower()
words=re.sub(r'[^a-z]','',text)
if 'luaerror' not in words or 'reloadu' not in words or 'close' not in words:raise RuntimeError('Expected Lua error dialog is not visible')
click_at(d,win,1432,690)
elif args.action in ('console-query','console-autocomplete'):
verify_console(d,win)
if not args.command or not re.fullmatch(r'[A-Za-z_?][A-Za-z0-9_? .-]{0,95}',args.command):
raise RuntimeError('Console diagnostics require a bounded public command without script syntax')
if args.action=='console-query' and not (args.command in ('help','?','version','cmdlist','consolelog','loglevel','developerLog 0','developerLog 1') or re.fullmatch(r'help [A-Za-z_][A-Za-z0-9_]{0,63}',args.command) or re.fullmatch(r'cvarlist (?:developerLog|consoleShow|scriptErrors|ClientCastDebug|enableQuestCacheLogging|ConsoleKey|HotfixEventLog|SpellVisuals|spellVisualDensityFilterSetting|AuraDebugger|AuraEventLog|SpellEventLog)',args.command)):
raise RuntimeError('Console query is outside the initial read-only discovery allowlist')
click_at(d,win,200,416);key(d,'End')
for _ in range(96):key(d,'BackSpace')
type_text(d,args.command)
key(d,'Tab' if args.action=='console-autocomplete' else 'Return')
time.sleep(.5)
print('Sent focused console diagnostic:',args.action,args.command)
elif args.action=='key':
if not 0<=args.hold<=5: p.error('--hold must be between 0 and 5 seconds')
code=d.keysym_to_keycode(XK.string_to_keysym(args.key))
if not code: raise RuntimeError('Unknown keysym')
fake(d,X.KeyPress,code)
try: time.sleep(args.hold)
finally: fake(d,X.KeyRelease,code); d.sync()
elif args.action in ('click','hover'):
if args.x is None or args.y is None: p.error('--x/--y required')
click_at(d,win,args.x,args.y,None if args.action=='hover' else (ecodes.BTN_RIGHT if args.button=='right' else ecodes.BTN_LEFT))
elif args.action in ('gm-mode','combat-start','combat-stop'):
if not is_world_screen(private_screen(d,win)):raise RuntimeError('Gameplay mode action requires verified Northshire world')
if args.action=='gm-mode':
if not args.gm_mode:p.error('--gm-mode on|off required')
command='/say .gm '+args.gm_mode
else:command='/startattack' if args.action=='combat-start' else '/stopattack'
key(d,'Return');type_text(d,command);key(d,'Return')
print('Requested local test action:',args.action,args.gm_mode or '')
elif args.action=='allow-readonly-api':
text=re.sub(r'[^a-z]','',private_screen(d,win).lower())
if not all(v in text for v in ('allowcustomscripts','attemptingtorunacustomscript')):raise RuntimeError('Read-only API enable action requires the exact client script-consent dialog')
click_at(d,win,894,230)
print('Accepted the verified custom-script dialog for bounded read-only API diagnostics.')
elif args.action in ('reload-ui','diagnostics-addon','turtle-talents'):
if not is_world_screen(private_screen(d,win)):raise RuntimeError('Diagnostic addon action requires verified local world')
command={'reload-ui':'/reload','diagnostics-addon':'/gwdiag console','turtle-talents':'/turtletalents'}[args.action]
key(d,'Return');type_text(d,command);key(d,'Return');time.sleep(1)
print('Requested local UI diagnostic action:',args.action)
elif args.action=='combat-api':
if not is_world_screen(private_screen(d,win)):raise RuntimeError('Combat API requires verified local world')
key(d,'Return');type_text(d,'/run print("Gateway health",UnitHealth("player"),UnitHealthMax("player"),UnitHealth("target"),UnitGUID("target"))');key(d,'Return')
elif args.action in ('power-api','reputation-api','bindings-api','talent-api','talent-spec-api','spellbook-api'):
if not is_world_screen(private_screen(d,win)):raise RuntimeError('Gameplay diagnostic API requires verified local world')
commands={
'power-api':'/run print("GW power",UnitPower("player"),UnitPowerMax("player"),UnitPowerType("player"))',
'reputation-api':'/run print("GW rep APIs",type(C_Reputation),C_Reputation and type(C_Reputation.GetNumFactions),C_Reputation and type(C_Reputation.GetFactionDataByIndex));print("GW rep binding",GetBindingKey("TOGGLEREPUTATION"))',
'bindings-api':'/run for i=1,GetNumBindings() do local n,k,a,b=GetBinding(i);if n:find("REPUT") then print("GW binding",n,a,b) end end',
'talent-api':'/run print("GW traits",C_SpecializationInfo.IsInitialized(),C_SpecializationInfo.GetSpecialization(),C_ClassTalents.GetActiveConfigID());print("GW Arms tree",C_ClassTalents.GetTraitTreeForSpec(71))',
'talent-spec-api':'/run local id,name=C_SpecializationInfo.GetSpecializationInfo(1);print("GW actual spec",id,name);print("GW actual tree",id and C_ClassTalents.GetTraitTreeForSpec(id))',
'spellbook-api':'/run print("GW spellbook lines",C_SpellBook.GetNumSpellBookSkillLines());print("GW Attack known",C_SpellBook.IsSpellKnown(6603));print("GW Heroic Strike known",C_SpellBook.IsSpellKnown(78))',
}
key(d,'Return');type_text(d,commands[args.action]);key(d,'Return');time.sleep(.5)
elif args.action in ('console-api','console-catalog-api','console-echo','console-build-api','console-event-api','console-frame-api'):
if not is_world_screen(private_screen(d,win)):raise RuntimeError('Console Lua API discovery requires the verified world, with console closed')
commands={
'console-api':'/run print("GW Console APIs",type(ConsoleGetAllCommands),type(ConsoleEcho),type(ConsoleExec),type(ConsoleIsActive),type(ConsolePrintAllMatchingCommands),type(GetCVarInfo))',
'console-catalog-api':'/run local c=ConsoleGetAllCommands();print("GW catalog",type(c),#c,ConsoleIsActive());for k,v in pairs(c[1]) do print("GW row",k,v) end',
'console-echo':'/run ConsoleEcho("GWDIAG Literal console marker")',
'console-build-api':'/run print("GW build",GetBuildInfo());print("GW CVars",type(C_CVar),type(GetCVar));print("GW logging",GetCVar("developerLog"),GetCVar("developerLogWriteToFile"))',
'console-frame-api':'/run for _,f in ipairs({GetFramesRegisteredForEvent("CONSOLE_MESSAGE")}) do print("GW console frame",f:GetName()) end',
'console-event-api':'/run GWC=CreateFrame("Frame");GWC:RegisterEvent("CONSOLE_MESSAGE");GWC:SetScript("OnEvent",function(_,_,m) if type(m)=="string" and m:find("Commands registered",1,true) then print("GW event",m) end end);ConsoleExec("help console")',
}
if len(commands[args.action])>255:raise RuntimeError('Diagnostic exceeds verified chat input bound')
key(d,'Return');type_text(d,commands[args.action]);key(d,'Return')
elif args.action=='melee-capture':
if not is_world_screen(private_screen(d,win)):raise RuntimeError('Melee capture requires verified local world')
key(d,'Return');type_text(d,'/targetexact Young Wolf');key(d,'Return');time.sleep(.3)
key(d,'Return');type_text(d,'/startattack');key(d,'Return')
directory=ROOT/'runtime/melee-observation';directory.mkdir(exist_ok=True,mode=0o700)
for i in range(8):
path=directory/f'frame-{i}.png';text=capture_text(d,win,path)
if is_login_screen(text):path.unlink(missing_ok=True);raise RuntimeError('Melee capture stopped on a login transition')
print('Captured actual melee frame',i,flush=True);time.sleep(.4)
elif args.action=='gm-command':
if not is_world_screen(private_screen(d,win)):raise RuntimeError('GM diagnostic requires verified local world')
if not args.command or not re.fullmatch(r'(?:\.save|\.gm(?: visible)? (?:on|off)|\.go creature [1-9][0-9]{0,6}|\.levelup -?[0-9]{1,2}|\.modify (?:hp|mana|money|rage) [0-9]{1,6}|\.modify rep [1-9][0-9]{0,4} -?[0-9]{1,5}|\.learn [0-9]{1,6}|\.unlearn [0-9]{1,6}|\.gps)',args.command):raise RuntimeError('Command outside bounded disposable-character test actions')
key(d,'Return');type_text(d,'/say '+args.command);key(d,'Return')
print('Requested scoped local gameplay test command:',args.command)
elif args.action=='vendor-api':
if not is_world_screen(private_screen(d,win)):raise RuntimeError('Vendor API read requires verified world')
key(d,'Return');type_text(d,'/run print("Gateway merchant", GetMerchantNumItems(), MerchantFrame:IsShown())');key(d,'Return')
elif args.action=='logout':
if not is_world_screen(private_screen(d,win)): raise RuntimeError('Logout requires verified world scene')
key(d,'Return');type_text(d,'/logout');key(d,'Return')
elif args.action=='target-object':
if not args.name or not re.fullmatch(r"[A-Za-z '\-]{1,63}",args.name): p.error('--name requires a bounded local object name')
if not is_world_screen(private_screen(d,win)): raise RuntimeError('Object target requires the verified local world scene')
key(d,'Return');type_text(d,'/targetexact '+args.name);key(d,'Return')
print('Requested local client target:',args.name,'; no movement or server state change requested.')
elif args.action=='camera-pan':
if not -800<=args.yaw_pixels<=800: p.error('--yaw-pixels must be -800..800')
if not is_world_screen(private_screen(d,win)): raise RuntimeError('Camera pan requires the verified local world scene')
click_at(d,win,960,450)
UI.write(ecodes.EV_KEY,ecodes.BTN_LEFT,1);UI.syn()
try:
for step in range(abs(args.yaw_pixels)//5):
if not owns_input(d,win.id): raise RuntimeError('WowB lost focus; camera action stopped')
UI.write(ecodes.EV_REL,ecodes.REL_X,5 if args.yaw_pixels>=0 else -5);UI.syn();time.sleep(.01)
finally:
UI.write(ecodes.EV_KEY,ecodes.BTN_LEFT,0);UI.syn()
print('Panned actual WowB camera with left mouse only; no character movement requested.')
elif args.action=='temporary-mailbox-test':
key(d,'Return'); type_text(d,'/say .gobject tmpadd 144131 10'); key(d,'Return')
elif args.action=='npc-position-test':
# Five yards west of existing local Turtle spawn79970 (entry197), facing east.
key(d,'Return'); type_text(d,'/say .go xyz -8907.59 -162.606 82.0223 0'); key(d,'Return')
elif args.action=='visibility-away-test':
# Same-map Goldshire position, outside Northshire's Turtle visibility range.
key(d,'Return'); type_text(d,'/say .go xyz -9465.58 64.72 56.38 0'); key(d,'Return')
elif args.action=='mailbox-position-test':
key(d,'Return'); type_text(d,'/say .go xyz -8913.8 -132.054 81.2 0'); key(d,'Return')
elif args.action=='gps-test':
key(d,'Return'); type_text(d,'/say .gps'); key(d,'Return')
elif args.action=='teleport-test':
key(d,'Return'); type_text(d,'/say .go xyz -8949.95 -132.493 83.5312 0'); key(d,'Return')
elif args.action=='say-test':
key(d,'Return'); type_text(d,'/say Gateway local chat test'); key(d,'Return')
elif args.action=='type-test': clear(d); type_text(d,'GWTEST')
elif args.action in ('login','fill-login'):
verified_login_fields(d,win)
if args.action=='login':
key(d,'Return')
print('Entered disposable local Forever credentials; values omitted.')
if UI is not None: time.sleep(.2); UI.close()
d.close()
if __name__=='__main__':
with timed('cli-total'):main()