#!/usr/bin/env python3 """Capture before/after screenshots for CL 8623059 (crbug.com/41131764). Loads the demo extension (`cl-8623059-extension`) plus a sample target extension that declares content scripts, opens the demo extension's panel and screenshots it. "before" is a local build of the CL's parent revision, "after" the same build with the patch applied; stock Chrome refuses --load-extension. Output: rendered/panel-before.png rendered/panel-after.png """ import base64 import json import os import shutil import subprocess import sys import tempfile import time import urllib.request import websocket HERE = os.path.dirname(os.path.abspath(__file__)) EXTENSION = os.path.expanduser("~/lab/cl-8623059-extension") TARGET = os.path.join(EXTENSION, "sample-target") CHROME = os.path.expanduser("~/chromium_2/src/out/Default/chrome") VIEWPORT_WIDTH = 600 VIEWPORT_HEIGHT = 520 def wait_devtools(port): for _ in range(60): try: resp = urllib.request.urlopen("http://127.0.0.1:{}/json".format(port)) tabs = json.loads(resp.read()) if tabs: return tabs 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 extension_id(ws, counter): """Returns the demo extension's id, read from the management API itself.""" resp = devtools( ws, counter, "Runtime.evaluate", { "expression": "new Promise(r => chrome.management.getAll(" "all => r(JSON.stringify(all))))", "awaitPromise": True, }, ) for info in json.loads(resp["result"]["result"]["value"]): if info["name"] == "Content Script Inspector": return info["id"] raise RuntimeError("demo extension not found") def capture(label, port=9480): chrome = CHROME profile = tempfile.mkdtemp(prefix="cl8623059-") proc = subprocess.Popen( [ chrome, "--remote-debugging-port={}".format(port), "--remote-allow-origins=*", "--user-data-dir=" + profile, "--no-first-run", "--no-default-browser-check", "--disable-features=DisableLoadExtensionCommandLineSwitch", "--disable-extensions-except={},{}".format(EXTENSION, TARGET), "--load-extension={},{}".format(EXTENSION, TARGET), "--window-size={},{}".format(VIEWPORT_WIDTH, VIEWPORT_HEIGHT), "about:blank", ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) try: tabs = wait_devtools(port) page = [t for t in tabs if t["type"] == "page"][0] ws = websocket.create_connection(page["webSocketDebuggerUrl"]) counter = [0] devtools( ws, counter, "Emulation.setDeviceMetricsOverride", { "width": VIEWPORT_WIDTH, "height": VIEWPORT_HEIGHT, "deviceScaleFactor": 1, "mobile": False, }, ) # The panel is a normal extension page, so it can be opened in a tab. devtools( ws, counter, "Page.navigate", {"url": "chrome://extensions"}, ) time.sleep(2) demo_id = extension_id(ws, counter) devtools( ws, counter, "Page.navigate", {"url": "chrome-extension://{}/panel.html".format(demo_id)}, ) time.sleep(2) shot = devtools( ws, counter, "Page.captureScreenshot", { "format": "png", "captureBeyondViewport": True, }, ) out_path = os.path.join(HERE, "rendered", "panel-{}.png".format(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"])) print(" {:<6} -> {}".format(label, out_path)) ws.close() finally: proc.terminate() try: proc.wait(timeout=10) except subprocess.TimeoutExpired: proc.kill() shutil.rmtree(profile, ignore_errors=True) def main(): """Captures one label; the caller builds the matching binary first. The CL has no runtime flag, so "before" is a build of the parent revision and "after" a build with the patch applied: git stash && autoninja -C out/Default chrome python3 capture_screenshots.py before git stash pop && autoninja -C out/Default chrome python3 capture_screenshots.py after """ label = sys.argv[1] if len(sys.argv) > 1 else "after" capture(label) print("Done.") if __name__ == "__main__": sys.exit(main())