#!/usr/bin/env python3 """Capture before/after screenshots for crbug.com/377537312. Mirrors what a screenshot tool does: set the generic font families over the DevTools protocol (Page.setFontFamilies), then take a captureBeyondViewport screenshot, which makes the browser re-push unchanged WebPreferences. Without the fix that re-push drops the override, so the second screenshot renders with a different monospace font than the first. The CL is behind a kill switch, so both runs use the same binary: python3 capture_screenshots.py after python3 capture_screenshots.py before # adds --disable-blink-features """ import base64 import functools import http.server import json import os import subprocess import sys import threading import time import urllib.request import websocket from PIL import Image, ImageChops HERE = os.path.dirname(os.path.abspath(__file__)) CHROME = os.path.expanduser("~/chromium_2/src/out/Default/chrome") PORT = 8785 VIEWPORT_WIDTH = 460 VIEWPORT_HEIGHT = 150 FEATURE = "PreserveDevToolsFontFamilyOverrides" def serve(): handler = functools.partial(http.server.SimpleHTTPRequestHandler, directory=HERE) server = http.server.ThreadingHTTPServer(("127.0.0.1", PORT), handler) threading.Thread(target=server.serve_forever, daemon=True).start() return server def wait_devtools(port): for _ in range(60): try: tabs = json.loads( urllib.request.urlopen( "http://127.0.0.1:{}/json".format(port)).read()) pages = [t for t in tabs if t["type"] == "page"] if pages: return pages[0] except Exception: time.sleep(0.5) raise RuntimeError("DevTools did not come up") 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 screenshot(ws, counter): shot = devtools(ws, counter, "Page.captureScreenshot", { "format": "png", "captureBeyondViewport": True, }) return base64.b64decode(shot["result"]["data"]) def capture(label, port=9540): flags = [] if label == "after" else ["--disable-blink-features=" + FEATURE] proc = subprocess.Popen( [ CHROME, "--remote-debugging-port={}".format(port), "--remote-allow-origins=*", "--force-device-scale-factor=1", "--no-sandbox", "--hide-scrollbars", "--no-first-run", "--no-default-browser-check", "--window-size=460,260", "--user-data-dir=/tmp/cl8649780-profile-" + label, "about:blank", ] + flags, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) try: page = wait_devtools(port) ws = websocket.create_connection(page["webSocketDebuggerUrl"]) counter = [0] devtools(ws, counter, "Page.enable") # What a screenshot tool does: pin the generic families first. devtools(ws, counter, "Page.setFontFamilies", {"fontFamilies": {"fixed": "Liberation Serif"}}) devtools(ws, counter, "Page.navigate", {"url": "http://127.0.0.1:{}/sampler.html".format(PORT)}) time.sleep(2) # The full-page capture re-pushes WebPreferences whose font family # maps did not change. Shoot again afterwards: that is the page a # screenshot tool gets for every capture after the first one. screenshot(ws, counter) time.sleep(1.5) out_path = os.path.join(HERE, "rendered", "page-{}.png".format(label)) os.makedirs(os.path.dirname(out_path), exist_ok=True) with open(out_path, "wb") as f: f.write(screenshot(ws, counter)) width = devtools(ws, counter, "Runtime.evaluate", { "expression": "document.getElementById('sample')" ".getBoundingClientRect().width", })["result"]["result"]["value"] print(" {:<6} monospace run width after the capture: {}".format( label, width)) ws.close() finally: proc.terminate() try: proc.wait(timeout=5) except subprocess.TimeoutExpired: proc.kill() def write_diff(): """Diffs the two builds; only runs once both captures exist.""" paths = [os.path.join(HERE, "rendered", "page-{}.png".format(label)) for label in ("before", "after")] if not all(os.path.exists(path) for path in paths): return a = Image.open(paths[0]).convert("RGBA") b = Image.open(paths[1]).convert("RGBA") 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", "page.png") os.makedirs(os.path.dirname(out_path), exist_ok=True) out.save(out_path) print(" diff changed_px={}".format(changed)) def main(): label = sys.argv[1] if len(sys.argv) > 1 else "after" server = serve() try: capture(label) write_diff() finally: server.shutdown() print("Done.") if __name__ == "__main__": sys.exit(main())