Compare commits
48
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c8842355fb | ||
|
|
e9c888d8e8 | ||
|
|
c7c7285557 | ||
|
|
da503f254a | ||
|
|
43a3197d89 | ||
|
|
ce79a51417 | ||
|
|
d9c21dd67b | ||
|
|
64f76b2d94 | ||
|
|
808c8f8c97 | ||
|
|
a42d863e48 | ||
|
|
f62bf3f6dc | ||
|
|
eadf95b90a | ||
|
|
b81f1561c5 | ||
|
|
61d2ee29d5 | ||
|
|
882c0f3a0e | ||
|
|
dde60415d7 | ||
|
|
be60e4d7e4 | ||
|
|
8c2dcbf570 | ||
|
|
4fddee2d46 | ||
|
|
87f48c9b8a | ||
|
|
7d702fb188 | ||
|
|
42cbc45da2 | ||
|
|
97faaa84f2 | ||
|
|
e5cb8934a2 | ||
|
|
16abec2c09 | ||
|
|
742281ec3a | ||
|
|
c5e89a85d2 | ||
|
|
a8da4b117f | ||
|
|
4ba1cefcdd | ||
|
|
3378b8f3e2 | ||
|
|
07a03e41e9 | ||
|
|
22a098843a | ||
|
|
e76c63a6cb | ||
|
|
caae1ea0aa | ||
|
|
acb073dda7 | ||
|
|
081b3a1aa0 | ||
|
|
9460e8eb86 | ||
|
|
3abd710393 | ||
|
|
80034c9c84 | ||
|
|
820d88e8eb | ||
|
|
558a402fa9 | ||
|
|
2b3cbe0795 | ||
|
|
3dd1424a0a | ||
|
|
5847dfe87a | ||
|
|
622b6e82a7 | ||
|
|
4355274838 | ||
|
|
97f8663ec6 | ||
|
|
ce68aea668 |
No files matched your search
@@ -0,0 +1,76 @@
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# counters.yml - the daily snapshot of the launch counter, and the README badges.
|
||||
#
|
||||
# GitHub keeps only the running total of a release asset's downloads, so the
|
||||
# launches of a day exist only if someone records the total every day. This is
|
||||
# that someone: no machine and no personal token, just the scheduler and the
|
||||
# built-in GITHUB_TOKEN. A run that fails sends GitHub's failure mail, and the
|
||||
# run's log warns when a day between two snapshots is missing.
|
||||
#
|
||||
# Everything it writes lives on the `badges` branch, which is not protected:
|
||||
# counters/history.csv date,key,value - every counter, once a day
|
||||
# counters/launches_daily.csv day_utc,launches - one row per measured day
|
||||
# docs/badges/launches.svg, docs/badges/stars.svg
|
||||
#
|
||||
# 00:10 UTC, so the snapshot dated D closes calendar day D-1.
|
||||
name: counters
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: "10 0 * * *"
|
||||
workflow_dispatch: {}
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
concurrency:
|
||||
group: counters
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
snapshot:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Check out the script (main)
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
path: main
|
||||
|
||||
- name: Check out the badges branch
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: badges
|
||||
path: badges
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.12"
|
||||
|
||||
- name: Self-test
|
||||
run: python main/scripts/launch_counters.py --selftest
|
||||
|
||||
- name: Record today's counters and redraw the badges
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
run: >
|
||||
python main/scripts/launch_counters.py
|
||||
--history badges/counters/history.csv
|
||||
--daily badges/counters/launches_daily.csv
|
||||
--badges badges/docs/badges
|
||||
|
||||
- name: Commit to the badges branch
|
||||
working-directory: badges
|
||||
run: |
|
||||
set -euo pipefail
|
||||
git config user.name "feder-cr"
|
||||
git config user.email "85809106+feder-cr@users.noreply.github.com"
|
||||
git add counters docs/badges
|
||||
if git diff --cached --quiet; then
|
||||
echo "nothing changed"
|
||||
exit 0
|
||||
fi
|
||||
total=$(awk -F, '$2=="launches_total"{v=$3} END{print v}' counters/history.csv)
|
||||
git commit -q -m "counters: $(date -u +%F), browser launches at ${total}"
|
||||
git push origin HEAD:badges
|
||||
@@ -50,6 +50,14 @@ concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
# Engine and GeoIP downloads go through the release API with this token.
|
||||
# Anonymous requests share a 60-an-hour limit per runner address and are the
|
||||
# ones GitHub drops first when it is degraded (2026-11-08: timeouts for
|
||||
# unauthenticated users failed the gates three times). user-install.yml stays
|
||||
# anonymous on purpose: it is the user's path.
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
|
||||
jobs:
|
||||
hunt:
|
||||
name: hunt (${{ inputs.os }})
|
||||
|
||||
@@ -47,6 +47,14 @@ concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
# Engine and GeoIP downloads go through the release API with this token.
|
||||
# Anonymous requests share a 60-an-hour limit per runner address and are the
|
||||
# ones GitHub drops first when it is degraded (2026-11-08: timeouts for
|
||||
# unauthenticated users failed the gates three times). user-install.yml stays
|
||||
# anonymous on purpose: it is the user's path.
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
|
||||
jobs:
|
||||
# The install below resolves `invisible-core==N.M.0` from the package index,
|
||||
# and the core is published BEFORE this package. This gate answers whether it
|
||||
|
||||
@@ -28,6 +28,14 @@ on:
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
# Engine and GeoIP downloads go through the release API with this token.
|
||||
# Anonymous requests share a 60-an-hour limit per runner address and are the
|
||||
# ones GitHub drops first when it is degraded (2026-11-08: timeouts for
|
||||
# unauthenticated users failed the gates three times). user-install.yml stays
|
||||
# anonymous on purpose: it is the user's path.
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
|
||||
jobs:
|
||||
# `pip install .` below resolves `invisible-core==N.M.0` from the package
|
||||
# index, and the core is published BEFORE this package. This gate answers
|
||||
|
||||
@@ -42,6 +42,14 @@ concurrency:
|
||||
group: publish
|
||||
cancel-in-progress: false
|
||||
|
||||
# Engine and GeoIP downloads go through the release API with this token.
|
||||
# Anonymous requests share a 60-an-hour limit per runner address and are the
|
||||
# ones GitHub drops first when it is degraded (2026-11-08: timeouts for
|
||||
# unauthenticated users failed the gates three times). user-install.yml stays
|
||||
# anonymous on purpose: it is the user's path.
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
|
||||
jobs:
|
||||
# Asked of the INDEX, first, because a tag can legitimately name a version that
|
||||
# is already published: a tag backfilled for a hand-published release, a tag
|
||||
|
||||
@@ -19,6 +19,14 @@ concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
# Engine and GeoIP downloads go through the release API with this token.
|
||||
# Anonymous requests share a 60-an-hour limit per runner address and are the
|
||||
# ones GitHub drops first when it is degraded (2026-11-08: timeouts for
|
||||
# unauthenticated users failed the gates three times). user-install.yml stays
|
||||
# anonymous on purpose: it is the user's path.
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
|
||||
jobs:
|
||||
# The gate was written FOR this repository on 2026-08-27, after 549 lines of
|
||||
# Italian shipped here in one subsystem and 852 more were found in 33 files
|
||||
|
||||
@@ -22,6 +22,14 @@ on:
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
# Engine and GeoIP downloads go through the release API with this token.
|
||||
# Anonymous requests share a 60-an-hour limit per runner address and are the
|
||||
# ones GitHub drops first when it is degraded (2026-11-08: timeouts for
|
||||
# unauthenticated users failed the gates three times). user-install.yml stays
|
||||
# anonymous on purpose: it is the user's path.
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
|
||||
jobs:
|
||||
# `pip install -e ".[dev]"` below resolves `invisible-core==N.M.0` from the
|
||||
# package index, and the core is published BEFORE this package. This gate
|
||||
|
||||
@@ -6,6 +6,61 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [0.47.1] - 2026-11-08
|
||||
|
||||
### Changed
|
||||
- invisible-core 58.56.0, which this version pins. A persona has the keyboards
|
||||
Windows installs with its language and country, read from Windows'
|
||||
locale.nls (English US besides Persian, Azerbaijani, Bashkir, Cherokee and
|
||||
Sakha; Russian besides Belarusian, Tatar and Armenian; Hindi Traditional for
|
||||
Hindi), and switches as a user does: left Alt + Shift to the next language,
|
||||
Ctrl + Shift to the next keyboard of the same language. The keyboard pref
|
||||
carries Windows' own form (LANGID:KLID joined by semicolons).
|
||||
|
||||
## [0.47.0] - 2026-11-08
|
||||
|
||||
### Changed
|
||||
- Engine firefox-58 (Firefox 159.0), through invisible-core 58.55.0, which
|
||||
this version pins.
|
||||
- A persona has the keyboards Windows installs with its language: the
|
||||
language's, and the second one (English US with Russian, Greek, Arabic,
|
||||
Hebrew and most languages not written in Latin letters). A character the
|
||||
active keyboard lacks is typed on the other one, after left Alt + left
|
||||
Shift, Windows' default switch; `press("x")` on a Russian or Greek session
|
||||
no longer raises "unknown key". Only a character no keyboard has is inserted
|
||||
as text.
|
||||
- `scroll_into_view_if_needed()` is the engine's own scroll, only when needed.
|
||||
|
||||
### Fixed
|
||||
- In the engine: a navigation Firefox refuses before any channel (a
|
||||
restricted port) ends with its error instead of never; a request held by
|
||||
`route()` that the page cancels is no longer held; `unroute` with a request
|
||||
that can no longer be resumed no longer fails; a session cookie set with
|
||||
`expires: -1` is kept, `sameSite: "None"` is SameSite=None, and a cookie
|
||||
Firefox refuses fails `add_cookies()` with Firefox's reason.
|
||||
|
||||
## [0.46.4] - 2026-11-08
|
||||
|
||||
### Fixed
|
||||
- The engine and the GeoIP database install when GitHub's direct release
|
||||
links fail. Through invisible-core 57.54.0, which this version pins: each
|
||||
release file is fetched from the API route first and from the direct link
|
||||
second, and one download attempt tries both, so a 504 on one route is
|
||||
served by the other at once. On 2026-11-08 every direct link answered 504
|
||||
while the API route served the same files.
|
||||
|
||||
## [0.46.3] - 2026-11-08
|
||||
|
||||
### Changed
|
||||
- Engine firefox-57 (Firefox 159.0), through invisible-core 57.53.0, which
|
||||
this version pins. The WebGL extensions a page sees are decided once, by
|
||||
the engine's WebGL host, from the persona's declared list: the content
|
||||
process no longer has a list of its own, an extension the host's GPU
|
||||
cannot serve is never created (its calls stay harmless), and
|
||||
`getSupportedExtensions()` lists them in Firefox's own order, the only
|
||||
order a retail Firefox gives (the WebGL 1 list had `EXT_sRGB` before
|
||||
`EXT_shader_texture_lod`).
|
||||
|
||||
## [0.46.2] - 2026-11-07
|
||||
|
||||
### Changed
|
||||
|
||||
+2018
File diff suppressed because it is too large.
Load diff
+2
-2
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
||||
|
||||
[project]
|
||||
name = "invisible_playwright"
|
||||
version = "0.46.2"
|
||||
version = "0.47.1"
|
||||
description = "Playwright wrapper for a patched Firefox with deterministic stealth profile."
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.11"
|
||||
@@ -69,7 +69,7 @@ dependencies = [
|
||||
# metadata; nothing in src/ hardcodes a second copy (tests/test_core_pin.py
|
||||
# fails if one appears). What stays invisible to install-time machinery is the
|
||||
# --no-deps / lockfile residue, and _pin.py is the only layer that sees it.
|
||||
"invisible_core==56.53.0",
|
||||
"invisible_core==58.56.0",
|
||||
# ⛔ playwright is NO LONGER a dependency: since the full fork, the Python
|
||||
# client lives in src/invisible_playwright/_pw/ and its server in
|
||||
# src/invisible_playwright/_juggler/ (no Node driver). Reintroducing it would not visibly
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
"""Builds tests/data/canvas_icc_ref/refs.json, the reference of the canvas ICC readback test.
|
||||
|
||||
One measurement of retail Firefox 159.0 on Windows with the default prefs (the run
|
||||
``a_win_default``: qcms converts a tagged image to the monitor profile, here the stock
|
||||
"sRGB Color Space Profile.icm"), and one control run on the same machine with
|
||||
gfx.color_management.force_srgb=true (``b_win_force_srgb``: the bytes without that
|
||||
conversion), both made by index.html and the images of gen_images.py:
|
||||
|
||||
python -I scripts/build_canvas_icc_refs.py <a_win_default.json> <b_win_force_srgb.json> \
|
||||
--repeat <a2_win_default_repeat.json> --host-profile <host_display_profile.json> \
|
||||
--source <name of the capture> [--out tests/data/canvas_icc_ref/refs.json]
|
||||
|
||||
The script stops if the repeat run has other hashes than the reference run, if the runs
|
||||
were not made on the same Firefox build, or if the prefs of the two runs are not the default
|
||||
and force_srgb=true. The probes are the 72 of the page: for each of the 10 images drawImage,
|
||||
drawImage at 32 px, createImageBitmap with the default colour space conversion and with
|
||||
``none``; the 22 fill colours; the canvas colorSpace probe; the 9 environment values.
|
||||
|
||||
Standard library only: it does not import invisible_core, and the repository holds no PNG
|
||||
and no run's pixel hex, only hashes and sizes.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
DEFAULT_OUT = Path(__file__).resolve().parents[1] / "tests" / "data" / "canvas_icc_ref" / "refs.json"
|
||||
IMAGE_PROBES = ("drawImage", "drawImage_scaled32", "bitmap_default", "bitmap_none")
|
||||
#: Value probes that are not colour management: the host's theme, which the retail machine
|
||||
#: had dark; the test does not compare it (the persona's colour scheme is checked elsewhere).
|
||||
NOT_COMPARED = ("env | prefers-color-scheme:dark",)
|
||||
|
||||
|
||||
GEN_IMAGES = DEFAULT_OUT.parent / "gen_images.py"
|
||||
|
||||
|
||||
def image_files():
|
||||
"""{image id: {file, bytes, sha256}} of the ten images gen_images.py writes: the reference
|
||||
names them, so a generator that drifts is seen before the engine is blamed."""
|
||||
spec = importlib.util.spec_from_file_location("gen_images", GEN_IMAGES)
|
||||
mod = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(mod)
|
||||
imgs, _profiles = mod.build_images()
|
||||
return {iid: {"file": "images/%s.%s" % (iid, ext), "bytes": len(data),
|
||||
"sha256": hashlib.sha256(data).hexdigest()}
|
||||
for iid, ext, data, _what in imgs}
|
||||
|
||||
|
||||
class RefError(ValueError):
|
||||
"""The runs cannot be one reference."""
|
||||
|
||||
|
||||
def env_sha256(value):
|
||||
"""The hash of an environment value: SHA-256 of its compact JSON (as JSON.stringify)."""
|
||||
return hashlib.sha256(json.dumps(value, separators=(",", ":")).encode()).hexdigest()
|
||||
|
||||
|
||||
def probes(R):
|
||||
"""{probe name: {kind, sha256, bytes (pixel probes), value (env)}} of a page result R
|
||||
(``window.R`` of index.html). ``bytes`` is the RGBA length: 4 x width x height."""
|
||||
out = {}
|
||||
for iid, v in R["images"].items():
|
||||
for k in IMAGE_PROBES:
|
||||
e = v.get(k)
|
||||
if not isinstance(e, dict) or "sha256" not in e:
|
||||
raise RefError("image %s probe %s has no hash: %r" % (iid, k, e))
|
||||
size = 32 if k == "drawImage_scaled32" else 16
|
||||
out["%s | %s" % (iid, k)] = {"kind": "image", "sha256": e["sha256"],
|
||||
"bytes": 4 * size * size}
|
||||
for f, v in R["fills"].items():
|
||||
if "sha256" not in v:
|
||||
raise RefError("fill %s has no hash: %r" % (f, v))
|
||||
out["fill | " + f] = {"kind": "fill", "sha256": v["sha256"], "bytes": 4 * 16 * 16}
|
||||
p3 = R["canvas_colorspace"].get("p3_fill_p3_canvas") or {}
|
||||
if "sha256" not in p3:
|
||||
raise RefError("the canvas colorSpace probe has no hash")
|
||||
out["canvas colorSpace p3 fill"] = {"kind": "colorspace", "sha256": p3["sha256"],
|
||||
"bytes": 4 * 16 * 16}
|
||||
for k, v in R["env"].items():
|
||||
out["env | " + k] = {"kind": "env", "sha256": env_sha256(v), "value": v}
|
||||
return out
|
||||
|
||||
|
||||
def build(a, b, repeat, host_profile, source):
|
||||
"""The reference from the default run ``a``, the control run ``b`` (force_srgb), the
|
||||
repeat of ``a`` and the host profile description; all as loaded JSON."""
|
||||
for key in ("buildid", "exe_sha256", "version", "os"):
|
||||
if a["firefox"][key] != b["firefox"][key] or a["firefox"][key] != repeat["firefox"][key]:
|
||||
raise RefError("the runs differ in the Firefox %s" % key)
|
||||
pa, pb, pr = probes(a["R"]), probes(b["R"]), probes(repeat["R"])
|
||||
if pa != pr:
|
||||
bad = sorted(k for k in pa if pa[k] != pr.get(k))
|
||||
raise RefError("the repeat run differs from the reference run on %d probes: %s"
|
||||
% (len(bad), ", ".join(bad[:5])))
|
||||
if set(pa) != set(pb):
|
||||
raise RefError("the control run has other probes than the reference run")
|
||||
prefs_a, prefs_b = a["prefs_read_back"], b["prefs_read_back"]
|
||||
if prefs_a.get("gfx.color_management.display_profile") not in ("", None):
|
||||
raise RefError("the reference run has a display_profile pref: it must read the host's")
|
||||
if prefs_a.get("gfx.color_management.force_srgb") is not False:
|
||||
raise RefError("the reference run is not made with the default force_srgb (false)")
|
||||
if prefs_b.get("gfx.color_management.force_srgb") is not True:
|
||||
raise RefError("the control run is not made with force_srgb=true")
|
||||
for k, v in prefs_a.items():
|
||||
if k != "gfx.color_management.force_srgb" and prefs_b.get(k) != v:
|
||||
raise RefError("the control run differs in %s" % k)
|
||||
|
||||
out = {}
|
||||
dependent = []
|
||||
for name, p in pa.items():
|
||||
e = dict(p)
|
||||
if pb[name]["sha256"] != p["sha256"]:
|
||||
e["without_conversion_sha256"] = pb[name]["sha256"]
|
||||
dependent.append(name)
|
||||
if name in NOT_COMPARED:
|
||||
e["compared"] = False
|
||||
out[name] = e
|
||||
return {
|
||||
"test_page": "index.html",
|
||||
"image_generator": "gen_images.py",
|
||||
"source": {
|
||||
"capture": source,
|
||||
"reference_run": "runs/a_win_default.json",
|
||||
"repeat_run": "runs/a2_win_default_repeat.json (same hashes on all probes)",
|
||||
"control_run": "runs/b_win_force_srgb.json (gfx.color_management.force_srgb=true)",
|
||||
"date": "2026-11-09",
|
||||
},
|
||||
"firefox": {**a["firefox"], "prefs": prefs_a},
|
||||
"display_profile": {"file": host_profile["file"], "size": host_profile["size"],
|
||||
"sha256": host_profile["sha256"], "api": "GetICMProfileW"},
|
||||
"images": image_files(),
|
||||
"probe_count": len(out),
|
||||
"profile_dependent_count": len(dependent),
|
||||
"profile_dependent": sorted(dependent),
|
||||
"probes": out,
|
||||
}
|
||||
|
||||
|
||||
def main(argv):
|
||||
ap = argparse.ArgumentParser(description=__doc__,
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("reference", help="run json of the retail default run (a_win_default)")
|
||||
ap.add_argument("control", help="run json of the force_srgb run (b_win_force_srgb)")
|
||||
ap.add_argument("--repeat", required=True, help="run json of the repeat of the default run")
|
||||
ap.add_argument("--host-profile", required=True, help="host_display_profile.json")
|
||||
ap.add_argument("--source", default="canvas-color/canvas-color-icc-readback",
|
||||
help="name of the capture the runs come from")
|
||||
ap.add_argument("--out", default=str(DEFAULT_OUT))
|
||||
a = ap.parse_args(argv[1:])
|
||||
|
||||
def load(p):
|
||||
return json.loads(Path(p).read_text(encoding="utf-8"))
|
||||
|
||||
try:
|
||||
refs = build(load(a.reference), load(a.control), load(a.repeat),
|
||||
load(a.host_profile), a.source)
|
||||
except RefError as e:
|
||||
print("error: %s" % e, file=sys.stderr)
|
||||
return 1
|
||||
Path(a.out).write_text(json.dumps(refs, ensure_ascii=False, indent=1) + "\n",
|
||||
encoding="utf-8")
|
||||
print("%d probes (%d depend on the display profile) -> %s"
|
||||
% (refs["probe_count"], refs["profile_dependent_count"], a.out))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv))
|
||||
@@ -0,0 +1,106 @@
|
||||
"""Builds tests/data/canvas_text_ref/refs.json, the one reference of the canvas text test.
|
||||
|
||||
Two measurements of retail Firefox 159.0 on Windows, made with the same page code, the same
|
||||
bundled font files and the same machine, are merged by case id:
|
||||
|
||||
python -I scripts/build_canvas_text_refs.py <canvas_ref_bundle/refs.json> \
|
||||
<canvas_ref_ext/refs.json> [--out tests/data/canvas_text_ref/refs.json]
|
||||
|
||||
The bundle file has the base cases (no ``gruppo`` field: they become group ``0_base``), the
|
||||
extension file has the cases of the other groups. A case id that is in both files is kept
|
||||
once, with the extension's group; the script stops if the two hashes of such a case differ,
|
||||
or if the two files were not measured on the same Firefox build, with the same ClearType
|
||||
state and the same font files. Fields that name a file of the measuring machine (the PNG
|
||||
paths) are dropped: the repository holds no PNG and no font.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
BASE_GROUP = "0_base"
|
||||
DEFAULT_OUT = Path(__file__).resolve().parents[1] / "tests" / "data" / "canvas_text_ref" / "refs.json"
|
||||
_DROP = ("png",)
|
||||
|
||||
|
||||
class MergeError(ValueError):
|
||||
"""The two measurements cannot be one reference."""
|
||||
|
||||
|
||||
def _case(case, group):
|
||||
out = {k: v for k, v in case.items() if k not in _DROP}
|
||||
out.setdefault("alpha", True)
|
||||
out.setdefault("stretch", "normal")
|
||||
out.setdefault("text", "TEXT")
|
||||
out["gruppo"] = group
|
||||
return out
|
||||
|
||||
|
||||
def merge(bundle, ext):
|
||||
"""One reference from the bundle measurement and the extension measurement."""
|
||||
for key in ("firefox", "canvas", "cleartype", "text"):
|
||||
if bundle[key] != ext[key]:
|
||||
raise MergeError("the two measurements differ in %r: %r vs %r"
|
||||
% (key, bundle[key], ext[key]))
|
||||
ext_fonts = {f["bundle_file"]: f for f in ext["fonts"]}
|
||||
for f in bundle["fonts"]:
|
||||
other = ext_fonts.get(f["bundle_file"])
|
||||
if other is None or other["sha256"] != f["sha256"]:
|
||||
raise MergeError("font %s is not the same file in the two measurements"
|
||||
% f["bundle_file"])
|
||||
|
||||
cases = {}
|
||||
for cid, c in bundle["cases"].items():
|
||||
cases[cid] = _case(c, c.get("gruppo") or BASE_GROUP)
|
||||
for cid, c in ext["cases"].items():
|
||||
if not c.get("gruppo"):
|
||||
raise MergeError("extension case %r has no group" % cid)
|
||||
if cid in cases and cases[cid]["sha256"] != c["sha256"]:
|
||||
raise MergeError("case %r has two different hashes: %s and %s"
|
||||
% (cid, cases[cid]["sha256"], c["sha256"]))
|
||||
cases[cid] = _case(c, c["gruppo"])
|
||||
|
||||
groups = {}
|
||||
for c in cases.values():
|
||||
groups[c["gruppo"]] = groups.get(c["gruppo"], 0) + 1
|
||||
status = {**bundle.get("font_load_status", {}), **ext.get("font_load_status", {})}
|
||||
return {
|
||||
"test_page": "index.html",
|
||||
"font_source": "bundle",
|
||||
"text": bundle["text"],
|
||||
"firefox": bundle["firefox"],
|
||||
"canvas": bundle["canvas"],
|
||||
"cleartype": bundle["cleartype"],
|
||||
"fonts": ext["fonts"],
|
||||
"font_load_status": status,
|
||||
"case_count": len(cases),
|
||||
"groups": dict(sorted(groups.items())),
|
||||
"cases": cases,
|
||||
}
|
||||
|
||||
|
||||
def main(argv):
|
||||
ap = argparse.ArgumentParser(description=__doc__,
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("bundle", help="refs.json of the base measurement (canvas_ref_bundle)")
|
||||
ap.add_argument("ext", help="refs.json of the extension measurement (canvas_ref_ext)")
|
||||
ap.add_argument("--out", default=str(DEFAULT_OUT))
|
||||
a = ap.parse_args(argv[1:])
|
||||
load = lambda p: json.loads(Path(p).read_text(encoding="utf-8"))
|
||||
try:
|
||||
refs = merge(load(a.bundle), load(a.ext))
|
||||
except MergeError as e:
|
||||
print("error: %s" % e, file=sys.stderr)
|
||||
return 1
|
||||
Path(a.out).write_text(json.dumps(refs, ensure_ascii=False, indent=1) + "\n",
|
||||
encoding="utf-8")
|
||||
print("%d cases -> %s" % (refs["case_count"], a.out))
|
||||
for g, n in refs["groups"].items():
|
||||
print(" %-30s %3d" % (g, n))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv))
|
||||
+18
-1
@@ -400,7 +400,11 @@ def dump(firefox: str, leg: str, out: Path, reference: Path, timeout_ms: int = 1
|
||||
for seed in SEEDS:
|
||||
with InvisiblePlaywright(**visit_options(firefox, seed, dpr, zone)) as browser:
|
||||
page = browser.new_context().new_page()
|
||||
page.goto("http://127.0.0.1:%d/?dpr%s" % (server.server_address[1], dpr))
|
||||
# The same budget as the wait below: a cold Windows runner took
|
||||
# more than goto's default 30 s to reach `load` on the first
|
||||
# visit (candidate 42410156024), and passed locally 6/6.
|
||||
page.goto("http://127.0.0.1:%d/?dpr%s" % (server.server_address[1], dpr),
|
||||
timeout=timeout_ms)
|
||||
page.wait_for_function("document.title === 'done'", timeout=timeout_ms)
|
||||
result = page.evaluate("window.__hostGate")
|
||||
if result.get("format") == FORMAT:
|
||||
@@ -541,6 +545,19 @@ def compare(dumps: Path, reference: Path, exceptions: dict, notes: list | None =
|
||||
if leg != base and value != values[base] and not excused(key, leg):
|
||||
failures.append("host %s dpr %s seed %d: %s differs from %s: %s"
|
||||
% (key, dpr, seed, leg, base, describe(value, values[base])))
|
||||
# 1b. host-independence among the legs of one OS (two Linux
|
||||
# distributions): a known defect excuses a difference from Windows,
|
||||
# never one between two machines of the same system, whose libraries
|
||||
# (FreeType, fontconfig, Mesa) are the host's and must not show.
|
||||
for seed in SEEDS:
|
||||
for family in sorted({l.split("-")[0] for l in legs}):
|
||||
same_os = [l for l in legs if l.split("-")[0] == family and (l, dpr, seed) in visits]
|
||||
for leg in same_os[1:]:
|
||||
value = visits[(leg, dpr, seed)].get(key, "<missing>")
|
||||
first = visits[(same_os[0], dpr, seed)].get(key, "<missing>")
|
||||
if value != first and not matching(excusable, key):
|
||||
failures.append("host %s dpr %s seed %d: %s differs from %s (same OS): %s"
|
||||
% (key, dpr, seed, leg, same_os[0], describe(value, first)))
|
||||
# 2. retail equality, for a value that is the same for every seed
|
||||
if key.startswith(pending[dpr]):
|
||||
continue
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
"""Which canvas text cases two runs draw differently.
|
||||
|
||||
tests/test_canvas_text_is_windows_e2e.py writes canvas_text_<tag>.json (case id -> SHA-256
|
||||
of the RGBA bytes) into INVISIBLE_CANVAS_TEXT_OUT. Run it on Debian 12 and on Ubuntu 24.04
|
||||
(and the retail reference, tests/data/canvas_text_ref/refs.json, is accepted too), then:
|
||||
|
||||
python scripts/compare_canvas_text_runs.py debian.json ubuntu.json
|
||||
|
||||
The exit status is 0 when every case is equal on both sides and both draw the same set.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sys
|
||||
|
||||
|
||||
def load(path):
|
||||
"""case id -> sha256, from a run file or from refs.json."""
|
||||
data = json.loads(open(path, encoding="utf-8").read())
|
||||
if "cases" in data:
|
||||
return {k: v["sha256"] for k, v in data["cases"].items()}
|
||||
return data
|
||||
|
||||
|
||||
def compare(a, b):
|
||||
"""(only in a, only in b, ids whose hash differs)."""
|
||||
only_a = sorted(set(a) - set(b))
|
||||
only_b = sorted(set(b) - set(a))
|
||||
differ = sorted(k for k in set(a) & set(b) if a[k] != b[k])
|
||||
return only_a, only_b, differ
|
||||
|
||||
|
||||
def main(argv):
|
||||
if len(argv) != 3:
|
||||
print(__doc__)
|
||||
return 2
|
||||
a, b = load(argv[1]), load(argv[2])
|
||||
only_a, only_b, differ = compare(a, b)
|
||||
for label, ids in (("only in %s" % argv[1], only_a), ("only in %s" % argv[2], only_b),
|
||||
("differ", differ)):
|
||||
if ids:
|
||||
print("%s (%d):" % (label, len(ids)))
|
||||
for k in ids:
|
||||
print(" " + k)
|
||||
print("%d cases compared, %d differ" % (len(set(a) & set(b)), len(differ)))
|
||||
return 1 if (only_a or only_b or differ) else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv))
|
||||
@@ -26,9 +26,12 @@
|
||||
"why": "retail was measured on a hidden desktop, where its window never has focus"}
|
||||
],
|
||||
"known_defects": [
|
||||
{"keys": ["text.*", "blend.*"],
|
||||
"why": "phase 4: text from idwr (DWrite 26100) on every OS; today Windows asks the host's DWrite and Linux FreeType"},
|
||||
{"keys": ["control.webgl1", "control.webgl2"], "legs": ["linux-x86_64"],
|
||||
{"keys": ["blend.*", "text.canvas.*", "text.char.*", "text.emoji.*", "text.fallback.*",
|
||||
"text.pixelscan.*", "text.svg.*", "text.metrics.*.width", "text.metrics.*.actualBoundingBoxLeft",
|
||||
"text.metrics.*.actualBoundingBoxRight", "text.fallbackwidth.*.serif",
|
||||
"text.fallbackwidth.*.monospace"],
|
||||
"why": "phase 4: text from idwr (DWrite 26100) on every OS; today Windows asks the host's DWrite and Linux FreeType. Only the rasterised glyphs, their advances and ink extents and the serif/monospace fallback widths differ (firefox-59 dumps): text.adjust, text.fonts, text.rect, text.units and the vertical metrics are held"},
|
||||
{"keys": ["control.webgl1", "control.webgl2"], "legs": ["linux-x86_64", "linux-x86_64-debian12"],
|
||||
"why": "WebGL draws through the host's driver (llvmpipe here, ANGLE on Windows); a host-independent rasterizer is its own project"}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Daily snapshot of the public counters, and the two README badges drawn from it.
|
||||
|
||||
python scripts/launch_counters.py --history H.csv --daily D.csv --badges DIR
|
||||
python scripts/launch_counters.py --selftest
|
||||
|
||||
Run once a day by .github/workflows/counters.yml, which keeps the files on the
|
||||
unprotected `badges` branch. Nothing here needs a person or a machine of ours:
|
||||
every input is a public GitHub API answer and every output is a file on that
|
||||
branch.
|
||||
|
||||
WHAT A LAUNCH IS. Every browser process the engine starts makes one GET to a
|
||||
fixed release asset (platform/launch-counter in the engine series), and GitHub
|
||||
counts the fetches as that asset's `download_count`. GitHub keeps only the
|
||||
running total, never a history, which is why this snapshot exists: a day's
|
||||
launches are the difference between two consecutive daily totals, and a day
|
||||
nobody recorded is lost for good.
|
||||
|
||||
THE TOTAL IS A SUM, and its terms are fixed history:
|
||||
* LAUNCHES_BASELINE_V3 is everything counted before the counter moved to the
|
||||
two live assets below; those earlier assets no longer exist.
|
||||
* usage_counter_v3 is the wrapper repo's asset, counted from zero. Engines
|
||||
whose core does not declare the address ping it.
|
||||
* usage_counter_v4 is the engine repo's asset above the value it already held
|
||||
when it came back into use (USAGE_COUNTER_RESUMED_AT). Current cores point
|
||||
every session at it.
|
||||
The two populations are disjoint, so the launches are the sum.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
import datetime as dt
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import urllib.request
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
ENGINE_REPO = "feder-cr/firefox_antidetect_patch"
|
||||
WRAPPER_REPO = "feder-cr/invisible_playwright"
|
||||
COUNTER_TAG = "usage-counter"
|
||||
|
||||
LAUNCHES_BASELINE_V3 = 2_084_136
|
||||
USAGE_COUNTER_RESUMED_AT = 1_162_840
|
||||
|
||||
Api = Callable[[str], object]
|
||||
|
||||
|
||||
def github_api(token: str | None) -> Api:
|
||||
def get(path: str):
|
||||
req = urllib.request.Request("https://api.github.com" + path)
|
||||
req.add_header("Accept", "application/vnd.github+json")
|
||||
if token:
|
||||
req.add_header("Authorization", "Bearer " + token)
|
||||
with urllib.request.urlopen(req, timeout=60) as r:
|
||||
return json.load(r)
|
||||
return get
|
||||
|
||||
|
||||
def _releases(api: Api, repo: str) -> list[dict]:
|
||||
out: list[dict] = []
|
||||
page = 1
|
||||
while True:
|
||||
batch = api(f"/repos/{repo}/releases?per_page=100&page={page}")
|
||||
if not batch:
|
||||
return out
|
||||
out.extend(batch)
|
||||
page += 1
|
||||
|
||||
|
||||
def _counter(api: Api, repo: str) -> int:
|
||||
rel = api(f"/repos/{repo}/releases/tags/{COUNTER_TAG}")
|
||||
return sum(a["download_count"] for a in rel["assets"])
|
||||
|
||||
|
||||
def launches_total(usage_counter: int, usage_counter_v3: int) -> int:
|
||||
return (LAUNCHES_BASELINE_V3 + usage_counter_v3
|
||||
+ max(0, usage_counter - USAGE_COUNTER_RESUMED_AT))
|
||||
|
||||
|
||||
def collect(api: Api) -> dict[str, int]:
|
||||
"""Every key the history has always carried, read fresh."""
|
||||
out: dict[str, int] = {}
|
||||
binaries = 0
|
||||
for r in _releases(api, ENGINE_REPO):
|
||||
tag = r["tag_name"]
|
||||
if tag == COUNTER_TAG:
|
||||
continue
|
||||
n = sum(a["download_count"] for a in r["assets"]
|
||||
if a["name"].endswith((".zip", ".tar.gz")))
|
||||
if n or tag.startswith("firefox-"):
|
||||
out[tag] = n
|
||||
binaries += n
|
||||
out["total_binaries"] = binaries
|
||||
out["usage_counter"] = _counter(api, ENGINE_REPO)
|
||||
out["usage_counter_v3"] = _counter(api, WRAPPER_REPO)
|
||||
out["usage_counter_v4"] = max(0, out["usage_counter"] - USAGE_COUNTER_RESUMED_AT)
|
||||
out["launches_total"] = launches_total(out["usage_counter"], out["usage_counter_v3"])
|
||||
out["stars"] = api(f"/repos/{WRAPPER_REPO}")["stargazers_count"]
|
||||
return out
|
||||
|
||||
|
||||
# ── history ─────────────────────────────────────────────────────────────────
|
||||
|
||||
def read_history(path: Path) -> dict[str, dict[str, int]]:
|
||||
out: dict[str, dict[str, int]] = {}
|
||||
if path.exists():
|
||||
with path.open(encoding="utf-8", newline="") as f:
|
||||
for row in csv.DictReader(f):
|
||||
out.setdefault(row["date"], {})[row["key"]] = int(float(row["value"]))
|
||||
return out
|
||||
|
||||
|
||||
def append_snapshot(path: Path, day: str, data: dict[str, int]) -> list[str]:
|
||||
"""Append today's rows. Idempotent per (date, key): a rerun the same day
|
||||
writes only keys that are not there yet, and never a second value."""
|
||||
seen = set(read_history(path).get(day, {}))
|
||||
fresh = {k: v for k, v in data.items() if k not in seen}
|
||||
if not fresh:
|
||||
return []
|
||||
new = not path.exists()
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with path.open("a", encoding="utf-8", newline="") as f:
|
||||
w = csv.writer(f, lineterminator="\n")
|
||||
if new:
|
||||
w.writerow(["date", "key", "value"])
|
||||
ff = sorted((k for k in fresh if re.fullmatch(r"firefox-\d+", k)),
|
||||
key=lambda k: int(k.split("-")[1]))
|
||||
rest = sorted(k for k in fresh if k not in ff)
|
||||
for k in ff + rest:
|
||||
w.writerow([day, k, fresh[k]])
|
||||
return list(fresh)
|
||||
|
||||
|
||||
def launches_per_day(history: dict[str, dict[str, int]]) -> list[tuple[str, int]]:
|
||||
"""(day counted, launches) for each pair of snapshots ONE day apart.
|
||||
|
||||
The snapshot dated D is taken just after midnight UTC, so the difference
|
||||
from D-1 is the launches of calendar day D-1. A gap between snapshots is
|
||||
not a day and is never spread over the missing days.
|
||||
"""
|
||||
dates = sorted(d for d in history if "launches_total" in history[d])
|
||||
out = []
|
||||
for a, b in zip(dates, dates[1:]):
|
||||
if (dt.date.fromisoformat(b) - dt.date.fromisoformat(a)).days != 1:
|
||||
continue
|
||||
delta = history[b]["launches_total"] - history[a]["launches_total"]
|
||||
if delta > 0:
|
||||
out.append((a, delta))
|
||||
return out
|
||||
|
||||
|
||||
def write_daily(path: Path, history: dict[str, dict[str, int]]) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with path.open("w", encoding="utf-8", newline="") as f:
|
||||
w = csv.writer(f, lineterminator="\n")
|
||||
w.writerow(["day_utc", "launches"])
|
||||
w.writerows(launches_per_day(history))
|
||||
|
||||
|
||||
# ── badges ──────────────────────────────────────────────────────────────────
|
||||
|
||||
VALUE_PAD = 6
|
||||
COLOUR_LABEL = "#555"
|
||||
CHAR_W = {".": 4.0, "M": 10.0, "k": 6.0} # Verdana 11px advances
|
||||
DIGIT_W = 7.0
|
||||
SAFE_VALUE = re.compile(r"^[0-9]+(\.[0-9]+)?[kM]?$")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Badge:
|
||||
label: str
|
||||
label_box: int # measured from the committed SVG
|
||||
colour: str
|
||||
file_name: str
|
||||
key: str
|
||||
|
||||
|
||||
BADGES = [
|
||||
Badge("browser launches", 116, "#007ec6", "launches.svg", "launches_total"),
|
||||
Badge("Stars", 43, "#e8a317", "stars.svg", "stars"),
|
||||
]
|
||||
|
||||
|
||||
def format_count(n: int) -> str:
|
||||
"""Two decimals, TRUNCATED: an adoption figure is never rounded up."""
|
||||
if n < 1000:
|
||||
return str(n)
|
||||
scaled, suffix = (n / 1000, "k") if n < 1_000_000 else (n / 1_000_000, "M")
|
||||
text = f"{int(scaled * 100) / 100:.2f}".rstrip("0").rstrip(".")
|
||||
return text + suffix
|
||||
|
||||
|
||||
def render(value: str, badge: Badge) -> bytes:
|
||||
if not SAFE_VALUE.match(value):
|
||||
raise ValueError(f"refusing to draw an unexpected value: {value!r}")
|
||||
box = int(sum(CHAR_W.get(c, DIGIT_W) for c in value) + VALUE_PAD)
|
||||
total = badge.label_box + box
|
||||
lx, vx = badge.label_box / 2, badge.label_box + box / 2
|
||||
aria = f"{badge.label}: {value}"
|
||||
lines = [
|
||||
f'<svg xmlns="http://www.w3.org/2000/svg" width="{total}" height="20"'
|
||||
f' role="img" aria-label="{aria}">',
|
||||
f"<title>{aria}</title>",
|
||||
'<linearGradient id="s" x2="0" y2="100%"><stop offset="0"'
|
||||
' stop-color="#bbb" stop-opacity=".1"/><stop offset="1"'
|
||||
' stop-opacity=".1"/></linearGradient>',
|
||||
f'<clipPath id="r"><rect width="{total}" height="20" rx="3"'
|
||||
' fill="#fff"/></clipPath>',
|
||||
'<g clip-path="url(#r)">',
|
||||
f'<rect width="{badge.label_box}" height="20" fill="{COLOUR_LABEL}"/>',
|
||||
f'<rect x="{badge.label_box}" width="{box}" height="20"'
|
||||
f' fill="{badge.colour}"/>',
|
||||
f'<rect width="{total}" height="20" fill="url(#s)"/>',
|
||||
"</g>",
|
||||
'<g fill="#fff" text-anchor="middle"'
|
||||
' font-family="Verdana,Geneva,DejaVu Sans,sans-serif" font-size="11">',
|
||||
f'<text x="{lx:.1f}" y="15" fill="#010101" fill-opacity=".3">{badge.label}</text>',
|
||||
f'<text x="{lx:.1f}" y="14">{badge.label}</text>',
|
||||
f'<text x="{vx:.1f}" y="15" fill="#010101" fill-opacity=".3">{value}</text>',
|
||||
f'<text x="{vx:.1f}" y="14">{value}</text>',
|
||||
"</g>",
|
||||
"</svg>",
|
||||
]
|
||||
return "\n".join(lines).encode("utf-8")
|
||||
|
||||
|
||||
def write_badges(directory: Path, history: dict[str, dict[str, int]]) -> None:
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
for b in BADGES:
|
||||
days = [d for d in history if b.key in history[d]]
|
||||
if not days:
|
||||
raise SystemExit(f"no {b.key} in the history")
|
||||
(directory / b.file_name).write_bytes(
|
||||
render(format_count(history[max(days)][b.key]), b))
|
||||
|
||||
|
||||
# ── entry point ─────────────────────────────────────────────────────────────
|
||||
|
||||
def run(api: Api, history: Path, daily: Path, badges: Path, today: dt.date) -> int:
|
||||
day = today.isoformat()
|
||||
before = read_history(history)
|
||||
written = append_snapshot(history, day, collect(api))
|
||||
after = read_history(history)
|
||||
write_daily(daily, after)
|
||||
write_badges(badges, after)
|
||||
print(f"[counters] {day}: wrote {len(written)} keys, "
|
||||
f"launches_total={after[day]['launches_total']}")
|
||||
previous = sorted(d for d in before if d < day)
|
||||
if previous and (today - dt.date.fromisoformat(previous[-1])).days > 1:
|
||||
# Recorded anyway, but a hole is a lost measurement: say it in the run.
|
||||
print(f"::warning::no snapshot between {previous[-1]} and {day}: "
|
||||
f"those days cannot be split")
|
||||
return 0
|
||||
|
||||
|
||||
def selftest() -> int:
|
||||
import tempfile
|
||||
fails = []
|
||||
# The row of 2026-11-04 as recorded: the sum must give its total back.
|
||||
if launches_total(2_758_110, 937_317) != 4_616_723:
|
||||
fails.append("sum")
|
||||
if format_count(4_616_723) != "4.61M" or format_count(2554) != "2.55k":
|
||||
fails.append("format")
|
||||
hist = {"2026-11-01": {"launches_total": 100}, "2026-11-02": {"launches_total": 160},
|
||||
"2026-11-04": {"launches_total": 300}}
|
||||
if launches_per_day(hist) != [("2026-11-01", 60)]:
|
||||
fails.append("gap")
|
||||
with tempfile.TemporaryDirectory() as t:
|
||||
p = Path(t) / "h.csv"
|
||||
append_snapshot(p, "2026-11-08", {"stars": 1})
|
||||
if append_snapshot(p, "2026-11-08", {"stars": 2}) or read_history(p)["2026-11-08"]["stars"] != 1:
|
||||
fails.append("idempotent")
|
||||
print("selftest:", "OK" if not fails else "FAIL " + ", ".join(fails))
|
||||
return 1 if fails else 0
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--selftest", action="store_true")
|
||||
ap.add_argument("--history", type=Path)
|
||||
ap.add_argument("--daily", type=Path)
|
||||
ap.add_argument("--badges", type=Path)
|
||||
a = ap.parse_args()
|
||||
if a.selftest:
|
||||
return selftest()
|
||||
if not (a.history and a.daily and a.badges):
|
||||
ap.error("--history, --daily and --badges are required")
|
||||
api = github_api(os.environ.get("GITHUB_TOKEN"))
|
||||
return run(api, a.history, a.daily, a.badges, dt.datetime.now(dt.timezone.utc).date())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,47 @@
|
||||
import socket,json,subprocess,time,os,sys,base64
|
||||
base=os.getcwd(); prof=base+'/prof'; os.makedirs(prof,exist_ok=True)
|
||||
exe=base+'/ex3/core/firefox.exe'
|
||||
open(prof+'/user.js','w').write('user_pref("marionette.port",2828);user_pref("browser.shell.checkDefaultBrowser",false);user_pref("datareporting.policy.dataSubmissionEnabled",false);user_pref("app.update.auto",false);user_pref("app.update.enabled",false);\n')
|
||||
p=subprocess.Popen([exe,'-headless','-marionette','-remote-allow-system-access','-no-remote','-profile',prof,'about:blank'],env=dict(os.environ,MOZ_REMOTE_ALLOW_SYSTEM_ACCESS='1'),stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
|
||||
try:
|
||||
s=None
|
||||
for i in range(60):
|
||||
try:
|
||||
s=socket.create_connection(('127.0.0.1',2828),timeout=5);break
|
||||
except Exception: time.sleep(1)
|
||||
f=s.makefile('rwb',buffering=0)
|
||||
def rd():
|
||||
n=b''
|
||||
while True:
|
||||
c=s.recv(1)
|
||||
if c==b':':break
|
||||
n+=c
|
||||
n=int(n);d=b''
|
||||
while len(d)<n: d+=s.recv(n-len(d))
|
||||
return json.loads(d)
|
||||
mid=[0]
|
||||
def cmd(name,params=None):
|
||||
mid[0]+=1
|
||||
m=json.dumps([0,mid[0],name,params or {}]).encode()
|
||||
s.sendall(str(len(m)).encode()+b':'+m)
|
||||
while True:
|
||||
r=rd()
|
||||
if r[0]==1 and r[1]==mid[0]: return r[2] if r[2] else r[3]
|
||||
s.settimeout(60)
|
||||
rd()
|
||||
cmd('WebDriver:NewSession',{'capabilities':{}})
|
||||
h=cmd('WebDriver:GetWindowHandles'); cmd('WebDriver:SwitchToWindow',{'handle':h[0]})
|
||||
cmd('WebDriver:Navigate',{'url':'data:text/html,<body><p id=p>text</p>'})
|
||||
js="""
|
||||
const fonts=['menu','caption','icon','message-box','small-caption','status-bar','system-ui'];
|
||||
const colors=['Canvas','CanvasText','LinkText','VisitedText','ActiveText','ButtonFace','ButtonText','ButtonBorder','Field','FieldText','GrayText','Highlight','HighlightText','Mark','MarkText','SelectedItem','SelectedItemText','AccentColor','AccentColorText','ActiveBorder','ActiveCaption','AppWorkspace','Background','ButtonHighlight','ButtonShadow','CaptionText','InactiveBorder','InactiveCaption','InactiveCaptionText','InfoBackground','InfoText','Menu','MenuText','Scrollbar','ThreeDDarkShadow','ThreeDFace','ThreeDHighlight','ThreeDLightShadow','ThreeDShadow','Window','WindowFrame','WindowText'];
|
||||
const o={fonts:{},light:{},dark:{},selection:{}};
|
||||
for(const f of fonts){const d=document.createElement('div');d.style.font=f==='system-ui'?'16px system-ui':f;document.body.appendChild(d);const c=getComputedStyle(d);o.fonts[f]={family:c.fontFamily,size:c.fontSize,weight:c.fontWeight,style:c.fontStyle,stretch:c.fontStretch};d.remove();}
|
||||
for(const sch of ['light','dark']){for(const k of colors){const d=document.createElement('div');d.style.colorScheme=sch;d.style.color=k;d.style.backgroundColor=k;document.body.appendChild(d);o[sch][k]=getComputedStyle(d).color;d.remove();}
|
||||
const d=document.createElement('div');d.style.colorScheme=sch;d.textContent='x';document.body.appendChild(d);const c=getComputedStyle(d,'::selection');o.selection[sch]={color:c.color,bg:c.backgroundColor};d.remove();}
|
||||
return o;"""
|
||||
r=cmd('WebDriver:ExecuteScript',{'script':js,'args':[]})
|
||||
json.dump(r['value'] if 'value' in r else r,open(base+'/retail_theme.json','w'),indent=1)
|
||||
print(json.dumps(r)[:1500])
|
||||
finally:
|
||||
subprocess.run(['taskkill','/F','/T','/PID',str(p.pid)],capture_output=True)
|
||||
@@ -0,0 +1,218 @@
|
||||
"""The expected values of tests/test_css_calc_is_windows_e2e.py.
|
||||
|
||||
Run it with `python -I`. Two steps, because a number is only worth testing if
|
||||
the two C libraries give a different page-visible text for it:
|
||||
|
||||
python -I scripts/ucrt_css_calc.py dump OUT # on Windows: ucrtbase.dll's f32 functions
|
||||
python -I scripts/ucrt_css_calc.py dump OUT # on Linux: the host's libm
|
||||
python -I scripts/ucrt_css_calc.py pick WIN LINUX tests/data/ucrt_css_calc.txt
|
||||
|
||||
`dump` computes, for a fixed grid of inputs, what the style engine (Servo's
|
||||
calc.rs) makes of ``calc(1px * sin(x))`` and the others, and the text it then
|
||||
serializes. The style engine does every step in f32 (CSSFloat): the library
|
||||
function is the f32 one (sinf, cosf, tanf, asinf, acosf, atanf, atan2f, expf,
|
||||
logf, powf), an angle is converted to degrees with one f32 multiplication, and
|
||||
a number is written by cssparser's dtoa_short: the shortest decimal that
|
||||
reads back as that f32, rounded half up to 6 significant digits. So two
|
||||
libraries whose results differ in the last f32 bit only show on the page when
|
||||
that bit moves the 6th digit - which `pick` looks for.
|
||||
|
||||
`pick` keeps every input whose text differs between the two dumps, and a few
|
||||
that do not (the control: the same text from both libraries), in the format
|
||||
the test reads:
|
||||
|
||||
<fn> <args...> <text on Windows>
|
||||
|
||||
The reference is ucrtbase's FMA3 code path, the one every Windows 11 CPU runs
|
||||
(the same one idwr_math reproduces); the SSE2 fallback of older CPUs can differ in
|
||||
the last bit and is not what a page on Windows 11 reads.
|
||||
|
||||
Inputs are exact in f32 (multiples of a power of two), so the page and this
|
||||
script read the same number whatever the CSS parser does with decimals.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import ctypes
|
||||
import math
|
||||
import struct
|
||||
import sys
|
||||
from decimal import ROUND_HALF_UP, Decimal
|
||||
from pathlib import Path
|
||||
|
||||
#: Rust's f32::to_degrees multiplier, as an f32.
|
||||
RAD_TO_DEG = struct.unpack("<f", struct.pack("<f", 57.2957795130823208767981548141051703))[0]
|
||||
|
||||
#: How many differing inputs of each function `pick` keeps, and how many of the
|
||||
#: ones that agree.
|
||||
KEEP_DIFFERENT = 6
|
||||
KEEP_SAME = 3
|
||||
|
||||
|
||||
def f32(x: float) -> float:
|
||||
return struct.unpack("<f", struct.pack("<f", x))[0]
|
||||
|
||||
|
||||
def load_libm():
|
||||
if sys.platform == "win32":
|
||||
lib = ctypes.CDLL("ucrtbase.dll")
|
||||
else:
|
||||
lib = ctypes.CDLL("libm.so.6")
|
||||
funcs = {}
|
||||
for name, nargs in (("sinf", 1), ("cosf", 1), ("tanf", 1), ("asinf", 1), ("acosf", 1),
|
||||
("atanf", 1), ("atan2f", 2), ("expf", 1), ("logf", 1), ("powf", 2)):
|
||||
fn = getattr(lib, name)
|
||||
fn.restype = ctypes.c_float
|
||||
fn.argtypes = [ctypes.c_float] * nargs
|
||||
funcs[name] = fn
|
||||
return funcs
|
||||
|
||||
|
||||
def shortest_f32(x: float) -> str:
|
||||
"""The shortest decimal text that reads back as this f32."""
|
||||
for digits in range(1, 10):
|
||||
text = "%.*e" % (digits - 1, x)
|
||||
if f32(float(text)) == x:
|
||||
return text
|
||||
return "%.8e" % x
|
||||
|
||||
|
||||
def serialize(x: float) -> str:
|
||||
"""cssparser's number text for an f32: 6 significant digits, half up,
|
||||
no trailing zeros, no exponent in the range the grid stays in."""
|
||||
if x == 0:
|
||||
return "0"
|
||||
d = Decimal(shortest_f32(x))
|
||||
exp = d.adjusted()
|
||||
q = d.quantize(Decimal(1).scaleb(exp - 5), rounding=ROUND_HALF_UP)
|
||||
text = format(q.normalize(), "f")
|
||||
return "0" if text in ("-0", "") else text
|
||||
|
||||
|
||||
def decimal(k: int, shift: int) -> str:
|
||||
"""k / 2**shift as an exact decimal text."""
|
||||
d = Decimal(k) / Decimal(2 ** shift)
|
||||
return format(d.normalize(), "f")
|
||||
|
||||
|
||||
def grid():
|
||||
"""(fn, args as texts) for every case of the dump."""
|
||||
out = []
|
||||
for fn, lim, shift in (("sin", 16, 10), ("cos", 16, 10), ("tan", 16, 10)):
|
||||
for k in range(-lim << shift, (lim << shift) + 1):
|
||||
out.append((fn, [decimal(k, shift)]))
|
||||
# Finer, over the stretch where the functions bend the most.
|
||||
for k in range(-(4 << 13), (4 << 13) + 1):
|
||||
out.append(("tan", [decimal(k, 13)]))
|
||||
for k in range(-(8 << 12), (8 << 12) + 1):
|
||||
out.append(("atan", [decimal(k, 12)]))
|
||||
for k in range(-(4 << 12), (4 << 12) + 1):
|
||||
out.append(("exp", [decimal(k, 12)]))
|
||||
for k in range(1, 32 * 1024 + 1):
|
||||
out.append(("log", [decimal(k, 10)]))
|
||||
for a in range(-128, 129):
|
||||
for b in range(-128, 129):
|
||||
if a or b:
|
||||
out.append(("atan2", [decimal(a, 6), decimal(b, 6)]))
|
||||
for k in range(-4096, 4097):
|
||||
out.append(("asin", [decimal(k, 12)]))
|
||||
out.append(("acos", [decimal(k, 12)]))
|
||||
for k in range(-8 * 512, 8 * 512 + 1):
|
||||
out.append(("atan", [decimal(k, 9)]))
|
||||
for a in range(-64, 65):
|
||||
for b in range(-64, 65):
|
||||
if a or b:
|
||||
out.append(("atan2", [decimal(a, 4), decimal(b, 4)]))
|
||||
for k in range(-10 * 256, 10 * 256 + 1):
|
||||
out.append(("exp", [decimal(k, 8)]))
|
||||
for k in range(1, 64 * 64 + 1):
|
||||
out.append(("log", [decimal(k, 6)]))
|
||||
for a in range(2, 513):
|
||||
for b in (2, 3, 5, 7, 10):
|
||||
out.append(("log", [decimal(a, 3), str(b)]))
|
||||
for a in range(-32, 33):
|
||||
for b in range(-32, 33):
|
||||
out.append(("hypot", [decimal(a * 3, 4), decimal(b * 5, 4)]))
|
||||
for a in range(4, 257):
|
||||
for b in range(-64, 65):
|
||||
out.append(("pow", [decimal(a, 4), decimal(b, 4)]))
|
||||
return out
|
||||
|
||||
|
||||
def evaluate(lib, fn, args):
|
||||
"""(text, unit) the page shows, from f32 steps."""
|
||||
v = [f32(float(a)) for a in args]
|
||||
if fn in ("sin", "cos", "tan", "exp"):
|
||||
return serialize(f32(lib[fn + "f"](v[0]))), "px"
|
||||
if fn == "log":
|
||||
if len(v) == 1:
|
||||
return serialize(f32(lib["logf"](v[0]))), "px"
|
||||
return serialize(f32(f32(lib["logf"](v[0])) / f32(lib["logf"](v[1])))), "px"
|
||||
if fn == "hypot":
|
||||
# powi(2) is a product, the sum is f32, sqrt is exact in IEEE: no library
|
||||
# function here, so no difference between the two - the control.
|
||||
return serialize(f32(math.sqrt(f32(f32(v[0] * v[0]) + f32(v[1] * v[1]))))), "px"
|
||||
if fn == "pow":
|
||||
return serialize(f32(lib["powf"](v[0], v[1]))), "px"
|
||||
if fn in ("asin", "acos", "atan"):
|
||||
return serialize(f32(f32(lib[fn + "f"](v[0])) * RAD_TO_DEG)), "deg"
|
||||
if fn == "atan2":
|
||||
return serialize(f32(f32(lib["atan2f"](v[0], v[1])) * RAD_TO_DEG)), "deg"
|
||||
raise ValueError(fn)
|
||||
|
||||
|
||||
def dump(out: Path) -> None:
|
||||
lib = load_libm()
|
||||
lines = []
|
||||
for fn, args in grid():
|
||||
text, unit = evaluate(lib, fn, args)
|
||||
if text in ("nan", "inf", "-inf") or "e" in text.lower():
|
||||
continue
|
||||
lines.append("%s %s %s%s" % (fn, " ".join(args), text, unit))
|
||||
out.write_text("\n".join(lines) + "\n")
|
||||
print("wrote %s: %d cases (%s)" % (out, len(lines), sys.platform))
|
||||
|
||||
|
||||
def read(path: Path) -> dict:
|
||||
cases = {}
|
||||
for line in path.read_text().splitlines():
|
||||
parts = line.split()
|
||||
cases[tuple(parts[:-1])] = parts[-1]
|
||||
return cases
|
||||
|
||||
|
||||
def pick(win: Path, linux: Path, out: Path) -> None:
|
||||
a, b = read(win), read(linux)
|
||||
chosen = ["# Expected text of getComputedStyle for calc(1px * f(args)) (word-spacing)",
|
||||
"# and of rotate: f(args) for the angle functions, from ucrtbase.dll's f32",
|
||||
"# functions. Generated by scripts/ucrt_css_calc.py (python -I) - do not edit.",
|
||||
"# <fn> <args...> <text on Windows>"]
|
||||
stats = []
|
||||
for fn in ("sin", "cos", "tan", "asin", "acos", "atan", "atan2", "exp", "log", "pow", "hypot"):
|
||||
keys = sorted(k for k in a if k[0] == fn and k in b)
|
||||
different = [k for k in keys if a[k] != b[k]]
|
||||
same = [k for k in keys if a[k] == b[k]]
|
||||
# Spread over the list, not the first ones.
|
||||
step_d = max(1, len(different) // KEEP_DIFFERENT)
|
||||
quarter = max(1, len(same) // 4)
|
||||
take = different[::step_d][:KEEP_DIFFERENT] + same[quarter::quarter][:KEEP_SAME]
|
||||
stats.append("%s: %d of %d differ" % (fn, len(different), len(keys)))
|
||||
for k in take:
|
||||
chosen.append("%s %s" % (" ".join(k), a[k]))
|
||||
out.write_text("\n".join(chosen) + "\n")
|
||||
print("\n".join(stats))
|
||||
print("wrote %s" % out)
|
||||
|
||||
|
||||
def main(argv) -> int:
|
||||
if len(argv) == 3 and argv[1] == "dump":
|
||||
dump(Path(argv[2]))
|
||||
elif len(argv) == 5 and argv[1] == "pick":
|
||||
pick(Path(argv[2]), Path(argv[3]), Path(argv[4]))
|
||||
else:
|
||||
print(__doc__)
|
||||
return 2
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv))
|
||||
@@ -46,7 +46,8 @@ from .dispatcher import (Dispatcher, ExpectNotMet, ProtocolException,
|
||||
from invisible_core.juggler.injected import (ContextDestroyed, EvaluationError,
|
||||
InjectedScript, js_truthy)
|
||||
from invisible_core.juggler.keyboard import MODIFIER_MASK
|
||||
from invisible_core.juggler.keyboard import layout_for as keyboard_layout_for
|
||||
from invisible_core.juggler.keyboard import layouts_for as keyboard_layouts_for
|
||||
from invisible_core.juggler.keyboard import profiles_pref
|
||||
from invisible_core.juggler.lifecycle import Lifecycle
|
||||
|
||||
# ⛔ RE-EXPORTED ON PURPOSE, not merely imported. These leaf helpers moved out
|
||||
@@ -217,10 +218,11 @@ SESSION_SEED_PREF = "invisible.server.session_seed"
|
||||
#: a cap of its own would be a second answer to a question the caller answered,
|
||||
#: and would show up as a drag that ignores a budget every click obeys.
|
||||
MOTION_BUDGET_PREF = "invisible.server.motion_budget_ms"
|
||||
#: The persona's keyboard (a Windows KLID), decided by the core from the
|
||||
#: session's language AND country (`keyboard.layout_for`). Server-only, like
|
||||
#: The persona's keyboards, as Windows writes its input profiles (LANGID:KLID
|
||||
#: joined by semicolons, the language's first), decided by the core from the
|
||||
#: session's language AND country (`keyboard.profiles_for`). Server-only, like
|
||||
#: the seed: taken out of the prefs before the profile is written.
|
||||
KEYBOARD_LAYOUT_PREF = "invisible.server.keyboard_layout"
|
||||
from invisible_core.juggler.keyboard import KEYBOARD_LAYOUT_PREF # noqa: E402
|
||||
|
||||
|
||||
def take_session_motion(prefs: Dict) -> tuple:
|
||||
@@ -666,34 +668,17 @@ class ElementHandleDispatcher(Dispatcher):
|
||||
{"objectId": self.object_id}))}
|
||||
|
||||
def op_scroll_into_view(self, params: Dict) -> Any:
|
||||
"""Bring the element into view, through the injected script.
|
||||
"""Bring the element into view, through the core's
|
||||
`InjectedScript.scroll_into_view`, the one the click path uses too.
|
||||
|
||||
⛔ IT USED TO SEND `Page.scrollIntoViewIfNeeded`, AND THAT COMMAND CAN
|
||||
NEVER SUCCEED. [B184]: the engine's handler calls
|
||||
`unsafeObject.scrollRectIntoViewIfNeeded`, and that method is not
|
||||
declared in ANY binding of `Element` in the tree - not a `.webidl`, not
|
||||
a `.idl`, not `Bindings.conf` - so it is `undefined` for every caller
|
||||
and the `else` branch always throws. Measured on the shipped binary at
|
||||
four positions, including an element ALREADY IN VIEW: timeout every
|
||||
time, while `bounding_box()` on the same element answered correctly.
|
||||
|
||||
⛔ AND THE REMEDY WAS ALREADY IN THIS FILE'S REACH, which is the part
|
||||
worth knowing. `Actions` scrolls before every click through
|
||||
`InjectedScript.scroll_into_view` - native `scrollIntoView` reached from
|
||||
the utility world, `block: "center"` - and has done since a click below
|
||||
the fold was found to miss. So the click path scrolled correctly while
|
||||
the public method sent a command that cannot work. One concept, two
|
||||
implementations, and the broken one was the one users call.
|
||||
|
||||
Reusing that helper rather than writing a second one is the whole fix:
|
||||
no new abstraction, and the two paths cannot drift.
|
||||
|
||||
⛔ `rect` IS NOT HONOURED, and saying so is better than pretending.
|
||||
Playwright can ask to scroll a sub-rectangle of the element; the helper
|
||||
scrolls the element. No caller in this package passes it, and a partial
|
||||
answer that looks total is worse than a named limit.
|
||||
The core sends the engine's `Page.scrollIntoViewIfNeeded` (firefox-58):
|
||||
the page's own `scrollIntoView` through the Xray, only when the element
|
||||
is not in full view, centred. Until firefox-58 that command failed on
|
||||
every node [B184] and the core scrolled with a script in the page.
|
||||
A `rect` in the call is handed on; the public method sends none.
|
||||
"""
|
||||
self.injected.scroll_into_view(self.frame.frame_id, self.object_id)
|
||||
self.injected.scroll_into_view(self.frame.frame_id, self.object_id,
|
||||
params.get("rect"))
|
||||
return None
|
||||
|
||||
def op_owner_frame(self, params: Dict) -> Any:
|
||||
@@ -4137,8 +4122,8 @@ class BrowserDispatcher(Dispatcher):
|
||||
service_workers_enabled: bool = True,
|
||||
layout: str = "us") -> None:
|
||||
self.conn = conn
|
||||
#: The keyboard the persona types on, from the session's language
|
||||
#: (`keyboard.layout_for` on `intl.accept_languages`): one keyboard per
|
||||
#: The keyboards the persona types on, from the session's language
|
||||
#: (`keyboard.profiles_for`, LANGID:KLID joined by semicolons): one set per
|
||||
#: session, whatever a context later says its language is.
|
||||
self.layout = layout
|
||||
#: ⛔ WHETHER `route()` CAN WORK AT ALL. Firefox asks a channel's
|
||||
@@ -5038,8 +5023,8 @@ class BrowserTypeDispatcher(Dispatcher):
|
||||
params.get("firefoxUserPrefs") or {})
|
||||
# The keyboard the session decided, out of the prefs before the
|
||||
# profile sees them; without it, the language alone decides.
|
||||
keyboard_layout = prefs.pop(KEYBOARD_LAYOUT_PREF, None) or \
|
||||
keyboard_layout_for(prefs.get("intl.accept_languages") or "")
|
||||
keyboard_layout = prefs.pop(KEYBOARD_LAYOUT_PREF, None) or profiles_pref(
|
||||
prefs.get("intl.accept_languages") or "")
|
||||
write_user_js(profile, prefs)
|
||||
# ⛔ THE CALLER'S TIMEOUT, not ours. `launch(timeout=)` is a
|
||||
# documented option and this server ignored it, so a caller who
|
||||
|
||||
@@ -26,7 +26,7 @@ from ._cursor import (ENGINE_BINARY,
|
||||
enable_for as _enable_cursor_engine,
|
||||
max_seconds_for as _cursor_max_seconds)
|
||||
from ._engine import resolve_executable
|
||||
from ._juggler.server import KEYBOARD_LAYOUT_PREF, MOTION_BUDGET_PREF, SESSION_SEED_PREF
|
||||
from ._juggler.server import MOTION_BUDGET_PREF, SESSION_SEED_PREF
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
from invisible_core import compose_session_prefs, context_geometry, make_virtual_display
|
||||
@@ -231,11 +231,8 @@ def build_prefs(
|
||||
# Milliseconds, and an int: Gecko has no float pref type, and `1.0` written
|
||||
# as a number arrives with the right value and the wrong type - the defect
|
||||
# `ui.textScaleFactor` had.
|
||||
# The persona's keyboard, from the session's language AND country: the
|
||||
# server cannot know the country, the decision can (SessionLocale.region).
|
||||
if locale is not None and hasattr(locale, "languages"):
|
||||
from invisible_core.juggler.keyboard import layout_for
|
||||
prefs[KEYBOARD_LAYOUT_PREF] = layout_for(list(locale.languages), locale.region)
|
||||
# The persona's keyboards are in the prefs already: the core declares them
|
||||
# with the language and country (invisible_core.prefs._apply_locale).
|
||||
if session_seed is not None and humanize:
|
||||
prefs[SESSION_SEED_PREF] = int(session_seed)
|
||||
prefs[MOTION_BUDGET_PREF] = int(round(
|
||||
|
||||
@@ -2,6 +2,7 @@ import faulthandler
|
||||
import http.server
|
||||
import os
|
||||
import random
|
||||
import re
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
@@ -181,6 +182,58 @@ def firefox_binary():
|
||||
return str(entry)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# The engine a test runs against. main's e2e runs against the engine the
|
||||
# published core pins AND against the candidate of the next engine (the gate),
|
||||
# so a property only the newer engine promises must not run on the older one.
|
||||
#
|
||||
# The engine is read from the seal the process runs under, the same one that
|
||||
# checks the launch: `active_seal().tag`. Only the number counts: `firefox-60`
|
||||
# and `firefox-60-candidate` are both 60. A tag with no number (`local`, or
|
||||
# anything else) does not say which engine it is, so the test does not skip and
|
||||
# does not run: it fails and says why. A candidate is sealed as
|
||||
# `firefox-N-candidate` by the gate.
|
||||
#
|
||||
# No new pytest marker: the marker vocabulary is shared with invisible_core
|
||||
# and a marker only here would make the two drift.
|
||||
_ENGINE_TAG = re.compile(r"^firefox-(\d+)(?:-candidate)?$")
|
||||
|
||||
|
||||
def _engine_number(tag):
|
||||
"""N of `firefox-N` or `firefox-N-candidate`, or None."""
|
||||
m = _ENGINE_TAG.match(tag or "")
|
||||
return int(m.group(1)) if m else None
|
||||
|
||||
|
||||
def _skip_unless_engine_at_least(minimum, tag):
|
||||
want = _engine_number(minimum)
|
||||
if want is None:
|
||||
raise pytest.UsageError("engine_at_least wants 'firefox-N', got %r" % (minimum,))
|
||||
have = _engine_number(tag)
|
||||
if have is None:
|
||||
pytest.fail("the engine's seal has no number: a candidate must be sealed as "
|
||||
"firefox-N-candidate (seal tag %r)" % (tag,), pytrace=False)
|
||||
if have < want:
|
||||
pytest.skip("the property needs %s or later; this engine is %s"
|
||||
% (minimum, tag))
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def engine_at_least():
|
||||
"""``engine_at_least("firefox-60")``: skip the test unless the engine in
|
||||
use is that release or a later one (see above for how it is read). A seal
|
||||
whose tag has no number (``local``, anything but firefox-N or
|
||||
firefox-N-candidate) makes the test FAIL, saying so: it neither skips nor
|
||||
runs."""
|
||||
_require_package()
|
||||
from invisible_core.seal import active_seal
|
||||
tag = active_seal().tag
|
||||
|
||||
def check(minimum):
|
||||
_skip_unless_engine_at_least(minimum, tag)
|
||||
return check
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Local HTTP fixture server - service workers need a real http(s) origin
|
||||
# (data: and about:blank are opaque-origin, no SW registration possible).
|
||||
|
||||
@@ -0,0 +1,297 @@
|
||||
"""Writes the test images and ICC profiles of the canvas colour probe, standard library only.
|
||||
|
||||
python -I gen_images.py <out dir>
|
||||
|
||||
<out dir>/images/*.png|jpg, <out dir>/profiles/*.icc (built by hand: matrix/TRC, ICC v2.1),
|
||||
<out dir>/images.json (id, file, what the tag says). Nothing is downloaded. The pixels are the
|
||||
same 16x16 gradient in every image (R from x, G from y, B from x+y), so the files differ only
|
||||
in the colour tag they carry.
|
||||
"""
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import struct
|
||||
import sys
|
||||
import zlib
|
||||
|
||||
D50 = (0.9642, 1.0, 0.8249)
|
||||
D65_XY = (0.3127, 0.3290)
|
||||
D50_XY = (0.3457, 0.3585)
|
||||
# name: (primaries xy R,G,B, white xy, trc)
|
||||
SPACES = {
|
||||
"displayp3": (((0.680, 0.320), (0.265, 0.690), (0.150, 0.060)), D65_XY, ("para-srgb",)),
|
||||
"adobergb": (((0.640, 0.330), (0.210, 0.710), (0.150, 0.060)), D65_XY, ("gamma", 563 / 256)),
|
||||
"rec2020": (((0.708, 0.292), (0.170, 0.797), (0.131, 0.046)), D65_XY, ("gamma", 2.4)),
|
||||
"prophoto": (((0.7347, 0.2653), (0.1596, 0.8404), (0.0366, 0.0001)), D50_XY, ("gamma", 1.8)),
|
||||
"srgb": (((0.640, 0.330), (0.300, 0.600), (0.150, 0.060)), D65_XY, ("para-srgb",)),
|
||||
}
|
||||
|
||||
|
||||
def mat_mul(a, b):
|
||||
return [[sum(a[i][k] * b[k][j] for k in range(3)) for j in range(3)] for i in range(3)]
|
||||
|
||||
|
||||
def mat_vec(m, v):
|
||||
return [sum(m[i][k] * v[k] for k in range(3)) for i in range(3)]
|
||||
|
||||
|
||||
def mat_inv(m):
|
||||
a, b, c = m[0]
|
||||
d, e, f = m[1]
|
||||
g, h, i = m[2]
|
||||
det = a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g)
|
||||
return [[(e * i - f * h) / det, (c * h - b * i) / det, (b * f - c * e) / det],
|
||||
[(f * g - d * i) / det, (a * i - c * g) / det, (c * d - a * f) / det],
|
||||
[(d * h - e * g) / det, (b * g - a * h) / det, (a * e - b * d) / det]]
|
||||
|
||||
|
||||
def xy_to_xyz(xy):
|
||||
x, y = xy
|
||||
return [x / y, 1.0, (1 - x - y) / y]
|
||||
|
||||
|
||||
BRADFORD = [[0.8951, 0.2664, -0.1614], [-0.7502, 1.7135, 0.0367], [0.0389, -0.0685, 1.0296]]
|
||||
|
||||
|
||||
def adapt(src_white, dst_white):
|
||||
s = mat_vec(BRADFORD, src_white)
|
||||
d = mat_vec(BRADFORD, dst_white)
|
||||
scale = [[d[0] / s[0], 0, 0], [0, d[1] / s[1], 0], [0, 0, d[2] / s[2]]]
|
||||
return mat_mul(mat_inv(BRADFORD), mat_mul(scale, BRADFORD))
|
||||
|
||||
|
||||
def colorants_d50(prim, white_xy):
|
||||
"""The rXYZ, gXYZ, bXYZ columns adapted (Bradford) to the D50 PCS."""
|
||||
cols = [xy_to_xyz(p) for p in prim]
|
||||
m = [[cols[j][i] for j in range(3)] for i in range(3)]
|
||||
s = mat_vec(mat_inv(m), xy_to_xyz(white_xy))
|
||||
rgb2xyz = [[m[i][j] * s[j] for j in range(3)] for i in range(3)]
|
||||
ad = adapt(xy_to_xyz(white_xy), list(D50))
|
||||
out = mat_mul(ad, rgb2xyz)
|
||||
return [[out[i][j] for i in range(3)] for j in range(3)] # per channel XYZ
|
||||
|
||||
|
||||
def s15(v):
|
||||
return struct.pack(">i", int(round(v * 65536)))
|
||||
|
||||
|
||||
def tag_xyz(v):
|
||||
return b"XYZ \0\0\0\0" + s15(v[0]) + s15(v[1]) + s15(v[2])
|
||||
|
||||
|
||||
def tag_text(s):
|
||||
return b"text\0\0\0\0" + s.encode("ascii") + b"\0"
|
||||
|
||||
|
||||
def tag_desc(s):
|
||||
b = s.encode("ascii") + b"\0"
|
||||
return (b"desc\0\0\0\0" + struct.pack(">I", len(b)) + b + struct.pack(">II", 0, 0)
|
||||
+ struct.pack(">HB", 0, 0) + b"\0" * 67)
|
||||
|
||||
|
||||
def tag_trc(trc):
|
||||
if trc[0] == "gamma":
|
||||
return b"curv\0\0\0\0" + struct.pack(">IH", 1, int(round(trc[1] * 256))) + b"\0\0"
|
||||
# parametric type 3: Y = (aX+b)^g for X >= d, cX otherwise (the sRGB curve)
|
||||
return (b"para\0\0\0\0" + struct.pack(">HH", 3, 0) + s15(2.4) + s15(1 / 1.055) + s15(0.055 / 1.055)
|
||||
+ s15(1 / 12.92) + s15(0.04045))
|
||||
|
||||
|
||||
def pad4(b):
|
||||
return b + b"\0" * (-len(b) % 4)
|
||||
|
||||
|
||||
def build_icc(name):
|
||||
prim, white, trc = SPACES[name]
|
||||
cols = colorants_d50(prim, white)
|
||||
trc_b = pad4(tag_trc(trc))
|
||||
tags = [(b"desc", pad4(tag_desc("invisible probe " + name))),
|
||||
(b"cprt", pad4(tag_text("public domain, generated by gen_images.py"))),
|
||||
(b"wtpt", tag_xyz(D50)),
|
||||
(b"rXYZ", tag_xyz(cols[0])), (b"gXYZ", tag_xyz(cols[1])), (b"bXYZ", tag_xyz(cols[2])),
|
||||
(b"rTRC", trc_b), (b"gTRC", trc_b), (b"bTRC", trc_b)]
|
||||
off = 128 + 4 + 12 * len(tags)
|
||||
table = struct.pack(">I", len(tags))
|
||||
body = b""
|
||||
seen = {}
|
||||
for sig, data in tags:
|
||||
if data in seen and sig.endswith(b"TRC"):
|
||||
o = seen[data]
|
||||
else:
|
||||
o = off + len(body)
|
||||
body += data
|
||||
seen[data] = o
|
||||
table += sig + struct.pack(">II", o, len(data))
|
||||
size = 128 + len(table) + len(body)
|
||||
hdr = (struct.pack(">I", size) + b"\0\0\0\0" + bytes([2, 0x10, 0, 0]) + b"mntrRGB XYZ "
|
||||
+ struct.pack(">6H", 2026, 11, 9, 0, 0, 0) + b"acsp"
|
||||
+ b"\0" * 28 # platform, flags, manufacturer, model, attributes (8), rendering intent
|
||||
+ s15(D50[0]) + s15(D50[1]) + s15(D50[2]) + b"\0" * 4 + b"\0" * 16 + b"\0" * 28)
|
||||
assert len(hdr) == 128, len(hdr)
|
||||
return hdr + table + body
|
||||
|
||||
|
||||
def pixels():
|
||||
rows = []
|
||||
for y in range(16):
|
||||
rows.append([(x * 17, y * 17, (x + y) * 17 // 2) for x in range(16)])
|
||||
return rows
|
||||
|
||||
|
||||
def chunk(typ, data):
|
||||
c = typ + data
|
||||
return struct.pack(">I", len(data)) + c + struct.pack(">I", zlib.crc32(c) & 0xFFFFFFFF)
|
||||
|
||||
|
||||
def png(extra):
|
||||
raw = b"".join(b"\0" + bytes(v for px in row for v in px) for row in pixels())
|
||||
return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", 16, 16, 8, 2, 0, 0, 0))
|
||||
+ b"".join(chunk(t, d) for t, d in extra) + chunk(b"IDAT", zlib.compress(raw, 9)) + chunk(b"IEND", b""))
|
||||
|
||||
|
||||
def iccp(name, profile):
|
||||
return (b"iCCP", name.encode() + b"\0\0" + zlib.compress(profile, 9))
|
||||
|
||||
|
||||
def chrm(prim, white):
|
||||
vals = [white[0], white[1]] + [c for p in prim for c in p]
|
||||
return (b"cHRM", b"".join(struct.pack(">I", int(round(v * 100000))) for v in vals))
|
||||
|
||||
|
||||
# ---- baseline JPEG, 4:4:4, quantisation all 1, own Huffman tables (no tables copied from anywhere)
|
||||
ZIGZAG = [0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14,
|
||||
21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53,
|
||||
60, 61, 54, 47, 55, 62, 63]
|
||||
AC_SYMS = [0x00, 0xF0] + [(r << 4) | s for r in range(16) for s in range(1, 11)] # 162 symbols, 8-bit codes 0..161
|
||||
|
||||
|
||||
def dct8(block):
|
||||
out = [0.0] * 64
|
||||
for u in range(8):
|
||||
for v in range(8):
|
||||
s = 0.0
|
||||
for x in range(8):
|
||||
for y in range(8):
|
||||
s += block[y * 8 + x] * math.cos((2 * x + 1) * u * math.pi / 16) * math.cos((2 * y + 1) * v * math.pi / 16)
|
||||
cu = 1 / math.sqrt(2) if u == 0 else 1
|
||||
cv = 1 / math.sqrt(2) if v == 0 else 1
|
||||
out[v * 8 + u] = 0.25 * cu * cv * s
|
||||
return out
|
||||
|
||||
|
||||
def jpeg(profile):
|
||||
ycc = []
|
||||
for row in pixels():
|
||||
r = []
|
||||
for (R, G, B) in row:
|
||||
r.append((0.299 * R + 0.587 * G + 0.114 * B,
|
||||
-0.168736 * R - 0.331264 * G + 0.5 * B + 128,
|
||||
0.5 * R - 0.418688 * G - 0.081312 * B + 128))
|
||||
ycc.append(r)
|
||||
bits = []
|
||||
|
||||
def put(code, n):
|
||||
for i in range(n - 1, -1, -1):
|
||||
bits.append((code >> i) & 1)
|
||||
|
||||
def cat(v):
|
||||
return 0 if v == 0 else abs(v).bit_length()
|
||||
|
||||
def amp(v, s):
|
||||
return v if v >= 0 else v + (1 << s) - 1
|
||||
|
||||
pred = [0, 0, 0]
|
||||
for by in range(2):
|
||||
for bx in range(2):
|
||||
for c in range(3):
|
||||
blk = [ycc[by * 8 + y][bx * 8 + x][c] - 128 for y in range(8) for x in range(8)]
|
||||
co = [int(round(v)) for v in dct8(blk)]
|
||||
zz = [co[i] for i in ZIGZAG]
|
||||
d = zz[0] - pred[c]
|
||||
pred[c] = zz[0]
|
||||
s = cat(d)
|
||||
put(s, 4) # DC symbol s has the 4-bit code s
|
||||
if s:
|
||||
put(amp(d, s), s)
|
||||
run = 0
|
||||
last = max([i for i in range(1, 64) if zz[i]] or [0])
|
||||
for i in range(1, last + 1):
|
||||
v = zz[i]
|
||||
if v == 0:
|
||||
run += 1
|
||||
continue
|
||||
while run > 15:
|
||||
put(AC_SYMS.index(0xF0), 8)
|
||||
run -= 16
|
||||
s = cat(v)
|
||||
put(AC_SYMS.index((run << 4) | s), 8)
|
||||
put(amp(v, s), s)
|
||||
run = 0
|
||||
if last < 63:
|
||||
put(AC_SYMS.index(0x00), 8)
|
||||
while len(bits) % 8:
|
||||
bits.append(1)
|
||||
data = bytearray()
|
||||
for i in range(0, len(bits), 8):
|
||||
b = int("".join(map(str, bits[i:i + 8])), 2)
|
||||
data.append(b)
|
||||
if b == 0xFF:
|
||||
data.append(0)
|
||||
|
||||
def seg(m, payload):
|
||||
return bytes([0xFF, m]) + struct.pack(">H", len(payload) + 2) + payload
|
||||
|
||||
icc = b"ICC_PROFILE\0" + bytes([1, 1]) + profile
|
||||
out = b"\xFF\xD8" + seg(0xE0, b"JFIF\0\x01\x01\0\0\x01\0\x01\0\0") + seg(0xE2, icc)
|
||||
out += seg(0xDB, bytes([0]) + bytes([1] * 64))
|
||||
out += seg(0xC0, bytes([8]) + struct.pack(">HH", 16, 16) + bytes([3, 1, 0x11, 0, 2, 0x11, 0, 3, 0x11, 0]))
|
||||
out += seg(0xC4, bytes([0x00]) + bytes([0, 0, 0, 12] + [0] * 12) + bytes(range(12)))
|
||||
out += seg(0xC4, bytes([0x10]) + bytes([0] * 7 + [len(AC_SYMS)] + [0] * 8) + bytes(AC_SYMS))
|
||||
out += seg(0xDA, bytes([3, 1, 0x00, 2, 0x00, 3, 0x00, 0, 63, 0])) + bytes(data) + b"\xFF\xD9"
|
||||
return out
|
||||
|
||||
|
||||
def build_images():
|
||||
"""The ten test images, in memory: a list of (id, extension, bytes, what the tag says),
|
||||
and the five generated ICC profiles by name. Deterministic: the same bytes on every run."""
|
||||
profs = {n: build_icc(n) for n in SPACES}
|
||||
p3prim, p3white, _ = SPACES["displayp3"]
|
||||
imgs = [
|
||||
("iccp-displayp3", "png", png([iccp("p3", profs["displayp3"])]), "iCCP Display P3 (matrix, sRGB-curve parametric TRC)"),
|
||||
("iccp-adobergb", "png", png([iccp("a98", profs["adobergb"])]), "iCCP Adobe RGB (1998) (matrix, gamma 563/256)"),
|
||||
("iccp-rec2020", "png", png([iccp("r2020", profs["rec2020"])]), "iCCP Rec.2020 primaries (matrix, gamma 2.4)"),
|
||||
("iccp-prophoto", "png", png([iccp("pp", profs["prophoto"])]), "iCCP ProPhoto RGB (matrix, gamma 1.8, D50 white)"),
|
||||
("iccp-srgb", "png", png([iccp("s", profs["srgb"])]), "iCCP sRGB primaries (matrix, sRGB parametric TRC): control"),
|
||||
("cicp-p3", "png", png([(b"cICP", bytes([12, 13, 0, 1]))]), "cICP primaries 12 (Display P3), transfer 13 (sRGB), full range"),
|
||||
("gama-chrm-p3", "png", png([(b"gAMA", struct.pack(">I", 45455)), chrm(p3prim, p3white)]), "gAMA 45455 + cHRM of Display P3"),
|
||||
("srgb-chunk", "png", png([(b"sRGB", b"\0")]), "sRGB chunk, perceptual"),
|
||||
("untagged", "png", png([]), "no colour tag"),
|
||||
("jpeg-icc-displayp3", "jpg", jpeg(profs["displayp3"]), "JPEG (own encoder) with APP2 ICC Display P3"),
|
||||
]
|
||||
return imgs, profs
|
||||
|
||||
|
||||
def images_json(imgs):
|
||||
"""What the page fetches as images.json: id, URL (relative) and the tag, per image."""
|
||||
return [{"id": iid, "file": "images/%s.%s" % (iid, ext), "tag": what}
|
||||
for iid, ext, _data, what in imgs]
|
||||
|
||||
|
||||
def main():
|
||||
out = sys.argv[1]
|
||||
os.makedirs(os.path.join(out, "images"), exist_ok=True)
|
||||
os.makedirs(os.path.join(out, "profiles"), exist_ok=True)
|
||||
imgs, profs = build_images()
|
||||
for n, p in profs.items():
|
||||
with open(os.path.join(out, "profiles", n + ".icc"), "wb") as f:
|
||||
f.write(p)
|
||||
for (iid, ext, data, _what), meta in zip(imgs, images_json(imgs)):
|
||||
with open(os.path.join(out, meta["file"]), "wb") as f:
|
||||
f.write(data)
|
||||
with open(os.path.join(out, "images.json"), "w") as f:
|
||||
json.dump(images_json(imgs), f, indent=1)
|
||||
print("wrote %d images and %d profiles to %s" % (len(imgs), len(profs), out))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,102 @@
|
||||
<!doctype html>
|
||||
<meta charset="utf-8">
|
||||
<title>canvas colour readback probe</title>
|
||||
<body>
|
||||
<script>
|
||||
"use strict";
|
||||
// Reads, from a page served on localhost, the bytes the canvas 2D hands back after a tagged image is
|
||||
// drawn (drawImage, createImageBitmap) and after fillRect with CSS colour functions. Result: window.R.
|
||||
const hex = (u8) => Array.from(u8, (b) => b.toString(16).padStart(2, "0")).join("");
|
||||
async function sha(u8) { return hex(new Uint8Array(await crypto.subtle.digest("SHA-256", u8))); }
|
||||
|
||||
async function readCanvas(c) {
|
||||
const ctx = c.getContext("2d");
|
||||
const d = ctx.getImageData(0, 0, c.width, c.height).data;
|
||||
const u8 = new Uint8Array(d.buffer, d.byteOffset, d.byteLength);
|
||||
return { sha256: await sha(u8), rgba_hex: hex(u8) };
|
||||
}
|
||||
|
||||
function loadImage(url) {
|
||||
return new Promise((res, rej) => {
|
||||
const i = new Image();
|
||||
i.onload = () => res(i);
|
||||
i.onerror = () => rej(new Error("image load failed " + url));
|
||||
i.src = url;
|
||||
});
|
||||
}
|
||||
|
||||
async function drawProbe(draw, size) {
|
||||
const c = document.createElement("canvas");
|
||||
c.width = size; c.height = size;
|
||||
const ctx = c.getContext("2d");
|
||||
ctx.clearRect(0, 0, size, size);
|
||||
await draw(ctx, size);
|
||||
return readCanvas(c);
|
||||
}
|
||||
|
||||
const FILLS = [
|
||||
"color(srgb 1 0 0)", "color(srgb 0.2 0.8 0.4)",
|
||||
"color(display-p3 1 0 0)", "color(display-p3 0 1 0)", "color(display-p3 0.2 0.8 0.4)", "color(display-p3 0.5 0.5 0.5)",
|
||||
"color(a98-rgb 0.2 0.8 0.4)", "color(prophoto-rgb 0.2 0.8 0.4)", "color(rec2020 0.2 0.8 0.4)",
|
||||
"color(xyz-d65 0.2 0.3 0.4)", "color(xyz-d50 0.2 0.3 0.4)",
|
||||
"color-mix(in oklab, red 30%, blue)", "color-mix(in srgb, red 30%, blue)", "color-mix(in display-p3, color(display-p3 1 0 0) 30%, blue)",
|
||||
"color-mix(in oklch, #336699 40%, #cc9933)", "oklab(0.6 0.1 -0.1)", "oklch(0.7 0.15 150)", "lab(60 40 -30)", "lch(60 40 200)",
|
||||
"hsl(200 60% 40%)", "#336699", "rgba(51,102,153,0.5)",
|
||||
];
|
||||
|
||||
async function run() {
|
||||
const R = { env: {}, images: {}, fills: {}, canvas_colorspace: {} };
|
||||
const mq = (q) => { try { return matchMedia(q).matches; } catch (e) { return "error"; } };
|
||||
R.env = {
|
||||
"color-gamut:srgb": mq("(color-gamut: srgb)"), "color-gamut:p3": mq("(color-gamut: p3)"), "color-gamut:rec2020": mq("(color-gamut: rec2020)"),
|
||||
"dynamic-range:high": mq("(dynamic-range: high)"), "video-dynamic-range:high": mq("(video-dynamic-range: high)"),
|
||||
"prefers-color-scheme:dark": mq("(prefers-color-scheme: dark)"),
|
||||
colorDepth: screen.colorDepth, pixelDepth: screen.pixelDepth, devicePixelRatio: window.devicePixelRatio,
|
||||
};
|
||||
const list = await (await fetch("images.json")).json();
|
||||
for (const it of list) {
|
||||
const out = { tag: it.tag };
|
||||
try {
|
||||
const img = await loadImage(it.file);
|
||||
out.natural = [img.naturalWidth, img.naturalHeight];
|
||||
out.drawImage = await drawProbe((ctx) => ctx.drawImage(img, 0, 0), 16);
|
||||
out.drawImage_scaled32 = await drawProbe((ctx) => ctx.drawImage(img, 0, 0, 32, 32), 32);
|
||||
const blob = await (await fetch(it.file)).blob();
|
||||
for (const csc of ["default", "none"]) {
|
||||
try {
|
||||
const bmp = await createImageBitmap(blob, { colorSpaceConversion: csc });
|
||||
out["bitmap_" + csc] = await drawProbe((ctx) => ctx.drawImage(bmp, 0, 0), 16);
|
||||
bmp.close();
|
||||
} catch (e) { out["bitmap_" + csc] = { error: String(e) }; }
|
||||
}
|
||||
} catch (e) { out.error = String(e); }
|
||||
R.images[it.id] = out;
|
||||
}
|
||||
for (const f of FILLS) {
|
||||
try {
|
||||
const c = document.createElement("canvas"); c.width = 16; c.height = 16;
|
||||
const ctx = c.getContext("2d");
|
||||
ctx.fillStyle = "#010203"; ctx.fillStyle = f;
|
||||
if (ctx.fillStyle === "#010203") { R.fills[f] = { unsupported: true }; continue; }
|
||||
ctx.fillRect(0, 0, 16, 16);
|
||||
const r = await readCanvas(c);
|
||||
R.fills[f] = { sha256: r.sha256, rgba: r.rgba_hex.slice(0, 8), fillStyle_readback: ctx.fillStyle };
|
||||
} catch (e) { R.fills[f] = { error: String(e) }; }
|
||||
}
|
||||
// canvas with colorSpace option and putImageData/getImageData colorSpace
|
||||
try {
|
||||
const c = document.createElement("canvas"); c.width = 16; c.height = 16;
|
||||
const ctx = c.getContext("2d", { colorSpace: "display-p3" });
|
||||
const attrs = ctx.getContextAttributes ? ctx.getContextAttributes() : null;
|
||||
R.canvas_colorspace.attributes = attrs ? { colorSpace: attrs.colorSpace } : "no getContextAttributes";
|
||||
R.canvas_colorspace.ctx_colorSpace = ctx.colorSpace === undefined ? "undefined" : ctx.colorSpace;
|
||||
ctx.fillStyle = "color(display-p3 1 0 0)"; ctx.fillRect(0, 0, 16, 16);
|
||||
const r = await readCanvas(c);
|
||||
R.canvas_colorspace.p3_fill_p3_canvas = { sha256: r.sha256, rgba: r.rgba_hex.slice(0, 8) };
|
||||
} catch (e) { R.canvas_colorspace.error = String(e); }
|
||||
window.R = R;
|
||||
window.DONE = true;
|
||||
}
|
||||
run().catch((e) => { window.ERR = String(e && e.stack || e); });
|
||||
</script>
|
||||
</body>
|
||||
@@ -0,0 +1,505 @@
|
||||
{
|
||||
"test_page": "index.html",
|
||||
"image_generator": "gen_images.py",
|
||||
"source": {
|
||||
"capture": "canvas-color/canvas-color-icc-readback",
|
||||
"reference_run": "runs/a_win_default.json",
|
||||
"repeat_run": "runs/a2_win_default_repeat.json (same hashes on all probes)",
|
||||
"control_run": "runs/b_win_force_srgb.json (gfx.color_management.force_srgb=true)",
|
||||
"date": "2026-11-09"
|
||||
},
|
||||
"firefox": {
|
||||
"buildid": "20261022150525",
|
||||
"exe": "firefox.exe",
|
||||
"exe_sha256": "d8b5ed82fcd9c0f159dc86dc1c4526ceae981c4d9651f21908b6de90d0a56d85",
|
||||
"os": "Windows_NT",
|
||||
"os_version": "10.0",
|
||||
"version": "159.0",
|
||||
"prefs": {
|
||||
"gfx.canvas.accelerated": false,
|
||||
"gfx.color_management.display_profile": "",
|
||||
"gfx.color_management.force_srgb": false,
|
||||
"gfx.color_management.mode": 2,
|
||||
"gfx.color_management.native_srgb": false
|
||||
}
|
||||
},
|
||||
"display_profile": {
|
||||
"file": "sRGB Color Space Profile.icm",
|
||||
"size": 3144,
|
||||
"sha256": "2b3aa1645779a9e634744faf9b01e9102b0c9b88fd6deced7934df86b949af7e",
|
||||
"api": "GetICMProfileW"
|
||||
},
|
||||
"images": {
|
||||
"iccp-displayp3": {
|
||||
"file": "images/iccp-displayp3.png",
|
||||
"bytes": 839,
|
||||
"sha256": "d0b1cb83418856be9238914c623c62304656dca6e1f8d72fab4b1907501fc94a"
|
||||
},
|
||||
"iccp-adobergb": {
|
||||
"file": "images/iccp-adobergb.png",
|
||||
"bytes": 821,
|
||||
"sha256": "b66251789a8432ac74e80206e5a5eed6368f1244e53394b02256260b712a10e5"
|
||||
},
|
||||
"iccp-rec2020": {
|
||||
"file": "images/iccp-rec2020.png",
|
||||
"bytes": 824,
|
||||
"sha256": "7c58cc0c31435196f37288fb600c4220effd27cca4f34285e40f098f84086133"
|
||||
},
|
||||
"iccp-prophoto": {
|
||||
"file": "images/iccp-prophoto.png",
|
||||
"bytes": 812,
|
||||
"sha256": "ca661ae5c42dfda0e9fe1b1eca2a08e1f2f7137cec112afd59d2a2480cfa9b24"
|
||||
},
|
||||
"iccp-srgb": {
|
||||
"file": "images/iccp-srgb.png",
|
||||
"bytes": 833,
|
||||
"sha256": "fc84c167782b6d17d3e4f462e696f41e98c90c71adeaddeefdfde7bbc02123bb"
|
||||
},
|
||||
"cicp-p3": {
|
||||
"file": "images/cicp-p3.png",
|
||||
"bytes": 572,
|
||||
"sha256": "5c2de96dbcfd4e2255785974d33082ccfb8e297b486676222a09f2922a3972ed"
|
||||
},
|
||||
"gama-chrm-p3": {
|
||||
"file": "images/gama-chrm-p3.png",
|
||||
"bytes": 616,
|
||||
"sha256": "e07805116e2a9a40e901401c00d1beb8b47f82d6e8f9708be335f06486429f26"
|
||||
},
|
||||
"srgb-chunk": {
|
||||
"file": "images/srgb-chunk.png",
|
||||
"bytes": 569,
|
||||
"sha256": "6481d9b1e09b6b89b7d7355328ade8ceaf2fec3cfe6e7bf57e052a26c4589576"
|
||||
},
|
||||
"untagged": {
|
||||
"file": "images/untagged.png",
|
||||
"bytes": 556,
|
||||
"sha256": "d10d32213102277c1b28271a19ce56aac0553bc784023e2640b9713a5ef10677"
|
||||
},
|
||||
"jpeg-icc-displayp3": {
|
||||
"file": "images/jpeg-icc-displayp3.jpg",
|
||||
"bytes": 1044,
|
||||
"sha256": "26ecbdd5a632c531522cbbda37133dd405a6135669b6a810874ddf3a5151b61b"
|
||||
}
|
||||
},
|
||||
"probe_count": 72,
|
||||
"profile_dependent_count": 27,
|
||||
"profile_dependent": [
|
||||
"cicp-p3 | bitmap_default",
|
||||
"cicp-p3 | drawImage",
|
||||
"cicp-p3 | drawImage_scaled32",
|
||||
"gama-chrm-p3 | bitmap_default",
|
||||
"gama-chrm-p3 | drawImage",
|
||||
"gama-chrm-p3 | drawImage_scaled32",
|
||||
"iccp-adobergb | bitmap_default",
|
||||
"iccp-adobergb | drawImage",
|
||||
"iccp-adobergb | drawImage_scaled32",
|
||||
"iccp-displayp3 | bitmap_default",
|
||||
"iccp-displayp3 | drawImage",
|
||||
"iccp-displayp3 | drawImage_scaled32",
|
||||
"iccp-prophoto | bitmap_default",
|
||||
"iccp-prophoto | drawImage",
|
||||
"iccp-prophoto | drawImage_scaled32",
|
||||
"iccp-rec2020 | bitmap_default",
|
||||
"iccp-rec2020 | drawImage",
|
||||
"iccp-rec2020 | drawImage_scaled32",
|
||||
"iccp-srgb | bitmap_default",
|
||||
"iccp-srgb | drawImage",
|
||||
"iccp-srgb | drawImage_scaled32",
|
||||
"jpeg-icc-displayp3 | bitmap_default",
|
||||
"jpeg-icc-displayp3 | drawImage",
|
||||
"jpeg-icc-displayp3 | drawImage_scaled32",
|
||||
"srgb-chunk | bitmap_default",
|
||||
"srgb-chunk | drawImage",
|
||||
"srgb-chunk | drawImage_scaled32"
|
||||
],
|
||||
"probes": {
|
||||
"cicp-p3 | drawImage": {
|
||||
"kind": "image",
|
||||
"sha256": "da7e0175bb0c175e3d8bd5f6c9ca408707103b4b6a2d276233eca8c92d16b577",
|
||||
"bytes": 1024,
|
||||
"without_conversion_sha256": "36c40e179db9bda2444948eee00fa2b9af802a42b7183e5caa46ff5100d46558"
|
||||
},
|
||||
"cicp-p3 | drawImage_scaled32": {
|
||||
"kind": "image",
|
||||
"sha256": "dcb22689a38b7a73881b1e998bdec904b9cb4ab17b4d0f339fae9d1d2b119bd8",
|
||||
"bytes": 4096,
|
||||
"without_conversion_sha256": "68bc6166faaabddf135829bb9ea5bcec861938cb5f304f9fca235d59737fe1d9"
|
||||
},
|
||||
"cicp-p3 | bitmap_default": {
|
||||
"kind": "image",
|
||||
"sha256": "da7e0175bb0c175e3d8bd5f6c9ca408707103b4b6a2d276233eca8c92d16b577",
|
||||
"bytes": 1024,
|
||||
"without_conversion_sha256": "36c40e179db9bda2444948eee00fa2b9af802a42b7183e5caa46ff5100d46558"
|
||||
},
|
||||
"cicp-p3 | bitmap_none": {
|
||||
"kind": "image",
|
||||
"sha256": "4408185fd170878816ebdc7412ecc36d75d53a02ff41a07f4f76c9042a531b73",
|
||||
"bytes": 1024
|
||||
},
|
||||
"gama-chrm-p3 | drawImage": {
|
||||
"kind": "image",
|
||||
"sha256": "40794d510b713345bd0f1e972078cbc794bab9a031b93cd6993fb1d303210571",
|
||||
"bytes": 1024,
|
||||
"without_conversion_sha256": "9e5bba7e830226a96689458592f8a51f43161d9a61c989705022fbe8027fd247"
|
||||
},
|
||||
"gama-chrm-p3 | drawImage_scaled32": {
|
||||
"kind": "image",
|
||||
"sha256": "cf3fb3bd1722ec5155bb4b9a04de3d6e9468ad586e0417d75e6bc21a8bd09a1a",
|
||||
"bytes": 4096,
|
||||
"without_conversion_sha256": "65051f0a8b4ff1112fd8b37682ae481a932d08ab6a8da1fe5902192f61450027"
|
||||
},
|
||||
"gama-chrm-p3 | bitmap_default": {
|
||||
"kind": "image",
|
||||
"sha256": "40794d510b713345bd0f1e972078cbc794bab9a031b93cd6993fb1d303210571",
|
||||
"bytes": 1024,
|
||||
"without_conversion_sha256": "9e5bba7e830226a96689458592f8a51f43161d9a61c989705022fbe8027fd247"
|
||||
},
|
||||
"gama-chrm-p3 | bitmap_none": {
|
||||
"kind": "image",
|
||||
"sha256": "4408185fd170878816ebdc7412ecc36d75d53a02ff41a07f4f76c9042a531b73",
|
||||
"bytes": 1024
|
||||
},
|
||||
"iccp-adobergb | drawImage": {
|
||||
"kind": "image",
|
||||
"sha256": "b13bc0493dfad6d36c6763077c5a9144c217777fd0f282a344a11f1966910905",
|
||||
"bytes": 1024,
|
||||
"without_conversion_sha256": "ec8e92bb2dfedc2c4ed7a86a22e5d88aaf3176f5bf95a1bc95d4a0d9207b2145"
|
||||
},
|
||||
"iccp-adobergb | drawImage_scaled32": {
|
||||
"kind": "image",
|
||||
"sha256": "5902f7aab7e9420a50e6c0145ed7f192355f061eb03290279b9b57c7f44f1240",
|
||||
"bytes": 4096,
|
||||
"without_conversion_sha256": "4641000ca8c7208c7c773a640d9e739e5893d871010ebdcf18642b34a60bc2b1"
|
||||
},
|
||||
"iccp-adobergb | bitmap_default": {
|
||||
"kind": "image",
|
||||
"sha256": "b13bc0493dfad6d36c6763077c5a9144c217777fd0f282a344a11f1966910905",
|
||||
"bytes": 1024,
|
||||
"without_conversion_sha256": "ec8e92bb2dfedc2c4ed7a86a22e5d88aaf3176f5bf95a1bc95d4a0d9207b2145"
|
||||
},
|
||||
"iccp-adobergb | bitmap_none": {
|
||||
"kind": "image",
|
||||
"sha256": "4408185fd170878816ebdc7412ecc36d75d53a02ff41a07f4f76c9042a531b73",
|
||||
"bytes": 1024
|
||||
},
|
||||
"iccp-displayp3 | drawImage": {
|
||||
"kind": "image",
|
||||
"sha256": "1320722da92c41789949998337f35ec8159f698b123581d56a464b24c64982bc",
|
||||
"bytes": 1024,
|
||||
"without_conversion_sha256": "551fb216de2b52c749e7010781ea575f5068907f28fe673c8d0820e67ba8ab1a"
|
||||
},
|
||||
"iccp-displayp3 | drawImage_scaled32": {
|
||||
"kind": "image",
|
||||
"sha256": "b387a847012c88a79c3f18ad52e32a1aef606354b846e24d66c376e1e1c9c25d",
|
||||
"bytes": 4096,
|
||||
"without_conversion_sha256": "fb974c99747b957e44a325789effaad9a548a52a8b75077a22cc1ce7648448f8"
|
||||
},
|
||||
"iccp-displayp3 | bitmap_default": {
|
||||
"kind": "image",
|
||||
"sha256": "1320722da92c41789949998337f35ec8159f698b123581d56a464b24c64982bc",
|
||||
"bytes": 1024,
|
||||
"without_conversion_sha256": "551fb216de2b52c749e7010781ea575f5068907f28fe673c8d0820e67ba8ab1a"
|
||||
},
|
||||
"iccp-displayp3 | bitmap_none": {
|
||||
"kind": "image",
|
||||
"sha256": "4408185fd170878816ebdc7412ecc36d75d53a02ff41a07f4f76c9042a531b73",
|
||||
"bytes": 1024
|
||||
},
|
||||
"iccp-prophoto | drawImage": {
|
||||
"kind": "image",
|
||||
"sha256": "4fab448b2199c831c15ec6ddfa4c923a73bcb5f67ec1893f53c8282525512b20",
|
||||
"bytes": 1024,
|
||||
"without_conversion_sha256": "c3637f042c01b44fd5c7ff59a5948695e9ea6e396056be7589e475c8a46f19a0"
|
||||
},
|
||||
"iccp-prophoto | drawImage_scaled32": {
|
||||
"kind": "image",
|
||||
"sha256": "367bc57e1fd774471cdcd1098335af3fb54d2c009c4a530aecc8806bfceb65f4",
|
||||
"bytes": 4096,
|
||||
"without_conversion_sha256": "840d2c6b5264364f23c63a33c21380797c61e40a75750e11a69266057d381298"
|
||||
},
|
||||
"iccp-prophoto | bitmap_default": {
|
||||
"kind": "image",
|
||||
"sha256": "4fab448b2199c831c15ec6ddfa4c923a73bcb5f67ec1893f53c8282525512b20",
|
||||
"bytes": 1024,
|
||||
"without_conversion_sha256": "c3637f042c01b44fd5c7ff59a5948695e9ea6e396056be7589e475c8a46f19a0"
|
||||
},
|
||||
"iccp-prophoto | bitmap_none": {
|
||||
"kind": "image",
|
||||
"sha256": "4408185fd170878816ebdc7412ecc36d75d53a02ff41a07f4f76c9042a531b73",
|
||||
"bytes": 1024
|
||||
},
|
||||
"iccp-rec2020 | drawImage": {
|
||||
"kind": "image",
|
||||
"sha256": "4d837ae68e7ef5039bc2cf88812ebbf7eae8624922191741d4157f697f3283db",
|
||||
"bytes": 1024,
|
||||
"without_conversion_sha256": "f6aca679f032c943db350b8a942dcb189e48ff097617f91441082c560ba76400"
|
||||
},
|
||||
"iccp-rec2020 | drawImage_scaled32": {
|
||||
"kind": "image",
|
||||
"sha256": "09fdec5e80bdff0cc09171bc2c627657484ec1c5cd390d86edc6cb8c3f9fb406",
|
||||
"bytes": 4096,
|
||||
"without_conversion_sha256": "2aa895aa06e8b06ed0fe9629a2ba97ed3fc3ec978d21a9f9871859784a96d38f"
|
||||
},
|
||||
"iccp-rec2020 | bitmap_default": {
|
||||
"kind": "image",
|
||||
"sha256": "4d837ae68e7ef5039bc2cf88812ebbf7eae8624922191741d4157f697f3283db",
|
||||
"bytes": 1024,
|
||||
"without_conversion_sha256": "f6aca679f032c943db350b8a942dcb189e48ff097617f91441082c560ba76400"
|
||||
},
|
||||
"iccp-rec2020 | bitmap_none": {
|
||||
"kind": "image",
|
||||
"sha256": "4408185fd170878816ebdc7412ecc36d75d53a02ff41a07f4f76c9042a531b73",
|
||||
"bytes": 1024
|
||||
},
|
||||
"iccp-srgb | drawImage": {
|
||||
"kind": "image",
|
||||
"sha256": "4408185fd170878816ebdc7412ecc36d75d53a02ff41a07f4f76c9042a531b73",
|
||||
"bytes": 1024,
|
||||
"without_conversion_sha256": "f0f7aa5f113b0409ec14f6ba894b5e7749d79b3cafd6ea9c88632c1f0a9dbbb7"
|
||||
},
|
||||
"iccp-srgb | drawImage_scaled32": {
|
||||
"kind": "image",
|
||||
"sha256": "464a7a31f6a336c88616ff1bd651e6d569287aaf9445891d65f30a5b3c019bc7",
|
||||
"bytes": 4096,
|
||||
"without_conversion_sha256": "96d26754fcd4e0c13ab72dd3e5f569eb49bed726de3da7b16bac7094f30a8d12"
|
||||
},
|
||||
"iccp-srgb | bitmap_default": {
|
||||
"kind": "image",
|
||||
"sha256": "4408185fd170878816ebdc7412ecc36d75d53a02ff41a07f4f76c9042a531b73",
|
||||
"bytes": 1024,
|
||||
"without_conversion_sha256": "f0f7aa5f113b0409ec14f6ba894b5e7749d79b3cafd6ea9c88632c1f0a9dbbb7"
|
||||
},
|
||||
"iccp-srgb | bitmap_none": {
|
||||
"kind": "image",
|
||||
"sha256": "4408185fd170878816ebdc7412ecc36d75d53a02ff41a07f4f76c9042a531b73",
|
||||
"bytes": 1024
|
||||
},
|
||||
"jpeg-icc-displayp3 | drawImage": {
|
||||
"kind": "image",
|
||||
"sha256": "782dc2e3d91cedc3bd985480e0575812f790ca5788fc116483baa4e551b04115",
|
||||
"bytes": 1024,
|
||||
"without_conversion_sha256": "4c3b8db4f93d8b0ba68891cd3fdb29627b762f594286811364ac7dbb182abb5c"
|
||||
},
|
||||
"jpeg-icc-displayp3 | drawImage_scaled32": {
|
||||
"kind": "image",
|
||||
"sha256": "760cb8015791f49de184209a7f9b7f0cdecf7ad6dd9f89701477f840af446291",
|
||||
"bytes": 4096,
|
||||
"without_conversion_sha256": "0d5bcd78f2230a685636cafb732109384b42064bd710631a57fe653554865f6f"
|
||||
},
|
||||
"jpeg-icc-displayp3 | bitmap_default": {
|
||||
"kind": "image",
|
||||
"sha256": "782dc2e3d91cedc3bd985480e0575812f790ca5788fc116483baa4e551b04115",
|
||||
"bytes": 1024,
|
||||
"without_conversion_sha256": "4c3b8db4f93d8b0ba68891cd3fdb29627b762f594286811364ac7dbb182abb5c"
|
||||
},
|
||||
"jpeg-icc-displayp3 | bitmap_none": {
|
||||
"kind": "image",
|
||||
"sha256": "1319eeadc9d1d109384f113e3fdcf6d66db169b5fd8ede666055b3e3da70f23c",
|
||||
"bytes": 1024
|
||||
},
|
||||
"srgb-chunk | drawImage": {
|
||||
"kind": "image",
|
||||
"sha256": "ff2033eebf547bf729b8ed5cde16e5cda42729f141aa2b2eaa2d693513d61542",
|
||||
"bytes": 1024,
|
||||
"without_conversion_sha256": "4408185fd170878816ebdc7412ecc36d75d53a02ff41a07f4f76c9042a531b73"
|
||||
},
|
||||
"srgb-chunk | drawImage_scaled32": {
|
||||
"kind": "image",
|
||||
"sha256": "4805ce9fad88c53aa5f9df7c5ec7352fdf55691377f4d00986c7e6b76dac9ac9",
|
||||
"bytes": 4096,
|
||||
"without_conversion_sha256": "464a7a31f6a336c88616ff1bd651e6d569287aaf9445891d65f30a5b3c019bc7"
|
||||
},
|
||||
"srgb-chunk | bitmap_default": {
|
||||
"kind": "image",
|
||||
"sha256": "ff2033eebf547bf729b8ed5cde16e5cda42729f141aa2b2eaa2d693513d61542",
|
||||
"bytes": 1024,
|
||||
"without_conversion_sha256": "4408185fd170878816ebdc7412ecc36d75d53a02ff41a07f4f76c9042a531b73"
|
||||
},
|
||||
"srgb-chunk | bitmap_none": {
|
||||
"kind": "image",
|
||||
"sha256": "4408185fd170878816ebdc7412ecc36d75d53a02ff41a07f4f76c9042a531b73",
|
||||
"bytes": 1024
|
||||
},
|
||||
"untagged | drawImage": {
|
||||
"kind": "image",
|
||||
"sha256": "4408185fd170878816ebdc7412ecc36d75d53a02ff41a07f4f76c9042a531b73",
|
||||
"bytes": 1024
|
||||
},
|
||||
"untagged | drawImage_scaled32": {
|
||||
"kind": "image",
|
||||
"sha256": "464a7a31f6a336c88616ff1bd651e6d569287aaf9445891d65f30a5b3c019bc7",
|
||||
"bytes": 4096
|
||||
},
|
||||
"untagged | bitmap_default": {
|
||||
"kind": "image",
|
||||
"sha256": "4408185fd170878816ebdc7412ecc36d75d53a02ff41a07f4f76c9042a531b73",
|
||||
"bytes": 1024
|
||||
},
|
||||
"untagged | bitmap_none": {
|
||||
"kind": "image",
|
||||
"sha256": "4408185fd170878816ebdc7412ecc36d75d53a02ff41a07f4f76c9042a531b73",
|
||||
"bytes": 1024
|
||||
},
|
||||
"fill | #336699": {
|
||||
"kind": "fill",
|
||||
"sha256": "071cae1acd9f38907222c770e611ba43fea0ade431c883ea8a88824e0aadd1c8",
|
||||
"bytes": 1024
|
||||
},
|
||||
"fill | color(a98-rgb 0.2 0.8 0.4)": {
|
||||
"kind": "fill",
|
||||
"sha256": "4258c9f7552305c497331032b1ca6413b1d1edd099e0d4ffef3a896be30531eb",
|
||||
"bytes": 1024
|
||||
},
|
||||
"fill | color(display-p3 0 1 0)": {
|
||||
"kind": "fill",
|
||||
"sha256": "0b3b4eba5c7d53beec5ac1aa3b64c56188bcbf52906e124e5ab3e77a96fdd9cd",
|
||||
"bytes": 1024
|
||||
},
|
||||
"fill | color(display-p3 0.2 0.8 0.4)": {
|
||||
"kind": "fill",
|
||||
"sha256": "290e0a38d91b939f45da0a3889e4398944bbd9e5cb89fed8fadb5479bdb65cd5",
|
||||
"bytes": 1024
|
||||
},
|
||||
"fill | color(display-p3 0.5 0.5 0.5)": {
|
||||
"kind": "fill",
|
||||
"sha256": "041338275ad973347712ad0ea33583ae668a01fbef9a12c2ebf0f6b227c1bc87",
|
||||
"bytes": 1024
|
||||
},
|
||||
"fill | color(display-p3 1 0 0)": {
|
||||
"kind": "fill",
|
||||
"sha256": "71205eb7a329a3ead670c77eee185c0fbeb612f7a2b3d6aadbe2af4f9276b60d",
|
||||
"bytes": 1024
|
||||
},
|
||||
"fill | color(prophoto-rgb 0.2 0.8 0.4)": {
|
||||
"kind": "fill",
|
||||
"sha256": "1c19bf5b233573459d494705c2ee42bd2d0238701eea614af76e28066dd2a836",
|
||||
"bytes": 1024
|
||||
},
|
||||
"fill | color(rec2020 0.2 0.8 0.4)": {
|
||||
"kind": "fill",
|
||||
"sha256": "6ca68d3ad37c475f5571e34aa0233cd2ebb710cac5d12375975a5fcadfd49cd4",
|
||||
"bytes": 1024
|
||||
},
|
||||
"fill | color(srgb 0.2 0.8 0.4)": {
|
||||
"kind": "fill",
|
||||
"sha256": "daed9ae3ff78acf0f758d2a4ddfad5e10f14a053f2718e7835fe3b535dabf3fb",
|
||||
"bytes": 1024
|
||||
},
|
||||
"fill | color(srgb 1 0 0)": {
|
||||
"kind": "fill",
|
||||
"sha256": "71205eb7a329a3ead670c77eee185c0fbeb612f7a2b3d6aadbe2af4f9276b60d",
|
||||
"bytes": 1024
|
||||
},
|
||||
"fill | color(xyz-d50 0.2 0.3 0.4)": {
|
||||
"kind": "fill",
|
||||
"sha256": "75fc3134903d2193aa029256f8b99c5d87cfbce7286ec890d3cf4d7477ee9947",
|
||||
"bytes": 1024
|
||||
},
|
||||
"fill | color(xyz-d65 0.2 0.3 0.4)": {
|
||||
"kind": "fill",
|
||||
"sha256": "966ab57aae3025be30c2452c1cc49b3e5b6711f9eb43259ffa0555db58084602",
|
||||
"bytes": 1024
|
||||
},
|
||||
"fill | color-mix(in display-p3, color(display-p3 1 0 0) 30%, blue)": {
|
||||
"kind": "fill",
|
||||
"sha256": "58b694deea5f11273f95ffd037423b17bc813bda6b6ea82888f9892e6528a5b0",
|
||||
"bytes": 1024
|
||||
},
|
||||
"fill | color-mix(in oklab, red 30%, blue)": {
|
||||
"kind": "fill",
|
||||
"sha256": "699525471658eda7a99f26181e44841d8a8202443fad2500bae3f1b4e1a8158a",
|
||||
"bytes": 1024
|
||||
},
|
||||
"fill | color-mix(in oklch, #336699 40%, #cc9933)": {
|
||||
"kind": "fill",
|
||||
"sha256": "d35dbf1963cff18033cc64d1991a01072b16cf2e757fbc3a1800b9319470d1f0",
|
||||
"bytes": 1024
|
||||
},
|
||||
"fill | color-mix(in srgb, red 30%, blue)": {
|
||||
"kind": "fill",
|
||||
"sha256": "5f173ac28e4f26e1f70d6cac12adcd59707692664770315983ecbe9eff88458b",
|
||||
"bytes": 1024
|
||||
},
|
||||
"fill | hsl(200 60% 40%)": {
|
||||
"kind": "fill",
|
||||
"sha256": "e9ae94390dabacc90a2fde5f91884eba10d5fc4cf5f1aa80a0978c36b5a8e2c7",
|
||||
"bytes": 1024
|
||||
},
|
||||
"fill | lab(60 40 -30)": {
|
||||
"kind": "fill",
|
||||
"sha256": "12d7c045adeb8a76347d3fd4261593c8b80d97b1dbf55f265991037a4adac6b0",
|
||||
"bytes": 1024
|
||||
},
|
||||
"fill | lch(60 40 200)": {
|
||||
"kind": "fill",
|
||||
"sha256": "8063e38ed7df66e53b13ea08a949685f03e51847f7794ec9bfbb32c45bd8e10e",
|
||||
"bytes": 1024
|
||||
},
|
||||
"fill | oklab(0.6 0.1 -0.1)": {
|
||||
"kind": "fill",
|
||||
"sha256": "ec97eed8fc2beb419339539ee9687a9bee6a2126db047e813d3ab91570a4d7ce",
|
||||
"bytes": 1024
|
||||
},
|
||||
"fill | oklch(0.7 0.15 150)": {
|
||||
"kind": "fill",
|
||||
"sha256": "f256508187ad893812958b37b75d739a131acf40ecf8f1a54f98fc2daf615624",
|
||||
"bytes": 1024
|
||||
},
|
||||
"fill | rgba(51,102,153,0.5)": {
|
||||
"kind": "fill",
|
||||
"sha256": "d57f26dd3a6a96762190a7fcc95bb813d10e6332a6b762aba3057d108930c62c",
|
||||
"bytes": 1024
|
||||
},
|
||||
"canvas colorSpace p3 fill": {
|
||||
"kind": "colorspace",
|
||||
"sha256": "71205eb7a329a3ead670c77eee185c0fbeb612f7a2b3d6aadbe2af4f9276b60d",
|
||||
"bytes": 1024
|
||||
},
|
||||
"env | color-gamut:p3": {
|
||||
"kind": "env",
|
||||
"sha256": "fcbcf165908dd18a9e49f7ff27810176db8e9f63b4352213741664245224f8aa",
|
||||
"value": false
|
||||
},
|
||||
"env | color-gamut:rec2020": {
|
||||
"kind": "env",
|
||||
"sha256": "fcbcf165908dd18a9e49f7ff27810176db8e9f63b4352213741664245224f8aa",
|
||||
"value": false
|
||||
},
|
||||
"env | color-gamut:srgb": {
|
||||
"kind": "env",
|
||||
"sha256": "b5bea41b6c623f7c09f1bf24dcae58ebab3c0cdd90ad966bc43a45b44867e12b",
|
||||
"value": true
|
||||
},
|
||||
"env | colorDepth": {
|
||||
"kind": "env",
|
||||
"sha256": "c2356069e9d1e79ca924378153cfbbfb4d4416b1f99d41a2940bfdb66c5319db",
|
||||
"value": 24
|
||||
},
|
||||
"env | devicePixelRatio": {
|
||||
"kind": "env",
|
||||
"sha256": "6b86b273ff34fce19d6b804eff5a3f5747ada4eaa22f1d49c01e52ddb7875b4b",
|
||||
"value": 1
|
||||
},
|
||||
"env | dynamic-range:high": {
|
||||
"kind": "env",
|
||||
"sha256": "fcbcf165908dd18a9e49f7ff27810176db8e9f63b4352213741664245224f8aa",
|
||||
"value": false
|
||||
},
|
||||
"env | pixelDepth": {
|
||||
"kind": "env",
|
||||
"sha256": "c2356069e9d1e79ca924378153cfbbfb4d4416b1f99d41a2940bfdb66c5319db",
|
||||
"value": 24
|
||||
},
|
||||
"env | prefers-color-scheme:dark": {
|
||||
"kind": "env",
|
||||
"sha256": "b5bea41b6c623f7c09f1bf24dcae58ebab3c0cdd90ad966bc43a45b44867e12b",
|
||||
"value": true,
|
||||
"compared": false
|
||||
},
|
||||
"env | video-dynamic-range:high": {
|
||||
"kind": "env",
|
||||
"sha256": "fcbcf165908dd18a9e49f7ff27810176db8e9f63b4352213741664245224f8aa",
|
||||
"value": false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>canvas text ref</title>
|
||||
<style>
|
||||
@font-face{font-family:"Arial";src:url("bundle/arial7_04.ttf") format("truetype");font-weight:400;font-style:normal}
|
||||
@font-face{font-family:"Segoe UI";src:url("bundle/segoeui5_67.ttf") format("truetype");font-weight:400;font-style:normal}
|
||||
@font-face{font-family:"Times New Roman";src:url("bundle/times7_11.ttf") format("truetype");font-weight:400;font-style:normal}
|
||||
@font-face{font-family:"Consolas";src:url("bundle/consola7_00.ttf") format("truetype");font-weight:400;font-style:normal}
|
||||
@font-face{font-family:"Calibri";src:url("bundle/calibri6_26.ttf") format("truetype");font-weight:400;font-style:normal}
|
||||
@font-face{font-family:"Bahnschrift";src:url("bundle/bahnschrift2_07.ttf") format("truetype");font-weight:300 700;font-stretch:75% 100%;font-style:normal}
|
||||
@font-face{font-family:"Segoe UI Variable";src:url("bundle/seguivar2_03.ttf") format("truetype");font-weight:300 700;font-style:normal}
|
||||
@font-face{font-family:"Twemoji Mozilla";src:url("bundle/TwemojiMozilla.ttf") format("truetype");font-weight:400;font-style:normal}
|
||||
body{margin:16px;background:#fff;color:#000;font:13px sans-serif}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<p id="status">loading fonts</p>
|
||||
<script>
|
||||
// Canvas 2D text reference page. Every case draws TEXT (or EMOJI) on a white canvas, reads the
|
||||
// pixels back with getImageData and hashes the RGBA bytes with SHA-256. Fonts are loaded
|
||||
// before anything is measured or drawn. The case ids and the drawing code are the ones retail
|
||||
// Firefox 159.0 on Windows ran to write refs.json, so the hashes compare.
|
||||
const FAMILIES5 = ["Arial", "Segoe UI", "Times New Roman", "Consolas", "Calibri"];
|
||||
const SIZES6 = [9, 12.5, 16, 33, 72, 300];
|
||||
const SIZES5 = [9, 12.5, 16, 33, 72];
|
||||
const TEXT = "Hamburgefonstiv 0123";
|
||||
const EMOJI = "\u{1F600}\u{1F389}\u{1F41F}";
|
||||
const ROT = "rot15-scale1.5x2";
|
||||
const TRANSFORMS = ["none", ROT];
|
||||
|
||||
const SPECS = [];
|
||||
const SEEN = new Set();
|
||||
function add(sp) {
|
||||
sp.style = sp.style || "normal";
|
||||
sp.weight = sp.weight || "normal";
|
||||
sp.stretch = sp.stretch || "";
|
||||
sp.op = sp.op || "fill";
|
||||
sp.transform = sp.transform || "none";
|
||||
sp.alpha = sp.alpha !== false;
|
||||
sp.text = sp.text || TEXT;
|
||||
let id = [sp.family, sp.size, sp.transform, sp.style, sp.weight, sp.op].join("|");
|
||||
if (sp.stretch) id += "|stretch=" + sp.stretch;
|
||||
if (!sp.alpha) id += "|alpha=false";
|
||||
if (sp.text !== TEXT) id += "|text=emoji";
|
||||
if (SEEN.has(id)) throw new Error("duplicate case id: " + id);
|
||||
SEEN.add(id);
|
||||
sp.id = id;
|
||||
SPECS.push(sp);
|
||||
}
|
||||
|
||||
// 0) base: fillText and strokeText, with and without a transform; synthetic italic and bold
|
||||
// on a regular face (fillText). Default canvas (alpha: true).
|
||||
for (const family of FAMILIES5) for (const size of SIZES6) for (const transform of TRANSFORMS) for (const op of ["fill", "stroke"])
|
||||
add({family, size, transform, op});
|
||||
for (const family of FAMILIES5) for (const size of SIZES6) for (const transform of TRANSFORMS) for (const syn of ["italic", "bold"])
|
||||
add({family, size, transform, style: syn === "italic" ? "italic" : "normal", weight: syn === "bold" ? "bold" : "normal"});
|
||||
|
||||
// 1) getContext("2d", {alpha: false}): an opaque canvas, where LCD text is possible
|
||||
for (const f of FAMILIES5) for (const s of SIZES5)
|
||||
add({family: f, size: s, alpha: false});
|
||||
|
||||
// 2) rotate(15deg) scale(1.5, 2) on an opaque canvas. The same cases with alpha: true are in
|
||||
// the base above (group 2a of the reference), so they are not drawn twice.
|
||||
for (const f of FAMILIES5) for (const s of SIZES5)
|
||||
add({family: f, size: s, transform: ROT, alpha: false});
|
||||
|
||||
// 3) COLR v0 emoji (Twemoji Mozilla), the one COLR v0 face of the bundle
|
||||
for (const s of [16, 33, 72]) for (const alpha of [true, false]) for (const transform of TRANSFORMS)
|
||||
add({family: "Twemoji Mozilla", size: s, transform, alpha, text: EMOJI});
|
||||
|
||||
// 4) past the glyph-size thresholds (255, 256, 257, 400 px; 300 px is in the base): fillText
|
||||
// and strokeText, Arial and Segoe UI
|
||||
for (const f of ["Arial", "Segoe UI"]) for (const s of [255, 256, 257, 400]) for (const op of ["fill", "stroke"])
|
||||
add({family: f, size: s, op});
|
||||
|
||||
// 5) the variable face Bahnschrift: weight (300, 400, 700) by stretch (75% = condensed, 100% = normal);
|
||||
// canvas has no font-variation-settings, so the axes are reached through font-weight and font-stretch
|
||||
for (const w of [300, 400, 700]) for (const st of ["condensed", "normal"]) for (const s of [16, 33])
|
||||
add({family: "Bahnschrift", size: s, weight: w, stretch: st});
|
||||
|
||||
// 6) the variable face Segoe UI Variable (wght 300-700, opsz 5-36): weight 300, 400 and 700 at four
|
||||
// sizes. font-optical-sizing is auto, so opsz follows the size; the weight reaches the face
|
||||
// through font-weight, as canvas has no font-variation-settings
|
||||
for (const w of [300, 400, 700]) for (const s of [9, 12.5, 16, 33])
|
||||
add({family: "Segoe UI Variable", size: s, weight: w});
|
||||
|
||||
const fontCss = sp => [sp.style, sp.weight, sp.stretch, sp.size + "px", '"' + sp.family + '"'].filter(Boolean).join(" ");
|
||||
const hex = buf => [...new Uint8Array(buf)].map(b => b.toString(16).padStart(2, "0")).join("");
|
||||
|
||||
function measure(sp) {
|
||||
const ctx = document.createElement("canvas").getContext("2d");
|
||||
ctx.font = fontCss(sp);
|
||||
return ctx.measureText(sp.text).width;
|
||||
}
|
||||
|
||||
async function drawCase(sp) {
|
||||
const m = measure(sp), S = sp.size;
|
||||
const W = Math.ceil(1.6 * m + 3 * S) + 80;
|
||||
const H = Math.ceil(4 * S + 0.42 * m) + 80;
|
||||
const c = document.createElement("canvas");
|
||||
c.width = W; c.height = H;
|
||||
const ctx = c.getContext("2d", {alpha: sp.alpha, willReadFrequently: true});
|
||||
ctx.fillStyle = "#fff"; ctx.fillRect(0, 0, W, H);
|
||||
ctx.fillStyle = "#000"; ctx.strokeStyle = "#000"; ctx.lineWidth = 1;
|
||||
ctx.font = fontCss(sp);
|
||||
ctx.textAlign = "start"; ctx.textBaseline = "alphabetic";
|
||||
const y0 = Math.ceil(2.5 * S) + 40;
|
||||
let x = 40, y = y0;
|
||||
if (sp.transform !== "none") {
|
||||
ctx.translate(40, y0);
|
||||
ctx.rotate(15 * Math.PI / 180);
|
||||
ctx.scale(1.5, 2);
|
||||
x = 0; y = 0;
|
||||
}
|
||||
if (sp.op === "stroke") ctx.strokeText(sp.text, x, y); else ctx.fillText(sp.text, x, y);
|
||||
const readback = ctx.font;
|
||||
let img = ctx.getImageData(0, 0, W, H);
|
||||
const digest = await crypto.subtle.digest("SHA-256", img.data.buffer);
|
||||
// The largest cases are 7727 x 3373 (100 MB of RGBA): release the canvas and its readback
|
||||
// before the next case, so that the page never holds more than one at a time.
|
||||
img = null;
|
||||
c.width = 0; c.height = 0;
|
||||
return {id: sp.id, family: sp.family, size: sp.size, transform: sp.transform,
|
||||
style: sp.style, weight: String(sp.weight), stretch: sp.stretch || "normal", op: sp.op,
|
||||
alpha: sp.alpha, text: sp.text === TEXT ? "TEXT" : "EMOJI", font_readback: readback,
|
||||
width: W, height: H, measured_width: m, sha256: hex(digest)};
|
||||
}
|
||||
|
||||
(async () => {
|
||||
const st = document.getElementById("status");
|
||||
try {
|
||||
const LOADS = ['16px "Arial"', '16px "Segoe UI"', '16px "Times New Roman"', '16px "Consolas"',
|
||||
'16px "Calibri"', '300 condensed 16px "Bahnschrift"', '300 normal 16px "Bahnschrift"',
|
||||
'400 normal 16px "Bahnschrift"', '700 normal 16px "Bahnschrift"', '300 16px "Segoe UI Variable"',
|
||||
'400 16px "Segoe UI Variable"', '700 16px "Segoe UI Variable"', '16px "Twemoji Mozilla"'];
|
||||
window.FONTS = {};
|
||||
for (const q of LOADS) {
|
||||
const r = await document.fonts.load(q);
|
||||
window.FONTS[q] = r.map(x => x.status);
|
||||
if (!r.length || r.some(x => x.status !== "loaded")) throw new Error("font not loaded: " + q);
|
||||
}
|
||||
window.R = {};
|
||||
for (const sp of SPECS) {
|
||||
window.R[sp.id] = await drawCase(sp);
|
||||
window.PROGRESS = Object.keys(window.R).length;
|
||||
st.textContent = `cases: ${window.PROGRESS}/${SPECS.length}`;
|
||||
}
|
||||
window.CASE_COUNT = SPECS.length;
|
||||
st.textContent = `done: ${SPECS.length} cases`;
|
||||
window.DONE = true;
|
||||
} catch (e) {
|
||||
window.ERR = String(e);
|
||||
st.textContent = "error: " + e;
|
||||
}
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,151 @@
|
||||
{
|
||||
"fonts": {
|
||||
"menu": {
|
||||
"family": "Segoe UI",
|
||||
"size": "12px",
|
||||
"weight": "400",
|
||||
"style": "normal",
|
||||
"stretch": "100%"
|
||||
},
|
||||
"caption": {
|
||||
"family": "Segoe UI",
|
||||
"size": "12px",
|
||||
"weight": "400",
|
||||
"style": "normal",
|
||||
"stretch": "100%"
|
||||
},
|
||||
"icon": {
|
||||
"family": "Segoe UI",
|
||||
"size": "12px",
|
||||
"weight": "400",
|
||||
"style": "normal",
|
||||
"stretch": "100%"
|
||||
},
|
||||
"message-box": {
|
||||
"family": "Segoe UI",
|
||||
"size": "12px",
|
||||
"weight": "400",
|
||||
"style": "normal",
|
||||
"stretch": "100%"
|
||||
},
|
||||
"small-caption": {
|
||||
"family": "Segoe UI",
|
||||
"size": "12px",
|
||||
"weight": "400",
|
||||
"style": "normal",
|
||||
"stretch": "100%"
|
||||
},
|
||||
"status-bar": {
|
||||
"family": "Segoe UI",
|
||||
"size": "12px",
|
||||
"weight": "400",
|
||||
"style": "normal",
|
||||
"stretch": "100%"
|
||||
},
|
||||
"system-ui": {
|
||||
"family": "system-ui",
|
||||
"size": "16px",
|
||||
"weight": "400",
|
||||
"style": "normal",
|
||||
"stretch": "100%"
|
||||
}
|
||||
},
|
||||
"light": {
|
||||
"Canvas": "rgb(255, 255, 255)",
|
||||
"CanvasText": "rgb(0, 0, 0)",
|
||||
"LinkText": "rgb(0, 0, 238)",
|
||||
"VisitedText": "rgb(85, 26, 139)",
|
||||
"ActiveText": "rgb(238, 0, 0)",
|
||||
"ButtonFace": "rgb(233, 233, 237)",
|
||||
"ButtonText": "rgb(0, 0, 0)",
|
||||
"ButtonBorder": "rgb(129, 127, 132)",
|
||||
"Field": "rgb(255, 255, 255)",
|
||||
"FieldText": "rgb(0, 0, 0)",
|
||||
"GrayText": "rgb(109, 109, 109)",
|
||||
"Highlight": "rgb(0, 120, 212)",
|
||||
"HighlightText": "rgb(255, 255, 255)",
|
||||
"Mark": "rgb(255, 255, 0)",
|
||||
"MarkText": "rgb(0, 0, 0)",
|
||||
"SelectedItem": "rgb(0, 120, 212)",
|
||||
"SelectedItemText": "rgb(255, 255, 255)",
|
||||
"AccentColor": "rgb(0, 96, 223)",
|
||||
"AccentColorText": "rgb(255, 255, 255)",
|
||||
"ActiveBorder": "rgb(129, 127, 132)",
|
||||
"ActiveCaption": "rgb(255, 255, 255)",
|
||||
"AppWorkspace": "rgb(255, 255, 255)",
|
||||
"Background": "rgb(255, 255, 255)",
|
||||
"ButtonHighlight": "rgb(233, 233, 237)",
|
||||
"ButtonShadow": "rgb(233, 233, 237)",
|
||||
"CaptionText": "rgb(0, 0, 0)",
|
||||
"InactiveBorder": "rgb(129, 127, 132)",
|
||||
"InactiveCaption": "rgb(255, 255, 255)",
|
||||
"InactiveCaptionText": "rgb(109, 109, 109)",
|
||||
"InfoBackground": "rgb(255, 255, 255)",
|
||||
"InfoText": "rgb(0, 0, 0)",
|
||||
"Menu": "rgb(255, 255, 255)",
|
||||
"MenuText": "rgb(0, 0, 0)",
|
||||
"Scrollbar": "rgb(255, 255, 255)",
|
||||
"ThreeDDarkShadow": "rgb(129, 127, 132)",
|
||||
"ThreeDFace": "rgb(233, 233, 237)",
|
||||
"ThreeDHighlight": "rgb(129, 127, 132)",
|
||||
"ThreeDLightShadow": "rgb(129, 127, 132)",
|
||||
"ThreeDShadow": "rgb(129, 127, 132)",
|
||||
"Window": "rgb(255, 255, 255)",
|
||||
"WindowFrame": "rgb(129, 127, 132)",
|
||||
"WindowText": "rgb(0, 0, 0)"
|
||||
},
|
||||
"dark": {
|
||||
"Canvas": "rgb(28, 27, 34)",
|
||||
"CanvasText": "rgb(251, 251, 254)",
|
||||
"LinkText": "rgb(0, 202, 219)",
|
||||
"VisitedText": "rgb(255, 173, 255)",
|
||||
"ActiveText": "rgb(255, 102, 102)",
|
||||
"ButtonFace": "rgb(43, 42, 51)",
|
||||
"ButtonText": "rgb(251, 251, 254)",
|
||||
"ButtonBorder": "rgb(148, 146, 151)",
|
||||
"Field": "rgb(43, 42, 51)",
|
||||
"FieldText": "rgb(251, 251, 254)",
|
||||
"GrayText": "rgb(117, 116, 122)",
|
||||
"Highlight": "rgba(0, 221, 255, 0.306)",
|
||||
"HighlightText": "rgb(0, 0, 0)",
|
||||
"Mark": "rgb(255, 255, 0)",
|
||||
"MarkText": "rgb(0, 0, 0)",
|
||||
"SelectedItem": "rgb(0, 221, 255)",
|
||||
"SelectedItemText": "rgb(43, 42, 51)",
|
||||
"AccentColor": "rgb(0, 96, 223)",
|
||||
"AccentColorText": "rgb(255, 255, 255)",
|
||||
"ActiveBorder": "rgb(57, 57, 57)",
|
||||
"ActiveCaption": "rgb(28, 27, 34)",
|
||||
"AppWorkspace": "rgb(28, 27, 34)",
|
||||
"Background": "rgb(28, 27, 34)",
|
||||
"ButtonHighlight": "rgb(43, 42, 51)",
|
||||
"ButtonShadow": "rgb(43, 42, 51)",
|
||||
"CaptionText": "rgb(251, 251, 254)",
|
||||
"InactiveBorder": "rgb(57, 57, 57)",
|
||||
"InactiveCaption": "rgb(28, 27, 34)",
|
||||
"InactiveCaptionText": "rgb(251, 251, 254)",
|
||||
"InfoBackground": "rgb(28, 27, 34)",
|
||||
"InfoText": "rgb(251, 251, 254)",
|
||||
"Menu": "rgb(43, 42, 51)",
|
||||
"MenuText": "rgb(251, 251, 254)",
|
||||
"Scrollbar": "rgb(28, 27, 34)",
|
||||
"ThreeDDarkShadow": "rgb(34, 33, 40)",
|
||||
"ThreeDFace": "rgb(43, 42, 51)",
|
||||
"ThreeDHighlight": "rgb(148, 146, 151)",
|
||||
"ThreeDLightShadow": "rgb(148, 146, 151)",
|
||||
"ThreeDShadow": "rgb(148, 146, 151)",
|
||||
"Window": "rgb(28, 27, 34)",
|
||||
"WindowFrame": "rgb(117, 116, 122)",
|
||||
"WindowText": "rgb(251, 251, 254)"
|
||||
},
|
||||
"selection": {
|
||||
"light": {
|
||||
"color": "rgb(0, 0, 0)",
|
||||
"bg": "rgba(0, 0, 0, 0)"
|
||||
},
|
||||
"dark": {
|
||||
"color": "rgb(0, 0, 0)",
|
||||
"bg": "rgba(0, 0, 0, 0)"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
# Expected text of getComputedStyle for calc(1px * f(args)) (word-spacing)
|
||||
# and of rotate: f(args) for the angle functions, from ucrtbase.dll's f32
|
||||
# functions. Generated by scripts/ucrt_css_calc.py (python -I) - do not edit.
|
||||
# <fn> <args...> <text on Windows>
|
||||
sin -12.2958984375 0.267186px
|
||||
sin -3.3349609375 0.192165px
|
||||
sin -8.728515625 -0.641354px
|
||||
sin -9.603515625 0.177787px
|
||||
sin 2.6865234375 0.439525px
|
||||
sin 5.9267578125 -0.348928px
|
||||
sin -15.998046875 0.286032px
|
||||
sin 0 0px
|
||||
sin 15.9970703125 -0.285096px
|
||||
cos -10.3515625 -0.600409px
|
||||
cos -2.0146484375 -0.429422px
|
||||
cos -3.9794921875 -0.669025px
|
||||
cos 10.3515625 -0.600409px
|
||||
cos 2.0146484375 -0.429422px
|
||||
cos 3.9794921875 -0.669025px
|
||||
cos -16 -0.95766px
|
||||
cos 0 1px
|
||||
cos 15.9990234375 -0.95794px
|
||||
tan -2 2.18504px
|
||||
tan 0 0px
|
||||
tan 16 0.300632px
|
||||
asin -0.27099609375 -15.7235deg
|
||||
asin -0.6416015625 -39.9114deg
|
||||
asin -0.859619140625 -59.2738deg
|
||||
asin -0.982421875 -79.2413deg
|
||||
asin 0.59423828125 36.4583deg
|
||||
asin 0.751953125 48.7598deg
|
||||
asin -0.4990234375 -29.9354deg
|
||||
asin -1 -90deg
|
||||
asin 0.49853515625 29.9031deg
|
||||
acos -0.61669921875 128.076deg
|
||||
acos 0.499267578125 60.0484deg
|
||||
acos 0.615234375 52.031deg
|
||||
acos -0.5 120deg
|
||||
acos -1 180deg
|
||||
acos 0.499755859375 60.0161deg
|
||||
atan -4.000244140625 -75.9646deg
|
||||
atan 0 0deg
|
||||
atan 4 75.9638deg
|
||||
atan2 -1.125 1.890625 -30.7544deg
|
||||
atan2 0 0.015625 0deg
|
||||
atan2 1.125 -1.90625 149.452deg
|
||||
exp -2.1875 0.112197px
|
||||
exp 0 1px
|
||||
exp 2.187255859375 8.91073px
|
||||
log 1.0966796875 0.0922872px
|
||||
log 24.4873046875 3.19816px
|
||||
log 31.2861328125 3.44317px
|
||||
log 16.7880859375 2.82067px
|
||||
log 24.5703125 3.20154px
|
||||
log 35.609375 3.57261px
|
||||
pow 1.125 -1.5 0.838052px
|
||||
pow 4.4375 4 387.751px
|
||||
pow 12.1875 -2.0625 0.00575839px
|
||||
pow 2.0625 -4 0.0552617px
|
||||
pow 6 1.9375 32.1861px
|
||||
hypot -3.1875 -5 5.9296px
|
||||
hypot 0 0 0px
|
||||
hypot 3 4.6875 5.56531px
|
||||
File diff suppressed because it is too large.
Load diff
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,110 @@
|
||||
{
|
||||
"source": "C:/ff/invisible_WebCodecs/captures/h264-1080p-bframes/retail-win/result.json",
|
||||
"source_meta": "C:/ff/invisible_WebCodecs/captures/h264-1080p-bframes/retail-win/meta.json",
|
||||
"browser": "ff159-win-1080p",
|
||||
"codecString": "avc3.640028",
|
||||
"codedWidth": 1920,
|
||||
"codedHeight": 1080,
|
||||
"frameCount": 96,
|
||||
"frameDurationUs": 41667,
|
||||
"rgbaAllocationSize": 8294400,
|
||||
"rgbaFormat": "RGBA",
|
||||
"rgbaSha256ByIndex": [
|
||||
"ec86f786dfd4fb31be388382b7132df8f692c166f0398047454bbef38abf280c",
|
||||
"612a924786de8460f6ebcd5893921a8ae04fb41b441cd9f0087cf6183fb960a9",
|
||||
"e9aa87d893e542f53c3900fcd37f7a9ad40bc89b5e456d4a6ae73f142df04759",
|
||||
"441e299f66fca23ff0716ebb32982f919558967fbaa4bf877040e8e0e41f67f7",
|
||||
"c9b54bf73bc6d87c90196e128ee21aa5ae8c855d8474b1a967fbf6ba2110e22b",
|
||||
"2ab4b1709f2f049541095d386e7cd7297e3ebe1503d120d1138ca61d74a1b8af",
|
||||
"8fa4df13e422b44d585ba7413be439069b7911b7be4916aa6f338821be6665fc",
|
||||
"ce2e7286c19a9c461342c439ccdc31a8573f50dd9318dc836ba8adbc1c6f8958",
|
||||
"b64915b1f2d8fbb9795002736543baaf65339458c8ff204c370f78e1a0ff4da1",
|
||||
"ae82fff8551a99dee31cdda4fb1154b58382cf6e9d6a275b320b35db14fb47fe",
|
||||
"bbcc0181e5beeb699abfd810f2598e66d8f151b5e2712b030b9b8d8506cd9f64",
|
||||
"2b52fcb494ae4b3fa8bc4f7c66da19cf3816c4928c2861ca807f079a835c69dd",
|
||||
"6eeb0e0293a7447ea85227a04fba74b72f4b16573ddb457f4f7ec0b96a05a5dc",
|
||||
"8c3dc83cd33c5411cdba6123cfb62ee8c53fe181a325b4abb450ce7afb9edfa7",
|
||||
"d4d9297594c0af1c331c6d403cb78bedfcf33d82707f06873b48155287f33139",
|
||||
"f01b715b011494cf2bf5f97212507d07a48a00282ce8d2bd4afd8f76aa8f4f65",
|
||||
"976790562ae138a42395663d66d8fb987b83e1cc40b067821f3d438fe496765a",
|
||||
"5896a442951c90479e6093ee92fc51b00734c8fafe84061c6ad2988c5c9719ce",
|
||||
"dc84a9c2e608daf77ee25c881d0df69f9ddf6715b07b8eba3cbbfaaa692f4aa2",
|
||||
"98dc9edd09bf0ce330fdc8eafa675f509adccd92e21b231f4d82b67e0448b172",
|
||||
"1cc5bcb92c1947231e63a034675233933928d318962cca2598631dda4ea0398d",
|
||||
"7851d124d7665bbc63decfde6035775bc29b7fc9466513789cafd7db49c9fb03",
|
||||
"d00140e72758644c62ea0be72ff6d6371b27b1a8e488bb30b43931501def5719",
|
||||
"3fa367ee394ed399a41f60d4b0fc9a9a93c36daffb8da37d44a09999a88c8929",
|
||||
"b724e7bdd2e08efd665aeb1d088bdb6fa860c80d0e1c810f4b60e017d75b4060",
|
||||
"26920b0129c66dcc1f5df0832f7a7fa5dec50e7b0841c4bf4cbf75d886b1bd14",
|
||||
"bea97dc4d9550ab244ca648458c46cca3a8c278488e9add218af26fc37caf96e",
|
||||
"330907a28b53c8d1f97e854c827960c7a1da7fd8460694a1a145ae9bdd90a48b",
|
||||
"ac7bd746456764639eea4bb43b5d60502ee3b18cc7e7266a62960b2b1f21a3bd",
|
||||
"9797886bc01f7ab73470850cc79fe21541e286dab9f818a73e7b0f1d5f8ab838",
|
||||
"017db98229f47489c899fcedcb41c3fdace8d00adbf2c828a930eeac0adc9d3a",
|
||||
"2258e361a2762ded437a2d3b0793670d790d4e829d406f5a1c26c04d9b3272b2",
|
||||
"07ea8b535e731f51cb197015e82ebdd1b61ceff43397df94959c3bf4244bfdb8",
|
||||
"37e0a701d67c6a06b81783e27f0646071a788f0820d0d8a27d206a0e5e1bab87",
|
||||
"9e9c465245061255dea8f3e4263e500ddd96ae6555a2935771688572aa57904e",
|
||||
"ca8696c5c343ab883ee48998b20fdede0ea89da43921ce6aa010988091ad7ffe",
|
||||
"37c760b0eafc7f9b58f43cff84ff5ea4297085645a96b5b089ace4bed6579654",
|
||||
"306bd7874a05f7ee13a1977a677a901d9a803cc63a5ef51234cd09f4343b2578",
|
||||
"9e862bd1ef856d4d6e897f765b3a34405a2b33f08748135fa49782b36ebd018e",
|
||||
"9bdf82e391f7a415200b564cdb41e30b1d79e8550aaa2e100d0c93214dd02f84",
|
||||
"c58f9d86f624efcbae62ee01cadf7f1b974a9a0d1741c5a5add3d4baa4d54a57",
|
||||
"a41205a558148bc2c24c25d3f08abec0eb76371ac071cddba1a0b74f0b00b2d5",
|
||||
"8799abc56859269cc034e87b4c795b7c756db289b66d4944843bd88d44bcee0f",
|
||||
"ccfd5404af0d7ee5866e65ad1d420152be2591a339bb8cbfc8946f5789c5d46e",
|
||||
"ea56bed52ff1544be1fa04010a8a6d50c3beb9b249bd125b253006798c9c146e",
|
||||
"9f5c23b53933d5f52430f6c8d2e20b501e4747517856ee6f9e42b3c2ab3dfd93",
|
||||
"13c6283059d08e83b7a3e2823887746105c8161df2c43172a21ce81d73bf8e94",
|
||||
"62e109d54a8359628072dbd611f7c7d86a4aeb24093a79bd5e62a6212946f058",
|
||||
"00d37fb6a8bd4746bdee78fd703dbc21d571d281d270b90d315f47f807a9c8f7",
|
||||
"72b5749554816682dfb490f9a6e84c031fb257e066257de5ca38f9e61d8336e3",
|
||||
"5f736aae1dc7165be27fcbcde0424a7e81efe6ba23ea3b9ff18fe33e85edeadf",
|
||||
"82e781edecfed6f8cff7217aa7bb9843cfa050223670313f53439e5bb1cd581d",
|
||||
"2a7c33ab17ae5b68ddb6ab18157e29cd3146c170d638747d9f850bf820a0c106",
|
||||
"54638e8b4dd3721bd5e1b6ebb92d0d6269d7b3d1bb532f754860d0496657aca5",
|
||||
"f609d30438dc792107ed97d1040d5ab51d6dcf74b023429eb4cb7b687058fe44",
|
||||
"f4416eccaa2b90b2b28907dfc4560e63a4880c5c627cbf24225d68d17e3bad0d",
|
||||
"27ba6138b23ce0c3979de1943b282cbafff52a212db9665833bfefc22e1cd6a9",
|
||||
"7d3cd0fe51defbe28fac6447250b2c57614046739fb5fb9704d191470a88b629",
|
||||
"3d34c42f7038328efcffd83f12448f79d1b601aee0bb5aa9559a161715309b6e",
|
||||
"da3253068d029fcc47026cd1698316c65e9b8e30f1c33cea367e4af87569309b",
|
||||
"5b7ca1d07a9185644749ca361db6faa04b2c2fa7b6e23eba0d5e824e2294f4d3",
|
||||
"82522459c674f01cfeacc600ebbb5cffeabcd371613f5632f5c496c4018057f9",
|
||||
"72dc38d3ea4c917495c4c7eaa34f372d90dbedb9e41b6c6d2fd14649bcde3f11",
|
||||
"b6fa4a96d2aa0be036845b6180c8cbd03cf0e37f8f68cee4f13972bd29ba5dcc",
|
||||
"e4ddf2cdc4a372df492d9a3babd06b2e2e8eb3ff0f065332b066f54bf801718e",
|
||||
"7feaf1dc3f234c715e107461be06c7952c497374ad6feb1f352de690a62b5f8d",
|
||||
"edcd3c7d093d2e0bfeefaedd493c4f7bd8a2a13733b072c9c009308e45830dcb",
|
||||
"a5be7f4f6ae2aa30f391de192f89e83a2f494f0b0a29c9d4c25072e7cdbd4e8c",
|
||||
"a85212783e0614f7191cb6ea96361fd136be9afaa74c2dfe011f2a02b51acade",
|
||||
"bd3f233278c255bb4ef6cb83f2b2a3dd7daf8788aedb4f37db893ed2eb233055",
|
||||
"da0646ae2080593fe95ad475e9f88a61aaa5c67f45c88db1159afc6c808a395e",
|
||||
"635d187d98ca46b0916f83a3cb8c5e306c87519b0d97efd0b3a053be10726cae",
|
||||
"493463e004d5e760427057f25a9309dd1a7ccd8db7ff678385c0956a0df4ed6b",
|
||||
"f551dad30b92a9dc572768ec8b7d5cfdea6cbdf3d6a2612caa0a446604948d81",
|
||||
"7fccc7de25a0723a7fb96c82da7b3dfb90d13a040912e28390aa1893cfb9544c",
|
||||
"994aa24a02e2a4767c4b8c505a798d4ef2a9b6a56f457b165662951e087827ff",
|
||||
"ddcd5fcb63faeb2de4736f716384ba8033e4caf80531c6be879abcb7d1e2e3c4",
|
||||
"de319d6d3cc31892b31798aa382d3bbadbfb5c63b5d085d44535753cd1154d88",
|
||||
"bf0a1dee65b36efc72d9d47081064cd1478a41eb2930f5f209efde82ad81a90f",
|
||||
"58250251ac29c974e1c172ed7891f7b8918dc92722738051a2d47652fa15cb0c",
|
||||
"9d54d9c89ba4bb7bc44eaa92ba162851c425e6da7061712971a816d2f76226e9",
|
||||
"f8606f3d9cc85dd938e7c81c80bf459b704ee2fcf90dd5db2b22a57e9063b2d1",
|
||||
"9146f5fbfa4b9d0c6fb5d3fc754114f45b2960b0160bc5ec8049c766cb159a8f",
|
||||
"2a8fcf1082f08ad75bd679e43c331d8c68dd125583a0215a9d791f2dedacd252",
|
||||
"1cc30cac847d1f4cb3be1a6548320587083f8a140360720cf6e602643604db55",
|
||||
"f12ee7fa2a4f6c67ff363515af5d5ff269c2888c5cb0b1ef65b51c532c6513fe",
|
||||
"1fb7c9b0e42cc75c72f80ceab00ddbf1c53b79f0079afdc7f2d12a0b1362d470",
|
||||
"4204700c6c144ea21dcf35004c506abf1b4c31c7e56cb7593fe91a0df7a7e4bf",
|
||||
"1604b6be565a34d390015a69d4ce4939d1223a2a7340c665516cc268896f7302",
|
||||
"945f03992308869fd8c3cb866d587bc02cce18718491eb014e4c3a2d2b9910db",
|
||||
"b1483d183ecec1757c21ea90abe833ec6c7473e69be22fab59a804f469844fbc",
|
||||
"699ec626d2c4044b8fd95a6187b6b670f00b3e357f6147b5225f8b0b53855c08",
|
||||
"07b37382fee8cebab882854cf3ea1c05ada71ea88288333a878271c9a2d11c83",
|
||||
"4210279021308f9a52367d78c3527904da8d3488388dc78e49c435695f300f15",
|
||||
"616e4309c7b433d282b0727984cd797d0f384975749b34c12cba56b3bc6ec770",
|
||||
"6791837bb4b63b58877031e95b7e5d8556310b5f5bcbe40432ea41cd3d0a29e6"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
"""A Latin letter on a persona whose keyboard has none is typed on the second
|
||||
keyboard Windows installs with the language, with its key events.
|
||||
|
||||
⛔ KNOWN-BAD, measured on firefox-57 with 0.46.3: a session in Russian or Greek
|
||||
(the runner's address decides the language) answered `press("x")` with
|
||||
"Locator.press: unknown key: 'x'", and `type("cafe")` put every letter in
|
||||
without a key event, which a real user never produces. A Russian user has
|
||||
English (US) too, which Windows installs with Russian, switches to it with
|
||||
left Alt and left Shift (Windows' default shortcut between input languages,
|
||||
whose keys the page sees) and types the `x` with KeyX. Where Windows installs no keyboard with Latin letters (Nepali in
|
||||
India), the letter is inserted as text, as for any character no key makes.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
PAGE = ("<!doctype html><input id=i><script>window.log = [];"
|
||||
"for (const t of ['keydown', 'input']) document.getElementById('i')"
|
||||
".addEventListener(t, e => log.push([t, e.key || '', e.code || '', e.data || '']));"
|
||||
"</script>")
|
||||
|
||||
|
||||
def _typed(firefox_binary, locale, act):
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
with InvisiblePlaywright(seed=42, binary_path=firefox_binary, headless=True,
|
||||
locale=locale) as browser:
|
||||
page = browser.new_page()
|
||||
page.set_content(PAGE)
|
||||
act(page.locator("#i"))
|
||||
return page.input_value("#i"), page.evaluate("window.log")
|
||||
|
||||
|
||||
def test_a_russian_persona_presses_x_on_english(firefox_binary):
|
||||
value, log = _typed(firefox_binary, "ru-RU", lambda field: field.press("x"))
|
||||
assert value == "x"
|
||||
assert [e[2] for e in log if e[0] == "keydown"] == ["AltLeft", "ShiftLeft", "KeyX"], log
|
||||
|
||||
|
||||
def test_a_greek_persona_types_latin_text_with_its_keys(firefox_binary):
|
||||
value, log = _typed(firefox_binary, "el-GR",
|
||||
lambda field: field.press_sequentially("cafe"))
|
||||
assert value == "cafe"
|
||||
assert [e[2] for e in log if e[0] == "keydown"] == [
|
||||
"AltLeft", "ShiftLeft", "KeyC", "KeyA", "KeyF", "KeyE"], log
|
||||
|
||||
|
||||
def test_a_letter_no_default_keyboard_has_is_inserted(firefox_binary):
|
||||
value, log = _typed(firefox_binary, "ne-IN",
|
||||
lambda field: field.press_sequentially("x"))
|
||||
assert value == "x"
|
||||
assert not [e for e in log if e[0] == "keydown"], log
|
||||
@@ -0,0 +1,87 @@
|
||||
"""A launch missing a system font or colour declaration is refused.
|
||||
|
||||
The engine reads the CSS system fonts (ui.font.*) and the system colours no
|
||||
stand-in covers (ui.highlight, ui.-moz-field, ...) from what invisible_core
|
||||
declares, and never from the toolkit. With the stealth engine on and one of
|
||||
them missing, the browser must refuse to start - before a page can load - and
|
||||
say which pref, instead of answering from GTK. With every pref declared the
|
||||
same launch succeeds (the control).
|
||||
|
||||
The profile and its user.js are the ones build_launch_plan writes, with the
|
||||
named pref removed; the engine is started the way the Juggler connection tests
|
||||
start it.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import shutil
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
MISSING = [
|
||||
"ui.highlight",
|
||||
"ui.-moz-field",
|
||||
"ui.font.menu",
|
||||
]
|
||||
|
||||
|
||||
def _drop(user_js: Path, names) -> int:
|
||||
"""Remove the user_pref lines of exactly these names (the .dark and .size
|
||||
variants are other prefs and stay). Returns how many lines went."""
|
||||
kept, dropped = [], 0
|
||||
for line in user_js.read_text(encoding="utf-8").splitlines():
|
||||
m = re.match(r'user_pref\(("(?:[^"\]|\.)*"),', line)
|
||||
if m and json.loads(m.group(1)) in names:
|
||||
dropped += 1
|
||||
else:
|
||||
kept.append(line)
|
||||
user_js.write_text("\n".join(kept) + "\n", encoding="utf-8")
|
||||
return dropped
|
||||
|
||||
|
||||
def _launch(firefox_binary, drop):
|
||||
from invisible_core.juggler import connection as conn
|
||||
from invisible_core.launch import build_launch_plan
|
||||
|
||||
profile_dir = tempfile.mkdtemp(prefix="system_theme_")
|
||||
try:
|
||||
plan = build_launch_plan(6023, profile_dir=profile_dir, binary_path=firefox_binary,
|
||||
timezone="UTC", locale="en-US")
|
||||
if drop:
|
||||
assert _drop(Path(profile_dir) / "user.js", {drop}) == 1, (
|
||||
"%s is not declared by this core, so there is nothing to remove" % drop)
|
||||
return conn.launch(firefox_binary, profile_dir, headless=True,
|
||||
env=plan.env, ready_timeout=60.0), profile_dir
|
||||
except BaseException:
|
||||
shutil.rmtree(profile_dir, ignore_errors=True)
|
||||
raise
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
@pytest.mark.parametrize("pref", MISSING)
|
||||
def test_a_missing_pref_refuses_the_launch(firefox_binary, engine_at_least, pref):
|
||||
engine_at_least("firefox-60")
|
||||
with pytest.raises(RuntimeError) as err:
|
||||
c, profile_dir = _launch(firefox_binary, pref)
|
||||
# Not reached when the engine refuses: close what must not be running.
|
||||
c.close()
|
||||
shutil.rmtree(profile_dir, ignore_errors=True)
|
||||
message = str(err.value)
|
||||
assert "exited during startup" in message, message
|
||||
assert pref in message, "the refusal does not name %s:\n%s" % (pref, message)
|
||||
assert "is not declared" in message, message
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_every_pref_declared_the_launch_succeeds(firefox_binary, engine_at_least):
|
||||
engine_at_least("firefox-60")
|
||||
c, profile_dir = _launch(firefox_binary, None)
|
||||
try:
|
||||
assert c.ready_seen, "the browser did not announce the protocol"
|
||||
assert c._process.poll() is None, "the browser is not running"
|
||||
finally:
|
||||
c.close()
|
||||
shutil.rmtree(profile_dir, ignore_errors=True)
|
||||
@@ -0,0 +1,187 @@
|
||||
"""Tagged images drawn on a canvas read back as retail Windows Firefox reads them.
|
||||
|
||||
Retail Firefox 159.0 on Windows with the default prefs converts an image that carries a colour
|
||||
tag (an iCCP chunk, cICP, gAMA + cHRM, an sRGB chunk, a JPEG APP2 profile) from its own space
|
||||
to the output profile with qcms, and the output profile is the monitor's: on a stock Windows
|
||||
that is "sRGB Color Space Profile.icm", which qcms does not take for sRGB, so the bytes
|
||||
getImageData returns for drawImage and createImageBitmap change by a few units. The engine
|
||||
declares that profile (it never reads the host's) and converts like retail from firefox-60.
|
||||
Until firefox-59 it skipped the conversion (force_srgb): 27 of the 72 probes below differ
|
||||
there, and this test fails on such an engine, naming each of them. It is gated on
|
||||
firefox-60 only so that those releases skip it instead of failing the run.
|
||||
|
||||
tests/data/canvas_icc_ref/index.html, a page served on localhost, measures 72 probes:
|
||||
|
||||
40 the ten images of gen_images.py (iccp Display P3, Adobe RGB, Rec.2020 primaries,
|
||||
ProPhoto, sRGB primaries; cicp-p3; gama-chrm-p3; srgb-chunk; untagged; a JPEG with a
|
||||
Display P3 profile) each drawn with drawImage (16 px), drawImage scaled to 32 px,
|
||||
createImageBitmap with the default colorSpaceConversion and with "none"
|
||||
22 fillRect with CSS colours (color(display-p3 ...), color-mix(), oklab, ...)
|
||||
1 a canvas opened with colorSpace "display-p3"
|
||||
9 environment values (color-gamut, dynamic-range, colour depth, devicePixelRatio, the
|
||||
colour scheme); the colour scheme is the machine's theme and is not compared
|
||||
|
||||
The 27 that depend on the profile are the drawImage, drawImage at 32 px and
|
||||
createImageBitmap-default probes of the nine tagged images. Each probe's RGBA bytes
|
||||
(getImageData) are hashed with SHA-256. The images are not files of the repository: the test
|
||||
builds them with tests/data/canvas_icc_ref/gen_images.py (standard library, the bytes the
|
||||
measurement used, checked against refs.json before the browser starts) and serves them.
|
||||
|
||||
tests/data/canvas_icc_ref/refs.json holds the hashes retail Firefox 159.0 gave on Windows
|
||||
(build 20261022150525, firefox.exe sha256 d8b5ed82...) with default prefs, gfx.canvas.accelerated
|
||||
off and the monitor profile above (sha256 2b3aa164...), measured twice with equal results; for
|
||||
the 27 probes it also holds the hash without the conversion (force_srgb=true on the same
|
||||
machine), which the failure message names when the engine gave that value. The file is built
|
||||
by scripts/build_canvas_icc_refs.py from the run files.
|
||||
|
||||
Every differing probe is listed (name, expected hash, hash got), not just the first. Set
|
||||
INVISIBLE_CANVAS_ICC_OUT to a directory and the run writes the hashes it got there
|
||||
(canvas_icc_<tag>.json).
|
||||
|
||||
Run: pytest tests/test_canvas_icc_readback_is_windows_e2e.py -m e2e -v
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import http.server
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
DATA = Path(__file__).parent / "data" / "canvas_icc_ref"
|
||||
|
||||
#: The page's result without the pixel hex (only the hashes are compared; the hex of every
|
||||
#: probe would cross the pipe for nothing).
|
||||
_RESULT = """
|
||||
() => {
|
||||
const strip = (o) => {
|
||||
if (o === null || typeof o !== "object") return o;
|
||||
const out = {};
|
||||
for (const [k, v] of Object.entries(o)) if (k !== "rgba_hex") out[k] = strip(v);
|
||||
return out;
|
||||
};
|
||||
return strip(window.R);
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def _load(path, name):
|
||||
spec = importlib.util.spec_from_file_location(name, path)
|
||||
mod = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(mod)
|
||||
return mod
|
||||
|
||||
|
||||
def _serve(imgs, listing):
|
||||
"""index.html, images.json and the generated images, on 127.0.0.1."""
|
||||
page = (DATA / "index.html").read_bytes()
|
||||
routes = {"/": (page, "text/html"), "/index.html": (page, "text/html")}
|
||||
routes["/images.json"] = (json.dumps(listing).encode(), "application/json")
|
||||
for iid, ext, data, _what in imgs:
|
||||
kind = "image/jpeg" if ext == "jpg" else "image/png"
|
||||
routes["/images/%s.%s" % (iid, ext)] = (data, kind)
|
||||
|
||||
class _H(http.server.BaseHTTPRequestHandler):
|
||||
def do_GET(self):
|
||||
hit = routes.get(self.path.split("?")[0])
|
||||
if hit is None:
|
||||
self.send_error(404)
|
||||
return
|
||||
body, kind = hit
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", kind)
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), _H)
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
return server
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
@pytest.mark.timeout(300, method="thread")
|
||||
def test_tagged_images_read_back_as_retail_windows_reads_them(firefox_binary, engine_at_least):
|
||||
engine_at_least("firefox-60")
|
||||
refs_path = DATA / "refs.json"
|
||||
if not refs_path.is_file():
|
||||
pytest.fail("tests/data/canvas_icc_ref/refs.json is missing: it is the reference "
|
||||
"retail Firefox on Windows wrote for this page (see the module docstring)")
|
||||
refs = json.loads(refs_path.read_text(encoding="utf-8"))
|
||||
want = refs["probes"]
|
||||
|
||||
gen = _load(DATA / "gen_images.py", "canvas_icc_gen_images")
|
||||
imgs, _profiles = gen.build_images()
|
||||
drift = ["%s: %s bytes, sha256 %s, the reference was made with %s"
|
||||
% (iid, len(data), hashlib.sha256(data).hexdigest(), refs["images"][iid]["sha256"])
|
||||
for iid, _ext, data, _what in imgs
|
||||
if hashlib.sha256(data).hexdigest() != refs["images"][iid]["sha256"]]
|
||||
assert not drift, ("gen_images.py no longer writes the images the reference was measured "
|
||||
"with, so it compares nothing:\n " + "\n ".join(drift))
|
||||
|
||||
builder = _load(ROOT / "scripts" / "build_canvas_icc_refs.py", "canvas_icc_build_refs")
|
||||
server = _serve(imgs, gen.images_json(imgs))
|
||||
try:
|
||||
url = "http://127.0.0.1:%d/" % server.server_address[1]
|
||||
with InvisiblePlaywright(seed=21, binary_path=firefox_binary, headless=True,
|
||||
pin={"screen.dpr": 1.0}) as b:
|
||||
page = b.new_context().new_page()
|
||||
page.goto(url, timeout=60_000)
|
||||
page.wait_for_function("window.DONE === true || window.ERR", timeout=240_000)
|
||||
err = page.evaluate("window.ERR || null")
|
||||
assert err is None, "the reference page failed: %s" % err
|
||||
result = page.evaluate(_RESULT)
|
||||
finally:
|
||||
server.shutdown()
|
||||
|
||||
try:
|
||||
got = builder.probes(result)
|
||||
except builder.RefError as e:
|
||||
pytest.fail("the page did not give a hash for every probe: %s" % e)
|
||||
|
||||
out_dir = os.environ.get("INVISIBLE_CANVAS_ICC_OUT")
|
||||
if out_dir:
|
||||
from invisible_core.seal import active_seal
|
||||
Path(out_dir).mkdir(parents=True, exist_ok=True)
|
||||
(Path(out_dir) / ("canvas_icc_%s.json" % active_seal().tag)).write_text(
|
||||
json.dumps({k: v["sha256"] for k, v in got.items()}, indent=1, sort_keys=True),
|
||||
encoding="utf-8")
|
||||
|
||||
compared = sorted(k for k, v in want.items() if v.get("compared", True))
|
||||
missing = sorted(k for k in want if k not in got)
|
||||
extra = sorted(set(got) - set(want))
|
||||
differ = [k for k in compared if k in got and got[k]["sha256"] != want[k]["sha256"]]
|
||||
|
||||
lines = []
|
||||
for k in differ:
|
||||
note = ""
|
||||
if got[k]["sha256"] == want[k].get("without_conversion_sha256"):
|
||||
note = " (the value without the conversion: qcms did not convert)"
|
||||
elif "without_conversion_sha256" in want[k]:
|
||||
note = " (depends on the display profile)"
|
||||
shown = ("; reference value %r, got %r" % (want[k]["value"], got[k]["value"])
|
||||
if want[k]["kind"] == "env" else "")
|
||||
lines.append("%s: expected %s, got %s%s%s"
|
||||
% (k, want[k]["sha256"], got[k]["sha256"], shown, note))
|
||||
lines += ["not drawn: " + k for k in missing]
|
||||
if extra:
|
||||
lines.append("drawn but not in the reference: " + ", ".join(extra))
|
||||
unconverted = [k for k in differ
|
||||
if got[k]["sha256"] == want[k].get("without_conversion_sha256")]
|
||||
assert not lines, (
|
||||
"%d of %d canvas colour probes differ from retail Firefox 159.0 on Windows, %d were not "
|
||||
"drawn; %d of the %d that depend on the display profile gave the value without the "
|
||||
"conversion.\n %s"
|
||||
% (len(differ), len(compared), len(missing), len(unconverted),
|
||||
refs["profile_dependent_count"], "\n ".join(lines)))
|
||||
@@ -0,0 +1,181 @@
|
||||
"""Canvas 2D text is drawn as retail Firefox on Windows draws it, on every OS.
|
||||
|
||||
Retail Firefox on Windows draws canvas text with Skia over DirectWrite. The engine draws it
|
||||
with Skia over idwr (DirectWrite 10.0.26100.9711 in portable C) from firefox-60, so the
|
||||
same page gives the same RGBA bytes on Windows, on Debian 12 and on Ubuntu 24.04.
|
||||
|
||||
tests/data/canvas_text_ref/index.html draws 342 cases, in groups (the ``gruppo`` field of
|
||||
each case in refs.json):
|
||||
|
||||
0_base 211 Arial, Segoe UI, Times New Roman, Consolas and Calibri at 9,
|
||||
12.5, 16, 33, 72 and 300 px, with and without a rotate(15deg)
|
||||
scale(1.5, 2) transform; fillText, strokeText, synthetic
|
||||
italic and bold
|
||||
1_alpha_false 25 the same faces at 5 sizes on getContext('2d', {alpha: false})
|
||||
(an opaque canvas, where LCD text is possible)
|
||||
2a_rot_alpha_true_controllo 25 rotated and scaled, alpha true (the base's cases, drawn once)
|
||||
2b_rot_alpha_false 25 rotated and scaled, alpha false
|
||||
3_emoji_colr0 12 COLR v0 emoji, Twemoji Mozilla, alpha true and false
|
||||
4_soglie 20 255, 256, 257, 300 and 400 px, fillText and strokeText
|
||||
5_variabile_bahnschrift 12 font-weight 300/400/700 by font-stretch 75%/100%
|
||||
6_variabile_seguivar 12 Segoe UI Variable, font-weight 300/400/700 at 9, 12.5, 16 and
|
||||
33 px (opsz follows the size): the instance the scaled font
|
||||
asks of idwr, on every OS
|
||||
|
||||
Each canvas is read back with getImageData and its RGBA bytes are hashed with SHA-256. The
|
||||
fonts are @font-face webfonts: the files of the engine's own ``fonts`` directory, served by
|
||||
this test, so the comparison does not depend on what the host has installed.
|
||||
tests/data/canvas_text_ref/refs.json holds the hashes retail Firefox 159.0 on Windows gave for
|
||||
the same page and the same bundled files (gfx.canvas.accelerated off, white background), and
|
||||
the ClearType state of that machine, which the test declares as the persona (system text
|
||||
quality 5). Its ``fonts`` entries carry the sha256 of each file, which must be the engine's
|
||||
bundled one (Arial 05c7da5fe195...; Twemoji Mozilla, Bahnschrift and Segoe UI Variable too): a reference made with
|
||||
other font files compares nothing. The file is built by scripts/build_canvas_text_refs.py from
|
||||
the two measurements.
|
||||
|
||||
The largest canvases (400 px: 7727 x 3373, 100 MB of RGBA) are drawn one at a time and
|
||||
released after their hash is taken, as the measuring page did.
|
||||
|
||||
Every differing case is listed, group by group, not just the first. Set INVISIBLE_CANVAS_TEXT_OUT to a
|
||||
directory and the run writes its hashes there (canvas_text_<tag>.json); scripts/
|
||||
compare_canvas_text_runs.py says which cases two runs, the Debian one and the Ubuntu one,
|
||||
draw differently.
|
||||
|
||||
Run: pytest tests/test_canvas_text_is_windows_e2e.py -m e2e -v
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import http.server
|
||||
import json
|
||||
import os
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
DATA = Path(__file__).parent / "data" / "canvas_text_ref"
|
||||
|
||||
#: What the reference's ``cleartype`` field says the retail machine had: FontSmoothing 2 with
|
||||
#: FontSmoothingType 2 is ClearType (system text quality 5). The other tuning values are an
|
||||
#: untuned Windows machine's (gamma 1.8, contrast 1.0, level 1.0), which refs.json does not
|
||||
#: record.
|
||||
_UNTUNED = {"font.cleartype_gamma": 1800, "font.cleartype_contrast": 100,
|
||||
"font.cleartype_level": 100}
|
||||
|
||||
|
||||
def _pin(refs):
|
||||
ct = refs["cleartype"]
|
||||
smoothing, kind = str(ct["FontSmoothing"]), str(ct["FontSmoothingType"])
|
||||
if smoothing == "2" and kind in ("2", "0x2"):
|
||||
quality = 5
|
||||
elif smoothing == "2":
|
||||
quality = 4
|
||||
else:
|
||||
quality = 0
|
||||
return {"screen.dpr": 1.0, "font.system_text_quality": quality, **_UNTUNED}
|
||||
|
||||
|
||||
def _bundle_font(fonts_dir, entry):
|
||||
"""The bundled file a reference entry names."""
|
||||
return fonts_dir / entry["bundle_file"]
|
||||
|
||||
|
||||
def _serve(fonts_dir, entries):
|
||||
"""The page and, under fonts/<name from the page>, the engine's bundled files."""
|
||||
by_url = {"/bundle/" + e["bundle_file"]: _bundle_font(fonts_dir, e) for e in entries}
|
||||
page = (DATA / "index.html").read_bytes()
|
||||
|
||||
class _H(http.server.BaseHTTPRequestHandler):
|
||||
def do_GET(self):
|
||||
path = self.path.split("?")[0]
|
||||
if path in ("/", "/index.html"):
|
||||
body, kind = page, "text/html"
|
||||
elif path in by_url and by_url[path].is_file():
|
||||
body, kind = by_url[path].read_bytes(), "font/ttf"
|
||||
else:
|
||||
self.send_error(404)
|
||||
return
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", kind)
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), _H)
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
return server
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
@pytest.mark.timeout(1800, method="thread")
|
||||
def test_canvas_text_is_what_retail_windows_draws(firefox_binary, engine_at_least):
|
||||
engine_at_least("firefox-60")
|
||||
refs_path = DATA / "refs.json"
|
||||
if not refs_path.is_file():
|
||||
pytest.fail("tests/data/canvas_text_ref/refs.json is missing: it is the reference "
|
||||
"retail Firefox on Windows wrote for this page (see the module docstring)")
|
||||
refs = json.loads(refs_path.read_text(encoding="utf-8"))
|
||||
fonts_dir = Path(firefox_binary).parent / "fonts"
|
||||
|
||||
wrong = []
|
||||
for e in refs["fonts"]:
|
||||
f = _bundle_font(fonts_dir, e)
|
||||
got = hashlib.sha256(f.read_bytes()).hexdigest() if f.is_file() else None
|
||||
if got != e["sha256"]:
|
||||
wrong.append("%s: the engine's %s has sha256 %s, the reference was made with %s"
|
||||
% (e["family"], f.name, got, e["sha256"]))
|
||||
assert not wrong, (
|
||||
"the reference was measured with other font files than the engine's bundle, so it "
|
||||
"compares nothing; rebuild refs.json from the bundled files:\n " + "\n ".join(wrong))
|
||||
|
||||
pin = _pin(refs)
|
||||
server = _serve(fonts_dir, refs["fonts"])
|
||||
try:
|
||||
url = "http://127.0.0.1:%d/" % server.server_address[1]
|
||||
with InvisiblePlaywright(seed=21, binary_path=firefox_binary, headless=True,
|
||||
pin=pin) as b:
|
||||
page = b.new_context().new_page()
|
||||
page.goto(url, timeout=60_000)
|
||||
page.wait_for_function("window.DONE === true || window.ERR", timeout=1_500_000)
|
||||
err = page.evaluate("window.ERR || null")
|
||||
assert err is None, "the reference page failed: %s" % err
|
||||
got = page.evaluate(
|
||||
"Object.fromEntries(Object.entries(window.R).map(([k, v]) => [k, v.sha256]))")
|
||||
finally:
|
||||
server.shutdown()
|
||||
|
||||
out_dir = os.environ.get("INVISIBLE_CANVAS_TEXT_OUT")
|
||||
if out_dir:
|
||||
from invisible_core.seal import active_seal
|
||||
Path(out_dir).mkdir(parents=True, exist_ok=True)
|
||||
(Path(out_dir) / ("canvas_text_%s.json" % active_seal().tag)).write_text(
|
||||
json.dumps(got, indent=1, sort_keys=True), encoding="utf-8")
|
||||
|
||||
cases = refs["cases"]
|
||||
want = {k: v["sha256"] for k, v in cases.items()}
|
||||
missing = sorted(set(want) - set(got))
|
||||
extra = sorted(set(got) - set(want))
|
||||
differ = sorted(k for k in want if k in got and got[k] != want[k])
|
||||
|
||||
lines = []
|
||||
for group in sorted({v["gruppo"] for v in cases.values()}):
|
||||
ids = sorted(k for k, v in cases.items() if v["gruppo"] == group)
|
||||
bad = [k for k in ids if k in differ]
|
||||
gone = [k for k in ids if k in missing]
|
||||
if bad or gone:
|
||||
lines.append("%s: %d of %d differ, %d not drawn" % (group, len(bad), len(ids), len(gone)))
|
||||
lines += [" differs: " + k for k in bad[:40]]
|
||||
if len(bad) > 40:
|
||||
lines.append(" ... and %d more" % (len(bad) - 40))
|
||||
lines += [" not drawn: " + k for k in gone[:20]]
|
||||
if extra:
|
||||
lines.append("drawn but not in the reference: " + ", ".join(extra[:20]))
|
||||
assert not lines, (
|
||||
"%d of %d canvas text cases differ from retail Firefox on Windows, %d were not drawn.\n%s"
|
||||
% (len(differ), len(want), len(missing), "\n".join(lines)))
|
||||
@@ -0,0 +1,40 @@
|
||||
"""Every workflow that runs the suite downloads the engine with the job's token.
|
||||
|
||||
On 2026-11-08 GitHub had timeouts for unauthenticated users, and the gates
|
||||
here failed three times on the engine download, because the jobs called the
|
||||
release API anonymously. The core uses GITHUB_TOKEN when it is set, so the fix
|
||||
is declaring it once, at the top of each workflow that runs tests.
|
||||
user-install.yml is the exception: it is the user's path, and users download
|
||||
anonymously.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
WORKFLOWS = Path(__file__).resolve().parents[1] / ".github" / "workflows"
|
||||
ANONYMOUS_ON_PURPOSE = {"user-install.yml"}
|
||||
RUNS_TESTS = re.compile(r"pytest|run_e2e\.py")
|
||||
TOP_LEVEL_TOKEN = re.compile(r"^env:\n(?:[ ]{2}.*\n)*?[ ]{2}GITHUB_TOKEN: \$\{\{ github\.token \}\}\n",
|
||||
re.MULTILINE)
|
||||
|
||||
|
||||
def test_every_workflow_that_runs_tests_declares_the_token():
|
||||
missing = [
|
||||
p.name for p in sorted(WORKFLOWS.glob("*.yml"))
|
||||
if p.name not in ANONYMOUS_ON_PURPOSE
|
||||
and RUNS_TESTS.search(p.read_text(encoding="utf-8"))
|
||||
and not TOP_LEVEL_TOKEN.search(p.read_text(encoding="utf-8"))
|
||||
]
|
||||
assert not missing, ("these workflows run tests that download the engine "
|
||||
"anonymously; declare `env: GITHUB_TOKEN: ${{ github.token }}` "
|
||||
"at the top: " + ", ".join(missing))
|
||||
|
||||
|
||||
def test_the_user_path_stays_anonymous_at_the_top():
|
||||
text = (WORKFLOWS / "user-install.yml").read_text(encoding="utf-8")
|
||||
assert not TOP_LEVEL_TOKEN.search(text)
|
||||
@@ -54,14 +54,14 @@ def broken(**override):
|
||||
return {inv.name for inv, state, message in gate.check_invariants(gate.visit_states(retail_states(**override)))}
|
||||
|
||||
|
||||
def write(tmp_path, items_by_leg_seed, retail):
|
||||
def write(tmp_path, items_by_leg_seed, retail, legs=None):
|
||||
dumps = tmp_path / "dumps"
|
||||
ref = tmp_path / "ref"
|
||||
dumps.mkdir(parents=True)
|
||||
ref.mkdir(parents=True)
|
||||
for dpr in gate.DPRS:
|
||||
(ref / ("dpr%s.json" % dpr)).write_text(json.dumps({"items": retail}), encoding="utf-8")
|
||||
for leg in LEGS:
|
||||
for leg in legs or LEGS:
|
||||
for seed in gate.SEEDS:
|
||||
items = dict(retail_states(), **items_by_leg_seed(leg, seed))
|
||||
(dumps / ("%s_dpr%s_seed%d.json" % (leg, dpr, seed))).write_text(json.dumps(
|
||||
@@ -70,8 +70,8 @@ def write(tmp_path, items_by_leg_seed, retail):
|
||||
return dumps, ref
|
||||
|
||||
|
||||
def run(tmp_path, items, retail, exceptions=None, notes=None):
|
||||
dumps, ref = write(tmp_path, items, retail)
|
||||
def run(tmp_path, items, retail, exceptions=None, notes=None, legs=None):
|
||||
dumps, ref = write(tmp_path, items, retail, legs)
|
||||
return gate.compare(dumps, ref, exceptions or {}, notes)
|
||||
|
||||
|
||||
@@ -420,3 +420,44 @@ def test_every_page_call_the_driver_makes_exists_in_the_page():
|
||||
assert used == {"prepare", "arm", "wait", "leave", "clear", "measure"}
|
||||
for name in used:
|
||||
assert re.search(r"\b%s\b\s*[(,]" % name, api), name
|
||||
|
||||
|
||||
def test_the_navigation_has_the_page_s_budget_not_goto_s_default():
|
||||
"""Known-bad: page.goto without a timeout, 30 s, while the wait for the page
|
||||
after it has 180 s; a cold Windows runner crossed the 30 s on the first visit."""
|
||||
src = (Path(__file__).resolve().parent.parent / "scripts" / "ci_host_gate.py").read_text(encoding="utf-8")
|
||||
call = re.search(r"page\.goto\((.*?)\)$", src, re.S | re.M).group(1)
|
||||
assert "timeout=timeout_ms" in call, call
|
||||
|
||||
|
||||
|
||||
# Two Linux machines were never compared with each other: every leg was held to
|
||||
# the Windows leg only, and a known defect (text, which Linux draws with the
|
||||
# host's FreeType) excused every Linux leg's difference from Windows, so two
|
||||
# distributions with different libraries could disagree and nothing saw it.
|
||||
|
||||
THREE_LEGS = ["linux-x86_64", "linux-x86_64-debian12", "win-x86_64"]
|
||||
TEXT_DEFECT = {"known_defects": [{"keys": ["text.*"], "why": "phase 4"}]}
|
||||
|
||||
|
||||
def test_two_linux_machines_must_agree_where_a_known_defect_excuses_windows(tmp_path):
|
||||
items = lambda leg, seed: {"text.canvas.H": {"win-x86_64": "dwrite", "linux-x86_64": "ft-ubuntu",
|
||||
"linux-x86_64-debian12": "ft-debian"}[leg]}
|
||||
failures = run(tmp_path, items, {"text.canvas.H": "dwrite"}, TEXT_DEFECT, legs=THREE_LEGS)
|
||||
assert failures and all("(same OS)" in f and "linux-x86_64-debian12" in f for f in failures)
|
||||
|
||||
|
||||
def test_two_linux_machines_that_agree_pass(tmp_path):
|
||||
items = lambda leg, seed: {"text.canvas.H": "dwrite" if leg == "win-x86_64" else "freetype"}
|
||||
assert run(tmp_path, items, {"text.canvas.H": "dwrite"}, TEXT_DEFECT, legs=THREE_LEGS) == []
|
||||
|
||||
|
||||
def test_a_known_defect_of_linux_covers_every_linux_leg_of_the_gate():
|
||||
"""A defect of the Linux GL (Mesa's raster, delta 1 from Windows) is the same on both Linux legs: an exception
|
||||
scoped to one of them failed the gate on the other (re-gate of firefox-59 with the Debian leg, 12 failures)."""
|
||||
linux = [leg for leg in THREE_LEGS if leg.startswith("linux-")]
|
||||
scoped = [e for e in gate.load_exceptions()["known_defects"] if e.get("legs")]
|
||||
assert scoped
|
||||
for e in scoped:
|
||||
if any(leg.startswith("linux-") for leg in e["legs"]):
|
||||
assert sorted(leg for leg in e["legs"] if leg.startswith("linux-")) == linux, e
|
||||
@@ -0,0 +1,88 @@
|
||||
"""CSS calc() functions give Windows' text on every OS.
|
||||
|
||||
The style engine evaluates ``calc(1px * sin(x))``, ``asin``, ``pow``, ``log``
|
||||
and the others in f32 with the C library's f32 functions (sinf, asinf, powf,
|
||||
logf...), and writes the number with 6 significant digits. Windows Firefox gets
|
||||
them from ucrtbase.dll; Linux Firefox got glibc's, whose last f32 bit differs
|
||||
for some inputs - and for some of those the difference moves the 6th digit,
|
||||
which is what a page reads with getComputedStyle.
|
||||
|
||||
tests/data/ucrt_css_calc.txt holds, per function, inputs where ucrtbase.dll and
|
||||
glibc write a different text (and a few where they agree), with the text
|
||||
ucrtbase.dll gives; scripts/ucrt_css_calc.py makes it. A function with no
|
||||
differing input in the searched grid (tan, atan, atan2, exp: 0 of 65,000 to
|
||||
90,000 each; hypot is a sum and a square root, exact) is in the file with
|
||||
control inputs only, so it checks that the page computes at all.
|
||||
|
||||
A number is read with ``word-spacing`` (px) and an angle with ``rotate``
|
||||
(deg): both are computed values that getComputedStyle writes as the style
|
||||
engine serialized them, with no layout in between.
|
||||
|
||||
Every mismatch is listed in the failure, not just the first.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
DATA = Path(__file__).parent / "data" / "ucrt_css_calc.txt"
|
||||
ANGLE_FUNCTIONS = ("asin", "acos", "atan", "atan2")
|
||||
|
||||
READ = """
|
||||
(cases) => cases.map(([prop, value]) => {
|
||||
const el = document.createElement("div");
|
||||
el.style.setProperty(prop, value);
|
||||
document.body.appendChild(el);
|
||||
const got = getComputedStyle(el).getPropertyValue(prop);
|
||||
el.remove();
|
||||
return got;
|
||||
})
|
||||
"""
|
||||
|
||||
|
||||
def _cases():
|
||||
out = []
|
||||
for line in DATA.read_text().splitlines():
|
||||
if line and not line.startswith("#"):
|
||||
parts = line.split()
|
||||
out.append((parts[0], parts[1:-1], parts[-1]))
|
||||
return out
|
||||
|
||||
|
||||
def _css(fn, args):
|
||||
"""(property, value) that makes the style engine compute fn(args)."""
|
||||
call = "%s(%s)" % (fn, ", ".join(args))
|
||||
if fn in ANGLE_FUNCTIONS:
|
||||
return "rotate", call
|
||||
return "word-spacing", "calc(1px * %s)" % call
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_the_data_has_every_function_and_the_inputs_that_tell_the_libraries_apart():
|
||||
cases = _cases()
|
||||
assert {c[0] for c in cases} == {
|
||||
"sin", "cos", "tan", "asin", "acos", "atan", "atan2", "exp", "log", "pow", "hypot"}
|
||||
# The cases that make this test about the library and not only the engine.
|
||||
for fn in ("sin", "cos", "asin", "acos", "log", "pow"):
|
||||
assert sum(1 for c in cases if c[0] == fn) >= 4, fn
|
||||
# sin(-12.2958984375): ucrtbase 0.267186, glibc 0.267187.
|
||||
assert ("sin", ["-12.2958984375"], "0.267186px") in cases
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_css_calc_functions_are_ucrtbase_bytes(firefox_binary, engine_at_least):
|
||||
engine_at_least("firefox-60")
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
cases = _cases()
|
||||
with InvisiblePlaywright(seed=6021, binary_path=firefox_binary, headless=True) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto("about:blank")
|
||||
got = page.evaluate(READ, [list(_css(fn, args)) for fn, args, _ in cases])
|
||||
|
||||
wrong = ["%s(%s): page %r, ucrtbase %r" % (fn, ", ".join(args), g, want)
|
||||
for (fn, args, want), g in zip(cases, got) if g != want]
|
||||
assert not wrong, ("%d of %d calc() results are not ucrtbase's:\n %s"
|
||||
% (len(wrong), len(cases), "\n ".join(wrong)))
|
||||
@@ -231,8 +231,9 @@ def test_two_tabs_of_one_session_are_typed_with_two_rhythms(firefox_binary, page
|
||||
assert _distance(plans[0], plans[1]) > 2 * 1600
|
||||
|
||||
seen = []
|
||||
# The US keyboard, named: the persona's keyboard follows the session's language, which the runner's address decides.
|
||||
with InvisiblePlaywright(seed=SEED, binary_path=firefox_binary,
|
||||
headless=True) as browser:
|
||||
headless=True, locale="en-US") as browser:
|
||||
pages = [browser.new_page(), browser.new_page()]
|
||||
for p in pages:
|
||||
p.goto(page_url)
|
||||
|
||||
@@ -351,21 +351,44 @@ def test_audio_offline_context_deterministic(page):
|
||||
@pytest.mark.e2e
|
||||
def test_webgl_getParameter_deterministic(page):
|
||||
"""WebGL parameters must not drift across reads."""
|
||||
ok = _ev(page, """() => {
|
||||
res = _ev(page, """() => {
|
||||
const norm = v => (ArrayBuffer.isView(v) ? Array.from(v) : v);
|
||||
const c = document.createElement('canvas');
|
||||
const gl = c.getContext('webgl');
|
||||
if (!gl) return false;
|
||||
if (!gl) {
|
||||
return {ok: false, reason: 'gl null',
|
||||
webgl2: !!c.getContext('webgl2')};
|
||||
}
|
||||
if (gl.isContextLost()) {
|
||||
return {ok: false, reason: 'context lost'};
|
||||
}
|
||||
const names = ['MAX_TEXTURE_SIZE', 'MAX_VIEWPORT_DIMS',
|
||||
'MAX_RENDERBUFFER_SIZE', 'MAX_VERTEX_ATTRIBS'];
|
||||
const params = [gl.MAX_TEXTURE_SIZE, gl.MAX_VIEWPORT_DIMS,
|
||||
gl.MAX_RENDERBUFFER_SIZE, gl.MAX_VERTEX_ATTRIBS];
|
||||
const ref = JSON.stringify(params.map(p => gl.getParameter(p)));
|
||||
gl.MAX_RENDERBUFFER_SIZE, gl.MAX_VERTEX_ATTRIBS];
|
||||
const read = () => params.map(p => norm(gl.getParameter(p)));
|
||||
const ref = read();
|
||||
const refJson = JSON.stringify(ref);
|
||||
for (let i = 0; i < 50; i++) {
|
||||
if (JSON.stringify(params.map(p => gl.getParameter(p))) !== ref) {
|
||||
return false;
|
||||
const cur = read();
|
||||
if (JSON.stringify(cur) !== refJson) {
|
||||
if (gl.isContextLost()) {
|
||||
return {ok: false, reason: 'context lost', round: i + 1};
|
||||
}
|
||||
const k = cur.findIndex(
|
||||
(v, j) => JSON.stringify(v) !== JSON.stringify(ref[j]));
|
||||
return {ok: false, reason: 'drift', round: i + 1,
|
||||
param: names[k], first: cur[k], ref: ref[k]};
|
||||
}
|
||||
}
|
||||
return true;
|
||||
return {ok: true};
|
||||
}""")
|
||||
assert ok
|
||||
assert res["ok"], (
|
||||
f"WebGL getParameter check failed: reason={res.get('reason')!r} "
|
||||
f"webgl2={res.get('webgl2')!r} round={res.get('round')!r} "
|
||||
f"param={res.get('param')!r} first={res.get('first')!r} "
|
||||
f"ref={res.get('ref')!r}"
|
||||
)
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
|
||||
@@ -0,0 +1,273 @@
|
||||
"""Fontconfig reads nothing of the host (e2e, Linux): no process of the browser,
|
||||
parent or content, opens, stats or probes the host's fontconfig
|
||||
configuration or its font directories.
|
||||
|
||||
The engine runs fontconfig on an empty configuration installed before the
|
||||
first ``FcInit()`` (``StealthFcEmptyConfig``, nsLookAndFeel and the platform
|
||||
font list); the fonts are the bundle's. The engine's own gtest only looks at
|
||||
the final state, so it would also pass if the host's configuration had been
|
||||
loaded first, by GTK, Pango or anything else, and replaced afterwards. What
|
||||
sees the order is the system calls themselves: the browser runs under
|
||||
``strace -f`` and a page with text is drawn, and a single look at
|
||||
``/etc/fonts``, ``~/.config/fontconfig``, ``$FONTCONFIG_FILE`` or
|
||||
``/usr/share/fonts`` by any process fails the test.
|
||||
|
||||
strace runs through a stand-in tree: a temporary directory with a link to
|
||||
every file of the engine's directory, where the executable is a script that
|
||||
execs the real one under strace. The core reads the engine's identity from
|
||||
the directory of the path it is given, so the seal check passes as it does
|
||||
for the real tree.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import signal
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from collections import defaultdict
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = [
|
||||
pytest.mark.e2e,
|
||||
pytest.mark.skipif(not sys.platform.startswith("linux"),
|
||||
reason="fontconfig is the Linux font system"),
|
||||
pytest.mark.skipif(shutil.which("strace") is None or shutil.which("setsid") is None,
|
||||
reason="needs strace and setsid (apt install strace util-linux)"),
|
||||
]
|
||||
|
||||
_SYSCALLS = ("execve,clone,clone3,fork,vfork,open,openat,stat,lstat,"
|
||||
"newfstatat,statx,access,faccessat,faccessat2,readlink")
|
||||
|
||||
_PAGE = ("<!doctype html><meta charset=utf-8><body style='font-family:serif'>"
|
||||
"<h1>Fontconfig</h1><p style='font-family:sans-serif'>The quick brown "
|
||||
"fox jumps over the lazy dog.</p><code>monospace 0123456789</code>"
|
||||
"<p style='font-family:Arial'>Arial</p></body>")
|
||||
|
||||
|
||||
def _host_font_paths() -> list:
|
||||
"""Every place the host keeps fontconfig configuration or fonts."""
|
||||
home = os.path.expanduser("~")
|
||||
config_home = os.environ.get("XDG_CONFIG_HOME") or os.path.join(home, ".config")
|
||||
paths = ["/etc/fonts", os.path.join(config_home, "fontconfig"),
|
||||
os.path.join(home, ".config", "fontconfig"),
|
||||
os.path.join(home, ".fonts.conf"), "/usr/share/fonts"]
|
||||
if os.environ.get("FONTCONFIG_FILE"):
|
||||
paths.append(os.environ["FONTCONFIG_FILE"])
|
||||
if os.environ.get("FONTCONFIG_PATH"):
|
||||
paths += os.environ["FONTCONFIG_PATH"].split(":")
|
||||
return sorted(set(p.rstrip("/") for p in paths if p))
|
||||
|
||||
|
||||
def _strace_options() -> str:
|
||||
"""strace's own flags: quiet, follow forks, and die with the traced process
|
||||
when this build knows --kill-on-exit."""
|
||||
help_text = subprocess.run([shutil.which("strace"), "-h"], capture_output=True,
|
||||
text=True).stdout
|
||||
return "-f -qq -s 4096" + (" --kill-on-exit" if "--kill-on-exit" in help_text else "")
|
||||
|
||||
|
||||
def _require_strace_can_trace(tmp: Path) -> None:
|
||||
"""strace needs ptrace: a container or yama can refuse it, and then the
|
||||
failure is the environment's, said as such, not the launch's."""
|
||||
probe = subprocess.run([shutil.which("strace"), "-o", str(tmp / "probe.log"), "true"],
|
||||
capture_output=True, text=True)
|
||||
if probe.returncode != 0:
|
||||
pytest.fail("strace cannot trace here: %s" % (probe.stderr.strip() or probe.returncode),
|
||||
pytrace=False)
|
||||
|
||||
|
||||
def _stand_in(binary: str, tree: Path, log: Path, pidfile: Path) -> str:
|
||||
"""A copy of the engine's directory made of links, whose executable runs
|
||||
the real one under strace, in a session of its own.
|
||||
|
||||
The script writes its pid and execs ``setsid``: it is not a group leader,
|
||||
so setsid does not fork, the pid stays, and it is the id of a process
|
||||
group that holds strace and everything it traces (``_kill_group``)."""
|
||||
real = Path(os.path.realpath(binary))
|
||||
tree.mkdir()
|
||||
for entry in real.parent.iterdir():
|
||||
if entry.name != real.name:
|
||||
(tree / entry.name).symlink_to(entry)
|
||||
script = tree / real.name
|
||||
script.write_text(
|
||||
"#!/bin/sh\n"
|
||||
"echo $$ > %s\n"
|
||||
'exec %s %s %s -o %s -e trace=%s %s "$@"\n'
|
||||
% (pidfile, shutil.which("setsid"), shutil.which("strace"), _strace_options(),
|
||||
log, _SYSCALLS, real))
|
||||
script.chmod(script.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
|
||||
return str(script)
|
||||
|
||||
|
||||
_LINE = re.compile(r"^(\d+)\s+(\w+)\((.*)$")
|
||||
# strace -f splits a call that another thread interrupts in two lines:
|
||||
# "PID clone3({...} <unfinished ...>" and "PID <... clone3 resumed>) = CHILD".
|
||||
_RESUMED = re.compile(r"^(\d+)\s+<\.\.\. (\w+) resumed>(.*)$")
|
||||
_RESULT = re.compile(r"=\s+(\d+)\s*$")
|
||||
|
||||
|
||||
def _host_lookups(log: Path, real_binary: str) -> dict:
|
||||
"""``{"parent"|"content"|"other": ["<syscall> <line>", ...]}`` for every
|
||||
system call of the browser that names a host font path."""
|
||||
lines = log.read_text(errors="replace").splitlines()
|
||||
parent_of = {}
|
||||
argv_of = {}
|
||||
for line in lines:
|
||||
m = _LINE.match(line) or _RESUMED.match(line)
|
||||
if not m:
|
||||
continue
|
||||
pid, call, rest = int(m.group(1)), m.group(2), m.group(3)
|
||||
if call in ("clone", "clone3", "fork", "vfork"):
|
||||
r = _RESULT.search(rest)
|
||||
if r:
|
||||
parent_of[int(r.group(1))] = pid
|
||||
elif call == "execve" and real_binary in rest:
|
||||
# The arguments are on the first line even when the result comes
|
||||
# on a resumed one; the last execve of a process is what it runs.
|
||||
argv_of[pid] = rest
|
||||
|
||||
def role(pid: int) -> str:
|
||||
seen = set()
|
||||
while pid not in seen:
|
||||
seen.add(pid)
|
||||
argv = argv_of.get(pid)
|
||||
if argv is not None and real_binary in argv:
|
||||
return "content" if "-contentproc" in argv else "parent"
|
||||
if pid not in parent_of:
|
||||
break
|
||||
pid = parent_of[pid]
|
||||
return "other"
|
||||
|
||||
paths = _host_font_paths()
|
||||
found = defaultdict(list)
|
||||
for line in lines:
|
||||
m = _LINE.match(line)
|
||||
if not m or m.group(2) in ("execve", "clone", "clone3", "fork", "vfork"):
|
||||
continue
|
||||
quoted = re.findall(r'"([^"]*)"', m.group(3))
|
||||
if any(q == p or q.startswith(p + "/") for q in quoted for p in paths):
|
||||
found[role(int(m.group(1)))].append(line)
|
||||
return dict(found)
|
||||
|
||||
|
||||
def _kill_group(pidfile: Path) -> None:
|
||||
"""Kill the stand-in's process group: strace, the browser and its children.
|
||||
|
||||
Looking for the stand-in's path in the command lines found nothing (strace
|
||||
and its children carry the real binary's path), so the group is the handle."""
|
||||
try:
|
||||
pgid = int(pidfile.read_text().strip())
|
||||
except (OSError, ValueError):
|
||||
return
|
||||
try:
|
||||
os.killpg(pgid, signal.SIGKILL)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def _group_members(pidfile: Path) -> list:
|
||||
"""Pids still in the stand-in's process group."""
|
||||
try:
|
||||
pgid = int(pidfile.read_text().strip())
|
||||
except (OSError, ValueError):
|
||||
return []
|
||||
members = []
|
||||
for pid in os.listdir("/proc"):
|
||||
if not pid.isdigit():
|
||||
continue
|
||||
try:
|
||||
stat_line = Path("/proc/%s/stat" % pid).read_text()
|
||||
except OSError:
|
||||
continue
|
||||
fields = stat_line.rsplit(")", 1)[1].split()
|
||||
# fields: state ppid pgrp ...; a zombie is already dead.
|
||||
if fields[0] != "Z" and int(fields[2]) == pgid:
|
||||
members.append(int(pid))
|
||||
return members
|
||||
|
||||
|
||||
def _wait_for_exit(pidfile: Path, seconds: float = 10.0) -> list:
|
||||
end = time.monotonic() + seconds
|
||||
left = _group_members(pidfile)
|
||||
while left and time.monotonic() < end:
|
||||
time.sleep(0.1)
|
||||
left = _group_members(pidfile)
|
||||
return left
|
||||
|
||||
|
||||
def test_a_killed_stand_in_leaves_neither_strace_nor_the_browser(firefox_binary, tmp_path):
|
||||
"""The cleanup after a forced timeout kills everything: it launches the
|
||||
stand-in as the test does, kills it as the test's `finally` does, and
|
||||
looks for survivors."""
|
||||
_require_strace_can_trace(tmp_path)
|
||||
log = tmp_path / "strace.log"
|
||||
pidfile = tmp_path / "stand-in.pid"
|
||||
stand_in = _stand_in(firefox_binary, tmp_path / "engine", log, pidfile)
|
||||
profile = tmp_path / "profile"
|
||||
profile.mkdir()
|
||||
proc = subprocess.Popen([stand_in, "-headless", "-no-remote", "-profile", str(profile),
|
||||
"about:blank"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
try:
|
||||
end = time.monotonic() + 30
|
||||
while time.monotonic() < end and "-contentproc" not in (
|
||||
log.read_text(errors="replace") if log.exists() else ""):
|
||||
time.sleep(0.2)
|
||||
assert len(_group_members(pidfile)) >= 3, "strace and the browser did not come up"
|
||||
_kill_group(pidfile)
|
||||
proc.wait(timeout=10)
|
||||
left = _wait_for_exit(pidfile)
|
||||
finally:
|
||||
_kill_group(pidfile)
|
||||
assert not left, "processes left after the kill: %s" % [
|
||||
Path("/proc/%d/cmdline" % p).read_bytes()[:120] for p in left
|
||||
if Path("/proc/%d" % p).exists()]
|
||||
|
||||
|
||||
def test_no_process_reads_the_host_fontconfig(firefox_binary, tmp_path, engine_at_least):
|
||||
engine_at_least("firefox-60")
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
_require_strace_can_trace(tmp_path)
|
||||
log = tmp_path / "strace.log"
|
||||
tree = tmp_path / "engine"
|
||||
pidfile = tmp_path / "stand-in.pid"
|
||||
stand_in = _stand_in(firefox_binary, tree, log, pidfile)
|
||||
real = os.path.realpath(firefox_binary)
|
||||
try:
|
||||
with InvisiblePlaywright(seed=4246, binary_path=stand_in,
|
||||
headless=True) as browser:
|
||||
page = browser.new_page()
|
||||
page.set_content(_PAGE)
|
||||
# Text was laid out with real fonts: the page measured something.
|
||||
assert page.evaluate(
|
||||
"() => document.querySelector('p').getBoundingClientRect().width") > 0
|
||||
page.screenshot()
|
||||
finally:
|
||||
_kill_group(pidfile)
|
||||
|
||||
text = log.read_text(errors="replace")
|
||||
assert "-contentproc" in text, (
|
||||
"strace saw no content process, so the test could not judge one")
|
||||
found = _host_lookups(log, real)
|
||||
report = []
|
||||
for who, hits in sorted(found.items()):
|
||||
pids = sorted({int(h.split()[0]) for h in hits})
|
||||
names = sorted({q for h in hits for q in re.findall(r'"([^"]*)"', h)
|
||||
if any(q == p or q.startswith(p + "/")
|
||||
for p in _host_font_paths())})
|
||||
roots = {p: sum(1 for n in names if n == p or n.startswith(p + "/"))
|
||||
for p in _host_font_paths()}
|
||||
report.append("%s: %d calls by pids %s, %d paths (%s), first ones:"
|
||||
% (who, len(hits), pids, len(names),
|
||||
", ".join("%s %d" % kv for kv in roots.items() if kv[1])))
|
||||
report += [" " + n for n in names[:12]]
|
||||
report += [" " + h[:240] for h in hits[:4]]
|
||||
assert not found, (
|
||||
"the browser looked at the host's fontconfig (%s):\n%s"
|
||||
% (", ".join(_host_font_paths()), "\n".join(report)))
|
||||
@@ -1,4 +1,5 @@
|
||||
"""Frame identity must travel with every selector and handle."""
|
||||
import threading
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import Mock
|
||||
|
||||
@@ -163,6 +164,8 @@ def test_adopt_is_one_wire_call_for_both_crossings(element, into, expected):
|
||||
injected.session = "session"
|
||||
injected.contexts = {("widget", UTILITY_WORLD): "widget-utility",
|
||||
("payment", UTILITY_WORLD): "payment-utility"}
|
||||
# What __init__ gives it: the world waits sleep on it (invisible-core 58).
|
||||
injected._contexts_changed = threading.Condition()
|
||||
assert injected.adopt("widget", element, into=into) == "adopted"
|
||||
assert sent == [("Page.adoptNode", expected)]
|
||||
|
||||
|
||||
@@ -211,8 +211,9 @@ def test_the_page_sees_the_delay_the_caller_asked_for(firefox_binary, page_url):
|
||||
150 ms and a dwell of 300 ms can only come from the caller's `delay`."""
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
# The US keyboard, named: the persona's keyboard follows the session's language, which the runner's address decides.
|
||||
with InvisiblePlaywright(binary_path=firefox_binary, headless=True,
|
||||
humanize=False) as browser:
|
||||
humanize=False, locale="en-US") as browser:
|
||||
page = browser.new_page()
|
||||
page.goto(page_url)
|
||||
page.locator("#f").type("abcd", delay=150)
|
||||
|
||||
@@ -158,7 +158,8 @@ def test_a_real_page_measures_a_human_rhythm(firefox_binary):
|
||||
"for (const t of ['keydown','keyup'])"
|
||||
" document.getElementById('f').addEventListener(t,"
|
||||
" e => window.__e.push([t, e.key, e.timeStamp]));</script>")
|
||||
with InvisiblePlaywright(seed=42, binary_path=firefox_binary) as browser:
|
||||
# The US keyboard, named: the persona's keyboard follows the session's language, which the runner's address decides.
|
||||
with InvisiblePlaywright(seed=42, binary_path=firefox_binary, locale="en-US") as browser:
|
||||
page = browser.new_page()
|
||||
page.goto("data:text/html," + urllib.parse.quote(html))
|
||||
page.click("#f")
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
"""The launch counter is recorded by GitHub Actions, never by a machine of ours.
|
||||
|
||||
GitHub keeps only the running total of the counter asset, so a day's launches
|
||||
exist only if the total is written down that day. The snapshot used to run
|
||||
from a scheduled task on one PC with a token file beside it; when that task
|
||||
went, the badge stopped and three days of launches were lost with no error
|
||||
anywhere. These tests pin the replacement: a scheduled workflow, the script it
|
||||
runs, and the arithmetic the history has always used.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "scripts"))
|
||||
import launch_counters as lc # noqa: E402
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
WORKFLOW = ROOT / ".github" / "workflows" / "counters.yml"
|
||||
|
||||
# docs/badges/launches.svg on the badges branch as the old renderer left it.
|
||||
BADGE_461 = (
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" width="157" height="20" role="img" aria-label="browser launches: 4.61M">\n'
|
||||
"<title>browser launches: 4.61M</title>\n"
|
||||
'<linearGradient id="s" x2="0" y2="100%"><stop offset="0" stop-color="#bbb" stop-opacity=".1"/><stop offset="1" stop-opacity=".1"/></linearGradient>\n'
|
||||
'<clipPath id="r"><rect width="157" height="20" rx="3" fill="#fff"/></clipPath>\n'
|
||||
'<g clip-path="url(#r)">\n'
|
||||
'<rect width="116" height="20" fill="#555"/>\n'
|
||||
'<rect x="116" width="41" height="20" fill="#007ec6"/>\n'
|
||||
'<rect width="157" height="20" fill="url(#s)"/>\n'
|
||||
"</g>\n"
|
||||
'<g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" font-size="11">\n'
|
||||
'<text x="58.0" y="15" fill="#010101" fill-opacity=".3">browser launches</text>\n'
|
||||
'<text x="58.0" y="14">browser launches</text>\n'
|
||||
'<text x="136.5" y="15" fill="#010101" fill-opacity=".3">4.61M</text>\n'
|
||||
'<text x="136.5" y="14">4.61M</text>\n'
|
||||
"</g>\n"
|
||||
"</svg>"
|
||||
).encode()
|
||||
|
||||
|
||||
def test_the_snapshot_is_a_scheduled_workflow_with_no_personal_secret():
|
||||
text = WORKFLOW.read_text(encoding="utf-8")
|
||||
assert "schedule:" in text and "cron:" in text
|
||||
assert "scripts/launch_counters.py" in text
|
||||
assert "ref: badges" in text and "HEAD:badges" in text
|
||||
assert "secrets." not in text, "it must run on the built-in token alone"
|
||||
|
||||
|
||||
def test_the_script_reads_no_local_file_for_its_token():
|
||||
src = (ROOT / "scripts" / "launch_counters.py").read_text(encoding="utf-8")
|
||||
assert "C:/" not in src and ".ghtok" not in src
|
||||
|
||||
|
||||
def test_the_sum_gives_back_a_recorded_total():
|
||||
# 2026-11-04 row: usage_counter 2758110, usage_counter_v3 937317.
|
||||
assert lc.launches_total(2_758_110, 937_317) == 4_616_723
|
||||
|
||||
|
||||
def test_the_badge_is_byte_for_byte_the_old_one():
|
||||
assert lc.render(lc.format_count(4_616_723), lc.BADGES[0]) == BADGE_461
|
||||
|
||||
|
||||
def test_a_gap_is_not_spread_over_the_missing_days():
|
||||
hist = {"2026-11-03": {"launches_total": 10}, "2026-11-04": {"launches_total": 70},
|
||||
"2026-11-08": {"launches_total": 400}}
|
||||
assert lc.launches_per_day(hist) == [("2026-11-03", 60)]
|
||||
|
||||
|
||||
def test_a_second_run_the_same_day_keeps_the_first_value(tmp_path):
|
||||
p = tmp_path / "h.csv"
|
||||
assert lc.append_snapshot(p, "2026-11-08", {"stars": 1, "launches_total": 5})
|
||||
assert lc.append_snapshot(p, "2026-11-08", {"stars": 2, "launches_total": 6}) == []
|
||||
assert lc.read_history(p)["2026-11-08"] == {"stars": 1, "launches_total": 5}
|
||||
|
||||
|
||||
def test_a_run_writes_history_daily_and_badges(tmp_path):
|
||||
def api(path):
|
||||
if path.startswith("/repos/feder-cr/firefox_antidetect_patch/releases?"):
|
||||
if path.endswith("&page=1"):
|
||||
return [{"tag_name": "firefox-56", "assets": [
|
||||
{"name": "x.tar.gz", "download_count": 3},
|
||||
{"name": "checksums.txt", "download_count": 9}]}]
|
||||
return []
|
||||
if path == "/repos/feder-cr/firefox_antidetect_patch/releases/tags/usage-counter":
|
||||
return {"assets": [{"download_count": 2_758_110}]}
|
||||
if path == "/repos/feder-cr/invisible_playwright/releases/tags/usage-counter":
|
||||
return {"assets": [{"download_count": 937_317}]}
|
||||
if path == "/repos/feder-cr/invisible_playwright":
|
||||
return {"stargazers_count": 2554}
|
||||
raise AssertionError(path)
|
||||
|
||||
h, d, b = tmp_path / "history.csv", tmp_path / "daily.csv", tmp_path / "badges"
|
||||
h.write_text("date,key,value\n2026-11-07,launches_total,4556723\n", encoding="utf-8")
|
||||
import datetime as dt
|
||||
assert lc.run(api, h, d, b, dt.date(2026, 11, 8)) == 0
|
||||
row = lc.read_history(h)["2026-11-08"]
|
||||
assert row["launches_total"] == 4_616_723 and row["firefox-56"] == 3
|
||||
assert d.read_text(encoding="utf-8").splitlines() == ["day_utc,launches", "2026-11-07,60000"]
|
||||
assert (b / "launches.svg").read_bytes() == BADGE_461
|
||||
assert b"Stars: 2.55k" in (b / "stars.svg").read_bytes()
|
||||
@@ -0,0 +1,108 @@
|
||||
"""Math.sin, Math.cos and Math.tan give Windows' bytes on every OS.
|
||||
|
||||
A page reads the last bit of Math.sin(Math.PI / 4): Windows Firefox computes it
|
||||
with ucrtbase.dll and gets 0.7071067811865476 (0x3fe6a09e667f3bcd); Linux
|
||||
Firefox got 0.7071067811865475 (...bcc), from fdlibm, which the engine used
|
||||
outside Windows (javascript.options.use_fdlibm_for_sin_cos_tan), or from glibc
|
||||
with that pref off. Measured over 30,372 distinct hard inputs (near multiples of
|
||||
pi/4, the reduction thresholds, huge arguments; NaN results left out): fdlibm
|
||||
differs from ucrtbase on 441, glibc 2.43 on 651, one or both on 832 (Windows 11,
|
||||
WSL Ubuntu, 2026-11-08).
|
||||
|
||||
The engine now keeps Windows' value of the pref (false) everywhere, and on Linux
|
||||
libxul defines sin, cos and tan itself with ucrtbase's results (gfx/idwr/
|
||||
libm_ucrt.c in the engine series), so every call inside libxul gets them.
|
||||
|
||||
The test reads the result bits of the 4,516 inputs of
|
||||
tests/data/ucrt_sin_cos_tan.txt (those 832, and every 8th of the others), in
|
||||
the same three functions, round after round for at least MIN_SECONDS each, and
|
||||
every round must equal ucrtbase. A loop that hot for that long is where the JITs
|
||||
take over, but no page-visible API tells which tier ran a call, so the test does
|
||||
not claim one: it shows that the result does not change over a long hot run.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
DATA = Path(__file__).parent / "data" / "ucrt_sin_cos_tan.txt"
|
||||
|
||||
#: Each function runs over its ~1,500 inputs for at least this long (and at
|
||||
#: least MIN_ROUNDS rounds): millions of calls from the same loop.
|
||||
MIN_SECONDS = 3
|
||||
MIN_ROUNDS = 12
|
||||
|
||||
RUN = """
|
||||
([cases, minRounds, minSeconds]) => {
|
||||
const buf = new DataView(new ArrayBuffer(8));
|
||||
const fromHex = (h) => { buf.setBigUint64(0, BigInt("0x" + h)); return buf.getFloat64(0); };
|
||||
const toHex = (d) => { buf.setFloat64(0, d); return buf.getBigUint64(0).toString(16).padStart(16, "0"); };
|
||||
// One monomorphic function per Math function, as a page would write them.
|
||||
const fns = {
|
||||
sin(xs, out) { for (let i = 0; i < xs.length; i++) out[i] = Math.sin(xs[i]); },
|
||||
cos(xs, out) { for (let i = 0; i < xs.length; i++) out[i] = Math.cos(xs[i]); },
|
||||
tan(xs, out) { for (let i = 0; i < xs.length; i++) out[i] = Math.tan(xs[i]); },
|
||||
};
|
||||
const wrong = [];
|
||||
const rounds = {};
|
||||
for (const name of Object.keys(fns)) {
|
||||
const mine = cases.filter((c) => c[0] === name);
|
||||
const xs = new Float64Array(mine.map((c) => fromHex(c[1])));
|
||||
const want = mine.map((c) => c[2]);
|
||||
const out = new Float64Array(xs.length);
|
||||
const t0 = performance.now();
|
||||
let r = 0;
|
||||
for (; r < minRounds || performance.now() - t0 < minSeconds * 1000; r++) {
|
||||
fns[name](xs, out);
|
||||
for (let i = 0; i < xs.length; i++) {
|
||||
const got = toHex(out[i]);
|
||||
if (got !== want[i] && wrong.length < 1000) wrong.push([r, name, mine[i][1], got, want[i]]);
|
||||
}
|
||||
}
|
||||
rounds[name] = r;
|
||||
}
|
||||
return {wrong, rounds, pi4: toHex(Math.sin(Math.PI / 4)), pi4Text: String(Math.sin(Math.PI / 4))};
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def _cases():
|
||||
out = []
|
||||
for line in DATA.read_text().splitlines():
|
||||
if line and not line.startswith("#"):
|
||||
fn, x, want = line.split()
|
||||
out.append([fn, x, want])
|
||||
return out
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_the_data_holds_the_inputs_that_tell_the_libraries_apart():
|
||||
cases = _cases()
|
||||
assert {c[0] for c in cases} == {"sin", "cos", "tan"}
|
||||
assert len(cases) == 4516
|
||||
# Math.PI / 4 is in the list, with ucrtbase's sin.
|
||||
assert ["sin", "3fe921fb54442d18", "3fe6a09e667f3bcd"] in cases
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_math_sin_cos_tan_bytes_are_ucrtbase_over_a_long_hot_loop(firefox_binary, engine_at_least):
|
||||
engine_at_least("firefox-60")
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
cases = _cases()
|
||||
with InvisiblePlaywright(seed=5807, binary_path=firefox_binary, headless=True) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto("about:blank")
|
||||
result = page.evaluate(RUN, [cases, MIN_ROUNDS, MIN_SECONDS])
|
||||
|
||||
assert result["pi4"] == "3fe6a09e667f3bcd", result["pi4"]
|
||||
assert result["pi4Text"] == "0.7071067811865476"
|
||||
assert all(r >= MIN_ROUNDS for r in result["rounds"].values()), result["rounds"]
|
||||
wrong = result["wrong"]
|
||||
by_round = {}
|
||||
for r, name, *_ in wrong:
|
||||
by_round.setdefault(r, {}).setdefault(name, 0)
|
||||
by_round[r][name] += 1
|
||||
assert not wrong, "%d+ results differ from ucrtbase (round: {fn: count}) %s; first: %s; rounds %s" % (
|
||||
len(wrong), by_round, wrong[:5], result["rounds"])
|
||||
@@ -291,9 +291,23 @@ def isolated_cache_env(workspace: Path) -> dict:
|
||||
return env
|
||||
|
||||
|
||||
#: The deadline of a test that takes `clean_venv`. The module installs from the
|
||||
#: index ONCE, in that fixture, and pytest-timeout counts a fixture's setup in
|
||||
#: the first test that requests it: `--dist loadfile` keeps the module on one
|
||||
#: worker, so whichever of these tests runs first pays the README's whole
|
||||
#: block (uv, the packages from PyPI, the 110 MB engine). On 2026-11-08, with
|
||||
#: PyPI slow, that took 517 s, over run_e2e.py's 420 s per-test deadline, and
|
||||
#: the guard killed the worker on a test that was slow, not stuck. The global
|
||||
#: deadline stays tight; these tests get their own, under the block's own
|
||||
#: 1800 s cap (run_readme_block) so a real hang still ends in this file.
|
||||
INSTALL_DEADLINE_S = 900
|
||||
_install_deadline = pytest.mark.timeout(INSTALL_DEADLINE_S)
|
||||
|
||||
|
||||
# ---------- tests ----------------------------------------------------------- #
|
||||
|
||||
|
||||
@_install_deadline
|
||||
@pytest.mark.e2e
|
||||
def test_clean_install_the_way_a_user_does_it(clean_venv: Path, workspace: Path):
|
||||
"""The README's install block, from the index, into a project uv made.
|
||||
@@ -367,6 +381,7 @@ def test_clean_install_the_way_a_user_does_it(clean_venv: Path, workspace: Path)
|
||||
assert len(init) == 1 and f'--python "{floor}"' in init[0], (init, floor)
|
||||
|
||||
|
||||
@_install_deadline
|
||||
@pytest.mark.e2e
|
||||
def test_the_resolved_playwright_is_inside_the_range_the_package_declares(
|
||||
clean_venv: Path):
|
||||
@@ -418,6 +433,7 @@ def test_the_resolved_playwright_is_inside_the_range_the_package_declares(
|
||||
f"creation.")
|
||||
|
||||
|
||||
@_install_deadline
|
||||
@pytest.mark.e2e
|
||||
def test_version_command_reports_wrapper_and_binary(clean_venv: Path):
|
||||
"""`python -m invisible_playwright --version` runs and reports both the
|
||||
@@ -430,6 +446,7 @@ def test_version_command_reports_wrapper_and_binary(clean_venv: Path):
|
||||
assert "firefox-" in text, f"BINARY_VERSION not reported: {text!r}"
|
||||
|
||||
|
||||
@_install_deadline
|
||||
@pytest.mark.e2e
|
||||
def test_fetch_against_live_release(clean_venv: Path, isolated_cache_env: dict):
|
||||
"""Hit the LIVE GitHub release: download tarball + checksums.txt, parse,
|
||||
@@ -468,6 +485,7 @@ def test_fetch_against_live_release(clean_venv: Path, isolated_cache_env: dict):
|
||||
)
|
||||
|
||||
|
||||
@_install_deadline
|
||||
@pytest.mark.e2e
|
||||
def test_binary_executes_after_fetch(clean_venv: Path, isolated_cache_env: dict):
|
||||
"""After fetch, the binary cache contains a launchable Firefox."""
|
||||
@@ -505,6 +523,7 @@ def test_binary_executes_after_fetch(clean_venv: Path, isolated_cache_env: dict)
|
||||
)
|
||||
|
||||
|
||||
@_install_deadline
|
||||
@pytest.mark.e2e
|
||||
def test_playwright_launch_against_real_site(clean_venv: Path,
|
||||
isolated_cache_env: dict):
|
||||
@@ -551,6 +570,22 @@ def test_playwright_launch_against_real_site(clean_venv: Path,
|
||||
# ---------- meta: verify the test markers themselves work ------------------- #
|
||||
|
||||
|
||||
def test_every_test_that_installs_from_the_index_has_the_install_deadline():
|
||||
"""A test that takes `clean_venv` may be the one that pays the install, so
|
||||
each of them carries INSTALL_DEADLINE_S, not run_e2e.py's 420 s: the
|
||||
measured slow install (517 s) must fit, and the block's own 1800 s cap
|
||||
must stay the outer bound."""
|
||||
import inspect
|
||||
assert 517 * 1.5 <= INSTALL_DEADLINE_S < 1800
|
||||
takers = [(name, fn) for name, fn in sorted(globals().items())
|
||||
if name.startswith("test_") and callable(fn)
|
||||
and "clean_venv" in inspect.signature(fn).parameters]
|
||||
assert len(takers) >= 6, [n for n, _ in takers]
|
||||
for name, fn in takers:
|
||||
deadlines = [m.args[0] for m in getattr(fn, "pytestmark", []) if m.name == "timeout"]
|
||||
assert deadlines == [INSTALL_DEADLINE_S], (name, deadlines)
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_e2e_marker_is_excluded_by_default():
|
||||
"""Sanity check on pyproject.toml's `addopts = '-m not e2e'` - this test
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
"""A screenshot of a page with text comes back (e2e, Linux).
|
||||
|
||||
On the candidate engine of firefox-60 ``page.screenshot()`` of a page with HTML
|
||||
text never answered: the parent waited for a paint that the text never let
|
||||
finish, while a page without text, or a canvas, was fine. Every engine before
|
||||
it draws the same page, so this is not tied to an engine release: it must pass
|
||||
on all of them, headed and headless.
|
||||
|
||||
The page has serif, sans-serif and monospace text. The screenshot must answer
|
||||
within 15 seconds, and the PNG must hold pixels of more than one colour (text
|
||||
on a background), not a blank frame.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import struct
|
||||
import sys
|
||||
import time
|
||||
import zlib
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = [
|
||||
pytest.mark.e2e,
|
||||
pytest.mark.skipif(not sys.platform.startswith("linux"), reason="the Linux text path"),
|
||||
]
|
||||
|
||||
DEADLINE_S = 15
|
||||
|
||||
PAGE = ("<!doctype html><meta charset=utf-8><body style='margin:8px;background:#fff;color:#000'>"
|
||||
"<h1 style='font-family:serif'>Serif heading</h1>"
|
||||
"<p style='font-family:sans-serif;font-size:20px'>The quick brown fox jumps over the lazy dog.</p>"
|
||||
"<pre style='font-family:monospace;font-size:16px'>monospace 0123456789</pre></body>")
|
||||
|
||||
|
||||
def _pixel_bytes(png: bytes) -> bytes:
|
||||
"""The decompressed scanlines of a PNG."""
|
||||
assert png[:8] == b"\x89PNG\r\n\x1a\n", "not a PNG"
|
||||
pos, idat, width, height = 8, b"", 0, 0
|
||||
while pos < len(png):
|
||||
(length,) = struct.unpack(">I", png[pos:pos + 4])
|
||||
kind, body = png[pos + 4:pos + 8], png[pos + 8:pos + 8 + length]
|
||||
if kind == b"IHDR":
|
||||
width, height = struct.unpack(">II", body[:8])
|
||||
elif kind == b"IDAT":
|
||||
idat += body
|
||||
pos += 12 + length
|
||||
assert width > 0 and height > 0, (width, height)
|
||||
return zlib.decompress(idat)
|
||||
|
||||
|
||||
@pytest.mark.wall_clock
|
||||
@pytest.mark.parametrize("headless", [True, False], ids=["headless", "headed"])
|
||||
def test_a_screenshot_of_a_page_with_text_returns(firefox_binary, headless):
|
||||
if not headless and not os.environ.get("DISPLAY"):
|
||||
pytest.skip("a headed run needs a display (xvfb-run)")
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
with InvisiblePlaywright(seed=4246, binary_path=firefox_binary, headless=headless) as browser:
|
||||
page = browser.new_page()
|
||||
page.set_content(PAGE)
|
||||
assert page.evaluate("() => document.querySelector('p').getBoundingClientRect().width") > 0
|
||||
started = time.monotonic()
|
||||
png = page.screenshot(timeout=DEADLINE_S * 1000)
|
||||
took = time.monotonic() - started
|
||||
|
||||
assert took < DEADLINE_S, "the screenshot took %.1fs" % took
|
||||
assert len(png) > 1000, "the PNG is %d bytes" % len(png)
|
||||
pixels = _pixel_bytes(png)
|
||||
assert len(set(pixels)) > 4, "the screenshot is a blank frame"
|
||||
@@ -0,0 +1,87 @@
|
||||
"""The CSS system fonts and system colours are Windows retail's, on every OS.
|
||||
|
||||
``font: menu`` (and caption, icon, message-box, small-caption, status-bar) and
|
||||
every CSS system colour keyword, in both colour schemes, are read with
|
||||
getComputedStyle. Our engine must answer what Firefox 159 retail answers on
|
||||
Windows: fonts come from the ui.font.* prefs the core declares (never Pango or
|
||||
GTK), colours from the declared palette or from Firefox's own stand-ins.
|
||||
|
||||
tests/data/retail_159_system_theme.json is the measurement: Firefox 159 retail
|
||||
for Windows, headless, an empty profile, read through Marionette by
|
||||
scripts/measure_retail_system_theme.py. ``system-ui`` is a family keyword
|
||||
resolved by the font list (retail: the menu font), so its computed family,
|
||||
size, weight, style and stretch are compared like the others.
|
||||
|
||||
Every mismatch is listed in the failure, not just the first.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
RETAIL = json.loads((Path(__file__).parent / "data" / "retail_159_system_theme.json").read_text())
|
||||
|
||||
READ = """
|
||||
({fonts, colors}) => {
|
||||
const out = {fonts: {}, light: {}, dark: {}};
|
||||
for (const f of fonts) {
|
||||
const d = document.createElement('div');
|
||||
d.style.font = f === 'system-ui' ? '16px system-ui' : f;
|
||||
document.body.appendChild(d);
|
||||
const c = getComputedStyle(d);
|
||||
out.fonts[f] = {family: c.fontFamily, size: c.fontSize, weight: c.fontWeight,
|
||||
style: c.fontStyle, stretch: c.fontStretch};
|
||||
d.remove();
|
||||
}
|
||||
for (const scheme of ['light', 'dark']) {
|
||||
for (const k of colors) {
|
||||
const d = document.createElement('div');
|
||||
d.style.colorScheme = scheme;
|
||||
d.style.color = k;
|
||||
document.body.appendChild(d);
|
||||
out[scheme][k] = getComputedStyle(d).color;
|
||||
d.remove();
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_the_reference_has_every_font_and_both_schemes():
|
||||
assert set(RETAIL["fonts"]) == {
|
||||
"menu", "caption", "icon", "message-box", "small-caption", "status-bar", "system-ui"}
|
||||
assert set(RETAIL["light"]) == set(RETAIL["dark"])
|
||||
assert {"Highlight", "HighlightText", "Mark", "MarkText", "SelectedItem",
|
||||
"AccentColor", "LinkText", "VisitedText", "ActiveText"} <= set(RETAIL["light"])
|
||||
# Segoe UI at 9pt: 12px, normal weight, upright.
|
||||
assert RETAIL["fonts"]["menu"] == {
|
||||
"family": "Segoe UI", "size": "12px", "weight": "400", "style": "normal",
|
||||
"stretch": "100%"}
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_system_fonts_and_colours_match_windows_retail(firefox_binary, engine_at_least):
|
||||
engine_at_least("firefox-60")
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
with InvisiblePlaywright(seed=6022, binary_path=firefox_binary, headless=True) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto("about:blank")
|
||||
got = page.evaluate(READ, {"fonts": list(RETAIL["fonts"]),
|
||||
"colors": list(RETAIL["light"])})
|
||||
|
||||
wrong = []
|
||||
for name, want in RETAIL["fonts"].items():
|
||||
have = got["fonts"][name]
|
||||
if have != want:
|
||||
wrong.append("font %s: page %r, retail %r" % (name, have, want))
|
||||
for scheme in ("light", "dark"):
|
||||
for name, want in RETAIL[scheme].items():
|
||||
if got[scheme][name] != want:
|
||||
wrong.append("%s %s: page %s, retail %s" % (scheme, name, got[scheme][name], want))
|
||||
assert not wrong, ("%d system values differ from Windows retail:\n %s"
|
||||
% (len(wrong), "\n ".join(wrong)))
|
||||
@@ -12,38 +12,51 @@ profile and never restated); the list is then kept, as Firefox keeps it.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import glob
|
||||
import http.server
|
||||
import threading
|
||||
|
||||
import pytest
|
||||
|
||||
# `wall_clock`: the e2e run gives this file the machine alone, after the
|
||||
# parallel tests. Why it needs that is on HOST_STACK_MS.
|
||||
# parallel tests: the lower bounds below still read the page's clock.
|
||||
pytestmark = [pytest.mark.e2e, pytest.mark.wall_clock]
|
||||
|
||||
_SEED = 42
|
||||
|
||||
#: The smallest time the host's audio stack added to an enumeration before
|
||||
#: firefox-45 (287-351 ms on our Windows build, the docstring above). The
|
||||
#: margin over the declared time is half of it: wide enough for a runner's own
|
||||
#: noise, narrow enough that the defect it guards cannot hide in it.
|
||||
#:
|
||||
#: These bounds used to be absolute - the first within declared + 110 ms, the
|
||||
#: second under 50 ms - and a CI run with four browsers crossed each of them
|
||||
#: once in the release of 0.35.10 (656 against 543 + 110, then exactly 50),
|
||||
#: both green again on the same SHA ([B312]). A bound that the load of the
|
||||
#: machine can cross is a bound on the machine, not on the engine.
|
||||
#:
|
||||
#: ⛔ AND THE RELATIVE BOUND THAT REPLACED THEM CROSSED TOO, because its premise
|
||||
#: was false: that the load both calls share cancels out of their difference.
|
||||
#: It does not. The declared wait is dispatched on the parent process's main
|
||||
#: thread, which four browsers make late, and only the FIRST call waits it; the
|
||||
#: second pays the round trip alone. Measured on a CI run of PR #355: 807 ms of
|
||||
#: difference against 686, green again on the same SHA. No margin holds beside
|
||||
#: four browsers, so the test no longer runs beside them.
|
||||
HOST_STACK_MS = 287
|
||||
|
||||
MEASURE = """async () => {
|
||||
class _Page(http.server.BaseHTTPRequestHandler):
|
||||
"""A page on 127.0.0.1: a potentially trustworthy origin, so mediaDevices exists."""
|
||||
|
||||
def do_GET(self):
|
||||
body = b"<!doctype html><title>e</title>"
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/html")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
|
||||
def _measure(firefox_binary):
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), _Page)
|
||||
srv.daemon_threads = True
|
||||
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||
try:
|
||||
with InvisiblePlaywright(seed=_SEED, binary_path=firefox_binary,
|
||||
headless=True) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto("http://127.0.0.1:%d/" % srv.server_address[1])
|
||||
return page.evaluate(MEASURE)
|
||||
finally:
|
||||
srv.shutdown()
|
||||
|
||||
|
||||
MEASURE ="""async () => {
|
||||
const out = [];
|
||||
for (let i = 0; i < 2; i++) {
|
||||
const t0 = performance.now();
|
||||
@@ -55,31 +68,7 @@ MEASURE = """async () => {
|
||||
|
||||
|
||||
def test_the_first_enumeration_takes_the_declared_time(firefox_binary):
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
class H(http.server.BaseHTTPRequestHandler):
|
||||
def do_GET(self):
|
||||
body = b"<!doctype html><title>e</title>"
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/html")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), H)
|
||||
srv.daemon_threads = True
|
||||
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||
try:
|
||||
with InvisiblePlaywright(seed=_SEED, binary_path=firefox_binary,
|
||||
headless=True) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto("http://127.0.0.1:%d/" % srv.server_address[1])
|
||||
(first, kinds), (second, _) = page.evaluate(MEASURE)
|
||||
finally:
|
||||
srv.shutdown()
|
||||
(first, kinds), (second, _) = _measure(firefox_binary)
|
||||
from invisible_core._fpforge import generate_profile
|
||||
declared = generate_profile(_SEED).hardware.media_enumeration_ms
|
||||
assert kinds == "audioinput,videoinput"
|
||||
@@ -88,8 +77,32 @@ def test_the_first_enumeration_takes_the_declared_time(firefox_binary):
|
||||
# Kept, as Firefox keeps it: a list asked again would wait the declared
|
||||
# time again.
|
||||
assert second < declared / 2, (second, declared)
|
||||
# And nothing on top of it. The second call is the same round trip to the
|
||||
# parent without the wait, so the difference is the declared time plus
|
||||
# whatever the host added. It is NOT free of the machine's load (see
|
||||
# HOST_STACK_MS): this holds because the run gives the test the machine.
|
||||
assert first - second < declared + HOST_STACK_MS / 2, (first, second, declared)
|
||||
# ⛔ NO UPPER BOUND HERE ANY MORE. "Nothing on top of the declared time"
|
||||
# was measured with the page's clock against a runner whose load delays the
|
||||
# parent's main thread by 150-200 ms (741 and 702 against 543 + 143 on the
|
||||
# same day, green on rerun). Whether the host was asked is now read from
|
||||
# inside the engine: the next test.
|
||||
|
||||
|
||||
def _engine_release() -> int:
|
||||
import invisible_core
|
||||
return int(invisible_core.__version__.split(".")[0])
|
||||
|
||||
|
||||
def test_the_engine_waits_the_declared_time_and_never_asks_the_host(firefox_binary, tmp_path, monkeypatch):
|
||||
"""From inside the engine, whatever the load of the machine: the declared
|
||||
enumeration logs the wait it dispatched, and the host's speakers are never
|
||||
asked (MOZ_LOG=StealthMediaEnumeration, from firefox-57)."""
|
||||
if _engine_release() < 57:
|
||||
pytest.skip("the engine logs the enumeration from firefox-57")
|
||||
from invisible_core._fpforge import generate_profile
|
||||
|
||||
log = tmp_path / "enum"
|
||||
monkeypatch.setenv("MOZ_LOG", "sync,StealthMediaEnumeration:4")
|
||||
monkeypatch.setenv("MOZ_LOG_FILE", str(log))
|
||||
_measure(firefox_binary)
|
||||
text ="".join(open(f, encoding="utf-8", errors="replace").read()
|
||||
for f in glob.glob(str(log) + "*"))
|
||||
declared = generate_profile(_SEED).hardware.media_enumeration_ms
|
||||
assert text.count("declared wait: %d ms" % declared) == 1, text[-2000:]
|
||||
assert "host speakers asked: yes" not in text, text[-2000:]
|
||||
@@ -12,16 +12,16 @@ and the keyboard; this file tests the wiring, on the public pieces.
|
||||
from __future__ import annotations
|
||||
|
||||
from invisible_core.juggler import PageActs
|
||||
from invisible_core.juggler.keyboard import layout_for
|
||||
from invisible_core.juggler.keyboard import layouts_for
|
||||
|
||||
from invisible_playwright._juggler.server import BrowserDispatcher, keyboard_layout_for
|
||||
from invisible_playwright._juggler.server import BrowserDispatcher, keyboard_layouts_for
|
||||
|
||||
|
||||
def test_the_layout_comes_from_the_language_the_launcher_wrote():
|
||||
assert keyboard_layout_for is layout_for
|
||||
assert keyboard_layout_for("it-IT,it,en-US,en") == "00000410"
|
||||
assert keyboard_layout_for("en-US,en") == "00000409"
|
||||
assert keyboard_layout_for("") == "00000409"
|
||||
assert keyboard_layouts_for is layouts_for
|
||||
assert keyboard_layouts_for("it-IT,it,en-US,en") == ["00000410"]
|
||||
assert keyboard_layouts_for("en-US,en") == ["00000409"]
|
||||
assert keyboard_layouts_for("") == ["00000409"]
|
||||
|
||||
|
||||
def test_the_session_hands_the_server_its_language_and_country_s_keyboard():
|
||||
@@ -35,7 +35,20 @@ def test_the_session_hands_the_server_its_language_and_country_s_keyboard():
|
||||
prefs = build_prefs(profile=generate_profile(seed=4242), locale=SessionLocale(("de", "en-US", "en"), "CH"),
|
||||
timezone="Europe/Zurich", extra_prefs=None, virtual_display=False,
|
||||
cursor_engine="python", humanize=True, session_seed=4242)
|
||||
assert prefs[KEYBOARD_LAYOUT_PREF] == "00000807"
|
||||
# Swiss French is the second keyboard Windows installs with Swiss German.
|
||||
assert prefs[KEYBOARD_LAYOUT_PREF] == "0807:00000807;100c:0000100C"
|
||||
|
||||
|
||||
def test_a_russian_session_has_english_as_its_second_keyboard():
|
||||
"""Windows installs English (US) with Russian: the persona types a Latin
|
||||
letter on it, so the pref carries both, the language's first."""
|
||||
from invisible_core import SessionLocale, generate_profile
|
||||
from invisible_playwright._juggler.server import KEYBOARD_LAYOUT_PREF
|
||||
from invisible_playwright._session import build_prefs
|
||||
prefs = build_prefs(profile=generate_profile(seed=4242), locale=SessionLocale(("ru-RU", "ru"), "RU"),
|
||||
timezone="Europe/Moscow", extra_prefs=None, virtual_display=False,
|
||||
cursor_engine="python", humanize=True, session_seed=4242)
|
||||
assert prefs[KEYBOARD_LAYOUT_PREF] == "0419:00000419;0409:00000409"
|
||||
|
||||
|
||||
def test_the_browser_hands_its_layout_to_every_page(monkeypatch):
|
||||
|
||||
@@ -22,8 +22,9 @@ PAGE = ("<!doctype html><input id=i><input id=j><script>window.log = [];"
|
||||
def test_text_with_a_character_without_a_key_is_typed(firefox_binary):
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
# The US keyboard, named: the persona's keyboard follows the session's language, which the runner's address decides.
|
||||
with InvisiblePlaywright(seed=42, binary_path=firefox_binary,
|
||||
headless=True) as browser:
|
||||
headless=True, locale="en-US") as browser:
|
||||
page = browser.new_page()
|
||||
page.set_content(PAGE)
|
||||
page.type("#i", "café")
|
||||
|
||||
@@ -0,0 +1,192 @@
|
||||
"""VideoFrame.timestamp on a real H.264 B-frame stream is in retail's own order.
|
||||
|
||||
ff_h264_decoder (h264dec.c) does not set FF_CODEC_CAP_SETS_FRAME_PROPS: without
|
||||
the engine's own reorder buffer (dom/media/platforms/ffmpeg/
|
||||
FFmpegVideoDecoder.cpp, mPendingFrameTimes), ffmpeg's generic layer stamps
|
||||
every frame leaving avcodec_receive_frame() with the pts of the most recently
|
||||
SENT packet, not the one that produced that image, so VideoFrame.timestamp (a
|
||||
page reading WebCodecs output sees it directly) comes out reordered on a
|
||||
B-frame stream even though the decoded image content is already correct. REA
|
||||
on media/ffvpx/libavcodec/decode.c, confirmed with a real build
|
||||
(MOZ_LOG="FFmpegVideo:5") and confirmed as a Mozilla-wrapper-level gap (the
|
||||
same stream decoded with Firefox 159.0 retail Linux's own system libavcodec
|
||||
reproduces the identical broken sequence).
|
||||
|
||||
The stream is the same 96-frame 1080p clip measured in invisible_WebCodecs
|
||||
(captures/h264-1080p-bframes/h264_8bit_1920x1080.h264, has_b_frames 2, sha256
|
||||
04da8f4dcbb8bc0f72749c0170d0684591aa10b9f8d04486a199dff84e0d51be), vendored
|
||||
here at tests/data/webcodecs_h264_1080p_bframes.annexb. The access units are
|
||||
split client-side with the exact same algorithm as
|
||||
invisible_WebCodecs/scripts/probe.html (splitAccessUnits), which is how a
|
||||
real page would do it, and each chunk is tagged timestamp = index * 41667 µs
|
||||
in bitstream order - exactly like the browser-side probe that produced
|
||||
captures/h264-1080p-bframes/retail-win/result.json. That capture (Firefox
|
||||
159.0 retail Windows) is the ground truth this test compares against: 96
|
||||
frames, duration 41667 each, strictly the dense sequence 0, 41667, 83334, ...,
|
||||
95*41667 in output order.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
from http.server import BaseHTTPRequestHandler
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from _servers import LocalServer
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
_DATA_FILE = Path(__file__).parent / "data" / "webcodecs_h264_1080p_bframes.annexb"
|
||||
_FRAME_US = 41667
|
||||
_EXPECTED_FRAMES = 96
|
||||
|
||||
_PAGE = """
|
||||
async (frameUs) => {
|
||||
const result = {frames: [], errors: []};
|
||||
if (typeof VideoDecoder === 'undefined') {
|
||||
result.errors.push('VideoDecoder is not defined');
|
||||
return result;
|
||||
}
|
||||
const bytes = new Uint8Array(await (await fetch('/h264.annexb')).arrayBuffer());
|
||||
|
||||
// Same access-unit split as invisible_WebCodecs/scripts/probe.html
|
||||
// (splitAccessUnits): a new AU starts at an AUD, or at a VCL NAL with
|
||||
// first_mb_in_slice == 0 when the current AU already holds a VCL. Non-VCL
|
||||
// NALs (SEI, SPS, PPS) right before that VCL go to the new AU.
|
||||
function startCodes(b) {
|
||||
const pos = [];
|
||||
for (let i = 0; i + 3 < b.length; i++) {
|
||||
if (b[i] === 0 && b[i + 1] === 0 && b[i + 2] === 1) pos.push(i);
|
||||
}
|
||||
return pos;
|
||||
}
|
||||
const nalType = (b) => b & 0x1f;
|
||||
const isAud = (t) => t === 9;
|
||||
const isVcl = (t) => t >= 1 && t <= 5;
|
||||
const isKey = (t) => t === 5;
|
||||
const firstSlice = (b, h) => (b[h + 1] & 0x80) !== 0;
|
||||
function splitAccessUnits(b) {
|
||||
const sc = startCodes(b);
|
||||
const starts = [0];
|
||||
let curHasVcl = false, prevVcl = false, runStart = null;
|
||||
for (const i of sc) {
|
||||
const h = i + 3;
|
||||
const t = nalType(b[h]);
|
||||
if (isAud(t)) {
|
||||
if (curHasVcl) starts.push(i);
|
||||
curHasVcl = false; prevVcl = false; runStart = null;
|
||||
} else if (isVcl(t)) {
|
||||
if (firstSlice(b, h) && curHasVcl) {
|
||||
starts.push(runStart ?? i);
|
||||
curHasVcl = false;
|
||||
}
|
||||
curHasVcl = true; prevVcl = true; runStart = null;
|
||||
} else if (prevVcl && runStart === null) {
|
||||
runStart = i;
|
||||
}
|
||||
}
|
||||
const aus = [];
|
||||
for (let k = 0; k < starts.length; k++) {
|
||||
const s = starts[k];
|
||||
let e = k + 1 < starts.length ? starts[k + 1] : b.length;
|
||||
while (e > s && b[e - 1] === 0) e--;
|
||||
aus.push(b.subarray(s, e));
|
||||
}
|
||||
return aus;
|
||||
}
|
||||
function auIsKey(au) {
|
||||
for (const i of startCodes(au)) {
|
||||
if (i + 3 < au.length && isKey(nalType(au[i + 3]))) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const aus = splitAccessUnits(bytes);
|
||||
result.auCount = aus.length;
|
||||
const config = {codec: 'avc3.640028', codedWidth: 1920, codedHeight: 1080};
|
||||
const support = await VideoDecoder.isConfigSupported(config);
|
||||
result.supported = support.supported;
|
||||
if (!support.supported) {
|
||||
result.errors.push('isConfigSupported is false');
|
||||
return result;
|
||||
}
|
||||
await new Promise((resolve) => {
|
||||
const decoder = new VideoDecoder({
|
||||
output: (frame) => {
|
||||
result.frames.push({timestamp: frame.timestamp, duration: frame.duration});
|
||||
frame.close();
|
||||
},
|
||||
error: (e) => result.errors.push(String(e)),
|
||||
});
|
||||
decoder.configure(config);
|
||||
aus.forEach((au, i) => {
|
||||
decoder.decode(new EncodedVideoChunk({
|
||||
type: auIsKey(au) ? 'key' : 'delta',
|
||||
timestamp: i * frameUs,
|
||||
duration: frameUs,
|
||||
data: au,
|
||||
}));
|
||||
});
|
||||
decoder.flush().then(() => { decoder.close(); resolve(); });
|
||||
});
|
||||
return result;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
class _AnnexbHandler(BaseHTTPRequestHandler):
|
||||
def do_GET(self):
|
||||
if self.path == "/h264.annexb":
|
||||
body = _DATA_FILE.read_bytes()
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "application/octet-stream")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
else:
|
||||
body = b"<!doctype html><title>webcodecs-h264-bframe-pts</title>"
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/html")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
|
||||
def test_webcodecs_h264_bframe_pts_matches_retail_order(firefox_binary, engine_at_least):
|
||||
engine_at_least("firefox-60")
|
||||
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
with LocalServer(("127.0.0.1", 0), _AnnexbHandler) as srv:
|
||||
port = srv.server_address[1]
|
||||
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||
try:
|
||||
with InvisiblePlaywright(
|
||||
seed=4260, binary_path=firefox_binary, headless=True,
|
||||
extra_prefs={
|
||||
"dom.media.webcodecs.enabled": True,
|
||||
"media.ffvpx.enabled": True,
|
||||
# Scope of the fix: the software CreateImage() path only.
|
||||
"media.gpu-process-decoder": False,
|
||||
"media.rdd-process.enabled": False,
|
||||
},
|
||||
) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto("http://127.0.0.1:%d/" % port)
|
||||
got = page.evaluate(_PAGE, _FRAME_US)
|
||||
finally:
|
||||
srv.shutdown()
|
||||
|
||||
assert not got["errors"], "WebCodecs errors decoding the B-frame clip: %s" % got["errors"]
|
||||
assert got.get("supported"), "avc3.640028 is not isConfigSupported: %s" % got
|
||||
assert got["auCount"] == _EXPECTED_FRAMES, got
|
||||
assert len(got["frames"]) == _EXPECTED_FRAMES, got
|
||||
for k, frame in enumerate(got["frames"]):
|
||||
assert frame["timestamp"] == k * _FRAME_US, (
|
||||
"output frame %d: timestamp %r, expected %r (retail's own order)"
|
||||
% (k, frame["timestamp"], k * _FRAME_US))
|
||||
assert frame["duration"] == _FRAME_US, (k, frame)
|
||||
@@ -0,0 +1,250 @@
|
||||
"""With the engine on, WebCodecs decodes in software even when the page asks
|
||||
for hardware - VideoFrame.copyTo(RGBA) matches the software reference bit for
|
||||
bit.
|
||||
|
||||
REA (C:/ff/invisible_WebCodecs/notes/nv12-rgb-conversion.md) found that
|
||||
WebCodecs' D3D11/DXVA hardware decode path does its NV12->RGB conversion in
|
||||
the GPU (``ID3D11VideoContext::VideoProcessorBlt``), which depends on the
|
||||
driver: a host dependency no two machines are guaranteed to agree on, and
|
||||
exactly the kind of value the engine's own rule 3 kills at the call that would
|
||||
read the host. dom/media/webcodecs/DecoderTemplate.cpp's
|
||||
``ShouldPreferSoftwareDecoder`` makes the decoder ignore the page's
|
||||
``hardwareAcceleration`` entirely while the engine is on
|
||||
(``gfx::StealthEngineActive()``): always software (libyuv, fixed Firefox
|
||||
code), never the driver's own blit.
|
||||
|
||||
This is firefox-60 checklist goal 6b: frames a page reads through WebCodecs
|
||||
must never be converted by the host's GPU VideoProcessor; with the engine on
|
||||
it stays on the libyuv path, verified by an e2e on the copyTo hash matching
|
||||
retail's software path.
|
||||
|
||||
Same stream as test_webcodecs_h264_bframe_pts_order_e2e.py (the 96-frame 1080p
|
||||
clip, has_b_frames 2, vendored at
|
||||
tests/data/webcodecs_h264_1080p_bframes.annexb, sha256
|
||||
04da8f4dcbb8bc0f72749c0170d0684591aa10b9f8d04486a199dff84e0d51be), decoded the
|
||||
same way (access units split client-side like
|
||||
invisible_WebCodecs/scripts/probe.html's splitAccessUnits), but the page's
|
||||
config explicitly asks for ``hardwareAcceleration: "prefer-hardware"`` - the
|
||||
opposite of what the engine must actually do. For every output frame the page
|
||||
computes SHA-256 of ``frame.copyTo(buf, {format: "RGBA"})``, exactly like
|
||||
probe.html did to produce the reference capture.
|
||||
|
||||
The reference is captures/h264-1080p-bframes/retail-win/result.json (Firefox
|
||||
159.0 retail Windows, headless - which turns DXVA off on retail too, so that
|
||||
capture is itself the SOFTWARE path, per its own meta.json
|
||||
``"hardware_decode": false``): 96 RGBA hashes, one per frame index, vendored
|
||||
here at tests/data/webcodecs_h264_1080p_bframes_rgba_sha256.json so this test
|
||||
does not depend on the private study repo being checked out beside this one.
|
||||
|
||||
On a VM with no GPU this test runs and asserts the same thing it would with a
|
||||
real GPU present: there is no hardware path to force into software here, so a
|
||||
pass only says libyuv's output has not drifted from the reference. What it
|
||||
actually guards against is a regression that gives the engine's WebCodecs a
|
||||
real hardware path again while leaving the page's request wired straight
|
||||
through - the day that happens on a machine with a GPU, this hash stops
|
||||
matching.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import threading
|
||||
from http.server import BaseHTTPRequestHandler
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from _servers import LocalServer
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
_DATA_FILE = Path(__file__).parent / "data" / "webcodecs_h264_1080p_bframes.annexb"
|
||||
_REFERENCE_FILE = (
|
||||
Path(__file__).parent / "data" / "webcodecs_h264_1080p_bframes_rgba_sha256.json"
|
||||
)
|
||||
_FRAME_US = 41667
|
||||
_EXPECTED_FRAMES = 96
|
||||
|
||||
_PAGE = """
|
||||
async (frameUs) => {
|
||||
const result = {frames: [], errors: []};
|
||||
if (typeof VideoDecoder === 'undefined') {
|
||||
result.errors.push('VideoDecoder is not defined');
|
||||
return result;
|
||||
}
|
||||
const bytes = new Uint8Array(await (await fetch('/h264.annexb')).arrayBuffer());
|
||||
|
||||
// Same access-unit split as invisible_WebCodecs/scripts/probe.html
|
||||
// (splitAccessUnits): a new AU starts at an AUD, or at a VCL NAL with
|
||||
// first_mb_in_slice == 0 when the current AU already holds a VCL. Non-VCL
|
||||
// NALs (SEI, SPS, PPS) right before that VCL go to the new AU.
|
||||
function startCodes(b) {
|
||||
const pos = [];
|
||||
for (let i = 0; i + 3 < b.length; i++) {
|
||||
if (b[i] === 0 && b[i + 1] === 0 && b[i + 2] === 1) pos.push(i);
|
||||
}
|
||||
return pos;
|
||||
}
|
||||
const nalType = (b) => b & 0x1f;
|
||||
const isAud = (t) => t === 9;
|
||||
const isVcl = (t) => t >= 1 && t <= 5;
|
||||
const isKey = (t) => t === 5;
|
||||
const firstSlice = (b, h) => (b[h + 1] & 0x80) !== 0;
|
||||
function splitAccessUnits(b) {
|
||||
const sc = startCodes(b);
|
||||
const starts = [0];
|
||||
let curHasVcl = false, prevVcl = false, runStart = null;
|
||||
for (const i of sc) {
|
||||
const h = i + 3;
|
||||
const t = nalType(b[h]);
|
||||
if (isAud(t)) {
|
||||
if (curHasVcl) starts.push(i);
|
||||
curHasVcl = false; prevVcl = false; runStart = null;
|
||||
} else if (isVcl(t)) {
|
||||
if (firstSlice(b, h) && curHasVcl) {
|
||||
starts.push(runStart ?? i);
|
||||
curHasVcl = false;
|
||||
}
|
||||
curHasVcl = true; prevVcl = true; runStart = null;
|
||||
} else if (prevVcl && runStart === null) {
|
||||
runStart = i;
|
||||
}
|
||||
}
|
||||
const aus = [];
|
||||
for (let k = 0; k < starts.length; k++) {
|
||||
const s = starts[k];
|
||||
let e = k + 1 < starts.length ? starts[k + 1] : b.length;
|
||||
while (e > s && b[e - 1] === 0) e--;
|
||||
aus.push(b.subarray(s, e));
|
||||
}
|
||||
return aus;
|
||||
}
|
||||
function auIsKey(au) {
|
||||
for (const i of startCodes(au)) {
|
||||
if (i + 3 < au.length && isKey(nalType(au[i + 3]))) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
async function sha256Hex(buf) {
|
||||
const d = await crypto.subtle.digest('SHA-256', buf);
|
||||
return [...new Uint8Array(d)].map((x) => x.toString(16).padStart(2, '0')).join('');
|
||||
}
|
||||
|
||||
const aus = splitAccessUnits(bytes);
|
||||
result.auCount = aus.length;
|
||||
const config = {
|
||||
codec: 'avc3.640028',
|
||||
codedWidth: 1920,
|
||||
codedHeight: 1080,
|
||||
// The opposite of what the engine must actually do: this must make no
|
||||
// difference while the engine is on.
|
||||
hardwareAcceleration: 'prefer-hardware',
|
||||
};
|
||||
const support = await VideoDecoder.isConfigSupported(config);
|
||||
result.supported = support.supported;
|
||||
if (!support.supported) {
|
||||
result.errors.push('isConfigSupported is false');
|
||||
return result;
|
||||
}
|
||||
|
||||
let chain = Promise.resolve();
|
||||
async function handleFrame(frame) {
|
||||
const row = {timestamp: frame.timestamp, duration: frame.duration, rgbaSha256: null};
|
||||
try {
|
||||
const size = frame.allocationSize({format: 'RGBA'});
|
||||
const buf = new Uint8Array(size);
|
||||
await frame.copyTo(buf, {format: 'RGBA'});
|
||||
row.rgbaSha256 = await sha256Hex(buf.buffer);
|
||||
} catch (e) {
|
||||
result.errors.push('copyTo: ' + String(e));
|
||||
}
|
||||
result.frames.push(row);
|
||||
frame.close();
|
||||
}
|
||||
|
||||
await new Promise((resolve) => {
|
||||
const decoder = new VideoDecoder({
|
||||
output: (frame) => { chain = chain.then(() => handleFrame(frame)); },
|
||||
error: (e) => result.errors.push(String(e)),
|
||||
});
|
||||
decoder.configure(config);
|
||||
aus.forEach((au, i) => {
|
||||
decoder.decode(new EncodedVideoChunk({
|
||||
type: auIsKey(au) ? 'key' : 'delta',
|
||||
timestamp: i * frameUs,
|
||||
duration: frameUs,
|
||||
data: au,
|
||||
}));
|
||||
});
|
||||
decoder.flush().then(() => chain).then(() => { decoder.close(); resolve(); });
|
||||
});
|
||||
return result;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
class _AnnexbHandler(BaseHTTPRequestHandler):
|
||||
def do_GET(self):
|
||||
if self.path == "/h264.annexb":
|
||||
body = _DATA_FILE.read_bytes()
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "application/octet-stream")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
else:
|
||||
body = (
|
||||
b"<!doctype html>"
|
||||
b"<title>webcodecs-h264-software-decode-ignores-hardware-request</title>"
|
||||
)
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/html")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
|
||||
def test_webcodecs_h264_software_decode_matches_retail_even_with_hardware_request(
|
||||
firefox_binary, engine_at_least
|
||||
):
|
||||
engine_at_least("firefox-60")
|
||||
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
reference = json.loads(_REFERENCE_FILE.read_text(encoding="utf-8"))
|
||||
expected_hashes = reference["rgbaSha256ByIndex"]
|
||||
assert len(expected_hashes) == _EXPECTED_FRAMES, reference
|
||||
|
||||
with LocalServer(("127.0.0.1", 0), _AnnexbHandler) as srv:
|
||||
port = srv.server_address[1]
|
||||
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||
try:
|
||||
with InvisiblePlaywright(
|
||||
seed=4260, binary_path=firefox_binary, headless=True,
|
||||
extra_prefs={
|
||||
"dom.media.webcodecs.enabled": True,
|
||||
"media.ffvpx.enabled": True,
|
||||
},
|
||||
) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto("http://127.0.0.1:%d/" % port)
|
||||
got = page.evaluate(_PAGE, _FRAME_US)
|
||||
finally:
|
||||
srv.shutdown()
|
||||
|
||||
assert not got["errors"], "WebCodecs errors decoding the B-frame clip: %s" % got["errors"]
|
||||
assert got.get("supported"), "avc3.640028 is not isConfigSupported: %s" % got
|
||||
assert got["auCount"] == _EXPECTED_FRAMES, got
|
||||
assert len(got["frames"]) == _EXPECTED_FRAMES, got
|
||||
for k, (frame, expected) in enumerate(zip(got["frames"], expected_hashes)):
|
||||
assert frame["timestamp"] == k * _FRAME_US, (
|
||||
"output frame %d: timestamp %r, expected %r"
|
||||
% (k, frame["timestamp"], k * _FRAME_US))
|
||||
assert frame["rgbaSha256"] == expected, (
|
||||
"frame %d: copyTo(RGBA) sha256 %r does not match the software "
|
||||
"reference %r - with the engine on this must hold regardless of "
|
||||
"hardwareAcceleration: 'prefer-hardware'"
|
||||
% (k, frame["rgbaSha256"], expected))
|
||||
@@ -0,0 +1,155 @@
|
||||
"""WebCodecs decodes H.264 on a Linux host that has no libavcodec/libavutil.
|
||||
|
||||
A page tells a host whose system ffmpeg decodes the stream from one where the
|
||||
engine's own ffvpx does by whether ``VideoDecoder`` still produces frames once
|
||||
``libavcodec``/``libavutil`` are gone from the host: the engine ships its own
|
||||
copy (``media/ffvpx``) and must decode with it, never by falling back to a
|
||||
system library that may or may not be there. With a host libavcodec present,
|
||||
decoding succeeds on every engine (the system library would mask a missing
|
||||
ffvpx), so this test only means something where there is none: the gate
|
||||
removes libavcodec/libavutil from its Linux legs (same schema as the Mesa
|
||||
check, see ``test_webgl2_exists_without_host_mesa_linux_e2e.py``), and a
|
||||
machine that still has one skips it.
|
||||
|
||||
The stream is ``webcodecs/h264.annexb`` of web-platform-tests (10 Annex B
|
||||
frames, 320x240), vendored at ``tests/data/webcodecs_h264.annexb``; the chunk
|
||||
offsets are those of ``webcodecs/videoDecoder-codec-specific-setup.js``
|
||||
(``H264_ANNEXB_DATA``), the same ones the manual check in
|
||||
``media/ffvpx/test/webcodecs_h264/test.html`` uses.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import glob
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
from http.server import BaseHTTPRequestHandler
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from _servers import LocalServer
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
LIBDIR = "/usr/lib/x86_64-linux-gnu"
|
||||
HOST_LIBAVCODEC = (
|
||||
"libavcodec.so*",
|
||||
"libavutil.so*",
|
||||
)
|
||||
|
||||
_DATA_FILE = Path(__file__).parent / "data" / "webcodecs_h264.annexb"
|
||||
|
||||
# Offsets of webcodecs/videoDecoder-codec-specific-setup.js (H264_ANNEXB_DATA),
|
||||
# the same ones media/ffvpx/test/webcodecs_h264/test.html decodes.
|
||||
_CHUNKS = [
|
||||
(0, 4175), (4175, 602), (4777, 473), (5250, 559), (5809, 585),
|
||||
(6394, 517), (6911, 530), (7441, 521), (7962, 452), (8414, 526),
|
||||
]
|
||||
|
||||
_PAGE = """
|
||||
async (chunks) => {
|
||||
const result = {frames: 0, sizes: [], errors: []};
|
||||
if (typeof VideoDecoder === 'undefined') {
|
||||
result.errors.push('VideoDecoder is not defined');
|
||||
return result;
|
||||
}
|
||||
const config = {
|
||||
codec: 'avc1.64000b',
|
||||
codedWidth: 320,
|
||||
codedHeight: 240,
|
||||
displayAspectWidth: 320,
|
||||
displayAspectHeight: 240,
|
||||
};
|
||||
const support = await VideoDecoder.isConfigSupported(config);
|
||||
result.supported = support.supported;
|
||||
if (!support.supported) {
|
||||
result.errors.push('isConfigSupported is false');
|
||||
return result;
|
||||
}
|
||||
const buf = new Uint8Array(await (await fetch('/h264.annexb')).arrayBuffer());
|
||||
await new Promise((resolve) => {
|
||||
const decoder = new VideoDecoder({
|
||||
output: (frame) => {
|
||||
result.frames++;
|
||||
result.sizes.push(frame.codedWidth + 'x' + frame.codedHeight);
|
||||
frame.close();
|
||||
},
|
||||
error: (e) => result.errors.push(String(e)),
|
||||
});
|
||||
decoder.configure(config);
|
||||
chunks.forEach(([offset, size], i) => {
|
||||
decoder.decode(new EncodedVideoChunk({
|
||||
type: i === 0 ? 'key' : 'delta',
|
||||
timestamp: i * 33333,
|
||||
data: buf.subarray(offset, offset + size),
|
||||
}));
|
||||
});
|
||||
decoder.flush().then(() => { decoder.close(); resolve(); });
|
||||
});
|
||||
return result;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def _host_libavcodec_files() -> list:
|
||||
out = []
|
||||
for pattern in HOST_LIBAVCODEC:
|
||||
out += glob.glob(os.path.join(LIBDIR, pattern))
|
||||
return sorted(out)
|
||||
|
||||
|
||||
class _AnnexbHandler(BaseHTTPRequestHandler):
|
||||
def do_GET(self):
|
||||
if self.path == "/h264.annexb":
|
||||
body = _DATA_FILE.read_bytes()
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "application/octet-stream")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
else:
|
||||
body = b"<!doctype html><title>webcodecs-h264</title>"
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/html")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
|
||||
def test_webcodecs_h264_decodes_on_a_host_without_libavcodec(firefox_binary, engine_at_least):
|
||||
engine_at_least("firefox-60")
|
||||
if not sys.platform.startswith("linux"):
|
||||
pytest.skip("the host libavcodec/libavutil that could mask a missing ffvpx are Linux libraries")
|
||||
present = _host_libavcodec_files()
|
||||
if present:
|
||||
pytest.skip("this host has a libavcodec (%s ...): decoding succeeds with one on every "
|
||||
"engine, so the test proves nothing here" % present[0])
|
||||
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
with LocalServer(("127.0.0.1", 0), _AnnexbHandler) as srv:
|
||||
port = srv.server_address[1]
|
||||
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||
try:
|
||||
with InvisiblePlaywright(
|
||||
seed=4260, binary_path=firefox_binary, headless=True,
|
||||
extra_prefs={
|
||||
"dom.media.webcodecs.enabled": True,
|
||||
"media.ffvpx.enabled": True,
|
||||
"media.ffmpeg.enabled": False,
|
||||
},
|
||||
) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto("http://127.0.0.1:%d/" % port)
|
||||
got = page.evaluate(_PAGE, _CHUNKS)
|
||||
finally:
|
||||
srv.shutdown()
|
||||
|
||||
assert not got["errors"], "WebCodecs errors without a host libavcodec: %s" % got["errors"]
|
||||
assert got.get("supported"), "avc1.64000b is not isConfigSupported: %s" % got
|
||||
assert got["frames"] == 10, got
|
||||
assert got["sizes"] == ["320x240"] * 10, got
|
||||
@@ -0,0 +1,77 @@
|
||||
"""WebGL2 exists on a Linux host that has no Mesa.
|
||||
|
||||
A page tells a host with no GL from one with a Mesa by `getContext("webgl2")`
|
||||
returning null. The engine's WebGL draws on the GL it ships (llvmpipe behind
|
||||
EGL), so what the host has or lacks must not decide whether WebGL exists; on
|
||||
firefox-59 it did (the host's glxtest blocked WEBGL_OPENGL, and the context
|
||||
failed with FEATURE_FAILURE_WEBGL_EXHAUSTED_DRIVERS). With a host Mesa present,
|
||||
WebGL2 exists on every engine, so this test only means something where there is
|
||||
none: the gate removes every Mesa library from its Linux legs, and a machine that
|
||||
has one skips it.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import glob
|
||||
import os
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
LIBDIR = "/usr/lib/x86_64-linux-gnu"
|
||||
HOST_MESA = (
|
||||
"libgallium-*.so",
|
||||
"dri/*_dri.so",
|
||||
"libGLX_mesa.so*",
|
||||
"libEGL_mesa.so*",
|
||||
)
|
||||
|
||||
PAGE = """
|
||||
() => {
|
||||
const errors = [];
|
||||
const make = (kind) => {
|
||||
const c = document.createElement('canvas');
|
||||
c.width = c.height = 4;
|
||||
c.addEventListener('webglcontextcreationerror', e => errors.push(kind + ': ' + e.statusMessage));
|
||||
return [c, c.getContext(kind)];
|
||||
};
|
||||
const [c2, gl2] = make('webgl2');
|
||||
const [c1, gl1] = make('webgl');
|
||||
let px = null;
|
||||
if (gl2) {
|
||||
gl2.clearColor(1, 0, 0, 1);
|
||||
gl2.clear(gl2.COLOR_BUFFER_BIT);
|
||||
const buf = new Uint8Array(4);
|
||||
gl2.readPixels(0, 0, 1, 1, gl2.RGBA, gl2.UNSIGNED_BYTE, buf);
|
||||
px = Array.from(buf);
|
||||
}
|
||||
return {webgl2: !!gl2, webgl: !!gl1, pixel: px, errors};
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def _host_mesa_files() -> list:
|
||||
out = []
|
||||
for pattern in HOST_MESA:
|
||||
out += glob.glob(os.path.join(LIBDIR, pattern))
|
||||
return sorted(out)
|
||||
|
||||
|
||||
def test_webgl2_exists_on_a_host_without_mesa(firefox_binary, engine_at_least):
|
||||
engine_at_least("firefox-60")
|
||||
if not sys.platform.startswith("linux"):
|
||||
pytest.skip("the host's GL probe that blocked WebGL is a Linux one")
|
||||
present = _host_mesa_files()
|
||||
if present:
|
||||
pytest.skip("this host has a Mesa (%s ...): WebGL2 exists with one on every "
|
||||
"engine, so the test proves nothing here" % present[0])
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
with InvisiblePlaywright(seed=42, binary_path=firefox_binary, headless=True) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto("about:blank")
|
||||
got = page.evaluate(PAGE)
|
||||
assert got["webgl2"], "no WebGL2 on a host without Mesa: %s" % got["errors"]
|
||||
assert got["webgl"], "no WebGL1 on a host without Mesa: %s" % got["errors"]
|
||||
assert got["pixel"] == [255, 0, 0, 255], got
|
||||
@@ -0,0 +1,338 @@
|
||||
"""WebGL blending is done on the unquantized shader output and rounded once.
|
||||
|
||||
On Windows the engine draws through ANGLE on Direct3D 11: the fragment shader's
|
||||
float output goes into the blender as it is, the blend is computed at float
|
||||
precision, and the result is rounded once, to the render target's format. On
|
||||
Linux the engine draws on its own Mesa llvmpipe, and until that was fixed
|
||||
llvmpipe first quantized the shader output to the target's 8 bits and then
|
||||
blended in 8-bit arithmetic, so a page read back values up to one step off
|
||||
(two for SUBTRACT) across most factor pairs: `blendFunc(SRC_ALPHA,
|
||||
ONE_MINUS_SRC_ALPHA)` over a destination of 100 with a source of 200 and an
|
||||
alpha of 1/255 read back 101 where D3D11 reads round(100.392) = 100.
|
||||
|
||||
The rule, the same on both systems: result = clamp(blend(src, dst)) computed
|
||||
exactly from the float32 values the shader outputs and the destination as it is
|
||||
stored, then rounded half up to the target's step, once.
|
||||
|
||||
One page, one WebGL2 context. For every render-target format the context gives
|
||||
a complete framebuffer (RGBA8, RGB10_A2, RGBA4 as renderbuffers; R16 and RGBA16
|
||||
as textures when EXT_texture_norm16 is there) the page clears a 256x1 strip to
|
||||
a destination, then draws a constant colour from a uniform onto one pixel of the
|
||||
strip per source alpha (the scissor picks the pixel, so every pixel is one
|
||||
independent 1x1 blend), and reads the strip back. It sweeps the factor pairs
|
||||
SRC_ALPHA / ONE_MINUS_SRC_ALPHA, ONE / ONE_MINUS_SRC_ALPHA (premultiplied
|
||||
source), ONE_MINUS_DST_ALPHA / DST_ALPHA, DST_COLOR / ZERO and
|
||||
CONSTANT_COLOR / ONE_MINUS_CONSTANT_COLOR with FUNC_ADD, FUNC_SUBTRACT and
|
||||
FUNC_REVERSE_SUBTRACT, and MIN and MAX, over straight, premultiplied and
|
||||
non-8-bit-exact (0.31...) sources with a different value in each of R, G, B, A.
|
||||
The page returns the raw values; the reference is computed here in double.
|
||||
A result that is a hair from a rounding boundary (within 2e-4 of a half step, in
|
||||
target steps; scaled up for 16 bits, where float32 itself is that coarse) cannot
|
||||
be told from float noise in the hardware and is skipped, and the test insists
|
||||
that nearly all cases were compared.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import struct
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
# Render targets: name, steps per channel (R, G, B, A), step between the source
|
||||
# alphas swept (RGBA8 takes every one), how the page reads it back.
|
||||
FORMATS = [
|
||||
{"name": "RGBA8", "max": (255, 255, 255, 255), "step": 1, "kind": "rbo", "ifmt": "RGBA8", "read": "u8"},
|
||||
{"name": "RGB10_A2", "max": (1023, 1023, 1023, 3), "step": 3, "kind": "rbo", "ifmt": "RGB10_A2", "read": "u1010102"},
|
||||
{"name": "RGBA4", "max": (15, 15, 15, 15), "step": 3, "kind": "rbo", "ifmt": "RGBA4", "read": "u4"},
|
||||
{"name": "RGBA16", "max": (65535, 65535, 65535, 65535), "step": 3, "kind": "norm16", "ifmt": "RGBA16_EXT", "read": "u16"},
|
||||
# no alpha in R16: a missing alpha reads as 1 for DST_ALPHA, only R is stored
|
||||
{"name": "R16", "max": (65535, 0, 0, 0), "step": 3, "kind": "norm16", "ifmt": "R16_EXT", "read": "u16"},
|
||||
]
|
||||
|
||||
# Blend states: (name, source factor, destination factor, equation). MIN and MAX
|
||||
# ignore the factors.
|
||||
STATES = [
|
||||
("SRC_ALPHA/ONE_MINUS_SRC_ALPHA ADD", "SRC_ALPHA", "ONE_MINUS_SRC_ALPHA", "FUNC_ADD"),
|
||||
("ONE/ONE_MINUS_SRC_ALPHA ADD", "ONE", "ONE_MINUS_SRC_ALPHA", "FUNC_ADD"),
|
||||
("ONE_MINUS_DST_ALPHA/DST_ALPHA ADD", "ONE_MINUS_DST_ALPHA", "DST_ALPHA", "FUNC_ADD"),
|
||||
("DST_COLOR/ZERO ADD", "DST_COLOR", "ZERO", "FUNC_ADD"),
|
||||
("CONSTANT_COLOR/ONE_MINUS_CONSTANT_COLOR ADD", "CONSTANT_COLOR", "ONE_MINUS_CONSTANT_COLOR", "FUNC_ADD"),
|
||||
("SRC_ALPHA/ONE_MINUS_SRC_ALPHA SUBTRACT", "SRC_ALPHA", "ONE_MINUS_SRC_ALPHA", "FUNC_SUBTRACT"),
|
||||
("ONE/ONE SUBTRACT", "ONE", "ONE", "FUNC_SUBTRACT"),
|
||||
("SRC_ALPHA/ONE_MINUS_SRC_ALPHA REVERSE_SUBTRACT", "SRC_ALPHA", "ONE_MINUS_SRC_ALPHA", "FUNC_REVERSE_SUBTRACT"),
|
||||
("ONE/ONE REVERSE_SUBTRACT", "ONE", "ONE", "FUNC_REVERSE_SUBTRACT"),
|
||||
("MIN", "ONE", "ONE", "MIN"),
|
||||
("MAX", "ONE", "ONE", "MAX"),
|
||||
]
|
||||
|
||||
# The constant blend colour (float32 values as the GL stores them).
|
||||
BLEND_COLOR = (0.25, 0.6, 0.9, 0.35)
|
||||
|
||||
# (source rgb in bytes, fraction rgb for the non-8-bit-exact source, destination
|
||||
# rgba in bytes). Different in R, G, B and A, with dst alpha both partial and full.
|
||||
COLOUR_SETS = [
|
||||
((200, 50, 137), (0.31, 0.71, 0.123), (100, 210, 88, 77)),
|
||||
((50, 255, 0), (0.9, 0.05, 0.456), (210, 0, 255, 255)),
|
||||
((10, 128, 250), (0.77, 0.333, 0.01), (255, 37, 129, 200)),
|
||||
]
|
||||
MODES = ("straight", "premul", "frac")
|
||||
|
||||
# The least share of the (case, channel) results that may be skipped as
|
||||
# near-ties before the test would prove nothing.
|
||||
MAX_SKIPPED = 0.02
|
||||
|
||||
PAGE = r"""(plan) => {
|
||||
const gl = document.createElement('canvas').getContext('webgl2');
|
||||
if (!gl) return { error: 'no webgl2' };
|
||||
gl.disable(gl.DITHER);
|
||||
const vs = '#version 300 es\nvoid main(){vec2 p=vec2(float((gl_VertexID<<1)&2),float(gl_VertexID&2));gl_Position=vec4(p*2.-1.,0.,1.);}';
|
||||
const fs = '#version 300 es\nprecision highp float;uniform vec4 c;out vec4 o;void main(){o=c;}';
|
||||
const prog = gl.createProgram();
|
||||
for (const [type, src] of [[gl.VERTEX_SHADER, vs], [gl.FRAGMENT_SHADER, fs]]) {
|
||||
const s = gl.createShader(type); gl.shaderSource(s, src); gl.compileShader(s);
|
||||
if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) return { error: 'shader: ' + gl.getShaderInfoLog(s) };
|
||||
gl.attachShader(prog, s);
|
||||
}
|
||||
gl.linkProgram(prog);
|
||||
if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) return { error: 'link: ' + gl.getProgramInfoLog(prog) };
|
||||
gl.useProgram(prog);
|
||||
const uc = gl.getUniformLocation(prog, 'c');
|
||||
gl.viewport(0, 0, 256, 1);
|
||||
gl.blendColor(plan.blendColor[0], plan.blendColor[1], plan.blendColor[2], plan.blendColor[3]);
|
||||
const norm16 = gl.getExtension('EXT_texture_norm16');
|
||||
|
||||
function target(f) {
|
||||
const fb = gl.createFramebuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
|
||||
if (f.kind === 'rbo') {
|
||||
const rb = gl.createRenderbuffer(); gl.bindRenderbuffer(gl.RENDERBUFFER, rb);
|
||||
gl.renderbufferStorage(gl.RENDERBUFFER, gl[f.ifmt], 256, 1);
|
||||
gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, rb);
|
||||
} else {
|
||||
if (!norm16) return 'no EXT_texture_norm16';
|
||||
const t = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, t);
|
||||
gl.texStorage2D(gl.TEXTURE_2D, 1, norm16[f.ifmt], 256, 1);
|
||||
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, t, 0);
|
||||
}
|
||||
if (gl.getError() !== 0) return 'storage refused';
|
||||
const st = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
|
||||
return st === gl.FRAMEBUFFER_COMPLETE ? '' : 'framebuffer status 0x' + st.toString(16);
|
||||
}
|
||||
|
||||
// The strip as target steps, 4 numbers per pixel (a channel the target does not store reads 0).
|
||||
function read(f, n) {
|
||||
const out = new Array(n * 4).fill(0);
|
||||
if (f.read === 'u1010102') {
|
||||
const b = new Uint32Array(256);
|
||||
gl.readPixels(0, 0, 256, 1, gl.RGBA, gl.UNSIGNED_INT_2_10_10_10_REV, b);
|
||||
for (let i = 0; i < n; i++) {
|
||||
out[i * 4] = b[i] & 1023; out[i * 4 + 1] = (b[i] >>> 10) & 1023;
|
||||
out[i * 4 + 2] = (b[i] >>> 20) & 1023; out[i * 4 + 3] = b[i] >>> 30;
|
||||
}
|
||||
} else if (f.read === 'u16') {
|
||||
let formats = [gl.RGBA, gl.RED], done = false;
|
||||
for (const fmt of formats) {
|
||||
const ch = fmt === gl.RGBA ? 4 : 1;
|
||||
const b = new Uint16Array(256 * ch);
|
||||
while (gl.getError() !== 0) {}
|
||||
gl.readPixels(0, 0, 256, 1, fmt, gl.UNSIGNED_SHORT, b);
|
||||
if (gl.getError() !== 0) continue;
|
||||
for (let i = 0; i < n; i++) for (let c = 0; c < ch; c++) out[i * 4 + c] = b[i * ch + c];
|
||||
done = true; break;
|
||||
}
|
||||
if (!done) return null;
|
||||
} else {
|
||||
const b = new Uint8Array(256 * 4);
|
||||
gl.readPixels(0, 0, 256, 1, gl.RGBA, gl.UNSIGNED_BYTE, b);
|
||||
const div = f.read === 'u4' ? 17 : 1; // 4 bits come back as v * 17
|
||||
for (let i = 0; i < n * 4; i++) out[i] = Math.round(b[i] / div);
|
||||
}
|
||||
return gl.getError() === 0 ? out : null;
|
||||
}
|
||||
|
||||
const result = {};
|
||||
for (const f of plan.formats) {
|
||||
const problem = target(f);
|
||||
if (problem) { result[f.name] = { skipped: problem }; continue; }
|
||||
const groups = [];
|
||||
for (const g of f.groups) {
|
||||
gl.disable(gl.BLEND); gl.disable(gl.SCISSOR_TEST);
|
||||
gl.clearColor(g.dst[0], g.dst[1], g.dst[2], g.dst[3]);
|
||||
gl.clear(gl.COLOR_BUFFER_BIT);
|
||||
gl.enable(gl.SCISSOR_TEST); gl.enable(gl.BLEND);
|
||||
gl.blendFunc(gl[g.sf], gl[g.df]); gl.blendEquation(gl[g.eq]);
|
||||
for (let x = 0; x < g.src.length; x++) {
|
||||
gl.scissor(x, 0, 1, 1);
|
||||
gl.uniform4f(uc, g.src[x][0], g.src[x][1], g.src[x][2], g.src[x][3]);
|
||||
gl.drawArrays(gl.TRIANGLES, 0, 3);
|
||||
}
|
||||
const px = read(f, g.src.length);
|
||||
if (!px) { result[f.name] = { skipped: 'read back refused, error 0x' + gl.getError().toString(16) }; break; }
|
||||
groups.push(px);
|
||||
}
|
||||
if (groups.length === f.groups.length) result[f.name] = { groups };
|
||||
}
|
||||
return result;
|
||||
}"""
|
||||
|
||||
|
||||
def _f32(x: float) -> float:
|
||||
"""x as the float32 the shader and the GL hold."""
|
||||
return struct.unpack("<f", struct.pack("<f", x))[0]
|
||||
|
||||
|
||||
def _short(x: float) -> float:
|
||||
"""The shortest decimal that is still the same float32, so the plan stays small
|
||||
on the wire (the page rounds it to float32 again, to the same value)."""
|
||||
for digits in range(1, 10):
|
||||
y = float(f"{x:.{digits}g}")
|
||||
if _f32(y) == x:
|
||||
return y
|
||||
return x
|
||||
|
||||
|
||||
def _alphas(step: int) -> list:
|
||||
return list(range(0, 256, step))
|
||||
|
||||
|
||||
def build_plan() -> dict:
|
||||
"""What the page draws: per format, per (blend state, colour set, source mode)
|
||||
one group, the destination in target steps and one source colour per alpha."""
|
||||
formats = []
|
||||
for fmt in FORMATS:
|
||||
groups = []
|
||||
for name, sf, df, eq in STATES:
|
||||
for set_i, (rgb, frac, dst_bytes) in enumerate(COLOUR_SETS):
|
||||
dst = [round(b / 255 * m) for b, m in zip(dst_bytes, fmt["max"])]
|
||||
for mode in MODES:
|
||||
src = []
|
||||
for a in _alphas(fmt["step"]):
|
||||
alpha = a / 255
|
||||
if mode == "frac":
|
||||
alpha = min(1.0, (a * 0.9961 + 0.37) / 255)
|
||||
alpha = _f32(alpha)
|
||||
if mode == "frac":
|
||||
col = [_f32(v) for v in frac]
|
||||
elif mode == "premul":
|
||||
col = [_f32(_f32(b / 255) * alpha) for b in rgb]
|
||||
else:
|
||||
col = [_f32(b / 255) for b in rgb]
|
||||
src.append(col + [alpha])
|
||||
groups.append({"state": name, "sf": sf, "df": df, "eq": eq, "set": set_i, "mode": mode,
|
||||
"dst": [_short(_f32(d / m)) if m else 0.0 for d, m in zip(dst, fmt["max"])],
|
||||
"dst_steps": dst, "src": src})
|
||||
formats.append({"name": fmt["name"], "kind": fmt["kind"], "ifmt": fmt["ifmt"], "read": fmt["read"],
|
||||
"groups": groups})
|
||||
return {"blendColor": [_f32(v) for v in BLEND_COLOR], "formats": formats}
|
||||
|
||||
|
||||
def wire(plan: dict) -> dict:
|
||||
"""The plan as the page gets it: the sources as short decimals."""
|
||||
return {**plan, "formats": [{**f, "groups": [{**g, "src": [[_short(v) for v in px] for px in g["src"]]}
|
||||
for g in f["groups"]]} for f in plan["formats"]]}
|
||||
|
||||
|
||||
def _factor(name: str, s, d, k, ch: int) -> float:
|
||||
return {
|
||||
"ZERO": lambda: 0.0,
|
||||
"ONE": lambda: 1.0,
|
||||
"SRC_COLOR": lambda: s[ch],
|
||||
"ONE_MINUS_SRC_COLOR": lambda: 1 - s[ch],
|
||||
"DST_COLOR": lambda: d[ch],
|
||||
"ONE_MINUS_DST_COLOR": lambda: 1 - d[ch],
|
||||
"SRC_ALPHA": lambda: s[3],
|
||||
"ONE_MINUS_SRC_ALPHA": lambda: 1 - s[3],
|
||||
"DST_ALPHA": lambda: d[3],
|
||||
"ONE_MINUS_DST_ALPHA": lambda: 1 - d[3],
|
||||
"CONSTANT_COLOR": lambda: k[ch],
|
||||
"ONE_MINUS_CONSTANT_COLOR": lambda: 1 - k[ch],
|
||||
}[name]()
|
||||
|
||||
|
||||
def exact_steps(group: dict, src, k, fmt: dict, ch: int) -> float:
|
||||
"""The blend of one channel in double, from the float32 source and the
|
||||
destination as stored, in target steps, clamped to the target's range."""
|
||||
mx = fmt["max"]
|
||||
d = [dst / m if m else 0.0 for dst, m in zip(group["dst_steps"], mx)]
|
||||
if mx[3] == 0:
|
||||
d[3] = 1.0 # a target with no alpha reads as 1
|
||||
s = src
|
||||
if group["eq"] == "MIN":
|
||||
r = min(s[ch], d[ch])
|
||||
elif group["eq"] == "MAX":
|
||||
r = max(s[ch], d[ch])
|
||||
else:
|
||||
a = s[ch] * _factor(group["sf"], s, d, k, ch)
|
||||
b = d[ch] * _factor(group["df"], s, d, k, ch)
|
||||
r = {"FUNC_ADD": a + b, "FUNC_SUBTRACT": a - b, "FUNC_REVERSE_SUBTRACT": b - a}[group["eq"]]
|
||||
return min(1.0, max(0.0, r)) * mx[ch]
|
||||
|
||||
|
||||
def check(plan: dict, got: dict):
|
||||
"""-> (failures, compared, skipped_as_near_ties, formats_checked, formats_skipped)."""
|
||||
k = plan["blendColor"]
|
||||
failures, compared, near_ties = [], 0, 0
|
||||
checked, skipped = [], {}
|
||||
for pf in plan["formats"]:
|
||||
fmt = next(f for f in FORMATS if f["name"] == pf["name"])
|
||||
res = got[pf["name"]]
|
||||
if "skipped" in res:
|
||||
skipped[pf["name"]] = res["skipped"]
|
||||
continue
|
||||
checked.append(pf["name"])
|
||||
# float32 itself is this coarse at the target's scale; 2e-4 at 8 bits and below
|
||||
tol = max(2e-4, 7.8e-7 * max(fmt["max"]))
|
||||
for g, px in zip(pf["groups"], res["groups"]):
|
||||
for x, src in enumerate(g["src"]):
|
||||
for ch in range(4):
|
||||
if fmt["max"][ch] == 0:
|
||||
continue
|
||||
exact = exact_steps(g, src, k, fmt, ch)
|
||||
if abs((exact - math.floor(exact)) - 0.5) < tol:
|
||||
near_ties += 1
|
||||
continue
|
||||
want = math.floor(exact + 0.5)
|
||||
have = px[x * 4 + ch]
|
||||
compared += 1
|
||||
if have != want:
|
||||
failures.append({"format": pf["name"], "state": g["state"], "set": g["set"], "mode": g["mode"],
|
||||
"channel": "RGBA"[ch], "alpha": round(src[3] * 255, 3),
|
||||
"dst": g["dst_steps"][ch], "src": src[ch],
|
||||
"got": have, "exact": round(exact, 4)})
|
||||
return failures, compared, near_ties, checked, skipped
|
||||
|
||||
|
||||
def _describe(failures: list, worst: int = 8) -> str:
|
||||
lines = [f" {f['format']} {f['state']} set {f['set']} {f['mode']} channel {f['channel']} "
|
||||
f"alpha {f['alpha']} src {f['src']:.6f} dst {f['dst']}: got {f['got']}, exact {f['exact']}"
|
||||
for f in failures[:worst]]
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def test_blending_is_done_unquantized_and_rounded_once(firefox_binary, engine_at_least):
|
||||
engine_at_least("firefox-60")
|
||||
if not sys.platform.startswith("linux"):
|
||||
pytest.skip("Windows: objective 5. On Windows the blend is done by the host's Direct3D 11 (WARP on a runner "
|
||||
"without a GPU, which rounds up to 2 off), until ANGLE's translator does it; the Mesa patch fixes "
|
||||
"Linux only. It returns to Windows when the blending goes through the translator.")
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
plan = build_plan()
|
||||
with InvisiblePlaywright(seed=42, binary_path=firefox_binary, headless=True) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto("about:blank")
|
||||
got = page.evaluate(PAGE, wire(plan))
|
||||
assert "error" not in got, got.get("error")
|
||||
assert "groups" in got["RGBA8"], f"RGBA8 target unusable: {got['RGBA8']}"
|
||||
|
||||
failures, compared, near_ties, checked, skipped = check(plan, got)
|
||||
total = compared + near_ties
|
||||
assert compared > 50_000, (compared, checked, skipped)
|
||||
assert near_ties / total < MAX_SKIPPED, (near_ties, total)
|
||||
max_err = max((abs(f["got"] - math.floor(f["exact"] + 0.5)) for f in failures), default=0)
|
||||
assert not failures, (
|
||||
f"{len(failures)} of {compared} results differ from the blend computed unquantized and rounded once "
|
||||
f"(max error {max_err}; formats checked {checked}, not available {skipped}); first:\n"
|
||||
+ _describe(failures))
|
||||
@@ -0,0 +1,219 @@
|
||||
"""A WebGL dot() gives the bits of the GPU family the persona declares.
|
||||
|
||||
Which instructions an adapter runs for dot(a, b) decides the last bit of what a
|
||||
page reads back: NVIDIA hardware evaluates it as one chain of fused
|
||||
multiply-adds, left to right, the first product rounded; another adapter, or
|
||||
the software rasteriser Windows falls back to, may sum the products another
|
||||
way. With `zoom.stealth.webgl.alu_class` 1 (NVIDIA Maxwell and Pascal) or 2
|
||||
(NVIDIA Volta and later) ANGLE emits every float dot() of two, three or four
|
||||
components as IEEE-only `precise` helpers that reproduce that chain, the same
|
||||
text and the same bits on every adapter, whichever of the two classes (the helpers match
|
||||
the RTX 5080's own dot() on 65536 random vectors on Intel, the RTX 5080 and WARP).
|
||||
|
||||
The page below computes dot(a, b) for fixed vectors in a fragment shader and
|
||||
reads the float back as four bytes (floatBitsToUint, one byte per channel of an
|
||||
RGBA8 target, so no float render target is needed). The expected bits come from
|
||||
the same chain computed here in exact rational arithmetic and rounded once to
|
||||
float32 at every fma.
|
||||
|
||||
The class-1 and class-2 tests pass on every adapter. The class-0 test is the control: it
|
||||
shows the vectors tell the host's own dot() from the chain, and is skipped on an
|
||||
adapter whose dot() already is the chain (an NVIDIA GPU), where the difference
|
||||
is not visible. The two browser tests need ANGLE's D3D translation: Windows only.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import math
|
||||
import random
|
||||
import struct
|
||||
import sys
|
||||
from fractions import Fraction
|
||||
|
||||
import pytest
|
||||
|
||||
N = 4096 # vectors per component count: the canvas is N pixels wide
|
||||
|
||||
|
||||
def _f32(x: float) -> float:
|
||||
return struct.unpack("<f", struct.pack("<f", x))[0]
|
||||
|
||||
|
||||
def _bits(x: float) -> int:
|
||||
return struct.unpack("<I", struct.pack("<f", x))[0]
|
||||
|
||||
|
||||
def _round_f32(fr: Fraction) -> float:
|
||||
"""The float32 nearest to an exact rational, ties to even (normal range)."""
|
||||
if fr == 0:
|
||||
return 0.0
|
||||
sign = -1 if fr < 0 else 1
|
||||
fr = abs(fr)
|
||||
e = fr.numerator.bit_length() - fr.denominator.bit_length()
|
||||
shift = 23 - e
|
||||
while True:
|
||||
scaled = fr * Fraction(2) ** shift
|
||||
m = scaled.numerator // scaled.denominator
|
||||
if m >= 1 << 24:
|
||||
shift -= 1
|
||||
elif m < 1 << 23:
|
||||
shift += 1
|
||||
else:
|
||||
break
|
||||
rem = scaled - m
|
||||
if rem > Fraction(1, 2) or (rem == Fraction(1, 2) and m & 1):
|
||||
m += 1
|
||||
return sign * float(Fraction(m) / Fraction(2) ** shift)
|
||||
|
||||
|
||||
def _fma(a: float, b: float, c: float) -> float:
|
||||
"""Fused multiply-add, one rounding, with IEEE's sign of a zero result: a zero sum is -0
|
||||
only when the product and c are both -0 (a cancellation gives +0)."""
|
||||
exact = Fraction(a) * Fraction(b) + Fraction(c)
|
||||
if exact == 0:
|
||||
both_negative_zero = (a == 0 or b == 0) and c == 0 and math.copysign(1.0, a) * math.copysign(1.0, b) < 0 and math.copysign(1.0, c) < 0
|
||||
return -0.0 if both_negative_zero else 0.0
|
||||
return _round_f32(exact)
|
||||
|
||||
|
||||
def nv_dot(a: list[float], b: list[float]) -> float:
|
||||
"""One fma chain, left to right, the first product rounded."""
|
||||
t = _f32(a[0] * b[0])
|
||||
for x, y in zip(a[1:], b[1:]):
|
||||
t = _fma(x, y, t)
|
||||
return t
|
||||
|
||||
|
||||
def _vectors(seed: int) -> list[list[float]]:
|
||||
"""N rows of 8 float32: a.xyzw then b.xyzw, magnitudes spread over 2^-6..2^6."""
|
||||
rng = random.Random(seed)
|
||||
rows = []
|
||||
for _ in range(N):
|
||||
rows.append([_f32(rng.choice((-1.0, 1.0)) * rng.uniform(0.25, 4.0) * 2.0 ** rng.randint(-6, 6))
|
||||
for _ in range(8)])
|
||||
# The last rows are zeros of both signs: a page tells -0 from +0 (1/x, Object.is), and a chain whose
|
||||
# product and running sum are both -0 stays -0 (a dot of zeros with signs).
|
||||
zeros = (0.0, -0.0)
|
||||
for i in range(min(64, N)):
|
||||
z = [zeros[(i >> j) & 1] for j in range(4)]
|
||||
w = [rng.choice((-1.0, 1.0)) * rng.choice((0.0, 1.0, 2.0)) for _ in range(4)]
|
||||
rows[N - 1 - i] = [z[0], z[1], z[2], z[3], w[0], w[1], w[2], w[3]]
|
||||
return rows
|
||||
|
||||
|
||||
# One program per component count; the pixel i reads its two vectors from a
|
||||
# 2-row RGBA32F texture with texelFetch and writes the 32 bits of dot() as bytes.
|
||||
PAGE = r"""(args) => {
|
||||
const [rows, K] = args;
|
||||
const n = rows.length;
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = n; canvas.height = 1;
|
||||
const gl = canvas.getContext('webgl2', {antialias: false, preserveDrawingBuffer: true});
|
||||
if (!gl) return {error: 'no webgl2'};
|
||||
const sw = ['x', 'xy', 'xyz', 'xyzw'][K - 1];
|
||||
const vs = '#version 300 es\n' +
|
||||
'void main(){ vec2 p = vec2(float((gl_VertexID << 1) & 2), float(gl_VertexID & 2));' +
|
||||
' gl_Position = vec4(p * 2.0 - 1.0, 0.0, 1.0); }';
|
||||
const fs = '#version 300 es\nprecision highp float; precision highp int; precision highp sampler2D;\n' +
|
||||
'uniform sampler2D T; out vec4 o;\n' +
|
||||
'void main(){ int i = int(gl_FragCoord.x);\n' +
|
||||
' vec4 a = texelFetch(T, ivec2(i, 0), 0); vec4 b = texelFetch(T, ivec2(i, 1), 0);\n' +
|
||||
' float d = dot(a.' + sw + ', b.' + sw + ');\n' +
|
||||
' uint u = floatBitsToUint(d);\n' +
|
||||
' o = vec4(float(u & 255u), float((u >> 8) & 255u), float((u >> 16) & 255u), float(u >> 24)) / 255.0; }';
|
||||
function sh(type, src) {
|
||||
const s = gl.createShader(type); gl.shaderSource(s, src); gl.compileShader(s);
|
||||
if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(s));
|
||||
return s;
|
||||
}
|
||||
const p = gl.createProgram();
|
||||
gl.attachShader(p, sh(gl.VERTEX_SHADER, vs)); gl.attachShader(p, sh(gl.FRAGMENT_SHADER, fs));
|
||||
gl.linkProgram(p);
|
||||
if (!gl.getProgramParameter(p, gl.LINK_STATUS)) return {error: gl.getProgramInfoLog(p)};
|
||||
gl.useProgram(p);
|
||||
const data = new Float32Array(n * 8);
|
||||
for (let i = 0; i < n; i++) {
|
||||
for (let c = 0; c < 4; c++) { data[i * 4 + c] = rows[i][c]; data[(n + i) * 4 + c] = rows[i][4 + c]; }
|
||||
}
|
||||
const t = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, t);
|
||||
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA32F, n, 2, 0, gl.RGBA, gl.FLOAT, data);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
|
||||
gl.uniform1i(gl.getUniformLocation(p, 'T'), 0);
|
||||
gl.viewport(0, 0, n, 1);
|
||||
gl.drawArrays(gl.TRIANGLES, 0, 3);
|
||||
const px = new Uint8Array(n * 4);
|
||||
gl.readPixels(0, 0, n, 1, gl.RGBA, gl.UNSIGNED_BYTE, px);
|
||||
const err = gl.getError();
|
||||
if (err) return {error: 'gl error 0x' + err.toString(16)};
|
||||
return {bytes: Array.from(px)};
|
||||
}"""
|
||||
|
||||
|
||||
def _mismatches(firefox_binary, alu_class: int, k: int) -> list[tuple[int, int, int]]:
|
||||
"""(index, page bits, model bits) of every vector where the page and the chain differ."""
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
rows = _vectors(2026 + k)
|
||||
prefs = {"zoom.stealth.webgl.alu_class": alu_class,
|
||||
# a readback with canvas noise would change low bits of the bytes under test
|
||||
"zoom.stealth.canvas.substitute_pixels": False}
|
||||
with InvisiblePlaywright(seed=42, binary_path=firefox_binary, headless=True, extra_prefs=prefs) as browser:
|
||||
page = browser.new_context().new_page()
|
||||
page.goto("about:blank", timeout=30_000)
|
||||
res = page.evaluate(PAGE, [rows, k])
|
||||
if "error" in res:
|
||||
pytest.skip("WebGL2 not usable here: %s" % res["error"])
|
||||
px = res["bytes"]
|
||||
bad = []
|
||||
for i, row in enumerate(rows):
|
||||
got = px[4 * i] | px[4 * i + 1] << 8 | px[4 * i + 2] << 16 | px[4 * i + 3] << 24
|
||||
want = _bits(nv_dot(row[:k], row[4:4 + k]))
|
||||
if got != want:
|
||||
bad.append((i, got, want))
|
||||
return bad
|
||||
|
||||
|
||||
def test_the_model_is_one_fma_chain():
|
||||
"""The reference itself: exact fma, first product rounded, left to right."""
|
||||
# 1 + 2^-24 is a tie that the chain rounds once, to even: 1.
|
||||
assert nv_dot([1.0, 1.0], [1.0, 2.0 ** -24]) == 1.0
|
||||
assert nv_dot([3.0, 5.0], [7.0, 11.0]) == 76.0
|
||||
# The first product is rounded: (1+2^-12)^2 = 1 + 2^-11 + 2^-24 is a tie, rounded to
|
||||
# 1 + 2^-11, so the chain leaves 2^-11 after adding -1 (the exact value is 2^-11 + 2^-24).
|
||||
x = _f32(1.0 + 2.0 ** -12)
|
||||
assert nv_dot([x, 1.0], [x, -1.0]) == 2.0 ** -11
|
||||
|
||||
|
||||
def test_the_model_keeps_the_sign_of_a_zero_sum():
|
||||
"""An fma whose product and addend are both -0 is -0; a cancellation is +0."""
|
||||
assert _bits(_fma(0.0, -1.0, -0.0)) == 0x80000000
|
||||
assert _bits(_fma(-0.0, 1.0, -0.0)) == 0x80000000
|
||||
assert _bits(_fma(0.0, 1.0, -0.0)) == 0
|
||||
assert _bits(_fma(1.5, 2.0, -3.0)) == 0
|
||||
assert _bits(nv_dot([0.0, 0.0], [-1.0, -1.0])) == 0x80000000
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
@pytest.mark.timeout(300, method="thread")
|
||||
@pytest.mark.skipif(sys.platform != "win32", reason="the HLSL is ANGLE's D3D translation, Windows only")
|
||||
@pytest.mark.parametrize("alu_class", (1, 2))
|
||||
@pytest.mark.parametrize("k", (2, 3, 4))
|
||||
def test_dot_is_the_nvidia_fma_chain_when_declared(firefox_binary, engine_at_least, k, alu_class):
|
||||
engine_at_least("firefox-60")
|
||||
bad = _mismatches(firefox_binary, alu_class, k)
|
||||
assert not bad, "dot%d, class %d: %d of %d differ from the chain, first %s" % (
|
||||
k, alu_class, len(bad), N, json.dumps(bad[:3]))
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
@pytest.mark.timeout(300, method="thread")
|
||||
@pytest.mark.skipif(sys.platform != "win32", reason="the HLSL is ANGLE's D3D translation, Windows only")
|
||||
@pytest.mark.parametrize("k", (2, 3, 4))
|
||||
def test_dot_without_the_declaration_is_the_hosts_own(firefox_binary, engine_at_least, k):
|
||||
"""The control: with class 0 the same vectors tell the host's dot() from the chain."""
|
||||
engine_at_least("firefox-60")
|
||||
bad = _mismatches(firefox_binary, 0, k)
|
||||
if not bad:
|
||||
pytest.skip("this adapter's dot%d() already is the NVIDIA chain: the difference is not visible here" % k)
|
||||
assert bad
|
||||
@@ -0,0 +1,280 @@
|
||||
"""On Linux WebGL draws on the engine's own GL, never the host's.
|
||||
|
||||
Until firefox-59 the engine drew WebGL on Linux with whatever GL the host had,
|
||||
GLX or EGL from the system's libraries: the host's Mesa version, or its GPU
|
||||
driver, decided which declared extensions could be served and every pixel a
|
||||
page read back. Measured on 2026-11-08 with firefox-57 under Xvfb: the process
|
||||
that draws WebGL mapped the host's libEGL, libGLX and libgallium 26.0.8 from
|
||||
/usr/lib. From firefox-59 the GL ships with the engine in `llvmpipe/` next to
|
||||
the executable (Mesa's llvmpipe behind EGL, surfaceless, built from the same
|
||||
pinned tree and patches as WebGPU's lavapipe), and with the engine on Firefox
|
||||
loads it by path and never falls back to the host's.
|
||||
|
||||
The first test also stands for the X11 case: under Xvfb, as every session on
|
||||
Linux runs, candidate 42484125583 had no WebGL at all, because the surfaceless
|
||||
display was asked for with the X11 display, which Mesa refuses.
|
||||
|
||||
The first test reads the maps of the process that draws: the engine's libEGL
|
||||
and libgallium are there, and no libEGL of the host's. (GTK still opens the
|
||||
host's GLX at startup to choose its X11 visuals; nothing of it reaches WebGL
|
||||
or a page, and it is not what this test is about.) The second uses every
|
||||
extension the persona declares, for real, and compares each answer with the
|
||||
one firefox-57 gave on Windows (ANGLE on D3D11), measured the same day.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import glob
|
||||
import os
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = [pytest.mark.e2e,
|
||||
pytest.mark.skipif(not sys.platform.startswith("linux"), reason="the engine's own GL is Linux's")]
|
||||
|
||||
DRAW = """() => {
|
||||
const gl = document.createElement('canvas').getContext('webgl2');
|
||||
gl.clearColor(1, 0, 0, 1);
|
||||
gl.clear(gl.COLOR_BUFFER_BIT);
|
||||
const px = new Uint8Array(4);
|
||||
gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, px);
|
||||
return Array.from(px);
|
||||
}"""
|
||||
|
||||
# Every declared extension used for real: a call, an enum, a shader, a
|
||||
# framebuffer, and the error or state it leaves.
|
||||
USE = r"""() => {
|
||||
const R = {};
|
||||
function ctx(kind) { return document.createElement('canvas').getContext(kind); }
|
||||
function err(gl) { const e = gl.getError(); return e === 0 ? 'ok' : '0x' + e.toString(16); }
|
||||
function clean(gl) { while (gl.getError()) {} }
|
||||
function fbo(gl, ifmt, fmt, type) {
|
||||
const t = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, t);
|
||||
gl.texImage2D(gl.TEXTURE_2D, 0, ifmt, 4, 4, 0, fmt, type, null);
|
||||
const e1 = gl.getError();
|
||||
const f = gl.createFramebuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, f);
|
||||
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, t, 0);
|
||||
const s = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
|
||||
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
|
||||
return (e1 ? 'tex 0x' + e1.toString(16) + ' ' : '') + (s === gl.FRAMEBUFFER_COMPLETE ? 'complete' : 'fb 0x' + s.toString(16));
|
||||
}
|
||||
function shader(gl, src) {
|
||||
const s = gl.createShader(gl.FRAGMENT_SHADER); gl.shaderSource(s, src); gl.compileShader(s);
|
||||
return gl.getShaderParameter(s, gl.COMPILE_STATUS) ? 'ok' : 'fail: ' + gl.getShaderInfoLog(s).slice(0, 80);
|
||||
}
|
||||
function comp(gl, ext, fmtName, bytes) {
|
||||
const t = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, t);
|
||||
gl.compressedTexImage2D(gl.TEXTURE_2D, 0, ext[fmtName], 4, 4, 0, new Uint8Array(bytes));
|
||||
return err(gl);
|
||||
}
|
||||
function program(gl) {
|
||||
const p = gl.createProgram();
|
||||
for (const [type, src] of [[gl.VERTEX_SHADER, 'void main(){gl_PointSize=1.0;gl_Position=vec4(0.0,0.0,0.0,1.0);}'],
|
||||
[gl.FRAGMENT_SHADER, 'void main(){gl_FragColor=vec4(1.0);}']]) {
|
||||
const s = gl.createShader(type); gl.shaderSource(s, src); gl.compileShader(s); gl.attachShader(p, s);
|
||||
}
|
||||
gl.linkProgram(p); gl.useProgram(p); return p;
|
||||
}
|
||||
function tex(gl, ifmt, fmt, type) {
|
||||
const t = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, t);
|
||||
gl.texImage2D(gl.TEXTURE_2D, 0, ifmt, 2, 1, 0, fmt, type, null);
|
||||
return t;
|
||||
}
|
||||
for (const kind of ['webgl', 'webgl2']) {
|
||||
const gl = ctx(kind); const out = {}; R[kind] = out;
|
||||
const two = kind === 'webgl2';
|
||||
for (const name of gl.getSupportedExtensions()) {
|
||||
clean(gl);
|
||||
const x = gl.getExtension(name);
|
||||
let r;
|
||||
try {
|
||||
switch (name) {
|
||||
case 'ANGLE_instanced_arrays': program(gl); x.vertexAttribDivisorANGLE(0, 1); x.drawArraysInstancedANGLE(gl.POINTS, 0, 1, 1); r = err(gl) + ' divisor=' + gl.getVertexAttrib(0, x.VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE); x.vertexAttribDivisorANGLE(0, 0); break;
|
||||
case 'EXT_blend_minmax': gl.blendEquation(x.MIN_EXT); r = err(gl); gl.blendEquation(gl.FUNC_ADD); break;
|
||||
case 'EXT_color_buffer_half_float':
|
||||
if (two) r = fbo(gl, gl.RGBA16F, gl.RGBA, gl.HALF_FLOAT);
|
||||
else { const h = gl.getExtension('OES_texture_half_float'); r = fbo(gl, gl.RGBA, gl.RGBA, h.HALF_FLOAT_OES); }
|
||||
break;
|
||||
case 'EXT_color_buffer_float': r = fbo(gl, gl.RGBA32F, gl.RGBA, gl.FLOAT); break;
|
||||
case 'WEBGL_color_buffer_float': gl.getExtension('OES_texture_float'); r = fbo(gl, gl.RGBA, gl.RGBA, gl.FLOAT); break;
|
||||
case 'EXT_float_blend':
|
||||
if (two) { gl.getExtension('EXT_color_buffer_float'); r = fbo(gl, gl.RGBA32F, gl.RGBA, gl.FLOAT); }
|
||||
else { gl.getExtension('OES_texture_float'); gl.getExtension('WEBGL_color_buffer_float'); r = fbo(gl, gl.RGBA, gl.RGBA, gl.FLOAT); }
|
||||
break;
|
||||
case 'EXT_frag_depth': r = shader(gl, '#extension GL_EXT_frag_depth : require\nvoid main(){gl_FragDepthEXT=0.5;}'); break;
|
||||
case 'EXT_shader_texture_lod': r = shader(gl, '#extension GL_EXT_shader_texture_lod : require\nprecision mediump float;uniform sampler2D s;void main(){gl_FragColor=texture2DLodEXT(s,vec2(0.),0.);}'); break;
|
||||
case 'OES_standard_derivatives': r = shader(gl, '#extension GL_OES_standard_derivatives : require\nprecision mediump float;void main(){gl_FragColor=vec4(dFdx(1.));}'); break;
|
||||
case 'EXT_sRGB': tex(gl, x.SRGB_ALPHA_EXT, x.SRGB_ALPHA_EXT, gl.UNSIGNED_BYTE); r = err(gl); break;
|
||||
case 'EXT_texture_compression_bptc': r = comp(gl, x, 'COMPRESSED_RGBA_BPTC_UNORM_EXT', 16); break;
|
||||
case 'EXT_texture_compression_rgtc': r = comp(gl, x, 'COMPRESSED_RED_RGTC1_EXT', 8); break;
|
||||
case 'WEBGL_compressed_texture_s3tc': r = comp(gl, x, 'COMPRESSED_RGBA_S3TC_DXT5_EXT', 16); break;
|
||||
case 'WEBGL_compressed_texture_s3tc_srgb': r = comp(gl, x, 'COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT', 16); break;
|
||||
case 'EXT_texture_filter_anisotropic': {
|
||||
tex(gl, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE);
|
||||
gl.texParameterf(gl.TEXTURE_2D, x.TEXTURE_MAX_ANISOTROPY_EXT, 2);
|
||||
r = err(gl) + ' max=' + gl.getParameter(x.MAX_TEXTURE_MAX_ANISOTROPY_EXT) + ' read=' + gl.getTexParameter(gl.TEXTURE_2D, x.TEXTURE_MAX_ANISOTROPY_EXT);
|
||||
break; }
|
||||
case 'OES_element_index_uint': {
|
||||
const b = gl.createBuffer(); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, b);
|
||||
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint32Array([0]), gl.STATIC_DRAW);
|
||||
program(gl); gl.drawElements(gl.POINTS, 1, gl.UNSIGNED_INT, 0); r = err(gl); break; }
|
||||
case 'OES_fbo_render_mipmap': {
|
||||
const t = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, t);
|
||||
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 4, 4, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
|
||||
gl.texImage2D(gl.TEXTURE_2D, 1, gl.RGBA, 2, 2, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
|
||||
const f = gl.createFramebuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, f);
|
||||
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, t, 1);
|
||||
r = err(gl); gl.bindFramebuffer(gl.FRAMEBUFFER, null); break; }
|
||||
case 'OES_texture_float': tex(gl, gl.RGBA, gl.RGBA, gl.FLOAT); r = err(gl); break;
|
||||
case 'OES_texture_half_float': tex(gl, gl.RGBA, gl.RGBA, x.HALF_FLOAT_OES); r = err(gl); break;
|
||||
case 'OES_vertex_array_object': {
|
||||
const v = x.createVertexArrayOES(); x.bindVertexArrayOES(v);
|
||||
r = err(gl) + ' isVA=' + x.isVertexArrayOES(v); x.bindVertexArrayOES(null); break; }
|
||||
case 'WEBGL_depth_texture': tex(gl, gl.DEPTH_COMPONENT, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT); r = err(gl); break;
|
||||
case 'WEBGL_draw_buffers': { const t = tex(gl, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE); const f = gl.createFramebuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, f); gl.framebufferTexture2D(gl.FRAMEBUFFER, x.COLOR_ATTACHMENT0_WEBGL, gl.TEXTURE_2D, t, 0); x.drawBuffersWEBGL([x.COLOR_ATTACHMENT0_WEBGL]); r = err(gl) + ' max=' + gl.getParameter(x.MAX_DRAW_BUFFERS_WEBGL); gl.bindFramebuffer(gl.FRAMEBUFFER, null); break; }
|
||||
case 'WEBGL_provoking_vertex': {
|
||||
x.provokingVertexWEBGL(x.FIRST_VERTEX_CONVENTION_WEBGL);
|
||||
const v = gl.getParameter(x.PROVOKING_VERTEX_WEBGL);
|
||||
r = err(gl) + ' read=' + (v === x.FIRST_VERTEX_CONVENTION_WEBGL ? 'first' : v);
|
||||
x.provokingVertexWEBGL(x.LAST_VERTEX_CONVENTION_WEBGL); break; }
|
||||
case 'OES_draw_buffers_indexed':
|
||||
x.colorMaskiOES(0, false, true, true, true);
|
||||
r = err(gl) + ' read=' + JSON.stringify(gl.getIndexedParameter(gl.COLOR_WRITEMASK, 0));
|
||||
x.colorMaskiOES(0, true, true, true, true); break;
|
||||
case 'OVR_multiview2': {
|
||||
const t = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D_ARRAY, t);
|
||||
gl.texStorage3D(gl.TEXTURE_2D_ARRAY, 1, gl.RGBA8, 4, 4, 2);
|
||||
const f = gl.createFramebuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, f);
|
||||
x.framebufferTextureMultiviewOVR(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, t, 0, 0, 2);
|
||||
r = err(gl) + ' ' + (gl.checkFramebufferStatus(gl.FRAMEBUFFER) === gl.FRAMEBUFFER_COMPLETE ? 'complete' : 'incomplete') + ' maxViews=' + gl.getParameter(x.MAX_VIEWS_OVR);
|
||||
gl.bindFramebuffer(gl.FRAMEBUFFER, null); break; }
|
||||
case 'OES_texture_float_linear': case 'OES_texture_half_float_linear': {
|
||||
const half = name.includes('half');
|
||||
if (two) tex(gl, half ? gl.RGBA16F : gl.RGBA32F, gl.RGBA, half ? gl.HALF_FLOAT : gl.FLOAT);
|
||||
else { const h = gl.getExtension(half ? 'OES_texture_half_float' : 'OES_texture_float');
|
||||
tex(gl, gl.RGBA, gl.RGBA, half ? h.HALF_FLOAT_OES : gl.FLOAT); }
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); r = err(gl); break; }
|
||||
case 'WEBGL_debug_shaders': {
|
||||
const s = gl.createShader(gl.FRAGMENT_SHADER); gl.shaderSource(s, 'void main(){}'); gl.compileShader(s);
|
||||
r = (x.getTranslatedShaderSource(s) || '').slice(0, 40).replace(/\n/g, ' '); break; }
|
||||
default: r = x ? 'object' : 'null';
|
||||
}
|
||||
} catch (e) { r = 'throw ' + e.name + ': ' + e.message.slice(0, 60); }
|
||||
out[name] = r;
|
||||
}
|
||||
}
|
||||
return R;
|
||||
}"""
|
||||
|
||||
# firefox-57 on Windows (ANGLE, Direct3D 11), seed 42, 2026-11-08.
|
||||
ON_WINDOWS = {
|
||||
"webgl": {
|
||||
'ANGLE_instanced_arrays': 'ok divisor=1',
|
||||
'EXT_blend_minmax': 'ok',
|
||||
'EXT_clip_control': 'object',
|
||||
'EXT_color_buffer_half_float': 'complete',
|
||||
'EXT_depth_clamp': 'object',
|
||||
'EXT_float_blend': 'complete',
|
||||
'EXT_frag_depth': 'ok',
|
||||
'EXT_polygon_offset_clamp': 'object',
|
||||
'EXT_sRGB': 'ok',
|
||||
'EXT_shader_texture_lod': 'ok',
|
||||
'EXT_texture_compression_bptc': 'ok',
|
||||
'EXT_texture_compression_rgtc': 'ok',
|
||||
'EXT_texture_filter_anisotropic': 'ok max=16 read=2',
|
||||
'EXT_texture_mirror_clamp_to_edge': 'object',
|
||||
'OES_element_index_uint': 'ok',
|
||||
'OES_fbo_render_mipmap': 'ok',
|
||||
'OES_standard_derivatives': 'ok',
|
||||
'OES_texture_float': 'ok',
|
||||
'OES_texture_float_linear': 'ok',
|
||||
'OES_texture_half_float': 'ok',
|
||||
'OES_texture_half_float_linear': 'ok',
|
||||
'OES_vertex_array_object': 'ok isVA=true',
|
||||
'WEBGL_color_buffer_float': 'complete',
|
||||
'WEBGL_compressed_texture_s3tc': 'ok',
|
||||
'WEBGL_compressed_texture_s3tc_srgb': 'ok',
|
||||
'WEBGL_debug_renderer_info': 'object',
|
||||
'WEBGL_debug_shaders': 'void main(){ } ',
|
||||
'WEBGL_depth_texture': 'ok',
|
||||
'WEBGL_draw_buffers': 'ok max=8',
|
||||
'WEBGL_lose_context': 'object',
|
||||
'WEBGL_provoking_vertex': 'ok read=first',
|
||||
},
|
||||
"webgl2": {
|
||||
'EXT_clip_control': 'object',
|
||||
'EXT_color_buffer_float': 'complete',
|
||||
'EXT_depth_clamp': 'object',
|
||||
'EXT_float_blend': 'complete',
|
||||
'EXT_polygon_offset_clamp': 'object',
|
||||
'EXT_texture_compression_bptc': 'ok',
|
||||
'EXT_texture_compression_rgtc': 'ok',
|
||||
'EXT_texture_filter_anisotropic': 'ok max=16 read=2',
|
||||
'EXT_texture_mirror_clamp_to_edge': 'object',
|
||||
'EXT_texture_norm16': 'object',
|
||||
'OES_draw_buffers_indexed': 'ok read=[false,true,true,true]',
|
||||
'OES_texture_float_linear': 'ok',
|
||||
'OVR_multiview2': 'ok complete maxViews=4',
|
||||
'WEBGL_compressed_texture_s3tc': 'ok',
|
||||
'WEBGL_compressed_texture_s3tc_srgb': 'ok',
|
||||
'WEBGL_debug_renderer_info': 'object',
|
||||
'WEBGL_debug_shaders': 'void main(){ } ',
|
||||
'WEBGL_lose_context': 'object',
|
||||
'WEBGL_provoking_vertex': 'ok read=first',
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _ships_its_own_gl(binary_dir: str) -> bool:
|
||||
"""The engine's own GL is in the package from firefox-59: the test follows
|
||||
the package under test, not the core's version (the gate runs a candidate
|
||||
under the published core)."""
|
||||
return os.path.isfile(os.path.join(binary_dir, "llvmpipe", "libEGL.so.1"))
|
||||
|
||||
|
||||
def _maps_of_the_drawing_process(binary_dir: str) -> list:
|
||||
"""The files mapped by the engine process that runs WebGL's host (the one
|
||||
with the CanvasRenderer thread)."""
|
||||
for d in glob.glob("/proc/[0-9]*"):
|
||||
try:
|
||||
if not os.readlink(d + "/exe").startswith(binary_dir):
|
||||
continue
|
||||
threads = {open(t + "/comm").read().strip() for t in glob.glob(d + "/task/*")}
|
||||
if "CanvasRenderer" not in threads:
|
||||
continue
|
||||
return sorted({line.split()[-1] for line in open(d + "/maps") if len(line.split()) > 5})
|
||||
except OSError:
|
||||
continue
|
||||
return []
|
||||
|
||||
|
||||
def test_webgl_draws_on_the_engine_s_own_gl(firefox_binary):
|
||||
binary_dir = os.path.dirname(os.path.realpath(firefox_binary))
|
||||
if not _ships_its_own_gl(binary_dir):
|
||||
pytest.skip("this engine has no GL of its own (it ships from firefox-59)")
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
with InvisiblePlaywright(seed=42, binary_path=firefox_binary, headless=True) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto("about:blank")
|
||||
assert page.evaluate(DRAW) == [255, 0, 0, 255]
|
||||
maps = _maps_of_the_drawing_process(binary_dir)
|
||||
own = os.path.join(binary_dir, "llvmpipe") + os.sep
|
||||
assert maps, "no engine process with a CanvasRenderer thread"
|
||||
assert own + "libEGL.so.1" in maps, [m for m in maps if "EGL" in m or "gallium" in m]
|
||||
assert any(m.startswith(own + "libgallium-") for m in maps), [m for m in maps if "gallium" in m]
|
||||
assert not [m for m in maps if "libEGL" in os.path.basename(m) and not m.startswith(own)], maps
|
||||
|
||||
|
||||
def test_every_declared_extension_answers_as_on_windows(firefox_binary):
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
with InvisiblePlaywright(seed=42, binary_path=firefox_binary, headless=True) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto("about:blank")
|
||||
got = page.evaluate(USE)
|
||||
for kind in ("webgl", "webgl2"):
|
||||
differ = {name: (got[kind].get(name), want) for name, want in ON_WINDOWS[kind].items()
|
||||
if got[kind].get(name) != want}
|
||||
assert not differ, (kind, differ)
|
||||
assert sorted(got[kind]) == sorted(ON_WINDOWS[kind]), kind
|
||||
@@ -0,0 +1,178 @@
|
||||
"""A `mediump` WebGL shader computes at 32 bit, as on Windows.
|
||||
|
||||
On Windows the engine draws through ANGLE on Direct3D 11, which has no 16-bit
|
||||
float for a shader's `mediump` and `lowp`: both run at full 32-bit precision, so
|
||||
a page that reads a value back from a `mediump` shader gets the float32 it would
|
||||
get from `highp`. On Linux the engine draws on its own Mesa llvmpipe, which ran
|
||||
`mediump` and `lowp` as fp16 (an 11-bit significand, range 65504): an 8-bit
|
||||
texel read through a sampler of default precision came back as texel/255 rounded
|
||||
to fp16, up to about 0.12 of a step off (visible once the page scales it up),
|
||||
and plain arithmetic lost everything past 2048. The result is a different
|
||||
answer on the same page, and one a real Windows Firefox does not give.
|
||||
|
||||
The rule, the same on both systems: in a shader with `precision mediump float;`
|
||||
every value is a float32.
|
||||
|
||||
Three shaders, each writing the bits of its floats (`floatBitsToUint`) into an
|
||||
RGBA32UI target so nothing between the shader and the page can round them:
|
||||
|
||||
1. a `sampler2D` of default precision (lowp in GLSL ES 3.00) fetches, with
|
||||
`texelFetch`, an RGBA8 texture whose channels each hold all 256 byte values;
|
||||
every channel must be the float32 of byte/255 (the conversion is allowed one
|
||||
unit in the last place, since a driver may multiply by 1/255; fp16 is
|
||||
thousands of units off);
|
||||
2. the same with `precision mediump sampler2D;` declared;
|
||||
3. arithmetic whose exact float32 result fp16 cannot hold: 2049.0 + u (u = 1.0,
|
||||
from a uniform) is 2050 only past 11 bits, 0.1 * u is float32(0.1), 1.0 + u *
|
||||
2^-12 and 32.0 + u * 2^-10 need 13 and 16 bits. Each is one correctly
|
||||
rounded operation, so it is exact in float32 and the answer is the same on
|
||||
every hardware.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import struct
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
# The conversion of an 8-bit texel to float may be one unit in the last place
|
||||
# off the float32 nearest byte/255 (a driver multiplies by 1/255); fp16 is
|
||||
# around 2000 units off for most bytes.
|
||||
TEXEL_ULPS = 1
|
||||
|
||||
CHANNELS = "RGBA"
|
||||
|
||||
|
||||
def _texels() -> list:
|
||||
"""256 RGBA texels: every channel takes every byte value (37 and 91 are odd)."""
|
||||
return [(i, 255 - i, (i * 37) % 256, (i * 91 + 13) % 256) for i in range(256)]
|
||||
|
||||
|
||||
# The arithmetic of the third shader: (channel, GLSL, value, why fp16 cannot hold it).
|
||||
ARITHMETIC = [
|
||||
("r", "2049.0 + u", 2050.0, "fp16 cannot hold 2049 (steps of 2 above 2048)"),
|
||||
("g", "0.1 * u", None, "fp16 holds 0.1 as 0.0999756"),
|
||||
("b", "1.0 + u * 0.000244140625", 1.0 + 2.0 ** -12, "1 + 2^-12 needs 13 bits"),
|
||||
("a", "32.0 + u * 0.0009765625", 32.0 + 2.0 ** -10, "32 + 2^-10 needs 16 bits"),
|
||||
]
|
||||
|
||||
FS_HEAD = "#version 300 es\nprecision mediump float;\n"
|
||||
FS_TEXEL = """uniform sampler2D t;
|
||||
out highp uvec4 o;
|
||||
void main() {
|
||||
vec4 v = texelFetch(t, ivec2(gl_FragCoord.xy), 0);
|
||||
o = uvec4(floatBitsToUint(v.r), floatBitsToUint(v.g), floatBitsToUint(v.b), floatBitsToUint(v.a));
|
||||
}"""
|
||||
FS_ARITH = """uniform float u;
|
||||
out highp uvec4 o;
|
||||
void main() {
|
||||
float r = 2049.0 + u;
|
||||
float g = 0.1 * u;
|
||||
float b = 1.0 + u * 0.000244140625;
|
||||
float a = 32.0 + u * 0.0009765625;
|
||||
o = uvec4(floatBitsToUint(r), floatBitsToUint(g), floatBitsToUint(b), floatBitsToUint(a));
|
||||
}"""
|
||||
SHADERS = {
|
||||
"texelFetch, sampler2D of default precision": FS_HEAD + FS_TEXEL,
|
||||
"texelFetch, precision mediump sampler2D": FS_HEAD + "precision mediump sampler2D;\n" + FS_TEXEL,
|
||||
"arithmetic": FS_HEAD + FS_ARITH,
|
||||
}
|
||||
|
||||
PAGE = r"""(plan) => {
|
||||
const gl = document.createElement('canvas').getContext('webgl2');
|
||||
if (!gl) return { error: 'no webgl2' };
|
||||
const vsSrc = '#version 300 es\nvoid main(){vec2 p=vec2(float((gl_VertexID<<1)&2),float(gl_VertexID&2));gl_Position=vec4(p*2.-1.,0.,1.);}';
|
||||
function compile(type, src) {
|
||||
const s = gl.createShader(type); gl.shaderSource(s, src); gl.compileShader(s);
|
||||
return gl.getShaderParameter(s, gl.COMPILE_STATUS) ? s : null;
|
||||
}
|
||||
const rb = gl.createRenderbuffer(); gl.bindRenderbuffer(gl.RENDERBUFFER, rb);
|
||||
gl.renderbufferStorage(gl.RENDERBUFFER, gl.RGBA32UI, 256, 1);
|
||||
const fb = gl.createFramebuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
|
||||
gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, rb);
|
||||
if (gl.checkFramebufferStatus(gl.FRAMEBUFFER) !== gl.FRAMEBUFFER_COMPLETE) return { error: 'RGBA32UI target incomplete' };
|
||||
gl.viewport(0, 0, 256, 1);
|
||||
|
||||
const tex = gl.createTexture(); gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, tex);
|
||||
gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
|
||||
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, 256, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array(plan.texels.flat()));
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
|
||||
|
||||
const vs = compile(gl.VERTEX_SHADER, vsSrc);
|
||||
const out = {};
|
||||
for (const [name, src] of Object.entries(plan.shaders)) {
|
||||
const fs = compile(gl.FRAGMENT_SHADER, src);
|
||||
if (!fs) { out[name] = { error: 'fragment shader does not compile' }; continue; }
|
||||
const p = gl.createProgram(); gl.attachShader(p, vs); gl.attachShader(p, fs); gl.linkProgram(p);
|
||||
if (!gl.getProgramParameter(p, gl.LINK_STATUS)) { out[name] = { error: 'link: ' + gl.getProgramInfoLog(p) }; continue; }
|
||||
gl.useProgram(p);
|
||||
const t = gl.getUniformLocation(p, 't'); if (t) gl.uniform1i(t, 0);
|
||||
const u = gl.getUniformLocation(p, 'u'); if (u) gl.uniform1f(u, 1.0);
|
||||
gl.clearBufferuiv(gl.COLOR, 0, new Uint32Array([0xdeadbeef, 0xdeadbeef, 0xdeadbeef, 0xdeadbeef]));
|
||||
gl.drawArrays(gl.TRIANGLES, 0, 3);
|
||||
const px = new Uint32Array(256 * 4);
|
||||
gl.readPixels(0, 0, 256, 1, gl.RGBA_INTEGER, gl.UNSIGNED_INT, px);
|
||||
const e = gl.getError();
|
||||
out[name] = e ? { error: 'GL error 0x' + e.toString(16) } : { bits: Array.from(px) };
|
||||
}
|
||||
return out;
|
||||
}"""
|
||||
|
||||
|
||||
def _bits(x: float) -> int:
|
||||
return struct.unpack("<I", struct.pack("<f", x))[0]
|
||||
|
||||
|
||||
def _float(bits: int) -> float:
|
||||
return struct.unpack("<f", struct.pack("<I", bits & 0xFFFFFFFF))[0]
|
||||
|
||||
|
||||
def texel_problems(texels: list, bits: list) -> list:
|
||||
"""Every channel of every texel that is not the float32 of byte/255 (to TEXEL_ULPS)."""
|
||||
problems = []
|
||||
for x, texel in enumerate(texels):
|
||||
for ch in range(4):
|
||||
byte = texel[ch]
|
||||
want = _bits(byte / 255)
|
||||
got = bits[x * 4 + ch]
|
||||
ulps = abs(got - want)
|
||||
if ulps > TEXEL_ULPS:
|
||||
problems.append(f"texel {x} {CHANNELS[ch]}: byte {byte} read as {_float(got)!r} "
|
||||
f"(0x{got:08x}), float32(byte/255) is {_float(want)!r} (0x{want:08x}), {ulps} ulps off")
|
||||
return problems
|
||||
|
||||
|
||||
def arithmetic_problems(bits: list) -> list:
|
||||
problems = []
|
||||
for ch, (name, glsl, value, why) in enumerate(ARITHMETIC):
|
||||
want = _bits(0.1 if value is None else value) # packing rounds to the float32
|
||||
got_values = {bits[x * 4 + ch] for x in range(256)}
|
||||
if got_values != {want}:
|
||||
got = sorted(got_values)[0]
|
||||
problems.append(f"{glsl} ({name}): got {_float(got)!r} (0x{got:08x}), "
|
||||
f"float32 is {_float(want)!r} (0x{want:08x}); {why}")
|
||||
return problems
|
||||
|
||||
|
||||
def test_mediump_computes_at_32_bit(firefox_binary, engine_at_least):
|
||||
engine_at_least("firefox-60")
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
texels = _texels()
|
||||
with InvisiblePlaywright(seed=42, binary_path=firefox_binary, headless=True) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto("about:blank")
|
||||
got = page.evaluate(PAGE, {"texels": [list(t) for t in texels], "shaders": SHADERS})
|
||||
assert "error" not in got, got.get("error")
|
||||
failed = {}
|
||||
for name in SHADERS:
|
||||
res = got[name]
|
||||
assert "bits" in res, f"{name}: {res}"
|
||||
found = (arithmetic_problems(res["bits"]) if name == "arithmetic"
|
||||
else texel_problems(texels, res["bits"]))
|
||||
if found:
|
||||
failed[name] = found
|
||||
assert not failed, "mediump is not at 32 bit:\n" + "\n".join(
|
||||
f"- {name}: {len(found)} wrong, first:\n " + "\n ".join(found[:4]) for name, found in failed.items())
|
||||
@@ -0,0 +1,177 @@
|
||||
"""The canvas ICC readback reference: tests/data/canvas_icc_ref/refs.json."""
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = Path(__file__).parents[2]
|
||||
DATA = ROOT / "tests" / "data" / "canvas_icc_ref"
|
||||
REFS = DATA / "refs.json"
|
||||
SCRIPT = ROOT / "scripts" / "build_canvas_icc_refs.py"
|
||||
HEX64 = re.compile(r"[0-9a-f]{64}")
|
||||
|
||||
IMAGES = ["iccp-displayp3", "iccp-adobergb", "iccp-rec2020", "iccp-prophoto", "iccp-srgb",
|
||||
"cicp-p3", "gama-chrm-p3", "srgb-chunk", "untagged", "jpeg-icc-displayp3"]
|
||||
#: The images that carry a colour tag: qcms converts them to the output profile.
|
||||
TAGGED = [i for i in IMAGES if i != "untagged"]
|
||||
CONVERTED_PROBES = ("drawImage", "drawImage_scaled32", "bitmap_default")
|
||||
|
||||
|
||||
def _load(path, name):
|
||||
spec = importlib.util.spec_from_file_location(name, path)
|
||||
mod = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(mod)
|
||||
return mod
|
||||
|
||||
|
||||
def _builder():
|
||||
return _load(SCRIPT, "build_canvas_icc_refs")
|
||||
|
||||
|
||||
def _refs():
|
||||
return json.loads(REFS.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
def test_the_reference_has_72_probes_with_a_hash_each():
|
||||
refs = _refs()
|
||||
probes = refs["probes"]
|
||||
assert refs["probe_count"] == len(probes) == 72
|
||||
kinds = {}
|
||||
for name, p in probes.items():
|
||||
assert HEX64.fullmatch(p["sha256"]), name
|
||||
kinds[p["kind"]] = kinds.get(p["kind"], 0) + 1
|
||||
assert kinds == {"image": 40, "fill": 22, "colorspace": 1, "env": 9}
|
||||
for name in (f"{i} | {k}" for i in IMAGES
|
||||
for k in ("drawImage", "drawImage_scaled32", "bitmap_default", "bitmap_none")):
|
||||
p = probes[name]
|
||||
assert p["bytes"] == (4 * 32 * 32 if name.endswith("scaled32") else 4 * 16 * 16)
|
||||
|
||||
|
||||
def test_the_reference_names_the_retail_build_and_the_monitor_profile():
|
||||
refs = _refs()
|
||||
ff = refs["firefox"]
|
||||
assert ff["version"] == "159.0" and ff["buildid"] == "20261022150525"
|
||||
assert ff["exe_sha256"].startswith("d8b5ed82") and HEX64.fullmatch(ff["exe_sha256"])
|
||||
assert ff["prefs"]["gfx.color_management.force_srgb"] is False
|
||||
assert ff["prefs"]["gfx.color_management.display_profile"] == ""
|
||||
prof = refs["display_profile"]
|
||||
assert prof["file"] == "sRGB Color Space Profile.icm" and prof["size"] == 3144
|
||||
assert prof["sha256"] == "2b3aa1645779a9e634744faf9b01e9102b0c9b88fd6deced7934df86b949af7e"
|
||||
assert refs["source"]["capture"].endswith("canvas-color-icc-readback")
|
||||
|
||||
|
||||
def test_the_27_probes_that_depend_on_the_profile_are_there_and_differ_from_no_conversion():
|
||||
"""Without the conversion (force_srgb=true on the same machine, the bytes the engine
|
||||
gave until firefox-59) these 27 probes hash otherwise: the test compares them, so it
|
||||
fails on an engine that skips the conversion."""
|
||||
refs = _refs()
|
||||
probes = refs["probes"]
|
||||
want = sorted(f"{i} | {k}" for i in TAGGED for k in CONVERTED_PROBES)
|
||||
assert len(want) == 27
|
||||
assert refs["profile_dependent"] == want
|
||||
assert refs["profile_dependent_count"] == 27
|
||||
for name in want:
|
||||
p = probes[name]
|
||||
assert HEX64.fullmatch(p["without_conversion_sha256"]), name
|
||||
assert p["without_conversion_sha256"] != p["sha256"], name
|
||||
others = [n for n, p in probes.items() if "without_conversion_sha256" in p]
|
||||
assert sorted(others) == want, "no other probe depends on the profile"
|
||||
|
||||
|
||||
def test_the_untagged_bitmap_none_and_fill_probes_do_not_depend_on_the_profile():
|
||||
probes = _refs()["probes"]
|
||||
for i in IMAGES:
|
||||
assert "without_conversion_sha256" not in probes[f"{i} | bitmap_none"]
|
||||
assert all("without_conversion_sha256" not in p for n, p in probes.items()
|
||||
if n.startswith("fill | "))
|
||||
# untagged images and bitmap_none are the same 16x16 gradient: one hash for them all
|
||||
plain = {probes[f"{i} | bitmap_none"]["sha256"] for i in IMAGES if i != "jpeg-icc-displayp3"}
|
||||
assert len(plain) == 1
|
||||
|
||||
|
||||
def test_the_generator_gives_the_images_the_reference_names():
|
||||
refs = _refs()
|
||||
gen = _load(DATA / "gen_images.py", "gen_images")
|
||||
imgs, profiles = gen.build_images()
|
||||
assert [i[0] for i in imgs] == IMAGES == list(refs["images"])
|
||||
assert len(profiles) == 5
|
||||
for iid, ext, data, _what in imgs:
|
||||
want = refs["images"][iid]
|
||||
assert want["file"] == f"images/{iid}.{ext}"
|
||||
assert (len(data), hashlib.sha256(data).hexdigest()) == (want["bytes"], want["sha256"])
|
||||
assert [m["file"] for m in gen.images_json(imgs)] == [v["file"] for v in refs["images"].values()]
|
||||
|
||||
|
||||
def test_the_page_reads_the_probes_the_reference_names():
|
||||
page = (DATA / "index.html").read_text(encoding="utf-8")
|
||||
for needle in ('drawImage_scaled32', "createImageBitmap(blob", "color-gamut:p3",
|
||||
'fetch("images.json")', "p3_fill_p3_canvas"):
|
||||
assert needle in page, needle
|
||||
assert "http://" not in page and "https://" not in page, "the page loads nothing external"
|
||||
|
||||
|
||||
def _run(force_srgb, **pixel):
|
||||
"""A run json as run_color.py writes it, with the pixel hashes of ``pixel`` varying."""
|
||||
def img(prefix, tagged):
|
||||
e = {}
|
||||
for k in ("drawImage", "drawImage_scaled32", "bitmap_default", "bitmap_none"):
|
||||
conv = tagged and k != "bitmap_none" and not force_srgb
|
||||
e[k] = {"sha256": hashlib.sha256((prefix + k + ("c" if conv else "")).encode()).hexdigest()}
|
||||
return e
|
||||
return {
|
||||
"firefox": {"buildid": "1", "exe_sha256": "ab" * 32, "version": "159.0", "os": "Windows_NT"},
|
||||
"prefs_read_back": {"gfx.color_management.display_profile": "",
|
||||
"gfx.color_management.force_srgb": force_srgb,
|
||||
"gfx.color_management.mode": 2},
|
||||
"R": {"images": {"t": img("t", True), "u": img("u", False)},
|
||||
"fills": {"#336699": {"sha256": "11" * 32}},
|
||||
"canvas_colorspace": {"p3_fill_p3_canvas": {"sha256": "22" * 32}},
|
||||
"env": {"colorDepth": 24, "prefers-color-scheme:dark": True}},
|
||||
}
|
||||
|
||||
|
||||
HOST = {"file": "x.icm", "size": 1, "sha256": "33" * 32}
|
||||
|
||||
|
||||
def test_the_builder_keeps_the_no_conversion_hash_of_what_the_profile_changes():
|
||||
m = _builder()
|
||||
refs = m.build(_run(False), _run(True), _run(False), HOST, "cap")
|
||||
assert refs["profile_dependent"] == ["t | bitmap_default", "t | drawImage",
|
||||
"t | drawImage_scaled32"]
|
||||
assert refs["probe_count"] == 4 + 4 + 1 + 1 + 2
|
||||
p = refs["probes"]["t | drawImage"]
|
||||
assert p["without_conversion_sha256"] == _run(True)["R"]["images"]["t"]["drawImage"]["sha256"]
|
||||
assert refs["probes"]["env | prefers-color-scheme:dark"]["compared"] is False
|
||||
assert refs["probes"]["env | colorDepth"]["value"] == 24
|
||||
|
||||
|
||||
def test_a_repeat_run_with_other_hashes_is_refused():
|
||||
m = _builder()
|
||||
other = _run(False)
|
||||
other["R"]["fills"]["#336699"]["sha256"] = "44" * 32
|
||||
with pytest.raises(m.RefError, match="repeat run differs"):
|
||||
m.build(_run(False), _run(True), other, HOST, "cap")
|
||||
|
||||
|
||||
def test_runs_of_other_builds_or_prefs_are_refused():
|
||||
m = _builder()
|
||||
b = _run(True)
|
||||
b["firefox"]["buildid"] = "2"
|
||||
with pytest.raises(m.RefError, match="buildid"):
|
||||
m.build(_run(False), b, _run(False), HOST, "cap")
|
||||
with pytest.raises(m.RefError, match="force_srgb=true"):
|
||||
m.build(_run(False), _run(False), _run(False), HOST, "cap")
|
||||
a = _run(False)
|
||||
a["prefs_read_back"]["gfx.color_management.display_profile"] = "/p3.icc"
|
||||
with pytest.raises(m.RefError, match="display_profile"):
|
||||
m.build(a, _run(True), copy.deepcopy(a), HOST, "cap")
|
||||
b = _run(True)
|
||||
b["prefs_read_back"]["gfx.color_management.mode"] = 1
|
||||
with pytest.raises(m.RefError, match="mode"):
|
||||
m.build(_run(False), b, _run(False), HOST, "cap")
|
||||
@@ -0,0 +1,108 @@
|
||||
"""The merged canvas text reference: tests/data/canvas_text_ref/refs.json."""
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = Path(__file__).parents[2]
|
||||
REFS = ROOT / "tests" / "data" / "canvas_text_ref" / "refs.json"
|
||||
PAGE = ROOT / "tests" / "data" / "canvas_text_ref" / "index.html"
|
||||
SCRIPT = ROOT / "scripts" / "build_canvas_text_refs.py"
|
||||
|
||||
GROUPS = {"0_base": 211, "1_alpha_false": 25, "2a_rot_alpha_true_controllo": 25,
|
||||
"2b_rot_alpha_false": 25, "3_emoji_colr0": 12, "4_soglie": 20,
|
||||
"5_variabile_bahnschrift": 12, "6_variabile_seguivar": 12}
|
||||
|
||||
|
||||
def _builder():
|
||||
spec = importlib.util.spec_from_file_location("build_canvas_text_refs", SCRIPT)
|
||||
mod = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(mod)
|
||||
return mod
|
||||
|
||||
|
||||
def _refs():
|
||||
return json.loads(REFS.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
def test_the_merged_reference_has_every_case_once_in_its_group():
|
||||
refs = _refs()
|
||||
cases = refs["cases"]
|
||||
assert refs["case_count"] == len(cases) == sum(GROUPS.values()) == 342
|
||||
assert refs["groups"] == GROUPS
|
||||
got = {}
|
||||
for cid, c in cases.items():
|
||||
assert c["id"] == cid, "the key and the id of a case are one"
|
||||
assert len(c["sha256"]) == 64
|
||||
got[c["gruppo"]] = got.get(c["gruppo"], 0) + 1
|
||||
assert got == GROUPS
|
||||
assert len(cases) == len({c["id"] for c in cases.values()})
|
||||
assert not any("png" in c for c in cases.values()), "no PNG path: the repository holds none"
|
||||
|
||||
|
||||
def test_every_font_the_page_loads_is_named_with_its_hash():
|
||||
refs = _refs()
|
||||
files = {f["bundle_file"]: f for f in refs["fonts"]}
|
||||
assert {"TwemojiMozilla.ttf", "bahnschrift2_07.ttf", "seguivar2_03.ttf"} <= set(files)
|
||||
assert all(re.fullmatch(r"[0-9a-f]{64}", f["sha256"]) for f in files.values())
|
||||
page = PAGE.read_text(encoding="utf-8")
|
||||
assert set(re.findall(r'url\("bundle/([^"]+)"\)', page)) == set(files)
|
||||
families = {c["family"] for c in refs["cases"].values()}
|
||||
assert families <= {f["family"] for f in refs["fonts"]}
|
||||
|
||||
|
||||
def test_the_alpha_false_cases_say_so_and_the_page_opens_them_so():
|
||||
cases = _refs()["cases"]
|
||||
opaque = [c for c in cases.values() if c["gruppo"] in ("1_alpha_false", "2b_rot_alpha_false")]
|
||||
assert opaque and all(c["alpha"] is False and c["id"].endswith("|alpha=false") for c in opaque)
|
||||
assert 'getContext("2d", {alpha: sp.alpha' in PAGE.read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def _two(**over):
|
||||
base = {"text": "T", "firefox": {"v": 1}, "canvas": {}, "cleartype": {"a": 1},
|
||||
"fonts": [{"bundle_file": "a.ttf", "sha256": "11"}],
|
||||
"cases": {"x": {"id": "x", "sha256": "aa", "png": "cases/x.png"}}}
|
||||
ext = {**base, "cases": {"x": {"id": "x", "sha256": "aa", "gruppo": "2a"},
|
||||
"y": {"id": "y", "sha256": "bb", "gruppo": "5"}}}
|
||||
ext.update(over)
|
||||
return base, ext
|
||||
|
||||
|
||||
def test_a_shared_case_is_kept_once_with_the_extension_group():
|
||||
m = _builder()
|
||||
refs = m.merge(*_two())
|
||||
assert refs["case_count"] == 2
|
||||
assert refs["cases"]["x"]["gruppo"] == "2a" and "png" not in refs["cases"]["x"]
|
||||
assert refs["groups"] == {"2a": 1, "5": 1}
|
||||
|
||||
|
||||
def test_two_hashes_for_one_case_are_refused():
|
||||
m = _builder()
|
||||
b, e = _two()
|
||||
e["cases"]["x"]["sha256"] = "zz"
|
||||
with pytest.raises(m.MergeError, match="two different hashes"):
|
||||
m.merge(b, e)
|
||||
|
||||
|
||||
def test_two_measurements_of_different_machines_are_refused():
|
||||
m = _builder()
|
||||
b, e = _two(firefox={"v": 2})
|
||||
with pytest.raises(m.MergeError, match="firefox"):
|
||||
m.merge(b, e)
|
||||
|
||||
|
||||
def test_the_variable_cases_have_three_distinct_weights_at_every_size():
|
||||
"""A reference whose three weights hash alike proves nothing about the axes."""
|
||||
cases = _refs()["cases"]
|
||||
for group, family in (("5_variabile_bahnschrift", "Bahnschrift"),
|
||||
("6_variabile_seguivar", "Segoe UI Variable")):
|
||||
by = {}
|
||||
for c in cases.values():
|
||||
if c["gruppo"] == group:
|
||||
by.setdefault((c["size"], c["stretch"]), {})[c["weight"]] = c["sha256"]
|
||||
assert by and all(len(w) == 3 and len(set(w.values())) == 3 for w in by.values()), family
|
||||
assert all(c["family"] == family for c in cases.values() if c["gruppo"] == group)
|
||||
@@ -0,0 +1,33 @@
|
||||
"""scripts/compare_canvas_text_runs.py names the cases two runs draw differently."""
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
SCRIPT = Path(__file__).parents[2] / "scripts" / "compare_canvas_text_runs.py"
|
||||
|
||||
|
||||
def _module():
|
||||
spec = importlib.util.spec_from_file_location("compare_canvas_text_runs", SCRIPT)
|
||||
mod = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(mod)
|
||||
return mod
|
||||
|
||||
|
||||
def test_equal_runs_have_nothing_to_report():
|
||||
m = _module()
|
||||
assert m.compare({"a": "1", "b": "2"}, {"b": "2", "a": "1"}) == ([], [], [])
|
||||
|
||||
|
||||
def test_a_differing_and_a_missing_case_are_named():
|
||||
m = _module()
|
||||
only_a, only_b, differ = m.compare({"a": "1", "b": "2", "c": "3"}, {"a": "1", "b": "9", "d": "4"})
|
||||
assert (only_a, only_b, differ) == (["c"], ["d"], ["b"])
|
||||
|
||||
|
||||
def test_a_reference_file_loads_as_case_hashes(tmp_path):
|
||||
m = _module()
|
||||
p = tmp_path / "refs.json"
|
||||
p.write_text(json.dumps({"cases": {"x": {"sha256": "ab", "width": 3}}}), encoding="utf-8")
|
||||
assert m.load(str(p)) == {"x": "ab"}
|
||||
@@ -0,0 +1,32 @@
|
||||
"""engine_at_least (tests/conftest.py): which engines a test runs on. No browser."""
|
||||
import pytest
|
||||
from _pytest.outcomes import Failed, Skipped
|
||||
|
||||
import conftest
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
|
||||
def _check(tag, minimum="firefox-60"):
|
||||
conftest._skip_unless_engine_at_least(minimum, tag)
|
||||
|
||||
|
||||
def test_an_older_engine_is_skipped_with_the_reason():
|
||||
with pytest.raises(Skipped, match="needs firefox-60 or later; this engine is firefox-58"):
|
||||
_check("firefox-58")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("tag", ["firefox-60", "firefox-60-candidate", "firefox-61"])
|
||||
def test_the_engine_that_promises_it_runs(tag):
|
||||
_check(tag)
|
||||
|
||||
|
||||
def test_a_candidate_counts_as_its_number():
|
||||
with pytest.raises(Skipped):
|
||||
_check("firefox-59-candidate")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("tag", ["local", "my-build", "", None])
|
||||
def test_a_seal_with_no_number_fails_and_says_why(tag):
|
||||
with pytest.raises(Failed, match="has no number: a candidate must be sealed as firefox-N-candidate"):
|
||||
_check(tag)
|
||||
Reference in new issue
Block a user