app: cherry-pick rune's pause and sound fixes onto the checkout

Rune comes from app/vendor/rune now, a checkout of 63ad0209 on branch
ported, carrying the four commits of upstream issues 1320 (a pause while
a clip is layered holds the layer's picture and time) and 1325 (a video's
sound is read ahead of the clock and leads it). Both were written against
eb9f1104 and ported across the refactors since. The faults are the first
two and the third in docs/rune-upstream.md; the app's workarounds in
review.rs stay until the fixes arrive upstream.
This commit is contained in:
vhaudiquet committed 2026-11-22 22:16:30 +01:00
1 parent 80fef698ce
commit 5bf262b82b
3795 files changed
+663463 -28

No files matched your search

+88
View File
@@ -0,0 +1,88 @@
#!/usr/bin/env bash
# Crude checklist for the slow patterns Rune's "Fast apps" page (and its "Smooth scrolling" section)
# describes, over a repo's Rust files.
# Usage: scripts/app-audit [--strict] <repo>
# Prints one line per finding (check, file:line, source) and a count. Exits 0, or 1 with --strict
# when there are findings. Heuristics only: a finding is a place to look, not a verdict.
set -euo pipefail
strict=0
if [ "${1:-}" = "--strict" ]; then strict=1; shift; fi
root="${1:-}"
if [ -z "$root" ] || [ ! -d "$root" ]; then
echo "usage: scripts/app-audit [--strict] <repo>" >&2
exit 2
fi
command -v rg >/dev/null || { echo "app-audit: needs ripgrep (rg)" >&2; exit 2; }
cd "$root"
out=$(rg --files -g '*.rs' -g '!target' -g '!**/tests/**' -g '!tests.rs' -g '!*_tests.rs' -g '!**/benches/**' 2>/dev/null \
| LC_ALL=C sort \
| xargs awk '
function trim(s) { sub(/^[ \t]+/, "", s); if (length(s) > 70) s = substr(s, 1, 70) "..."; return s }
function near(i, before, after, re, j) {
for (j = i - before; j <= i + after; j++) if (j >= 1 && j <= N && L[j] ~ re) return 1
return 0
}
function hit(check, i) { printf "%s\t%s:%d\t%s\n", check, file, i, trim(L[i]) }
function flush( i, j, n, v, only, uses, win, cond, ms, evicts, entry) {
if (file == "") return
entry = 0; evicts = 0
for (i = 1; i <= N; i++) {
if (L[i] ~ /fn (view|poll|init)[ (<]|\.on_[a-z_]+\(/) entry = 1
if (L[i] ~ /retain|\.remove\(|\.pop|evict|\.clear\(\)|LruCache|truncate/) evicts = 1
}
for (i = 1; i <= N; i++) {
if (L[i] ~ /^[ \t]*\/\//) continue
if (L[i] ~ /\.virtualize\(/ && L[i] !~ /virtual_rows/) {
win = 0
for (j = i - 15; j <= i + 40; j++) if (j >= 1 && j <= N && L[j] ~ /\.child\(|\.children\(|\.extend\(|\.push\(/) win = 1
if (win) hit("virtualize over built rows", i)
}
if (entry && L[i] ~ /Command::new|UnixStream|TcpStream|reqwest::blocking|rusqlite|std::fs::read_to_string|fs::read_to_string/ \
&& L[i] !~ /^[ \t]*use /) hit("blocking call near view/poll/init", i)
if (L[i] ~ /wake_after\(/ && match(L[i], /from_millis\([0-9]+\)/)) {
ms = substr(L[i], RSTART + 12, RLENGTH - 13) + 0
if (ms <= 33) {
cond = 0
for (j = i - 4; j <= i; j++) if (j >= 1 && L[j] ~ /(^|[^a-z_])(if|match|return)([^a-z_]|$)/) cond = 1
if (!cond) hit("wake_after <= 33 ms, unconditional", i)
}
}
if (L[i] ~ /\.layout\((&|"|format)/) {
if (L[i] ~ /\.layout\([^;]*\[[23]\]/ && L[i] !~ /\[[01]\]/) hit("layout rect read for one size", i)
else if (match(L[i], /let (mut )?[a-z_][a-z_0-9]* = .*\.layout\(/)) {
v = L[i]; sub(/^[ \t]*let (mut )?/, "", v); sub(/[^a-z_0-9].*/, "", v)
only = 1; uses = 0
for (j = i + 1; j <= i + 12 && j <= N; j++) {
n = L[j]
while (match(n, v "\\[[0-9]\\]")) {
uses++
if (substr(n, RSTART + length(v) + 1, 1) !~ /[23]/) only = 0
n = substr(n, RSTART + RLENGTH)
}
}
if (uses > 0 && only) hit("layout rect read for one size", i)
}
}
if (!evicts && L[i] ~ /static .*(HashMap|BTreeMap)/) hit("static map cache with no eviction in file", i)
if (L[i] ~ /\.window_layout\(/) hit("window_layout read (re-runs each scroll frame)", i)
if (L[i] ~ /\.on_(layout|drawn_layout)(_tx)?(::<[^>]*>)?\(/ && !near(i, 0, 8, "live_only")) hit("layout handler without live_only", i)
if (L[i] ~ /\.on_hover(_change)?(::<[^>]*>)?\(/ && !near(i, 0, 6, "live_only")) hit("hover kept in state", i)
if (L[i] ~ /scroll_to_instant\(/ && near(i, 10, 10, "wake_after\\(")) hit("instant scroll stepped by wake_after", i)
}
}
FNR == 1 { flush(); file = FILENAME; N = 0; stop = 0 }
{ if (!stop) { if ($0 ~ /#\[cfg\(test\)\]/) stop = 1; else L[++N] = $0 } }
END { flush() }
' 2>/dev/null || true)
if [ -z "$out" ]; then
echo "app-audit: no findings"
exit 0
fi
printf '%s\n' "$out" | awk -F'\t' '{ printf "%-42s %-48s %s\n", $1, $2, $3 }'
n=$(printf '%s\n' "$out" | wc -l | tr -d ' ')
echo "app-audit: $n finding(s)"
[ "$strict" = 1 ] && exit 1
exit 0
+34
View File
@@ -0,0 +1,34 @@
#!/usr/bin/env python3
"""CPU submission benchmark for 16 × 60 Hz meters + 4 × 120 Hz cursors; no window."""
import argparse
import json
import re
import statistics
import subprocess
from perf_binary import perf_binary
p = argparse.ArgumentParser()
p.add_argument('--binary', default='target/perf/live-values')
p.add_argument('--baseline', action='store_true')
a = p.parse_args()
a.binary = str(perf_binary(a.binary))
modes = ['rebuild'] if a.baseline else ['rebuild', 'live']
samples = {mode: [] for mode in modes}
for run in range(8):
# Alternate order so driver load and temperature cannot systematically favour a mode.
for mode in modes[::(-1 if run % 2 else 1)]:
cmd = [a.binary, '--frames', '480', '--fps', '120']
if mode == 'rebuild':
cmd.append('--rebuild')
output = subprocess.run(cmd, check=True, capture_output=True, text=True).stderr
match = re.search(r'frame cpu mean ([\d.]+) ms p50 ([\d.]+) p95 ([\d.]+)', output)
if not match:
raise RuntimeError(output)
if run:
samples[mode].append(dict(zip(['mean_ms', 'p50_ms', 'p95_ms'], map(float, match.groups()))))
results = {}
for mode, runs in samples.items():
results[mode] = {k: statistics.median(r[k] for r in runs) for k in runs[0]}
results[mode]['runs'] = runs
print(json.dumps(results, indent=2))
+51
View File
@@ -0,0 +1,51 @@
#!/usr/bin/env python3
"""Fresh-process launch to GPU-complete readable pixels; OS/driver caches stay warm."""
import argparse
import json
import pathlib
import selectors
import statistics
import subprocess
import time
from perf_binary import perf_binary
p = argparse.ArgumentParser()
p.add_argument('--out', required=True, type=pathlib.Path)
p.add_argument('--runs', type=int, default=7)
a = p.parse_args()
a.out.mkdir(parents=True, exist_ok=True)
cases = {
'settings': ['target/perf/settings'],
}
result = {}
for name, cmd in cases.items():
cmd = [str(perf_binary(cmd[0])), *cmd[1:]]
runs = []
for i in range(a.runs + 1):
start = time.perf_counter()
proc = subprocess.Popen(cmd + ['--first-pixels', '--frames', '1'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
try:
with selectors.DefaultSelector() as selector:
selector.register(proc.stdout, selectors.EVENT_READ)
if not selector.select(timeout=30):
raise TimeoutError(f'{name}: first pixels not ready after 30s')
line = proc.stdout.readline().decode()
elapsed = (time.perf_counter() - start) * 1000
_, stderr = proc.communicate(timeout=30)
(a.out / f'{name}-{i}.log').write_bytes(line.encode() + stderr)
if proc.returncode or not line.startswith('rune-first-pixels '):
raise RuntimeError(f'{name}: {line}\n{stderr.decode()}')
row = json.loads(line.removeprefix('rune-first-pixels '))
row['process_ms'] = elapsed
if i:
runs.append(row)
finally:
if proc.poll() is None:
proc.kill()
proc.wait()
median = {k: statistics.median(r[k] for r in runs) for k in runs[0]}
mad = {k: statistics.median(abs(r[k] - median[k]) for r in runs) for k in median}
result[name] = {'median': median, 'mad': mad, 'runs': runs}
print(name, json.dumps(median), flush=True)
(a.out / 'results.json').write_text(json.dumps(result, indent=2) + '\n')
+148
View File
@@ -0,0 +1,148 @@
#!/usr/bin/env python3
"""Repeatable offscreen workloads; build and run on a headless GPU worker.
Frame-CPU mode:
cargo build --profile perf -p settings --bins --features frame-profile
python3 scripts/bench-ui.py --frame-cpu --out target/frame-cpu --runs 9
Scroll frame-CPU mode (windowless; input through draw lists, no GPU submission):
cargo build --profile perf -p rune-kit --example scroll_bench --features markdown,frame-profile
python3 scripts/bench-ui.py --frame-cpu --scroll --out target/scroll --runs 9
Save scroll_bench under saved/target/perf/examples/ to compare scroll workloads.
Save the baseline binaries in saved/target/perf,
then build the candidate and add --compare saved/target/perf. Use separate Cargo
target directories for separate source roots. Comparison verifies binary hashes
differ, discards one warmup per side, and alternates paired runs; report medians
and MAD, and keep timing changes only above the observed noise.
Commit includes view/layout/shaping, and Layout includes shaping: phases overlap;
do not sum them. CPU clocks measure the calling thread; elapsed encode/submit may
include queue backpressure. The runner forces idle frames, so idle is not native
wake CPU; startup measures first completed pixels, not display presentation.
"""
import argparse
import hashlib
import json
import pathlib
import re
import statistics
import subprocess
import os
import selectors
import time
from perf_binary import perf_binary
ROOT = pathlib.Path(__file__).resolve().parents[1]
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
p.add_argument('--out', required=True, type=pathlib.Path)
p.add_argument('--runs', type=int, default=7)
p.add_argument('--only', default='')
p.add_argument('--frame-cpu', action='store_true', help='include dense fixtures and phase/allocation metrics (build --features frame-profile)')
p.add_argument('--scroll', action='store_true', help='windowless scroll workloads; build rune-kit example scroll_bench with markdown,frame-profile')
p.add_argument('--compare', type=pathlib.Path, help='alternate with saved baseline binaries in a target/perf directory')
a = p.parse_args()
if a.runs < 1:
p.error('--runs must be positive')
a.out.mkdir(parents=True, exist_ok=True)
workloads = {
'settings': ('settings', ['--script', 'examples/settings/scripts/bench.json', '--frames', '360']),
}
if a.frame_cpu:
workloads['startup'] = ('settings', ['--first-pixels', '--frames', '1'])
if a.scroll:
workloads = {f'scroll-{name}': ('examples/scroll_bench', ['--workload', name, '--frames', '480'])
for name in ('list', 'markdown', 'sticky', 'growth', 'prose')}
rx = re.compile(r'gpu init ([\d.]+) ms, first frame ([\d.]+) ms, frame cpu mean ([\d.]+) ms p50 ([\d.]+) p95 ([\d.]+) max ([\d.]+), (\d+) instances')
names = ['gpu_ms', 'first_ms', 'mean_ms', 'p50_ms', 'p95_ms', 'max_ms', 'instances']
result = {}
targets = {'current': pathlib.Path(os.environ.get('CARGO_TARGET_DIR', ROOT / 'target')) / 'perf'}
if a.compare:
targets['before'] = a.compare.resolve()
for name, (binary, args) in workloads.items():
if a.only and name not in a.only.split(','):
continue
binaries = {stage: perf_binary(target / binary) for stage, target in targets.items()}
if a.compare:
hashes = []
for path in binaries.values():
digest = hashlib.sha256()
with path.open('rb') as source:
for chunk in iter(lambda: source.read(1024 * 1024), b''):
digest.update(chunk)
hashes.append(digest.digest())
if hashes[0] == hashes[1]:
p.error(f'{name}: current and before binaries have identical SHA-256 hashes; rebuild separate candidates')
samples = {stage: [] for stage in targets}
for i in range(a.runs + 1):
for stage in list(targets)[::(-1 if i % 2 else 1)]:
cmd = [str(binaries[stage]), *args, '--fps', '120']
process_ms = None
log_path = a.out / f'{name}-{stage}-{i}.log'
if name == 'startup':
with log_path.open('w+') as log:
start = time.perf_counter()
with subprocess.Popen(cmd, cwd=ROOT, stdout=subprocess.PIPE, stderr=log, text=True) as proc:
try:
with selectors.DefaultSelector() as selector:
selector.register(proc.stdout, selectors.EVENT_READ)
if not selector.select(timeout=30):
raise TimeoutError('first pixels not ready after 30s')
first = proc.stdout.readline()
process_ms = (time.perf_counter() - start) * 1000
if not first.startswith('rune-first-pixels '):
raise RuntimeError(f'unexpected first-pixels marker: {first}')
stdout, _ = proc.communicate(timeout=30)
log.seek(0)
r = subprocess.CompletedProcess(cmd, proc.returncode, first + stdout, log.read())
r.check_returncode()
finally:
if proc.poll() is None:
proc.kill()
proc.wait()
else:
r = subprocess.run(cmd, cwd=ROOT, capture_output=True, text=True, check=True, timeout=180)
log_path.write_text(r.stdout + r.stderr)
if a.scroll:
profile = re.search(r'rune-scroll-profile (.+)', r.stdout)
if not profile:
raise RuntimeError(r.stdout + r.stderr)
if i:
samples[stage].append(json.loads(profile[1]))
continue
m = rx.search(r.stderr)
if not m:
raise RuntimeError(r.stderr)
row = dict(zip(names, map(float, m.groups())))
phase = re.search(r'rune-frame-profile (.+)', r.stderr)
if a.frame_cpu and not phase:
raise RuntimeError('rebuild with --features frame-profile')
if phase:
row.update({k: v for k, v in json.loads(phase[1]).items() if v is not None})
pixels = re.search(r'rune-first-pixels (.+)', r.stdout)
if pixels:
row.update(json.loads(pixels[1]))
if process_ms is not None:
row['process_ms'] = process_ms
if i:
samples[stage].append(row)
for stage, runs in samples.items():
med = {k: statistics.median(r[k] for r in runs) for k in runs[0]}
mad = {k: statistics.median(abs(r[k] - med[k]) for r in runs) for k in med}
label = f'{name}.{stage}' if a.compare else name
result[label] = {'median': med, 'mad': mad, 'runs': runs}
print(label, json.dumps(med), flush=True)
for key, value in med.items():
print(f'METRIC {label}.{key}={value:.6f}', flush=True)
print(f'METRIC {label}.{key}.mad={mad[key]:.6f}', flush=True)
if a.compare:
metric = 'cpu_ms_p50' if a.scroll else ('thread_cpu_ms' if 'thread_cpu_ms' in samples['current'][0] and 'thread_cpu_ms' in samples['before'][0] else 'mean_ms')
ratios = [cur[metric] / old[metric] for cur, old in zip(samples['current'], samples['before'])]
ratio = statistics.median(ratios)
spread = statistics.median(abs(r - ratio) for r in ratios)
result[f'{name}.paired'] = {'metric': metric, 'ratio': ratio, 'mad': spread}
print(f'{name}: paired ratio uses {metric}', flush=True)
print(f'METRIC {name}.paired_ratio={ratio:.6f}', flush=True)
print(f'METRIC {name}.paired_ratio.mad={spread:.6f}', flush=True)
(a.out / 'results.json').write_text(json.dumps(result, indent=2) + '\n')
+9
View File
@@ -0,0 +1,9 @@
#!/bin/sh
# Reproducibly builds `crates/rune-kit/assets/math/ratex-math.wasm.deflate`,
# `crates/rune-kit/assets/math/katex-fonts.pack.deflate`, and
# `crates/rune-kit/src/math/wasm_hash.rs` from pinned `tools/ratex-math-wasm/`.
# Pass `--check` to rebuild from source and assert byte-for-byte equality.
set -eu
cd "$(dirname "$0")/.."
exec cargo run --release --manifest-path tools/ratex-math-wasm/pack/Cargo.toml -- "$@"
+52
View File
@@ -0,0 +1,52 @@
#!/usr/bin/env python3
"""Fold changelog/unreleased/*.md into CHANGELOG.md under `## dev`, newest first, then delete them.
Usage: scripts/changelog-fold [--check]
Order is each fragment's first-commit time (git log --diff-filter=A), else the date in its filename.
"""
import calendar, glob, os, re, subprocess, sys, time
root = subprocess.check_output(["git", "rev-parse", "--show-toplevel"], text=True).strip()
os.chdir(root)
check = "--check" in sys.argv[1:]
def stamp(path):
out = subprocess.run(
["git", "log", "--diff-filter=A", "--format=%ct", "-1", "--", path],
capture_output=True, text=True,
).stdout.strip()
if out:
return int(out)
m = re.match(r"(\d{4})-(\d{2})-(\d{2})", os.path.basename(path))
return calendar.timegm((int(m[1]), int(m[2]), int(m[3]), 0, 0, 0)) if m else int(time.time())
frags = [f for f in glob.glob("changelog/unreleased/*.md") if os.path.basename(f) != "README.md"]
if not frags:
print("no fragments")
sys.exit(0)
frags.sort(key=lambda f: (-stamp(f), os.path.basename(f)))
entries = [open(f).read().strip("\n") for f in frags]
text = open("CHANGELOG.md").read()
lines = text.split("\n")
i = lines.index("## dev")
j = i + 1
while j < len(lines) and lines[j].strip() == "":
j += 1
# keep the note line (and any other leading prose) above the entries
while j < len(lines) and lines[j] and not lines[j].startswith(("- ", "## ")):
j += 1
while j < len(lines) and lines[j].strip() == "":
j += 1
block = "\n\n".join(entries).split("\n") + [""]
new = lines[:j] + block + lines[j:]
if check:
for f in frags:
print("would fold", f)
sys.exit(0)
open("CHANGELOG.md", "w").write("\n".join(new))
for f in frags:
os.remove(f)
print("folded", f)
+76
View File
@@ -0,0 +1,76 @@
#!/usr/bin/env python3
"""Pro-only accessory -> Regular proof; uses existing TCC and /tmp/pro-gui.lock."""
import fcntl
import importlib
import json
import os
import platform
import subprocess
import sys
native = importlib.import_module("check-native-menu-macos")
native.SESSION = "rune-dock-menu"
def check(binary, order):
process = subprocess.Popen([binary], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, env=dict(os.environ, RUNE_MENU_ORDER=order))
reader = native.Reader(process)
def command(text):
process.stdin.write((text + "\n").encode())
process.stdin.flush()
def status(custom, regular=True):
command("status")
lines = reader.until("STATUS")
assert f"CUSTOM_PRESENT {str(custom).lower()}" in lines
assert f"POLICY NSApplicationActivationPolicy({0 if regular else 1})" in lines
return next(line.removeprefix("QUIT_KEY ") for line in lines if line.startswith("QUIT_KEY "))
try:
reader.until("ACCESSORY_CUSTOM" if order == "before" else "ACCESSORY_MISSING")
command("show")
reader.until("WINDOW_READY")
native.call("start_session")
windows = native.call("list_windows", pid=process.pid)
window = next(w for w in windows["windows"] if w["pid"] == process.pid
and w.get("title") == "Rune Dock menu probe" and w.get("is_on_screen"))
target = dict(pid=process.pid, window_id=window["window_id"])
status(order == "before")
if order == "after":
command("custom")
status(True)
# A real AX menu action verifies the application menu is available after promotion.
native.call("invoke_menu", **target, path=[os.path.basename(binary), "Custom Action"])
reader.until("CUSTOM")
command("clear")
status(False)
command("dock-off")
status(False, regular=False) # The same root/defaults survive hiding the Dock icon.
command("dock-on")
quit_key = status(False)
native.call("press_key", **target, key=quit_key, modifiers=["cmd"], delivery_mode="foreground")
process.wait(timeout=15)
assert process.returncode == 0, process.returncode
print(f"PASS {order}: accessory promotion, visible app menu, custom composition/removal, Dock toggles and Cmd-Q", flush=True)
finally:
if process.poll() is None:
command("quit")
try:
process.wait(timeout=10)
except subprocess.TimeoutExpired:
process.terminate()
process.wait(timeout=10)
subprocess.run([native.CUA, "end_session", json.dumps({"session": native.SESSION})],
capture_output=True, timeout=15)
def main():
if len(sys.argv) != 2 or not platform.node().lower().startswith("kits-shiny-computer"):
raise SystemExit("run on Pro: check-dock-menu-macos.py /path/to/dock_menu_probe")
with open("/tmp/pro-gui.lock", "a") as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
for order in ("after", "before"):
check(sys.argv[1], order)
if __name__ == "__main__":
main()
+83
View File
@@ -0,0 +1,83 @@
#!/usr/bin/env python3
"""Run on pro with the built shortcut_probe binary. Does not change TCC permissions."""
import fcntl
import json
import os
import platform
import selectors
import subprocess
import sys
import time
CUA = "/Applications/CuaDriver.app/Contents/MacOS/cua-driver"
SESSION = "rune-global-shortcut"
def call(tool, arguments):
result = subprocess.run([CUA, tool, json.dumps(arguments)], capture_output=True, text=True, timeout=30)
if result.returncode:
raise RuntimeError(result.stderr or result.stdout)
value = json.loads(result.stdout)
if value.get("isError"):
raise RuntimeError(result.stdout)
return value
def line(process, expected):
deadline = time.monotonic() + 30
pending = b""
with selectors.DefaultSelector() as selector:
selector.register(process.stdout, selectors.EVENT_READ)
while time.monotonic() < deadline:
if not selector.select(max(0, deadline - time.monotonic())):
break
output = os.read(process.stdout.fileno(), 4096)
if not output:
raise RuntimeError(f"probe exited {process.poll()} before {expected}")
pending += output
while b"\n" in pending:
output, pending = pending.split(b"\n", 1)
output = output.decode()
print(output.rstrip(), flush=True)
if output.rstrip() == expected:
return
raise RuntimeError(f"timed out waiting for {expected}")
def main():
if len(sys.argv) != 2:
raise SystemExit("usage: check-global-shortcut-macos.py /path/to/shortcut_probe")
if not platform.node().lower().startswith("kits-shiny-computer"):
raise SystemExit("this native check must run on pro, not a fallback worker")
with open("/tmp/pro-gui.lock", "a") as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
owner = subprocess.Popen([sys.argv[1]], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, text=True, bufsize=1)
try:
line(owner, "READY")
# A second process must get Carbon's real conflict, not an in-process duplicate.
conflict = subprocess.run([sys.argv[1], "--probe-conflict"], input="", capture_output=True, text=True, timeout=30)
if conflict.returncode or "CONFLICT" not in conflict.stdout:
raise RuntimeError(conflict.stdout + conflict.stderr)
print("SECOND PROCESS: CONFLICT", flush=True)
# Inspect the native session before input. The registered app stays windowless.
call("start_session", {"session": SESSION})
call("list_apps", {"session": SESSION})
result = call("press_key", {"session": SESSION, "target": {"kind": "desktop", "display_id": "primary"},
"key": "k", "modifiers": ["cmd", "ctrl", "alt", "shift"]})
print(json.dumps(result), flush=True)
# Driver success alone is not proof: the application must report the handler.
line(owner, "FIRED 1")
print("PASS: Carbon activation reached the app state on its creating thread", flush=True)
finally:
owner.stdin.close()
try:
owner.wait(timeout=10)
except subprocess.TimeoutExpired:
owner.terminate()
owner.wait(timeout=10)
subprocess.run([CUA, "end_session", json.dumps({"session": SESSION})], capture_output=True, timeout=15)
if __name__ == "__main__":
main()
+155
View File
@@ -0,0 +1,155 @@
#!/usr/bin/env bash
# Fast, opt-in local developer checks for Rune (pure POSIX bash/awk/grep; no Python required).
# Usage: scripts/check-local.sh [--wasm] [--all] [--tests] [--help]
set -euo pipefail
cd "$(git rev-parse --show-toplevel)"
usage() {
cat <<'EOF'
Usage: scripts/check-local.sh [options]
Fast, opt-in local checks for Rune (no Python required).
Default steps:
1. scripts/file-size.sh (includes scripts/folder-shape.sh)
2. Public-repo hygiene scan on staged + unstaged diff (git diff HEAD)
3. cargo check (default workspace members)
4. cargo clippy --lib --bins (default workspace members)
Options:
--wasm Also run cargo check-wasm and cargo check-webgl
--all Check and lint --workspace --all-targets instead of default members
--tests Also run cargo test-fast
-h, --help Show this help message and exit
EOF
}
run_wasm=0
run_all=0
run_tests=0
for arg in "$@"; do
case "$arg" in
--wasm) run_wasm=1 ;;
--all) run_all=1 ;;
--tests) run_tests=1 ;;
-h|--help) usage; exit 0 ;;
*)
printf 'unknown option: %s\n\n' "$arg" >&2
usage >&2
exit 2
;;
esac
done
hygiene_tmp=""
trap 'rm -f "${hygiene_tmp:-}"' EXIT
check_hygiene() {
# Bracketed slashes keep the pattern identical to the repo hygiene regex
# without matching this script itself.
local re='[/]Users[/]|[/]private[/]var[/]|\.ts\.net|ses_[A-Za-z0-9]{20}'
local rc=0
hygiene_tmp=$(mktemp) || return 1
git -c core.quotepath=false diff --no-color --no-ext-diff --src-prefix=a/ --dst-prefix=b/ -U0 HEAD -- \
| awk '
/^\+\+\+ b\// {
file = substr($0, 7)
sub(/\r$/, "", file)
sub(/\t$/, "", file)
next
}
/^@@ / {
if (match($0, /\+[0-9]+/)) {
line = substr($0, RSTART + 1, RLENGTH - 1) + 0
}
next
}
/^\+/ && !/^\+\+\+/ {
body = substr($0, 2)
sub(/\r$/, "", body)
check = body
gsub(/host\.example\.ts\.net/, "", check)
printf "%s:%d: %s\n", file, line, check
line++
}
' \
| grep -E -- "$re" > "$hygiene_tmp" || rc=$?
if [ -s "$hygiene_tmp" ]; then
echo "Public-repo hygiene check found disallowed patterns in diff against HEAD:" >&2
cat "$hygiene_tmp" >&2
rm -f "$hygiene_tmp"
hygiene_tmp=""
return 1
fi
rm -f "$hygiene_tmp"
hygiene_tmp=""
# grep exits 1 on zero matches; any other non-zero status means git/awk/grep errored.
[ "$rc" -eq 0 ] || [ "$rc" -eq 1 ]
}
step_names=()
step_status=()
step_secs=()
failures=0
run_step() {
local name="$1"
shift
printf '\n==> %s\n' "$name"
local start="$SECONDS"
local rc=0
"$@" || rc=$?
local elapsed=$((SECONDS - start))
step_names+=("$name")
step_secs+=("$elapsed")
if [ "$rc" -eq 0 ]; then
step_status+=("PASS")
else
step_status+=("FAIL")
failures=$((failures + 1))
fi
}
total_start="$SECONDS"
run_step "file-size" bash scripts/file-size.sh
run_step "public-repo hygiene" check_hygiene
if [ "$run_all" -eq 1 ]; then
run_step "cargo check --workspace --all-targets" cargo check --workspace --all-targets
run_step "cargo lint-all" cargo lint-all
else
run_step "cargo check" cargo check
run_step "cargo clippy --lib --bins" cargo clippy --lib --bins
fi
if [ "$run_wasm" -eq 1 ]; then
run_step "cargo check-wasm" cargo check-wasm
run_step "cargo check-webgl" cargo check-webgl
fi
if [ "$run_tests" -eq 1 ]; then
run_step "cargo test-fast" cargo test-fast
fi
total_elapsed=$((SECONDS - total_start))
if [ "$failures" -eq 0 ]; then
overall="PASS"
else
overall="FAIL"
fi
printf '\nSummary:\n'
printf ' %-38s %-6s %8s\n' "step" "status" "elapsed"
printf ' %-38s %-6s %8s\n' "--------------------------------------" "------" "--------"
i=0
while [ "$i" -lt "${#step_names[@]}" ]; do
printf ' %-38s %-6s %7ds\n' "${step_names[$i]}" "${step_status[$i]}" "${step_secs[$i]}"
i=$((i + 1))
done
printf ' %-38s %-6s %8s\n' "--------------------------------------" "------" "--------"
printf ' %-38s %-6s %7ds\n' "total" "$overall" "$total_elapsed"
[ "$failures" -eq 0 ]
+111
View File
@@ -0,0 +1,111 @@
#!/usr/bin/env python3
"""Pro-only native menu proof. Uses existing CuaDriver permissions; no TCC changes."""
import fcntl
import json
import os
import platform
import selectors
import subprocess
import sys
import time
CUA = "/Applications/CuaDriver.app/Contents/MacOS/cua-driver"
SESSION = "rune-native-menu"
def call(tool, **arguments):
result = subprocess.run([CUA, tool, json.dumps(dict(session=SESSION, **arguments))],
capture_output=True, text=True, timeout=30)
if result.returncode:
raise RuntimeError(result.stderr or result.stdout)
value = json.loads(result.stdout)
if value.get("isError"):
raise RuntimeError(result.stdout)
print(tool, json.dumps(value), flush=True)
if "structuredContent" in value:
return value["structuredContent"]
for part in value.get("content", []):
if part.get("type") == "text":
try:
return json.loads(part["text"])
except json.JSONDecodeError:
pass
return value
class Reader:
def __init__(self, process):
self.process = process
self.pending = b""
def until(self, expected):
deadline = time.monotonic() + 30
lines = []
with selectors.DefaultSelector() as selector:
selector.register(self.process.stdout, selectors.EVENT_READ)
while time.monotonic() < deadline:
while b"\n" in self.pending:
line, self.pending = self.pending.split(b"\n", 1)
line = line.decode().rstrip()
print(line, flush=True)
lines.append(line)
if line == expected:
return lines
if not selector.select(max(0, deadline - time.monotonic())):
break
chunk = os.read(self.process.stdout.fileno(), 4096)
if not chunk:
raise RuntimeError(f"probe exited {self.process.poll()} before {expected}")
self.pending += chunk
raise RuntimeError(f"timed out waiting for {expected}")
def main():
if len(sys.argv) != 2 or not platform.node().lower().startswith("kits-shiny-computer"):
raise SystemExit("run on Pro: check-native-menu-macos.py /path/to/menu_probe")
with open("/tmp/pro-gui.lock", "a") as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
process = subprocess.Popen([sys.argv[1]], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
reader = Reader(process)
def command(text):
process.stdin.write((text + "\n").encode())
process.stdin.flush()
try:
reader.until("READY")
call("start_session")
windows = call("list_windows", pid=process.pid)
records = windows.get("windows", windows) if isinstance(windows, dict) else windows
window = next(w for w in records if w["pid"] == process.pid and w.get("title") == "Rune menu probe" and w.get("is_on_screen"))
target = dict(pid=process.pid, window_id=window["window_id"])
command("status")
status = reader.until("STATUS")
assert "NATIVE enabled=true checked=false" in status and "DOCK items=1" in status
assert "NAMED items=3 separators=[1]" in status
# winit labels the default app menu with NSProcessInfo.processName.
call("invoke_menu", **target, path=[os.path.basename(sys.argv[1]), "Open Quick Panel"])
reader.until("FIRED 1")
call("press_key", **target, key="k", modifiers=["cmd", "alt", "shift"], delivery_mode="foreground")
reader.until("FIRED 2")
call("invoke_menu", **target, path=["Rune Tools", "Named Quick Panel"])
reader.until("FIRED 3")
command("disable"); command("status")
status = reader.until("STATUS")
assert "NATIVE enabled=false checked=true" in status and "COUNT 3" in status
command("clear"); command("status")
status = reader.until("STATUS")
assert "NATIVE cleared" in status and "DOCK items=0" in status and "DEFAULTS preserved" in status
print("PASS: app-menu click, key equivalent and named-menu click ran on app thread; runtime state, Dock hook and defaults verified", flush=True)
finally:
if process.poll() is None:
command("quit")
try:
process.wait(timeout=10)
except subprocess.TimeoutExpired:
process.terminate(); process.wait(timeout=10)
subprocess.run([CUA, "end_session", json.dumps({"session": SESSION})], capture_output=True, timeout=15)
assert process.returncode == 0, process.returncode
if __name__ == "__main__":
main()
+18
View File
@@ -0,0 +1,18 @@
#!/usr/bin/env python3
"""Check a timestamp-only `pacing --native --trace FILE --frames 240` run."""
import json
import statistics
import sys
with open(sys.argv[1]) as source:
header, *frames = [json.loads(line) for line in source]
assert header['clock'] != 'virtual', 'headless timestamps cannot prove native pacing'
assert len(frames) >= 60, f'only {len(frames)} native frames'
assert sum(frame.get('quality', {}).get('animating', False) for frame in frames) >= 10, 'no spring animation'
# Exclude the first frame/initial gap, not later commit or idle-resume gaps.
gaps = [b['t'] - a['t'] for a, b in zip(frames[1:], frames[2:])]
half_refresh = 500 / header['hz']
bad = [gap for gap in gaps if gap < half_refresh - 0.01]
print(json.dumps({'frames': len(frames), 'hz': header['hz'], 'half_refresh_ms': half_refresh,
'minimum_gap_ms': min(gaps), 'median_gap_ms': statistics.median(gaps), 'short_gaps': len(bad)}, indent=2))
assert not bad, f'{len(bad)} sub-half-refresh gaps'
+26
View File
@@ -0,0 +1,26 @@
#!/bin/sh
# Run BOTH revisions on the same Linux worker/toolchain with a shared target dir.
# First: ... save; on the candidate: ... check. Never silently bless a missing baseline.
set -eu
[ "$(uname -s)" = Linux ] || { echo 'Linux + Valgrind required' >&2; exit 1; }
command -v valgrind >/dev/null
command -v gungraun-runner >/dev/null
export RUSTC_WRAPPER=
export RUSTFLAGS="${RUSTFLAGS:-} -C llvm-args=-fp-contract=off"
baseline="${CARGO_TARGET_DIR:-target}/rune-ref-instruction-baseline"
case "${1:-check}" in
save)
cargo bench --locked -p rune-ref --bench instructions -- --save-baseline=main
mkdir -p "$(dirname "$baseline")"
{ rustc -Vv; valgrind --version; gungraun-runner --version; } > "$baseline"
;;
check)
[ -f "$baseline" ] || { echo 'Missing baseline: measure base revision with save first' >&2; exit 1; }
current=$(mktemp)
trap 'rm -f "$current"' EXIT
{ rustc -Vv; valgrind --version; gungraun-runner --version; } > "$current"
cmp "$baseline" "$current"
cargo bench --locked -p rune-ref --bench instructions -- --baseline=main
;;
*) echo 'usage: check-reference-instructions.sh save|check' >&2; exit 1 ;;
esac
+11
View File
@@ -0,0 +1,11 @@
#!/bin/sh
# Invoke on a build worker through the build queue. GPU is headless but still needs an adapter.
set -eu
export RUSTC_WRAPPER=
export RUSTFLAGS="${RUSTFLAGS:-} -C llvm-args=-fp-contract=off"
cargo test --locked -p rune-ref --test reference --test alloc
cargo test --locked -p rune --test alloc
if [ "${1:-}" = "--gpu" ]; then
cargo test --locked -p rune-ref --features gpu --test differential -- --test-threads=1 --nocapture
cargo test --locked -p rune-ref --features gpu --test fx_blend -- --test-threads=1
fi
+58
View File
@@ -0,0 +1,58 @@
// No AppKit, window, or screen access. Matched positions isolate rasterization from shaping.
import Foundation
import CoreText
import CoreGraphics
import ImageIO
import UniformTypeIdentifiers
let dir = URL(fileURLWithPath: CommandLine.arguments[1])
let nativeOpticalSize = CommandLine.arguments.contains("--native-opsz")
var shaping: [[String: Any]] = []
for url in try FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: nil)
where url.pathExtension == "json" && (url.lastPathComponent.hasPrefix("light-") || url.lastPathComponent.hasPrefix("dark-")) {
let data = try JSONSerialization.jsonObject(with: Data(contentsOf: url)) as! [String: Any]
let width = data["width"] as! Int, height = data["height"] as! Int
let scale = data["scale"] as! Double
let fontURL = URL(fileURLWithPath: data["font"] as! String)
let provider = CGDataProvider(url: fontURL as CFURL)!
let cgfont = CGFont(provider)!
let cs = CGColorSpace(name: CGColorSpace.sRGB)!
let ctx = CGContext(data:nil,width:width,height:height,bitsPerComponent:8,bytesPerRow:width*4,
space:cs,bitmapInfo:CGImageAlphaInfo.premultipliedLast.rawValue)!
let fg = CGFloat(data["fg"] as! Int)/255, bg = CGFloat(data["bg"] as! Int)/255
ctx.setFillColor(red:bg,green:bg,blue:bg,alpha:1)
ctx.fill(CGRect(x:0,y:0,width:width,height:height))
ctx.setFillColor(red:fg,green:fg,blue:fg,alpha:1)
ctx.setAllowsAntialiasing(true); ctx.setShouldAntialias(true)
ctx.setAllowsFontSmoothing(true); ctx.setShouldSmoothFonts(true)
ctx.setAllowsFontSubpixelPositioning(true); ctx.setShouldSubpixelPositionFonts(true)
ctx.setAllowsFontSubpixelQuantization(false); ctx.setShouldSubpixelQuantizeFonts(false)
// Preserve nominal point size: CoreText optical smoothing can depend on it.
ctx.scaleBy(x:scale,y:scale)
for row in data["rows"] as! [[String:Any]] {
let base = CTFontCreateWithGraphicsFont(cgfont,CGFloat(row["size"] as! Double),nil,nil)
// Parley's current optical-size selection uses the run's device-pixel size.
// Pin the reference to that same variation; otherwise SF compares different outlines.
let opsz = row["opsz"] as? Double ?? (row["size"] as! Double)*scale
let attrs = [kCTFontVariationAttribute: [NSNumber(value:0x6f70737a): opsz]] as CFDictionary
let font = nativeOpticalSize ? base : CTFontCreateCopyWithAttributes(base,0,nil,CTFontDescriptorCreateWithAttributes(attrs))
let attributed = NSAttributedString(string: row["text"] as! String,
attributes: [NSAttributedString.Key(kCTFontAttributeName as String): font])
let line = CTLineCreateWithAttributedString(attributed)
let advance = CTLineGetTypographicBounds(line, nil, nil, nil) * scale
shaping.append(["sample": url.lastPathComponent, "size": row["size"]!, "text": row["text"]!,
"rune_advance": row["advance"] ?? 0, "coretext_advance": advance,
"coretext_variations": String(describing: CTFontCopyVariation(font))])
let items = row["glyphs"] as! [[String:Any]]
var glyphs = items.map { CGGlyph($0["id"] as! Int) }
var positions = items.map { CGPoint(x:($0["x"] as! Double)/scale,y:(Double(height)-($0["y"] as! Double))/scale) }
CTFontDrawGlyphs(font,&glyphs,&positions,glyphs.count,ctx)
}
let dest = dir.appendingPathComponent("coretext-"+url.deletingPathExtension().lastPathComponent+".png")
let sink = CGImageDestinationCreateWithURL(dest as CFURL,UTType.png.identifier as CFString,1,nil)!
CGImageDestinationAddImage(sink,ctx.makeImage()!,nil)
precondition(CGImageDestinationFinalize(sink))
print(dest.lastPathComponent)
}
try JSONSerialization.data(withJSONObject: shaping, options: [.prettyPrinted, .sortedKeys])
.write(to: dir.appendingPathComponent("coretext-shaping.json"))
+22
View File
@@ -0,0 +1,22 @@
#!/usr/bin/env bash
# Regenerates the CoreText reference sheets that `rune::text::pixel_compare` (its test and
# `--example coretext_compare`) compares Rune's text with. macOS only. Rune's layout of each
# case goes to scripts/coretext-reference.swift, which draws it with CoreText, font smoothing on
# and off; layout.txt records that layout so a change to it marks the sheets stale.
# crates/rune/tests/coretext/ Inter, committed.
# crates/rune/tests/coretext/sf/ San Francisco from this Mac's system font; never committed
# (Apple's font can't be redistributed). Skipped without SFNS.
# crates/rune/tests/coretext/mono/ SF Mono (SFNSMono) the same way. Skipped without it.
set -euo pipefail
cd "$(git rev-parse --show-toplevel)"
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
cargo run -q -p rune --example coretext_compare -- export "$tmp"
for set in inter sf mono; do
[[ -d "$tmp/$set" ]] || continue
for scale in 1 2; do
swift scripts/coretext-reference.swift "$tmp/$set/cases-${scale}x.json" "$tmp/$set" >/dev/null
done
done
cargo run -q -p rune --example coretext_compare -- pack "$tmp"
du -ch crates/rune/tests/coretext/*.png | tail -1
+106
View File
@@ -0,0 +1,106 @@
// CoreText references for `rune::text::pixel_compare`.
// usage: swift scripts/coretext-reference.swift cases-2x.json OUT_DIR
//
// Draws each case's glyphs (Rune's glyph ids at its unquantised pen positions and whole-pixel
// baselines) with CTFontDrawGlyphs into an opaque sRGB bitmap, one sheet per entry of "sheets":
// antialiasing, subpixel positioning and subpixel quantisation on, as macOS draws window text,
// with font smoothing on or off. Inter comes from its files; "system" cases use CoreText's own
// system font (CTFontCreateUIFontForLanguage) at the case's wght and opsz; "mono" cases AppKit's
// monospaced system font (NSFont.monospacedSystemFont, SF Mono) at the case's weight, the
// instance native apps draw code in. Sheets keep the green
// channel. No window or screen access.
import AppKit
import CoreGraphics
import CoreText
import Foundation
import ImageIO
import UniformTypeIdentifiers
let args = CommandLine.arguments
let spec = try JSONSerialization.jsonObject(with: Data(contentsOf: URL(fileURLWithPath: args[1]))) as! [String: Any]
let out = URL(fileURLWithPath: args[2])
let scale = CGFloat(spec["scale"] as! Double)
let width = spec["width"] as! Int, height = spec["height"] as! Int
let paths = spec["fonts"] as! [String: Any]
func fileFont(_ path: String, _ size: CGFloat) -> CTFont {
let url = URL(fileURLWithPath: path) as CFURL
let desc = (CTFontManagerCreateFontDescriptorsFromURL(url) as! [CTFontDescriptor])[0]
return CTFontCreateWithFontDescriptor(desc, size, nil)
}
func systemFont(_ size: CGFloat, weight: Double, opsz: Double) -> CTFont {
let base = CTFontCreateUIFontForLanguage(.system, size, nil)!
// Rune shapes the same file at the same instance; anything else would draw other glyphs.
let url = CTFontCopyAttribute(base, kCTFontURLAttribute) as! URL
let rune = paths["system"] as? String ?? ""
precondition(url.resolvingSymlinksInPath().path == URL(fileURLWithPath: rune).resolvingSymlinksInPath().path,
"CoreText's system font is \(url.path), Rune loaded \(rune)")
let axes = [NSNumber(value: 0x7767_6874): weight, NSNumber(value: 0x6f70_737a): opsz] as [NSNumber: Double]
let desc = CTFontDescriptorCreateWithAttributes([kCTFontVariationAttribute: axes] as CFDictionary)
return CTFontCreateCopyWithAttributes(base, size, nil, desc)
}
func monoFont(_ size: CGFloat, weight: Double) -> CTFont {
let named: [(Double, NSFont.Weight)] = [(100, .ultraLight), (200, .thin), (300, .light), (400, .regular), (500, .medium), (600, .semibold), (700, .bold), (800, .heavy), (900, .black)]
let w = named.min { abs($0.0 - weight) < abs($1.0 - weight) }!.1
let font = NSFont.monospacedSystemFont(ofSize: size, weight: w) as CTFont
// Rune shapes SFNSMono's glyph ids; the system's monospaced font must be that file.
let file = (CTFontManagerCreateFontDescriptorsFromURL(URL(fileURLWithPath: paths["mono"] as! String) as CFURL) as! [CTFontDescriptor])[0]
precondition(CTFontGetGlyphCount(font) == CTFontGetGlyphCount(CTFontCreateWithFontDescriptor(file, size, nil)),
"AppKit's monospaced system font isn't \(paths["mono"] as! String)")
return font
}
func color(_ hex: String) -> CGColor {
let v = Int(hex.dropFirst(), radix: 16)!
return CGColor(srgbRed: CGFloat((v >> 16) & 255) / 255, green: CGFloat((v >> 8) & 255) / 255, blue: CGFloat(v & 255) / 255, alpha: 1)
}
let cases = spec["cases"] as! [[String: Any]]
let fonts: [CTFont] = cases.map { c in
let size = CGFloat(c["size"] as! Double)
switch c["font"] as! String {
case "system": return systemFont(size, weight: c["weight"] as! Double, opsz: c["opsz"] as! Double)
case "mono": return monoFont(size, weight: c["weight"] as! Double)
case let name: return fileFont(paths[name] as! String, size)
}
}
for sheet in spec["sheets"] as! [[String: Any]] {
let smooth = sheet["smooth"] as! Bool
let ctx = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * 4,
space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)!
ctx.setFillColor(color(sheet["bg"] as! String))
ctx.fill(CGRect(x: 0, y: 0, width: width, height: height))
// Top-left origin in points.
ctx.translateBy(x: 0, y: CGFloat(height))
ctx.scaleBy(x: scale, y: -scale)
ctx.setAllowsAntialiasing(true); ctx.setShouldAntialias(true)
ctx.setAllowsFontSmoothing(smooth); ctx.setShouldSmoothFonts(smooth)
ctx.setAllowsFontSubpixelPositioning(true); ctx.setShouldSubpixelPositionFonts(true)
ctx.setAllowsFontSubpixelQuantization(true); ctx.setShouldSubpixelQuantizeFonts(true)
ctx.setFillColor(color(sheet["fg"] as! String))
// The flipped text matrix draws glyphs upright under the y-down CTM; positions are in text
// space, so y is negated.
ctx.textMatrix = CGAffineTransform(scaleX: 1, y: -1)
for (c, f) in zip(cases, fonts) {
let rows = c["glyphs"] as! [[Double]]
var glyphs = rows.map { CGGlyph($0[0]) }
var positions = rows.map { CGPoint(x: CGFloat($0[1]) / scale, y: -CGFloat($0[2]) / scale) }
CTFontDrawGlyphs(f, &glyphs, &positions, glyphs.count, ctx)
}
// Keep the green channel only, as raw bytes: the comparison measures green, and one
// channel keeps the sheets small.
let rgba = ctx.data!.bindMemory(to: UInt8.self, capacity: width * height * 4)
var green = [UInt8](repeating: 0, count: width * height)
for i in 0..<(width * height) { green[i] = rgba[i * 4 + 1] }
let grey = CGImage(width: width, height: height, bitsPerComponent: 8, bitsPerPixel: 8, bytesPerRow: width,
space: CGColorSpaceCreateDeviceGray(), bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.none.rawValue),
provider: CGDataProvider(data: Data(green) as CFData)!, decode: nil, shouldInterpolate: false, intent: .defaultIntent)!
let name = sheet["file"] as! String
let sink = CGImageDestinationCreateWithURL(out.appendingPathComponent(name) as CFURL, UTType.png.identifier as CFString, 1, nil)!
CGImageDestinationAddImage(sink, grey, nil)
precondition(CGImageDestinationFinalize(sink))
print(name)
}
+253
View File
@@ -0,0 +1,253 @@
#!/usr/bin/env python3
"""Buckets the stacks `layout_text_cost --mode sample|heap` records by owner: Taffy, Parley
and its font stack, Rune (split by runtime phase), the app's view code, and the allocator.
scripts/cost-attribution.py symbolize DUMP --exe BINARY > SYMS # where BINARY was built
scripts/cost-attribution.py report DUMP SYMS [--top 12]
`symbolize` runs `atos -i` (run `dsymutil BINARY` first) so inlined frames count. `report` needs
`rustfilt` on PATH to demangle. Exclusive attribution: a sample or allocation belongs to the
innermost frame that isn't the standard library, collections or memmove; a sample in malloc or
free is the allocator's, with its caller's owner noted. See research/31-layout-text-cost.md.
"""
import collections
import re
import subprocess
import sys
TRANSPARENT = {"core", "alloc", "std", "hashbrown", "smallvec", "arrayvec", "memchr", "compiler_builtins",
"unicode_segmentation", "rustc_hash", "foldhash", "ahash", "bytemuck", "indexmap", "tinyvec", "slotmap",
"usize", "isize", "u8", "u16", "u32", "u64", "u128", "i8", "i16", "i32", "i64", "i128", "f32", "f64",
"bool", "char", "str", "deduplicated_symbol", "DYLD", "?"}
OWNED = re.compile(r"\b(taffy|parley|parley_engine|fontique|swash|harfrust|skrifa|rune_kit|rune)::")
ALLOCATOR = re.compile(r"^(_?malloc|_?free|_?realloc|_?calloc|_?posix_memalign|_malloc_zone|_?szone|_?nanov2|_?mfm|_xzm|xzm|_?tiny_|_?small_|_?medium_|_?large_|_?default_zone|_?malloc_)")
MEMFN = re.compile(r"^_?(_platform_)?(memmove|memcpy|memset|bzero|memcmp|strlen|bcmp)")
PARLEY_PARTS = [ # first match on the stack, in this order
("Parley shaping (HarfRust, font tables)", re.compile(r"^<?(harfrust|read_fonts|skrifa|font_types)::|shape::shaper|shape_text")),
("Parley text analysis (ICU segmenter, bidi)", re.compile(r"^<?icu_|analysis::|itemize::|bidi::|analyze_text")),
("Parley layout clone (re-break)", re.compile(r"parley::layout::layout::Layout<.*> as core::clone::Clone>::clone")),
("Parley line breaking and alignment", re.compile(r"line_break|break_all_lines|alignment::align|BreakLines")),
]
PHASES = [ # innermost match wins
("layout", re.compile(r"text_layout::compute_layout")),
("flatten", re.compile(r"runtime::flatten::flatten")),
("view", re.compile(r">::(build_tree|root_view)$|rune::memo::")),
("place", re.compile(r">::place$")),
("final text pass", re.compile(r">::measure_view$")),
("apply", re.compile(r"runtime::Runtime<.*>>::apply$")),
("paint", re.compile(r"runtime::Runtime<.*>>::build$")),
]
def owner_of_crate(crate, name):
if crate == "taffy":
return "Taffy"
if crate == "taffy" or "taffy::" in name and re.search(r"PartialEq|::eq\b", name):
return "Taffy"
if crate in ("parley", "parley_engine", "parley_data", "parley_emoji", "parlance", "harfrust", "skrifa",
"read_fonts", "font_types"):
return "Parley" # split by what the stack is doing, in `parley_part`
if crate == "fontique":
return "Fontique"
if crate in ("swash", "zeno"):
return "Swash raster"
if crate.startswith("icu_") or crate in ("zerovec", "zerotrie", "yoke", "unicode_bidi", "unicode_script"):
return "Parley"
if crate == "rune":
return "Instrumentation (frame-profile clock)" if "frame_profile" in name or "frame::profile" in name else "Rune"
if crate in ("rune_kit", "pulldown_cmark"):
return "Kit and Markdown"
if crate == "layout_text_cost":
return "App (bench views and data)"
if crate in ("rune_motion",):
return "Rune"
return "Other: " + crate
def crate_of(name):
"""The crate a demangled frame belongs to; for `<T as Trait>::f` and drop glue, T's crate."""
n = name
m = re.match(r"^core::ptr::drop_in_place::<(.*)>$", n) or re.match(r"^core::ptr::drop_in_place<(.*)>$", n)
if m:
n = m.group(1)
while n.startswith(("<", "&", "mut ", "dyn ", "[", "(", "*const ", "*mut ")):
for p in ("<", "&", "mut ", "dyn ", "[", "(", "*const ", "*mut "):
if n.startswith(p):
n = n[len(p):]
m = re.match(r"^([A-Za-z_][A-Za-z0-9_]*)", n)
return m.group(1) if m else "?"
def demangle(names):
names = list(names)
out = subprocess.run(["rustfilt"], input="\n".join(names), capture_output=True, text=True, check=True).stdout.split("\n")
return {a: re.sub(r"::h[0-9a-f]{16}$", "", b) for a, b in zip(names, out)}
def symbolize(dump, exe):
addrs = collections.defaultdict(list)
for line in open(dump):
if line.startswith("ADDR "):
_, a, base, sym, image = line.rstrip("\n").split(" ", 4)
if image == exe or image.endswith("/" + exe.split("/")[-1]):
addrs[base].append(a)
for base, group in addrs.items():
lst = "\n".join(f"0x{int(a, 16) - 1:x}" for a in group)
res = subprocess.run(["atos", "-i", "-o", exe, "-l", "0x" + base], input=lst, capture_output=True, text=True, check=True).stdout
blocks = res.split("\n\n")
if len(blocks) < len(group):
sys.exit(f"atos returned {len(blocks)} blocks for {len(group)} addresses")
for a, block in zip(group, blocks):
frames = [re.sub(r" \(in [^)]*\).*$", "", f).strip() for f in block.strip("\n").split("\n") if f.strip()]
print("SYM " + a + " " + "\t".join(frames))
def load(dump, syms):
cases, meta, addr, stacks = {}, [], {}, {}
samples, allocs, live = [], [], []
for line in open(dump):
p = line.rstrip("\n").split(" ")
if p[0] == "CASE":
cases[int(p[1])] = p[2]
elif p[0] == "META":
meta.append(dict(kv.split("=", 1) for kv in p[1:]))
elif p[0] == "ADDR":
addr[p[1]] = [p[3]] # system image: its exported symbol; replaced by SYMS below
elif p[0] == "STACK":
stacks[int(p[1])] = p[2:]
elif p[0] == "SAMPLE":
samples.append((int(p[1]), int(p[2]), int(p[3]), 0))
elif p[0] == "ALLOC":
allocs.append((int(p[1]), int(p[2]), int(p[3]), int(p[4])))
elif p[0] == "LIVE":
live.append((int(p[1]), int(p[2]), int(p[3]), int(p[4])))
mangled = set()
exe_frames = {}
for line in open(syms):
if line.startswith("SYM "):
_, a, rest = line.rstrip("\n").split(" ", 2)
exe_frames[a] = rest.split("\t")
mangled.update(exe_frames[a])
names = demangle(mangled)
for a, frames in exe_frames.items():
addr[a] = [names.get(f, f) for f in frames]
return cases, meta, addr, stacks, samples, allocs, live
def classify(stack, addr, exe_addrs):
"""(owner, phase, allocator caller owner or None, inclusive owner set)."""
frames = [] # (name, in_exe)
for i, a in enumerate(stack):
names = addr.get(a, ["?"])
if i == 1 and len(frames) and a in exe_addrs and addr.get(stack[0]) == names:
continue # the link register pointing into pc's own function
frames.extend((n, a in exe_addrs) for n in names)
owner, alloc_owner, in_alloc, leaf = None, None, False, None
inclusive = set()
for name, in_exe in frames:
if not in_exe:
if owner is None and ALLOCATOR.match(name):
in_alloc = True
continue
if re.search(r"layout_text_cost::probe|__rust_alloc|__rust_dealloc|__rust_realloc|__rdl_|__rg_", name):
continue
crate = crate_of(name)
if crate in TRANSPARENT:
# Dropping or cloning a container of another crate's values is that crate's.
m = re.search(r"drop|clone", name) and OWNED.search(name)
if not m:
continue
crate = m.group(1)
o = owner_of_crate(crate, name)
family = o.split(" ")[0]
if family in ("Taffy", "Parley", "Fontique", "Swash"):
inclusive.add("Parley+fonts" if family in ("Parley", "Fontique", "Swash") else family)
if owner is None:
owner, leaf = o, name
phase = "other"
for name, _ in frames:
hit = next((p for p, rx in PHASES if rx.search(name)), None)
if hit:
phase = hit
break
if owner is None:
owner = "System" if frames and not frames[0][1] else "Unknown"
if owner == "Parley":
owner = next((part for part, rx in PARLEY_PARTS if any(rx.search(n) for n, e in frames if e)), "Parley layout building")
if in_alloc:
alloc_owner, owner = owner, "Allocator"
return owner, phase, alloc_owner, inclusive, leaf or (frames[0][0] if frames else "?")
def report(dump, syms, top):
cases, meta, addr, stacks, samples, allocs, live = load(dump, syms)
exe_addrs = set()
for line in open(syms):
if line.startswith("SYM "):
exe_addrs.add(line.split(" ", 2)[1])
cache = {}
def cls(sid):
if sid not in cache:
cache[sid] = classify(stacks[sid], addr, exe_addrs)
return cache[sid]
for kind, rows in (("SAMPLES", samples), ("ALLOCS", allocs), ("LIVE", live)):
if not rows:
continue
for tag, name in sorted(cases.items()):
mine = [r for r in rows if r[0] == tag]
if not mine:
continue
total = sum(r[2] for r in mine)
total_b = sum(r[3] for r in mine)
by_owner = collections.Counter()
by_owner_b = collections.Counter()
by_phase = collections.Counter()
by_alloc = collections.Counter()
incl = collections.Counter()
funcs = collections.defaultdict(collections.Counter)
funcs_b = collections.defaultdict(collections.Counter)
for _, sid, n, b in mine:
owner, phase, alloc_owner, inclusive, leaf = cls(sid)
by_owner[owner] += n
by_owner_b[owner] += b
by_phase[(owner if not owner.startswith("Rune") else "Rune", phase)] += n
if alloc_owner:
by_alloc[alloc_owner] += n
for o in inclusive:
incl[o] += n
funcs[owner][leaf[:140]] += n
funcs_b[owner][leaf[:140]] += b
print(f"\n== {kind} case={name} total={total}" + (f" bytes={total_b}" if kind != "SAMPLES" else ""))
for o, n in by_owner.most_common():
extra = f" bytes {by_owner_b[o]:>12} {100 * by_owner_b[o] / max(total_b, 1):5.1f}%" if kind != "SAMPLES" else ""
print(f" {o:<34} {n:>9} {100 * n / total:5.1f}%{extra}")
if kind == "SAMPLES":
print(" -- inclusive (any frame on the stack)")
for o, n in incl.most_common():
print(f" {o:<31} {100 * n / total:5.1f}%")
print(" -- by runtime phase (Rune = Rune's own code)")
for (o, ph), n in sorted(by_phase.items(), key=lambda kv: -kv[1])[:24]:
print(f" {o:<31} {ph:<16} {100 * n / total:5.1f}%")
if by_alloc:
print(" -- allocator time by caller")
for o, n in by_alloc.most_common():
print(f" {o:<31} {100 * n / total:5.1f}%")
for o, _ in by_owner.most_common(6):
print(f" -- top in {o}")
for f, n in funcs[o].most_common(top):
extra = f" bytes {100 * funcs_b[o][f] / max(total_b, 1):5.1f}%" if kind != "SAMPLES" else ""
print(f" {100 * n / total:5.1f}%{extra} {f}")
for m in meta:
print("META", " ".join(f"{k}={v}" for k, v in m.items()))
if __name__ == "__main__":
a = sys.argv[1:]
if a and a[0] == "symbolize":
symbolize(a[1], a[a.index("--exe") + 1])
elif a and a[0] == "report":
report(a[1], a[2], int(a[a.index("--top") + 1]) if "--top" in a else 12)
else:
sys.exit(__doc__)
+2
View File
@@ -0,0 +1,2 @@
# <path> <ceiling>: non-test line ceilings for files above 1500. Ceilings only go down.
# Refresh with scripts/file-size.sh --update-exceptions.
+141
View File
@@ -0,0 +1,141 @@
#!/usr/bin/env bash
# Checks Rust file sizes. Counts non-test lines per tracked .rs file under crates/ and examples/
# (inline #[cfg(test)] items are excluded; test-only files are measured separately).
# warn > 800 non-test lines error > 1500 non-test lines unless listed in
# warn > 1000 lines in a test file or inline test module scripts/file-size-exceptions.txt ("<path> <ceiling>")
# Also runs scripts/folder-shape.sh (prefix families and folder breadth); its errors and warnings are
# added to the summary line, and --update-exceptions refreshes both exception lists.
# Usage: scripts/file-size.sh [--warn-only] [--update-exceptions [--allow-raise]]
set -euo pipefail
cd "$(git rev-parse --show-toplevel)"
SOFT=800 HARD=1500 TESTCAP=1000
EXC=scripts/file-size-exceptions.txt
warn_only=0 update=0 raise=0
for a in "$@"; do
case "$a" in
--warn-only) warn_only=1 ;;
--update-exceptions) update=1 ;;
--allow-raise) raise=1 ;;
*) echo "unknown option: $a" >&2; exit 2 ;;
esac
done
measure() {
git ls-files -z 'crates/*.rs' 'examples/*.rs' | xargs -0 awk '
function reset() { prod = 0; test = 0; st = 0; depth = 0; maxtest = 0; cur = 0 }
function braces(s, t, o, c) {
gsub(/\\./, "", s); gsub(/"[^"]*"/, "", s); gsub(/\047.\047/, "", s)
sub(/\/\/.*/, "", s)
t = s; o = gsub(/\{/, "", t); t = s; c = gsub(/\}/, "", t)
return o - c
}
function flush() {
if (name != "") {
if (cur > maxtest) maxtest = cur
printf "%s %d %d %d\n", name, prod, test, maxtest
}
}
FNR == 1 { flush(); reset(); name = FILENAME
testfile = (FILENAME ~ /(^|\/)tests?\.rs$/ || FILENAME ~ /_tests\.rs$/ || FILENAME ~ /(^|\/)tests\//) }
{
if (testfile) { test++; cur++; next }
if (st == 0) {
if ($0 ~ /^[ \t]*#\[cfg\(test\)\]/) { st = 1; cur = 1; test++; next }
prod++; next
}
test++; cur++
if (st == 1) { # attribute seen, find the item head
if ($0 ~ /^[ \t]*#\[/) next
d = braces($0)
if (d > 0 || $0 ~ /\{/) { depth = d; st = (depth > 0) ? 2 : 0 }
else if ($0 ~ /;[ \t]*$/) st = 0
if (st == 0) { if (cur > maxtest) maxtest = cur; cur = 0 }
next
}
depth += braces($0)
if (depth <= 0) { st = 0; if (cur > maxtest) maxtest = cur; cur = 0 }
}
END { flush() }'
}
rows=$(measure)
ceil_of() { [ -f "$EXC" ] && awk -v p="$1" '$1 == p { print $2; exit }' "$EXC" || true; }
errors=0 warns=0 oversoft=0 overhard=0
out=$(mktemp); trap 'rm -f "$out"' EXIT
ann() { [ "${GITHUB_ACTIONS:-}" = true ] && echo "::$1 file=$2::$3" || true; }
while read -r p prod test maxtest; do
if [ "$prod" -eq 0 ] && [ "$test" -gt 0 ] && [ "$maxtest" -eq "$test" ] && [ "$test" -gt "$TESTCAP" ]; then
# test-only file
warns=$((warns + 1))
printf '%6d %-6s %s\n' "$test" "tests" "$p" >> "$out"
ann warning "$p" "test file has $test lines (limit $TESTCAP)"
continue
fi
if [ "$maxtest" -gt "$TESTCAP" ]; then
warns=$((warns + 1))
printf '%6d %-6s %s\n' "$maxtest" "tests" "$p" >> "$out"
ann warning "$p" "inline test module has $maxtest lines (limit $TESTCAP)"
fi
[ "$prod" -gt "$SOFT" ] || continue
oversoft=$((oversoft + 1))
if [ "$prod" -gt "$HARD" ]; then
overhard=$((overhard + 1))
limit=$(ceil_of "$p"); limit=${limit:-$HARD}
if [ "$prod" -gt "$limit" ]; then
errors=$((errors + 1))
printf '%6d %-6s %s (limit %d)\n' "$prod" "ERROR" "$p" "$limit" >> "$out"
ann error "$p" "$prod non-test lines, limit $limit; split a module out before adding more"
else
warns=$((warns + 1))
printf '%6d %-6s %s (exception, ceiling %d)\n' "$prod" "warn" "$p" "$limit" >> "$out"
ann warning "$p" "$prod non-test lines (exception ceiling $limit, soft limit $SOFT)"
fi
else
warns=$((warns + 1))
printf '%6d %-6s %s\n' "$prod" "warn" "$p" >> "$out"
ann warning "$p" "$prod non-test lines (soft limit $SOFT)"
fi
done <<< "$rows"
sort -rn "$out"
shape_args=()
[ "$update" -eq 1 ] && shape_args+=(--update-exceptions)
[ "$raise" -eq 1 ] && shape_args+=(--allow-raise)
shape_out=$(bash scripts/folder-shape.sh ${shape_args[@]+"${shape_args[@]}"} --warn-only)
if [ "$update" -eq 0 ]; then
printf '%s\n' "$shape_out"
shape_sum=$(printf '%s\n' "$shape_out" | tail -1)
errors=$((errors + $(sed -n 's/.*errors: \([0-9]*\),.*/\1/p' <<< "$shape_sum")))
warns=$((warns + $(sed -n 's/.*warnings: \([0-9]*\)$/\1/p' <<< "$shape_sum")))
else
printf '%s\n' "$shape_out"
fi
echo "over $SOFT: $oversoft, over $HARD: $overhard, errors: $errors, warnings: $warns"
if [ "$update" -eq 1 ]; then
tmp=$(mktemp)
{
echo "# <path> <ceiling>: non-test line ceilings for files above $HARD. Ceilings only go down."
echo "# Refresh with scripts/file-size.sh --update-exceptions."
while read -r p prod _ _; do
[ "$prod" -gt "$HARD" ] || continue
old=$(ceil_of "$p")
if [ -z "$old" ]; then
if [ "$raise" -eq 1 ]; then echo "$p $prod"; else echo "not listing new oversized file $p ($prod); use --allow-raise" >&2; fi
elif [ "$prod" -gt "$old" ] && [ "$raise" -eq 0 ]; then
echo "$p $old"
else
echo "$p $prod"
fi
done <<< "$rows" | sort
} > "$tmp"
mv "$tmp" "$EXC"
echo "wrote $EXC ($(grep -vc '^#' "$EXC") entries)"
exit 0
fi
[ "$warn_only" -eq 1 ] && exit 0
[ "$errors" -eq 0 ]
+2
View File
@@ -0,0 +1,2 @@
# <key> <ceiling>: existing folder-shape violations (see scripts/folder-shape.sh). Ceilings only go down.
# Refresh with scripts/folder-shape.sh --update-exceptions.
+182
View File
@@ -0,0 +1,182 @@
#!/usr/bin/env bash
# Checks folder shape for tracked source files under crates/ and examples/.
# prefix family x.rs or x/ plus 2+ x_*.rs siblings, or 3+ x_*.rs alone: error, "move into x/"
# folder breadth > 40 non-test source files in one folder: warn; > 60: error
# Files directly in examples/, benches/ and bin/ are skipped (each is its own program).
# Test files (*_tests.rs, *_test.rs, tests.rs, *.test.ts, ...) are not counted. The prefix is the stem
# up to the first "_" or "-". Existing violations are listed in scripts/folder-shape-exceptions.txt
# ("<key> [ceiling]", key is "<dir>/<prefix>_*" or "<dir>/"; the ceiling is optional); ceilings only go down.
# Usage: scripts/folder-shape.sh [--warn-only] [--update-exceptions [--allow-raise]]
set -euo pipefail
cd "$(git rev-parse --show-toplevel)"
WARN=40 HARD=60 FAM=3
EXC=scripts/folder-shape-exceptions.txt
warn_only=0 update=0 raise=0
for a in "$@"; do
case "$a" in
--warn-only) warn_only=1 ;;
--update-exceptions) update=1 ;;
--allow-raise) raise=1 ;;
*) echo "unknown option: $a" >&2; exit 1 ;;
esac
done
found=$(
git ls-files crates examples | awk -v warn="$WARN" -v fam="$FAM" '
BEGIN {
src[".rs"] = 1; src[".ts"] = 1; src[".tsx"] = 1; src[".swift"] = 1
prog["examples"] = 1; prog["benches"] = 1; prog["bin"] = 1
}
{
sub(/\r$/, "")
if ($0 == "") next
slash = 0
for (i = length($0); i >= 1; i--) {
if (substr($0, i, 1) == "/") { slash = i; break }
}
if (slash > 0) {
d = substr($0, 1, slash - 1)
name = substr($0, slash + 1)
} else {
d = ""
name = $0
}
nparts = split(d, parts, "/")
if (nparts >= 3) {
parent = parts[1] "/" parts[2]
for (i = 3; i <= nparts; i++) {
has_sub[parent SUBSEP parts[i]] = 1
dirs[parent] = 1
parent = parent "/" parts[i]
}
}
if (nparts > 0 && (parts[nparts] in prog)) next
dot = 0
for (i = length(name); i >= 1; i--) {
if (substr(name, i, 1) == ".") { dot = i; break }
}
if (dot > 1 && substr(name, 1, dot - 1) !~ /^\.+$/) {
stem = substr(name, 1, dot - 1)
ext = substr(name, dot)
} else {
stem = name
ext = ""
}
if (!(ext in src)) next
if (stem ~ /(^|[_.-])tests?$/) next
if (index("/" d "/", "/tests/") > 0) next
dirs[d] = 1
dir_count[d]++
has_stem[d SUBSEP stem] = 1
if (match(stem, /^[^_-]+[_-]/)) {
p = substr(stem, 1, RLENGTH - 1)
if (!((d SUBSEP p) in fam_count)) {
fam_n[d]++
fam_list[d SUBSEP fam_n[d]] = p
}
fam_count[d SUBSEP p]++
}
}
END {
for (d in dirs) {
m = fam_n[d] + 0
for (i = 1; i <= m; i++) {
p = fam_list[d SUBSEP i]
base = ((d SUBSEP p) in has_stem) || ((d SUBSEP p) in has_sub)
limit = base ? 2 : fam
cnt = fam_count[d SUBSEP p]
if (cnt >= limit) {
printf "%s/%s_*\t%d\tmove into %s/\n", d, p, cnt, p
}
}
if (dir_count[d] + 0 > warn) {
printf "%s/\t%d\tgroup into capability subfolders\n", d, dir_count[d]
}
}
}
' | LC_ALL=C sort -t $'\t' -k1,1
)
ceil_of() {
[ -f "$EXC" ] || return 0
awk -v k="$1" '
{ sub(/\r$/, "") }
/^#/ || NF == 0 { next }
$1 == k { val = (NF > 1 ? $2 : 1000000000); seen = 1 }
END { if (seen) print val }
' "$EXC"
}
if [ "$update" -eq 1 ]; then
tmp=$(mktemp)
trap 'rm -f "$tmp"' EXIT
{
echo "# <key> <ceiling>: existing folder-shape violations (see scripts/folder-shape.sh). Ceilings only go down."
echo "# Refresh with scripts/folder-shape.sh --update-exceptions."
if [ -n "$found" ]; then
while IFS=$'\t' read -r k n _; do
case "$k" in
*_\*) ;;
*) [ "$n" -gt "$HARD" ] || continue ;;
esac
old=$(ceil_of "$k")
if [ -z "$old" ]; then
if [ "$raise" -eq 1 ]; then
echo "$k $n"
else
echo "not listing new violation $k ($n); use --allow-raise" >&2
fi
elif [ "$n" -le "$old" ] || [ "$raise" -eq 1 ]; then
echo "$k $n"
else
echo "$k $old"
fi
done <<< "$found"
fi
} > "$tmp"
mv "$tmp" "$EXC"
trap - EXIT
entries=$(awk '/^#/ || NF == 0 { next } { c++ } END { print c + 0 }' "$EXC")
echo "wrote $EXC ($entries entries)"
exit 0
fi
errors=0 warns=0 families=0 over_warn=0
rows=$(mktemp)
trap 'rm -f "$rows"' EXIT
if [ -n "$found" ]; then
while IFS=$'\t' read -r k n hint; do
case "$k" in
*_\*) fam=1; families=$((families + 1)) ;;
*) fam=0; over_warn=$((over_warn + 1)) ;;
esac
if [ "$fam" -eq 1 ] || [ "$n" -gt "$HARD" ]; then
limit=$(ceil_of "$k")
if [ -n "$limit" ] && [ "$n" -le "$limit" ]; then
warns=$((warns + 1))
printf '%6d warn %s (%s; exception, ceiling %d)\n' "$n" "$k" "$hint" "$limit" >> "$rows"
else
errors=$((errors + 1))
if [ -n "$limit" ]; then
printf '%6d ERROR %s (%s; limit %d)\n' "$n" "$k" "$hint" "$limit" >> "$rows"
else
printf '%6d ERROR %s (%s)\n' "$n" "$k" "$hint" >> "$rows"
fi
if [ "${GITHUB_ACTIONS:-}" = true ]; then
printf '::error file=%s::%d files: %s\n' "$k" "$n" "$hint"
fi
fi
else
warns=$((warns + 1))
printf '%6d warn %s (%s, soft limit %d)\n' "$n" "$k" "$hint" "$WARN" >> "$rows"
fi
done <<< "$found"
fi
if [ -s "$rows" ]; then
cat "$rows"
fi
echo "folder shape: families: $families, folders over $WARN: $over_warn, errors: $errors, warnings: $warns"
[ "$warn_only" -eq 1 ] || [ "$errors" -eq 0 ]
+1
View File
@@ -0,0 +1 @@
[{"shortcut":"cmd+ctrl+alt+shift+k"}]
+147
View File
@@ -0,0 +1,147 @@
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.11"
# dependencies = ["pillow>=10", "numpy>=1.26"]
# ///
"""Diffs rune-kit's gallery against @opencode/ui's Storybook, story by story.
usage:
OPENCODE=<opencode checkout> scripts/kit-diff.py [--out perf/kit-diff] [--only button,switch]
[--schemes light,dark] [--no-build]
Needs: `bun install` and `bun run --cwd packages/storybook build` in the OpenCode checkout
(Playwright's Chromium comes from that checkout), and a GPU or lavapipe for Rune
(VK_ICD_FILENAMES=/usr/share/vulkan/icd.d/lvp_icd.json on a headless Linux box).
For every story in STORIES and each scheme it renders the web story in headless Chromium at
2x (viewport fitted to the story), renders the gallery scene of the same id at the same size,
and writes web.png, rune.png, diff.png (amplified |web - rune|) and side.png (web | rune |
diff) per story, plus report.json and report.md with two numbers per story:
similarity 100 * (1 - mean |web - rune| / 255) over RGB; 100 is identical
off % of pixels whose largest channel differs by more than 24/255 (visible)
"""
import argparse
import json
import os
import subprocess
import sys
from pathlib import Path
import numpy as np
from PIL import Image
ROOT = Path(__file__).resolve().parent.parent
# Every gallery scene is diffed against the Storybook story of the same id. Per-story options:
# width (viewport points, default 720) and actions run before the web shot (click/hover/focus a
# selector) to reach the state the Rune scene starts in.
MENU = {"actions": [{"click": "#storybook-root button"}]}
OPTIONS: dict[str, dict] = {
"ui-dialog--basic": {"height": 480},
"ui-menu--basic": MENU,
"ui-menu--rich": MENU,
"ui-menu--with-checkbox": MENU,
"ui-menu--with-radio": MENU,
"ui-menu--with-submenu": MENU,
"ui-select--playground": {"actions": [{"click": "[data-component=select-v2]"}]},
"ui-select--grouped": {"actions": [{"click": "[data-component=select-v2]"}]},
"components-hover-card--basic": {"actions": [{"hover": "[data-slot=hover-card-trigger]", "wait": 1200}]},
"ui-tooltip--simple": {"actions": [{"hover": "[data-component=tooltip-v2-trigger]", "wait": 900}]},
"ui-tooltip--with-keybind": {"actions": [{"hover": "[data-component=tooltip-v2-trigger]", "wait": 900}]},
"ui-tooltip--path": {"actions": [{"hover": "[data-component=tooltip-v2-trigger]", "wait": 900}]},
"ui-tooltip--title-description": {"actions": [{"hover": "[data-component=tooltip-v2-trigger]", "wait": 900}]},
"ui-toast--all-examples": {"actions": [{"click": "#storybook-root button", "wait": 900}], "height": 480},
}
def sh(cmd, **kw):
return subprocess.run(cmd, check=True, **kw)
def load(p: Path) -> np.ndarray:
return np.asarray(Image.open(p).convert("RGB")).astype(np.int16)
def compare(web: Path, rune: Path, out: Path) -> dict:
a, b = load(web), load(rune)
h, w = min(a.shape[0], b.shape[0]), min(a.shape[1], b.shape[1])
a, b = a[:h, :w], b[:h, :w]
d = np.abs(a - b)
similarity = 100.0 * (1.0 - d.mean() / 255.0)
off = 100.0 * float((d.max(axis=2) > 24).mean())
heat = np.clip(d.max(axis=2) * 4, 0, 255).astype(np.uint8)
diff = np.stack([heat, np.zeros_like(heat), np.zeros_like(heat)], axis=2)
base = (0.25 * a.mean(axis=2, keepdims=True)).astype(np.uint8)
diff = np.maximum(diff, np.repeat(base, 3, axis=2))
Image.fromarray(diff).save(out / "diff.png")
gap = 8
side = np.full((h, w * 3 + gap * 2, 3), 128, np.uint8)
side[:, :w] = a.astype(np.uint8)
side[:, w + gap : 2 * w + gap] = b.astype(np.uint8)
side[:, 2 * (w + gap) :] = diff
Image.fromarray(side).save(out / "side.png")
return {"similarity": round(similarity, 3), "off": round(off, 3)}
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--out", default=str(ROOT / "perf/kit-diff"))
ap.add_argument("--only", default="")
ap.add_argument("--schemes", default="light,dark")
ap.add_argument("--no-build", action="store_true")
ap.add_argument("--scale", type=float, default=2.0)
args = ap.parse_args()
out = Path(args.out)
out.mkdir(parents=True, exist_ok=True)
os.environ.setdefault("OPENCODE", str(ROOT.parent / "opencode"))
if not args.no_build:
sh(["cargo", "build", "--release", "-q", "-p", "kit-gallery"], cwd=ROOT)
gallery = ROOT / "target/release/kit-gallery"
scenes = set(subprocess.run([gallery, "--list-scenes"], capture_output=True, text=True, check=True).stdout.split())
only = [s for s in args.only.split(",") if s]
ids = [i for i in sorted(scenes) if "--" in i and (not only or any(o in i for o in only))]
schemes = args.schemes.split(",")
jobs = []
for i in ids:
for sc in schemes:
d = out / i / sc
d.mkdir(parents=True, exist_ok=True)
o = OPTIONS.get(i, {})
jobs.append({"id": i, "scheme": sc, "width": o.get("width", 720), "out": str(d / "web.png"),
"actions": o.get("actions", []), "scale": args.scale, **({"height": o["height"]} if "height" in o else {})})
shots = subprocess.run(["node", str(ROOT / "scripts/kit/shots.mjs")], input=json.dumps(jobs), capture_output=True,
text=True, cwd=ROOT)
if shots.returncode != 0:
sys.exit(shots.stderr)
sizes = {(r["id"], r["scheme"]): (r["width"], r["height"]) for r in json.loads(shots.stdout)}
env = dict(os.environ)
if sys.platform.startswith("linux") and Path("/usr/share/vulkan/icd.d/lvp_icd.json").exists():
env.setdefault("VK_ICD_FILENAMES", "/usr/share/vulkan/icd.d/lvp_icd.json")
report = []
for i in ids:
for sc in schemes:
d = out / i / sc
w, h = sizes[(i, sc)]
subprocess.run([gallery, "--scene", i, "--snap", d / "rune.png", "--theme", sc, "--size", f"{w}x{h}",
"--scale", str(args.scale)], check=True, env=env, capture_output=True)
r = {"id": i, "scheme": sc, "size": [w, h], **compare(d / "web.png", d / "rune.png", d)}
report.append(r)
print(f"{i:52} {sc:5} similarity {r['similarity']:7.3f} off {r['off']:6.2f}%")
(out / "report.json").write_text(json.dumps(report, indent=1))
lines = ["| story | scheme | similarity | off (% px) |", "|---|---|---:|---:|"]
lines += [f"| {r['id']} | {r['scheme']} | {r['similarity']:.2f} | {r['off']:.2f} |" for r in report]
mean = sum(r["similarity"] for r in report) / max(len(report), 1)
lines.append(f"\nmean similarity {mean:.2f} over {len(report)} renders")
(out / "report.md").write_text("\n".join(lines) + "\n")
print(f"mean similarity {mean:.3f} over {len(report)} renders -> {out}/report.md")
if __name__ == "__main__":
main()
+28
View File
@@ -0,0 +1,28 @@
// Prints the layout rects (points) of a story's slotted elements, for matching Rune layouts.
// usage: node scripts/kit/rects.mjs <story-id> [light|dark] [click-selector]
import { openStory, playwright, serve } from "./storybook.mjs"
const [id, scheme = "light", click] = process.argv.slice(2)
const server = await serve()
const browser = await playwright().chromium.launch()
const page = await browser.newPage({ viewport: { width: 720, height: 900 } })
await openStory(page, server.url, id, scheme)
if (click) {
await page.locator(click).first().click()
await page.waitForTimeout(500)
}
const rows = await page.evaluate(() => {
const out = []
for (const el of document.querySelectorAll("[data-component], [data-slot], [role], button, input, label, span, svg")) {
const r = el.getBoundingClientRect()
if (!r.width || !r.height) continue
const cs = getComputedStyle(el)
const name = el.getAttribute("data-component") ?? el.getAttribute("data-slot") ?? el.getAttribute("role") ?? el.tagName.toLowerCase()
const t = el.children.length === 0 ? (el.textContent ?? "").trim().slice(0, 24) : ""
out.push(`${name.padEnd(32)} ${[r.x, r.y, r.width, r.height].map((v) => v.toFixed(2).padStart(8)).join(" ")} ${cs.fontSize}/${cs.lineHeight} ${cs.fontWeight} ${t}`)
}
return out
})
console.log(rows.join("\n"))
await browser.close()
server.close()
+61
View File
@@ -0,0 +1,61 @@
// Renders Storybook stories to PNG in headless Chromium, for scripts/kit-diff.py.
//
// stdin: JSON [{ id, scheme, width, height?, out, actions? }]
// actions: [{ click | hover | focus: selector, nth?: n }] run before the shot.
// Without `height`, the viewport is fitted to the story (frame padding included).
// stdout: JSON [{ id, scheme, width, height }]
import fs from "node:fs"
import { openStory, playwright, serve } from "./storybook.mjs"
const jobs = JSON.parse(fs.readFileSync(0, "utf8"))
const server = await serve()
const browser = await playwright().chromium.launch()
const results = []
for (const job of jobs) {
const page = await browser.newPage({ viewport: { width: job.width, height: 1600 }, deviceScaleFactor: job.scale ?? 2 })
await page.emulateMedia({ reducedMotion: "reduce" })
await openStory(page, server.url, job.id, job.scheme)
for (const a of job.actions ?? []) {
const [kind, selector] = Object.entries(a).find(([k]) => ["click", "hover", "focus", "press"].includes(k))
const loc = page.locator(selector).nth(a.nth ?? 0)
try {
if (kind === "click") await loc.click({ timeout: 5000 })
if (kind === "hover") await loc.hover({ timeout: 5000 })
if (kind === "focus") await loc.focus({ timeout: 5000 })
if (kind === "press") await page.keyboard.press(selector)
} catch (e) {
process.stderr.write(`${job.id}: ${kind} ${selector} failed: ${e.message.split("\n")[0]}\n`)
}
await page.waitForTimeout(a.wait ?? 400)
}
// Pause every animation at its end so overlays are fully in.
await page.evaluate(() => {
for (const a of document.getAnimations()) {
try {
const t = a.effect?.getComputedTiming()
if (t && Number.isFinite(t.endTime)) a.currentTime = t.endTime
else a.currentTime = 0
a.pause()
} catch {}
}
})
const height =
job.height ??
(await page.evaluate(() => {
const frame = document.querySelector("#storybook-root > div")
let bottom = 0
for (const el of frame?.children ?? []) bottom = Math.max(bottom, el.getBoundingClientRect().bottom)
for (const el of document.querySelectorAll("[data-popper-positioner], [role=dialog], [role=tooltip], .toast-v2-region"))
bottom = Math.max(bottom, el.getBoundingClientRect().bottom)
return Math.ceil(bottom + 24)
}))
await page.setViewportSize({ width: job.width, height })
await page.waitForTimeout(100)
await page.screenshot({ path: job.out })
results.push({ id: job.id, scheme: job.scheme, width: job.width, height })
await page.close()
}
await browser.close()
server.close()
process.stdout.write(JSON.stringify(results))
+62
View File
@@ -0,0 +1,62 @@
// Shared helpers for the kit scripts: serve a static Storybook build and open stories in
// headless Chromium through the OpenCode checkout's own Playwright.
//
// OPENCODE (env) points at an opencode checkout with `bun install` done and
// `packages/storybook/storybook-static` built (`bun run --cwd packages/storybook build`).
import fs from "node:fs"
import http from "node:http"
import path from "node:path"
import { createRequire } from "node:module"
export const opencode = process.env.OPENCODE ?? path.resolve(import.meta.dirname, "../../../opencode")
const storybookPkg = path.join(opencode, "packages/storybook/package.json")
export const staticDir = process.env.STORYBOOK_STATIC ?? path.join(opencode, "packages/storybook/storybook-static")
const types = {
".html": "text/html",
".js": "text/javascript",
".mjs": "text/javascript",
".css": "text/css",
".json": "application/json",
".svg": "image/svg+xml",
".woff2": "font/woff2",
".woff": "font/woff",
".ttf": "font/ttf",
".png": "image/png",
}
export async function serve() {
if (!fs.existsSync(path.join(staticDir, "iframe.html"))) {
throw new Error(`no Storybook build at ${staticDir}; run \`bun run --cwd packages/storybook build\` in ${opencode}`)
}
const server = http.createServer((req, res) => {
const url = decodeURIComponent(req.url.split("?")[0])
const file = path.join(staticDir, url === "/" ? "index.html" : url)
if (!file.startsWith(staticDir) || !fs.existsSync(file) || fs.statSync(file).isDirectory()) {
res.statusCode = 404
return res.end()
}
res.setHeader("content-type", types[path.extname(file)] ?? "application/octet-stream")
fs.createReadStream(file).pipe(res)
})
await new Promise((ok) => server.listen(0, "127.0.0.1", ok))
return { url: `http://127.0.0.1:${server.address().port}`, close: () => server.close() }
}
export function playwright() {
return createRequire(storybookPkg)("@playwright/test")
}
/** Open a story with the given scheme; the decorator's padding stays, Storybook's own body padding goes. */
export async function openStory(page, base, id, scheme) {
await page.goto(`${base}/iframe.html?id=${id}&viewMode=story&globals=theme:${scheme}`)
await page.waitForSelector("#storybook-root > *", { timeout: 15000 })
await page.addStyleTag({
content: `body.sb-main-padded, body { padding: 0 !important; margin: 0 !important; }
html, body { background: var(--background-base) !important; }
*, *::before, *::after { transition: none !important; animation-play-state: paused !important; caret-color: transparent !important; }`,
})
await page.evaluate(() => document.fonts.ready)
await page.waitForTimeout(250)
}
+6
View File
@@ -0,0 +1,6 @@
#!/usr/bin/env bash
# Stage, sign, atomically exchange and check the replacement's Rune ready receipt.
# --help lists the existing bundle flags; --no-rune-ready supports older binaries.
# All installers use flock on Applications/.NAME.app.install.lock (see mac-app.md).
set -euo pipefail
exec python3 "$(dirname "$0")/mac_app_install.py" "$@"
+52
View File
@@ -0,0 +1,52 @@
# Installing a Rune app
`scripts/mac-app --name Demo --id com.example.demo --exe demo --bin target/release/demo`
stages and signs a bundle beside its destination, asks the running app to quit,
atomically exchanges the bundles, then launches the replacement. `--icon`,
`--scheme`, `--mic`, `--wait-idle SECONDS`, `MAC_APP_SIGN`, and arguments after `--`
work as before. Launches are normal, not occluded: an occluded first frame can
prevent Rune from reaching readiness.
Use `--bundle path/to/Demo.app` instead of `--bin` to install an already signed
bundle. `--only-relaunch` updates a closed app without opening it. When no explicit
app arguments are supplied, running instances' exact arguments are preserved.
`--stamp PATH --revision REV` publishes a revision stamp under the install lock
only after success. These options also serve remote updaters; transfer each bundle
to its own directory and invoke this installer on the destination machine.
The replacement must write its Rune ready receipt within 15 seconds. Each launch
gets a unique `RUNE_READY_DIR`; the receipt must identify its PID and bundle ID.
`--no-rune-ready` is only for binaries built before Rune's readiness protocol.
Failed launch or readiness restores the previous bundle with another atomic
exchange and reopens it. If the failed app refuses Cocoa quit, the installed
bundle is still restored, but no overlapping copy is opened. Desktop apps are
never force-quit.
## Shared install protocol
Rune and HiveMind land use the same protocol:
1. Resolve the target path, then take an exclusive POSIX `flock` on the persistent
sibling `.<bundle filename>.install.lock`. Never unlink the lock file.
2. Hold the lock through staging, idle/busy waits, process capture, swap, readiness,
rollback and cleanup. A caller delegating to this installer must not hold the
same lock in its parent process.
3. Stage in a unique sibling `.<bundle filename>.install-*` directory. Existing
bundles are exchanged using `renamex_np(RENAME_SWAP)` on macOS. There is no
remove-then-rename fallback. First installs use a single rename.
4. The staging path now contains the previous bundle. Delete it only after the
replacement is ready or rollback has restored the previous bundle.
An uncatchable interruption leaves a complete bundle at the live path and the
other complete bundle at the unique staging path. Recovery failures retain that
path and report it. Never sweep these retained backups as part of another install.
The lock is released by the kernel when its owner exits.
During rollout, let installers using the old protocol finish before admitting
new installs. An already-running old installer cannot be made to honor a new lock.
Regression tests use fake bundles only:
```sh
python3 scripts/mac_app_install_tests.py
```
+91
View File
@@ -0,0 +1,91 @@
"""Atomic bundle transaction. Lock protocol is also used by HiveMind land."""
import ctypes
import fcntl
import os
from pathlib import Path
import shutil
import signal
import sys
import tempfile
def exchange(a, b):
libc = ctypes.CDLL(None, use_errno=True)
if sys.platform == "darwin":
rename = libc.renamex_np
rename.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_uint]
result = rename(os.fsencode(a), os.fsencode(b), 2) # RENAME_SWAP
else:
rename = libc.renameat2
rename.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p, ctypes.c_uint]
result = rename(-100, os.fsencode(a), -100, os.fsencode(b), 2)
if result:
error = ctypes.get_errno()
raise OSError(error, os.strerror(error), str(a))
class Bundle:
def __init__(self, live):
self.live = Path(live).resolve()
self.stage = None
self.published = False
self.committed = False
def __enter__(self):
self.live.parent.mkdir(parents=True, exist_ok=True)
# Persistent inode, POSIX flock, same filename as HiveMind. Never unlink it.
self.lock = (self.live.parent / f".{self.live.name}.install.lock").open("a+b")
try:
fcntl.flock(self.lock, fcntl.LOCK_EX)
self.had_live = self.live.exists()
self.stage = Path(tempfile.mkdtemp(prefix=f".{self.live.name}.install-", dir=self.live.parent))
except BaseException:
self.lock.close()
raise
return self
def publish(self):
# Deliver catchable termination only after the in-memory state matches the
# syscall. SIGKILL still leaves both complete bundles on disk.
previous = signal.pthread_sigmask(signal.SIG_BLOCK, {signal.SIGINT, signal.SIGTERM})
try:
if self.had_live:
exchange(self.stage, self.live)
else:
os.rename(self.stage, self.live)
self.published = True
finally:
signal.pthread_sigmask(signal.SIG_SETMASK, previous)
def restore(self):
if not self.published:
return
if not self.had_live:
raise RuntimeError("no previous bundle to restore")
exchange(self.stage, self.live)
self.published = False
def replace(self, stop, launch, stop_replacement):
"""Keep the old bundle until launch and readiness succeed."""
stop()
try:
self.publish()
launch(False)
except BaseException:
try:
stop_replacement()
finally:
# Restore the installed path even if the failed app refuses to quit.
self.restore()
launch(True)
raise
self.committed = True
def __exit__(self, *_):
try:
if self.published and not self.committed:
print(f"mac-app: previous bundle retained at {self.stage}", file=sys.stderr)
elif self.stage and self.stage.exists():
shutil.rmtree(self.stage)
finally:
self.lock.close()
+231
View File
@@ -0,0 +1,231 @@
"""Build, atomically install and check a Rune app before discarding its old bundle."""
import argparse
import ctypes
import json
import os
from pathlib import Path
import plistlib
import re
import shutil
import signal
import subprocess
import sys
import tempfile
import time
from mac_app_bundle import Bundle
def command(*args, check=True):
return subprocess.run(args, check=check, capture_output=True, text=True, timeout=10)
def running(exe):
result = {}
for line in command("ps", "-axo", "pid=,lstart=,command=").stdout.splitlines():
parts = line.split(None, 6)
if len(parts) == 7 and (parts[6] == str(exe) or parts[6].startswith(str(exe) + " ")):
result[int(parts[0])] = tuple(parts[1:6])
return result
def parse_argv(data):
argc = int.from_bytes(data[:4], sys.byteorder, signed=True)
if argc <= 0:
raise ValueError("invalid process argument count")
rest = data[4:].split(b"\0", 1)[1].lstrip(b"\0")
args = rest.split(b"\0")[:argc]
if len(args) != argc:
raise ValueError("truncated process arguments")
return [os.fsdecode(arg) for arg in args[1:]]
def process_args(pid):
libc = ctypes.CDLL(None, use_errno=True)
mib = (ctypes.c_int * 3)(1, 49, pid) # CTL_KERN, KERN_PROCARGS2
data = ctypes.create_string_buffer(1024 * 1024)
size = ctypes.c_size_t(len(data))
if libc.sysctl(mib, 3, data, ctypes.byref(size), None, 0):
raise OSError(ctypes.get_errno(), f"cannot preserve app pid {pid}'s arguments")
return parse_argv(data.raw[:size.value])
def cocoa(pid, action):
script = """ObjC.import('AppKit');
function run(a) {
const app = $.NSRunningApplication.runningApplicationWithProcessIdentifier(Number(a[0]));
if (!app || app.isNil()) return 'gone';
return (a[1] === 'quit' ? app.terminate : (!app.terminated && app.finishedLaunching)) ? 'yes' : 'no';
}"""
return command("osascript", "-l", "JavaScript", "-e", script, str(pid), action).stdout.strip() == "yes"
def quit_apps(exe, apps):
for pid, birth in apps.items():
if running(exe).get(pid) == birth and not cocoa(pid, "quit"):
if running(exe).get(pid) == birth:
raise RuntimeError(f"app pid {pid} declined quit")
deadline = time.monotonic() + 10
while any(running(exe).get(pid) == birth for pid, birth in apps.items()):
if time.monotonic() >= deadline:
raise RuntimeError("app did not quit within 10s; no forced termination")
time.sleep(0.1)
def receipt_ready(directory, bundle_id, pid):
try:
receipt = json.loads((directory / f"{bundle_id}.{pid}").read_text())
return receipt["pid"] == pid and receipt["bundle_id"] == bundle_id
except (OSError, ValueError, KeyError, TypeError):
return False
def launch(live, exe, bundle_id, args, ready_root, require_ready=True):
# A unique directory per launch excludes stale receipts, even after PID reuse.
with tempfile.TemporaryDirectory(prefix="install-", dir=ready_root) as tmp:
directory = Path(tmp)
command("open", "-n", "--env", f"RUNE_READY_DIR={directory}", str(live), "--args", *args)
deadline = time.monotonic() + 15
while True:
for pid in running(exe):
if (not require_ready or receipt_ready(directory, bundle_id, pid)) and cocoa(pid, "ready"):
return
if time.monotonic() >= deadline:
raise RuntimeError("replacement did not become ready within 15s")
time.sleep(0.1)
def wait_idle(bundle_id, seconds):
if seconds is None:
return
while True:
front = command("lsappinfo", "front").stdout.strip()
info = command("lsappinfo", "info", "-only", "bundleid", front, check=False).stdout
if f'"{bundle_id}"' not in info:
return
idle = command("ioreg", "-c", "IOHIDSystem").stdout
match = re.search(r'"HIDIdleTime"\s*=\s*(\d+)', idle)
if match and int(match[1]) / 1_000_000_000 >= seconds:
return
time.sleep(2)
def build(stage, args):
if args.bundle:
source = Path(args.bundle)
if not (source / "Contents/MacOS" / args.exe).is_file():
raise RuntimeError("source bundle has no executable")
shutil.copytree(source, stage, dirs_exist_ok=True, symlinks=True)
return
macos = stage / "Contents/MacOS"
resources = stage / "Contents/Resources"
macos.mkdir(parents=True)
resources.mkdir()
shutil.copy2(args.bin, macos / args.exe)
if args.icon:
shutil.copy2(args.icon, resources / "icon.icns")
plist = dict(CFBundleName=args.name, CFBundleDisplayName=args.name,
CFBundleIdentifier=args.id, CFBundleExecutable=args.exe,
CFBundleIconFile="icon", CFBundlePackageType="APPL",
CFBundleShortVersionString="0.0.1", LSMinimumSystemVersion="13.0",
NSHighResolutionCapable=True)
if args.scheme:
plist["CFBundleURLTypes"] = [dict(CFBundleURLName=args.id, CFBundleURLSchemes=[args.scheme])]
if args.mic:
plist["NSMicrophoneUsageDescription"] = args.mic
with (stage / "Contents/Info.plist").open("wb") as file:
plistlib.dump(plist, file)
identity = os.environ.get("MAC_APP_SIGN") or "-"
if command("codesign", "--force", "--sign", identity, str(stage), check=False).returncode:
if identity == "-":
raise RuntimeError("ad hoc signing failed")
print("mac-app: signing identity failed; signing ad hoc", file=sys.stderr)
command("codesign", "--force", "--sign", "-", str(stage))
def main():
parser = argparse.ArgumentParser(description=__doc__)
for name in ("name", "id", "exe"):
parser.add_argument(f"--{name}", required=True)
source = parser.add_mutually_exclusive_group(required=True)
source.add_argument("--bin")
source.add_argument("--bundle", help="install an already signed bundle")
for name in ("icon", "scheme", "mic"):
parser.add_argument(f"--{name}")
parser.add_argument("--wait-idle", type=float)
parser.add_argument("--no-rune-ready", action="store_true", help="for binaries predating Rune readiness")
parser.add_argument("--only-relaunch", action="store_true", help="do not open an app that was not running")
parser.add_argument("--stamp", type=Path)
parser.add_argument("--revision")
parser.add_argument("args", nargs=argparse.REMAINDER)
args = parser.parse_args()
if args.args[:1] == ["--"]:
args.args = args.args[1:]
if args.bin and not os.access(args.bin, os.X_OK):
parser.error(f"no executable binary at {args.bin}")
if bool(args.stamp) != bool(args.revision):
parser.error("--stamp and --revision must be used together")
for name in (args.name, args.exe):
if name in (".", "..") or "/" in name:
parser.error("name and exe must be single path components")
home = Path.home()
live = home / "Applications" / f"{args.name}.app"
exe = live / "Contents/MacOS" / args.exe
ready_root = home / ".local/state/rune/ready"
ready_root.mkdir(parents=True, exist_ok=True)
with Bundle(live) as bundle:
build(bundle.stage, args)
wait_idle(args.id, args.wait_idle)
busy = home / "Library/Caches/mac-app/busy"
deadline = time.monotonic() + 900
while any((busy / str(pid)).exists() for pid in running(exe)):
if time.monotonic() >= deadline:
raise RuntimeError("app still busy after 15 minutes")
time.sleep(2)
old = running(exe)
launch_args = args.args
if old and not launch_args:
captured = [process_args(pid) for pid in old]
if any(value != captured[0] for value in captured) or running(exe) != old:
raise RuntimeError("running app instances changed or have different arguments")
launch_args = captured[0]
def start(rollback):
if args.scheme:
command("/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister",
"-f", str(live), check=False)
launch(live, exe, args.id, launch_args, ready_root,
require_ready=not (rollback or args.no_rune_ready))
if args.only_relaunch and not old:
bundle.publish()
bundle.committed = True
else:
bundle.replace(lambda: quit_apps(exe, old), start,
lambda: quit_apps(exe, running(exe)))
if args.stamp:
stamp = args.stamp.expanduser()
stamp.parent.mkdir(parents=True, exist_ok=True)
with tempfile.NamedTemporaryFile(mode="w", dir=stamp.parent, delete=False) as file:
file.write(args.revision + "\n")
temporary = Path(file.name)
try:
os.replace(temporary, stamp)
finally:
temporary.unlink(missing_ok=True)
print(live)
if __name__ == "__main__":
def interrupted(signum, _frame):
# A second termination signal must not interrupt the rollback itself.
signal.signal(signal.SIGTERM, signal.SIG_IGN)
signal.signal(signal.SIGINT, signal.SIG_IGN)
raise InterruptedError(f"installer interrupted by signal {signum}")
signal.signal(signal.SIGTERM, interrupted)
signal.signal(signal.SIGINT, interrupted)
try:
main()
except Exception as error:
print(f"mac-app: {error}", file=sys.stderr)
sys.exit(1)
+220
View File
@@ -0,0 +1,220 @@
"""Fake-bundle regressions: never launches a desktop application."""
import os
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
from unittest.mock import patch
from mac_app_bundle import Bundle
from mac_app_install import launch, receipt_ready, parse_argv
class InstallerRegression(unittest.TestCase):
def test_preserves_exact_arguments_without_reading_environment(self):
data = (6).to_bytes(4, sys.byteorder) + b"/Applications/Demo.app/Contents/MacOS/demo\0\0demo\0--server\0https://example.com\0--directory\0/a path\0\0SECRET=not-an-argument\0"
self.assertEqual(parse_argv(data), ["--server", "https://example.com", "--directory", "/a path", ""])
def test_prebuilt_inactive_app_installs_without_launch_and_stamps_success(self):
with tempfile.TemporaryDirectory() as tmp:
home = Path(tmp)
source = home / "source.app"
binary = source / "Contents/MacOS/demo"
binary.parent.mkdir(parents=True)
binary.write_text("new")
commands = home / "commands"
commands.mkdir()
for name, body in {"ps": "exit 0", "open": "exit 99", "codesign": "exit 99"}.items():
path = commands / name
path.write_text("#!/bin/sh\n" + body + "\n")
path.chmod(0o755)
stamp = home / "installed-rev"
result = subprocess.run(
[str(Path(__file__).with_name("mac-app")), "--name", "Demo",
"--id", "com.example.demo", "--exe", "demo", "--bundle", str(source),
"--only-relaunch", "--stamp", str(stamp), "--revision", "abc123"],
env={**os.environ, "HOME": tmp, "PATH": f"{commands}:/usr/bin:/bin"},
capture_output=True, text=True, timeout=10,
)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual((home / "Applications/Demo.app/Contents/MacOS/demo").read_text(), "new")
self.assertEqual(stamp.read_text(), "abc123\n")
def bundle(self, home):
live = Path(home) / "Demo.app"
live.mkdir()
(live / "version").write_text("old")
return live
def test_failed_launch_and_missing_receipt_roll_back(self):
for reason in ("open failed", "ready receipt timed out"):
with self.subTest(reason=reason), tempfile.TemporaryDirectory() as home:
live = self.bundle(home)
with Bundle(live) as bundle:
(bundle.stage / "version").write_text("new")
def start(rollback):
self.assertEqual((live / "version").read_text(), "old" if rollback else "new")
if not rollback:
raise RuntimeError(reason)
with self.assertRaisesRegex(RuntimeError, reason):
bundle.replace(lambda: None, start, lambda: None)
self.assertEqual((live / "version").read_text(), "old")
def test_unresponsive_replacement_still_restores_installed_path(self):
with tempfile.TemporaryDirectory() as home:
live = self.bundle(home)
with Bundle(live) as bundle:
(bundle.stage / "version").write_text("new")
def fail(_rollback=False):
raise RuntimeError("unresponsive")
with self.assertRaisesRegex(RuntimeError, "unresponsive"):
bundle.replace(lambda: None, fail, fail)
self.assertEqual((live / "version").read_text(), "old")
def test_receipt_timeout_uses_real_launch_path_and_rolls_back(self):
with tempfile.TemporaryDirectory() as home:
live = self.bundle(home)
with Bundle(live) as bundle:
(bundle.stage / "version").write_text("new")
with patch("mac_app_install.command"), patch("mac_app_install.running", return_value={123: ()}), \
patch("mac_app_install.time.monotonic", side_effect=[0, 16]):
def start(rollback):
if not rollback:
launch(live, live / "demo", "com.example.demo", [], home)
with self.assertRaisesRegex(RuntimeError, "did not become ready"):
bundle.replace(lambda: None, start, lambda: None)
self.assertEqual((live / "version").read_text(), "old")
def test_interrupt_after_exchange_keeps_both_bundles(self):
with tempfile.TemporaryDirectory() as home:
live = self.bundle(home)
script = """
from mac_app_bundle import Bundle
from pathlib import Path
import os, sys
with Bundle(sys.argv[1]) as bundle:
(bundle.stage / 'version').write_text('new')
(bundle.live.parent / 'backup-path').write_text(str(bundle.stage))
bundle.publish()
os._exit(0)
"""
subprocess.run([sys.executable, "-c", script, str(live)], check=True,
cwd=Path(__file__).parent, timeout=10)
self.assertEqual((live / "version").read_text(), "new")
backup = Path((live.parent / "backup-path").read_text())
self.assertEqual((backup / "version").read_text(), "old")
with Bundle(live): # no stale lock remains after death
pass
def test_termination_between_exchange_and_state_update_rolls_back(self):
with tempfile.TemporaryDirectory() as home:
live = self.bundle(home)
script = """
import mac_app_bundle as m
import os, signal, sys
real_exchange = m.exchange
def interrupt(a, b):
real_exchange(a, b)
if (b / 'version').read_text() == 'new':
os.kill(os.getpid(), signal.SIGTERM)
def terminated(*_):
raise InterruptedError('terminated')
m.exchange = interrupt
signal.signal(signal.SIGTERM, terminated)
with m.Bundle(sys.argv[1]) as bundle:
(bundle.stage / 'version').write_text('new')
try:
bundle.replace(lambda: None, lambda _: None, lambda: None)
except InterruptedError:
pass
else:
raise AssertionError('termination was lost')
assert (bundle.live / 'version').read_text() == 'old'
"""
subprocess.run([sys.executable, "-c", script, str(live)], check=True,
cwd=Path(__file__).parent, timeout=10)
self.assertEqual((live / "version").read_text(), "old")
def test_concurrent_installer_waits_until_rollback(self):
with tempfile.TemporaryDirectory() as home:
live = self.bundle(home)
script = """
from mac_app_bundle import Bundle
import fcntl, pathlib, sys
live = pathlib.Path(sys.argv[1])
with (live.parent / f'.{live.name}.install.lock').open('a+b') as f:
try:
fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
raise AssertionError('first installer has no lock')
except BlockingIOError:
print('blocked', flush=True)
with Bundle(live) as bundle:
assert (live / 'version').read_text() == 'old'
(bundle.stage / 'version').write_text('second')
bundle.replace(lambda: None, lambda _: None, lambda: None)
"""
with Bundle(live) as first:
(first.stage / "version").write_text("first")
first.publish()
child = subprocess.Popen([sys.executable, "-c", script, str(live)],
cwd=Path(__file__).parent, stdout=subprocess.PIPE, text=True)
self.assertEqual(child.stdout.readline().strip(), "blocked")
first.restore()
try:
self.assertEqual(child.wait(timeout=10), 0)
finally:
if child.poll() is None:
child.kill()
child.wait()
child.stdout.close()
self.assertEqual((live / "version").read_text(), "second")
def test_receipt_must_identify_replacement(self):
with tempfile.TemporaryDirectory() as home:
directory = Path(home)
receipt = directory / "com.example.demo.123"
receipt.write_text('{"pid": 124, "bundle_id": "com.example.demo"}')
self.assertFalse(receipt_ready(directory, "com.example.demo", 123))
receipt.write_text('{"pid": 123, "bundle_id": "com.example.demo"}')
self.assertTrue(receipt_ready(directory, "com.example.demo", 123))
def test_missing_stage_does_not_remove_live_app(self):
with tempfile.TemporaryDirectory() as tmp:
home = Path(tmp)
live = home / "Applications/Demo.app"
live.mkdir(parents=True)
(live / "version").write_text("old")
commands = home / "commands"
commands.mkdir()
# Simulate the other installer consuming this stage during codesign.
for name, body in {
"ps": "exit 0",
"codesign": 'for arg; do last="$arg"; done; rm -rf "$last"',
"open": "exit 1",
}.items():
path = commands / name
path.write_text("#!/bin/sh\n" + body + "\n")
path.chmod(0o755)
binary = home / "demo"
binary.write_text("#!/bin/sh\nexit 0\n")
binary.chmod(0o755)
stamp = home / "installed-rev"
stamp.write_text("old-revision\n")
result = subprocess.run(
[str(Path(__file__).with_name("mac-app")), "--name", "Demo",
"--id", "com.example.demo", "--exe", "demo", "--bin", str(binary),
"--stamp", str(stamp), "--revision", "new-revision"],
env={**os.environ, "HOME": tmp, "PATH": f"{commands}:/usr/bin:/bin", "MAC_APP_SIGN": ""},
capture_output=True, text=True, timeout=10,
)
self.assertNotEqual(result.returncode, 0)
self.assertTrue(live.is_dir(), result.stderr)
self.assertEqual((live / "version").read_text(), "old")
self.assertEqual(stamp.read_text(), "old-revision\n")
if __name__ == "__main__":
unittest.main()
+5
View File
@@ -0,0 +1,5 @@
[
{"t": 0.1, "menu": "Open Quick Panel"},
{"t": 0.3, "menu": "named"},
{"t": 0.5, "menu": "dock"}
]
+133
View File
@@ -0,0 +1,133 @@
# Motion audit
Per-frame traces of every element in the example apps, and a checker that flags motion a user
would notice: snaps, pops, neighbours that jump, exits that vanish before they play, overshoot,
motion that never settles, and work spent on things nobody can see.
```sh
scripts/motion-audit/run.sh # record all scenarios into target/motion-audit
python3 scripts/motion-audit/analyze.py target/motion-audit/*.jsonl [--quiet] [--json out.json]
python3 scripts/motion-audit/track.py target/motion-audit/oc-send.jsonl composer/editor 80 120
python3 scripts/motion-audit/test_analyze.py # analyze.py on synthetic traces
```
`run.sh` records each scenario headless at 120 fps on the virtual clock with
`--trace-all --trace`. `--trace-all` adds unkeyed elements (named by path) to the usual
motion-lint JSONL, and every trace now says why each frame animated (`quality.why`) and which
tracks it sampled (`tk`: `[element id or path, property, active]`; inactive means settling).
It also says how far scrolling carries each element when that changes (`sc`: `[id, x, y]` in
window points, scaled and turned as its rect is). The motion checks (overshoot, jiggle, reversal, stall, dog-leg) add it back, so a node
gliding inside a list that follows its end is judged against the list, not the screen.
`analyze.py` reports, per trace:
| Finding | Meaning |
| --- | --- |
| `invisible-work` | tracks sampled on an element that is transparent, off-window, clipped or occluded |
| `idle-frames`, `never-settles` | frames that animate with no visible change; motion still running at the end |
| `pop-in`, `pop-out` | an element appears or disappears at full opacity and size with no transition |
| `appear-then-jump` | mounts in one place, then moves there in a frame |
| `jump`, `step`, `sibling-jump` | a one-frame change in position or size, on its own or next to something animating, seen on both frames and in what shows: the visible part in the window moves, or what the element holds that shows moves with it, or it brings what it holds into view with no input (a scroll offset that lands in one frame with nothing asking for it; a loop wrapping while transparent or clipped, or a fold dropping rows above the window with the scroll offset, is not one) |
| `overshoot`, `jiggle` | passes its target, or reverses direction more than once |
| `latency`, `hitch` | input with no motion for several frames; a frame over budget |
| `cut-exit` | unmounts partway through its fade: nothing leaves above opacity 0 |
| `reversal`, `dog-leg` | one motion heads the wrong way first or goes out and back; a route much longer than its chord, on screen and against its parent |
| `stall` | one motion's speed drops for a frame and picks up again, as a retarget that lost part of its velocity does |
An app's scenario can say what each input should do with `"expect"` on its script event:
| Expect | Checks | Finding |
| --- | --- | --- |
| `instant` | everything in `scope` (an element name part) lands within a frame or two of the input; pops and jumps there are intended | `not-instant` |
| `follow` | a drag's `element` moves 1:1 with the pointer while it moves (it may stop at a limit) | `lags-hand` |
| `smooth` | after the input, `element` travels over several frames, not in one | `snap` |
| `leaves` | `element` is what leaves, not a sibling (index keys remove the last row) | `wrong-exit` |
```sh
python3 scripts/motion-audit/analyze.py --script s.json trace.jsonl --allow allow.json --fail
```
`--allow` takes a JSON list of `{"trace", "kind" (or a list), "element" (a substring),
"reason"}` rules for intended behaviour; every rule needs a reason, and a rule for a trace
the run recorded that matched nothing is listed as unused. `--fail` exits non-zero when a finding isn't allowed.
A motion that hides what it moves (a fade to 0, a collapse, a slide out) runs on for a few
frames below what anyone can see, down to its settle threshold. Up to 250 ms of that tail,
ending as its track settles, isn't `invisible-work`. A loop (a spinner) runs for as long as
it's shown, so frames animating only loops aren't `idle-frames` or `never-settles`.
Elements that draw nothing and hold nothing (hit and hover zones, spacers) carry the trace's
blank flag (64). Nobody can see them come, go or move, so they don't pop, jump or count as
drawn.
`track.py` prints one element's frames (rect, opacity, flags, sampled tracks) to confirm a
finding. Add scenarios as script JSON under `scenarios/` and a `run` line in `run.sh`.
## An app's own motion gate (`rune::motion_gate`)
The scenarios above are Rune's examples, recorded as traces and read by `analyze.py`. An app
gates its own motion inside `cargo test`, on its real view and state, with `rune::motion_gate`:
- `Run` wraps the app's `Runtime`: `idle` settles it unrecorded, `step`, `play` and `act` record
frames on the virtual clock (an `act` marks an input, so motion it retargets isn't held to one
path), and `quiet` marks where the cell's motion should end.
- `check` lists what a person would see go wrong in a `Recording`: `pop-in`, `pop-out`,
`cut-exit`, `jump`, `offset-jump`, `appear-then-jump`, `jerk`, `reversal`, `overshoot`,
`jiggle`, `text-swap`, `fade-snap`, `flicker`, `load-motion`, `never-settles`, `loop-jump`,
`wakes-after-end`, `lands-unseen`, `remount`, `unpinned`, `twice` and `scroll-commit` (the
app ran its view through a scroll). Thresholds and meanings are the `RULES` table. Elements are tracked by tree
path, so a keyed row keeps its identity however the rows around it change.
- Beside geometry and opacity, `check` follows everything an element paints (fill, border,
text, shadow, gradient and outline colours in OKLab, corners, border width, blurs, effect
payload, image and paint order) and the composited window as a grid of cells: `snap` (a
one-frame step between still frames), `flash` (it steps away and comes back, or drifts and
snaps back) and `changes-twice` (it changes, rests, then carries on). A colour counts by how
far it moves in OKLab and how much of it shows. The grid is a CPU raster of the painter
stream, or real frames through `Run::pixels`; a region finding is named after the surface
that changed, with ` (pixels)`. An input, a hover or press highlight landing, a
`Tx::instant` commit, `El::instant_changes` and `El::motion_intent` (`BOUNCE`, `KICK`,
`STEP`, `CUT`, `PULSE`, `TYPING`, …) mark a change as the design. Mark authored motion where
it's written rather than allowing it.
- `gate_rows(cells, ALLOW)` runs the app's cells (a name and a closure that records one) in
parallel, checks them, and fails the test on any finding its allowlist doesn't cover. Each
row is `AllowRow::new(kind, element contains, cells, why)`, needs its reason, scopes to the
cells it names (`"island-auto|island-click"`) and caps what it covers with `.max(n)`. A
whole run lists rows that matched nothing, so stale ones come out. `gate(cells, ALLOW)` takes
the older `(kind, element, cell, why)` tuples.
- Headless `rune` records the same checks with `RUNE_MOTION_GATE=<path>` (`run.sh` writes
`<name>.gate.txt` per scenario), and an app stepping its own runtime can use `Sampler`.
The app keeps its scenarios, its circumstance matrix (cell names like `send/pinned/long/wide`)
and its allowlist; Rune keeps the checker and the runner. The module docs show a whole test.
`gate` runs one:
```sh
scripts/motion-audit/gate -- -p my-app motion_gate # every cell
scripts/motion-audit/gate send/pinned -- -p my-app motion_gate # cells whose name contains it
scripts/motion-audit/gate --allowed -- -p my-app motion_gate # allowed findings too
scripts/motion-audit/gate --dump 'send/pinned/long/wide|composer|120|160' -- -p my-app motion_gate
scripts/motion-audit/gate --sheet 'send/pinned/long/wide|134|composer' -- -p my-app motion_gate
```
`--dump` writes one cell's tracks frame by frame (rect, visible rect, opacity, scale, flags,
and each painted property);
`--sheet` writes a PNG strip of the frames around one, every element outlined as strongly as
its opacity and the named one in red. An empty cell part (`'|composer|120|160'`) matches any
cell, and headless `rune` writes both beside its `RUNE_MOTION_GATE` report. Both are evidence
for reading a finding; the findings
are the gate. `MOTION_GATE_OUT` names the report (default `$TMPDIR/motion-gate`), and
`MOTION_GATE_WRAP` runs the test under a command prefix.
## Tracing the real app (`motion-trace.py`)
The gate runs headless on the virtual clock, so it says nothing about how long a real frame
takes. For that, an app can write its own trace in the installed build, one JSON line per key,
span and frame (the format is at the top of `motion-trace.py`), and read it:
```sh
python3 scripts/motion-audit/motion-trace.py trace.jsonl --key Enter --frames 40 --budget 16.7
```
For each matching key it prints how many frames passed before a watched element moved, then
each frame's update and render cost, marking the ones over budget, with the spans over 1 ms in
them.
File diff suppressed because it is too large. Load diff
+37
View File
@@ -0,0 +1,37 @@
#!/usr/bin/env bash
# Runs an app's motion gate (`rune::motion_gate::gate` in one of its tests) and prints one line per
# finding: kind, element, frame, detail and cell. Everything after `--` goes to `cargo test`, so it
# names the app's package and test:
# scripts/motion-audit/gate [CELL-FILTER] -- -p my-app motion_gate
# scripts/motion-audit/gate --sheet 'add-row/wide|134[|path part]' -- -p my-app motion_gate
# scripts/motion-audit/gate --dump 'add-row/wide|path part[|from|to]' -- -p my-app motion_gate
# scripts/motion-audit/gate --allowed [CELL-FILTER] -- … also list allowlisted findings
# `--sheet` writes a contact strip of the frames around one, the path part's outlines in red;
# `--dump` writes those tracks' frames. Both name a cell, which is also the filter.
# MOTION_GATE_OUT names the report file (default $TMPDIR/motion-gate). MOTION_GATE_WRAP runs the
# test under a command prefix (a build-queue lease, say); without it, it's plain cargo.
set -euo pipefail
OUT=${MOTION_GATE_OUT:-${TMPDIR:-/tmp}/motion-gate}
export MOTION_GATE_OUT=$OUT
filter=""
while [[ $# -gt 0 ]]; do
case "$1" in
--sheet) export MOTION_GATE_SHEET=$2; filter=${2%%|*}; shift 2 ;;
--dump) export MOTION_GATE_DUMP=$2; filter=${2%%|*}; shift 2 ;;
--allowed) export MOTION_GATE_ALLOWED=1; shift ;;
-h|--help) sed -n '2,13p' "$0"; exit 0 ;;
--) shift; break ;;
*) filter=$1; shift ;;
esac
done
[[ $# -gt 0 ]] || { echo "motion gate: name the app's test after --, e.g. -- -p my-app motion_gate" >&2; exit 2; }
export MOTION_GATE=$filter
rm -f "$OUT" "$OUT.sheet.png" "$OUT.dump"
wrap=()
[[ -n ${MOTION_GATE_WRAP:-} ]] && read -r -a wrap <<<"$MOTION_GATE_WRAP"
status=0
${wrap[@]+"${wrap[@]}"} cargo test -q "$@" >/dev/null 2>&1 || status=$?
if [[ -s "$OUT" ]]; then cat "$OUT"; else echo "motion gate: the test didn't run (exit $status); run cargo test $* to see why" >&2; exit 1; fi
[[ -f "$OUT.sheet.png" ]] && echo "sheet: $OUT.sheet.png"
[[ -f "$OUT.dump" ]] && echo "dump: $OUT.dump"
exit $status
+73
View File
@@ -0,0 +1,73 @@
#!/usr/bin/env python3
"""Reads an app's own motion trace, recorded in the installed app on real data, and prints, for
each key press, how many frames until a watched element first moved, and every frame of the move
that went over budget.
scripts/motion-audit/motion-trace.py TRACE.jsonl [--key Enter] [--frames 40] [--budget 16.7]
The trace is JSON lines the app writes (README.md, "Tracing the real app"):
{"k":"key","ms":…,"key":"Enter"} a key, as the app's handler got it
{"k":"span","ms":…,"name":"load","dur":…} time spent in one step on the main thread
{"k":"frame","ms":…,"update":…,"render":…,"rows":{"row-1":[y,h,opacity],…}}
`ms` is wall time since launch at the start of the step. A frame's cost is Rune's update
(handlers, poll, view, layout) plus the compositor's render; over the budget, the display shows
the previous frame again. `rows` holds whatever the app watches, by id, as numbers that change
when it moves. Spans over 1 ms in the frame are listed beside it.
"""
import argparse
import json
ap = argparse.ArgumentParser()
ap.add_argument("trace")
ap.add_argument("--key", default="Enter")
ap.add_argument("--frames", type=int, default=40)
ap.add_argument("--budget", type=float, default=1000 / 60)
a = ap.parse_args()
lines = [json.loads(l) for l in open(a.trace) if l.strip()]
frames = [l for l in lines if l["k"] == "frame"]
spans = [l for l in lines if l["k"] == "span"]
keys = [l for l in lines if l["k"] == "key" and a.key in l["key"]]
def start(f):
return f["ms"] - f["update"]
def moved(a_, b):
rows_a, rows_b = a_.get("rows", {}), b.get("rows", {})
for id_, r in rows_a.items():
o = rows_b.get(id_)
if o is None or any(abs(x - y) > 0.01 for x, y in zip(o, r)):
return True
return any(id_ not in rows_a for id_ in rows_b)
print(a.trace)
for k in keys:
i = next((i for i, f in enumerate(frames) if f["ms"] >= k["ms"]), None)
if i is None:
continue
key_frame = frames[i]
first = next((j for j in range(i + 1, len(frames)) if moved(frames[j - 1], frames[j])), None)
# The key frame itself already moved rows: the move started on it.
if moved(frames[i - 1], key_frame) if i else False:
first = i
sel = f" (sel {key_frame['sel']})" if "sel" in key_frame else ""
print(f"\n{k['key']} at {k['ms']:.0f} ms, handled in the frame starting {start(key_frame):.0f} ms{sel}")
if first is None:
print(" nothing watched moved")
continue
print(f" first moved frame: +{first - i} frames, {frames[first]['ms'] + frames[first]['render'] - k['ms']:.0f} ms from the key to its render's end")
over = 0
for j in range(i, min(len(frames), i + a.frames)):
f = frames[j]
cost = f["update"] + f["render"]
gap = start(f) - (frames[j - 1]["ms"] + frames[j - 1]["render"]) if j else 0
if cost > a.budget:
over += 1
mark = "OVER" if cost > a.budget else " "
big = [s for s in spans if start(f) <= s["ms"] < f["ms"] + f["render"] and s["dur"] > 1.0]
moving = "move" if j and moved(frames[j - 1], f) else " "
names = ", ".join(f"{s['name']} {s['dur']:.1f}" for s in big)
print(f" {mark} +{j - i:2d} {moving} update {f['update']:6.1f} render {f['render']:5.1f} idle-before {gap:6.1f} {names}")
print(f" frames over {a.budget:.1f} ms in the first {a.frames}: {over}")
+65
View File
@@ -0,0 +1,65 @@
#!/bin/sh
# Records a motion trace of every element (--trace-all) for each scenario below, at 120 fps on
# the virtual clock, plus the final element tree and what rune::motion_gate finds (<name>.gate.txt).
# Then scripts/motion-audit/analyze.py reads them.
# Run from the repo root: scripts/motion-audit/run.sh [out-dir] (default target/motion-audit).
set -e
O=${1:-target/motion-audit}
mkdir -p "$O"
MOTION_GATE_OUT="$O/live-tail.gate.txt" sh scripts/motion-audit/scenarios/live-tail.sh
cargo build --release -p todo -p settings -p kit-gallery -p odometer
cargo build --release -p rune-kit --features rune/tooling --example shell --example tab_strip
cargo build --release -p rune --features tooling --example growth_reorder --example keep_stuck --example sticky --example scroll_keys --example scroll_anchor --example text_glide --example one_snap
B=${CARGO_TARGET_DIR:-target}/release
SH=$B/examples/shell
GR=$B/examples/growth_reorder
KS=$B/examples/keep_stuck
S=scripts/motion-audit/scenarios
FPS=120
# name | seconds | command (trace args appended)
run() {
name=$1; secs=$2; shift 2
frames=$(python3 -c "print(int($secs * $FPS))")
echo "== $name ($frames frames)"
RUNE_MOTION_GATE="$O/$name.gate.txt" "$@" --fps $FPS --frames "$frames" --trace-all --trace "$O/$name.jsonl" --tree "$O/$name-end.json"
}
run todo-add-remove 4.4 $B/todo --script $S/todo-add-remove.json
run settings-toggle-retarget 1.5 $B/settings --script examples/settings/scripts/toggle-retarget.json
run settings-segmented-retarget 1.5 $B/settings --script examples/settings/scripts/segmented-retarget.json
run settings-slider 3.0 $B/settings --script examples/settings/scripts/slider.json
run settings-hover 3.0 $B/settings --script examples/settings/scripts/hover.json
run gallery-combobox 3.0 $B/kit-gallery --scene rune-combobox--searchable --script examples/kit-gallery/scripts/combobox.json
run gallery-combobox-animated 3.0 $B/kit-gallery --scene rune-combobox--animated-filter --script examples/kit-gallery/scripts/combobox-animated-filter.json
run gallery-scroll-bar 4.0 $B/kit-gallery --scene rune-scroll-bar--basic --script $S/gallery-scroll-bar.json
run gallery-scroll-bar-hover 3.2 $B/kit-gallery --scene rune-scroll-bar--basic --script $S/gallery-scroll-bar-hover.json
run gallery-scroll-bar-grow 2.4 $B/kit-gallery --scene rune-scroll-bar--grow --scroll-bars always --script $S/gallery-scroll-bar-grow.json
run gallery-modal 5.5 $B/kit-gallery --scene motion-focus-modal --script examples/kit-gallery/scripts/motion-focus-modal.json
run gallery-stagger-list 3.0 $B/kit-gallery --scene motion-stagger-list --script examples/kit-gallery/scripts/motion-stagger-list.json
run gallery-mermaid-stream 4.5 $B/kit-gallery --scene rune-markdown--mermaid-streaming --size 1100x1400 --script $S/gallery-mermaid-stream.json
run gallery-markdown-stream-tail 3.0 $B/kit-gallery --scene rune-markdown--stream-tail --script $S/gallery-markdown-stream-tail.json
run odometer 5.4 $B/odometer --script $S/odometer.json
run shell-idle 2.0 $SH
run shell-toggle 3.0 $SH --script $S/shell-toggle.json
run shell-peek 5.0 $SH --script $S/shell-peek.json
run shell-resize 3.6 $SH --script $S/shell-resize.json
run shell-reorder 3.6 $SH --script $S/shell-reorder.json
run shell-virtual-peek 5.0 $SH virtual --script $S/shell-peek.json
run shell-virtual-reorder 3.6 $SH virtual --script $S/shell-reorder-virtual.json
run shell-window-resize 3.0 $SH --script $S/shell-window-resize.json
run shell-virtual-window-resize 3.0 $SH virtual --script $S/shell-window-resize.json
run tab-strip 9.0 $B/examples/tab_strip --script $S/tab-strip.json
run growth-reorder 4.2 $GR --script $S/growth-reorder.json
run growth-reorder-virtual 4.0 $GR virtual --script $S/growth-reorder-virtual.json
run keep-stuck 3.2 $KS --script $S/keep-stuck.json
run growth-reorder-grow 3.5 $GR steer --script $S/growth-reorder-grow.json
run growth-reorder-gap 4.7 $GR steer --script $S/growth-reorder-gap.json
run growth-reorder-flight 2.6 $GR steer --script $S/growth-reorder-flight.json
run sticky-scroll 1.6 $B/examples/sticky --script crates/rune/examples/sticky.json
run scroll-keys 3.2 $B/examples/scroll_keys --script $S/scroll-keys.json
run wheel-distance 1.2 $B/examples/scroll_keys --script $S/wheel-distance.json
run scroll-anchor 3.4 $B/examples/scroll_anchor --script $S/scroll-anchor.json
run text-glide 3.8 $B/examples/text_glide --script $S/text-glide.json
run one-snap 4.4 $B/examples/one_snap --script $S/one-snap.json
ls "$O"
@@ -0,0 +1,7 @@
[
{"t":0.2,"type":"tap","key":"stream-more"},
{"t":0.6,"type":"tap","key":"stream-more"},
{"t":1.0,"type":"tap","key":"stream-more"},
{"t":1.4,"type":"tap","key":"stream-more"},
{"t":1.8,"type":"tap","key":"stream-more"}
]
@@ -0,0 +1,16 @@
[
{"t":0.2,"type":"tap","key":"stream-more"},
{"t":0.45,"type":"tap","key":"stream-more"},
{"t":0.7,"type":"tap","key":"stream-more"},
{"t":0.95,"type":"tap","key":"stream-more"},
{"t":1.2,"type":"tap","key":"stream-more"},
{"t":1.45,"type":"tap","key":"stream-more"},
{"t":1.7,"type":"tap","key":"stream-more"},
{"t":1.95,"type":"tap","key":"stream-more"},
{"t":2.2,"type":"tap","key":"stream-more"},
{"t":2.45,"type":"tap","key":"stream-more"},
{"t":2.7,"type":"tap","key":"stream-more"},
{"t":2.95,"type":"tap","key":"stream-more"},
{"t":3.2,"type":"tap","key":"stream-more"},
{"t":3.45,"type":"tap","key":"stream-more"}
]
@@ -0,0 +1,5 @@
[
{ "t": 0.3, "type": "tap", "key": "more" },
{ "t": 1.3, "type": "tap", "key": "more" },
{ "t": 2.4, "type": "mark", "name": "end" }
]
@@ -0,0 +1,6 @@
[
{ "t": 0.25, "type": "move", "key": "item-3" },
{ "t": 0.6, "type": "move", "key": "thumb" },
{ "t": 1.4, "type": "move", "key": "item-3" },
{ "t": 3.2, "type": "mark", "name": "end" }
]
@@ -0,0 +1,5 @@
[
{ "t": 0.25, "type": "scroll", "key": "feed", "dy": -260, "dur": 0.45 },
{ "t": 1.9, "type": "scroll", "key": "feed", "dy": 140, "dur": 0.35 },
{ "t": 4.0, "type": "mark", "name": "end" }
]
@@ -0,0 +1,7 @@
{
"events": [
{ "t": 0.38, "type": "tap", "key": "composer", "hold": 0 },
{ "t": 0.47, "type": "tap", "key": "working", "hold": 0, "expect": "smooth" },
{ "t": 1.5, "type": "move", "x": 10, "y": 10 }
]
}
@@ -0,0 +1,8 @@
{
"events": [
{ "t": 0.3, "type": "tap", "key": "composer" },
{ "t": 0.9, "type": "tap", "key": "composer" },
{ "t": 2.6, "type": "tap", "key": "working", "expect": "smooth" },
{ "t": 4.6, "type": "move", "x": 10, "y": 10 }
]
}
@@ -0,0 +1,7 @@
{
"events": [
{ "t": 0.3, "type": "tap", "key": "composer" },
{ "t": 1.8, "type": "tap", "key": "working", "expect": "smooth" },
{ "t": 3.4, "type": "move", "x": 10, "y": 10 }
]
}
@@ -0,0 +1,8 @@
{
"events": [
{ "t": 0.3, "type": "tap", "key": "v1", "expect": "smooth" },
{ "t": 1.4, "type": "tap", "key": "v0", "expect": "smooth" },
{ "t": 2.5, "type": "scroll", "x": 200, "y": 200, "dy": -300 },
{ "t": 3.6, "type": "move", "x": 10, "y": 10 }
]
}
@@ -0,0 +1,9 @@
{
"events": [
{ "t": 0.3, "type": "tap", "key": "working", "expect": "smooth" },
{ "t": 1.4, "type": "tap", "key": "working", "expect": "smooth" },
{ "t": 1.5, "type": "tap", "key": "working", "expect": "smooth" },
{ "t": 2.6, "type": "tap", "key": "m1", "expect": "smooth" },
{ "t": 3.8, "type": "move", "x": 10, "y": 10 }
]
}
@@ -0,0 +1,7 @@
{
"events": [
{ "t": 0.3, "type": "scroll", "x": 210, "y": 180, "dy": 450, "dur": 0.4 },
{ "t": 1.2, "type": "tap", "key": "hdr", "expect": "smooth", "element": "answer" },
{ "t": 3.0, "type": "move", "x": 10, "y": 10 }
]
}
@@ -0,0 +1,3 @@
#!/bin/sh
# A poll delivers a pending row; unchanged window, resizing, and reading above the end.
exec scripts/motion-audit/gate live-tail -- -p rune --lib live_tail_motion_gate
@@ -0,0 +1,11 @@
{
"events": [
{"t": 0.3, "type": "tap", "key": "up", "expect": "smooth", "element": "secs.3"},
{"t": 1.1, "type": "tap", "key": "down", "expect": "smooth", "element": "secs.5"},
{"t": 1.9, "type": "tap", "key": "up"},
{"t": 1.98, "type": "tap", "key": "down", "expect": "smooth", "element": "secs.8"},
{"t": 2.8, "type": "tap", "key": "down", "expect": "smooth", "element": "count.8"},
{"t": 3.4, "type": "tap", "key": "step"},
{"t": 4.2, "type": "tap", "key": "big"}
]
}
@@ -0,0 +1,7 @@
{
"events": [
{ "t": 0.25, "type": "tap", "key": "stage", "expect": "smooth", "element": "hud" },
{ "t": 1.6, "type": "tap", "key": "badge", "expect": "instant", "scope": "hud" },
{ "t": 2.4, "type": "tap", "key": "stage", "expect": "smooth", "element": "hud" }
]
}
@@ -0,0 +1,8 @@
{
"events": [
{ "t": 0.3, "type": "scroll", "key": "feed", "dy": -600, "dur": 0.4 },
{ "t": 1.4, "type": "key", "name": "Enter" },
{ "t": 2.4, "type": "key", "name": "Enter" },
{ "t": 3.4, "type": "mark", "name": "end" }
]
}
@@ -0,0 +1,40 @@
{
"events": [
{"t": 0.1, "type": "move", "x": 200, "y": 220},
{"t": 0.3, "type": "key", "name": "Down", "expect": "smooth", "element": "card-5"},
{"t": 0.55, "type": "key", "name": "Down", "repeat": true},
{"t": 0.5833, "type": "key", "name": "Down", "repeat": true},
{"t": 0.6167, "type": "key", "name": "Down", "repeat": true},
{"t": 0.65, "type": "key", "name": "Down", "repeat": true},
{"t": 0.6833, "type": "key", "name": "Down", "repeat": true},
{"t": 0.7167, "type": "key", "name": "Down", "repeat": true},
{"t": 0.75, "type": "key", "name": "Down", "repeat": true},
{"t": 0.7833, "type": "key", "name": "Down", "repeat": true},
{"t": 0.8167, "type": "key", "name": "Down", "repeat": true},
{"t": 0.85, "type": "key", "name": "Down", "repeat": true},
{"t": 0.8833, "type": "key", "name": "Down", "repeat": true},
{"t": 0.9167, "type": "key", "name": "Down", "repeat": true},
{"t": 0.95, "type": "key", "name": "Down", "repeat": true},
{"t": 0.9833, "type": "key", "name": "Down", "repeat": true},
{"t": 1.0167, "type": "key", "name": "Down", "repeat": true},
{"t": 1.05, "type": "key", "name": "Down", "repeat": true},
{"t": 1.0833, "type": "key", "name": "Down", "repeat": true},
{"t": 1.1167, "type": "key", "name": "Down", "repeat": true},
{"t": 1.15, "type": "key", "name": "Down", "repeat": true},
{"t": 1.1833, "type": "key", "name": "Down", "repeat": true},
{"t": 1.2167, "type": "key", "name": "Down", "repeat": true},
{"t": 1.25, "type": "key", "name": "Down", "repeat": true},
{"t": 1.2833, "type": "key", "name": "Down", "repeat": true},
{"t": 1.3167, "type": "key", "name": "Down", "repeat": true},
{"t": 1.35, "type": "key", "name": "Down", "repeat": true},
{"t": 1.3833, "type": "key", "name": "Down", "repeat": true},
{"t": 1.4167, "type": "key", "name": "Down", "repeat": true},
{"t": 1.45, "type": "key", "name": "Down", "repeat": true},
{"t": 1.4833, "type": "key", "name": "Down", "repeat": true},
{"t": 1.5167, "type": "key", "name": "Down", "repeat": true},
{"t": 2.2, "type": "key", "name": "Up"},
{"t": 2.32, "type": "key", "name": "Up"},
{"t": 2.44, "type": "key", "name": "Up"},
{"t": 3.2, "type": "mark", "name": "end"}
]
}
@@ -0,0 +1,12 @@
{
"events": [
{ "t": 0.3, "type": "tap", "key": "sidebar-toggle" },
{ "t": 0.9, "type": "move", "x": 700, "y": 400 },
{ "t": 1.3, "type": "move", "x": 10, "y": 300 },
{ "t": 1.9, "type": "move", "x": 150, "y": 300 },
{ "t": 2.5, "type": "move", "x": 700, "y": 300 },
{ "t": 3.2, "type": "move", "key": "sidebar-toggle" },
{ "t": 3.7, "type": "tap", "key": "sidebar-toggle" },
{ "t": 4.4, "type": "move", "x": 700, "y": 400 }
]
}
@@ -0,0 +1,8 @@
{
"events": [
{ "t": 0.3, "type": "drag", "key": "v1", "dy": 120, "dur": 0.6 },
{ "t": 1.6, "type": "drag", "key": "v0", "dy": 160, "dur": 0.8 },
{ "t": 2.1, "type": "key", "name": "Escape" },
{ "t": 3.2, "type": "move", "x": 700, "y": 400 }
]
}
@@ -0,0 +1,8 @@
{
"events": [
{ "t": 0.3, "type": "drag", "key": "s2", "dy": 120, "dur": 0.6 },
{ "t": 1.6, "type": "drag", "key": "s1", "dy": 160, "dur": 0.8 },
{ "t": 2.1, "type": "key", "name": "Escape" },
{ "t": 3.2, "type": "move", "x": 700, "y": 400 }
]
}
@@ -0,0 +1,9 @@
{
"events": [
{ "t": 0.3, "type": "move", "key": "sidebar-grip" },
{ "t": 0.6, "type": "drag", "key": "sidebar-grip", "dx": 140, "dur": 0.5 },
{ "t": 1.5, "type": "drag", "key": "sidebar-grip", "dx": -320, "dur": 0.6 },
{ "t": 2.5, "type": "double-click", "key": "sidebar-grip" },
{ "t": 3.3, "type": "move", "x": 700, "y": 400 }
]
}
@@ -0,0 +1,8 @@
{
"events": [
{ "t": 0.3, "type": "tap", "key": "sidebar-toggle" },
{ "t": 1.0, "type": "move", "x": 700, "y": 400 },
{ "t": 1.3, "type": "tap", "key": "sidebar-toggle" },
{ "t": 2.2, "type": "move", "x": 700, "y": 400 }
]
}
@@ -0,0 +1,7 @@
{
"events": [
{ "t": 0.3, "type": "resize", "dw": -320, "dur": 0.8 },
{ "t": 1.5, "type": "resize", "dw": 320, "dh": 160, "dur": 0.8 },
{ "t": 2.6, "type": "move", "x": 400, "y": 300 }
]
}
@@ -0,0 +1,14 @@
{
"events": [
{ "t": 0.3, "type": "drag", "key": "top-list/t-s1", "dx": 300, "dur": 0.8 },
{ "t": 1.6, "type": "drag", "key": "side-list/t-s6", "dy": -125, "dur": 0.7 },
{ "t": 2.8, "type": "drag", "key": "side-list/t-s2", "dy": 90, "dur": 0.8 },
{ "t": 3.3, "type": "key", "name": "Escape" },
{ "t": 4.2, "type": "click", "key": "top-list/t-s7", "button": "middle" },
{ "t": 4.6, "type": "click", "button": "middle" },
{ "t": 5.2, "type": "move", "x": 700, "y": 500 },
{ "t": 6.0, "type": "drag", "key": "top-list/t-s2", "dx": 70, "dy": 160, "dur": 0.8 },
{ "t": 7.2, "type": "click", "key": "new-tab" },
{ "t": 7.9, "type": "move", "x": 700, "y": 500 }
]
}
@@ -0,0 +1,6 @@
{
"events": [
{ "t": 0.3, "type": "tap", "key": "card", "expect": "smooth", "element": "card" },
{ "t": 2.0, "type": "tap", "key": "card", "expect": "smooth", "element": "card" }
]
}
@@ -0,0 +1,40 @@
{
"events": [
{
"t": 0.3,
"type": "tap",
"key": "add"
},
{
"t": 0.9,
"type": "tap",
"key": "add"
},
{
"t": 1.5,
"type": "tap",
"key": "todo-1/#2"
},
{
"t": 2.1,
"type": "tap",
"key": "todo-2/check"
},
{
"t": 2.7,
"type": "tap",
"key": "todo-0/#2"
},
{
"t": 2.75,
"type": "tap",
"key": "add"
},
{
"t": 3.6,
"type": "move",
"x": 10,
"y": 10
}
]
}
@@ -0,0 +1,6 @@
{
"events": [
{ "t": 0.25, "type": "wheel", "x": 200, "y": 220, "dy": -120, "precise": false, "expect": "instant", "scope": "cards" },
{ "t": 0.65, "type": "wheel", "x": 200, "y": 220, "dy": 12, "precise": true, "expect": "instant", "scope": "cards" }
]
}
+274
View File
@@ -0,0 +1,274 @@
#!/usr/bin/env python3
"""Checks analyze.py on small synthetic traces. Run: python3 scripts/motion-audit/test_analyze.py"""
import json
import math
import os
import sys
import tempfile
sys.dont_write_bytecode = True
sys.path.insert(0, os.path.dirname(__file__))
import analyze # noqa: E402
def trace(states):
"""A 120 Hz trace of one 10×10 element; `states` holds (x, opacity, visible width) per frame."""
lines = [json.dumps({"width": 200, "height": 100, "hz": 120})]
for k, (x, op, vis_w) in enumerate(states):
fr = {"e": [[1, x, 40, 10, 10, op, 0, 0, max(x, 20), 40, vis_w, 10]], "quality": {"animating": True}}
if k == 0:
fr["m"] = [{"id": 1, "nm": "label/sheen"}]
lines.append(json.dumps(fr))
f = tempfile.NamedTemporaryFile("w", suffix=".jsonl", delete=False)
f.write("\n".join(lines) + "\n")
f.close()
return f.name
def jumps(states):
path = trace(states)
try:
return [f for f in analyze.analyze(path)["findings"] if f["kind"] in ("jump", "step")]
finally:
os.unlink(path)
def sheen(wrap_from, wrap_to):
"""A loop sliding right 0.5 pt a frame, then wrapping back to its start."""
before = [(86 - 0.5 * (9 - i), *wrap_from) for i in range(10)]
after = [(15 + 0.5 * i, *wrap_to) for i in range(10)]
return before + after
def scene(frames, flags=None, clips=None):
"""A 120 Hz trace of named elements; each frame maps name -> (x, y, w, h, opacity), plus
how far scrolling carries it as (x, y) when it scrolls, and a name missing from a frame is
gone. A name's parent is its longest named prefix. `clips` maps a name to a window-space
clip (x0, y0, x1, y1) cutting the visible part of it and what it holds. A frame's "@ev"
lists the inputs the app recorded in it ("wheel 3.0")."""
names = sorted({nm for fr in frames for nm in fr if nm != "@ev"})
ids = {nm: i + 1 for i, nm in enumerate(names)}
def parent(nm):
cut = [nm[:j] for j in range(len(nm)) if nm[j] == "/" and nm[:j] in ids]
return ids[cut[-1]] if cut else None
lines = [json.dumps({"width": 400, "height": 400, "hz": 120})]
alive, meta = set(), set()
for fr in frames:
out = {"e": [], "quality": {"animating": True}, "m": [], "g": [], "sc": [], "ev": fr.get("@ev", [])}
fr = {nm: v for nm, v in fr.items() if nm != "@ev"}
for nm, (x, y, w, h, op, *sc) in fr.items():
out["sc"] += [[ids[nm], *sc[0]]] if sc else []
if nm not in meta:
meta.add(nm)
out["m"].append({"id": ids[nm], "nm": nm, "pv": parent(nm)})
vis = [x, y, w, h]
for c in [c for p, c in (clips or {}).items() if nm == p or nm.startswith(p + "/")]:
x0, y0 = max(vis[0], c[0]), max(vis[1], c[1])
x1, y1 = min(vis[0] + vis[2], c[2]), min(vis[1] + vis[3], c[3])
vis = [x0, y0, max(x1 - x0, 0), max(y1 - y0, 0)]
out["e"].append([ids[nm], x, y, w, h, op, 0, (flags or {}).get(nm, 0), *vis])
alive.add(nm)
for nm in sorted(alive - set(fr)):
out["g"].append(ids[nm])
alive.discard(nm)
lines.append(json.dumps(out))
f = tempfile.NamedTemporaryFile("w", suffix=".jsonl", delete=False)
f.write("\n".join(lines) + "\n")
f.close()
return f.name
def kinds(frames, events=None, flags=None, clips=None):
path = scene(frames, flags, clips)
try:
return [f["kind"] for f in analyze.analyze(path, {"events": events} if events else None)["findings"]]
finally:
os.unlink(path)
def ease(a, b, n):
"""n frames easing from a to b (no overshoot)."""
return [a + (b - a) * (1 - (1 - (i + 1) / n) ** 3) for i in range(n)]
def hold(fr, n):
return [dict(fr) for _ in range(n)]
def main():
# instant: a key whose answer fades in over 20 frames isn't a cut.
still = {"root": (0, 0, 400, 400, 1.0)}
key = [{"t": 0.1, "type": "key", "name": "Escape", "expect": "instant"}]
fade = hold(still, 12) + [{**still, "root/panel": (10, 10, 100, 100, op)} for op in ease(0, 1, 20)] + hold({**still, "root/panel": (10, 10, 100, 100, 1)}, 20)
assert "not-instant" in kinds(fade, key), "a fade answering an instant input"
cut = hold(still, 12) + hold({**still, "root/panel": (10, 10, 100, 100, 1)}, 40)
assert "not-instant" not in kinds(cut, key) and "pop-in" not in kinds(cut, key), "a cut is the answer, not a pop"
# follow: a drag that tracks the smoothstepped hand passes; one that trails it lags.
drag = [{"t": 0.1, "type": "drag", "key": "handle", "dx": 120, "dur": 0.5, "expect": "follow", "element": "root/handle"}]
def hand(k):
f = max(0, min(60, math.floor((k / 120 - 0.1) / 0.5 * 60 + 1e-6))) / 60
return 120 * f * f * (3 - 2 * f)
track = [{**still, "root/handle": (10 + hand(k), 10, 20, 20, 1)} for k in range(100)]
assert "lags-hand" not in kinds(track, drag), "a handle on the hand"
lag, x = [], 10.0
for k in range(100):
x += (10 + hand(k) - x) * 0.3
lag.append({**still, "root/handle": (x, 10, 20, 20, 1)})
assert "lags-hand" in kinds(lag, drag), "a handle on a spring behind the hand"
# one monotonic path: a wind-up the wrong way, and an L-shaped route.
at = lambda x, y: {**still, "root/card": (x, y, 40, 40, 1)}
windup = hold(at(100, 100), 5) + [at(x, 100) for x in ease(100, 94, 4) + ease(94, 200, 16)] + hold(at(200, 100), 10)
assert "reversal" in kinds(windup), "a wind-up before the move"
straight = hold(at(100, 100), 5) + [at(x, 100) for x in ease(100, 200, 20)] + hold(at(200, 100), 10)
assert not {"reversal", "dog-leg", "overshoot"} & set(kinds(straight)), "a straight eased move"
ell = hold(at(100, 100), 5) + [at(x, 100) for x in ease(100, 200, 10)] + [at(200, y) for y in ease(100, 200, 10)] + hold(at(200, 200), 10)
assert "dog-leg" in kinds(ell), "across, then down"
# a chevron sliding along its row as the list scrolls: across on the list, up with it.
list_y = ease(300, 200, 20) + [200] * 20
slide = [0] * 18 + ease(0, 100, 20) + [100] * 2
scroll = hold({**still, "root/list": (0, 300, 400, 100, 1), "root/list/chevron": (100, 310, 10, 10, 1)}, 5)
scroll += [{**still, "root/list": (0, y, 400, 100, 1), "root/list/chevron": (100 + x, y + 10, 10, 10, 1)} for y, x in zip(list_y, slide)]
assert "dog-leg" not in kinds(scroll + hold(scroll[-1], 10)), "a slide on a scrolling list"
# an L of its own on a moving list is still one.
ell_x, ell_y = ease(0, 100, 15) + [100] * 15, [0] * 15 + ease(0, 100, 15)
ell_on = [{**still, "root/list": (0, y, 400, 100, 1), "root/list/chevron": (100 + x, y + 10 + dy, 10, 10, 1)}
for y, x, dy in zip(ease(300, 200, 30), ell_x, ell_y)]
assert "dog-leg" in kinds(scroll[:5] + ell_on + hold(ell_on[-1], 10)), "across, then down, on a moving list"
# a drift out and back that rests a frame where it turns is still one motion.
drift = hold(at(100, 100), 5) + [at(x, 100) for x in ease(100, 97.5, 6)] + hold(at(97.5, 100), 2) + [at(x, 100) for x in ease(97.5, 100, 12)] + hold(at(100, 100), 10)
assert "reversal" in kinds(drift), "out and back with a rest at the turn"
# in a list following its growing end, 2 pt a frame up: judged against the scroll.
def scrolling(own, flags=0, told=True):
frames = []
for k in range(140):
t = min(max(k - 40, 0), 60)
frames.append({**still, "root/list/node": (100, 300 + own(t) - 2 * t, 40, 40, 1, *([(0, 2 * t)] if told else []))})
return kinds(frames, flags={"root/list/node": flags})
glide = lambda k: 60 * (1 - math.exp(-k / 8))
assert "reversal" in scrolling(glide, told=False), "on screen the glide and the scroll turn back"
assert not {"reversal", "jiggle", "overshoot", "stall"} & set(scrolling(glide)), "against the scroll it is one glide"
assert not {"reversal", "jiggle", "overshoot", "stall"} & set(scrolling(glide, analyze.SCROLLING))
wobble = lambda k: 2.5 * math.sin(k * 0.6)
assert "jiggle" not in scrolling(wobble, told=False), "on screen it only ever rises"
assert "jiggle" in scrolling(wobble), "against the scroll it wobbles"
assert "jiggle" in scrolling(wobble, analyze.SCROLLING), "a scroll that moves doesn't excuse it"
# jumps are judged on what shows. A fold drops 900 pt above a 200 pt viewport in one frame
# with the scroll offset: the content's and the fold's tops and heights step, while what
# shows stays put.
view = {"root/list": (0, 0, 400, 200)}
def frame(content, fold, extra=None):
return {**still, "root/list": (0, *content, 1), "root/list/fold": (0, *fold, 1),
"root/list/fold/a": (0, 60, 400, 40, 1), "root/list/after": (0, 150, 400, 100, 1), **(extra or {})}
drop = hold(frame((-1100, 400, 1500), (-900, 400, 1200)), 40) + hold(frame((-200, 400, 600), (0, 400, 300)), 40)
found = set(kinds(drop, clips=view))
assert not {"jump", "step", "sibling-jump"} & found, f"nothing that shows moves: {found}"
# Shut from its stuck header, the fold drops its rows above the window and its top comes
# in from the window's edge, gliding down from where it showed.
def shut(top):
return {**still, "root/list": (0, top - 1100, 400, 1500, 1), "root/list/fold": (0, top, 400, 200 - top, 1),
"root/list/after": (0, 200, 400, 100, 1)}
glide = hold(shut(-900), 40) + [shut(t) for t in (13, 43, 73, 100, 120, 135, 145, 150)] + hold(shut(150), 40)
found = set(kinds(glide, clips=view))
assert not {"jump", "step", "sibling-jump"} & found, f"it glides from where it showed: {found}"
# A row that shows, teleported 100 pt in the scrolled list, jumps.
row = lambda y: {"root/list/fold/row": (0, y, 400, 30, 1)}
tele = hold(frame((-200, 400, 600), (0, 400, 300), row(20)), 40) + hold(frame((-200, 400, 600), (0, 400, 300), row(120)), 40)
assert "jump" in kinds(tele, clips=view), "a row that shows jumps"
# The content jumps 100 pt and the rows that show with it.
shift = lambda dy: {**still, "root/list": (0, -600 + dy, 400, 2000, 1), "root/list/a": (0, 20 + dy, 400, 30, 1), "root/list/b": (0, 60 + dy, 400, 30, 1)}
assert "jump" in kinds(hold(shift(0), 40) + hold(shift(100), 40), clips=view), "the content jumps with what shows of it"
# The offset jumps 40 pt with no input: the first row, just under the viewport, pops 40 pt
# into view, though nothing showed on both frames. Under a key, it's the key's scroll.
pad = lambda dy: {**still, "root/list": (0, -dy, 400, 1100, 1), "root/list/row": (0, 300 - dy, 400, 40, 1)}
padded = hold(pad(0), 40) + hold(pad(40), 40)
port, scroll = {"root/list": (0, 0, 400, 300)}, {"root/list": analyze.SCROLLING, "root/list/row": analyze.SCROLLING}
assert "jump" in kinds(padded, flags=scroll, clips=port), "content that teleports a row into view"
end = [{"t": 40 / 120, "type": "key", "name": "End"}]
assert not {"jump", "step"} & set(kinds(padded, end, flags=scroll, clips=port)), "a key's scroll"
glide = hold(pad(0), 40) + [pad(y) for y in ease(0, 40, 20)] + hold(pad(40), 20)
assert not {"jump", "step"} & set(kinds(glide, flags=scroll, clips=port)), "a scroll that glides"
# one steady speed: a retarget that drops part of its speed for a frame stalls; one that
# keeps its speed and only pulls harder toward a farther target doesn't.
xs = ease(100, 200, 20)
slow = xs[7] + 0.3 * (xs[8] - xs[7])
dip = xs[:8] + [slow] + [slow + v for v in ease(0, 230 - slow, 24)]
assert "stall" in kinds(hold(at(100, 100), 5) + [at(x, 100) for x in dip] + hold(at(dip[-1], 100), 10)), "a re-aim that lost its speed for a frame"
def spring(x, v, target, n, k=320.0, c=36.0, dt=1 / 120):
out = []
for _ in range(n):
v += (k * (target - x) - c * v) * dt
x += v * dt
out.append(x)
return out, v
first, v = spring(100.0, 0.0, 200.0, 10)
retarget, _ = spring(first[-1], v, 240.0, 60)
assert "stall" not in kinds(hold(at(100, 100), 5) + [at(x, 100) for x in first + retarget] + hold(at(retarget[-1], 100), 10)), "a retarget at its own speed"
assert "stall" not in kinds(straight), "a straight eased move"
# A scroll bar's thumb follows the wheel: a wheel that slows to a stop and a fling that
# picks it up again is the hand's speed, not a lost retarget.
wheeled = [{**at(x, 100), "@ev": [f"wheel {v:.1f}"]} for x, v in zip(dip[:9], range(9, 0, -1))]
wheeled[8]["@ev"] = ["fling 1800"]
flung = hold(at(100, 100), 5) + wheeled + [at(x, 100) for x in dip[9:]] + hold(at(dip[-1], 100), 10)
assert "stall" not in kinds(flung), "the thumb slows and picks up with the wheel"
# nothing unmounts above opacity 0.
half = hold({**still, "root/chip": (10, 10, 50, 20, 1)}, 5) + [{**still, "root/chip": (10, 10, 50, 20, op)} for op in ease(1, 0.4, 6)] + hold(still, 10)
assert "cut-exit" in kinds(half), "a fade cut short at 0.4"
full = hold({**still, "root/chip": (10, 10, 50, 20, 1)}, 5) + [{**still, "root/chip": (10, 10, 50, 20, op)} for op in ease(1, 0, 12)] + hold(still, 10)
assert not {"cut-exit", "pop-out"} & set(kinds(full)), "a fade to 0, then gone"
# an instant scroll (wrapping to a long list's end) mounts the rows it lands on and drops the
# rows it left: the scroll, not pops. The same swap with no scroll pops.
top = {**still, "root/list/a": (0, 0, 200, 30, 1), "root/list/b": (0, 30, 200, 30, 1)}
end = {**still, "root/list/y": (0, 0, 200, 30, 1), "root/list/z": (0, 30, 200, 30, 1)}
swap = hold(top, 10) + hold(end, 20)
assert {"pop-in", "pop-out"} <= set(kinds(swap)), "rows swapped in place"
assert not {"pop-in", "pop-out"} & set(kinds(swap, flags={"root/list/y": 4 | 8, "root/list/z": 4 | 8})), "rows scrolled in"
# stable identity: closing row a must remove a, not b (index keys remove the last row).
rows = lambda *ks: {**still, **{f"root/list/{k}": (0, 30 * i, 200, 30, 1) for i, k in enumerate(ks)}, "root/list": (0, 0, 200, 90, 1)}
close = [{"t": 0.1, "type": "tap", "key": "a/close", "expect": "leaves", "element": "root/list/a"}]
assert "wrong-exit" in kinds(hold(rows("a", "b", "c"), 12) + hold(rows("a", "b"), 40), close), "the last row left instead"
assert "wrong-exit" not in kinds(hold(rows("a", "b", "c"), 12) + hold(rows("b", "c"), 40), close), "row a left"
# smooth: a release that lands in one frame snaps.
release = [{"t": 0.1, "type": "drag", "key": "card", "dx": 50, "dur": 0.1, "expect": "smooth", "element": "root/card"}]
assert "snap" in kinds(hold(at(100, 100), 30) + hold(at(200, 100), 40), release), "a landing in one frame"
assert "snap" not in kinds(hold(at(100, 100), 30) + [at(x, 100) for x in ease(100, 200, 24)] + hold(at(200, 100), 20), release), "a glide"
assert not jumps(sheen((1.0, 0.0), (1.0, 5.0))), "a wrap from clipped away isn't a jump"
assert not jumps(sheen((0.0, 10.0), (1.0, 5.0))), "a wrap from transparent isn't a jump"
assert not jumps(sheen((1.0, 10.0), (0.0, 10.0))), "a wrap into transparent isn't a jump"
found = jumps(sheen((1.0, 10.0), (1.0, 10.0)))
assert len(found) == 1 and found[0]["at"] == "10", f"a wrap in sight is: {found}"
# scale-settle: a <= 100 ms pixel-snap settle right after motion isn't idle; a cold or long one is.
def scale_settle_trace(settle_frames, preceded_by_motion=True):
lines = [json.dumps({"width": 200, "height": 100, "hz": 120})]
lines.append(json.dumps({"m": [{"id": 1, "nm": "stage"}], "e": [[1, 10, 10, 40, 20, 1, 0, 0]], "quality": {"animating": False, "why": []}}))
if preceded_by_motion:
lines.append(json.dumps({"e": [[1, 14, 10, 64, 32, 1, 0, 1]], "tk": [[1, "scale", 1]], "quality": {"animating": True, "why": ["tracks"]}}))
for _ in range(settle_frames):
lines.append(json.dumps({"quality": {"animating": True, "why": ["scale-settle"]}}))
lines.append(json.dumps({"quality": {"animating": False, "why": []}}))
f = tempfile.NamedTemporaryFile("w", suffix=".jsonl", delete=False)
f.write("\n".join(lines) + "\n")
f.close()
try:
return [x["kind"] for x in analyze.analyze(f.name)["findings"]]
finally:
os.unlink(f.name)
assert "idle-frames" not in scale_settle_trace(12, True), "100 ms scale-settle after motion"
assert "idle-frames" in scale_settle_trace(20, True), "overrun scale-settle"
assert "idle-frames" in scale_settle_trace(6, False), "cold scale-settle"
print("ok")
if __name__ == "__main__":
main()
+93
View File
@@ -0,0 +1,93 @@
"""Retargets split trajectories, never excuse bad motion between destinations."""
import json
import os
import unittest
import analyze
from test_analyze import scene
class Retargets(unittest.TestCase):
def findings(self, xs, goals=None, parent=None, opacity=1, flags=None):
frames = [{"root": (0, 0, 400, 400, 1), "root/piece": (x, 40, 10, 10, opacity)} for x in xs]
frames = [frames[0]] * 80 + frames + [frames[-1]] * 80
path = scene(frames, flags=flags)
try:
with open(path) as f:
rows = [json.loads(line) for line in f]
for k, mask in (goals or {}).items():
rows[81 + k]["retarget"] = [[1 if parent else 2, mask, mask if parent == "scale" else mask & 3]]
with open(path, "w") as f:
f.write("\n".join(json.dumps(row) for row in rows))
return {f["kind"] for f in analyze.analyze(path)["findings"]}
finally:
os.unlink(path)
def test_a_new_destination_is_not_one_out_and_back(self):
xs = [40, 42, 44, 46, 48, 50, 48, 46, 44, 42, 40]
self.assertIn("reversal", self.findings(xs))
self.assertNotIn("reversal", self.findings(xs, {6: 1}))
# A different property's goal cannot excuse this axis.
self.assertIn("reversal", self.findings(xs, {6: 2}))
def test_parent_motion_carries_children_but_size_does_not(self):
xs = [40, 42, 44, 46, 48, 50, 48, 46, 44, 42, 40]
self.assertNotIn("reversal", self.findings(xs, {6: 15}, parent="scale"))
self.assertIn("reversal", self.findings(xs, {6: 4}, parent="size"))
def test_retarget_preserves_decelerating_incoming_velocity(self):
xs = [40, 44, 48, 51, 53, 54, 53, 51, 48, 44, 40, 36, 33, 31, 30]
self.assertNotIn("reversal", self.findings(xs, {3: 1}))
xs[4:6] = [55, 60] # Accelerates away instead of braking.
self.assertIn("reversal", self.findings(xs, {3: 1}))
def test_bad_motion_before_another_retarget_is_still_checked(self):
xs = [40, 44, 48, 52, 50, 48, 46, 44, 42, 40, 38, 36, 34, 32]
self.assertIn("reversal", self.findings(xs, {10: 1}))
def test_a_jump_on_the_retarget_frame_still_fails(self):
self.assertIn("jump", self.findings([40, 40, 40, 100, 100, 100], {3: 1}))
def test_a_retarget_that_loses_velocity_still_fails(self):
self.assertIn("stall", self.findings([40, 43, 46, 46.2, 49.2, 52.2, 55.2], {3: 1}))
def thumb(self, ys, goal=None, flags=0):
"""A scroll bar's thumb beside a scrolled list, with `goal` = (frame, name) retargeted."""
def at(y):
return {"area": (0, 0, 400, 400, 1), "area/view": (0, 0, 390, 400, 1), "area/view/list": (0, -50, 390, 900, 1, (0, 50)),
"area/bar": (390, 0, 10, 400, 1), "area/bar/thumb": (392, y, 6, 120, 1), "other": (0, 0, 10, 10, 1)}
frames = [at(ys[0])] * 80 + [at(y) for y in ys] + [at(ys[-1])] * 80
path = scene(frames, flags={"area/bar/thumb": flags})
try:
with open(path) as f:
rows = [json.loads(line) for line in f]
ids = {m["nm"]: m["id"] for m in rows[1]["m"]}
if goal:
rows[81 + goal[0]]["retarget"] = [[ids[goal[1]], 8, 0]]
with open(path, "w") as f:
f.write("\n".join(json.dumps(row) for row in rows))
return {f["kind"] for f in analyze.analyze(path)["findings"]}
finally:
os.unlink(path)
def test_a_thumb_brakes_when_the_list_it_reads_retargets(self):
ys = [40, 44, 48, 51, 53, 54, 53, 51, 48, 44, 40, 36, 33, 31, 30]
self.assertIn("reversal", self.thumb(ys, flags=1))
self.assertTrue({"reversal", "dog-leg"}.isdisjoint(self.thumb(ys, (3, "area/view/list"), flags=1)))
# Only the content it reads moves its destination.
self.assertIn("reversal", self.thumb(ys, (3, "other"), flags=1))
def test_a_placed_readout_has_no_shape_of_its_own(self):
ys = [40, 44, 48, 51, 53, 54, 53, 51, 48, 44, 40, 36, 33, 31, 30]
self.assertNotIn("reversal", self.thumb(ys, flags=3 << 8))
# Springing, it answers for its own path.
self.assertIn("reversal", self.thumb(ys, flags=3 << 8 | 1))
def test_invisible_or_intentionally_instant_retargets_are_not_stalls(self):
xs = [40, 43, 46, 46.2, 49.2, 52.2, 55.2]
self.assertNotIn("stall", self.findings(xs, {3: 1}, opacity=0))
self.assertNotIn("stall", self.findings(xs, {3: 1}, flags={"root/piece": 1 << 8}))
if __name__ == "__main__":
unittest.main()
+57
View File
@@ -0,0 +1,57 @@
#!/usr/bin/env python3
"""Prints one element's per-frame state from a Rune trace: frame, t, rect, opacity, flags,
visible rect, and the tracks sampled for it.
Usage: scripts/motion-audit/track.py TRACE.jsonl NAME-SUBSTRING [FROM [TO]] [--all-names]
"""
import json
import sys
def main():
path, needle = sys.argv[1], sys.argv[2]
rest = [a for a in sys.argv[3:] if not a.startswith("--")]
lo = int(rest[0]) if rest else 0
hi = int(rest[1]) if len(rest) > 1 else 10**9
names, state, alive = {}, {}, set()
with open(path) as f:
f.readline()
frames = [json.loads(l) for l in f if l.strip()]
if "--all-names" in sys.argv:
for fr in frames:
for m in fr.get("m", []):
if needle in m["nm"]:
names[m["id"]] = m["nm"]
for id, n in names.items():
print(id, n)
return
for k, fr in enumerate(frames):
for m in fr.get("m", []):
names[m["id"]] = m["nm"]
rows = {r[0]: r for r in fr.get("e", [])}
for id, r in rows.items():
state[id] = r
alive.add(id)
gone = set(fr.get("g", []))
tk = {}
for who, prop, active in fr.get("tk", []):
tk.setdefault(who, []).append(prop + ("" if active else "·"))
if not (lo <= k <= hi):
alive -= gone
continue
for id in sorted(set(rows) | (gone & alive)):
if needle not in names.get(id, ""):
continue
if id in gone:
print(f"{k:4} {fr['t']:8.1f} {names[id][-50:]:<50} GONE")
continue
r = state[id]
vis = f" vis={r[8:12]}" if len(r) >= 12 else ""
q = fr.get("quality", {})
print(f"{k:4} {fr['t']:8.1f} {names[id][-50:]:<50} x={r[1]:<8} y={r[2]:<8} w={r[3]:<8} h={r[4]:<8} op={r[5]:<6} fl={r[7]}{vis} tk={tk.get(id, '')} {'+'.join(q.get('why', []))}")
alive -= gone
if __name__ == "__main__":
main()
+84
View File
@@ -0,0 +1,84 @@
# Native presentation pacing
Timestamp-only probe on a GUI Mac. No screen capture. It measures `nextDrawable` entry to
positive Metal `presentedTime`, using the overlay team's steady-state endpoint.
Three batches per mode, two-second warmup, then three three-second intervals;
the summary is the median of nine interval medians.
Build with `cargo build --profile perf -j 2 -p rune --example pacing_overlay --example pacing`
on the Mac that runs the probe, and run jobs one at a time. Pass the
`target/perf/examples/` executable path; the runners refuse binaries from any
other profile.
```sh
python3 scripts/native-pacing/run.py <out> <pacing_overlay> \
--reference <path to a reference app executable>
```
The runner checks it is on the expected GUI host, holds a GUI lock file, bounds
app lifetimes, and removes its instrumentation dylib. `--modes native` selects only
the continuous Rune workload; the default tests injected redraws and native
animation. The reference app is optional and its order alternates between batches.
Rune uses a 680×160-point overlay. Native mode animates opacity continuously;
injected mode uses a static view with an AppKit 60-Hz redraw timer. The reference
app runs on a different-sized surface.
Results include executable hashes, raw callback logs, drawable waits, interval
medians, acquisition gaps, and counts of excluded zero presentation timestamps.
These excluded callbacks are not a dropped-frame count. A timeout is a failed
run and cannot serve as a complete performance baseline.
The `pacing` example separately exercises state commits, idle, hide/show and
shutdown. Run it under the same GUI lock with `--native --trace <file>`, then
check the file with `python3 scripts/check-native-pacing.py <file>`.
## Isolated refresh-rate experiments
Use a fresh output directory for each experiment:
```sh
# Same production executable; one change at a time, in this order.
python3 scripts/native-pacing/run.py <out-ca> <pacing_overlay> --modes native --display-link ca
python3 scripts/native-pacing/run.py <out-two> <pacing_overlay> --modes native --drawables 2
python3 scripts/native-pacing/run.py <out-unsynced> <pacing_overlay> --modes native --display-sync 0
```
`clock-probe.m` interposes CV callback registration/start/stop. Its default mode
counts real CV callbacks. CA mode supplies the same Rune callback from an NSView
`CADisplayLink` with `CAFrameRateRangeMake(80, 120, 120)` on macOS 14+. This adapter
selects the fixture's visible panel and supports this single-surface workload;
it is not a general replacement for Rune's native display-link implementation.
Layer overrides affect Rune only. An optional reference app keeps its settings.
For the admission-guard comparison, apply `admission-probe.patch` in a disposable
checkout, generate a new source manifest, and rebuild the example. Run `--guard production` then `--guard no-half` on that same executable.
The latter removes only elapsed-half-refresh admission, retaining stale-target
and duplicate-target rejection. The runner requires matching diagnostic output.
Counters are printed after stopping the link, not in the callback. Revert the
patch and rebuild when finished. Never ship this patch; it exists to reproduce
the experiment and intentionally leaves the original unit-test helper unused.
`acquisition_hz` uses `nextDrawable` entry times. `presentation_hz` uses distinct,
positive `presentedTime` timestamps for frames acquired in the nine-second sample.
Callback Hz and guard counts cover the full app run, including warmup. Guard
reason counters can overlap; they are not an exhaustive partition of callbacks
because pending callbacks coalesce. The summary includes the selected overrides
and binary hash. Raw logs retain the actual layer settings.
With display sync disabled, positive presentation timestamps do not establish
tear-free 120-Hz scanout. Apple's API explicitly allows tearing in this mode.
## Findings
With the default synced layer, the tested overlay presents at about 60 Hz on a
120-Hz display, although CVDisplayLink and NSView CADisplayLink both deliver
about 120 callbacks/s. Two drawables lower latency but keep 60-Hz presentation.
Disabling display sync raises positive presentations above 100/s, which does not
prove tear-free output. Removing the half-refresh admission guard moves waiting
into `nextDrawable` without raising presentation frequency, and breaks the
half-refresh bound: keep the guard. The evidence points to synced drawable
backpressure, not callback rate.
`refresh-probe.m` then found the cause of the 60-Hz cap: Low Power Mode holds a
ProMotion panel at 60 Hz while both display links and `NSScreen` still report
120 Hz. `crates/rune/src/platform/display_link.rs` paces submissions at that cap.
@@ -0,0 +1,59 @@
diff --git a/crates/rune/src/display_link.rs b/crates/rune/src/display_link.rs
index fc25f6e..25823f9 100644
--- a/crates/rune/src/display_link.rs
+++ b/crates/rune/src/display_link.rs
@@ -25,6 +25,8 @@ pub(crate) struct DisplayLink {
last_target: Option<Instant>,
display: Option<u32>,
running: bool,
+ probe_no_half: bool,
+ probe_counts: [u64; 5],
}
unsafe extern "C-unwind" fn tick(
@@ -70,7 +72,8 @@ impl DisplayLink {
});
let status = unsafe { link.set_output_callback(Some(tick), (&mut *callback as *mut Callback).cast()) };
if status != 0 { eprintln!("display link callback failed: {status}"); return None; }
- let mut pacing = Self { link, callback, last_present: None, last_target: None, display: None, running: false };
+ let mut pacing = Self { link, callback, last_present: None, last_target: None, display: None, running: false,
+ probe_no_half: std::env::var("STEADY_GUARD").as_deref() == Ok("no-half"), probe_counts: [0; 5] };
pacing.update_display(window);
Some(pacing)
}
@@ -93,13 +96,20 @@ impl DisplayLink {
self.running = true;
}
let host_target = self.callback.target.swap(0, Ordering::Acquire);
- if host_target == 0 { return None; }
+ if host_target == 0 { self.probe_counts[0] += 1; return None; }
let now = Instant::now();
let target = target_time(now, CVGetCurrentHostTime(), host_target, self.callback.host_frequency);
let period = Duration::from_nanos(self.callback.period_ns.load(Ordering::Relaxed));
// A late render followed by an on-time tick must skip, not submit two frames
// together. Also discard stale callbacks after main-thread stalls.
- if !permits(self.last_present, self.last_target, target, now, period) { return None; }
+ let stale = now >= target;
+ let duplicate = self.last_target.is_some_and(|last| target <= last);
+ let short = self.last_present.is_some_and(|last| now.saturating_duration_since(last) < period / 2);
+ self.probe_counts[1] += u64::from(stale);
+ self.probe_counts[2] += u64::from(duplicate);
+ self.probe_counts[3] += u64::from(short);
+ if stale || duplicate || (!self.probe_no_half && short) { return None; }
+ self.probe_counts[4] += 1;
self.last_target = Some(target);
Some(target)
}
@@ -110,6 +120,12 @@ impl DisplayLink {
pub(crate) fn stop(&mut self) {
if self.running { self.link.stop(); self.running = false; }
+ if self.probe_counts[4] > 0 {
+ eprintln!("steady guard mode={} empty={} stale={} duplicate={} short={} admitted={}",
+ if self.probe_no_half { "no-half" } else { "production" }, self.probe_counts[0], self.probe_counts[1],
+ self.probe_counts[2], self.probe_counts[3], self.probe_counts[4]);
+ self.probe_counts = [0; 5];
+ }
self.callback.target.store(0, Ordering::Relaxed);
}
}
+78
View File
@@ -0,0 +1,78 @@
// Diagnostic adapter only: keep Rune's admission/render path unchanged while swapping
// its CV callback source for an NSView CADisplayLink. Not linked into shipping Rune.
#import <AppKit/AppKit.h>
#import <QuartzCore/QuartzCore.h>
#import <CoreVideo/CoreVideo.h>
@interface RuneClockProbe : NSObject
@property(nonatomic) CVDisplayLinkRef cv;
@property(nonatomic) CVDisplayLinkOutputCallback callback;
@property(nonatomic) void *context;
@property(nonatomic, strong) CADisplayLink *ca;
@property(nonatomic) unsigned count;
@property(nonatomic) double first;
@property(nonatomic) double last;
@end
@implementation RuneClockProbe
- (void)tick:(CADisplayLink *)link {
double now = CACurrentMediaTime();
CVTimeStamp at = {0}, target = {0};
at.hostTime = CVGetCurrentHostTime();
target.hostTime = at.hostTime + (int64_t)((link.targetTimestamp - now) * CVGetHostClockFrequency());
target.videoTimeScale = 1000000000;
target.videoRefreshPeriod = (int64_t)((link.targetTimestamp - link.timestamp) * 1e9);
target.flags = kCVTimeStampHostTimeValid | kCVTimeStampVideoRefreshPeriodValid;
CVOptionFlags flags = 0;
if (!self.count++) self.first = now;
self.last = now;
self.callback(self.cv, &at, &target, 0, &flags, self.context);
}
@end
static NSMutableDictionary<NSValue *, RuneClockProbe *> *clocks;
static CVReturn counted(CVDisplayLinkRef link, const CVTimeStamp *now, const CVTimeStamp *target,
CVOptionFlags in, CVOptionFlags *out, void *context) {
RuneClockProbe *probe = (__bridge RuneClockProbe *)context;
double at = CACurrentMediaTime();
if (!probe.count++) probe.first = at;
probe.last = at;
return probe.callback(link, now, target, in, out, probe.context);
}
static CVReturn probeSet(CVDisplayLinkRef link, CVDisplayLinkOutputCallback callback, void *context) {
if (!getenv("STEADY_CLOCK")) return CVDisplayLinkSetOutputCallback(link, callback, context);
if (!clocks) clocks = [NSMutableDictionary new];
RuneClockProbe *probe = [RuneClockProbe new];
probe.cv = link; probe.callback = callback; probe.context = context;
clocks[[NSValue valueWithPointer:link]] = probe;
return CVDisplayLinkSetOutputCallback(link, counted, (__bridge void *)probe);
}
static CVReturn probeStart(CVDisplayLinkRef link) {
RuneClockProbe *probe = clocks[[NSValue valueWithPointer:link]];
if (!getenv("STEADY_CA") || !probe) return CVDisplayLinkStart(link);
if (@available(macOS 14.0, *)) {
NSView *view = nil;
for (NSWindow *window in NSApp.windows)
if ([window isKindOfClass:NSPanel.class] && window.visible) { view = window.contentView; break; }
if (!view) return kCVReturnError;
probe.ca = [view displayLinkWithTarget:probe selector:@selector(tick:)];
probe.ca.preferredFrameRateRange = CAFrameRateRangeMake(80, 120, 120);
[probe.ca addToRunLoop:NSRunLoop.mainRunLoop forMode:NSRunLoopCommonModes];
return kCVReturnSuccess;
}
return kCVReturnError;
}
static CVReturn probeStop(CVDisplayLinkRef link) {
RuneClockProbe *probe = clocks[[NSValue valueWithPointer:link]];
CVReturn status = kCVReturnSuccess;
if (probe.ca) { [probe.ca invalidate]; probe.ca = nil; }
else status = CVDisplayLinkStop(link);
if (probe.count > 1) fprintf(stderr, "steady clock source=%s callbacks=%u hz=%.3f\n",
getenv("STEADY_CA") ? "ca" : "cv", probe.count, (probe.count - 1) / (probe.last - probe.first));
probe.count = 0;
return status;
}
#define INTERPOSE(new, old) __attribute__((used)) static struct { const void *replacement; const void *original; } \
interpose_##old __attribute__((section("__DATA,__interpose"))) = { (const void *)&new, (const void *)&old }
INTERPOSE(probeSet, CVDisplayLinkSetOutputCallback);
INTERPOSE(probeStart, CVDisplayLinkStart);
INTERPOSE(probeStop, CVDisplayLinkStop);
+77
View File
@@ -0,0 +1,77 @@
"""Pro-only, no capture. Post-commit cadence of the `pacing` example under /tmp/pro-gui.lock.
python3 scripts/native-pacing/commit-probe.py <out> <pacing executable> [runs]
Each burst starts after an idle gap. Prints the first acquisition (`nextDrawable` entry) and
positive Metal presentedTime intervals of each burst, plus totals over all bursts.
"""
import fcntl
import json
import os
import re
import socket
import statistics
import subprocess
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from perf_binary import perf_binary
assert socket.gethostname().startswith("Kits-Shiny-Computer"), "Pro only"
out, pacing = Path(sys.argv[1]).resolve(), perf_binary(sys.argv[2])
runs = int(sys.argv[3]) if len(sys.argv) > 3 else 3
out.mkdir(parents=True, exist_ok=True)
library = out / "steady-probe.dylib"
subprocess.run(["clang", "-dynamiclib", "-fobjc-arc", "-fblocks", "-O2", str(Path(__file__).with_name("steady-probe.m")),
"-framework", "AppKit", "-framework", "QuartzCore", "-framework", "Metal", "-o", str(library)], check=True)
env = {k: v for k, v in os.environ.items() if not k.startswith("STEADY_")}
env["DYLD_INSERT_LIBRARIES"] = str(library)
def gaps(times):
return [round((b - a) * 1000, 1) for a, b in zip(times, times[1:])]
summary = []
with open("/tmp/pro-gui.lock", "a") as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
try:
for run in range(runs):
log = out / f"{run}-pacing.log"
trace = out / f"{run}-pacing.jsonl"
with log.open("w") as output:
subprocess.run([str(pacing), "--native", "--trace", str(trace)], env=env, stdout=output,
stderr=subprocess.STDOUT, timeout=60, check=True)
rows = [{k: float(v) for k, v in re.findall(r"(\w+)=([\d.]+)", line)}
for line in log.read_text().splitlines() if line.startswith("steady frame ")]
rows.sort(key=lambda r: r["entered"])
bursts, current = [], []
for row in rows:
if current and row["entered"] - current[-1]["entered"] > 0.05:
bursts.append(current)
current = []
current.append(row)
bursts.append(current)
for index, burst in enumerate(bursts[1:], 1):
presented = sorted(r["presented"] for r in burst if r["presented"] > 0)
result = dict(run=run, burst=index, frames=len(burst), zero=sum(r["presented"] == 0 for r in burst),
acquisition_gaps_ms=gaps([r["entered"] for r in burst]),
presentation_gaps_ms=gaps(presented),
latency_ms=round(statistics.median((r["presented"] - r["entered"]) * 1000
for r in burst if r["presented"] > 0), 1),
wait_ms=round(statistics.median((r["acquired"] - r["entered"]) * 1000 for r in burst), 2))
summary.append(result)
print(json.dumps(result), flush=True)
finally:
library.unlink(missing_ok=True)
acquisition = [g for r in summary for g in r["acquisition_gaps_ms"]]
presentation = [g for r in summary for g in r["presentation_gaps_ms"]]
first = [g for r in summary for g in r["acquisition_gaps_ms"][:4]]
total = dict(bursts=len(summary), frames=sum(r["frames"] for r in summary),
median_acquisition_ms=statistics.median(acquisition), median_presentation_ms=statistics.median(presentation),
first_four_acquisition_gaps_under_12ms=sum(g < 12 for g in first), first_four_acquisition_gaps=len(first),
presentation_gaps_under_12ms=sum(g < 12 for g in presentation),
median_latency_ms=statistics.median(r["latency_ms"] for r in summary))
(out / "summary.json").write_text(json.dumps(dict(total=total, bursts=summary), indent=2) + "\n")
print(json.dumps(total), flush=True)
+150
View File
@@ -0,0 +1,150 @@
// Minimal native CAMetalLayer presenter, independent of Rune and wgpu. Prints the display's
// power and refresh state, then measures positive presentedTime cadence and the screen's
// framebuffer-update cadence for one presentation variant.
// refresh-probe <present|transaction|minduration|unsynced> <sub|backing> <drawables> <seconds>
#import <AppKit/AppKit.h>
#import <QuartzCore/QuartzCore.h>
#import <Metal/Metal.h>
#import <CoreVideo/CoreVideo.h>
static NSString *mode, *host;
static int drawables;
static double seconds;
static CAMetalLayer *layer;
static id<MTLCommandQueue> queue;
static NSMutableArray<NSNumber *> *presented, *updates, *callbacks;
static double started;
static NSScreen *screen;
static void summary(NSString *name, NSArray<NSNumber *> *times) {
NSArray<NSNumber *> *sorted = [times sortedArrayUsingSelector:@selector(compare:)];
NSMutableDictionary<NSNumber *, NSNumber *> *ticks = [NSMutableDictionary dictionary];
double first = 0, last = 0;
for (NSUInteger i = 1; i < sorted.count; i++) {
double gap = (sorted[i].doubleValue - sorted[i - 1].doubleValue) * 1000;
NSNumber *key = @(lround(gap / (1000.0 / 120)));
ticks[key] = @(ticks[key].intValue + 1);
}
if (sorted.count > 1) { first = sorted.firstObject.doubleValue; last = sorted.lastObject.doubleValue; }
NSMutableString *histogram = [NSMutableString string];
for (NSNumber *key in [ticks.allKeys sortedArrayUsingSelector:@selector(compare:)])
[histogram appendFormat:@" %@t:%@", key, ticks[key]];
printf("probe %s n=%lu hz=%.2f gaps_in_120hz_ticks=%s\n", name.UTF8String, (unsigned long)sorted.count,
sorted.count > 1 ? (sorted.count - 1) / (last - first) : 0, histogram.UTF8String);
}
@interface Target : NSObject
@end
@implementation Target
- (void)tick:(CADisplayLink *)link {
double now = CACurrentMediaTime();
if (now - started > seconds) {
[link invalidate];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC / 2), dispatch_get_main_queue(), ^{
printf("probe variant mode=%s host=%s drawables=%d presents_with_transaction=%d display_sync=%d opaque=%d format=%lu\n",
mode.UTF8String, host.UTF8String, drawables, layer.presentsWithTransaction,
layer.displaySyncEnabled, layer.opaque, (unsigned long)layer.pixelFormat);
summary(@"callbacks", callbacks);
summary(@"positive_presentations", presented);
summary(@"screen_updates", updates);
exit(0);
});
return;
}
[callbacks addObject:@(now)];
if (@available(macOS 12.0, *)) {
NSNumber *update = @(screen.lastDisplayUpdateTimestamp);
if (update.doubleValue > 0 && ![updates.lastObject isEqual:update]) [updates addObject:update];
}
id<CAMetalDrawable> drawable = [layer nextDrawable];
if (!drawable) return;
BOOL measured = now - started > 1;
[drawable addPresentedHandler:^(id<MTLDrawable> d) {
if (measured && d.presentedTime > 0) dispatch_async(dispatch_get_main_queue(), ^{ [presented addObject:@(d.presentedTime)]; });
}];
MTLRenderPassDescriptor *pass = [MTLRenderPassDescriptor renderPassDescriptor];
pass.colorAttachments[0].texture = drawable.texture;
pass.colorAttachments[0].loadAction = MTLLoadActionClear;
pass.colorAttachments[0].storeAction = MTLStoreActionStore;
double phase = fmod(now, 1.0);
pass.colorAttachments[0].clearColor = MTLClearColorMake(0.1 * phase, 0.3 * phase, 0.6 * phase, 0.6 + 0.3 * phase);
id<MTLCommandBuffer> buffer = [queue commandBuffer];
[[buffer renderCommandEncoderWithDescriptor:pass] endEncoding];
if ([mode isEqual:@"transaction"]) {
[buffer commit];
[buffer waitUntilScheduled];
[drawable present];
} else {
if ([mode isEqual:@"minduration"]) [buffer presentDrawable:drawable afterMinimumDuration:1.0 / 120];
else [buffer presentDrawable:drawable];
[buffer commit];
}
}
@end
int main(int argc, char **argv) {
@autoreleasepool {
mode = argc > 1 ? @(argv[1]) : @"present";
host = argc > 2 ? @(argv[2]) : @"sub";
drawables = argc > 3 ? atoi(argv[3]) : 3;
seconds = argc > 4 ? atof(argv[4]) : 5;
[NSApplication sharedApplication];
NSApp.activationPolicy = NSApplicationActivationPolicyAccessory;
screen = NSScreen.mainScreen;
CGDirectDisplayID display = [screen.deviceDescription[@"NSScreenNumber"] unsignedIntValue];
CGDisplayModeRef displayMode = CGDisplayCopyDisplayMode(display);
CVDisplayLinkRef cv;
CVDisplayLinkCreateWithCGDisplay(display, &cv);
CVTime nominal = CVDisplayLinkGetNominalOutputVideoRefreshPeriod(cv);
printf("probe system low_power=%d thermal=%ld max_fps=%ld min_interval_ms=%.3f max_interval_ms=%.3f granularity_ms=%.3f mode_hz=%.2f cv_nominal_ms=%.3f builtin=%d asleep=%d\n",
NSProcessInfo.processInfo.isLowPowerModeEnabled, (long)NSProcessInfo.processInfo.thermalState,
(long)screen.maximumFramesPerSecond, screen.minimumRefreshInterval * 1000, screen.maximumRefreshInterval * 1000,
screen.displayUpdateGranularity * 1000, CGDisplayModeGetRefreshRate(displayMode),
nominal.timeScale ? 1000.0 * nominal.timeValue / nominal.timeScale : 0, CGDisplayIsBuiltin(display),
CGDisplayIsAsleep(display));
CGDisplayModeRelease(displayMode);
CVDisplayLinkRelease(cv);
NSRect frame = NSMakeRect(NSMidX(screen.frame) - 340, NSMaxY(screen.visibleFrame) - 200, 680, 160);
NSPanel *panel = [[NSPanel alloc] initWithContentRect:frame
styleMask:NSWindowStyleMaskBorderless | NSWindowStyleMaskNonactivatingPanel backing:NSBackingStoreBuffered defer:NO];
panel.opaque = NO;
panel.backgroundColor = NSColor.clearColor;
panel.level = NSStatusWindowLevel;
panel.hasShadow = NO;
panel.ignoresMouseEvents = YES;
NSView *view = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, 680, 160)];
layer = [CAMetalLayer layer];
layer.device = MTLCreateSystemDefaultDevice();
layer.pixelFormat = MTLPixelFormatBGRA8Unorm_sRGB;
layer.opaque = NO;
layer.maximumDrawableCount = drawables;
layer.displaySyncEnabled = ![mode isEqual:@"unsynced"];
layer.presentsWithTransaction = [mode isEqual:@"transaction"];
layer.contentsScale = screen.backingScaleFactor;
layer.drawableSize = CGSizeMake(680 * screen.backingScaleFactor, 160 * screen.backingScaleFactor);
if ([host isEqual:@"backing"]) {
view.layer = layer;
view.wantsLayer = YES;
} else {
view.wantsLayer = YES;
layer.frame = view.layer.bounds;
[view.layer addSublayer:layer];
}
panel.contentView = view;
[panel orderFrontRegardless];
queue = [layer.device newCommandQueue];
presented = [NSMutableArray array];
updates = [NSMutableArray array];
callbacks = [NSMutableArray array];
started = CACurrentMediaTime();
CADisplayLink *link = [view displayLinkWithTarget:[Target new] selector:@selector(tick:)];
link.preferredFrameRateRange = CAFrameRateRangeMake(80, 120, 120);
[link addToRunLoop:NSRunLoop.mainRunLoop forMode:NSRunLoopCommonModes];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)((seconds + 5) * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
fprintf(stderr, "probe timeout\n");
exit(2);
});
[NSApp run];
}
}
+27
View File
@@ -0,0 +1,27 @@
"""Pro-only, no capture. Runs refresh-probe.m variants under /tmp/pro-gui.lock.
python3 scripts/native-pacing/refresh-probe.py <out> [mode:host:drawables ...]
"""
import fcntl
import socket
import subprocess
import sys
from pathlib import Path
assert socket.gethostname().startswith("Kits-Shiny-Computer"), "Pro only"
out = Path(sys.argv[1]).resolve()
out.mkdir(parents=True, exist_ok=True)
variants = sys.argv[2:] or ["present:sub:3", "transaction:backing:3", "minduration:sub:3", "present:sub:2", "unsynced:sub:3"]
binary = out / "refresh-probe"
subprocess.run(["clang", "-fobjc-arc", "-O2", str(Path(__file__).with_name("refresh-probe.m")),
"-framework", "AppKit", "-framework", "QuartzCore", "-framework", "Metal",
"-framework", "CoreVideo", "-Wno-deprecated-declarations", "-o", str(binary)], check=True)
with open("/tmp/pro-gui.lock", "a") as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
for variant in variants:
mode, host, drawables = variant.split(":")
result = subprocess.run([str(binary), mode, host, drawables, "5"], capture_output=True, text=True, timeout=30)
text = result.stdout + result.stderr
(out / f"{mode}-{host}-{drawables}.log").write_text(text)
print(text, flush=True)
binary.unlink(missing_ok=True)
+161
View File
@@ -0,0 +1,161 @@
"""Pro-only, no capture. Same 3 batches x 3 intervals and endpoint as the overlay team's probe.
Run through hash-checked GUI admission on the build queue. A matched 1360x320 Rune surface is
tested with both injected 60 Hz redraws and its real continuous animation scheduler.
"""
import argparse
import fcntl
import hashlib
import json
import math
import os
from pathlib import Path
import re
import socket
import signal
import statistics
import subprocess
import sys
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from perf_binary import perf_binary
parser = argparse.ArgumentParser()
parser.add_argument("out", type=Path)
parser.add_argument("rune", type=Path)
parser.add_argument("--reference", type=Path)
parser.add_argument("--modes", default="injected,native")
parser.add_argument("--display-link", choices=["cv", "ca"], default="cv")
parser.add_argument("--drawables", choices=["2", "3"])
parser.add_argument("--display-sync", choices=["0", "1"])
parser.add_argument("--guard", choices=["production", "no-half"], help="requires the diagnostic admission patch")
args = parser.parse_args()
assert socket.gethostname().startswith("Kits-Shiny-Computer"), "Pro only"
root, rune = args.out.resolve(), perf_binary(args.rune)
root.mkdir(parents=True, exist_ok=True)
def stats(values):
if not values:
return None
return dict(n=len(values), median=statistics.median(values),
p95=sorted(values)[math.ceil(len(values) * .95) - 1], min=min(values), max=max(values))
def parse(path, mode):
rows, configs, clocks, guards = [], [], [], []
for line in path.read_text().splitlines():
if line.startswith("steady config "):
configs.append(line)
if line.startswith("steady clock "):
clocks.append(line)
if line.startswith("steady guard "):
guards.append(line)
if line.startswith("steady frame "):
rows.append({k: float(v) for k, v in re.findall(r"(\w+)=([\d.]+)", line)})
visible = [r for r in rows if r["visible"] and r["window"] > 0]
assert visible, f"no visible frames: {path}"
start = min(r["entered"] for r in visible) + 2
selected = [r for r in visible if start <= r["entered"] < start + 9]
valid = [r for r in selected if r["presented"] >= r["acquired"]]
assert len(valid) >= 30, f"too few valid presentations: {path}"
intervals = [stats([(r["presented"] - r["entered"]) * 1000 for r in valid
if start + i * 3 <= r["entered"] < start + (i + 1) * 3]) for i in range(3)]
requests = [r for r in valid if 0 < r["requested"] <= r["entered"]]
entries = sorted(r["entered"] for r in selected)
gaps = [(b - a) * 1000 for a, b in zip(entries, entries[1:])]
presented = sorted(set(r["presented"] for r in valid))
presentation_gaps = [(b - a) * 1000 for a, b in zip(presented, presented[1:])]
if args.guard and mode != "reference":
assert guards and all(f"mode={args.guard} " in line for line in guards), "wrong admission-probe binary"
return dict(configs=configs, clocks=clocks, guards=guards, positive=len(valid), visible_callbacks=len(selected),
acquisition_hz=(len(entries)-1)/(entries[-1]-entries[0]),
presentation_hz=(len(presented)-1)/(presented[-1]-presented[0]),
presentation_gaps_ms=stats(presentation_gaps),
zero_callbacks=sum(r["presented"] == 0 for r in selected),
acquire_to_present_ms=stats([(r["presented"] - r["entered"]) * 1000 for r in valid]),
next_drawable_wait_ms=stats([(r["acquired"] - r["entered"]) * 1000 for r in valid]),
request_to_present_ms=stats([(r["presented"] - r["requested"]) * 1000 for r in requests]),
acquisition_gaps_ms=stats(gaps), sub_half_refresh_gaps=sum(g < 4.166666 - .01 for g in gaps),
interval_medians=intervals)
with open("/tmp/pro-gui.lock", "a") as lock:
def lock_timeout(_signal, _frame):
raise TimeoutError("Pro GUI lock remained busy for ten minutes")
signal.signal(signal.SIGALRM, lock_timeout)
signal.alarm(600)
fcntl.flock(lock, fcntl.LOCK_EX)
signal.alarm(0)
for pattern in ["[r]une-smoke/ci/Hex.app", "[s]crawl lab"]:
assert subprocess.run(["pgrep", "-f", pattern], capture_output=True).returncode != 0, pattern
for name in ["overlay-lab", "pacing_overlay"]:
assert subprocess.run(["pgrep", "-x", name], capture_output=True).returncode != 0, name
library = root / "steady-probe.dylib"
subprocess.run(["clang", "-dynamiclib", "-fobjc-arc", "-fblocks", "-O2",
str(Path(__file__).with_name("steady-probe.m")), str(Path(__file__).with_name("clock-probe.m")),
"-Wno-deprecated-declarations", "-framework", "AppKit", "-framework", "CoreVideo",
"-framework", "QuartzCore", "-framework", "Metal", "-o", str(library)], check=True)
env = dict(os.environ, DYLD_INSERT_LIBRARIES=str(library))
for key in ["OVERLAY_LAB_CONTROL", "OVERLAY_PROBE_REDRAW", "RUNE_OVERLAY_TRACE_INPUT",
"STEADY_RUNE_REDRAW", "STEADY_MAX_DRAWABLES", "STEADY_TRANSACTION", "PACING_NATIVE",
"STEADY_CA", "STEADY_CLOCK", "STEADY_DISPLAY_SYNC", "STEADY_GUARD"]:
env.pop(key, None)
modes = args.modes.split(",") + (["reference"] if args.reference else [])
assert all(mode in ["injected", "native", "reference"] for mode in modes)
results = []
(root / "load-before.txt").write_bytes(subprocess.check_output(["top", "-l", "1", "-n", "0"]))
try:
for batch in range(3):
for mode in (modes if batch % 2 == 0 else list(reversed(modes))):
command = [str(rune)] if mode != "reference" else [str(args.reference.resolve()), "lab", "pill",
"tap-then-screen", "--repeat", "0", "--time-scale", "1", "--no-backdrop"]
runenv = dict(env)
if mode != "reference":
runenv["STEADY_CLOCK"] = "1"
if args.display_link == "ca": runenv["STEADY_CA"] = "1"
if args.drawables: runenv["STEADY_MAX_DRAWABLES"] = args.drawables
if args.display_sync: runenv["STEADY_DISPLAY_SYNC"] = args.display_sync
if args.guard: runenv["STEADY_GUARD"] = args.guard
if mode == "injected":
runenv["STEADY_RUNE_REDRAW"] = "1"
elif mode == "native":
runenv["PACING_NATIVE"] = "1"
log = root / f"{batch}-{mode}.log"
with log.open("w") as output:
process = subprocess.Popen(command, env=runenv, stdout=output, stderr=subprocess.STDOUT)
try:
process.wait(timeout=14 if mode == "reference" else 22)
assert mode != "reference" and process.returncode == 0, (mode, process.returncode)
except subprocess.TimeoutExpired:
if mode != "reference":
subprocess.run(["sample", str(process.pid), "1", "-file", str(root / f"{batch}-{mode}-timeout.txt")], timeout=10)
raise
finally:
if process.poll() is None:
process.terminate()
try:
process.wait(timeout=5)
except subprocess.TimeoutExpired:
process.kill()
process.wait(timeout=5)
result = dict(batch=batch, mode=mode, **parse(log, mode))
results.append(result)
print(json.dumps(result), flush=True)
summary = dict(endpoint="nextDrawable entry to positive Metal presentedTime",
rune_sha256=hashlib.sha256(rune.read_bytes()).hexdigest(), runs=results,
experiment=dict(display_link=args.display_link, drawables=args.drawables,
display_sync=args.display_sync, guard=args.guard))
if args.reference:
summary["reference_sha256"] = hashlib.sha256(args.reference.read_bytes()).hexdigest()
for mode in modes:
medians = [interval["median"] for r in results if r["mode"] == mode
for interval in r["interval_medians"] if interval]
assert len(medians) == 9, (mode, medians)
summary[mode] = stats(medians)
(root / "results.json").write_text(json.dumps(summary, indent=2) + "\n")
print(json.dumps({k: v for k, v in summary.items() if k != "runs"}), flush=True)
finally:
library.unlink(missing_ok=True)
(root / "load-after.txt").write_bytes(subprocess.check_output(["top", "-l", "1", "-n", "0"]))
print("All disposable apps exited; GUI lock released.", flush=True)
+64
View File
@@ -0,0 +1,64 @@
// Same nextDrawable -> positive presentedTime endpoint as overlays/steady-state/steady-probe.m.
#import <AppKit/AppKit.h>
#import <QuartzCore/CAMetalLayer.h>
#import <Metal/Metal.h>
#import <objc/runtime.h>
static id<CAMetalDrawable> (*originalNext)(id, SEL);
static char requestKey, configKey;
static dispatch_source_t timer;
static NSWindow *ownerOf(CALayer *layer) {
for (NSWindow *window in NSApp.windows) {
CALayer *root = window.contentView.layer;
for (CALayer *p = layer; p; p = p.superlayer)
if (p == root) return window.contentView.window;
}
return nil;
}
static id<CAMetalDrawable> nextDrawable(CAMetalLayer *layer, SEL selector) {
if (getenv("STEADY_MAX_DRAWABLES")) layer.maximumDrawableCount = atoi(getenv("STEADY_MAX_DRAWABLES"));
if (getenv("STEADY_DISPLAY_SYNC")) layer.displaySyncEnabled = atoi(getenv("STEADY_DISPLAY_SYNC"));
double entered = CACurrentMediaTime();
id<CAMetalDrawable> drawable = originalNext(layer, selector);
double acquired = CACurrentMediaTime();
if (!drawable) return drawable;
NSWindow *owner = ownerOf(layer);
NSInteger windowID = owner.windowNumber;
BOOL visible = owner.visible && owner.alphaValue > 0;
NSNumber *request = objc_getAssociatedObject(owner, &requestKey);
double requested = request.doubleValue;
if (owner) objc_setAssociatedObject(owner, &requestKey, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
if (!objc_getAssociatedObject(layer, &configKey)) {
objc_setAssociatedObject(layer, &configKey, @YES, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
fprintf(stderr, "steady config window=%ld max_drawables=%lu transaction=%d display_sync=%d width=%.0f height=%.0f screen_hz=%ld\n",
(long)windowID, (unsigned long)layer.maximumDrawableCount, layer.presentsWithTransaction,
layer.displaySyncEnabled, layer.drawableSize.width, layer.drawableSize.height,
(long)owner.screen.maximumFramesPerSecond);
}
[drawable addPresentedHandler:^(id<MTLDrawable> d) {
fprintf(stderr, "steady frame window=%ld visible=%d requested=%.9f entered=%.9f acquired=%.9f presented=%.9f callback=%.9f\n",
(long)windowID, visible, requested, entered, acquired, d.presentedTime, CACurrentMediaTime());
}];
return drawable;
}
__attribute__((constructor)) static void install(void) {
Method method = class_getInstanceMethod(CAMetalLayer.class, @selector(nextDrawable));
originalNext = (void *)method_setImplementation(method, (IMP)nextDrawable);
if (!getenv("STEADY_RUNE_REDRAW")) return;
dispatch_async(dispatch_get_main_queue(), ^{
timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
dispatch_source_set_timer(timer, dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC), NSEC_PER_SEC / 60, 0);
dispatch_source_set_event_handler(timer, ^{
for (NSWindow *window in NSApp.windows) {
if (![window isKindOfClass:NSPanel.class] || !window.visible || window.alphaValue <= 0) continue;
if (!objc_getAssociatedObject(window, &requestKey))
objc_setAssociatedObject(window, &requestKey, @(CACurrentMediaTime()), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
window.contentView.needsDisplay = YES;
}
});
dispatch_resume(timer);
});
}
+23
View File
@@ -0,0 +1,23 @@
"""Benchmarks time `--profile perf` binaries only. Release builds are incremental, which can move timings."""
import os
from pathlib import Path
import sys
def _is_target(path):
target = os.environ.get('CARGO_TARGET_DIR')
return path.name == 'target' or (target is not None and path == Path(target).resolve())
def perf_binary(path):
path = Path(path).resolve()
profile = path.parent.parent if path.parent.name == 'examples' else path.parent
# <target>/perf/<bin>, <target>/perf/examples/<bin> or <target>/<triple>/perf/...
if profile.name != 'perf' or not (_is_target(profile.parent) or _is_target(profile.parent.parent)):
sys.exit(f'refusing to benchmark {path}: not a --profile perf build.\n'
'Build with `cargo build --profile perf -p <package>` and pass target/perf/<binary> '
'(target/perf/examples/<example> for examples; a saved copy must keep the '
'target/perf/ layout). Release builds are incremental, so their timings are not comparable.')
if not path.is_file():
sys.exit(f'missing perf binary {path}: build it with `cargo build --profile perf`.')
return path
+167
View File
@@ -0,0 +1,167 @@
#!/bin/sh
# Regenerates crates/rune/src/shaders/uber.metallib (wgpu's Metal backend), crates/rune/src/shaders/uber_native.metallib
# (Rune's own, `metal-backend`) and crates/rune/src/render/uber/metallib_hash.rs from
# crates/rune/src/shaders/{clip,shader}.wgsl using wgpu::naga and Xcode's Metal toolchain, the Windfoil
# variant's crates/rune/src/shaders/uber_windfoil{,_native}.metallib and render/uber/windfoil_hash.rs, then
# crates/rune-gpu/src/shaders/builtin_native{,_ios,_ios_sim}.metallib and crates/rune-gpu/src/metal/builtin_table.rs:
# every other pipeline Rune, rune-fx and rune-light ship, captured from Rune's Metal backend.
# App builds embed the committed libraries and do not run xcrun. Needs a Mac with a GPU.
set -eu
cd "$(dirname "$0")/.."
if ! xcrun -sdk macosx --find metal >/dev/null 2>&1; then
echo "error: xcrun -sdk macosx metal not found (install Xcode or Metal Toolchain)" >&2
exit 1
fi
tmp="$(mktemp -d "${TMPDIR:-/tmp}/rune-metallib.XXXXXX")"
trap 'rm -rf "$tmp"' EXIT
if ! cargo test --locked -p rune --features metal-backend --lib render::metallib::tests::dump_uber_msl -- --ignored --exact --nocapture >"$tmp/dump.txt" 2>&1; then
cat "$tmp/dump.txt" >&2
exit 1
fi
python3 - "$tmp/dump.txt" "$tmp" <<'PY'
import pathlib, re, sys
text = pathlib.Path(sys.argv[1]).read_text()
out = pathlib.Path(sys.argv[2])
def extract(tag: str) -> str:
m = re.search(rf"---BEGIN_{tag}---\n(.*?)\n?---END_{tag}---", text, re.S)
if not m:
raise SystemExit(f"missing {tag} in dump output")
return m.group(1)
(out / "wgsl.blake3").write_text(extract("WGSL_BLAKE3").strip())
(out / "msl.blake3").write_text(extract("MSL_BLAKE3").strip())
(out / "flags.txt").write_text(extract("METAL_FLAGS").strip())
(out / "abi.fnv64").write_text(extract("ABI_FNV64").strip())
(out / "options.fnv64").write_text(extract("OPTIONS_FNV64").strip())
(out / "vs.metal").write_text(extract("VS_MSL") + "\n")
(out / "fs.metal").write_text(extract("FS_MSL") + "\n")
(out / "native.blake3").write_text(extract("NATIVE_MSL_BLAKE3").strip())
(out / "native_flags.txt").write_text(extract("NATIVE_METAL_FLAGS").strip())
(out / "native_vs.metal").write_text(extract("NATIVE_VS_MSL") + "\n")
(out / "native_fs.metal").write_text(extract("NATIVE_FS_MSL") + "\n")
(out / "windfoil.blake3").write_text(extract("WINDFOIL_WGSL_BLAKE3").strip())
(out / "windfoil_abi.fnv64").write_text(extract("WINDFOIL_ABI_FNV64").strip())
(out / "windfoil_vs.metal").write_text(extract("WINDFOIL_VS_MSL") + "\n")
(out / "windfoil_fs.metal").write_text(extract("WINDFOIL_FS_MSL") + "\n")
(out / "windfoil_native_vs.metal").write_text(extract("WINDFOIL_NATIVE_VS_MSL") + "\n")
(out / "windfoil_native_fs.metal").write_text(extract("WINDFOIL_NATIVE_FS_MSL") + "\n")
PY
flags="$(cat "$tmp/flags.txt")"
# shellcheck disable=SC2086
xcrun -sdk macosx metal $flags -c "$tmp/vs.metal" -o "$tmp/vs.air"
# shellcheck disable=SC2086
xcrun -sdk macosx metal $flags -c "$tmp/fs.metal" -o "$tmp/fs.air"
xcrun -sdk macosx metallib "$tmp/vs.air" "$tmp/fs.air" -o crates/rune/src/shaders/uber.metallib
native_flags="$(cat "$tmp/native_flags.txt")"
# shellcheck disable=SC2086
xcrun -sdk macosx metal $native_flags -c "$tmp/native_vs.metal" -o "$tmp/native_vs.air"
# shellcheck disable=SC2086
xcrun -sdk macosx metal $native_flags -c "$tmp/native_fs.metal" -o "$tmp/native_fs.air"
xcrun -sdk macosx metallib "$tmp/native_vs.air" "$tmp/native_fs.air" -o crates/rune/src/shaders/uber_native.metallib
python3 - "$tmp" crates/rune/src/shaders/uber.metallib crates/rune/src/render/uber/metallib_hash.rs crates/rune/src/shaders/uber_native.metallib <<'PY'
import pathlib, sys
tmp = pathlib.Path(sys.argv[1])
metallib_path = pathlib.Path(sys.argv[2])
hash_rs_path = pathlib.Path(sys.argv[3])
wgsl_hash = (tmp / "wgsl.blake3").read_text().strip()
msl_hash = (tmp / "msl.blake3").read_text().strip()
native_hash = (tmp / "native.blake3").read_text().strip()
data = metallib_path.read_bytes()
def fnv64(data):
h = 0xcbf29ce484222325
for b in data:
h = ((h ^ b) * 0x100000001b3) & 0xFFFFFFFFFFFFFFFF
return h
h = fnv64(data)
native_h = fnv64(pathlib.Path(sys.argv[4]).read_bytes())
native_cfg = '#[cfg(all(test, target_os = "macos", feature = "metal-backend"))]\n'
hash_rs_path.write_text(
"// Generated by scripts/precompile-metal-shaders.sh, or refreshed from the freshness test when MSL is unchanged.\n"
'#[cfg(any(test, target_os = "macos"))]\n'
f'pub(super) const UBER_WGSL_BLAKE3: &str = "{wgsl_hash}";\n'
'#[cfg(any(test, target_os = "macos"))]\n'
f'pub(super) const UBER_ABI_FNV64: u64 = 0x{(tmp / "abi.fnv64").read_text().strip()};\n'
"#[cfg(all(test, target_os = \"macos\"))]\n"
f'pub(super) const UBER_MSL_OPTIONS_FNV64: u64 = 0x{(tmp / "options.fnv64").read_text().strip()};\n'
"#[cfg(test)]\n"
f'pub(super) const UBER_MSL_BLAKE3: &str = "{msl_hash}";\n'
"#[cfg(test)]\n"
f"pub(super) const UBER_METALLIB_FNV64: u64 = 0x{h:016x};\n"
+ native_cfg
+ f'pub(super) const UBER_NATIVE_MSL_BLAKE3: &str = "{native_hash}";\n'
+ native_cfg
+ f"pub(super) const UBER_NATIVE_METALLIB_FNV64: u64 = 0x{native_h:016x};\n"
)
print(f"wrote {metallib_path} ({len(data)} bytes, fnv64=0x{h:016x})")
PY
# The Windfoil uber variant (crates/rune/src/render/variant.rs), which only a renderer drawing
# glyphs from outlines loads: uber_windfoil.metallib (wgpu) and uber_windfoil_native.metallib (Rune's).
# shellcheck disable=SC2086
xcrun -sdk macosx metal $flags -c "$tmp/windfoil_vs.metal" -o "$tmp/windfoil_vs.air"
# shellcheck disable=SC2086
xcrun -sdk macosx metal $flags -c "$tmp/windfoil_fs.metal" -o "$tmp/windfoil_fs.air"
xcrun -sdk macosx metallib "$tmp/windfoil_vs.air" "$tmp/windfoil_fs.air" -o crates/rune/src/shaders/uber_windfoil.metallib
# shellcheck disable=SC2086
xcrun -sdk macosx metal $native_flags -c "$tmp/windfoil_native_vs.metal" -o "$tmp/windfoil_native_vs.air"
# shellcheck disable=SC2086
xcrun -sdk macosx metal $native_flags -c "$tmp/windfoil_native_fs.metal" -o "$tmp/windfoil_native_fs.air"
xcrun -sdk macosx metallib "$tmp/windfoil_native_vs.air" "$tmp/windfoil_native_fs.air" -o crates/rune/src/shaders/uber_windfoil_native.metallib
printf '%s\n' \
"// Generated by scripts/precompile-metal-shaders.sh. Empty until a Mac has built uber_windfoil.metallib." \
"pub(super) const WINDFOIL_WGSL_BLAKE3: &str = \"$(cat "$tmp/windfoil.blake3")\";" \
"pub(super) const WINDFOIL_ABI_FNV64: u64 = 0x$(cat "$tmp/windfoil_abi.fnv64");" \
> crates/rune/src/render/uber/windfoil_hash.rs
echo "wrote crates/rune/src/shaders/uber_windfoil.metallib and uber_windfoil_native.metallib"
# Every other built-in pipeline (crates/rune-gpu/src/metal/builtin.rs), captured once and compiled
# for macOS, iOS and the iOS simulator. MSL 3.0 needs macOS 13 and iOS 16. RUNE_DISABLE_METALLIB
# makes the uber shader compile from WGSL so it's captured too: iOS has no uber_native.metallib.
cap="$tmp/capture"
mkdir -p "$cap"
if ! RUNE_GPU_BACKEND=metal RUNE_DISABLE_METALLIB=1 RUNE_METAL_CAPTURE="$cap" cargo test --locked -p rune-light --features rune/metal-backend --test builtin_shaders >"$tmp/capture.txt" 2>&1; then
cat "$tmp/capture.txt" >&2
exit 1
fi
ios_flags="$(echo "$native_flags" | sed 's/-mmacosx-version-min=13.0/-mios-version-min=16.0/')"
sim_flags="$(echo "$native_flags" | sed 's/-mmacosx-version-min=13.0/-mios-simulator-version-min=16.0/')"
for target in "macosx:$native_flags:builtin_native" "iphoneos:$ios_flags:builtin_native_ios" "iphonesimulator:$sim_flags:builtin_native_ios_sim"; do
sdk="${target%%:*}" rest="${target#*:}"
flags="${rest%:*}" name="${rest##*:}"
mkdir -p "$cap/$sdk"
export sdk flags
# shellcheck disable=SC2016
find "$cap" -maxdepth 1 -name '*.metal' -print0 | xargs -0 -P 8 -n 1 sh -c 'xcrun -sdk "$sdk" metal $flags -Wno-unused-variable -c "$1" -o "$(dirname "$1")/$sdk/$(basename "${1%.metal}").air"' sh
xcrun -sdk "$sdk" metallib "$cap/$sdk"/*.air -o "crates/rune-gpu/src/shaders/$name.metallib"
done
python3 - "$cap" crates/rune-gpu/src/metal/builtin_table.rs <<'PY'
import pathlib, sys
cap = pathlib.Path(sys.argv[1])
rows = "".join(p.read_text() for p in sorted(cap.glob("*.row")))
sources = "".join(f' "{p.stem}",\n' for p in sorted(cap.glob("*.source")))
pathlib.Path(sys.argv[2]).write_text(
"// Generated by scripts/precompile-metal-shaders.sh: the built-in shaders' WGSL hashes, and each\n"
"// precompiled pipeline's key, function, sized bindings, workgroup size and workgroup memory sizes,\n"
"// sorted by key.\n"
f"const SOURCES: &[&str] = &[\n{sources}];\n"
f"const FUNCTIONS: &[(&str, &str, &[(u32, u32)], [u32; 3], &[u32])] = &[\n{rows}];\n"
)
print(f"wrote {sys.argv[2]} ({len(list(cap.glob('*.row')))} pipelines)")
PY
+479
View File
@@ -0,0 +1,479 @@
#!/usr/bin/env python3
"""Real-app frame costs from headless runs: per-frame distributions, launch and memory, and
where the main thread's time goes.
run Runs an app's scenarios from a JSON config, alternating their order across runs,
with RUNE_FRAME_LOG set (build the app with rune/frame-profile). `--sample` adds one
extra run per scenario under macOS `sample`, kept apart from the timed runs.
summary Reads a run directory: per scenario and window, frame CPU p50/p95/p99/max and frames
over the 120 Hz budget (median across runs, warmup left out), phase means, memory,
and committing frames by reason (the frame log's `why`: poll, input, layout, read,
dirty, relayout, settle, virtual, route; "other" for a commit outside the frame's checks).
profile Buckets a `sample` dump's main thread by self time (`--binary` adds file:line for
the hottest functions through atos).
Config: {"binary": "...", "args": [...], "env": {...}, "fps": 120, "size": "1240x780",
"scenarios": {"name": {"args": [...], "env": {...}, "frames": 600,
"script": [events] | "path", "windows": {"scroll": [1.0, 4.5]}}}}
Relative paths in the config resolve against the config's directory; "$OUT" in args and env
becomes the run directory.
Headless numbers are main-thread CPU for update, build, layout, paint and encode/submit. They
leave out GPU execution, presentation, display timing and the window server, and headless draws
every frame, so a frame "drawn" here may be one a real window skips: summary also reports the
frames a window would draw (input arrived, a commit, or something animating).
"""
import argparse
import json
import math
import os
import re
import shutil
import statistics
import subprocess
import sys
import time
from pathlib import Path
BUDGET_MS = 1000 / 120
def load_config(path):
cfg = json.loads(Path(path).read_text())
cfg["_dir"] = Path(path).resolve().parent
return cfg
def resolve(cfg, value, out):
value = os.path.expandvars(str(value).replace("$OUT", str(out)))
if value.startswith(("./", "../")):
return str((cfg["_dir"] / value).resolve())
return value
def command(cfg, name, sc, out, log):
script = sc.get("script")
if isinstance(script, list):
path = out / f"{name}.script.json"
path.write_text(json.dumps(script))
script = str(path)
elif script:
script = resolve(cfg, script, out)
args = [resolve(cfg, cfg["binary"], out)]
args += [resolve(cfg, a, out) for a in cfg.get("args", []) + sc.get("args", [])]
if script:
args += ["--script", script]
args += ["--fps", str(cfg.get("fps", 120)), "--frames", str(sc.get("frames", 600))]
if cfg.get("size") and "--size" not in args:
args += ["--size", cfg["size"]]
env = dict(os.environ)
env.update({k: resolve(cfg, v, out) for k, v in {**cfg.get("env", {}), **sc.get("env", {})}.items()})
if log:
env["RUNE_FRAME_LOG"] = str(log)
cwd = resolve(cfg, sc.get("cwd", cfg.get("cwd", ".")), out)
return args, env, cwd
def setup(cfg, sc, out):
for step in cfg.get("setup", []) + sc.get("setup", []):
subprocess.run(resolve(cfg, step, out), shell=True, check=True, cwd=cfg["_dir"])
def run(args):
cfg = load_config(args.config)
out = Path(args.out).resolve()
out.mkdir(parents=True, exist_ok=True)
names = [n for n in cfg["scenarios"] if not args.only or n in args.only.split(",")]
failed = set()
for n in range(args.runs + 1):
order = names if n % 2 == 0 else names[::-1]
for name in order:
if name in failed:
continue
sc = cfg["scenarios"][name]
setup(cfg, sc, out)
log = out / f"{name}-{n}.jsonl"
cmd, env, cwd = command(cfg, name, sc, out, log)
start = time.monotonic()
p = subprocess.run(cmd, env=env, cwd=cwd, capture_output=True, text=True, timeout=args.timeout)
wall = time.monotonic() - start
text = p.stdout + p.stderr
(out / f"{name}-{n}.log").write_text(text)
if p.returncode:
# Keep going with the other scenarios; the log keeps the failure.
print(f"{name} run {n} failed ({p.returncode}): {text[-1500:]}", file=sys.stderr, flush=True)
failed.add(name)
if log.exists():
log.rename(log.with_suffix(".failed"))
continue
launch = next((json.loads(l.split(" ", 1)[1]) for l in text.splitlines() if l.startswith("rune-first-pixels ")), None)
with log.open("a") as f:
f.write(json.dumps({"run": n, "warmup": n == 0, "process_wall_s": wall, "launch": launch}) + "\n")
print(f"{name} run {n}: {wall:.2f} s", flush=True)
if args.sample:
for name in (n for n in names if n not in failed):
sc = cfg["scenarios"][name]
setup(cfg, sc, out)
cmd, env, cwd = command(cfg, name, sc, out, None)
# A still of the last frame, to check the scenario did what it says.
if "--snap" not in cmd:
cmd += ["--snap", str(out / f"{name}.check.png"), "--at", f"{(sc.get('frames', 600) - 1) / cfg.get('fps', 120):.3f}"]
# The run holds before it starts (RUNE_HEADLESS_WAIT) so `sample` is attached for launch.
env["RUNE_HEADLESS_WAIT"] = str(args.sample_hold)
p = subprocess.Popen(cmd, env=env, cwd=cwd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
dump = out / f"{name}.sample.txt"
subprocess.run(["/usr/bin/sample", str(p.pid), str(args.sample_secs), "1", "-mayDie", "-file", str(dump)],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
p.wait()
print(f"{name}: sampled to {dump.name}", flush=True)
def q(values, p):
v = sorted(values)
return v[min(len(v) - 1, max(0, math.ceil(p * len(v)) - 1))] if v else None
def dist(values):
return {"n": len(values), "p50": q(values, .5), "p95": q(values, .95), "p99": q(values, .99),
"max": max(values, default=None), "over_budget": sum(v > BUDGET_MS for v in values),
"missed_refreshes": sum(max(0, math.ceil(v / BUDGET_MS) - 1) for v in values)}
def read_log(path):
frames, end, meta = [], None, None
for line in path.read_text().splitlines():
v = json.loads(line)
if "k" in v:
frames.append(v)
elif v.get("end"):
end = v
elif "run" in v:
meta = v
return frames, end, meta
PHASES = ("view_cpu", "commit_cpu", "layout_cpu", "text_cpu", "paint_cpu", "apply_cpu", "update_ms", "encode_ms")
def window_stats(frames, fps, t0, t1):
inside = [f for f in frames if t0 * fps <= f["k"] < t1 * fps]
drawn = [f for f in inside if f["animating"] or f["commits"] or f["events"]]
cost = lambda f: f["cpu_ms"] if f.get("cpu_ms") is not None else f["ms"]
return {
"all": dist([cost(f) for f in inside]),
"drawn": dist([cost(f) for f in drawn]),
"wall_drawn": dist([f["ms"] for f in drawn]),
"phases_mean_ms": {p: statistics.fmean(f[p] for f in drawn) if drawn else None for p in PHASES},
"allocations_mean": statistics.fmean(f["allocations"] for f in drawn) if drawn else None,
"commits_per_frame": statistics.fmean(f["commits"] for f in inside) if inside else None,
"commit_why": commit_why(inside),
"shaped_mean": statistics.fmean(f["shaped"] for f in drawn) if drawn else None,
"worst": sorted(({"k": f["k"], "t": round(f["k"] / fps, 3), "cpu_ms": cost(f), "shaped": f["shaped"],
"text_cpu": f["text_cpu"], "layout_cpu": f["layout_cpu"], "view_cpu": f["view_cpu"],
"encode_ms": f["encode_ms"], "allocations": f["allocations"]} for f in drawn),
key=lambda f: -f["cpu_ms"])[:5],
}
def commit_why(frames):
"""Committing frames per reason (the frame log's `why`; "other" when it names none)."""
counts = {}
for f in frames:
if f["commits"]:
for why in f.get("why") or ["other"]:
counts[why] = counts.get(why, 0) + 1
return counts
def median_of(rows, path):
vals = []
for r in rows:
v = r
for key in path:
v = v.get(key) if isinstance(v, dict) else None
if v is not None:
vals.append(v)
return statistics.median(vals) if vals else None
def summary(args):
cfg = load_config(args.config)
out = Path(args.out)
fps = cfg.get("fps", 120)
report = {}
for name, sc in cfg["scenarios"].items():
logs = sorted(out.glob(f"{name}-*.jsonl"), key=lambda p: int(p.stem.rsplit("-", 1)[1]))
if not logs:
continue
runs = []
for path in logs:
frames, end, meta = read_log(path)
if not meta or meta.get("warmup"):
continue
windows = sc.get("windows") or {"all": [1 / fps, len(frames) / fps]}
runs.append({"windows": {w: window_stats(frames, fps, *span) for w, span in windows.items()},
"memory": end, "launch": meta.get("launch"), "first_frame": frames[0] if frames else None,
"process_wall_s": meta.get("process_wall_s")})
if not runs:
continue
entry = {"runs": len(runs), "windows": {}}
for w in runs[0]["windows"]:
ws = [r["windows"][w] for r in runs]
entry["windows"][w] = {
"drawn_cpu_ms": {k: median_of(ws, ["drawn", k]) for k in ("n", "p50", "p95", "p99", "max", "over_budget", "missed_refreshes")},
"drawn_p50_range": [min(x["drawn"]["p50"] or 0 for x in ws), max(x["drawn"]["p50"] or 0 for x in ws)],
"drawn_max_range": [min(x["drawn"]["max"] or 0 for x in ws), max(x["drawn"]["max"] or 0 for x in ws)],
"all_cpu_ms": {k: median_of(ws, ["all", k]) for k in ("n", "p50", "p95", "p99", "max", "over_budget")},
"phases_mean_ms": {p: median_of(ws, ["phases_mean_ms", p]) for p in PHASES},
"allocations_mean": median_of(ws, ["allocations_mean"]),
"commits_per_frame": median_of(ws, ["commits_per_frame"]),
"commit_why": {k: statistics.median(x["commit_why"].get(k, 0) for x in ws)
for k in sorted({k for x in ws for k in x["commit_why"]})},
"shaped_mean": median_of(ws, ["shaped_mean"]),
"worst_frames_by_run": [x["worst"][:3] for x in ws],
}
entry["memory_mb"] = {k: median_of(runs, ["memory", k]) / 1e6 for k in ("footprint", "footprint_peak", "resident", "heap_live")
if median_of(runs, ["memory", k]) is not None}
if any(r["launch"] for r in runs):
entry["launch_ms"] = {k: median_of(runs, ["launch", k]) for k in ("headless_ms", "state_ms", "runtime_ms", "gpu_init_ms", "frame_cpu_ms")}
entry["first_frame_cpu_ms"] = median_of(runs, ["first_frame", "cpu_ms"])
entry["first_frame_phases"] = {p: median_of(runs, ["first_frame", p]) for p in PHASES}
report[name] = entry
text = json.dumps(report, indent=1)
if args.write:
Path(args.write).write_text(text + "\n")
print(table(report) if args.table else text)
def table(report):
"""One line per scenario window: drawn-frame CPU quantiles, budget misses and the phase split."""
f = lambda v: "-" if v is None else f"{v:.2f}" if isinstance(v, float) else str(v)
rows = ["scenario/window n p50 p95 p99 max >8.3ms view commit layout text paint update encode"]
for name, e in report.items():
for w, x in e["windows"].items():
d, ph = x["drawn_cpu_ms"], x["phases_mean_ms"]
rows.append(f"{name + '/' + w:<20} " + " ".join(f(d[k]) for k in ("n", "p50", "p95", "p99", "max", "over_budget"))
+ " " + " ".join(f(ph[k]) for k in ("view_cpu", "commit_cpu", "layout_cpu", "text_cpu", "paint_cpu", "update_ms", "encode_ms")))
if x.get("commit_why"):
rows.append(f"{'':<20} committing frames by reason: " + ", ".join(f"{k} {f(v)}" for k, v in x["commit_why"].items()))
if e.get("launch_ms"):
rows.append(f"{name}: launch " + json.dumps({k: round(v, 1) for k, v in e["launch_ms"].items() if v is not None})
+ " first frame " + f(e["first_frame_cpu_ms"]) + " memory MB " + json.dumps({k: round(v) for k, v in e["memory_mb"].items()}))
return "\n".join(rows)
# Buckets for self time, by the frame that owns it (generic std/alloc frames defer to their caller).
BUCKETS = [
("waiting (GPU, locks, sleep)", r"^(__semwait_signal|__psynch_cvwait|__psynch_mutexwait|mach_msg2_trap|mach_msg_trap|__workq_kernreturn|__ulock_wait|semaphore_wait_trap|nanosleep|kevent)"),
("allocation", r"^(_?malloc|_?free|_?realloc|_?calloc|szone_|tiny_|small_|nanov2_|_nanov2|mvm_|_malloc|_free|__rust_(alloc|dealloc|realloc)|alloc::alloc::|procwatch::alloc|<procwatch::alloc|xzm_|_xzm|malloc_|free_)"),
("motion", r"^(rune_motion::|<rune_motion::|rune::runtime::(motion|flights|transition|anim)|rune::motion|rune::anim)"),
("taffy", r"^(taffy::|<taffy::)"),
# Walking laid-out glyphs, mostly from the paint walk's glyph emission rather than line breaking.
("glyph iteration (parley)", r"^<parley::layout::(run::Glyphs|line::GlyphRunIter|line::GlyphRun)\b"),
("text shaping (parley/harfrust/fontique)", r"^(parley::shape|<parley::shape|harfrust::|<harfrust::|harfruzz::|rustybuzz::|fontique::|<fontique::|skrifa::|<skrifa::|read_fonts::|<read_fonts::|swash::shape|parley::resolve|parley::builder|parley::context|parley::analysis|<parley::analysis|icu_|<icu_)"),
("text breaking/layout (parley)", r"^(parley::|<parley::)"),
("glyph raster/atlas", r"^(swash::|<swash::|zeno::|<zeno::|rune::text::(atlas|raster|glyph)|rune::glyph|etagere::|<etagere::|guillotiere::)"),
("rune text", r"^(rune::text|<rune::text|rune_kit::markdown|<rune_kit::markdown|pulldown_cmark|<pulldown_cmark|rune_kit::(code|syntax|highlight)|syntect|tree_sitter)"),
("flatten/diff/commit", r"^(rune::runtime::(flatten|commit|diff|reconcile|mount|keys|bands)|<rune::runtime::(flatten|commit)|rune::tree|rune::diff|rune::reconcile)"),
("rune layout (non-taffy)", r"^(rune::(runtime::)?(layout|measure)|<rune::(runtime::)?layout)"),
("rune render/encode", r"^(rune::(render|paint|renderer|batch|instances|gpu|scene|draw|shape|offscreen|record|surface)|<rune::(render|paint))"),
("wgpu/naga", r"^(wgpu|<wgpu|naga|<naga|metal::|<metal::|objc2_metal)"),
("driver/OS", r"^(objc_|_objc|-\[|\+\[|AGX|IOGPU|IOKit|IOConnect|mach_|__|_dispatch|dispatch_|CF|CA|MTL|_MTL|os_unfair|pthread_|_pthread|semaphore_|kevent|_platform_|swift_|AGXMetal|libsystem|dyld)"),
# `Runtime::build` is the per-frame draw-list walk (Phase::Paint), not the view.
("rune paint walk", r"^(<rune::runtime::Runtime<.*>>::(build|glyphs_into|draw_text)\b|rune::runtime::paint)"),
("rune view/build", r"^(rune::|<rune::|rune_kit::|<rune_kit::|rune_theme|rune_fx|<rune_fx)"),
("hashing/containers (std)", r"^(hashbrown|<hashbrown|core::hash|<core::hash|std::collections|<std::collections|alloc::collections|<alloc::collections|rustc_hash|<rustc_hash|ahash|<ahash)"),
]
GENERIC = re.compile(r"^(<?(core|alloc|std|hashbrown|smallvec|<smallvec|rustc_hash|ahash)::|_platform_mem|DYLD-STUB|<&|<\[|<\(|<\*)")
def demangle(sym):
s = sym
for a, b in (("$LT$", "<"), ("$GT$", ">"), ("$u20$", " "), ("$RF$", "&"), ("$BP$", "*"), ("$C$", ","),
("$u7b$", "{"), ("$u7d$", "}"), ("$u5b$", "["), ("$u5d$", "]"), ("$u27$", "'"), ("$u3b$", ";"),
("$u22$", '"'), ("$LP$", "("), ("$RP$", ")"), ("$u2b$", "+"), ("$SP$", "@")):
s = s.replace(a, b)
s = s.replace("..", "::")
s = re.sub(r"::h[0-9a-f]{16}$", "", s)
return re.sub(r"^_(?=<)", "", s)
LINE = re.compile(r"^(?P<lead>[ +!:|]*)(?P<count>\d+) (?P<sym>.+?) \(in (?P<lib>[^)]+)\)(?: \+ [\d,.]+)?"
r"(?: \[(?P<addr>0x[0-9a-f]+)\](?:\s+(?P<src>\S+:\d+))?)?")
def demangle_all(syms):
"""Rust v0 and legacy symbols through rustfilt when it's installed, else the legacy rules."""
syms = sorted(set(syms))
if shutil.which("rustfilt"):
p = subprocess.run(["rustfilt"], input="\n".join(syms), capture_output=True, text=True)
out = p.stdout.splitlines()
if p.returncode == 0 and len(out) == len(syms):
return {a: re.sub(r"^_(?=<)", "", b) for a, b in zip(syms, out)}
return {a: demangle(a) for a in syms}
def parse_threads(path):
"""{thread title: [(depth, count, sym, lib, addr)]} from a `sample` call graph."""
threads, cur, in_graph = {}, None, False
for line in Path(path).read_text().splitlines():
if line.startswith("Call graph:"):
in_graph = True
continue
if in_graph and (line.startswith("Total number in stack") or line.startswith("Sort by top of stack")):
break
if not in_graph or not line.strip():
continue
m = re.match(r"^ {4}(\d+) (Thread_\d+.*)$", line)
if m:
cur = m.group(2).strip()
threads[cur] = []
continue
m = LINE.match(line[4:]) if cur else None
if m:
depth = len(m.group("lead")) // 2
threads[cur].append((depth, int(m.group("count")), m.group("sym").strip(), m.group("lib"), m.group("addr"), m.group("src")))
names = demangle_all(r[2] for rows in threads.values() for r in rows)
return {t: [(d, c, names[sym], lib, addr, src) for d, c, sym, lib, addr, src in rows] for t, rows in threads.items()}
def bucket_of(sym, lib, app_libs):
for name, rx in BUCKETS:
if re.search(rx, sym):
return name
if lib in app_libs or re.match(r"^<?[a-z_0-9]+::", sym):
return "app code"
return "driver/OS" if lib not in app_libs else "other"
def self_times(rows):
"""(self count, symbol, owner symbol, lib, addr, source line) for each node of one thread's tree,
leaving out the sampled run's RUNE_HEADLESS_WAIT hold."""
children = [0] * len(rows)
parents, stack = [None] * len(rows), []
for i, (depth, count, *_rest) in enumerate(rows):
while stack and rows[stack[-1]][0] >= depth:
stack.pop()
if stack:
parents[i] = stack[-1]
children[stack[-1]] += count
stack.append(i)
out = []
for i, (depth, count, sym, lib, addr, src) in enumerate(rows):
own = count - children[i]
if own <= 0:
continue
path, j = [], i
while j is not None:
path.append(j)
j = parents[j]
if any(rows[j][2].startswith("std::thread::") and "sleep" in rows[j][2] for j in path):
continue
# The hold's sleep is inlined into headless_configured in optimized builds.
if any(rows[j][2] == "nanosleep" and parents[j] is not None and "headless_configured" in rows[parents[j]][2] for j in path):
continue
owner = next((rows[j] for j in path if not GENERIC.match(rows[j][2]) or re.match(BUCKETS[0][1], rows[j][2])), rows[i])
out.append((own, sym, owner[2], owner[3], addr, owner[5] or src))
return out
def atos(binary, load, addrs):
if not addrs:
return {}
p = subprocess.run(["atos", "-i", "-o", binary, "-l", load, *addrs], capture_output=True, text=True)
lines, out, k = p.stdout.splitlines(), {}, 0
# One block per address, inlined frames first, separated by blank lines.
blocks, cur = [], []
for line in lines:
if not line.strip():
if cur:
blocks.append(cur)
cur = []
else:
cur.append(line)
if cur:
blocks.append(cur)
for addr, block in zip(addrs, blocks):
out[addr] = block
return out
def profile(args):
text = Path(args.dump).read_text()
threads = parse_threads(args.dump)
if not any(threads.values()):
sys.exit(f"{args.dump}: no samples (the process exited before sample attached)")
main = next((t for t in threads if "main-thread" in t), None) or max(threads, key=lambda t: sum(c for d, c, *_ in threads[t] if d == 0))
rows = threads[main]
exe = re.search(r"^Path:\s+(.+)$", text, re.M)
app_libs = {Path(exe.group(1)).name} if exe else set()
nodes = self_times(rows)
total = sum(n[0] for n in nodes)
buckets, funcs = {}, {}
for count, sym, owner, lib, addr, src in nodes:
b = bucket_of(sym, lib, app_libs)
if b in ("other", "driver/OS") or GENERIC.match(sym):
ob = bucket_of(owner, lib, app_libs)
b = b if b == "allocation" or (b == "driver/OS" and ob == "app code") else ob
buckets[b] = buckets.get(b, 0) + count
f = funcs.setdefault(owner, {"samples": 0, "bucket": b, "addrs": {}, "leaf": {}, "src": {}})
f["samples"] += count
if src:
f["src"][src] = f["src"].get(src, 0) + count
if addr:
f["addrs"][addr] = f["addrs"].get(addr, 0) + count
f["leaf"][sym] = f["leaf"].get(sym, 0) + count
if args.exclude:
rx = re.compile(args.exclude)
idle = sum(c for c, s, *_ in nodes if rx.search(s))
else:
idle = 0
top = sorted(funcs.items(), key=lambda kv: -kv[1]["samples"])[:args.top]
lines = {}
if args.binary:
load = re.search(r"^Load Address:\s+(0x[0-9a-f]+)", text, re.M)
addrs = [max(f["addrs"], key=f["addrs"].get) for _, f in top if f["addrs"]]
lines = atos(args.binary, load.group(1), addrs) if load else {}
report = {
"thread": main, "samples": total, "ms_per_sample": 1,
"buckets": {b: {"samples": c, "pct": round(100 * c / total, 1)} for b, c in sorted(buckets.items(), key=lambda kv: -kv[1])},
"top": [{"fn": fn, "samples": f["samples"], "pct": round(100 * f["samples"] / total, 1), "bucket": f["bucket"],
"leaves": sorted(f["leaf"].items(), key=lambda kv: -kv[1])[:3],
"lines": sorted(f["src"].items(), key=lambda kv: -kv[1])[:3],
"at": lines.get(max(f["addrs"], key=f["addrs"].get)) if f["addrs"] else None} for fn, f in top],
}
text = json.dumps(report, indent=1)
if args.write:
Path(args.write).write_text(text + "\n")
print(text)
def main():
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
sub = p.add_subparsers(dest="cmd", required=True)
r = sub.add_parser("run")
r.add_argument("config")
r.add_argument("--out", required=True)
r.add_argument("--runs", type=int, default=5, help="measured runs, after one warmup")
r.add_argument("--only", help="comma-separated scenarios")
r.add_argument("--sample", action="store_true")
r.add_argument("--sample-secs", type=int, default=120)
r.add_argument("--sample-hold", type=float, default=1.5, help="seconds the sampled run waits before starting")
r.add_argument("--timeout", type=int, default=600)
s = sub.add_parser("summary")
s.add_argument("config")
s.add_argument("--out", required=True)
s.add_argument("--write")
s.add_argument("--table", action="store_true", help="print a one-line-per-window table instead of JSON")
f = sub.add_parser("profile")
f.add_argument("dump")
f.add_argument("--binary")
f.add_argument("--top", type=int, default=25)
f.add_argument("--exclude")
f.add_argument("--write")
a = p.parse_args()
{"run": run, "summary": summary, "profile": profile}[a.cmd](a)
if __name__ == "__main__":
main()
+998
View File
@@ -0,0 +1,998 @@
#!/usr/bin/env python3
"""Guarded Rune hot editing. The compiler and app always run in the same build lease.
On the desk Mac this relays source edits to the build Mac; on a worker it watches a validated mirror.
Only view function bodies can patch. All other build inputs require a restart.
rune-dev settings [-- APP ARGS]
rune-dev --manifest-path APP/Cargo.toml --patch 'src/ui/*.rs' [--bin B] [--features F] [-- APP ARGS]
--desk compiles on the build Mac but runs the app on this Mac, patching it over an SSH tunnel.
--local (or RUNE_DEV_LOCAL=1) compiles and runs the app on this machine, with no build Mac, and
rebuilds and relaunches it after an edit that needs a restart. RUNE_DEV_WRAP runs that under a
command prefix (a build-queue lease, say); by default it's plain cargo.
"""
import argparse
from dataclasses import dataclass
import hashlib
import json
import os
from pathlib import Path, PurePosixPath
import platform
import posixpath
import re
import select
import shlex
import shutil
import signal
import socket
import subprocess
import sys
import tempfile
import threading
import time
import tomllib
from urllib.parse import parse_qs, urlsplit
ROOT = Path(__file__).resolve().parents[1]
EXAMPLES = {"settings": {"examples/settings/src/main.rs"}}
# Matches the workspace's [profile.rune-hot], for apps that don't define their own.
PROFILE = ['profile.rune-hot.inherits="dev"', "profile.rune-hot.debug=0", "profile.rune-hot.incremental=true",
"profile.rune-hot.package.png.opt-level=3", "profile.rune-hot.package.fdeflate.opt-level=3"]
SKIP_DIRS = ("target", ".git", "__pycache__", "node_modules")
@dataclass
class External:
"""An app crate outside Rune. Its files are `external/<path from base>` keys."""
base: Path
crate: str
dirs: list
tops: list
# Set when this process reads an external crate's original files; a build Mac's staging
# area already holds them at their keys.
EXTERNAL = None
def git_or_walk(directory, roots=("",)):
try:
out = subprocess.run(["git", "ls-files", "--cached", "--others", "--exclude-standard", "-z", "--", *[r or "." for r in roots]],
cwd=directory, capture_output=True, check=True).stdout.decode()
return [p for p in out.split("\0") if p]
except (subprocess.CalledProcessError, FileNotFoundError, NotADirectoryError):
result = []
for root in roots:
for parent, dirs, names in os.walk(directory / root):
dirs[:] = [d for d in dirs if d not in SKIP_DIRS]
result.extend(str((Path(parent) / n).relative_to(directory)) for n in names)
return result
def files():
manifest = ROOT / ".rune-dev-files.json"
if manifest.exists():
return json.loads(manifest.read_text())
if EXTERNAL:
tooling = [p for p in git_or_walk(ROOT, ("tools/rune-dev-guard",)) if not p.startswith("tools/rune-dev-guard/target/")]
keys = set(tooling) | {"scripts/rune-dev"} | {"external/" + p for p in EXTERNAL.tops}
for d in EXTERNAL.dirs:
keys.update(str(PurePosixPath("external", d, p)) for p in git_or_walk(EXTERNAL.base / d))
return sorted(keys)
if not (ROOT / ".git").exists():
# The build queue syncs source without Git metadata.
result = []
for directory in ("crates", "examples", "themes", "tools", "scripts", ".cargo"):
for parent, dirs, names in os.walk(ROOT / directory):
dirs[:] = [d for d in dirs if d not in SKIP_DIRS]
result.extend(str((Path(parent) / n).relative_to(ROOT)) for n in names)
result.extend(p for p in ("Cargo.toml", "Cargo.lock", "rust-toolchain.toml") if (ROOT / p).exists())
return result
return subprocess.check_output(["git", "ls-files", "--cached", "--others", "--exclude-standard", "-z"], cwd=ROOT).decode().strip("\0").split("\0")
def source(p):
"""The file behind a key on this machine."""
if EXTERNAL and (p == "external" or p.startswith("external/")):
return EXTERNAL.base / p.removeprefix("external").lstrip("/")
return ROOT / p
def tracked(p):
if not p or Path(p).name.startswith(".env") or Path(p).suffix in (".pem", ".key"):
return False
return p.startswith(("crates/", "examples/", "themes/", "external/")) or p in ("Cargo.toml", "Cargo.lock", "rust-toolchain.toml", ".cargo/config.toml")
def inputs(cache):
def stamp(path):
s = path.stat()
# ctime/inode also catch same-size saves with restored mtimes and atomic replacements.
return s.st_size, s.st_mtime_ns, s.st_ctime_ns, s.st_dev, s.st_ino
current = {}
for p in files():
if not tracked(p):
continue
path = source(p)
try:
before = stamp(path)
except (FileNotFoundError, NotADirectoryError):
continue
old = cache.get(p)
if old is not None and old[0] == before:
current[p] = old
else:
data = path.read_bytes()
if stamp(path) != before:
raise OSError(f"input changed while reading: {p}")
current[p] = before, data
# Publish the cache only after a complete scan, including deletions.
cache.clear()
cache.update(current)
return {p: data for p, (_, data) in current.items()}
def transfer_files(source):
return sorted(set(source) | {p for p in files() if p.startswith("tools/rune-dev-guard/")} | {"scripts/rune-dev"})
def watch(on_change, process, previous, cache, on_tick=None):
while process.poll() is None:
select.select([], [], [], .1)
if on_tick:
on_tick()
try:
current = inputs(cache)
except (OSError, json.JSONDecodeError):
continue # An editor or source relay is replacing a file.
if current != previous:
on_change(current)
previous = current
def stop(process):
if process.poll() is None:
os.killpg(process.pid, signal.SIGTERM)
try:
process.wait(timeout=15)
except subprocess.TimeoutExpired:
os.killpg(process.pid, signal.SIGKILL)
process.wait()
# --- Arguments --------------------------------------------------------------------------------
def parse(argv):
parser = argparse.ArgumentParser(prog="rune-dev", description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("example", nargs="?", choices=sorted(EXAMPLES))
parser.add_argument("--manifest-path", type=Path, help="an external app crate's Cargo.toml")
parser.add_argument("--package", help="default: the manifest's package")
parser.add_argument("--bin")
parser.add_argument("--features", default="", help="besides hot")
parser.add_argument("--patch", action="append", default=[], metavar="GLOB",
help="files, relative to the app crate, whose fn bodies patch live (repeatable; ** spans directories)")
parser.add_argument("--port", type=int, default=18744)
parser.add_argument("--desk", action="store_true", help="run the app on this Mac and compile on --build-host")
parser.add_argument("--local", action="store_true", default=bool(os.environ.get("RUNE_DEV_LOCAL")),
help="compile and run here; a restart-needed edit rebuilds and relaunches (env RUNE_DEV_LOCAL)")
parser.add_argument("--build-host", default=os.environ.get("RUNE_DEV_BUILD_HOST", "pro"), help="SSH host (env RUNE_DEV_BUILD_HOST)")
split = argv.index("--") if "--" in argv else len(argv)
opts, unknown = parser.parse_known_args(argv[:split])
# Before `--`, unrecognised arguments go to the app too, as they always have.
opts.app_args = unknown + argv[split + 1:]
if (opts.example is None) == (opts.manifest_path is None):
parser.error("name an example or pass --manifest-path")
if opts.manifest_path and not opts.patch:
parser.error("--manifest-path needs at least one --patch GLOB; every other file restarts")
if opts.example and (opts.patch or opts.package or opts.bin or opts.features):
parser.error("--patch, --package, --bin and --features are for --manifest-path")
if opts.local and opts.desk:
parser.error("--local runs everything here; --desk compiles on --build-host")
opts.parser = parser
return opts
def worker(host):
return os.environ.get("RUNE_DEV_WORKER", host)
# --- External crates --------------------------------------------------------------------------
def read_toml(path):
return tomllib.loads(Path(path).read_text())
def path_dependencies(doc, directory):
"""Directories of `path` dependencies in any dependency table, `[patch]` or `[replace]`."""
found = []
def walk(node, inside):
if isinstance(node, dict):
if inside and isinstance(node.get("path"), str):
found.append((directory / node["path"]).resolve())
for key, value in node.items():
walk(value, inside or key.endswith("dependencies") or key in ("patch", "replace"))
walk(doc, False)
return found
def workspace_root(package, stop=None):
doc = read_toml(package / "Cargo.toml")
explicit = doc.get("package", {}).get("workspace")
if isinstance(explicit, str):
return (package / explicit).resolve()
directory = package
while True:
manifest = directory / "Cargo.toml"
if manifest.exists() and "workspace" in read_toml(manifest):
return directory
if directory.parent == directory or directory == stop:
return None
directory = directory.parent
def external_layout(manifest):
"""The app crate, every path dependency and their workspaces' manifests and lockfiles."""
crate = manifest.resolve().parent
packages, roots = [], []
pending = [crate]
while pending:
package = pending.pop()
if package in packages:
continue
if not (package / "Cargo.toml").exists():
raise SystemExit(f"rune-dev: path dependency {package} has no Cargo.toml")
packages.append(package)
pending.extend(path_dependencies(read_toml(package / "Cargo.toml"), package))
root = workspace_root(package)
if root and root not in roots:
roots.append(root)
pending.extend(path_dependencies(read_toml(root / "Cargo.toml"), root))
base = Path(os.path.commonpath([*packages, *roots]))
rel = lambda p: str(PurePosixPath(p.relative_to(base).as_posix()))
tops = [rel(r / name) for r in roots for name in ("Cargo.toml", "Cargo.lock", "rust-toolchain", "rust-toolchain.toml", ".cargo/config.toml", ".cargo/config")
if (r / name).is_file()]
return External(base=base, crate=str(PurePosixPath("external", rel(crate))), dirs=sorted({rel(p) for p in packages}), tops=tops)
def workspace_key(crate, data):
"""The key of the app crate's workspace manifest among staged inputs, or None."""
doc = tomllib.loads(data[crate + "/Cargo.toml"].decode())
explicit = doc.get("package", {}).get("workspace")
if isinstance(explicit, str):
key = posixpath.normpath(posixpath.join(crate, explicit, "Cargo.toml"))
return key if key in data else None
directory = PurePosixPath(crate)
while True:
key = str(directory / "Cargo.toml")
if key in data and "workspace" in tomllib.loads(data[key].decode()):
return key
if str(directory) == "external":
return None
directory = directory.parent
def array_end(text, i):
"""The index after the TOML array whose `[` is at `i`."""
depth = 0
while i < len(text):
c = text[i]
if c == "#":
i = text.find("\n", i)
if i < 0: break
elif c in "\"'":
i += 1
while i < len(text) and text[i] != c:
i += 2 if c == '"' and text[i] == "\\" else 1
elif c == "[":
depth += 1
elif c == "]":
depth -= 1
if depth == 0: return i + 1
i += 1
raise ValueError("unterminated TOML array")
def staged_workspace(text, staged):
"""The app's workspace manifest with `members` and `default-members` cut to the staged
package directories (relative to it). Cargo loads every member, and the build Mac has
only the app and its path dependencies."""
workspace = tomllib.loads(text).get("workspace", {})
norm = lambda m: str(PurePosixPath(m))
excluded = {norm(m) for m in workspace.get("exclude", [])}
for key in ("default-members", "members"):
header = re.search(r"(?m)^[ \t]*\[workspace\][ \t]*(#.*)?$", text)
if key not in workspace or not header:
continue
end = re.compile(r"(?m)^[ \t]*\[").search(text, header.end())
found = re.compile(rf"(?m)^[ \t]*{re.escape(key)}[ \t]*=[ \t]*(?=\[)").search(text, header.end(), end.start() if end else len(text))
if not found:
continue
kept = sorted(d for d in staged if d not in excluded and any(PurePosixPath(d).full_match(norm(g)) for g in workspace[key]))
stop = array_end(text, found.end())
text = text[:found.end()] + json.dumps(kept) + text[stop:]
return text
def mirror_overrides(crate, data):
"""Mirror bytes that differ from the source: the app's workspace members."""
key = crate and workspace_key(crate, data)
if not key:
return {}
root = PurePosixPath(key).parent
staged = []
for k in data:
path = PurePosixPath(k)
if path.name == "Cargo.toml" and k != key and path.is_relative_to(root) and "package" in tomllib.loads(data[k].decode()):
staged.append(str(path.parent.relative_to(root)))
return {key: staged_workspace(data[key].decode(), staged).encode()}
def patchable(crate, globs):
"""Keys of the app crate's Rust files that `--patch` names. Everything else restarts."""
prefix = crate.rstrip("/") + "/"
def allowed(key):
if not key.startswith(prefix) or not key.endswith(".rs"):
return False
path = PurePosixPath(key.removeprefix(prefix))
return any(path.full_match(glob) for glob in globs)
return allowed
def crate_settings(crate_dir, stop):
"""(package name, whether a [profile.rune-hot] is defined) for an app crate on this machine."""
doc = read_toml(crate_dir / "Cargo.toml")
if "hot" not in doc.get("features", {}):
raise SystemExit(f'rune-dev: add `hot = ["rune/hot"]` to [features] in {crate_dir / "Cargo.toml"}')
root = workspace_root(crate_dir, stop) or crate_dir
profiles = read_toml(root / "Cargo.toml").get("profile", {})
return doc.get("package", {}).get("name"), "rune-hot" in profiles
def package_spec(crate_dir, stop):
"""`name@version` for an app crate, or just its name when the manifest has no version."""
package = read_toml(crate_dir / "Cargo.toml").get("package", {})
version = package.get("version")
if isinstance(version, dict) and version.get("workspace"):
root = workspace_root(crate_dir, stop) or crate_dir
version = read_toml(root / "Cargo.toml").get("workspace", {}).get("package", {}).get("version")
return f"{package['name']}@{version}" if isinstance(version, str) else package.get("name")
CARGO_SHIM = """#!/usr/bin/env python3
# dx builds with `cargo build -p NAME`, which Cargo rejects as ambiguous when a dependency
# shares the app's name; this names the app's version too.
import os, sys
real, name, spec = {real!r}, {name!r}, {spec!r}
args = sys.argv[1:]
for i, arg in enumerate(args):
if arg == name and i and args[i - 1] in ("-p", "--package"):
args[i] = spec
elif arg in ("-p" + name, "--package=" + name):
args[i] = arg[:-len(name)] + spec
os.execv(real, [real, *args])
"""
def cargo_shim(directory, name, spec, path):
"""A PATH whose `cargo` passes dx's `-p NAME` on as `-p NAME@VERSION`."""
real = shutil.which("cargo", path=path)
if not real or spec == name:
return path
directory.mkdir(parents=True, exist_ok=True)
shim = directory / "cargo"
shim.write_text(CARGO_SHIM.format(real=real, name=name, spec=spec))
shim.chmod(0o755)
return f"{directory}{os.pathsep}{path}"
def dx_command(dx, port, package, features, bin, cargo_config, app_args):
command = [str(dx), "serve", "--hot-patch", "--platform", "server", "--open", "false", "--interactive", "false",
"--addr", "127.0.0.1", "--port", str(port), "--package", package, "--features", ",".join(["hot", *filter(None, features.split(","))]), "--profile", "rune-hot"]
if bin:
command += ["--bin", bin]
if cargo_config:
command.append("--cargo-args=" + shlex.join(a for c in cargo_config for a in ("--config", c)))
if app_args:
# dx splits these on whitespace.
command.append("--args=" + " ".join(app_args))
return command
# --- Remote build host ------------------------------------------------------------------------
def ssh_options():
# One connection for every rsync, fetch and the tunnel.
return ["-o", "ControlMaster=auto", "-o", f"ControlPath=/tmp/rune-dev-{os.getuid()}-%C", "-o", "ControlPersist=60"]
def ssh(*args):
return ["ssh", *ssh_options(), *args]
def sha256(path):
digest = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(1 << 20), b""):
digest.update(chunk)
return digest.hexdigest()
def platform_info():
return {"system": platform.system(), "machine": platform.machine()}
def remote_argv(opts, desk):
"""The build Mac's arguments: an external crate is named by its staging path."""
argv = [opts.example] if opts.example else ["--manifest-path", EXTERNAL.crate + "/Cargo.toml"]
for flag in ("package", "bin"):
if getattr(opts, flag):
argv += ["--" + flag, getattr(opts, flag)]
if opts.features:
argv += ["--features", opts.features]
for glob in opts.patch:
argv += ["--patch", glob]
argv += ["--port", str(opts.port)]
if desk:
# The build Mac's copy only parks; the app's arguments are for the desk copy.
return argv + ["--desk"]
return argv + ["--", *opts.app_args]
def app_argv(opts, root):
"""Arguments for the app process, with Rune's file flags resolved against `root`."""
app_args = list(opts.app_args)
for flag in ("--snap-on-patch", "--hot-control", "--fixture"):
if flag in app_args:
i = app_args.index(flag) + 1
if i == len(app_args): opts.parser.error(flag + " needs a path")
app_args[i] = str((root / app_args[i]).resolve())
return (["--hot"] if opts.example else []) + app_args
def check_base(info, local):
if (info.get("system"), info.get("machine")) != (local["system"], local["machine"]):
return f"rune-dev: the build Mac built for {info.get('system')} {info.get('machine')}; this Mac is {local['system']} {local['machine']}"
return None
class Desk:
"""The desk copy of the app: the build Mac's binary, byte for byte, and the patches built for it."""
def __init__(self, host, cache, argv, cwd, env, ready=lambda: None):
self.host, self.cache, self.argv, self.cwd, self.env = host, cache, argv, cwd, env
# Raises unless the app's devserver path works; the app connects once, at startup.
self.ready = ready
self.lock = threading.Lock()
self.app = None
self.remote_exe = None
self.sha = None
self.restarting = False
self.failed = None
def base(self, info):
failure = check_base(info, platform_info())
if failure:
self.failed = failure
print(failure, file=sys.stderr, flush=True)
return
with self.lock:
if info["sha256"] == self.sha and self.app and self.app.poll() is None:
return
exe = self.cache / info["sha256"][:16] / Path(info["exe"]).name
if not exe.exists() or sha256(exe) != info["sha256"]:
exe.parent.mkdir(parents=True, exist_ok=True)
temp = exe.with_suffix(".fetch")
subprocess.run(["scp", *ssh_options(), "-q", f"{self.host}:{info['exe']}", str(temp)], check=True)
if sha256(temp) != info["sha256"]:
temp.unlink()
self.failed = "rune-dev: the copied app binary does not match the build Mac's"
print(self.failed, file=sys.stderr, flush=True)
return
temp.chmod(0o755)
temp.replace(exe)
self.ready()
self.restarting = True
if self.app:
print("rune-dev: the build Mac rebuilt the app; restarting it here", flush=True)
stop(self.app)
self.remote_exe, self.sha = info["exe"], info["sha256"]
self.app = subprocess.Popen([str(exe), *self.argv], cwd=self.cwd, env=self.env, start_new_session=True)
self.restarting = False
print(f"rune-dev: running {exe.name} here (sha256 {self.sha[:12]}), pid {self.app.pid}", flush=True)
def fetch_patch(self, lib):
"""Copies a patch dylib, after checking the build Mac still has the binary this one runs."""
with self.lock:
remote_exe, sha = self.remote_exe, self.sha
script = f"shasum -a 256 {shlex.quote(remote_exe)} | cut -c1-64 && cat {shlex.quote(lib)}"
out = subprocess.run(ssh(self.host, script), capture_output=True)
head, _, data = out.stdout.partition(b"\n")
if out.returncode or not data:
raise RuntimeError(f"rune-dev: could not fetch patch {lib}: {out.stderr.decode().strip()}")
built = head.decode().strip()
if built != sha:
raise RuntimeError(f"rune-dev: patch built against base {built[:12]}, but this Mac runs {sha[:12]}; not applying it")
dest = self.cache / sha[:16] / "patches" / PurePosixPath(lib).name
dest.parent.mkdir(parents=True, exist_ok=True)
temp = dest.with_suffix(".fetch")
temp.write_bytes(data)
temp.replace(dest)
return dest
def exited(self):
with self.lock:
return self.app is not None and not self.restarting and self.app.poll() is not None
BASE = "rune-dev-base "
def base_message(line):
"""The build Mac's base report in a line of its output; `ssh -tt` can prefix PTY bytes."""
at = line.find(BASE)
return None if at < 0 else json.loads(line[at + len(BASE):])
def tunnel_failure(tunnel):
if tunnel.poll() is not None:
return f"rune-dev: the SSH tunnel to dx exited ({tunnel.returncode}); edits can't reach the app. Rerun rune-dev."
return None
def answers(port):
"""Whether something answers HTTP through a forwarded port. ssh accepts a forwarded
connection before its remote end exists, and closes it silently when that fails."""
try:
with socket.create_connection(("127.0.0.1", port), timeout=2) as s:
s.sendall(b"GET / HTTP/1.0\r\nHost: 127.0.0.1\r\n\r\n")
return bool(s.recv(1))
except OSError:
return False
def wait_forward(port, tunnel, timeout=60.0, interval=.25):
deadline = time.monotonic() + timeout
while not answers(port):
failure = tunnel_failure(tunnel)
if failure:
raise RuntimeError(failure)
if time.monotonic() > deadline:
raise RuntimeError(f"rune-dev: dx did not answer through the SSH tunnel within {timeout:.0f} s")
time.sleep(interval)
def rewrite_patch(text, pid, fetch):
"""A devserver message with this process's patch dylib replaced by a local copy."""
try:
msg = json.loads(text)
except ValueError:
return text
reload = msg.get("HotReload") if isinstance(msg, dict) else None
table = reload and reload.get("jump_table")
if not table or reload.get("for_pid") != pid:
return text
table["lib"] = str(fetch(table["lib"]))
return json.dumps(msg)
def read_exact(stream, n):
data = stream.read(n)
if len(data) != n:
raise EOFError
return data
def read_frame(stream):
b0, b1 = read_exact(stream, 2)
n = b1 & 0x7f
if n == 126: n = int.from_bytes(read_exact(stream, 2))
elif n == 127: n = int.from_bytes(read_exact(stream, 8))
mask = read_exact(stream, 4) if b1 & 0x80 else None
payload = read_exact(stream, n)
if mask:
payload = bytes(b ^ mask[i % 4] for i, b in enumerate(payload))
return bool(b0 & 0x80), b0 & 0x0f, payload
def frame(opcode, payload, fin=True):
"""An unmasked server-to-client frame."""
n = len(payload)
head = bytes([(0x80 if fin else 0) | opcode])
if n < 126: head += bytes([n])
elif n < 1 << 16: head += bytes([126]) + n.to_bytes(2)
else: head += bytes([127]) + n.to_bytes(8)
return head + payload
class Prefixed:
def __init__(self, prefix, stream):
self.prefix, self.stream = prefix, stream
def read(self, n):
head, self.prefix = self.prefix[:n], self.prefix[n:]
return head + self.stream.read(n - len(head)) if len(head) < n else head
def read_head(sock):
data = b""
while b"\r\n\r\n" not in data:
chunk = sock.recv(4096)
if not chunk:
raise EOFError
data += chunk
head, _, rest = data.partition(b"\r\n\r\n")
return head + b"\r\n\r\n", rest
class PatchRelay:
"""The desk app's devserver: forwards the websocket to dx through the tunnel, and swaps each
patch dylib path on the build Mac for a copy on this one before the app loads it."""
def __init__(self, upstream, fetch, attempts=40, interval=.25):
self.upstream, self.fetch = upstream, fetch
self.attempts, self.interval = attempts, interval
self.server = socket.create_server(("127.0.0.1", 0))
self.port = self.server.getsockname()[1]
threading.Thread(target=self.accept, daemon=True).start()
def accept(self):
while True:
try:
client, _ = self.server.accept()
except OSError:
return
threading.Thread(target=self.connection, args=(client,), daemon=True).start()
def connection(self, client):
pid = None
try:
head, rest = read_head(client)
target = head.split(b"\r\n", 1)[0].split()[1].decode()
pid = int(parse_qs(urlsplit(target).query).get("pid", ["0"])[0])
# The frame reader below handles plain frames only.
lines = [l for l in head.split(b"\r\n") if not l.lower().startswith(b"sec-websocket-extensions:")]
upstream, response, body = self.handshake(b"\r\n".join(lines) + rest)
if b" 101 " not in response.split(b"\r\n", 1)[0] + b" ":
client.sendall(response + body)
return
client.sendall(response)
print(f"rune-dev: app pid {pid} connected to the devserver", flush=True)
threading.Thread(target=self.pipe, args=(client, upstream), daemon=True).start()
# Frames that arrived with the handshake are parsed like the rest.
self.patches(Prefixed(body, upstream.makefile("rb")), client, pid)
except EOFError:
if pid is not None:
print(f"rune-dev: app pid {pid} left the devserver", flush=True)
except (OSError, ValueError, IndexError) as error:
print(f"rune-dev: the devserver relay failed for app pid {pid}: {error}; edits will not reach it", file=sys.stderr, flush=True)
finally:
client.close()
def handshake(self, request):
"""The upgrade through the tunnel, retried while its remote end isn't there yet: ssh
accepts the connection and then closes it."""
failure = None
for _ in range(self.attempts):
upstream = None
try:
upstream = socket.create_connection(self.upstream, timeout=5)
upstream.sendall(request)
response, body = read_head(upstream)
upstream.settimeout(None)
return upstream, response, body
except (OSError, EOFError) as error:
failure = str(error) or "connection closed"
if upstream: upstream.close()
time.sleep(self.interval)
raise OSError(f"dx did not answer through the SSH tunnel ({failure})")
@staticmethod
def pipe(source, dest):
try:
while chunk := source.recv(65536):
dest.sendall(chunk)
except OSError:
pass
finally:
for s in (source, dest):
try: s.shutdown(socket.SHUT_RDWR)
except OSError: pass
def patches(self, stream, client, pid):
parts, binary = [], False
while True:
fin, op, payload = read_frame(stream)
if op >= 8 or op == 2 or (op == 0 and binary):
# Control and binary frames pass through as they came.
if op < 8: binary = not fin
client.sendall(frame(op, payload, fin))
continue
if op == 1:
parts = []
parts.append(payload)
if not fin:
continue
text = b"".join(parts).decode()
try:
text = rewrite_patch(text, pid, self.fetch)
except (RuntimeError, OSError) as error:
print(error, file=sys.stderr, flush=True)
continue
client.sendall(frame(1, text.encode()))
def close(self):
self.server.close()
def free_port():
with socket.socket() as s:
s.bind(("127.0.0.1", 0))
return s.getsockname()[1]
def relay(argv):
"""The desk Mac watches original files. The build Mac's guard sees a source staging area, never dx's mirror."""
global EXTERNAL
opts = parse(argv)
host = opts.build_host
if opts.manifest_path:
EXTERNAL = external_layout(opts.manifest_path)
key = str(ROOT) if not EXTERNAL else f"{ROOT}\0{EXTERNAL.base}\0{EXTERNAL.crate}"
tag = hashlib.sha256(key.encode()).hexdigest()[:12]
remote = os.environ.get("RUNE_DEV_REMOTE", f"scratch/rune-dev-{tag}")
# The build queue's local admission requires a Git root. This is an empty staging
# repository, not a copy of the user's history; the manifest supplies its inputs.
subprocess.run(ssh(host, f"mkdir -p {shlex.quote(remote)} && if [ ! -e {shlex.quote(remote + '/.git')} ]; then git -C {shlex.quote(remote)} init -q; fi"), check=True)
rsh = "ssh " + " ".join(shlex.quote(o) for o in ssh_options())
def sync(keys, listing):
own = [p for p in keys if not p.startswith("external/")]
external = [p.removeprefix("external/") for p in keys if p.startswith("external/")]
for paths, local, dest in ((own, ROOT, remote), (external, EXTERNAL and EXTERNAL.base, remote + "/external")):
if paths:
listing.write_text("\n".join(paths) + "\n")
subprocess.run(["rsync", "-ac", "-e", rsh, "--files-from", str(listing), str(local) + "/", f"{host}:{dest}/"], check=True)
with tempfile.TemporaryDirectory(prefix="rune-relay-") as tmp:
cache = {}
previous = inputs(cache)
manifest = Path(tmp) / ".rune-dev-files.json"
manifest.write_text(json.dumps(transfer_files(previous)))
listing = Path(tmp) / "files"
sync(transfer_files(previous), listing)
subprocess.run(["scp", *ssh_options(), "-q", str(manifest), f"{host}:{remote}/.rune-dev-files.json"], check=True)
command = f'export PATH="$HOME/.cargo/bin:$HOME/.local/bin:$HOME/bin:/opt/homebrew/bin:$PATH"; cd "$HOME/{remote}" && HIVEMIND_STRICT_PIN=1 hivemind run --worker {shlex.quote(worker(host))} --kind cargo --no-sync -- env RUNE_DEV_LEASE=1 python3 scripts/rune-dev ' + shlex.join(remote_argv(opts, opts.desk))
process = subprocess.Popen(["ssh", "-tt", host, command], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1, start_new_session=True)
desk = tunnel = patch_relay = None
snap = control = None
if opts.desk:
local = free_port()
tunnel = subprocess.Popen(["ssh", "-N", "-o", "ExitOnForwardFailure=yes", "-L", f"127.0.0.1:{local}:127.0.0.1:{opts.port}", host], start_new_session=True)
cwd = source(EXTERNAL.crate) if EXTERNAL else ROOT / "examples" / opts.example
env = {k: v for k, v in os.environ.items() if k not in ("RUNE_HOT_PARK", "RUNE_DEV_LEASE")}
# The app connects to its devserver once, at startup: start it only once dx answers.
desk = Desk(host, ROOT / "target/rune-dev-desk" / tag, app_argv(opts, Path.cwd()), cwd, env, lambda: wait_forward(local, tunnel))
patch_relay = PatchRelay(("127.0.0.1", local), desk.fetch_patch)
env.update(RUNE_DEV_GUARDED="1", RUNE_HOT="1", DIOXUS_DEVSERVER_IP="127.0.0.1", DIOXUS_DEVSERVER_PORT=str(patch_relay.port),
DIOXUS_BUILD_ID="0", CARGO_MANIFEST_DIR=str(cwd))
else:
def path_arg(flag):
return Path(opts.app_args[opts.app_args.index(flag) + 1]) if flag in opts.app_args[:-1] else None
snap = path_arg("--snap-on-patch")
control = path_arg("--hot-control")
def remote_path(path):
return str(path) if path.is_absolute() else f"{remote}/{path}"
if control:
subprocess.run(ssh(host, "mkdir -p " + shlex.quote(remote_path(control.parent))), check=True)
def receive():
for line in process.stdout:
if desk and BASE in line:
try:
desk.base(base_message(line))
except (subprocess.CalledProcessError, OSError, ValueError, RuntimeError) as error:
desk.failed = f"rune-dev: could not start the app here: {error}"
print(desk.failed, file=sys.stderr, flush=True)
continue
complete = True
if snap and "rune-hot-pixels " in line:
for path in (snap, snap.with_suffix(".json")):
dest = ROOT / path
dest.parent.mkdir(parents=True, exist_ok=True)
temp = dest.with_suffix(dest.suffix + ".fetch")
fetched = subprocess.run(["scp", *ssh_options(), "-q", f"{host}:{remote_path(path)}", str(temp)])
if fetched.returncode == 0: temp.replace(dest)
else: complete = False
if complete:
# A completion marker on the desk Mac means its local PNG/tree have arrived too.
print(line, end="", flush=True)
else:
print("rune-dev: snapshot fetch failed", file=sys.stderr, flush=True)
receiver = threading.Thread(target=receive, daemon=True)
receiver.start()
previous_control = None
def tick():
nonlocal previous_control
if desk and not desk.failed and (failure := tunnel_failure(tunnel)):
desk.failed = failure
print(failure, file=sys.stderr, flush=True)
if desk and (desk.failed or desk.exited()):
if not desk.failed:
print(f"rune-dev: the app exited ({desk.app.returncode})", flush=True)
stop(process)
return
if control:
try:
data = (ROOT / control).read_bytes()
except OSError:
return
if data != previous_control:
subprocess.run(["scp", *ssh_options(), "-q", str(ROOT / control), f"{host}:{remote_path(control)}"], check=True)
previous_control = data
def relay_source(current):
nonlocal previous
changed = [p for p, data in current.items() if previous.get(p) != data]
# Missing/new inputs are caught by the worker's manifest comparison.
sync(changed, listing)
manifest.write_text(json.dumps(transfer_files(current)))
subprocess.run(["scp", *ssh_options(), "-q", str(manifest), f"{host}:{remote}/.rune-dev-files.json"], check=True)
previous = current
where = "the app runs here; patches arrive over SSH" if desk else "PNG/tree snapshots are fetched here"
print(f"rune-dev: {host} source ~/{remote}; edit this checkout. {where}.", flush=True)
try:
watch(relay_source, process, previous, cache, tick)
finally:
for child in (desk and desk.app, tunnel, process):
if child: stop(child)
if patch_relay: patch_relay.close()
receiver.join(timeout=15)
if desk and desk.failed:
return 1
return process.returncode
class Restart(Exception):
"""A local run's edit needs a new build."""
def local(argv):
"""Compiles and runs the app here, rebuilding and relaunching it after a restart-needed edit."""
wrap = os.environ.get("RUNE_DEV_WRAP")
if wrap and not os.environ.get("RUNE_DEV_WRAPPED"):
os.environ["RUNE_DEV_WRAPPED"] = "1"
command = [*shlex.split(wrap), "python3", str(Path(__file__).resolve()), *argv]
os.execvp(command[0], command)
while True:
try:
return run(argv)
except Restart:
print("rune-dev: restarting with the new build", flush=True)
def run(args):
global EXTERNAL
opts = parse(args)
if not opts.local and "studio" in socket.gethostname().lower():
raise SystemExit("rune-dev: compiler and renderer must stay on Pro; restart without RUNE_DEV_LEASE")
parser = opts.parser
# The build Mac's copy parks in desk mode, so it needs no app arguments. A local run's file
# flags are relative to where it was started.
app_args = app_argv(opts, Path.cwd() if opts.local else ROOT) if not opts.desk else (["--hot"] if opts.example else [])
env = dict(os.environ, RUSTC_WRAPPER="", CARGO_INCREMENTAL="1", CARGO_BUILD_JOBS="2", RUNE_DEV_GUARDED="1", RUNE_HOT="1",
CARGO_TARGET_DIR=str(ROOT / "target/live-edit-build"))
env.pop("RUNE_HOT_PARK", None)
guard_root = ROOT / "tools/rune-dev-guard"
subprocess.run(["cargo", "build", "--manifest-path", str(guard_root / "Cargo.toml")], env=env, check=True)
guard = Path(env.get("CARGO_TARGET_DIR", str(guard_root / "target"))) / "debug/rune-dev-guard"
if opts.example:
mirror = ROOT / "target/rune-dev" / opts.example
allowed = EXAMPLES[opts.example].__contains__
package, crate, cargo_config = opts.example, None, []
else:
if (ROOT / ".rune-dev-files.json").exists():
# A relay staged the crate at its key.
crate = opts.manifest_path.parent.as_posix()
if crate != "external" and not crate.startswith("external/"): parser.error("a staged --manifest-path is external/…/Cargo.toml")
else:
EXTERNAL = external_layout(opts.manifest_path)
crate = EXTERNAL.crate
# Outside any checkout: Cargo would take an enclosing [workspace] for the app's.
mirror = Path(os.environ.get("XDG_CACHE_HOME", Path.home() / ".cache")) / "rune-dev" / hashlib.sha256(f"{ROOT}\0{crate}".encode()).hexdigest()[:12]
name, has_profile = crate_settings(source(crate), source("external"))
package = opts.package or name
if package == name:
spec = package_spec(source(crate), source("external"))
env["PATH"] = cargo_shim(mirror / ".rune-dev-bin", name, spec, env.get("PATH", os.defpath))
cargo_config = [] if has_profile else PROFILE
allowed = patchable(crate, opts.patch)
cache = {}
baseline = inputs(cache)
if crate and not any(p.startswith(crate + "/") for p in baseline):
parser.error(f"no files staged for {crate}")
# Remove stale source files, but retain compiler artifacts between invocations.
old_manifest = mirror / ".inputs.json"
if old_manifest.exists():
for p in set(json.loads(old_manifest.read_text())) - set(baseline):
(mirror / p).unlink(missing_ok=True)
overrides = mirror_overrides(crate, baseline)
for p, data in baseline.items():
data = overrides.get(p, data)
dest = mirror / p
dest.parent.mkdir(parents=True, exist_ok=True)
if not dest.exists() or dest.read_bytes() != data: dest.write_bytes(data)
old_manifest.parent.mkdir(parents=True, exist_ok=True)
old_manifest.write_text(json.dumps(list(baseline)))
# Workspace excludes reference this independent tool; Cargo needn't see its source.
dx = Path(os.environ.get("RUNE_DX", str(Path.home() / ".cargo/bin/dx")))
if not dx.exists(): parser.error("install dioxus-cli 0.7.10 (the Deno dx command is unrelated)")
park = mirror / ".rune-hot-park"
park.unlink(missing_ok=True)
if opts.desk:
env["RUNE_HOT_PARK"] = str(park)
command = dx_command(dx, opts.port, package, opts.features, opts.bin, cargo_config, app_args)
process = subprocess.Popen(command, cwd=mirror / crate if crate else mirror, env=env, start_new_session=True)
reported = None
def report_base():
# Each build's parked copy names the binary the desk Mac must run.
nonlocal reported
try:
exe = park.read_text()
stamp = park.stat().st_mtime_ns
except FileNotFoundError:
return
if (exe, stamp) != reported:
reported = exe, stamp
print(BASE + json.dumps({"exe": exe, "sha256": sha256(exe), **platform_info()}), flush=True)
try:
with tempfile.TemporaryDirectory(prefix="rune-guard-") as tmp:
candidate = Path(tmp) / "candidate.rs"
def publish(current):
nonlocal baseline
changed = [p for p, data in current.items() if baseline.get(p) != data]
incompatible = (set(current) ^ set(baseline)) | {p for p in changed if not allowed(p)}
if incompatible:
print("rune-dev: restart needed: " + ", ".join(sorted(incompatible)), flush=True)
if opts.local:
raise Restart()
return
for p in changed:
candidate.write_bytes(current[p])
if subprocess.run([str(guard), str(mirror / p), str(candidate)]).returncode:
return
# All files validated from immutable bytes before publishing any of them.
for p in changed:
dest = mirror / p
temp = dest.with_suffix(".rune-tmp")
temp.write_bytes(current[p])
temp.replace(dest)
baseline = current
print("rune-dev: accepted " + ", ".join(changed), flush=True)
watch(publish, process, baseline, cache, report_base if opts.desk else None)
finally:
stop(process)
return process.returncode
if __name__ == "__main__":
def interrupted(signum, frame):
raise KeyboardInterrupt()
signal.signal(signal.SIGTERM, interrupted)
signal.signal(signal.SIGHUP, interrupted)
try:
ours = sys.argv[1:sys.argv.index("--")] if "--" in sys.argv else sys.argv[1:]
if "--local" in ours or os.environ.get("RUNE_DEV_LOCAL"):
sys.exit(local(sys.argv[1:]))
if not os.environ.get("RUNE_DEV_LEASE"):
if "--desk" in ours or "studio" in socket.gethostname().lower():
sys.exit(relay(sys.argv[1:]))
os.environ["HIVEMIND_STRICT_PIN"] = "1"
host = os.environ.get("RUNE_DEV_BUILD_HOST", "pro")
os.execvp("hivemind", ["hivemind", "run", "--worker", worker(host), "--kind", "cargo", "--no-sync", "--", "env", "RUNE_DEV_LEASE=1", "python3", str(Path(__file__).resolve()), *sys.argv[1:]])
sys.exit(run(sys.argv[1:]))
except KeyboardInterrupt:
sys.exit(130)
+24
View File
@@ -0,0 +1,24 @@
#!/usr/bin/env bash
# Hot reload for a Rune app, compiled and run on this machine: `scripts/rune-dev --local` under the
# flags apps already pass. Saved edits to function bodies in the --patch files patch into the open
# window; any other edit rebuilds and restarts the app, so apps should restore their own state
# (tabs, route, drafts) at launch.
# scripts/rune-hot --manifest app/Cargo.toml --patch src/view.rs [--patch …] [--port 18745] \
# [-- APP ARGS]
# Needs Dioxus CLI 0.7.10 as `dx` in Cargo's bin directory (RUNE_DX overrides the path).
# RUNE_DEV_WRAP runs the build and the app under a command prefix (a build-queue lease, say);
# without it they run under plain cargo.
set -euo pipefail
here=$(cd "$(dirname "$0")" && pwd)
manifest="" port=18745 patches=()
while [[ $# -gt 0 ]]; do
case "$1" in
--manifest) manifest=$2; shift 2 ;;
--patch) patches+=(--patch "$2"); shift 2 ;;
--port) port=$2; shift 2 ;;
--) shift; break ;;
*) echo "rune-hot: unknown flag $1" >&2; exit 2 ;;
esac
done
[[ -n $manifest ]] || { echo "rune-hot: --manifest is required" >&2; exit 2; }
exec python3 "$here/rune-dev" --local --manifest-path "$manifest" ${patches[@]+"${patches[@]}"} --port "$port" -- "$@"
+5
View File
@@ -0,0 +1,5 @@
[
{"t": 0.1, "key": "shortcut", "type": "click"},
{"t": 0.3, "physical": "ctrl+alt+k"},
{"t": 0.5, "shortcut": "ctrl+alt+k"}
]
+15
View File
@@ -0,0 +1,15 @@
#!/usr/bin/env python3
"""Pin headless regression images. Usage: snap-ui.py OUT [BIN_DIR]. No native windows."""
import pathlib
import subprocess
import sys
out = pathlib.Path(sys.argv[1])
bin_dir = pathlib.Path(sys.argv[2]) if len(sys.argv) > 2 else pathlib.Path('target/release')
out.mkdir(parents=True, exist_ok=True)
cases = {
'settings-dark': ('settings', ['--scene', 'dark']),
'settings-light': ('settings', ['--scene', 'light']),
}
for name, (binary, args) in cases.items():
subprocess.run([str(bin_dir / binary), *args, '--snap', str(out / f'{name}.png')], check=True)
+412
View File
@@ -0,0 +1,412 @@
#!/usr/bin/env python3
"""Source-watch, external-crate and desk-relay regressions; no compiler, SSH, renderer or wall-clock waits."""
import importlib.machinery
import importlib.util
import io
import json
import os
from pathlib import Path
import socket
import sys
import tempfile
import threading
import unittest
from unittest.mock import Mock, patch
sys.dont_write_bytecode = True # no __pycache__ beside the script
loader = importlib.machinery.SourceFileLoader("rune_dev", str(Path(__file__).with_name("rune-dev")))
spec = importlib.util.spec_from_loader(loader.name, loader)
dev = importlib.util.module_from_spec(spec)
loader.exec_module(dev)
class WatchTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
self.names = ["Cargo.toml", "examples/settings/src/main.rs", "examples/settings/assets/font.ttf"]
for name in self.names:
path = self.root / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(b"original")
for mock in [patch.object(dev, "ROOT", self.root), patch.object(dev, "files", lambda: self.names)]:
mock.start()
self.addCleanup(mock.stop)
def fresh(self):
return {p: (self.root / p).read_bytes() for p in self.names if (self.root / p).is_file()}
def test_cache_matches_full_reads_through_saves_replacements_additions_and_deletions(self):
cache = {}
reads = []
read = Path.read_bytes
def counted(path):
reads.append(path)
return read(path)
with patch.object(Path, "read_bytes", counted):
first = dev.inputs(cache)
self.assertEqual(len(reads), 3)
self.assertEqual(dev.inputs(cache), first)
self.assertEqual(len(reads), 3, "unchanged scans must not re-read assets or source")
source = self.root / self.names[1]
saved = source.stat()
source.write_bytes(b"modified")
os.utime(source, ns=(saved.st_atime_ns, saved.st_mtime_ns))
changed = dev.inputs(cache)
self.assertEqual(changed[self.names[1]], b"modified")
self.assertEqual(reads[3:], [source], "same-size edits with restored mtime must be read")
replacement = self.root / "replacement"
replacement.write_bytes(b"replaced")
os.utime(replacement, ns=(saved.st_atime_ns, saved.st_mtime_ns))
replacement.replace(source)
self.assertEqual(dev.inputs(cache)[self.names[1]], b"replaced")
(self.root / self.names[0]).unlink()
self.names.append("examples/settings/src/added.rs")
(self.root / self.names[-1]).write_bytes(b"new")
self.assertEqual(dev.inputs(cache), self.fresh())
self.assertNotIn("Cargo.toml", cache)
def test_partial_read_does_not_publish_a_new_cache(self):
cache = {}
original = dev.inputs(cache)
source = self.root / self.names[1]
source.write_bytes(b"edit")
read = Path.read_bytes
def racing(path):
data = read(path)
if path == source:
path.write_bytes(b"finished edit")
return data
with patch.object(Path, "read_bytes", racing):
with self.assertRaises(OSError):
dev.inputs(cache)
self.assertEqual({p: data for p, (_, data) in cache.items()}, original)
self.assertEqual(dev.inputs(cache), self.fresh())
def test_shared_watch_retries_read_races_and_reports_each_change_once(self):
initial = {"view.rs": b"old"}
edited = {"view.rs": b"new"}
process = Mock()
process.poll.side_effect = [None, None, None, None, None, 0]
on_change, on_tick = Mock(), Mock()
with patch.object(dev.select, "select"), patch.object(dev, "inputs", side_effect=[initial, OSError("save in progress"), edited, edited, {}]):
dev.watch(on_change, process, initial, {}, on_tick)
self.assertEqual([call.args[0] for call in on_change.call_args_list], [edited, {}])
self.assertEqual(on_tick.call_count, 5)
class ArgumentTests(unittest.TestCase):
def test_examples_keep_their_old_command_lines(self):
opts = dev.parse(["settings", "--scene", "session", "--snap-on-patch", "a.png"])
self.assertEqual((opts.example, opts.app_args), ("settings", ["--scene", "session", "--snap-on-patch", "a.png"]))
self.assertEqual(dev.parse(["settings", "--", "--port", "1"]).port, 18744, "after -- every flag is the app's")
def test_external_crates_name_their_patchable_files(self):
opts = dev.parse(["--manifest-path", "../app/Cargo.toml", "--bin", "app", "--features", "fixture", "--patch", "src/ui/*.rs", "--desk", "--", "--hot-control", "c.json"])
self.assertEqual((opts.manifest_path, opts.bin, opts.features, opts.patch, opts.desk), (Path("../app/Cargo.toml"), "app", "fixture", ["src/ui/*.rs"], True))
self.assertEqual(opts.app_args, ["--hot-control", "c.json"])
for bad in [[], ["settings", "--manifest-path", "x/Cargo.toml"], ["--manifest-path", "x/Cargo.toml"], ["settings", "--patch", "*.rs"]]:
with self.subTest(bad=bad), self.assertRaises(SystemExit), patch("sys.stderr"):
dev.parse(bad)
def test_local_runs_take_the_flag_or_the_environment_but_not_desk(self):
argv = ["--manifest-path", "app/Cargo.toml", "--patch", "src/view.rs"]
with patch.dict(os.environ, {}, clear=False):
os.environ.pop("RUNE_DEV_LOCAL", None)
self.assertFalse(dev.parse(argv).local)
self.assertTrue(dev.parse([*argv, "--local"]).local)
os.environ["RUNE_DEV_LOCAL"] = "1"
self.assertTrue(dev.parse(argv).local)
with self.assertRaises(SystemExit), patch("sys.stderr"):
dev.parse([*argv, "--local", "--desk"])
def test_a_local_run_rebuilds_after_a_restart_and_returns_the_apps_exit(self):
with patch.dict(os.environ, {}, clear=False), patch.object(dev, "run", side_effect=[dev.Restart(), dev.Restart(), 3]) as run, patch("sys.stdout", io.StringIO()) as out:
os.environ.pop("RUNE_DEV_WRAP", None)
self.assertEqual(dev.local(["--local"]), 3)
self.assertEqual(run.call_count, 3)
self.assertEqual(out.getvalue().count("rune-dev: restarting with the new build"), 2)
def test_a_local_run_execs_itself_once_under_the_wrap_prefix(self):
with patch.dict(os.environ, {"RUNE_DEV_WRAP": "lease --kind build --"}, clear=False), patch.object(dev.os, "execvp") as execvp:
os.environ.pop("RUNE_DEV_WRAPPED", None)
execvp.side_effect = SystemExit(0)
with self.assertRaises(SystemExit):
dev.local(["--local", "--", "a"])
command = execvp.call_args.args[1]
self.assertEqual(command[:5], ["lease", "--kind", "build", "--", "python3"])
self.assertEqual(command[-3:], ["--local", "--", "a"])
self.assertEqual(os.environ["RUNE_DEV_WRAPPED"], "1")
def test_remote_arguments_name_the_staged_crate_and_park_the_build_copy(self):
opts = dev.parse(["--manifest-path", "/w/app/Cargo.toml", "--patch", "src/ui/**/*.rs", "--port", "9", "--", "--fixture", "f.json"])
with patch.object(dev, "EXTERNAL", dev.External(Path("/w"), "external/app", ["app"], [])):
self.assertEqual(dev.remote_argv(opts, False), ["--manifest-path", "external/app/Cargo.toml", "--patch", "src/ui/**/*.rs", "--port", "9", "--", "--fixture", "f.json"])
self.assertEqual(dev.remote_argv(opts, True)[-1], "--desk")
self.assertNotIn("f.json", dev.remote_argv(opts, True))
def test_dx_gets_the_app_target_and_an_adhoc_profile(self):
command = dev.dx_command("dx", 7, "app", "fixture,", "app", dev.PROFILE, [])
self.assertEqual(command[command.index("--features") + 1], "hot,fixture")
self.assertEqual(command[command.index("--bin") + 1], "app")
cargo_args = next(a for a in command if a.startswith("--cargo-args="))
self.assertIn("--config 'profile.rune-hot.inherits=\"dev\"'", cargo_args)
self.assertFalse(any(a.startswith("--args") for a in command), "no app arguments: RUNE_HOT enables Rune")
self.assertFalse(any(a.startswith("--cargo-args") for a in dev.dx_command("dx", 7, "app", "", None, [], ["--hot"])))
class ExternalTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name).resolve()
def write(self, name, text=""):
path = self.root / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text)
def test_layout_mirrors_path_dependencies_and_their_workspace_files(self):
self.write("work/Cargo.toml", '[workspace]\nmembers = ["app", "ui"]\n[workspace.dependencies]\nshared = { path = "../shared" }\n')
self.write("work/Cargo.lock")
self.write("work/.cargo/config.toml")
self.write("work/app/Cargo.toml", '[package]\nname = "app"\n[features]\nhot = ["rune/hot"]\n[dependencies]\nui = { path = "../ui" }\nshared.workspace = true\nrune = { git = "https://example.com/rune" }\n[lib]\npath = "src/lib.rs"\n')
self.write("work/ui/Cargo.toml", '[package]\nname = "ui"\n[target.\'cfg(unix)\'.dev-dependencies]\nleaf = { path = "../../leaf" }\n')
self.write("shared/Cargo.toml", '[package]\nname = "shared"\n')
self.write("leaf/Cargo.toml", '[package]\nname = "leaf"\n')
layout = dev.external_layout(self.root / "work/app/Cargo.toml")
self.assertEqual(layout.base, self.root)
self.assertEqual(layout.crate, "external/work/app")
self.assertEqual(layout.dirs, ["leaf", "shared", "work/app", "work/ui"])
self.assertEqual(sorted(layout.tops), ["work/.cargo/config.toml", "work/Cargo.lock", "work/Cargo.toml"])
self.assertEqual(dev.crate_settings(self.root / "work/app", self.root), ("app", False))
self.write("work/Cargo.toml", '[workspace]\n[profile.rune-hot]\ninherits = "dev"\n')
self.assertEqual(dev.crate_settings(self.root / "work/app", self.root), ("app", True))
self.write("work/ui/Cargo.toml", '[package]\nname = "ui"\n')
with self.assertRaisesRegex(SystemExit, "hot"):
dev.crate_settings(self.root / "work/ui", self.root)
def test_dx_names_the_app_by_version_when_a_dependency_shares_its_name(self):
self.write("work/Cargo.toml", '[workspace]\n[workspace.package]\nversion = "2.0.0"\n')
self.write("work/app/Cargo.toml", '[package]\nname = "codec"\nversion.workspace = true\n')
self.write("solo/Cargo.toml", '[package]\nname = "solo"\n')
self.assertEqual(dev.package_spec(self.root / "work/app", self.root), "codec@2.0.0")
self.assertEqual(dev.package_spec(self.root / "solo", self.root), "solo")
self.write("real/cargo", "#!/bin/sh\nprintf '%s\\n' \"$@\"\n")
(self.root / "real/cargo").chmod(0o755)
path = dev.cargo_shim(self.root / "bin", "codec", "codec@2.0.0", str(self.root / "real"))
self.assertEqual(path.split(os.pathsep)[0], str(self.root / "bin"))
run = lambda *args: dev.subprocess.run(["cargo", *args], env={"PATH": path + os.pathsep + os.defpath}, capture_output=True, text=True, check=True).stdout.split()
self.assertEqual(run("build", "-p", "codec", "--bin", "codec"), ["build", "-p", "codec@2.0.0", "--bin", "codec"])
self.assertEqual(run("rustc", "--package=codec", "-pcodec"), ["rustc", "--package=codec@2.0.0", "-pcodec@2.0.0"])
self.assertEqual(dev.cargo_shim(self.root / "none", "solo", "solo", str(self.root / "real")), str(self.root / "real"))
def test_external_keys_read_the_original_files(self):
self.write("app/Cargo.toml", '[package]\nname = "app"\n')
self.write("app/src/ui/list.rs", "fn view() {}")
self.write("app/target/debug/app", "binary")
layout = dev.external_layout(self.root / "app/Cargo.toml")
self.assertEqual(layout.crate, "external")
with patch.object(dev, "EXTERNAL", layout):
keys = dev.files()
self.assertIn("external/src/ui/list.rs", keys)
self.assertIn("scripts/rune-dev", keys)
self.assertFalse(any("target/" in k for k in keys))
self.assertEqual(dev.source("external/src/ui/list.rs").read_text(), "fn view() {}")
self.assertEqual(dev.source("scripts/rune-dev"), dev.ROOT / "scripts/rune-dev")
self.assertEqual(set(dev.inputs({})), {"external/Cargo.toml", "external/src/ui/list.rs"})
def test_the_mirrored_workspace_lists_only_staged_members(self):
manifest = ('[workspace]\nresolver = "2"\n# members below\nmembers = [\n "app", # the app\n "crates/*",\n "tools/[x]",\n]\n'
'default-members = ["app", "tools/cli"]\nexclude = ["crates/old"]\n\n[workspace.dependencies]\nui = { path = "crates/ui" }\n')
self.write("ws/Cargo.toml", manifest)
self.write("ws/app/Cargo.toml", '[package]\nname = "app"\n[features]\nhot = ["rune/hot"]\n[dependencies]\nui.workspace = true\n')
self.write("ws/crates/ui/Cargo.toml", '[package]\nname = "ui"\n')
self.write("ws/crates/old/Cargo.toml", '[package]\nname = "old"\n')
self.write("ws/crates/other/Cargo.toml", '[package]\nname = "other"\n')
self.write("ws/tools/cli/Cargo.toml", '[package]\nname = "cli"\n')
layout = dev.external_layout(self.root / "ws/app/Cargo.toml")
self.assertEqual(layout.dirs, ["app", "crates/ui"], "unrelated members aren't staged")
with patch.object(dev, "EXTERNAL", layout):
data = dev.inputs({})
# The build Mac has only these: a workspace naming crates/other or tools/cli fails to load.
self.assertNotIn("external/crates/other/Cargo.toml", data)
overrides = dev.mirror_overrides(layout.crate, data)
self.assertEqual(list(overrides), ["external/Cargo.toml"])
staged = dev.tomllib.loads(overrides["external/Cargo.toml"].decode())
self.assertEqual(staged["workspace"]["members"], ["app", "crates/ui"])
self.assertEqual(staged["workspace"]["default-members"], ["app"])
self.assertEqual(staged["workspace"]["dependencies"], {"ui": {"path": "crates/ui"}})
self.assertIn("# members below", overrides["external/Cargo.toml"].decode(), "the rest of the file is kept")
self.write("ws/Cargo.toml", '[workspace]\n')
self.write("ws/app/Cargo.toml", '[package]\nname = "app"\nworkspace = ".."\n')
self.assertEqual(dev.workspace_key("external/app", {"external/Cargo.toml": b"[workspace]\n", "external/app/Cargo.toml": b'[package]\nworkspace = ".."\n'}), "external/Cargo.toml")
self.assertEqual(dev.mirror_overrides("external/app", {"external/app/Cargo.toml": b'[package]\nname = "app"\n'}), {}, "a lone crate is mirrored as is")
def test_only_globbed_rust_files_in_the_app_crate_patch(self):
allowed = dev.patchable("external/work/app", ["src/ui/*.rs", "src/views/**/*.rs"])
self.assertTrue(allowed("external/work/app/src/ui/list.rs"))
self.assertTrue(allowed("external/work/app/src/views/a/b/c.rs"))
for key in ["external/work/app/src/ui/nested/list.rs", "external/work/app/src/ui/icon.svg", "external/work/app/src/main.rs",
"external/work/app/Cargo.toml", "external/work/ui/src/ui/list.rs", "external/work/application/src/ui/list.rs",
"external/rune/crates/rune/src/runtime.rs"]:
self.assertFalse(allowed(key), key)
def ws_frame(opcode, payload, fin=True):
return dev.frame(opcode, payload, fin)
class DeskTests(unittest.TestCase):
def test_only_this_process_patch_is_fetched_and_rewritten(self):
message = {"HotReload": {"jump_table": {"lib": "/build/libserver-patch-1.dylib", "map": {"4294983856": 4295000000}, "aslr_reference": 1, "new_base_address": 2},
"templates": [], "assets": [], "ms_elapsed": 1, "for_pid": 42, "for_build_id": 0}}
fetched = []
def fetch(lib):
fetched.append(lib)
return Path("/desk/patches/libserver-patch-1.dylib")
rewritten = json.loads(dev.rewrite_patch(json.dumps(message), 42, fetch))
self.assertEqual(rewritten["HotReload"]["jump_table"]["lib"], "/desk/patches/libserver-patch-1.dylib")
self.assertEqual(rewritten["HotReload"]["jump_table"]["map"], message["HotReload"]["jump_table"]["map"])
self.assertEqual(fetched, ["/build/libserver-patch-1.dylib"])
for other in [json.dumps(message).replace('"for_pid": 42', '"for_pid": 7'), '"HotPatchStart"', "not json", '{"HotReload": {"jump_table": null, "for_pid": 42}}']:
self.assertEqual(dev.rewrite_patch(other, 42, fetch), other)
self.assertEqual(len(fetched), 1)
def test_a_patch_for_another_base_binary_is_refused(self):
with tempfile.TemporaryDirectory() as tmp:
desk = dev.Desk("build", Path(tmp), [], tmp, {})
desk.remote_exe, desk.sha = "/build/server", "a" * 64
result = Mock(returncode=0, stdout=b"b" * 64 + b"\nPATCH", stderr=b"")
with patch.object(dev.subprocess, "run", return_value=result), self.assertRaisesRegex(RuntimeError, "not applying"):
desk.fetch_patch("/build/libserver-patch-2.dylib")
result.stdout = b"a" * 64 + b"\nPATCH"
with patch.object(dev.subprocess, "run", return_value=result) as run:
local = desk.fetch_patch("/build/libserver-patch-2.dylib")
self.assertEqual(local.read_bytes(), b"PATCH")
self.assertEqual(local.name, "libserver-patch-2.dylib")
self.assertIn("shasum -a 256 /build/server", run.call_args.args[0][-1])
def test_a_base_for_another_platform_fails_before_copying(self):
local = {"system": "Darwin", "machine": "arm64"}
self.assertIsNone(dev.check_base({"system": "Darwin", "machine": "arm64"}, local))
self.assertIn("x86_64", dev.check_base({"system": "Darwin", "machine": "x86_64"}, local))
with tempfile.TemporaryDirectory() as tmp, patch.object(dev, "platform_info", return_value=local), patch.object(dev.subprocess, "run") as run, patch("sys.stderr"):
desk = dev.Desk("build", Path(tmp), [], tmp, {})
desk.base({"exe": "/build/server", "sha256": "a" * 64, "system": "Linux", "machine": "arm64"})
self.assertIn("Linux", desk.failed)
run.assert_not_called()
def test_a_base_report_behind_pty_bytes_still_starts_the_desk_app(self):
info = {"exe": "/build/server", "sha256": "a" * 64, "system": "Darwin", "machine": "arm64"}
for line in [dev.BASE + json.dumps(info) + "\n", "\r\x1b[K" + dev.BASE + json.dumps(info) + "\r\n"]:
self.assertEqual(dev.base_message(line), info)
self.assertIsNone(dev.base_message("Compiling app\n"))
def forwarded(self, behaviour):
"""A stand-in for an `ssh -L` port: accepts, then answers or closes like a missing remote."""
server = socket.create_server(("127.0.0.1", 0))
self.addCleanup(server.close)
def serve():
while True:
try:
conn, _ = server.accept()
except OSError:
return
with conn:
behaviour(conn)
threading.Thread(target=serve, daemon=True).start()
return server.getsockname()[1]
def test_the_desk_app_waits_for_dx_through_the_tunnel_and_a_dead_tunnel_fails_loudly(self):
silent = self.forwarded(lambda conn: None)
self.assertFalse(dev.answers(silent), "ssh accepting a forward isn't dx answering")
tunnel = Mock(returncode=255)
tunnel.poll.side_effect = [None, None, 255]
with self.assertRaisesRegex(RuntimeError, "tunnel to dx exited"):
dev.wait_forward(silent, tunnel, timeout=30, interval=.01)
with self.assertRaisesRegex(RuntimeError, "did not answer"):
dev.wait_forward(silent, Mock(poll=Mock(return_value=None)), timeout=.05, interval=.01)
calls = []
def dx(conn):
calls.append(1)
if len(calls) > 2:
conn.recv(1024)
conn.sendall(b"HTTP/1.1 404 Not Found\r\n\r\n")
dev.wait_forward(self.forwarded(dx), Mock(poll=Mock(return_value=None)), timeout=30, interval=.01)
self.assertEqual(len(calls), 3, "the app starts once dx answers, not before")
self.assertIsNone(dev.tunnel_failure(Mock(poll=Mock(return_value=None))))
self.assertIn("Rerun", dev.tunnel_failure(Mock(poll=Mock(return_value=1), returncode=1)))
def test_the_relay_retries_dx_while_the_forward_comes_up(self):
calls = []
def dx(conn):
calls.append(1)
if len(calls) < 3:
return # ssh closing a forward whose remote end isn't listening yet
dev.read_head(conn)
conn.sendall(b"HTTP/1.1 101 Switching Protocols\r\n\r\n")
conn.recv(1)
relay = dev.PatchRelay(("127.0.0.1", self.forwarded(dx)), lambda lib: lib, interval=.01)
self.addCleanup(relay.close)
with socket.create_connection(("127.0.0.1", relay.port), timeout=10) as app:
app.sendall(b"GET /_dioxus?pid=7 HTTP/1.1\r\nHost: x\r\n\r\n")
response, _ = dev.read_head(app)
self.assertIn(b"101", response)
self.assertEqual(len(calls), 3)
def test_relay_rewrites_fragmented_patches_and_passes_other_frames(self):
upstream = socket.create_server(("127.0.0.1", 0))
self.addCleanup(upstream.close)
patch_message = json.dumps({"HotReload": {"jump_table": {"lib": "/build/p.dylib", "map": {}}, "for_pid": 42}}).encode()
long = json.dumps({"FullReloadStart": "x" * 70000}).encode()
seen = {}
def dx():
conn, _ = upstream.accept()
head, _ = dev.read_head(conn)
seen["head"] = head
conn.sendall(b"HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n")
conn.sendall(ws_frame(9, b"ping") + ws_frame(1, patch_message[:10], False) + ws_frame(0, patch_message[10:]) + ws_frame(1, long))
fin, op, payload = dev.read_frame(conn.makefile("rb"))
seen["client"] = (fin, op, payload)
conn.close()
server = threading.Thread(target=dx, daemon=True)
server.start()
relay = dev.PatchRelay(upstream.getsockname(), lambda lib: Path("/desk/p.dylib"))
self.addCleanup(relay.close)
with socket.create_connection(("127.0.0.1", relay.port)) as app:
app.sendall(b"GET /_dioxus?aslr_reference=1&build_id=0&pid=42 HTTP/1.1\r\nHost: x\r\nSec-WebSocket-Extensions: permessage-deflate\r\n\r\n")
response, rest = dev.read_head(app)
self.assertIn(b"101", response)
data = rest
def next_frame():
nonlocal data
while True:
try:
frame = dev.read_frame(io.BytesIO(data))
size = len(dev.frame(frame[1], frame[2], frame[0]))
data = data[size:]
return frame
except EOFError:
chunk = app.recv(65536)
if not chunk: raise
data += chunk
frames = [next_frame() for _ in range(3)]
mask = b"\x01\x02\x03\x04"
payload = b"pong"
app.sendall(bytes([0x8a, 0x80 | len(payload)]) + mask + bytes(b ^ mask[i % 4] for i, b in enumerate(payload)))
server.join(5)
self.assertNotIn(b"permessage-deflate", seen["head"].lower())
self.assertEqual(frames[0], (True, 9, b"ping"))
self.assertEqual(json.loads(frames[1][2])["HotReload"]["jump_table"]["lib"], "/desk/p.dylib")
self.assertEqual(frames[2], (True, 1, long))
self.assertEqual(seen["client"], (True, 10, b"pong"), "the app's frames reach dx unchanged")
if __name__ == "__main__":
unittest.main()
+45
View File
@@ -0,0 +1,45 @@
#!/usr/bin/env python3
"""Offline hypothesis search; production GPU renders must validate any selected result.
Fit on first two strings per size, report held-out last three. Never fit geometry.
"""
import argparse
import importlib.util
import json
from pathlib import Path
import numpy as np
from scipy.ndimage import maximum_filter
spec=importlib.util.spec_from_file_location('quality',Path(__file__).with_name('text-quality.py'))
q=importlib.util.module_from_spec(spec); spec.loader.exec_module(q)
p=argparse.ArgumentParser(); p.add_argument('directory',type=Path); a=p.parse_args()
results=[]
for scale in (1,2):
raw=q.read(a.directory/f'coverage-{scale}x.png')
expanded=maximum_filter(raw,size=3)
for mode in ('light','dark'):
m=json.loads((a.directory/f'{mode}-{scale}x.json').read_text())
ref=q.read(a.directory/f'coretext-{mode}-{scale}x.png')
fg=m['fg']/255; bg=m['bg']/255
train=np.zeros(raw.shape,dtype=bool); holdout=train.copy()
for i,row in enumerate(m['rows']):
y=int(row['top']); last=row['glyphs'][-1]
right=int(last['x']+last['advance']+4)
(train if i%5<2 else holdout)[y:y+42*scale,:right]=True
mask=((np.abs(ref-bg)>.005)|(raw>0))
train &= mask; holdout &= mask
candidates=[]
for dilation in (0,.05,.1,.15,.2,.3):
cov=raw+dilation*(expanded-raw)
for gamma in np.arange(.4,2.01,.05):
rendered=q.encode(q.decode(bg)+(q.decode(fg)-q.decode(bg))*cov**gamma)
err=(rendered-ref)**2
candidates.append({'gamma':round(float(gamma),3),'dilation':dilation,
'train_rmse':float(np.sqrt(err[train].mean())),
'holdout_rmse':float(np.sqrt(err[holdout].mean()))})
candidates.sort(key=lambda c:c['train_rmse'])
result={'scale':scale,'mode':mode,'best':candidates[:5],
'gamma_only':min((c for c in candidates if c['dilation']==0),key=lambda c:c['train_rmse'])}
results.append(result); print(json.dumps(result))
(a.directory/'sweep.json').write_text(json.dumps(results,indent=2)+'\n')
+49
View File
@@ -0,0 +1,49 @@
#!/usr/bin/env python3
"""Refresh text-affected stills, reusing the committed Storybook reference columns.
Run after building settings and kit-gallery in release mode. No browser.
Historical motion strips are separate captures; this updates only named stills.
"""
import importlib.util
import json
from pathlib import Path
import shutil
import subprocess
from PIL import Image
ROOT = Path(__file__).resolve().parents[1]
OUT = ROOT / 'perf/autoresearch/text/goldens'
OUT.mkdir(parents=True, exist_ok=True)
spec = importlib.util.spec_from_file_location('kit_diff', ROOT / 'scripts/kit-diff.py')
kit = importlib.util.module_from_spec(spec)
spec.loader.exec_module(kit)
def snap(binary, path, *args):
subprocess.run([str(ROOT / 'target/release' / binary), *args, '--snap', str(path)],
cwd=ROOT, check=True, capture_output=True)
snap('settings', ROOT / 'demo/settings-dark.png', '--theme', 'dark')
snap('settings', ROOT / 'demo/settings-light.png', '--scene', 'light')
report = []
for path in sorted((ROOT / 'demo/kit').glob('side-*.png')):
story, scheme = path.stem.removeprefix('side-').rsplit('-', 1)
directory = OUT / f'{story}-{scheme}'
directory.mkdir(exist_ok=True)
image = Image.open(path).convert('RGB')
width, height = (image.width - 16) // 3, image.height
image.crop((0, 0, width, height)).save(directory / 'web.png')
snap('kit-gallery', directory / 'rune.png', '--scene', story, '--theme', scheme,
'--size', f'{width // 2}x{height // 2}', '--scale', '2')
result = {'story': story, 'scheme': scheme, **kit.compare(directory / 'web.png', directory / 'rune.png', directory)}
report.append(result)
shutil.copyfile(directory / 'side.png', path)
for scheme in ('light', 'dark'):
snap('kit-gallery', ROOT / f'demo/kit/index-{scheme}.png',
'--theme', scheme, '--size', '720x1400', '--scale', '1')
(ROOT / 'demo/text/kit-metrics.json').write_text(json.dumps(report, indent=2) + '\n')
print(json.dumps(report, indent=2))
+92
View File
@@ -0,0 +1,92 @@
#!/usr/bin/env python3
"""SSIM on ink-bounded row crops, signed ink weight, and per-glyph advance-cell errors.
uv run --with numpy --with pillow --with scikit-image scripts/text-quality.py DIR
SSIM: Wang et al., IEEE TIP 2004. Gaussian sigma=1.5, population covariance, L=1.
No alignment search, rescaling, or full-page empty-background score inflation.
"""
import argparse
import json
from pathlib import Path
import numpy as np
from PIL import Image, ImageDraw
from skimage.metrics import structural_similarity
def decode(x):
return np.where(x <= .04045, x/12.92, ((x+.055)/1.055)**2.4)
def encode(x):
return np.where(x <= .0031308, x*12.92, 1.055*np.maximum(x,0)**(1/2.4)-.055)
def read(path):
return np.asarray(Image.open(path).convert('RGB'),dtype=np.float64)[:,:,0]/255
def save(path, data):
Image.fromarray(np.uint8(np.clip(data*255+.5,0,255))).save(path)
def analyze(root):
results=[]
for manifest in sorted(root.glob('[dl]*-?x.json')):
m=json.loads(manifest.read_text()); name=manifest.stem
a=read(root/f'rune-{name}.png'); b=read(root/f'coretext-{name}.png')
fg=m['fg']/255; bg=m['bg']/255
ink_a=(a-bg)/(fg-bg); ink_b=(b-bg)/(fg-bg)
rows=[]; glyphs=[]
for ri,row in enumerate(m['rows']):
y0=int(row['top']); y1=min(a.shape[0],y0+int(42*m['scale']))
mask=(np.abs(a[y0:y1]-bg)>.01)|(np.abs(b[y0:y1]-bg)>.01)
yy,xx=np.where(mask)
if not len(xx): continue
x0=max(0,int(xx.min())-6); x1=min(a.shape[1],int(xx.max())+7)
crop=(slice(y0,y1),slice(x0,x1))
ssim=structural_similarity(a[crop],b[crop],data_range=1,gaussian_weights=True,
sigma=1.5,use_sample_covariance=False)
ia=ink_a[crop].sum(); ib=ink_b[crop].sum()
rows.append({'size':row['size'],'text':row['text'],'ssim':ssim,
'weight_error_pct':100*(ia/ib-1),'ink_mae':float(np.abs(ink_a[crop]-ink_b[crop]).sum()/ib)})
for gi,g in enumerate(row['glyphs']):
# Advance cells attribute overlapping side bearings consistently to each origin.
l=int(g['x']); r=int(row['glyphs'][gi+1]['x']) if gi+1<len(row['glyphs']) else int(g['x']+g['advance']+3)
ca=ink_a[y0:y1,l:r]; cb=ink_b[y0:y1,l:r]
if cb.sum()>.1:
glyphs.append({'row':ri,'glyph':g['id'],'x':g['x'],'coverage_rune':float(ca.sum()),
'coverage_coretext':float(cb.sum()),'weight_error_pct':float(100*(ca.sum()/cb.sum()-1))})
result={'name':name,'ssim':float(np.mean([r['ssim'] for r in rows])),
'mean_abs_weight_error_pct':float(np.mean([abs(r['weight_error_pct']) for r in rows])),
'signed_weight_error_pct':float(np.mean([r['weight_error_pct'] for r in rows])),
'ink_mae':float(np.mean([r['ink_mae'] for r in rows])), 'rows':rows,'glyphs':glyphs}
results.append(result)
save(root/f'diff-{name}.png',np.abs(a-b)*4)
sheet=Image.new('RGB',(a.shape[1]*2,a.shape[0]+24),'#777777')
sheet.paste(Image.open(root/f'rune-{name}.png'),(0,24))
sheet.paste(Image.open(root/f'coretext-{name}.png'),(a.shape[1],24))
draw=ImageDraw.Draw(sheet); draw.text((8,5),'Rune',fill='white'); draw.text((a.shape[1]+8,5),'CoreText matched glyph positions',fill='white')
sheet.save(root/f'compare-{name}.png')
print(json.dumps({k:v for k,v in result.items() if k not in ('rows','glyphs')}))
for scale in (1,2):
path=root/f'phases-{scale}x.png'
if not path.exists(): continue
# White-on-black GPU sRGB output -> linear atlas coverage.
p=decode(read(path)).reshape(128,40,-1)
sums=p.sum(axis=(1,2)); mean=sums.mean()
shimmer={'scale':scale,'coverage_cv_pct':float(100*sums.std()/mean),
'coverage_peak_to_peak_pct':float(100*np.ptp(sums)/mean),
'frame_delta_rms_pct':float(100*np.sqrt(np.mean(np.diff(sums)**2))/mean)}
results.append({'motion':shimmer}); print(json.dumps(shimmer))
for mode in ('light','dark'):
m=json.loads((root/f'{mode}-{scale}x.json').read_text())
fg=m['fg']/255; bg=m['bg']/255
gamma=m.get('gamma',.78+.22*fg)
pixels=encode(decode(bg)+(decode(fg)-decode(bg))*p**gamma)
ink=(pixels-bg)/(fg-bg); mass=ink.sum(axis=(1,2))
brightness={'scale':scale,'mode':mode,'gamma':gamma,
'brightness_cv_pct':float(100*mass.std()/mass.mean()),
'frame_delta_rms_pct':float(100*np.sqrt(np.mean(np.diff(mass)**2))/mass.mean())}
results.append({'brightness':brightness}); print(json.dumps(brightness))
strip=np.concatenate([p[i] for i in (0,8,16,24,32,40,48,56,64)],axis=0)
save(root/f'phase-strip-{scale}x.png',encode(strip))
(root/'metrics.json').write_text(json.dumps(results,indent=2)+'\n')
if __name__=='__main__':
parser=argparse.ArgumentParser(); parser.add_argument('directory',type=Path)
analyze(parser.parse_args().directory)
+47
View File
@@ -0,0 +1,47 @@
#!/usr/bin/env python3
"""Publish compact comparison/phase strips and measurements; keep raw frames out of git."""
import argparse
import json
from pathlib import Path
import numpy as np
from PIL import Image, ImageDraw
p=argparse.ArgumentParser(); p.add_argument('runs',type=Path);p.add_argument('out',type=Path);a=p.parse_args()
a.out.mkdir(parents=True,exist_ok=True)
metrics={}
for font in ('inter','sf'):
before=a.runs/'before'/font;after=a.runs/'after'/font
# Keep only aggregates in the public report. text-quality.py regenerates the
# per-row and per-glyph data under the ignored run directory when needed.
metrics[font]={stage:[{k:v for k,v in result.items() if k not in ('rows','glyphs')}
for result in json.loads((a.runs/stage/font/'metrics.json').read_text())]
for stage in ('before','after')}
for scale in (1,2):
for mode in ('light','dark'):
name=f'{mode}-{scale}x';m=json.loads((after/f'{name}.json').read_text())
width=400*scale;row_h=42*scale;gap=8
sheet=Image.new('RGB',(width*3+gap*2,28+5*row_h),'#808080')
draw=ImageDraw.Draw(sheet)
for col,(directory,stem,title) in enumerate([(before,'rune','Before'),(after,'rune','After'),(after,'coretext','CoreText')]):
draw.text((col*(width+gap)+8,8),title,fill='white')
image=Image.open(directory/f'{stem}-{name}.png').convert('RGB')
for ri,row in enumerate(m['rows'][::5]):
y=int(row['top']);sheet.paste(image.crop((0,y,width,y+row_h)),(col*(width+gap),28+ri*row_h))
sheet.save(a.out/f'{font}-{name}.png')
ref=np.array(Image.open(after/f'coretext-{name}.png').convert('RGB'),dtype=np.int16)
diffs=Image.new('RGB',(width*2+gap,28+5*row_h),'#808080');d=ImageDraw.Draw(diffs)
for col,directory in enumerate((before,after)):
d.text((col*(width+gap)+8,8),('Before' if col==0 else 'After')+' absolute error x4',fill='white')
image=np.array(Image.open(directory/f'rune-{name}.png').convert('RGB'),dtype=np.int16)
diff=Image.fromarray(np.uint8(np.clip(abs(image-ref)*4,0,255)))
for ri,row in enumerate(m['rows'][::5]):
y=int(row['top']);diffs.paste(diff.crop((0,y,width,y+row_h)),(col*(width+gap),28+ri*row_h))
diffs.save(a.out/f'{font}-diff-{name}.png')
strip=Image.new('RGB',(648,28+40*9),'#808080');draw=ImageDraw.Draw(strip)
for col,directory in enumerate((before,after)):
draw.text((col*328+8,8),'Before' if col==0 else 'After',fill='white')
image=Image.open(directory/f'phases-{scale}x.png').convert('RGB')
for row,frame in enumerate((0,8,16,24,32,40,48,56,64)):
strip.paste(image.crop((0,frame*40,320,(frame+1)*40)),(col*328,28+row*40))
strip.save(a.out/f'{font}-phases-{scale}x.png')
(a.out/'metrics.json').write_text(json.dumps(metrics,indent=2)+'\n')
+27
View File
@@ -0,0 +1,27 @@
#!/usr/bin/env python3
"""Research-15 metrics from Rune traces. Virtual cadence is not measured display cadence."""
import json
import statistics
import sys
for path in sys.argv[1:]:
rows = [json.loads(s) for s in open(path)]
header = rows[0]
frames = [r for r in rows if 'quality' in r]
period = 1000 / header['hz']
intervals = [b['t'] - a['t'] for a, b in zip(frames, frames[1:])]
duration = frames[-1]['t'] - frames[0]['t']
q = [r['quality'] for r in frames]
cpu = [r['quality']['cpu_ms'] for r in frames[1:]]
errors = sorted(r['position_error_px'] for r in q)
print(json.dumps({
'trace': path, 'clock': header['clock'],
'position_frame_max_p99_px': errors[round((len(errors) - 1) * .99)],
'position_max_px': max(errors),
'retarget_lanes': sum(r['retarget_lanes'] for r in q),
'retarget_velocity_max_pt_s': max(r['velocity_error_pt_s'] for r in q),
'virtual_hitch_ms_s': sum(max(0, t - period) for t in intervals) / duration * 1000 if duration else 0,
'virtual_cadence_sigma_periods': statistics.pstdev(t / period - 1 for t in intervals) if intervals else 0,
'cpu_budget_excess_ms_s': sum(max(0, t - period) for t in cpu) / duration * 1000 if duration else 0,
'animating_at_end': q[-1]['animating'],
}, indent=2))
+24
View File
@@ -0,0 +1,24 @@
#!/usr/bin/env bash
# Re-makes vendor/accesskit_macos: the accesskit_macos crate exactly as published on crates.io at
# <version>, without its integration tests, plus vendor/accesskit_macos.patch (headings as AppKit's
# AXHeading with their level as the value, which the published adapter reports as a "Heading" role
# VoiceOver doesn't know, so VoiceOver's rotor and VO-Command-H found no heading; and accessibility
# children, focus and hit test reading the adapter's state only on the main thread, since AppKit
# calls them from a background thread while the process queries itself and the main thread may hold
# that borrow, which raced or aborted). Run it when
# AccessKit is bumped, then build: a patch that no longer applies fails here, and the change goes
# back in by hand. If upstream AccessKit takes the change, delete vendor/accesskit_macos and its
# `[patch.crates-io]` entry instead.
# Usage: scripts/vendor-accesskit-macos.sh <version> e.g. scripts/vendor-accesskit-macos.sh 0.27.2
set -euo pipefail
cd "$(git rev-parse --show-toplevel)"
version="${1:?usage: scripts/vendor-accesskit-macos.sh <version>}"
tmp="$(mktemp -d)"
trap 'rm -rf "$tmp"' EXIT
curl -fsSL "https://static.crates.io/crates/accesskit_macos/accesskit_macos-$version.crate" -o "$tmp/crate.tar.gz"
tar -xzf "$tmp/crate.tar.gz" -C "$tmp"
rm -rf vendor/accesskit_macos
mv "$tmp/accesskit_macos-$version" vendor/accesskit_macos
rm -rf vendor/accesskit_macos/tests
git apply --directory=vendor/accesskit_macos vendor/accesskit_macos.patch
echo "vendor/accesskit_macos: accesskit_macos $version + vendor/accesskit_macos.patch"
+20
View File
@@ -0,0 +1,20 @@
#!/usr/bin/env bash
# Re-makes vendor/accesskit_windows: the accesskit_windows crate exactly as published on crates.io at
# <version>, plus vendor/accesskit_windows.patch (UI Automation's HeadingLevel, LandmarkType and
# LocalizedLandmarkType for headings and landmarks, which the published adapter doesn't report, so
# Narrator's and NVDA's heading and landmark navigation found none). Run it when AccessKit is
# bumped, then build: a patch that no longer applies fails here, and the change goes back in by
# hand. If upstream AccessKit takes the change, delete vendor/accesskit_windows and its
# `[patch.crates-io]` entry instead.
# Usage: scripts/vendor-accesskit-windows.sh <version> e.g. scripts/vendor-accesskit-windows.sh 0.35.2
set -euo pipefail
cd "$(git rev-parse --show-toplevel)"
version="${1:?usage: scripts/vendor-accesskit-windows.sh <version>}"
tmp="$(mktemp -d)"
trap 'rm -rf "$tmp"' EXIT
curl -fsSL "https://static.crates.io/crates/accesskit_windows/accesskit_windows-$version.crate" -o "$tmp/crate.tar.gz"
tar -xzf "$tmp/crate.tar.gz" -C "$tmp"
rm -rf vendor/accesskit_windows
mv "$tmp/accesskit_windows-$version" vendor/accesskit_windows
git apply --directory=vendor/accesskit_windows vendor/accesskit_windows.patch
echo "vendor/accesskit_windows: accesskit_windows $version + vendor/accesskit_windows.patch"
+30
View File
@@ -0,0 +1,30 @@
#!/usr/bin/env bash
# Re-makes vendor/parley_engine: the parley_engine crate exactly as published on crates.io at
# <version>, plus vendor/parley_engine.patch (UAX #9 rule L1 for a paragraph's trailing
# whitespace, isolate initiators and PDIs, which parley_engine leaves at their resolved levels:
# with it, Unicode's BidiTest.txt passes 770,241 of 770,241, without it 644,283), and three caches
# of work shaping redid from the same inputs: `Analyzer` keeps the line and word segmenters it made
# (`analysis.rs` `Segmenters`; making one loads the ICU dictionaries), `Shaper` keeps each run's
# font metrics per font instance and size (`run_metrics_cache`), and `FontMetrics::from_font_instance`
# keeps a style's per thread (64 entries). Two hooks for a host without ICU's dictionaries or the
# fonts a script needs (Rune's web build): `dictionary::set_dictionary_segmenter` (the words, and
# Thai, Lao, Khmer and Burmese line breaks, of runs that need a dictionary; with the
# `line-dictionaries` feature, the words alone, the line segmenter keeping its Thai, Lao, Khmer and
# Burmese dictionaries: Rune's Windows build) and
# `platform::set_platform_face` (a face whose runs the host measures and draws, not HarfRust;
# `push_run` takes glyph infos and positions instead of a `GlyphBuffer` for it). Run it when
# parley is bumped, then build: a patch that no longer applies fails here, and the change goes
# back in by hand. If upstream parley takes the change, delete vendor/parley_engine and its
# `[patch.crates-io]` entry instead.
# Usage: scripts/vendor-parley-engine.sh <version> e.g. scripts/vendor-parley-engine.sh 0.12.0
set -euo pipefail
cd "$(git rev-parse --show-toplevel)"
version="${1:?usage: scripts/vendor-parley-engine.sh <version>}"
tmp="$(mktemp -d)"
trap 'rm -rf "$tmp"' EXIT
curl -fsSL "https://static.crates.io/crates/parley_engine/parley_engine-$version.crate" -o "$tmp/crate.tar.gz"
tar -xzf "$tmp/crate.tar.gz" -C "$tmp"
rm -rf vendor/parley_engine
mv "$tmp/parley_engine-$version" vendor/parley_engine
git apply --directory=vendor/parley_engine vendor/parley_engine.patch
echo "vendor/parley_engine: parley_engine $version + vendor/parley_engine.patch"
+21
View File
@@ -0,0 +1,21 @@
#!/usr/bin/env bash
# Re-makes vendor/sctk-adwaita: the sctk-adwaita crate exactly as published on crates.io at
# <version>, plus vendor/sctk-adwaita.patch (the visible one-point border follows the window's
# rounded bottom corners, as the headerbar above them already rounds the top ones, instead of
# drawing a square L there; and `AdwaitaFrame::content_corner_radius` says what radius the content
# leaves its own bottom corners to, for the app to clear outside it). Run it when sctk-adwaita is
# bumped, then build: a patch that no longer applies fails here, and the change goes back in by
# hand. If upstream sctk-adwaita takes the change, delete vendor/sctk-adwaita and its
# `[patch.crates-io]` entry instead.
# Usage: scripts/vendor-sctk-adwaita.sh <version> e.g. scripts/vendor-sctk-adwaita.sh 0.10.1
set -euo pipefail
cd "$(git rev-parse --show-toplevel)"
version="${1:?usage: scripts/vendor-sctk-adwaita.sh <version>}"
tmp="$(mktemp -d)"
trap 'rm -rf "$tmp"' EXIT
curl -fsSL "https://static.crates.io/crates/sctk-adwaita/sctk-adwaita-$version.crate" -o "$tmp/crate.tar.gz"
tar -xzf "$tmp/crate.tar.gz" -C "$tmp"
rm -rf vendor/sctk-adwaita
mv "$tmp/sctk-adwaita-$version" vendor/sctk-adwaita
git apply --directory=vendor/sctk-adwaita vendor/sctk-adwaita.patch
echo "vendor/sctk-adwaita: sctk-adwaita $version + vendor/sctk-adwaita.patch"
+27
View File
@@ -0,0 +1,27 @@
#!/usr/bin/env bash
# Re-makes vendor/tiny-skia-path: the tiny-skia-path crate exactly as published on crates.io at
# <version>, plus vendor/tiny-skia-path.patch, which puts back how Skia itself strokes and splits
# conics where tiny-skia's port has drifted (Rune's icons are covered as Chromium's Skia covers
# them: crates/rune-text/src/icon/area.rs):
# - a conic becomes quads a quarter of a *device* pixel from it (the stroker passes its
# resolution scale), and one quad when that's close enough, not at least two;
# - the stroker keeps each tangent as a vector, measures its distance to the tangent line as
# Skia's `pt_to_tangent_line` does, and, out of recursion, emits a line rather than giving up;
# - `set_point_length` multiplies in double and rounds once, as `SkPoint::setLength` does;
# - `PathBuilder::conic_to`, `set_conic_tolerance` and `AutoConicToQuads` are public.
# - `set_keep_conics` retains weighted conic segments for SVG arcs; the stroker fits the two
# contours against the conic itself instead of fitting against quadratic approximations.
# Run it when tiny-skia-path is bumped, then build: a patch that no longer applies fails here,
# and the changes go back in by hand.
# Usage: scripts/vendor-tiny-skia-path.sh <version> e.g. scripts/vendor-tiny-skia-path.sh 0.11.4
set -euo pipefail
cd "$(git rev-parse --show-toplevel)"
version="${1:?usage: scripts/vendor-tiny-skia-path.sh <version>}"
tmp="$(mktemp -d)"
trap 'rm -rf "$tmp"' EXIT
curl -fsSL "https://static.crates.io/crates/tiny-skia-path/tiny-skia-path-$version.crate" -o "$tmp/crate.tar.gz"
tar -xzf "$tmp/crate.tar.gz" -C "$tmp"
rm -rf vendor/tiny-skia-path
mv "$tmp/tiny-skia-path-$version" vendor/tiny-skia-path
git apply --directory=vendor/tiny-skia-path vendor/tiny-skia-path.patch
echo "vendor/tiny-skia-path: tiny-skia-path $version + vendor/tiny-skia-path.patch"
+20
View File
@@ -0,0 +1,20 @@
#!/usr/bin/env bash
# Re-makes vendor/wgpu-hal: the wgpu-hal crate exactly as published on crates.io at <version>, plus
# vendor/wgpu-hal.patch (`dx12::Instance::expose_adapter`, which `gpu/pick.rs` uses to hand wgpu the one
# adapter it picked through DXGI; FXC loaded on first use; `Surface::set_present_rects`, partial presents;
# Windows system DLLs loaded with `LOAD_LIBRARY_SEARCH_SYSTEM32`; a removed device's work stays pending,
# never finished; GPU-written drain markers on software adapters so releasing a removed WARP device waits for queued command lists). Run it when wgpu is bumped, then build: a patch
# that no longer applies fails here, and the function goes back in by hand. If upstream wgpu takes
# the function, delete vendor/ and the `[patch.crates-io]` entries instead.
# Usage: scripts/vendor-wgpu-hal.sh <version> e.g. scripts/vendor-wgpu-hal.sh 30.0.1
set -euo pipefail
cd "$(git rev-parse --show-toplevel)"
version="${1:?usage: scripts/vendor-wgpu-hal.sh <version>}"
tmp="$(mktemp -d)"
trap 'rm -rf "$tmp"' EXIT
curl -fsSL "https://static.crates.io/crates/wgpu-hal/wgpu-hal-$version.crate" -o "$tmp/crate.tar.gz"
tar -xzf "$tmp/crate.tar.gz" -C "$tmp"
rm -rf vendor/wgpu-hal
mv "$tmp/wgpu-hal-$version" vendor/wgpu-hal
git apply --directory=vendor/wgpu-hal vendor/wgpu-hal.patch
echo "vendor/wgpu-hal: wgpu-hal $version + vendor/wgpu-hal.patch"
+26
View File
@@ -0,0 +1,26 @@
#!/usr/bin/env bash
# Re-makes vendor/winit: the winit crate exactly as published on crates.io at <version>, plus
# vendor/winit.patch (Windows: a new window isn't added to the taskbar list it is already on, which
# cost every window CoInitializeEx and a TaskbarList COM object, about 7,800 µs and nine shell
# DLLs on its UI thread before its first frame; and a window given a position is made there, at
# its display's scale, not moved there and resized; and a new window's system menu, whose Close
# is already enabled, isn't copied for the window just to enable it again; and a window is made
# with the minimize and maximize boxes it asks for, not given them by a second style change; and winit's own
# helper window is cloaked, so screen readers and window pickers don't meet it; and Windows system DLLs
# load via `LoadLibraryExA` with `LOAD_LIBRARY_SEARCH_SYSTEM32`; and on macOS the input method reads the app's text around its selection, to convert it again, and its marked text's clauses reach the app, beside `Ime::Preedit`, through `platform::macos::{set_ime_text, take_ime_clauses, take_ime_replacement}`; and
# `platform::wayland::WindowExtWayland::content_corner_radius` says what radius a Wayland client-side frame
# leaves the window's content's bottom corners at, 0 when it draws none or draws it square). Run it when winit is bumped, then build: a patch
# that no longer applies fails here, and the change goes back in by hand. If upstream winit takes
# the change, delete vendor/winit and its `[patch.crates-io]` entry instead.
# Usage: scripts/vendor-winit.sh <version> e.g. scripts/vendor-winit.sh 0.30.13
set -euo pipefail
cd "$(git rev-parse --show-toplevel)"
version="${1:?usage: scripts/vendor-winit.sh <version>}"
tmp="$(mktemp -d)"
trap 'rm -rf "$tmp"' EXIT
curl -fsSL "https://static.crates.io/crates/winit/winit-$version.crate" -o "$tmp/crate.tar.gz"
tar -xzf "$tmp/crate.tar.gz" -C "$tmp"
rm -rf vendor/winit
mv "$tmp/winit-$version" vendor/winit
git apply --directory=vendor/winit vendor/winit.patch
echo "vendor/winit: winit $version + vendor/winit.patch"
+243
View File
@@ -0,0 +1,243 @@
#!/usr/bin/env bash
# Run from the app's Cargo workspace. Produces a static, HTTPS-hostable folder.
set -euo pipefail
usage="usage: web-build.sh PACKAGE [--example NAME] [--out DIR] [--opt] [--dev] [--watch] [--no-html] [--names]"
package=${1:?$usage}
shift
example=
out=target/web
opt=false
dev=false
watch=false
html=true
names=false
while (($#)); do
case "$1" in
--example) example=${2:?--example needs a name}; shift 2 ;;
--out) out=${2:?--out needs a directory}; shift 2 ;;
--opt) opt=true; shift ;;
--dev) dev=true; shift ;;
--watch) watch=true; shift ;;
--no-html) html=false; shift ;;
--names) names=true; shift ;;
-h|--help) echo "$usage"; exit 0 ;;
*) echo "unknown option: $1" >&2; echo "$usage" >&2; exit 2 ;;
esac
done
# Build with the toolchain's own cargo rather than a `cargo` wrapper on PATH, which may run
# the build on another machine and leave no wasm here. Set CARGO to choose a cargo binary.
cargo=${CARGO:-$(rustup which cargo 2>/dev/null || command -v cargo)}
# Calling the toolchain's cargo directly skips rustup's proxy, so pin the toolchain for the
# rustc it runs too: build scripts compile outside the repo, where rust-toolchain.toml can't reach.
if [[ -z ${RUSTUP_TOOLCHAIN:-} ]] && toolchain=$(rustup show active-toolchain 2>/dev/null); then
export RUSTUP_TOOLCHAIN=${toolchain%% *}
fi
# C and C++ dependencies (rune-luau's Luau) build for the web with WASI SDK's clang against WASI
# libc, using WebAssembly exception handling. Set WASI_SDK_PATH to an unpacked WASI SDK 33 or
# newer; rune-luau's build script links the SDK's libc and C++ runtime from it.
if [[ -n ${WASI_SDK_PATH:-} ]]; then
exe=
[[ -f $WASI_SDK_PATH/bin/clang.exe ]] && exe=.exe
export CC_wasm32_unknown_unknown="$WASI_SDK_PATH/bin/clang$exe" \
CXX_wasm32_unknown_unknown="$WASI_SDK_PATH/bin/clang++$exe" \
AR_wasm32_unknown_unknown="$WASI_SDK_PATH/bin/llvm-ar$exe" \
CXXSTDLIB_wasm32_unknown_unknown=c++ \
CFLAGS_wasm32_unknown_unknown=--target=wasm32-wasip1 \
LUAU_CXXFLAGS="--target=wasm32-wasip1 -fexceptions -fwasm-exceptions -mllvm -wasm-use-legacy-eh=false"
fi
meta=$("$cargo" metadata --format-version 1 --no-deps)
selection=$(python3 -c '
import json,sys
m=json.load(sys.stdin); p=next((p for p in m["packages"] if p["name"]==sys.argv[1]),None)
if p is None: sys.exit("package is not a workspace member")
targets=[t for t in p["targets"] if "example" in t["kind"] and t["name"]==sys.argv[2]] if sys.argv[2] else [t for t in p["targets"] if "cdylib" in t["crate_types"]]
if not targets and not sys.argv[2]: targets=[t for t in p["targets"] if "bin" in t["kind"]]
if len(targets)!=1: sys.exit("select one cdylib, binary, or --example target")
t=targets[0]
print(m["workspace_root"]); print(m["target_directory"]); print(t["name"])
print("example" if sys.argv[2] else "lib" if "cdylib" in t["crate_types"] else "bin")
' "$package" "$example" <<< "$meta")
root=$(sed -n '1p' <<< "$selection")
target=$(sed -n '2p' <<< "$selection")
name=$(sed -n '3p' <<< "$selection")
kind=$(sed -n '4p' <<< "$selection")
if $dev; then
# The debug profile without debug info, with dependencies at opt-level 1: an edit rebuilds
# only this package, unoptimized, while Rune and the rest stay fast at run time.
profile=web-dev
build=(--profile web-dev --config 'profile.web-dev.inherits="dev"' --config 'profile.web-dev.debug=0'
--config 'profile.web-dev.package."*".opt-level=1')
# `"*"` covers only non-members, so name the workspace members this package depends on.
while IFS= read -r member; do
[[ -n $member ]] && build+=(--config "profile.web-dev.package.\"$member\".opt-level=1")
done < <(python3 -c '
import json,sys
m=json.load(sys.stdin); by={p["name"]:p for p in m["packages"]}
todo=[sys.argv[1]]; seen=set()
while todo:
for d in by[todo.pop()]["dependencies"]:
if d.get("path") and d["name"] in by and d["name"] not in seen and d["kind"] is None:
seen.add(d["name"]); todo.append(d["name"])
print("\n".join(sorted(seen - {sys.argv[1]})))
' "$package" <<< "$meta")
opt=false
else
profile=release
build=(--release)
# Defaults for size; set any of these to override, e.g. CARGO_PROFILE_RELEASE_LTO=fat for a smaller, slower build.
export CARGO_PROFILE_RELEASE_OPT_LEVEL=${CARGO_PROFILE_RELEASE_OPT_LEVEL:-s} \
CARGO_PROFILE_RELEASE_LTO=${CARGO_PROFILE_RELEASE_LTO:-thin} CARGO_PROFILE_RELEASE_CODEGEN_UNITS=1 \
CARGO_PROFILE_RELEASE_DEBUG=0 CARGO_PROFILE_RELEASE_STRIP=debuginfo
# Panic messages carry source paths; keep the builder's home folder out of a wasm meant for the public.
# rustc applies the last matching prefix, so the narrower cargo home comes after the home folder.
export RUSTFLAGS="${RUSTFLAGS:-} --remap-path-prefix=$HOME=/home --remap-path-prefix=${CARGO_HOME:-$HOME/.cargo}=/cargo"
fi
args=(--lib)
artifact="$target/wasm32-unknown-unknown/$profile/${name//-/_}.wasm"
if [[ $kind == example ]]; then args=(--example "$name"); artifact="$target/wasm32-unknown-unknown/$profile/examples/$name.wasm"; fi
if [[ $kind == bin ]]; then args=(--bin "$name"); artifact="$target/wasm32-unknown-unknown/$profile/$name.wasm"; fi
version=$(python3 -c 'import sys,tomllib; print(next(p["version"] for p in tomllib.load(open(sys.argv[1],"rb"))["package"] if p["name"]=="wasm-bindgen"))' "$root/Cargo.lock")
if ! command -v wasm-bindgen >/dev/null || [[ $(wasm-bindgen --version) != "wasm-bindgen $version" ]]; then
echo "Install the matching CLI: cargo install wasm-bindgen-cli --version $version --locked" >&2
exit 2
fi
marker='<!-- generated by rune web-build.sh: delete this line to keep your own edits -->'
write_html() {
local reload='' import="import init from './app.js';" load="await init();"
if $watch; then
import=
reload='<script src="reload.js"></script>'
load="const v = Date.now(); const { default: init } = await import('./app.js?v=' + v); await init({ module_or_path: './app_bg.wasm?v=' + v });"
fi
cat > "$out/index.html" <<HTML
<!doctype html>
$marker
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no,viewport-fit=cover">
<meta name="color-scheme" content="light dark">
<title>Rune</title>
<style>html,body{margin:0;width:100%;height:100%;overflow:hidden;overscroll-behavior:none;touch-action:none}#status{font:16px system-ui;padding:24px}</style>
<div id="status">Loading…</div>
$reload
<script type="module">
$import
try {
if (!navigator.gpu) throw new Error('WebGPU requires a supported browser and HTTPS.');
$load
document.querySelector('#status').remove();
} catch (error) {
document.querySelector('#status').textContent = String(error);
console.error(error);
}
</script>
</html>
HTML
}
build_once() {
local start=$SECONDS
"$cargo" build -p "$package" --target wasm32-unknown-unknown "${build[@]}" "${args[@]}" || return 1
if [[ ! -f $artifact ]]; then
echo "cargo finished but $artifact is missing. If cargo ran on another machine, set CARGO to a local cargo binary." >&2
return 1
fi
# Build into a staging folder beside the output, then rename each file into place, so a
# page loading mid-build never gets app.js and app_bg.wasm from different builds.
local next="$out/.next"
rm -rf "$next"
mkdir -p "$next"
# A release build drops the function-name section (over 40% of an unoptimized wasm); a `--dev`
# build, or `--names` for profiling, keeps it so panics and profiles name their functions.
local bindgen=(--target web --out-dir "$next" --out-name app)
$dev || $names || bindgen+=(--remove-name-section)
wasm-bindgen "${bindgen[@]}" "$artifact" || return 1
if $opt; then
local keep=()
$names && keep=(-g)
wasm-opt -Oz ${keep[@]+"${keep[@]}"} --enable-bulk-memory --enable-nontrapping-float-to-int --enable-sign-ext --enable-reference-types --enable-exception-handling \
"$next/app_bg.wasm" -o "$next/app_bg.opt.wasm" || return 1
mv "$next/app_bg.opt.wasm" "$next/app_bg.wasm"
fi
# Rune's default fonts embed Inter cut to Latin, Greek and Cyrillic text and fetch the full faces from beside
# app.js once the first frame is up: copy those of the Rune this build embedded the cut from.
local cut
cut=$(tr ' ' '\n' < "${artifact%.wasm}.d" 2>/dev/null | grep -m1 '/assets/web/first/Inter-Regular\.ttf$' || true)
if [[ -n $cut ]]; then cp "${cut%/first/*}"/Inter-*.ttf "$next/"; fi
local entry
for entry in "$next"/*; do
if [[ -d $entry ]]; then
rm -rf "${out:?}/$(basename "$entry")"
fi
mv -f "$entry" "$out/"
done
rmdir "$next"
if $html; then
if [[ ! -e $out/index.html ]] || grep -qF "$marker" "$out/index.html"; then
write_html
else
echo "Kept $out/index.html: it has no generated-by marker."
fi
fi
if $watch; then
cat > "$out/reload.js" <<'JS'
// Reloads the page when web-build.sh --watch finishes a build.
(() => {
const url = new URL('.stamp', document.currentScript?.src ?? location.href);
let last;
setInterval(async () => {
try {
const stamp = await (await fetch(url, { cache: 'no-store' })).text();
if (last !== undefined && stamp !== last) location.reload();
last = stamp;
} catch {}
}, 500);
})();
JS
echo "$(date +%s)-$RANDOM" > "$out/.stamp"
else
rm -f "$out/reload.js" "$out/.stamp"
fi
$dev || python3 -c 'import gzip,pathlib,sys; p=pathlib.Path(sys.argv[1]); b=p.read_bytes(); print(f"{p}: {len(b):,} bytes raw, {len(gzip.compress(b,mtime=0)):,} bytes gzip")' "$out/app_bg.wasm"
echo "Built $profile in $((SECONDS - start)) s. Static folder: $out"
}
if ! $watch; then
build_once
exit
fi
echo "Watching. Serve the folder with: python3 -m http.server 8000 -d $out (then open http://localhost:8000)"
# Poll the workspace members' files, skipping build output, and return once one changed after
# the build started (so an edit made during a build is not lost) or one appeared or went away.
wait_for_change() {
META=$meta python3 - "$out" "$1" <<'PY'
import json, os, sys, time
out, since = os.path.realpath(sys.argv[1]), float(sys.argv[2])
m = json.loads(os.environ["META"])
root = m["workspace_root"]
dirs = {os.path.dirname(p["manifest_path"]) for p in m["packages"]}
def scan():
seen = {}
paths = [os.path.join(root, "Cargo.toml"), os.path.join(root, "Cargo.lock")]
for top in dirs:
for here, subdirs, files in os.walk(top):
subdirs[:] = [d for d in subdirs if d not in ("target", "node_modules") and not d.startswith(".")
and os.path.realpath(os.path.join(here, d)) != out]
paths += [os.path.join(here, f) for f in files]
for path in paths:
try: seen[path] = os.stat(path).st_mtime
except OSError: pass
return seen
first = scan()
while True:
now = scan()
if now.keys() != first.keys() or max(now.values(), default=0) >= since: break
time.sleep(0.3)
PY
}
while true; do
started=$(python3 -c 'import time; print(time.time())')
build_once || echo "Build failed; waiting for the next change." >&2
wait_for_change "$started"
done
+43
View File
@@ -0,0 +1,43 @@
// A page's fake clock drives Rune's frames, even one installed after the app started
// (Playwright's `clock.install`): with the clock paused, a touch fling's momentum waits for
// `runFor` instead of finishing in real time. Chromium only (touch comes from CDP).
import assert from 'node:assert/strict';
export async function clockSmoke(browser, url) {
// Its own context: Playwright's clock belongs to a context, and would pause the other pages.
const context = await browser.newContext({ viewport: { width: 390, height: 760 }, deviceScaleFactor: 3, hasTouch: true, isMobile: true });
const page = await context.newPage();
try {
await page.addInitScript(() => {
window.__submits = 0;
const submit = GPUQueue.prototype.submit;
GPUQueue.prototype.submit = function (...args) { window.__submits++; return submit.apply(this, args); };
});
await page.goto(url);
await page.waitForFunction(() => window.__submits > 0, { timeout: 30000 });
await page.waitForTimeout(1000);
await page.clock.install();
await page.clock.pauseAt(await page.evaluate(() => Date.now() + 1000));
const cdp = await context.newCDPSession(page);
const touch = (type, y) => cdp.send('Input.dispatchTouchEvent', { type, touchPoints: type === 'touchEnd' ? [] : [{ x: 180, y }] });
await touch('touchStart', 180);
for (let i = 1; i <= 10; i++) {
await touch('touchMove', 180 + 30 * i);
await page.clock.runFor(16);
}
await touch('touchEnd', 480);
await page.clock.runFor(16);
// Two seconds of real time with the page clock paused: the fling must not move on.
await page.waitForTimeout(2000);
await page.clock.runFor(16);
const a = await page.screenshot();
await page.clock.runFor(32);
assert.ok(!a.equals(await page.screenshot()), 'momentum follows the paused page clock, not real time');
await page.clock.runFor(5000);
const settled = await page.screenshot();
await page.clock.runFor(100);
assert.ok(settled.equals(await page.screenshot()), 'momentum settles as the page clock runs');
} finally {
await context.close();
}
}
+23
View File
@@ -0,0 +1,23 @@
#!/usr/bin/env bash
# Regenerate crates/rune/assets/web/: the bundled Inter faces without TrueType hinting or glyph
# names, for the web, whose rasterizer reads neither. Every glyph, mapping, layout table and name
# stays. IBM Plex Mono ships as is: its licence reserves the name "Plex" for unmodified fonts.
# web/first/ holds the same faces cut to Latin, Greek and Cyrillic text, which a web app embeds
# for its first frame; it fetches the full faces after that. Needs HarfBuzz's hb-subset (brew
# install harfbuzz). Check with `cargo test -p rune --lib default_fonts full_faces`.
set -euo pipefail
cd "$(dirname "$0")/../crates/rune/assets"
mkdir -p web/first
# Basic Latin, Latin-1, Latin Extended-A, Romanian's comma-below letters, spacing accents,
# Greek, Cyrillic with Ukrainian's Ghe with upturn, general punctuation, the euro and trade mark
# signs, arrows and the Mac's key symbols.
first='U+0020-007E,U+00A0-017F,U+0192,U+0218-021B,U+02C6-02DD,U+0370-03FF,U+0400-045F,U+0490-0491,U+2000-206F,U+20AC,U+2122,U+2190-2193,U+21A9,U+21E7,U+2212,U+2303,U+2318,U+2325,U+232B,U+238B,U+23CE,U+FFFD'
for font in Inter-Regular Inter-Medium Inter-SemiBold; do
hb-subset "$font.ttf" --unicodes='*' --glyphs='*' --retain-gids --notdef-outline \
--layout-features='*' --layout-scripts='*' --name-IDs='*' --name-languages='*' \
--no-prune-unicode-ranges --no-hinting -o "web/$font.ttf"
hb-subset "$font.ttf" --unicodes="$first" --notdef-outline \
--layout-features='*' --layout-scripts='*' --name-IDs='*' --name-languages='*' \
--no-hinting -o "web/first/$font.ttf"
echo "web/$font.ttf: $(wc -c < "$font.ttf" | tr -d ' ') -> $(wc -c < "web/$font.ttf" | tr -d ' ') bytes, first $(wc -c < "web/first/$font.ttf" | tr -d ' ')"
done
+126
View File
@@ -0,0 +1,126 @@
import assert from 'node:assert/strict';
export async function inputSmoke(page, url) {
await page.goto(`${url}/?input-proof`);
await page.waitForFunction(() => window.__inputProof);
assert.equal(await page.title(), 'Input proof');
assert.equal(await page.locator('pre').count(), 0, 'window requests must not replace the app');
const snapshot = () => page.evaluate(() => window.__inputProof);
// The fixture reports from poll, before that frame drains queued keys. Wait for the
// host's next presented frame rather than guessing how long shader startup takes.
const settle = () => page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
await page.touchscreen.tap(100, 36);
assert.equal(await page.evaluate(() => document.activeElement.tagName), 'TEXTAREA');
await page.keyboard.insertText('hello ');
await settle();
assert.equal((await snapshot()).plain, 'hello ');
// A touch inside the same editor must never pass focus through the canvas/body.
await page.evaluate(() => {
window.__editorBlurs = 0;
document.querySelector('textarea').addEventListener('blur', () => window.__editorBlurs++);
});
await page.touchscreen.tap(100, 36);
assert.equal(await page.evaluate(() => window.__editorBlurs), 0);
// Gboard reopens an existing word: include its unchanged prefix in the preedit range.
await page.locator('textarea').evaluate(field => {
field.dispatchEvent(new CompositionEvent('compositionstart'));
field.value = 'hello'; field.setSelectionRange(5, 5);
field.dispatchEvent(new CompositionEvent('compositionupdate', { data: 'hello' }));
field.dispatchEvent(new InputEvent('input', { data: 'hello', inputType: 'insertCompositionText', isComposing: true }));
});
await settle();
assert.equal((await snapshot()).display, 'hello');
assert.equal((await snapshot()).plain, 'hello ');
await page.locator('textarea').evaluate(field => field.dispatchEvent(new CompositionEvent('compositionend', { data: 'hello' })));
await settle();
assert.equal((await snapshot()).plain, 'hello');
// Enter with keyCode 229 may have no usable keydown; beforeinput is authoritative.
const lineBreak = async (inputType, shift = false) => page.locator('textarea').evaluate((field, { inputType, shift }) => {
field.dispatchEvent(new KeyboardEvent('keydown', { key: 'Unidentified', keyCode: 229, shiftKey: shift, bubbles: true }));
const event = new InputEvent('beforeinput', { inputType, cancelable: true, bubbles: true });
field.dispatchEvent(event);
if (!event.defaultPrevented) { field.setRangeText('\n', field.selectionStart, field.selectionEnd, 'end'); field.dispatchEvent(new InputEvent('input')); }
field.dispatchEvent(new KeyboardEvent('keyup', { shiftKey: false }));
return event.defaultPrevented;
}, { inputType, shift });
assert.equal(await lineBreak('insertParagraph'), true);
await settle();
assert.equal((await snapshot()).submits, 1);
assert.equal(await lineBreak('insertLineBreak', true), true);
await settle();
assert.equal((await snapshot()).plain, 'hello\n');
assert.equal((await snapshot()).submits, 1);
await page.keyboard.press('Tab'); // Single-line editor.
await page.keyboard.insertText('one line');
assert.equal(await lineBreak('insertLineBreak', true), true);
await settle();
assert.equal((await snapshot()).single, 'one line');
assert.equal((await snapshot()).submits, 2);
await page.keyboard.press('Tab'); // Secure editor must activate a password sink.
assert.equal(await page.evaluate(() => document.activeElement.type), 'password');
const password = page.locator('input[type=password]');
assert.equal(await password.getAttribute('autocomplete'), 'off');
assert.equal(await password.getAttribute('autocorrect'), 'off');
assert.equal(await password.evaluate(p => p.spellcheck), false);
await page.keyboard.insertText('sëcret');
assert.equal(await password.inputValue(), '', 'the secret must not remain in the DOM');
await settle();
assert.equal((await snapshot()).secretLength, 6, 'secure input reaches the model');
await password.evaluate(field => field.dispatchEvent(new InputEvent('beforeinput', {
inputType: 'deleteContentBackward', cancelable: true, bubbles: true,
})));
await settle();
assert.equal((await snapshot()).secretLength, 5);
await page.keyboard.press('Enter');
await settle();
assert.equal((await snapshot()).submits, 3);
await page.keyboard.press('Tab'); // A non-editor control must return DOM focus to canvas.
assert.equal(await page.evaluate(() => document.activeElement.tagName), 'CANVAS');
await page.keyboard.press('Meta+k');
await settle();
assert.equal((await snapshot()).shortcuts, 1, 'canvas shortcuts survive the editor-to-canvas focus handoff');
await page.keyboard.press('Shift+Tab');
assert.equal(await page.evaluate(() => document.activeElement.type), 'password');
await page.keyboard.press('Escape');
assert.equal(await page.evaluate(() => document.activeElement.tagName), 'CANVAS');
await page.keyboard.press('Meta+k');
await settle();
assert.equal((await snapshot()).shortcuts, 2);
await page.touchscreen.tap(100, 36);
await page.touchscreen.tap(300, 500); // Background tap dismisses the editor.
assert.equal(await page.evaluate(() => document.activeElement.tagName), 'CANVAS');
// Dispatch a burst in one JS turn: movement/wheels must wait for rAF, not run frames.
const polls = await page.evaluate(() => {
const before = window.__inputProof.polls;
const canvas = document.querySelector('canvas');
for (let i = 0; i < 20; i++) {
canvas.dispatchEvent(new PointerEvent('pointermove', { pointerType: 'mouse', pointerId: 1,
button: -1, buttons: 0, clientX: 100 + i, clientY: 500 }));
canvas.dispatchEvent(new WheelEvent('wheel', { deltaY: 1, clientX: 100, clientY: 500 }));
}
return window.__inputProof.polls - before;
});
assert.equal(polls, 0, 'continuous pointer events must not run synchronous frames');
await page.evaluate(() => {
Object.defineProperty(document, 'hidden', { configurable: true, value: true });
document.dispatchEvent(new Event('visibilitychange'));
});
await settle();
assert.equal((await snapshot()).visible, false);
await page.evaluate(() => {
delete document.hidden;
document.dispatchEvent(new Event('visibilitychange'));
});
await settle();
assert.equal((await snapshot()).visible, true);
console.log(JSON.stringify({ inputRegressions: 'passed', checks: ['stable editor focus', 'recomposition range',
'beforeinput Enter', 'multiline vs single-line', 'password sink and deletion', 'Tab to canvas',
'Escape shortcuts', 'outside dismiss', 'coalesced pointer frames', 'visibility', 'app title', 'nonfatal window requests'] }));
}
+174
View File
@@ -0,0 +1,174 @@
// Functional browser proof for web-hello. Requires Playwright and its Chromium browser.
import assert from 'node:assert/strict';
import { createServer } from 'node:http';
import { readFile, mkdir } from 'node:fs/promises';
import { resolve, extname, sep } from 'node:path';
import { inputSmoke } from './web-input-smoke.mjs';
import { clockSmoke } from './web-clock-smoke.mjs';
const { chromium, webkit } = await import(process.env.PLAYWRIGHT_MODULE || 'playwright');
const engine = process.env.WEB_ENGINE || 'chromium';
const root = resolve(process.argv[2] || 'target/web');
const output = resolve(process.argv[3] || 'target/web-proof');
await mkdir(output, { recursive: true });
const server = createServer(async (request, response) => {
const path = resolve(root, '.' + new URL(request.url, 'http://localhost').pathname.replace(/\/$/, '/index.html'));
if (!path.startsWith(root + sep)) { response.writeHead(403).end(); return; }
try {
const bytes = await readFile(path);
response.setHeader('Content-Type', ({ '.wasm': 'application/wasm', '.js': 'text/javascript', '.html': 'text/html' })[extname(path)] || 'application/octet-stream');
response.end(bytes);
} catch { response.writeHead(404).end(); }
});
await new Promise(done => server.listen(0, '127.0.0.1', done));
const browser = await (engine === 'webkit' ? webkit.launch({ headless: true }) :
chromium.launch({ headless: true, executablePath: process.env.CHROMIUM_PATH,
args: ['--enable-unsafe-webgpu', ...(process.platform === 'darwin' ? ['--use-angle=metal'] : [])] }));
const errors = [];
try {
const context = await browser.newContext({ viewport: { width: 390, height: 760 }, deviceScaleFactor: 3,
hasTouch: true, isMobile: true,
permissions: engine === 'chromium' ? ['clipboard-read', 'clipboard-write'] : [], colorScheme: 'dark' });
const page = await context.newPage();
page.on('pageerror', error => { errors.push(error.message); console.log(error.message); });
page.on('console', message => { if (message.type() === 'error') { errors.push(message.text()); console.log(message.text()); } });
await page.addInitScript(() => {
// Chromium's device emulation leaves devicePixelContentBoxSize at the host DPR.
// Exercise winit's Safari fallback (CSS content box × emulated DPR) instead.
delete ResizeObserverEntry.prototype.devicePixelContentBoxSize;
window.__proof = { submits: 0, rafs: 0, gpuErrors: [] };
const raf = window.requestAnimationFrame;
window.requestAnimationFrame = callback => { window.__proof.rafs++; return raf.call(window, callback); };
if (!globalThis.GPUQueue || !globalThis.GPUAdapter) return;
const submit = GPUQueue.prototype.submit;
GPUQueue.prototype.submit = function (...args) { window.__proof.submits++; return submit.apply(this, args); };
const request = GPUAdapter.prototype.requestDevice;
GPUAdapter.prototype.requestDevice = async function (...args) {
const device = await request.apply(this, args);
device.addEventListener('uncapturederror', e => window.__proof.gpuErrors.push(e.error.message));
return device;
};
});
const url = `http://127.0.0.1:${server.address().port}`;
await page.goto(url);
if (engine === 'webkit' && !await page.evaluate(async () => !!(await navigator.gpu?.requestAdapter()))) {
console.log(JSON.stringify({ engine, available: false, reason: 'Headless WebKit has no WebGPU adapter' }));
} else {
if (!process.env.WEB_INPUT_ONLY) {
await page.waitForFunction(() => window.__proof?.submits > 0, { timeout: 30000 });
await page.waitForTimeout(1000); // Let the initial appearance finish before measuring idle.
assert.deepEqual(await page.locator('canvas').evaluate(c => [c.width, c.height]), [1170, 2280]);
const beforeIdle = await page.evaluate(() => window.__proof.submits);
const beforeIdleRaf = await page.evaluate(() => window.__proof.rafs);
await page.waitForTimeout(600);
assert.equal(await page.evaluate(() => window.__proof.submits), beforeIdle, 'idle must not submit frames');
assert.equal(await page.evaluate(() => window.__proof.rafs), beforeIdleRaf, 'idle must not request animation frames');
await page.screenshot({ path: `${output}/web-dark.png` });
const beforePan = await page.screenshot();
const cdp = engine === 'chromium' ? await context.newCDPSession(page) : null;
const touch = async (type, y) => cdp ? cdp.send('Input.dispatchTouchEvent', {
type, touchPoints: type === 'touchEnd' ? [] : [{ x: 180, y }],
}) : page.locator('canvas').dispatchEvent(({ touchStart: 'pointerdown', touchMove: 'pointermove', touchEnd: 'pointerup' })[type],
{ pointerType: 'touch', pointerId: 1, isPrimary: true, clientX: 180, clientY: y, buttons: type === 'touchEnd' ? 0 : 1 });
await touch('touchStart', 180);
for (let i = 1; i <= 10; i++) {
await touch('touchMove', 180 + 30 * i);
await page.waitForTimeout(16);
}
await touch('touchEnd', 480);
const releaseSubmits = await page.evaluate(() => window.__proof.submits);
await page.waitForTimeout(250);
assert.ok(await page.evaluate(() => window.__proof.submits) > releaseSubmits, 'touch release continues momentum');
assert.ok(!beforePan.equals(await page.screenshot()), 'touch pan moves rendered content');
assert.notEqual(await page.evaluate(() => document.activeElement?.tagName), 'TEXTAREA', 'a pan must not focus an editor');
await page.touchscreen.tap(100, 720);
await page.waitForFunction(() => document.activeElement?.tagName === 'TEXTAREA');
await page.keyboard.insertText('Bonjour 🦀');
assert.equal(await page.locator('textarea').inputValue(), 'Bonjour 🦀');
await page.keyboard.press('Enter');
assert.equal(await page.locator('textarea').inputValue(), '');
await page.touchscreen.tap(330, 36);
assert.equal(await page.evaluate(() => navigator.clipboard.readText()), 'Bonjour 🦀', 'send updates the actual model');
await page.touchscreen.tap(100, 720);
await page.keyboard.insertText('x'.repeat(1200) + ' tail');
assert.ok((await page.locator('textarea').inputValue()).length <= 1024, 'mirror is a sliding context');
await page.locator('textarea').evaluate(field => {
field.setSelectionRange(field.value.length - 4, field.value.length);
field.setRangeText('corrected', field.selectionStart, field.selectionEnd, 'end');
field.dispatchEvent(new InputEvent('input', { inputType: 'insertReplacementText', data: 'corrected' }));
});
await page.keyboard.press('Enter');
await page.touchscreen.tap(330, 36);
assert.equal(await page.evaluate(() => navigator.clipboard.readText()), 'x'.repeat(1200) + ' corrected');
await page.touchscreen.tap(100, 720);
const beforeMissingGlyph = await page.evaluate(() => window.__proof.submits);
await page.locator('textarea').evaluate(field => {
field.dispatchEvent(new CompositionEvent('compositionstart', { data: '' }));
field.value = '日本語'; field.setSelectionRange(3, 3);
field.dispatchEvent(new CompositionEvent('compositionupdate', { data: '日本語' }));
field.dispatchEvent(new InputEvent('input', { data: '日本語', isComposing: true }));
field.dispatchEvent(new CompositionEvent('compositionend', { data: '日本語' }));
});
assert.equal(await page.locator('textarea').inputValue(), '日本語');
await page.waitForFunction(previous => window.__proof.submits > previous, beforeMissingGlyph);
await page.keyboard.press('Meta+A');
await page.keyboard.insertText('replacement');
assert.equal(await page.locator('textarea').inputValue(), 'replacement');
// Browser paste is independent of async clipboard-read permission.
await page.locator('textarea').evaluate(field => {
const clipboardData = new DataTransfer(); clipboardData.setData('text/plain', ' pasted');
field.dispatchEvent(new ClipboardEvent('paste', { clipboardData, bubbles: true }));
});
assert.equal(await page.locator('textarea').inputValue(), 'replacement pasted');
const popup = context.waitForEvent('page');
await page.touchscreen.tap(90, 36);
const linked = await popup;
await linked.waitForLoadState('domcontentloaded');
assert.ok(linked.url().includes('rust-lang.org'));
assert.equal(await linked.evaluate(() => window.opener), null);
await linked.close();
await page.emulateMedia({ colorScheme: 'light', reducedMotion: 'reduce' });
await page.setViewportSize({ width: 430, height: 540 });
await page.waitForFunction(() => document.querySelector('canvas')?.height === 1620);
await page.waitForTimeout(400);
await page.screenshot({ path: `${output}/web-light-keyboard-size.png` });
const gpuErrors = await page.evaluate(() => window.__proof.gpuErrors);
assert.deepEqual(gpuErrors, []);
assert.deepEqual(errors.filter(e => !e.includes('404')), []);
console.log(JSON.stringify({ ok: true, engine, idleSubmits: 0, idleRafs: 0, dpr: 3, sizingPath: 'Safari fallback', checks: ['WebGPU render', 'idle', 'touch focus',
'touch momentum', 'Unicode input', 'send', 'clipboard copy', 'sliding context', 'predictive replacement',
'composition', 'selection replacement', 'paste', 'noopener link', 'theme', 'resize'], gpuErrors }));
}
await page.setViewportSize({ width: 390, height: 760 });
await inputSmoke(page, url);
// JPEG bytes go to the browser's codecs, PNG bytes to Rune's.
await page.goto(`${url}/?image-proof`);
await page.waitForFunction(() => window.__imageProof?.jpeg && window.__imageProof?.png);
assert.deepEqual(await page.evaluate(() => window.__imageProof), { jpeg: { width: 12, height: 6 }, png: { width: 12, height: 6 } });
// The cursor over them is the PNG at 2x, which the browser decodes and sizes in points.
const cursor = () => page.evaluate(() => getComputedStyle(document.querySelector('canvas')).cursor);
await page.mouse.move(76, 114);
await page.waitForFunction(() => getComputedStyle(document.querySelector('canvas')).cursor.includes('image-set('));
const css = await cursor();
assert.match(css, /image-set\(url\("blob:[^"]+"\) 2(x|dppx)\) 1 2, auto$/, css);
const size = await page.evaluate(async (url) => {
const image = new Image();
image.src = url;
await image.decode();
return [image.naturalWidth, image.naturalHeight];
}, css.match(/blob:[^"]+/)[0]);
assert.deepEqual(size, [12, 6]);
await page.mouse.move(300, 700);
await page.waitForFunction(() => getComputedStyle(document.querySelector('canvas')).cursor === 'auto');
// Inter's full faces load from beside app.js once the first frame is up.
await page.waitForFunction(() => performance.getEntriesByType('resource').filter(e => /\/Inter-\w+\.ttf$/.test(e.name) && e.responseEnd > 0).length === 3);
assert.deepEqual(await page.evaluate(() => performance.getEntriesByType('resource')
.filter(e => /\/Inter-\w+\.ttf$/.test(e.name)).map(e => e.responseStatus ?? 200)), [200, 200, 200]);
console.log(JSON.stringify({ ok: true, checks: ['image bytes', 'image cursor', 'full Inter faces'] }));
assert.deepEqual(await page.evaluate(() => window.__proof.gpuErrors), []);
assert.deepEqual(errors.filter(e => !e.includes('404')), []);
if (engine === 'chromium') { await clockSmoke(browser, url); console.log(JSON.stringify({ ok: true, checks: ['page clock'] })); }
}
} finally {
await browser.close();
await new Promise(done => server.close(done));
}