- Preserve unmasked whole-frame and raw geometry metrics; compare the visible log against each side’s measured composer position. - Cover offset, size mismatch and missing geometry in three tests.
456 lines
20 KiB
Python
456 lines
20 KiB
Python
#!/usr/bin/env python3
|
|
"""Compare TS6 desktop reference captures with native 1280x800 captures (Pillow)."""
|
|
|
|
import argparse
|
|
import json
|
|
import math
|
|
import re
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
try:
|
|
from PIL import Image, ImageChops
|
|
except ImportError as exc:
|
|
raise SystemExit("Desktop parity requires Python with Pillow installed.") from exc
|
|
|
|
|
|
VIEWPORT = (1280, 800)
|
|
CHANNEL_TOLERANCE = 16
|
|
RATIO_DENOMINATOR = 200 # 1/200 = 0.005, inclusive; gate on integer counts.
|
|
MAX_GEOMETRY_DELTA = 1
|
|
RECT_FIELDS = ("x", "y", "width", "height")
|
|
SHELL = (
|
|
"sidebar-brand", "window-caption", "sidebar-search", "sidebar-servers",
|
|
"sidebar-community", "sidebar-bookmarks", "sidebar-account", "sidebar-footer",
|
|
"tree-toolbar",
|
|
)
|
|
SERVER = ("tree", "tree-status", "detail-toolbar", "detail-header", "detail-pane")
|
|
CHAT = ("chat-log", "composer")
|
|
SETTINGS = ("settings-nav", "settings-panel")
|
|
CHANNEL_CHAT = {"view": "channel-chat", "channelId": 2, "chat": "full"}
|
|
SCENES = {
|
|
"main": (
|
|
{"screen": "main", "route": "#/connection8/channel2?mode=,Chat", "chat": "full"},
|
|
CHANNEL_CHAT,
|
|
SHELL + SERVER + CHAT,
|
|
),
|
|
"private": (
|
|
{
|
|
"screen": "view:client-Alex.Chat",
|
|
"route": "#/connection8/client2:cmVmZXJlbmNlLWNsaWVudC0y?mode=,Chat",
|
|
"target": "client-Alex",
|
|
"mode": "Chat",
|
|
},
|
|
{"view": "private-chat", "clientId": 2, "client": "Alex"},
|
|
SHELL + SERVER + CHAT,
|
|
),
|
|
"menu": (
|
|
{"screen": "menu", "target": "Alex"},
|
|
{**CHANNEL_CHAT, "menuTarget": "Alex"},
|
|
SHELL + SERVER + ("context-menu",),
|
|
),
|
|
"settings-audio": (
|
|
{
|
|
"screen": "settings:audio", "route": "#/settings?mode=SettingsAudio",
|
|
"category": "audio", "position": "top", "scrolledContainers": 0,
|
|
},
|
|
{"view": "settings", "category": "audio", "position": "top"},
|
|
SHELL + SETTINGS,
|
|
),
|
|
"settings-appearance": (
|
|
{
|
|
"screen": "settings:appearance", "route": "#/settings?mode=SettingsAppearance",
|
|
"category": "appearance", "position": "top", "scrolledContainers": 0,
|
|
},
|
|
{"view": "settings", "category": "appearance", "position": "top"},
|
|
SHELL + SETTINGS,
|
|
),
|
|
}
|
|
MASK_LUT = [255 if delta > CHANNEL_TOLERANCE else 0 for delta in range(256)]
|
|
|
|
|
|
class EvidenceError(ValueError):
|
|
"""Capture evidence is missing, invalid, or not comparable."""
|
|
|
|
|
|
def object_value(value, label):
|
|
if not isinstance(value, dict):
|
|
raise EvidenceError(f"{label}: expected a JSON object")
|
|
return value
|
|
|
|
|
|
def read_object(path):
|
|
def reject_constant(token):
|
|
raise EvidenceError(f"{path}: invalid JSON number {token!r}")
|
|
|
|
def finite_float(token):
|
|
value = float(token)
|
|
if not math.isfinite(value):
|
|
reject_constant(token)
|
|
return value
|
|
|
|
with path.open(encoding="utf-8-sig") as stream:
|
|
return object_value(json.load(stream, parse_float=finite_float, parse_constant=reject_constant), str(path))
|
|
|
|
|
|
def require_fields(value, expected, label):
|
|
value = object_value(value, label)
|
|
for key, required in expected.items():
|
|
actual = value.get(key)
|
|
if type(actual) is not type(required) or actual != required:
|
|
raise EvidenceError(f"{label}.{key}: expected {required!r}, got {actual!r}")
|
|
|
|
|
|
def read_official_scope(directory, theme, locale):
|
|
path = directory / "manifest-chat-full.json"
|
|
manifest = read_object(path)
|
|
require_fields(
|
|
manifest, {"kind": "official-ts6-runtime-reference", "referenceOnly": True}, str(path),
|
|
)
|
|
config = manifest.get("config")
|
|
require_fields(config, {
|
|
"theme": theme, "locale": locale, "width": VIEWPORT[0], "height": VIEWPORT[1],
|
|
"scenario": "connected", "chat": "full",
|
|
}, f"{path}: config")
|
|
return config
|
|
|
|
|
|
def rectangle(value, label):
|
|
value = object_value(value, label)
|
|
rect = []
|
|
for field in RECT_FIELDS:
|
|
number = value.get(field)
|
|
if type(number) not in (float, int) or not math.isfinite(number):
|
|
raise EvidenceError(f"{label}.{field}: expected a finite number")
|
|
rect.append(number)
|
|
x, y, width, height = rect
|
|
if width <= 0 or height <= 0 or not all(map(math.isfinite, (x + width, y + height))):
|
|
raise EvidenceError(f"{label}: invalid extent {rect!r}")
|
|
return dict(zip(RECT_FIELDS, rect))
|
|
|
|
|
|
def pixel_box(rect, label):
|
|
x, y, width, height = (rect[field] for field in RECT_FIELDS)
|
|
box = (
|
|
max(0, math.floor(x)), max(0, math.floor(y)),
|
|
min(VIEWPORT[0], math.ceil(x + width)), min(VIEWPORT[1], math.ceil(y + height)),
|
|
)
|
|
if box[0] >= box[2] or box[1] >= box[3]:
|
|
raise EvidenceError(f"{label}: no pixels inside the viewport")
|
|
return box
|
|
|
|
|
|
def read_official_scene(path, expected_opened, expected_regions, result):
|
|
meta = read_object(path)
|
|
result["officialOpened"] = meta.get("opened")
|
|
require_fields(meta, {"viewport": list(VIEWPORT)}, str(path))
|
|
require_fields(meta.get("opened"), expected_opened, f"{path}: opened")
|
|
regions = object_value(meta.get("regions"), f"{path}: regions")
|
|
missing = set(expected_regions) - regions.keys()
|
|
if missing:
|
|
raise EvidenceError(f"{path}: missing official regions: {', '.join(sorted(missing))}")
|
|
for name, region in regions.items():
|
|
if not re.fullmatch(r"[a-z][a-z0-9-]*", name):
|
|
raise EvidenceError(f"{path}: invalid region name {name!r}")
|
|
label = f"{path}: regions.{name}.rect"
|
|
region = object_value(region, f"{path}: regions.{name}")
|
|
rect = rectangle(region.get("rect"), label)
|
|
result["regions"][name] = {
|
|
"officialRect": rect, "pixelBox": pixel_box(rect, label),
|
|
"pixels": None, "geometry": {"verdict": "not-measured"},
|
|
}
|
|
|
|
|
|
def read_native_scene(path, scene, theme, locale, expected_state, result):
|
|
meta = read_object(path)
|
|
result["nativeStatus"] = meta.get("status")
|
|
result["nativeProductState"] = meta.get("productState")
|
|
result["declaredDifferences"] = meta.get("differences")
|
|
require_fields(meta, {
|
|
"schema": 1, "scene": scene, "theme": theme, "locale": locale, "viewport": list(VIEWPORT),
|
|
}, str(path))
|
|
if meta.get("status") != "rendered":
|
|
reason = meta.get("reason") or "no reason provided"
|
|
raise EvidenceError(f"{path}: capture status {meta.get('status')!r}: {reason}")
|
|
if meta.get("screenshot", path.with_suffix(".png").name) != path.with_suffix(".png").name:
|
|
raise EvidenceError(f"{path}: screenshot must be {path.with_suffix('.png').name}")
|
|
state = meta.get("productState")
|
|
require_fields(state, expected_state, f"{path}: productState")
|
|
if scene != "menu" and state.get("menuTarget") is not None:
|
|
raise EvidenceError(f"{path}: unexpected open context menu")
|
|
if not isinstance(meta.get("differences"), list):
|
|
raise EvidenceError(f"{path}: differences must be a JSON array")
|
|
return meta.get("regions", {})
|
|
|
|
|
|
def load_png(path, sizes, side):
|
|
with Image.open(path) as image:
|
|
sizes[side] = image.size
|
|
if image.format != "PNG" or getattr(image, "n_frames", 1) != 1:
|
|
raise EvidenceError(f"{path}: expected a single PNG frame")
|
|
if image.size != VIEWPORT:
|
|
raise EvidenceError(f"{path}: size {image.size} does not match viewport {VIEWPORT}")
|
|
if "A" in image.getbands() or "transparency" in image.info:
|
|
if image.convert("RGBA").getchannel("A").getextrema() != (255, 255):
|
|
raise EvidenceError(f"{path}: desktop capture must be opaque")
|
|
rgb = image.convert("RGB")
|
|
if all(lo == hi for lo, hi in rgb.getextrema()):
|
|
raise EvidenceError(f"{path}: solid-color frame is not a rendered scene")
|
|
return rgb
|
|
|
|
|
|
def measure(delta, maximum, over_tolerance):
|
|
histogram = maximum.histogram()
|
|
total = maximum.width * maximum.height
|
|
differing = sum(histogram[CHANNEL_TOLERANCE + 1:])
|
|
absolute = sum((level % 256) * count for level, count in enumerate(delta.histogram()))
|
|
return {
|
|
"counted": total,
|
|
"differentAtAnyDelta": total - histogram[0],
|
|
"differing": differing,
|
|
"ratio": differing / total,
|
|
"maxAbsoluteChannelDelta": maximum.getextrema()[1],
|
|
"meanAbsoluteChannelDelta": absolute / (3 * total),
|
|
"aboveToleranceBox": over_tolerance.getbbox(),
|
|
"verdict": "pass" if differing * RATIO_DENOMINATOR <= total else "fail",
|
|
}
|
|
|
|
|
|
def geometry(official, native, name):
|
|
if name not in native:
|
|
return {"verdict": "not-measured", "reason": "native layout rectangle not provided"}
|
|
rect = rectangle(native[name], f"native regions.{name}")
|
|
delta = {field: rect[field] - official[field] for field in RECT_FIELDS}
|
|
return {
|
|
"nativeRect": rect, "delta": delta,
|
|
"verdict": "pass" if all(abs(value) <= MAX_GEOMETRY_DELTA for value in delta.values()) else "fail",
|
|
}
|
|
|
|
|
|
def pixel_differences(official, native):
|
|
delta = ImageChops.difference(official, native)
|
|
red, green, blue = delta.split()
|
|
maximum = ImageChops.lighter(ImageChops.lighter(red, green), blue)
|
|
return delta, maximum, maximum.point(MASK_LUT)
|
|
|
|
|
|
def visible_chat_box(log, composer, side):
|
|
left, top, right, bottom = pixel_box(log, f"{side} chat-log")
|
|
composer_top = pixel_box(composer, f"{side} composer")[1]
|
|
bottom = min(bottom, composer_top)
|
|
if bottom <= top:
|
|
raise EvidenceError(f"{side} chat-log: no visible pixels above its composer")
|
|
return left, top, right, bottom
|
|
|
|
|
|
def compare_visible_chat_log(official, native, regions):
|
|
log, composer = (regions[name] for name in CHAT)
|
|
try:
|
|
official_box = visible_chat_box(log["officialRect"], composer["officialRect"], "official")
|
|
for name, region in zip(CHAT, (log, composer)):
|
|
entry = region["geometry"]
|
|
if "nativeRect" not in entry:
|
|
reason = entry.get("reason", "layout rectangle not provided")
|
|
raise EvidenceError(f"native {name}: {reason}")
|
|
native_box = visible_chat_box(log["geometry"]["nativeRect"],
|
|
composer["geometry"]["nativeRect"], "native")
|
|
except EvidenceError as exc:
|
|
return {"verdict": "not-measured", "reason": str(exc)}
|
|
|
|
ox, oy, oright, obottom = official_box
|
|
nx, ny, nright, nbottom = native_box
|
|
ow, oh = oright - ox, obottom - oy
|
|
nw, nh = nright - nx, nbottom - ny
|
|
width, height = min(ow, nw), min(oh, nh)
|
|
overlap = measure(*pixel_differences(
|
|
official.crop((ox, oy, ox + width, oy + height)),
|
|
native.crop((nx, ny, nx + width, ny + height)),
|
|
))
|
|
unpaired = ow * oh + nw * nh - 2 * overlap["counted"]
|
|
total = overlap["counted"] + unpaired
|
|
differing = overlap["differing"] + unpaired
|
|
return {
|
|
"officialPixelBox": official_box, "nativePixelBox": native_box,
|
|
"sizeDelta": {"width": nw - ow, "height": nh - oh},
|
|
"overlapPixels": overlap, "unpairedPixels": unpaired,
|
|
"counted": total, "differing": differing, "ratio": differing / total,
|
|
"verdict": "pass" if differing * RATIO_DENOMINATOR <= total else "fail",
|
|
}
|
|
|
|
|
|
def compare_images(official, native, out, directory, result, native_regions):
|
|
delta, maximum, over_tolerance = pixel_differences(official, native)
|
|
result["whole"] = measure(delta, maximum, over_tolerance)
|
|
directory.mkdir(parents=True)
|
|
|
|
def save(image, path):
|
|
image.save(path)
|
|
return path.relative_to(out).as_posix()
|
|
|
|
result["whole"]["absoluteDiff"] = save(delta, directory / "whole-absolute.png")
|
|
result["whole"]["thresholdMask"] = save(over_tolerance, directory / "whole-over-tolerance.png")
|
|
|
|
geometry_error = None
|
|
if not isinstance(native_regions, dict):
|
|
geometry_error = "native regions must be a JSON object"
|
|
result["errors"].append(geometry_error)
|
|
for name, region in result["regions"].items():
|
|
box = region["pixelBox"]
|
|
region_delta = delta.crop(box)
|
|
pixels = measure(region_delta, maximum.crop(box), over_tolerance.crop(box))
|
|
region["pixels"] = pixels
|
|
pixels["absoluteDiff"] = save(region_delta, directory / f"region-{name}-absolute.png")
|
|
if geometry_error is None:
|
|
try:
|
|
region["geometry"] = geometry(region["officialRect"], native_regions, name)
|
|
except (EvidenceError, OverflowError) as exc:
|
|
result["errors"].append(str(exc))
|
|
region["geometry"] = {"verdict": "invalid", "reason": str(exc)}
|
|
|
|
if all(name in result["regions"] for name in CHAT):
|
|
result["visibleChatLog"] = compare_visible_chat_log(official, native, result["regions"])
|
|
|
|
|
|
def compare_scene(official_dir, native_dir, out, theme, locale, scene, scope_error):
|
|
official_json = official_dir / f"{scene}.json"
|
|
native_json = native_dir / f"{scene}.json"
|
|
result = {
|
|
"scope": official_dir.name, "scene": scene, "theme": theme, "locale": locale,
|
|
"verdict": "blocked", "errors": [], "whole": None, "regions": {}, "imageSizes": {},
|
|
"pixelVerdict": "not-compared", "geometryVerdict": "not-measured",
|
|
}
|
|
if scope_error is not None:
|
|
result["errors"].append(scope_error)
|
|
expected_opened, expected_state, expected_regions = SCENES[scene]
|
|
if all(name in expected_regions for name in CHAT):
|
|
result["visibleChatLog"] = {"verdict": "not-measured", "reason": "capture evidence unavailable"}
|
|
try:
|
|
read_official_scene(official_json, expected_opened, expected_regions, result)
|
|
except (OSError, ValueError, OverflowError) as exc:
|
|
result["errors"].append(f"Official metadata: {exc}")
|
|
try:
|
|
native_regions = read_native_scene(native_json, scene, theme, locale, expected_state, result)
|
|
except (OSError, ValueError) as exc:
|
|
result["errors"].append(f"Native metadata: {exc}")
|
|
if result["errors"]:
|
|
return result
|
|
|
|
images = {}
|
|
for side, metadata in (("official", official_json), ("native", native_json)):
|
|
try:
|
|
images[side] = load_png(metadata.with_suffix(".png"), result["imageSizes"], side)
|
|
except (OSError, ValueError, Image.DecompressionBombError) as exc:
|
|
result["errors"].append(f"{side} PNG: {exc}")
|
|
if result["errors"]:
|
|
return result
|
|
try:
|
|
compare_images(images["official"], images["native"], out, out / official_dir.name / scene,
|
|
result, native_regions)
|
|
except (OSError, ValueError) as exc:
|
|
result["errors"].append(f"Comparison evidence: {exc}")
|
|
return result
|
|
|
|
regions = result["regions"].values()
|
|
pixel_failed = result["whole"]["verdict"] == "fail" or any(
|
|
region["pixels"]["verdict"] == "fail" for region in regions
|
|
)
|
|
result["pixelVerdict"] = "fail" if pixel_failed else "pass"
|
|
geometry_verdicts = {region["geometry"]["verdict"] for region in regions}
|
|
if "fail" in geometry_verdicts:
|
|
result["geometryVerdict"] = "fail"
|
|
elif geometry_verdicts == {"pass"}:
|
|
result["geometryVerdict"] = "pass"
|
|
elif "invalid" in geometry_verdicts or result["errors"]:
|
|
result["geometryVerdict"] = "invalid"
|
|
|
|
if pixel_failed or result["declaredDifferences"] or result["geometryVerdict"] == "fail":
|
|
result["verdict"] = "fail"
|
|
elif result["geometryVerdict"] == "pass" and not result["errors"]:
|
|
result["verdict"] = "pass"
|
|
return result
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--official", "--official-root", type=Path, required=True,
|
|
help="reference root containing the four scope directories and manifests")
|
|
parser.add_argument("--native", "--native-root", type=Path, required=True,
|
|
help="native root containing matching scope directories and scene JSON/PNG pairs")
|
|
parser.add_argument("--out", "--output", type=Path, required=True,
|
|
help="fresh evidence directory (must not exist)")
|
|
args = parser.parse_args()
|
|
try:
|
|
official, native, out = (root.resolve() for root in (args.official, args.native, args.out))
|
|
if official == native:
|
|
raise EvidenceError("Official and native capture roots must be distinct.")
|
|
if out in (official, native) or official in out.parents or native in out.parents:
|
|
raise EvidenceError("Evidence must be outside both capture roots.")
|
|
out.mkdir(parents=True, exist_ok=False)
|
|
except (OSError, ValueError, RuntimeError) as exc:
|
|
print(f"Desktop parity: {exc}", file=sys.stderr)
|
|
return 2
|
|
|
|
report = {
|
|
"schema": 1,
|
|
"kind": "native-desktop-parity",
|
|
"referenceTarget": "TeamSpeak 6.0.0.5232",
|
|
"officialRoot": str(official), "nativeRoot": str(native), "viewport": VIEWPORT,
|
|
"thresholds": {
|
|
"channelTolerance": CHANNEL_TOLERANCE, "maxDifferingRatio": 1 / RATIO_DENOMINATOR,
|
|
"maxGeometryDeltaPx": MAX_GEOMETRY_DELTA,
|
|
},
|
|
"method": {
|
|
"pixels": "Unmasked RGB bytes from opaque PNGs. A pixel differs if any channel delta exceeds 16.",
|
|
"crops": "Official measured rectangles only; floor top/left, ceil bottom/right, clip to viewport. "
|
|
"Both sides use identical coordinates, with no alignment or resizing. "
|
|
"Bounding boxes are left/top/right/bottom-exclusive; mismatch boxes are crop-local.",
|
|
"geometry": "Compare independently measured native x/y/width/height to official fractional "
|
|
"bounds, componentwise without rounding. Missing native measurements cannot pass. "
|
|
"Region crops alone do not measure native geometry or document regions absent "
|
|
"from the official JSON; the whole-frame gate still covers every pixel.",
|
|
"visibleChatLog": "Diagnostic only; does not affect the whole-frame, raw region, or scene verdicts. "
|
|
"Crop each measured chat-log independently; stop at its own bottom or the first "
|
|
"pixel row of its measured composer, whichever comes first. Compare from the "
|
|
"two crop origins without shifting or resizing; unpaired pixels count as differences.",
|
|
"state": "Scope and scene declarations are checked before comparing. Explicit roots are trusted "
|
|
"capture inputs; this does not independently authenticate the reference build or "
|
|
"test application behavior not captured in the images.",
|
|
"images": "Absolute differences retain the raw RGB deltas. Threshold masks are white where "
|
|
"any channel delta exceeds 16 and black elsewhere. No input screenshots are copied.",
|
|
},
|
|
"officialScopes": {}, "pairs": [],
|
|
}
|
|
for theme in ("dark", "light"):
|
|
for locale in ("en", "ru"):
|
|
scope = f"{theme}-{locale}-{VIEWPORT[0]}x{VIEWPORT[1]}"
|
|
official_dir, native_dir = official / scope, native / scope
|
|
scope_error = None
|
|
try:
|
|
report["officialScopes"][scope] = read_official_scope(official_dir, theme, locale)
|
|
except (OSError, ValueError) as exc:
|
|
scope_error = f"Official scope metadata: {exc}"
|
|
report["officialScopes"][scope] = {"error": scope_error}
|
|
for scene in SCENES:
|
|
report["pairs"].append(compare_scene(official_dir, native_dir, out, theme, locale,
|
|
scene, scope_error))
|
|
|
|
summary = {verdict: sum(pair["verdict"] == verdict for pair in report["pairs"])
|
|
for verdict in ("pass", "fail", "blocked")}
|
|
report["summary"] = summary
|
|
report["verdict"] = "pass" if summary["pass"] == len(report["pairs"]) else "fail"
|
|
report_path = out / "parity-report.json"
|
|
try:
|
|
with report_path.open("x", encoding="utf-8") as stream:
|
|
json.dump(report, stream, ensure_ascii=True, indent=2, allow_nan=False)
|
|
stream.write("\n")
|
|
except (OSError, ValueError) as exc:
|
|
print(f"Desktop parity: cannot write report: {exc}", file=sys.stderr)
|
|
return 2
|
|
print(f"Desktop parity: {summary['pass']} passed, {summary['fail']} failed, {summary['blocked']} blocked")
|
|
print(f"Evidence: {report_path}")
|
|
return 0 if report["verdict"] == "pass" else 1
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|