#!/usr/bin/env python3 """Capture before/after screenshots for crbug.com/40853412. Renders sampler.html, which uses an external SVG and an in-document symbol, both carrying a SMIL animation, with both timelines frozen past the animation. The caller builds the matching binary first: git checkout HEAD~1 -- third_party/blink/renderer/core/svg && autoninja -C out/Default content_shell python3 capture_screenshots.py before git checkout HEAD -- third_party/blink/renderer/core/svg && autoninja -C out/Default content_shell python3 capture_screenshots.py after """ 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__)) CONTENT_SHELL = os.path.expanduser("~/chromium_4/src/out/Default/content_shell") SAMPLER_FILE = os.path.join(HERE, "sampler.html") # The external reference needs an http origin. PORT = 8778 VIEWPORT_WIDTH = 360 VIEWPORT_HEIGHT = 740 CASES = {"use": []} # "before" is the feature-off baseline, produced by the kill switch rather # than an old binary so both shots come from the same build. BEFORE_FLAGS = ["--disable-blink-features=SvgUseInstanceAnimations"] 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(label, case, flags, port=9495): proc = subprocess.Popen( [ CONTENT_SHELL, "--remote-debugging-port={}".format(port), "--remote-allow-origins=*", "--no-sandbox", "--hide-scrollbars", "about:blank", ] + flags, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) try: ws = websocket.create_connection(wait_devtools(port)) counter = [0] devtools( ws, counter, "Emulation.setDeviceMetricsOverride", { "width": VIEWPORT_WIDTH, "height": VIEWPORT_HEIGHT, "deviceScaleFactor": 1, "mobile": False, }, ) devtools(ws, counter, "Page.navigate", {"url": "http://127.0.0.1:{}/sampler.html".format(PORT)}) time.sleep(1.5) shot = devtools( ws, counter, "Page.captureScreenshot", { "format": "png", "clip": { "x": 0, "y": 0, "width": VIEWPORT_WIDTH, "height": VIEWPORT_HEIGHT, "scale": 1, }, }, ) out_path = os.path.join( HERE, "rendered", "{}-{}.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"])) readout = devtools( ws, counter, "Runtime.evaluate", {"expression": "document.title"}, )["result"]["result"]["value"] print(" {:<9} {:<6} {} -> {}".format(case, label, readout, out_path)) ws.close() finally: proc.terminate() try: proc.wait(timeout=5) except subprocess.TimeoutExpired: proc.kill() def write_diffs(): for case in CASES: before = os.path.join(HERE, "rendered", "{}-before.png".format(case)) after = os.path.join(HERE, "rendered", "{}-after.png".format(case)) if not (os.path.exists(before) and os.path.exists(after)): continue a = Image.open(before).convert("RGBA") b = Image.open(after).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", "{}.png".format(case)) os.makedirs(os.path.dirname(out_path), exist_ok=True) out.save(out_path) print(" diff {:<9} changed_px={} -> {}".format(case, changed, out_path)) 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 main(): label = sys.argv[1] if len(sys.argv) > 1 else "after" server = serve() for case, flags in CASES.items(): if label == "before": flags = flags + BEFORE_FLAGS capture(label, case, flags) write_diffs() server.shutdown() print("Done.") if __name__ == "__main__": sys.exit(main())