#!/usr/bin/env python3 """Capture before/after screenshots for issue 40768970. The CL adds the default-on kill switch `HideUnfocusedReadonlyTextControlSelection` to `FrameSelection::SelectionHasFocus()`. Without it a selection inside a readonly text control keeps being reported as focused after the control loses the focus, so the highlight stays painted. `sampler.html?case=` selects the text of one control and then moves the focus to a sink div. Screenshots are taken after the move. Output tree: rendered/-before.png feature disabled (bug behavior) rendered/-after.png feature enabled (default) expected/.png same as -after diff/.png per-pixel mask of before vs after """ import base64 import json import os import subprocess import sys import time import urllib.request import websocket from PIL import Image, ImageChops HERE = os.path.dirname(os.path.abspath(__file__)) CONTENT_SHELL = os.path.expanduser("~/chromium_2/src/out/Default/content_shell") SAMPLER_FILE = os.path.join(HERE, "sampler.html") VIEWPORT_WIDTH = 600 VIEWPORT_HEIGHT = 260 DEVICE_SCALE_FACTOR = 1 FEATURE = "HideUnfocusedReadonlyTextControlSelection" CASES = ["readonly", "editable", "disabled", "plaintext"] def wait_devtools(port): for _ in range(30): try: resp = urllib.request.urlopen("http://127.0.0.1:{}/json".format(port)) tabs = json.loads(resp.read()) if tabs: return tabs[0]["webSocketDebuggerUrl"] except Exception: time.sleep(0.5) raise RuntimeError("DevTools did not come up on port %d" % port) def devtools(ws, counter, method, params=None): counter[0] += 1 msg = {"id": counter[0], "method": method} if params: msg["params"] = params ws.send(json.dumps(msg)) while True: resp = json.loads(ws.recv()) if resp.get("id") == counter[0]: return resp def capture_run(label, extra_flags, out_subdir): port = 9431 if label == "after" else 9430 cmd = [ CONTENT_SHELL, "--remote-debugging-port={}".format(port), "--remote-allow-origins=*", "--force-device-scale-factor={}".format(DEVICE_SCALE_FACTOR), "--no-sandbox", "--hide-scrollbars", "about:blank", ] + extra_flags proc = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) try: ws_url = wait_devtools(port) ws = websocket.create_connection(ws_url) counter = [0] # Without focus emulation an offscreen content_shell window never # counts as focused, so no selection is painted at all. devtools(ws, counter, "Emulation.setFocusEmulationEnabled", {"enabled": True}) devtools( ws, counter, "Emulation.setDeviceMetricsOverride", { "width": VIEWPORT_WIDTH, "height": VIEWPORT_HEIGHT, "deviceScaleFactor": DEVICE_SCALE_FACTOR, "mobile": False, }, ) results = {} for case in CASES: url = "file://" + SAMPLER_FILE + "?case=" + case devtools(ws, counter, "Page.navigate", {"url": url}) time.sleep(1.5) if case == "disabled": select_disabled_and_move_focus(ws, counter) time.sleep(0.5) clip = { "x": 0, "y": 0, "width": VIEWPORT_WIDTH, "height": VIEWPORT_HEIGHT, "scale": DEVICE_SCALE_FACTOR, } shot = devtools( ws, counter, "Page.captureScreenshot", {"format": "png", "clip": clip} ) img = base64.b64decode(shot["result"]["data"]) out_path = os.path.join(HERE, out_subdir, "{}-{}.png".format(case, label)) os.makedirs(os.path.dirname(out_path), exist_ok=True) with open(out_path, "wb") as f: f.write(img) results[case] = out_path print(" {:<10} {:<6} -> {}".format(case, label, out_path)) ws.close() return results finally: proc.terminate() try: proc.wait(timeout=5) except subprocess.TimeoutExpired: proc.kill() def select_disabled_and_move_focus(ws, counter): """Double-clicks the disabled control, then moves the focus to the iframe. `select()` does not work on a disabled text control, so the selection has to come from real mouse events. """ box = devtools( ws, counter, "Runtime.evaluate", { "expression": "JSON.stringify(document.getElementById('field')" ".getBoundingClientRect())" }, ) rect = json.loads(box["result"]["result"]["value"]) x = int(rect["x"] + 40) y = int(rect["y"] + rect["height"] / 2) for click_count in (1, 2): for event_type in ("mousePressed", "mouseReleased"): devtools( ws, counter, "Input.dispatchMouseEvent", { "type": event_type, "x": x, "y": y, "button": "left", "clickCount": click_count, }, ) devtools( ws, counter, "Runtime.evaluate", { "expression": "document.getElementById('sink').contentWindow.focus();" "document.getElementById('state').textContent =" " 'step: focus moved into the iframe'" }, ) def write_diffs(before, after): for case in CASES: if case not in before or case not in after: continue a = Image.open(before[case]).convert("RGBA") b = Image.open(after[case]).convert("RGBA") if a.size != b.size: print("WARN: size mismatch for %s" % case) continue diff = ImageChops.difference(a, b) mask = diff.convert("L").point(lambda v: 255 if v else 0) out = Image.new("RGBA", a.size, (0, 0, 0, 0)) out.paste(Image.new("RGBA", a.size, (255, 0, 255, 255)), mask=mask) changed = sum(1 for p in mask.getdata() if p) out_path = os.path.join(HERE, "diff", "{}.png".format(case)) os.makedirs(os.path.dirname(out_path), exist_ok=True) out.save(out_path) print(" diff {:<10} changed_px={} -> {}".format(case, changed, out_path)) def copy_expected(after): for case, path in after.items(): dst = os.path.join(HERE, "expected", "{}.png".format(case)) os.makedirs(os.path.dirname(dst), exist_ok=True) with open(path, "rb") as src, open(dst, "wb") as out: out.write(src.read()) print(" expected {:<10} -> {}".format(case, dst)) def main(): print("[1/3] capture BEFORE (feature disabled)") before = capture_run( label="before", extra_flags=["--disable-blink-features=" + FEATURE], out_subdir="rendered", ) print("[2/3] capture AFTER (feature enabled, default)") after = capture_run( label="after", extra_flags=["--enable-blink-features=" + FEATURE], out_subdir="rendered", ) print("[3/3] write expected/ and diff/") copy_expected(after) write_diffs(before, after) print("Done.") if __name__ == "__main__": sys.exit(main())