#!/usr/bin/env python3 """Pixel-diff the Rust demo screenshots against the C++ demo screenshots. Compares, per widget, the CROP of the widget rectangle in each 800x600 window shot — not the whole window (the backgrounds are identically white, so a whole-window diff would mostly measure rectangle-size differences). Two known, deliberate differences between the shots, documented in `xframe-demo`'s module docs: * geometry: the C++ mains use ad-hoc rects per widget (40,40,340,200 for most; 20,20,720,480 for dialogs/charts; 20,20,760,520 for indicators); the Rust demo uses the registry default size clamped to 720x520. When the rects differ in size the Rust crop is resized (LANCZOS) to the C++ crop size before diffing and the row is flagged `resized=1`. * label text: the C++ constructor's default text vs the Rust demo's registry `kind` label — the glyphs differ, the body does not. Metric: per-pixel luminance difference (ITU-R 601-2, same weights as the Rust runner's `Image::diff_count`); a pixel counts as different when its luminance differs by > 30. `match` is diff_pct < 5%. Usage: python3 tools/pixel_diff.py [--rust-shots DIR] [--cpp-shots DIR] [--registry data/registry.json] [--cpp-src /opt/lightgui] [--out OUT.csv] Defaults: --rust-shots screenshots --cpp-shots /opt/lightgui/widgets/screenshots --out test-results/pixel_diff.csv """ import argparse import csv import json import os import re import sys from PIL import Image, ImageChops RECT_RE = re.compile( r"widget\(display,\s*screen,\s*window,\s*gc,\s*&styles,\s*(-?\d+),\s*(-?\d+),\s*(\d+),\s*(\d+)" ) MATCH_THRESHOLD_PCT = 5.0 def diff_count(a, b): """Pixels whose luminance differs by > 30 (same as the Rust runner). PIL `convert("L")` uses the same ITU-R 601-2 weights as the runner, so this is the identical metric, computed in C instead of a Python per-pixel loop. """ assert a.size == b.size, f"size mismatch {a.size} vs {b.size}" diff = ImageChops.difference(a.convert("L"), b.convert("L")) hist = diff.histogram() return sum(hist[31:]) def nonwhite_pct(im): """Fraction of pixels with any channel < 250 (the layout CHECKDRAW metric).""" r, g, b = im.split() darkest = ImageChops.darker(ImageChops.darker(r, g), b) hist = darkest.histogram() total = im.size[0] * im.size[1] return 100.0 * sum(hist[:250]) / total def cpp_rect(cpp_src, name): """Widget rect from the C++ demo main; (40,40,340,200) fallback.""" main = os.path.join(cpp_src, "widgets", "components", name, f"main_{name}.cpp") try: with open(main) as f: m = RECT_RE.search(f.read()) if m: return tuple(int(v) for v in m.groups()), "main" except OSError: pass return (40, 40, 340, 200), "fallback" def load_shot(path): im = Image.open(path).convert("RGB") return im def main(): ap = argparse.ArgumentParser() ap.add_argument("--rust-shots", default="screenshots") ap.add_argument("--cpp-shots", default="/opt/lightgui/widgets/screenshots") ap.add_argument("--registry", default="data/registry.json") ap.add_argument("--cpp-src", default="/opt/lightgui") ap.add_argument("--out", default="test-results/pixel_diff.csv") args = ap.parse_args() with open(args.registry) as f: reg = json.load(f) widgets = reg["widgets"] rows = [] missing_rust = [] for w in widgets: name = w["name"] rust_path = os.path.join(args.rust_shots, name + ".png") if not os.path.exists(rust_path): rust_path = os.path.join(args.rust_shots, name + ".ppm") cpp_path = os.path.join(args.cpp_shots, name + ".png") if not os.path.exists(rust_path): missing_rust.append(name) continue if not os.path.exists(cpp_path): rows.append((name, "no-cpp-shot")) continue rust = load_shot(rust_path) cpp = load_shot(cpp_path) rx, ry, rw, rh = (40, 40, min(w["default_w"], 720), min(w["default_h"], 520)) (cx, cy, cw, ch), geo_src = cpp_rect(args.cpp_src, name) rust_crop = rust.crop((rx, ry, rx + rw, ry + rh)) cpp_crop = cpp.crop((cx, cy, cx + cw, cy + ch)) same_size = (rw, rh) == (cw, ch) resized = not same_size cmp_rust = rust_crop if resized: cmp_rust = rust_crop.resize((cw, ch), Image.LANCZOS) diff_px = diff_count(cmp_rust, cpp_crop) area = cw * ch diff_pct = 100.0 * diff_px / area nw_rust = nonwhite_pct(rust_crop) nw_cpp = nonwhite_pct(cpp_crop) match = diff_pct < MATCH_THRESHOLD_PCT if nw_rust < 0.5: reason = "blank-rust" elif nw_cpp < 0.5: reason = "blank-cpp" elif not match and not same_size: reason = "geometry+content" elif not match: reason = "content" else: reason = "" rows.append({ "name": name, "cpp_rect": f"{cx},{cy},{cw},{ch}", "rust_rect": f"{rx},{ry},{rw},{rh}", "geo_src": geo_src, "same_size": int(same_size), "resized": int(resized), "diff_px": diff_px, "diff_pct": round(diff_pct, 2), "match": int(match), "nonwhite_rust_pct": round(nw_rust, 2), "nonwhite_cpp_pct": round(nw_cpp, 2), "reason": reason, }) dict_rows = [r for r in rows if isinstance(r, dict)] os.makedirs(os.path.dirname(args.out) or ".", exist_ok=True) with open(args.out, "w", newline="") as f: wr = csv.DictWriter(f, fieldnames=list(dict_rows[0].keys())) wr.writeheader() wr.writerows(dict_rows) n = len(dict_rows) matched = sum(r["match"] for r in dict_rows) same = [r for r in dict_rows if r["same_size"]] same_matched = sum(r["match"] for r in same) print(f"widgets compared: {n} (missing rust shot: {len(missing_rust)})") print(f"MATCH (diff < {MATCH_THRESHOLD_PCT}%): {matched}/{n}") print(f"DIFFER: {n - matched}/{n}") print(f"same-size subset: {same_matched}/{len(same)} match (no resampling)") print(f"resized (geometry differs): {n - len(same)}/{n}") from collections import Counter print("differ reasons:", dict(Counter( r["reason"] for r in dict_rows if not r["match"]))) print("blank-rust widgets:", [r["name"] for r in dict_rows if r["reason"] == "blank-rust"]) print("blank-cpp widgets:", [r["name"] for r in dict_rows if r["reason"] == "blank-cpp"]) if missing_rust: print("missing rust shots:", missing_rust) print(f"csv: {args.out}") return 0 if __name__ == "__main__": sys.exit(main())