#!/usr/bin/env python3 """Capture before/after screenshots for issue 40796813. After a box selection covers an `input[type=range]`, pressing the thumb used to arm a selection drag (`DragController::DraggableNode` sees the press inside the selection), which swallowed the thumb drag and showed the not-allowed cursor. The fix clears the selection in `SliderThumbElement::DefaultEventHandler` before `StartDragging()`. There is no runtime flag here, so "before" is an unpatched `content_shell` (`out/dist`) and "after" is the patched one (`out/Default`). Both run the same `sampler.html` with mouse events synthesized over DevTools. Output tree: rendered/-before.png unpatched content_shell rendered/-after.png patched content_shell 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__)) SRC = os.path.expanduser("~/chromium_2/src") SHELL_BEFORE = os.path.join(SRC, "out/dist/content_shell") SHELL_AFTER = os.path.join(SRC, "out/Default/content_shell") SAMPLER_FILE = os.path.join(HERE, "sampler.html") VIEWPORT_WIDTH = 600 VIEWPORT_HEIGHT = 260 DEVICE_SCALE_FACTOR = 1 CASES = ["boxselect", "trackpress", "plain", "elsewhere"] 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 evaluate(ws, counter, expression): resp = devtools(ws, counter, "Runtime.evaluate", {"expression": expression}) return resp["result"]["result"].get("value") def mouse(ws, counter, event_type, x, y): devtools( ws, counter, "Input.dispatchMouseEvent", { "type": event_type, "x": int(x), "y": int(y), "button": "left", "buttons": 1 if event_type != "mouseReleased" else 0, "clickCount": 1, }, ) time.sleep(0.05) def drag(ws, counter, path): """Presses at the first point, moves through the rest, releases.""" mouse(ws, counter, "mousePressed", *path[0]) for point in path[1:]: mouse(ws, counter, "mouseMoved", *point) mouse(ws, counter, "mouseReleased", *path[-1]) def rect_of(ws, counter, selector): raw = evaluate( ws, counter, "JSON.stringify(document.querySelector('{}')" ".getBoundingClientRect())".format(selector), ) return json.loads(raw) def run_case(ws, counter, case): slider = rect_of(ws, counter, "#slider") center_y = slider["y"] + slider["height"] / 2 if case in ("boxselect", "trackpress"): drag( ws, counter, [ (slider["x"] - 10, slider["y"] + slider["height"] + 25), (slider["x"] + 60, center_y), (slider["x"] + slider["width"] + 20, slider["y"] - 25), ], ) elif case == "elsewhere": below = rect_of(ws, counter, "#below") drag( ws, counter, [ (below["x"] + 2, below["y"] + below["height"] / 2), (below["x"] + 120, below["y"] + below["height"] / 2), ], ) if case == "elsewhere": thumb_x = slider["x"] + slider["width"] / 2 mouse(ws, counter, "mousePressed", thumb_x, center_y) mouse(ws, counter, "mouseReleased", thumb_x, center_y) return # Drag to the right, starting on the thumb (value 50 puts it at the track # center) or, for `trackpress`, on the track left of the thumb. start_x = slider["x"] + slider["width"] * (0.2 if case == "trackpress" else 0.5) drag( ws, counter, [ (start_x, center_y), (slider["x"] + slider["width"] * 0.7, center_y), (slider["x"] + slider["width"] * 0.95, center_y), ], ) def capture_run(label, shell, out_subdir): port = 9461 if label == "after" else 9460 proc = subprocess.Popen( [ shell, "--remote-debugging-port={}".format(port), "--remote-allow-origins=*", "--force-device-scale-factor={}".format(DEVICE_SCALE_FACTOR), "--no-sandbox", "--hide-scrollbars", "about:blank", ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) try: ws = websocket.create_connection(wait_devtools(port)) counter = [0] 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.0) run_case(ws, counter, case) time.sleep(0.4) shot = devtools( ws, counter, "Page.captureScreenshot", { "format": "png", "clip": { "x": 0, "y": 0, "width": VIEWPORT_WIDTH, "height": VIEWPORT_HEIGHT, "scale": DEVICE_SCALE_FACTOR, }, }, ) 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(base64.b64decode(shot["result"]["data"])) value = evaluate(ws, counter, "document.getElementById('slider').value") print(" {:<10} {:<6} value={:<4} -> {}".format( case, label, value, out_path)) results[case] = out_path ws.close() return results finally: proc.terminate() try: proc.wait(timeout=5) except subprocess.TimeoutExpired: proc.kill() def write_diffs(before, after): for case in CASES: 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 mask = ImageChops.difference(a, b).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(): for shell in (SHELL_BEFORE, SHELL_AFTER): if not os.path.exists(shell): raise SystemExit("missing content_shell: " + shell) print("[1/3] capture BEFORE (unpatched content_shell)") before = capture_run("before", SHELL_BEFORE, "rendered") print("[2/3] capture AFTER (patched content_shell)") after = capture_run("after", SHELL_AFTER, "rendered") print("[3/3] write expected/ and diff/") copy_expected(after) write_diffs(before, after) print("Done.") if __name__ == "__main__": sys.exit(main())