#!/usr/bin/env python3
"""Capture screenshots for the TableDefaultBorderColorCurrentColor cleanup.
Two cases per build:
default - how a
border paints out of the box
disabled - the same page with
--disable-blink-features=TableDefaultBorderColorCurrentColor
The feature shipped in M149, so `default` is identical before and after the
CL. `disabled` is the interesting one: before the CL the switch brings the
old `border-color: gray` UA rule back, after it the flag is gone and the
switch does nothing.
The caller builds the matching binary first:
git checkout HEAD~1 -- && autoninja -C out/Default content_shell
python3 capture_screenshots.py before
git checkout HEAD -- && autoninja -C out/Default content_shell
python3 capture_screenshots.py 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")
FEATURE = "TableDefaultBorderColorCurrentColor"
VIEWPORT_WIDTH = 460
VIEWPORT_HEIGHT = 240
CASES = {
"default": [],
"disabled": ["--disable-blink-features=" + FEATURE],
}
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": "file://" + SAMPLER_FILE})
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.getElementById('readout').textContent"},
)["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 main():
label = sys.argv[1] if len(sys.argv) > 1 else "after"
for case, flags in CASES.items():
capture(label, case, flags)
write_diffs()
print("Done.")
if __name__ == "__main__":
sys.exit(main())