Skip to content

A local video studio for your coding agent. Describe a video in one sentence: your agent directs, your machine renders. Claude Code, Codex, Cursor, Devin and more. No API keys, no uploads.

showtime 0.4.6

Favio Vázqueze26e53dfed32
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json
index 15dfb88..5d460c0 100644
--- a/.claude-plugin/marketplace.json
+++ b/.claude-plugin/marketplace.json
@@ -5,14 +5,14 @@
},
"metadata": {
"description": "showtime: a local video studio for your coding agent",
- "version": "0.4.5"
+ "version": "0.4.6"
},
"plugins": [
{
"name": "showtime",
"source": "./",
"description": "A local video studio for your coding agent. Describe a video. Your agent directs. Your machine renders. Motion graphics, voice-over, music, footage editing, captions and platform-ready exports, with no cloud AI services or API keys.",
- "version": "0.4.5",
+ "version": "0.4.6",
"author": {
"name": "Favio Vazquez"
},
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index cf7a80d..e87cae5 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "showtime",
- "version": "0.4.5",
+ "version": "0.4.6",
"description": "A local video studio for your coding agent. Describe a video. Your agent directs. Your machine renders. Motion graphics rendered frame-exactly, voice-over, music and sound design, footage editing from transcripts, captions and platform-ready exports. Everything runs on your machine.",
"author": {
"name": "Favio Vazquez"
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 55bf1ea..ed6f21e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,35 +1,162 @@
# Changelog
-All notable changes to showtime. Each entry says what changed and why, so this file also answers
-"where did X go?". Versions follow [semantic versioning](https://semver.org); the version lives in
-`skills/showtime/lib/st/__init__.py` and `python3 scripts/check_release.py` keeps the plugin manifests, the registry files and
-`setup/package.json` in sync with it.
-
-## 0.4.6 (unreleased)
-
+All notable changes to showtime. Each entry says what changed and why, so this file also answers "where did X go?".
+Versions follow [semantic versioning](https://semver.org); the version lives in `skills/showtime/lib/st/__init__.py` and
+`python3 scripts/check_release.py` keeps the plugin manifests, the registry files and `setup/package.json` in sync with
+it.
+
+## 0.4.6 (2026-10-16)
+
+- **Fixed: the X-ray template at 9:16 keeps its sound strip and labels where a phone shows them.** The strip sat under
+ the reels safe box (y 1472-1676 at 1080x1920), where the feed's caption and buttons cover it, and its label and the
+ part labels were 24-34 px, under the phone floor (43 px at 1920). The strip now sits above the counters, inside the
+ safe box, with its label on the ticks' row (the label fits as before: shrink to the floor, drop "the clip's sound",
+ then an ellipsis); the counters are one compact row, 64 px (they were 84). The part labels are 44 px, in a column at
+ the safe box's left edge, ordered so no two leaders in a column cross: parts at rest muted, the ones acting now red
+ with a dot on the part, leaders grey. When one column can't hold them (the drums name 8 parts), a second one sits at
+ the safe box's right edge; a long label wraps to two lines; the drawing sits between the columns, never under them,
+ with heavier lines, and ends at x 916, left of the platform's buttons. The layout is chosen once per film, so the
+ drawing never moves. The drums', guitar's and piano's captions (24-30 px inside the drawing) are a 44 px row over it,
+ and the guitar's string names (26 px on lines 21 px apart) are labels in the column; the kit's new calls for a
+ mechanism are in `showtime guide xray "Mechanism library"`. This change leaves 16:9, 4:5 and 1:1 as they were (16:9's
+ own fixes are the #68 entry below). Every library mechanism passes `check` in a fresh 9:16 project. At 4:5 and 1:1 the
+ template still has `check` findings it had before this change (text under the phone floor, labels on each other, and
+ at 4:5 text outside the safe box): a test keeps each mechanism's count of each kind at or under its count before this
+ change, until a later release fixes them.
+- **Fixed: the X-ray sound strip with `"xray".offset_frames`.** When the clip starts some frames into the film, the
+ strip placed its ticks and its caret by film time over the recording's length: late ticks were drawn past the
+ strip's end, off the frame, and the caret stopped at the end while the recording still played. Both now
+ follow the recording's own clock (the film frame minus the offset), in the `xray` template and its living-diagram
+ page; before the clip starts the caret waits at the strip's start. With no measured recording length the strip
+ takes the recording to run from the clip's start to the film's end (the diagram page: to the endcard), not from
+ frame 0. And `"xray".track_until` (the clip's seconds) is read on the recording's clock too: with an offset the
+ see-through used to fade out that many seconds early.
+- **Fixed: the X-ray piano, drums and guitar follow the recording's clock too.** `notes.json` times and its tempo map
+ are seconds of the recording, but a note that no event took was shown at the film frame of its time, and the
+ staff or tab scrolled by the film's time; with `"xray".offset_frames` both ran that many frames early. The drawing
+ kit now gives a mechanism `k.rt` (this frame's time on the recording) and `k.frameAt(t)` (the film frame of a
+ recording time), from the same mapping the sound strip and `track_until` use; the three mechanisms use them.
+- **New: `check` finds canvas text outside the vertical safe box between its samples, on any canvas.** The 9:16
+ safe-zone rule saw film-API text at the sample times only, so labels a page drew on its own canvas (chart notes, a
+ date counter) passed `check` and `qa --platform reels` while the feed's UI covered them. Now every step of the dense
+ timeline compares each canvas text with the safe box (x 64-916, y 220-1440 at 1080x1920): one `safe_zone` warning per
+ text with its span, when it sits outside two steps in a row without moving or for 1 s in all. A counter is one text
+ while its number changes. qa's phone check counts it, as before.
+- **New: `check` measures the size of canvas text a page draws itself** (#73, the check half). Raw
+ `fillText`/`strokeText` on any page canvas now feeds the `tiny_text` rule and the phone check on the dense timeline,
+ as DOM text and `F.text` already did; before, only the film API's text was measured, so a tiny label drawn by the page
+ passed. A counter in one place is one text; text inside `F.decor`, faint text (under half opacity) and text mostly off
+ the frame are not measured.
- **Fixed: the repository stores files exactly as they are installed.** `.gitattributes` is now `* -text`, so nothing is
converted at checkout, and the Windows launchers (`.cmd`, `.bat`, `.ps1`) are committed with CRLF; installed files
match the repository byte for byte on every OS. `scripts/check_release.py` now fails on any attribute that converts
content, on a Windows launcher with LF-only lines and on a shell script with CR bytes.
+- **Fixed: `showtime setup --home X` installs ffmpeg into X when a default install exists.** The default install's
+ ffmpeg (first on the PATH setup runs with) counted as "the system ffmpeg", so X got none of its own and had no ffmpeg
+ outside that PATH. Another showtime install's ffmpeg is no longer taken as the system's.
+- **Fixed: a page address with a malformed `%` escape** (`?x=%`) no longer stops the page runtime from starting in
+ preview; that query pair is skipped.
+- **Changed: hardening.** The page runtime keeps its URL query parameters in a map with no prototype; the MCP server's
+ `voice_say` writes its text to a new temporary file with a random name, readable by your user only; the benchmark
+ harness marks its short sha1 labels as not used for security.
+- **Changed: `check` reports a probe that did not run as a warning** (`cut_probe_failed` and `webgpu_probe_failed`,
+ were info), so a check whose first-frame-after-cut walk or WebGPU probe could not open its page never reads as
+ clean, and `check --strict` fails on it.
+- **Changed: the X-ray embed element takes a `file:` address only on a page opened from disk.** A post read offline
+ still loads its film from the disk; a web page that names a `file:` film now keeps the poster instead of framing an
+ address the browser would never load.
+- **Fixed: `xray import` refuses a JSON file with too many object keys before parsing it.** One object with millions
+ of keys passed the value and container limits and took about 930 MB to read (a 42 MB file); a file with more than
+ 1,600,000 colons (object keys, counting those inside strings) is now refused, like too many values or objects.
+- **Fixed: `showtime assets icon` with a misspelled name suggests the right one at once.** A name the icon set does
+ not have is checked against the set's listing (fetched once, kept 30 days) before its file is fetched; the icon
+ CDN took about 40 s to say a file is missing, so the command ended with a network error and no suggestion.
+- **New: `check` finds text drawn over other text between its samples and on any canvas.** The page runtime records
+ every text a page canvas paints (`fillText`/`strokeText`, the film API's or a scene's own) in render and check runs,
+ and `check` compares their painted glyphs, the DOM's and both against each other on its whole-timeline grid: a pair
+ that overlaps on two steps in a row, both holding (still, or blinking at half opacity or more; a crossfade or a
+ fade does not hold), is a `text_overlap` warning that says when it starts and ends. A faint canvas text counts
+ (alpha 0.15 and up, one of the two 0.5 and up). Canvas text counts only while it is on screen: not after its canvas
+ is cleared, reset or painted over (an opaque fill or filled box, a film card), not clipped away, not under an opaque
+ element or image above the canvas. Gradient text (`background-clip: text`) reads at full strength and hides nothing
+ under it. A labelled counter ("TICK 12", "TICK 13", …) is one text, moving or not, while no other text on its canvas
+ has the same words; labels that share their words ("ORBIT 1", "ORBIT 2") are each their own text, so they are followed
+ as they move. A counter that shares its words with another label on its canvas is keyed by its string, which changes
+ every step, so an overlap with it is not reported. A bare number ("42") is keyed by where it sits: one that moves
+ gives short findings, or none when it moves more than 16 px a step. Not overlaps: the same string twice (a shadow
+ pass), decor, a caption on its own plate over a canvas, DOM text turned far enough that its box is mostly empty
+ (kinetic rows), and text layered on purpose: `F.text(..., {layer: true})`, `F.layer(() => ...)`, or
+ `ST.layer(() => ...)` around raw canvas calls.
+- **Fixed: the `25-nobel-physics-ice-telescope` example had text over text.** Its "2,450 m" depth mark sat under a
+ caption line at 0:57; both depth marks now sit above their ruler ticks. The `tutorial` template's closing line,
+ drawn over the dimmed app on purpose, is marked as layered, so a new tutorial project checks clean.
+- **Fixed: `export html --interactive` packs a page's own fonts** (#71). The X-ray live page and the living diagram's
+ figure packed the files of linked stylesheets only; a project's own `@font-face` in the page's `<style>`
+ (`url("fonts/x.woff2")`) stayed a file the page's policy (`font-src data:`) blocks, so the text fell back to another
+ font. Files named in the page's own `<style>` blocks are packed like a stylesheet's (only from inside the project),
+ and one that is missing stops the export with its name. An inline `<script>` is never rewritten.
+- **Fixed: `export html` from inside a job writes into the job** (#72). On a project inside a job, or run from the job
+ folder of the project being exported (its `job.json` names it), it made a new `showtime-out/<title>-<time>/`
+ folder nested in the job; the export now goes into that job, and a live page or figure is noted in its `job.json`.
+ Another project exported from a job folder goes where it always did.
+- **Fixed: a new 16:9 X-ray project passes its own check** (#68). The brand, the tag and the counters sit 96 px (5%)
+ from the left edge, the counters above the player controls' strip, their labels and the end card's small print are
+ 26 px, and the red letter on the paper card and the end card's number use a red that reads at 4.5:1 on both themes
+ (the light theme's grey labels are darker too). The 16:9 end card is opaque, so the drawing's labels no longer show
+ through it.
+- **Fixed: the X-ray sound strip's label is 26 px at 16:9** (#73, the template half; the check half is the canvas text
+ size bullet above). It was 18 px, drawn on the canvas where `check`'s size rule did not see it. A
+ test reads the canvas text of a new project and holds every label at 25 px or more. A long mechanism word no longer
+ runs past the strip: the label shrinks to 24 px, then drops "the clip's sound", then ends the word with an ellipsis.
+- **Fixed: `xray verify` reads the sync marker on a `--preview` or `--scale` render** (#66). The marker was read at a
+ fixed 6x6 px patch in the corner; a draft fitted to 720p has it smaller and nearer the corner, so verify found none.
+ It now reads the marker at the film's scale against the project's size, and says so in its notes.
+- **Fixed: the X-ray receipt says what "the original" is** (#67). With `"xray": {"derived": "..."}` (the clip's
+ sound is a rendering of data, "the signal slowed 100x on a 400 Hz carrier") the line reads "audio ... ms from the
+ rendered sound" and the receipt adds that the audio check compares the film with that rendering, not with the
+ original data; events from `xray import` read "from the source sound", with the data file named. The audio check
+ passed against the rendering and read as a check of the data.
+- **Fixed: Space or Enter on a focused control of a living diagram no longer also fires the scene's key.** A scene
+ that maps Space or Enter to an action ran it as well as pressing the focused summary, button or link (0.4.5's
+ "keeps all of its own keys" held for typed letters, not for a scene's keys). A letter the control has no use for
+ still reaches the scene, so you can click a setting and then press its key.
+- **Release checks:** `scripts/check_release.py` refuses a bullet repeated in the unreleased CHANGELOG section (two
+ bullets with the same bold lead, and lines over 120 characters, are warnings) and any tracked path, or file a test
+ writes, with a name Windows reserves (`nul.csv` cost two 0.4.5 release CI rounds). A `route-<topic>` routing case must
+ read its own guide, a workflow guide needs its line in `references/index.md` (as CONTRIBUTING says), and a routing
+ pattern that is not a regex is reported once. A credential-shaped literal in a shipped file and a merge-conflict
+ marker left in a tracked file are errors (test fixtures build their credentials from pieces), and the directory check
+ refuses a `.gitattributes` line git ignores whole (`* -text # note` sets nothing). The CHANGELOG's long lines are
+ wrapped at 120.
+- **Fixed: `xray import` refuses a word in a `strength` column** even without `--strength`. A column named `strength`
+ sizes the events on its own; a cell that was not a number drew that event at full strength without a word. It is
+ refused like a bad `--strength` cell (a blank cell keeps the default). Every row is checked, the ones the time map
+ drops too, so a sheet with a word in a row before T0 that imported in 0.4.5 is now refused. Both refusals now come
+ before the `--source` recording is decoded, and the "no value: drawn at strength 0" count leaves out rows dropped by
+ the time map. The `xray notes` help says a recording with no picture keeps the 30 fps frame grid.
+- **Also in 0.4.5, missing from its notes:** `xray import` refuses a JSON file with more than 800,000 lists and
+ objects before parsing it, and a CSV whose first row holds a number too large to hold is refused with an error
+ instead of being taken for a header row.
## 0.4.5 (2026-10-14)
- **New: X-ray events from a data stream.** `showtime xray import <events.csv|json> --job <job> --time-map SLOW,T0`
writes `xray.json` from event times measured in data (peaks of a signal, a sensor log) instead of from the clip's
sound: film time = (t_data - T0) x SLOW, each event's frame = floor(t * fps), `detector.engine: "data"` with a note
- that says how. A CSV with a time column or a JSON list; `--strength <column>` sizes the events, other columns
- travel with them, events outside the film are listed under `dropped`, and `--source` (the sound the film plays)
- gives the frame rate and length and lets `xray verify` check the film. The live page's commands then start with
- `xray import`. A film made this way used to need a hand-written `xray.json`. Limits: an events file up to 50 MB and
- 100,000 events, film times up to 24 h; a file it cannot hold (NaN or infinity, a huge number, deep nesting, an
- over-long CSV cell, a file with a NUL byte (one saved as UTF-16, say)) is refused with the reason, before a job exists. `--strength` with a cell that is not a number
- is refused (a blank cell is strength 0, counted in one warning); `--time-map ",5"` sets T0 alone, and a part given
- twice is refused. The note it writes names the events file, never a folder. A data column named `kind`, `ch`,
- `notes` or `pitches` can no longer break the live page.
-- **New: X-ray of a recording with no picture.** `xray analyze` takes a WAV or any recording without
- a video stream instead of refusing it: the events land on a frame grid of `--fps` (default 30), and `xray notes` takes one too, always at 30 fps; xray.json marks the
- source `audio_only`, and the page draws the picture side. `--track` on such a recording is refused with the reason.
- `xray notes --help` says so too (it still called the clip "the video you filmed").
+ that says how. A CSV with a time column or a JSON list; `--strength <column>` sizes the events, other columns travel
+ with them, events outside the film are listed under `dropped`, and `--source` (the sound the film plays) gives the
+ frame rate and length and lets `xray verify` check the film. The live page's commands then start with `xray import`. A
+ film made this way used to need a hand-written `xray.json`. Limits: an events file up to 50 MB and 100,000 events,
+ film times up to 24 h; a file it cannot hold (NaN or infinity, a huge number, deep nesting, an over-long CSV cell, a
+ file with a NUL byte (one saved as UTF-16, say)) is refused with the reason, before a job exists. `--strength` with a
+ cell that is not a number is refused (a blank cell is strength 0, counted in one warning); `--time-map ",5"` sets T0
+ alone, and a part given twice is refused. The note it writes names the events file, never a folder. A data column
+ named `kind`, `ch`, `notes` or `pitches` can no longer break the live page.
+- **New: X-ray of a recording with no picture.** `xray analyze` takes a WAV or any recording without a video stream
+ instead of refusing it: the events land on a frame grid of `--fps` (default 30), and `xray notes` takes one too,
+ always at 30 fps; xray.json marks the source `audio_only`, and the page draws the picture side. `--track` on such a
+ recording is refused with the reason. `xray notes --help` says so too (it still called the clip "the video you
+ filmed").
- **Fixed: the X-ray live page states how the events were measured.** It said "from the clip's own sound" for every
film; it now uses `"xray".measured` from showtime.json, else xray.json's detector (the sound, or a data stream and
its note).
@@ -124,27 +251,29 @@ All notable changes to showtime. Each entry says what changed and why, so this f
light or dark, see-through or beside, labels on hover, the receipt and the credit. It then went further. Pads under
the picture play the next event of their kind from the real clip with its sound (a typewriter's keys laid out as a
keyboard, an instrument's notes in pitch order, a kit's drums named as people say them); the keys of your keyboard
- press them, so you type on the typewriter; dragging the picture scrubs and a click plays the next event.
- Links are plain anchors: `#hit4`, `#t2.5`, `_light`, `_split` (`#hit4_light`), and the Link button copies one. The page
- shows the request that made the film in quotes with Copy, then the commands: pass `--prompt "<request>"` to the
- export (or `xray.made.prompt` in showtime.json); the commands use placeholders and never your paths, `showtime new
- xray` records only `xray.made` (mechanism, layout, theme), and the export report says what it embedded. The page embeds
- with `<showtime-xray src="you-live.html" ratio="16/9">` (a poster and a Play button; the one script is `embed.js`) or
- an iframe with `#embed`, and its policy allows framing. The letter shortcuts moved to Shift (Shift+S quarter speed,
+ press them, so you type on the typewriter; dragging the picture scrubs and a click plays the next event. Links are
+ plain anchors: `#hit4`, `#t2.5`, `_light`, `_split` (`#hit4_light`), and the Link button copies one. The page shows
+ the request that made the film in quotes with Copy, then the commands: pass `--prompt "<request>"` to the export (or
+ `xray.made.prompt` in showtime.json); the commands use placeholders and never your paths, `showtime new xray` records
+ only `xray.made` (mechanism, layout, theme), and the export report says what it embedded. The page embeds with
+ `<showtime-xray src="you-live.html" ratio="16/9">` (a poster and a Play button; the one script is `embed.js`) or an
+ iframe with `#embed`, and its policy allows framing. The letter shortcuts moved to Shift (Shift+S quarter speed,
Shift+T theme, Shift+L layout). The live export takes the mechanism for its commands from `xray.made`, else from the
- project's own `mechanism.js`, and warns when it can only guess. Checked by tests that open the exported page in a browser and read what the export embeds.
+ project's own `mechanism.js`, and warns when it can only guess. Checked by tests that open the exported page in a
+ browser and read what the export embeds.
- **New: living diagrams you touch.** A figure's scene can answer the viewer, not only the knobs: `interactive.type`
receives every character typed on the figure (from anywhere on the page, or from a Type field on a phone's soft
keyboard; Enter and Backspace arrive too), `parts[].press` runs when a part is clicked or tapped (or Enter on its
button) and `parts[].drag` turns a knob while the viewer drags the part (`axis`, and `span` in pixels for the whole
range). With `type` set, plain letters belong to the scene and the figure's own shortcuts take Shift (Shift+R run
- again, Shift+L copy link, Shift+1-9 steps). Two new examples start from it: `showtime new diagram <dir> --example
- typewriter` (type on it: the key goes down, the typebar swings to the print point, the letter lands on the paper,
- the carriage steps, the bell rings near the margin, Enter returns the carriage) and `--example computer` (what
- happens when you press a key: the keyboard, a USB poll, an interrupt, RAM, the GPU and the screen's refresh, in slow
- motion with typical, labelled numbers; click a part to pulse it). The heat pump template's outdoor unit now drags to
- set the weather. Each still films from its tour, and a figure framed with `#embed` reports its height to the host
- like an X-ray page. `showtime check` walks a typed line and every pressable part. Checked by tests that type on the exported figures in a browser.
+ again, Shift+L copy link, Shift+1-9 steps). Two new examples start from it:
+ `showtime new diagram <dir> --example typewriter` (type on it: the key goes down, the typebar swings to the print
+ point, the letter lands on the paper, the carriage steps, the bell rings near the margin, Enter returns the carriage)
+ and `--example computer` (what happens when you press a key: the keyboard, a USB poll, an interrupt, RAM, the GPU and
+ the screen's refresh, in slow motion with typical, labelled numbers; click a part to pulse it). The heat pump
+ template's outdoor unit now drags to set the weather. Each still films from its tour, and a figure framed with
+ `#embed` reports its height to the host like an X-ray page. `showtime check` walks a typed line and every pressable
+ part. Checked by tests that type on the exported figures in a browser.
- **Fixed: code scanning.** The exported figure's title is cleaned of markup in one linear pass instead of a repeated
search.
- **The site's X-ray page.** A gallery of ten films (the typewriter four ways, the music box in a phone and a wide cut,
@@ -247,9 +376,9 @@ All notable changes to showtime. Each entry says what changed and why, so this f
- **New: `showtime repro` turns a failing Playwright test into a short narrated video for a bug report.** From a
`trace.zip`, or the test command after `--` (run with tracing on failure), it shows each step on the trace's own
screenshots with a cursor and the target boxed, then the failing step slowed down with expected and received, the
- error and the console errors, and writes `repro.md` to paste into the issue. It writes `script.md` and stops;
- `--yes` renders it. Typed values are never shown or spoken (their fields are covered); paths are shortened to
- the file name, URLs lose their query strings, and secrets are masked. Guide: `references/workflows/repro.md`. Test: `test_repro.py`.
+ error and the console errors, and writes `repro.md` to paste into the issue. It writes `script.md` and stops; `--yes`
+ renders it. Typed values are never shown or spoken (their fields are covered); paths are shortened to the file name,
+ URLs lose their query strings, and secrets are masked. Guide: `references/workflows/repro.md`. Test: `test_repro.py`.
- **Docs and site for 0.4.3: the new features, with three demos and a live figure on the site.** The README has a
"New in 0.4.3" section (living diagrams and live figures, recap, repro, the render fix, music per video and quiet
cuts, the harness page), the new commands in its quick list and `diagram`, `recap` and `repro` in the command
@@ -281,63 +410,63 @@ All notable changes to showtime. Each entry says what changed and why, so this f
(`test_write_json_retries_a_replace_another_process_holds`,
`test_permission_denied_names_both_sides_of_a_rename`); `test_audio.py` (`test_08_parallel_mixes_share_the_cache`)
is the end-to-end case.
-- **Docs, second pass: stale `--workers` and splice help, the voice Essentials, "Whisper for transcripts", and a doctor pointer.**
- Left over from the 0.4.2 audit: `render --help` still described the old one-browser-per-8-threads rule and a splice
- "mixed again" audio it now reuses; the README repeated the old worker rule; `voice.md` listed the fit command without
- its `--estimate` dry run first and said "9 languages" for 9 Kokoro variants (8 languages); the site said Whisper is
- fetched for transcripts (it is Parakeet). `showtime doctor` now ends with a link to the troubleshooting page when a
- check fails. Test: `test_skill_structure.py` (`test_fit_is_estimated_before_synthesis` now scans `voice.md`; the
- stale-phrase guard now scans `site/build.py` and `harness-notes.md`), `test_lean.py`
+- **Docs, second pass: stale `--workers` and splice help, the voice Essentials, "Whisper for transcripts", and a doctor
+ pointer.** Left over from the 0.4.2 audit: `render --help` still described the old one-browser-per-8-threads rule and
+ a splice "mixed again" audio it now reuses; the README repeated the old worker rule; `voice.md` listed the fit command
+ without its `--estimate` dry run first and said "9 languages" for 9 Kokoro variants (8 languages); the site said
+ Whisper is fetched for transcripts (it is Parakeet). `showtime doctor` now ends with a link to the troubleshooting
+ page when a check fails. Test: `test_skill_structure.py` (`test_fit_is_estimated_before_synthesis` now scans
+ `voice.md`; the stale-phrase guard now scans `site/build.py` and `harness-notes.md`), `test_lean.py`
(`test_doctor_brief_and_verbose` asserts the link).
-- **A capture lane's page keeps its size when its browser window is resized late (issue #49).** Under load, a
- whole capture lane of a normal render could come out wrong: with 3 workers on a 180-frame film, every frame from 60
- or 120 on. Playwright sizes a new page with two calls at once, the window (`Browser.setWindowBounds`) and the
- emulated viewport (`Emulation.setDeviceMetricsOverride`). A headless window on macOS is at least 500 px wide, so
- there the window always resizes, and when that resize landed after the emulated size, the view the screenshots
- copy took the window's content size, 500x57 for a 256x144 page, while the page itself still laid out at 256x144.
- Every screenshot of that lane was 500x57 (the page in the top-left corner, black beside it), and ffmpeg scaled them
- into the video; a clipped screenshot (`--scale` below 1, `--preview` above 720p) kept the right size with its bottom
- black. The saved captures of the failing renders show it; the frame writes, the encoder's reads (same bytes) and
- the frame order were right in every run. `stagehost.mjs` now sets the page's emulated size again from its own
- DevTools session once the page is ready, which fixes the race wherever it happens. Then it checks: `shot()` checks
- the size of every unclipped screenshot; a page whose screenshots are clipped gets one unclipped screenshot when it
- opens (the clipped ones have the clip's size whatever the view's); and every seek and every clipped screenshot
- read the page's layout size. A wrong size is set again and the screenshot or seek repeated (at most 3 times, then
- the capture fails and the worker retries on a new page), and render.log says so. Not covered: a clipped
- screenshot of a view that loses its size after the page opened while the page keeps its layout (not seen; the
- size set again at ready held through later window resizes in every probe), and `demo.mjs`, `capture.mjs`,
- `site.mjs` and `probe.mjs`, which take their own screenshots. Setting the size again also fixes `--scale 2`
- captures, which were 1x on a Mac every time (a 512x288 render came out 256x144). Measured on a 6-core Intel Mac
- with a GPU, a 256x144 page rendered with `--workers 3` against a 1-worker reference, every frame compared, under
- eight `yes` loops plus a looping 4 GB `dd` (load 17-78): 7 of 40 renders had a wrong lane before, 0 of 30 after
- (5 pages in those 30 runs opened with the 500x57 view and were set right when ready); at `--scale 0.5`, 5 of 20
- before, 0 of 20 after. The `dd` alone did it in 1 of 20 (load about 10), the `yes` loops alone in 0 of 20. Waiting
- for two equal screenshots before the first frame (tried first) does not catch it: two 500x57 screenshots are equal. Test: `test_render_speed.py`
- `TestCaptureSize` (a real window resize after the page opened, at scale 1, 0.5 and 2; each of the ready-time
- call, the screenshot size check, the seek's and the clipped screenshot's layout checks fails it when removed).
+- **A capture lane's page keeps its size when its browser window is resized late (issue #49).** Under load, a whole
+ capture lane of a normal render could come out wrong: with 3 workers on a 180-frame film, every frame from 60 or 120
+ on. Playwright sizes a new page with two calls at once, the window (`Browser.setWindowBounds`) and the emulated
+ viewport (`Emulation.setDeviceMetricsOverride`). A headless window on macOS is at least 500 px wide, so there the
+ window always resizes, and when that resize landed after the emulated size, the view the screenshots copy took the
+ window's content size, 500x57 for a 256x144 page, while the page itself still laid out at 256x144. Every screenshot of
+ that lane was 500x57 (the page in the top-left corner, black beside it), and ffmpeg scaled them into the video; a
+ clipped screenshot (`--scale` below 1, `--preview` above 720p) kept the right size with its bottom black. The saved
+ captures of the failing renders show it; the frame writes, the encoder's reads (same bytes) and the frame order were
+ right in every run. `stagehost.mjs` now sets the page's emulated size again from its own DevTools session once the
+ page is ready, which fixes the race wherever it happens. Then it checks: `shot()` checks the size of every unclipped
+ screenshot; a page whose screenshots are clipped gets one unclipped screenshot when it opens (the clipped ones have
+ the clip's size whatever the view's); and every seek and every clipped screenshot read the page's layout size. A wrong
+ size is set again and the screenshot or seek repeated (at most 3 times, then the capture fails and the worker retries
+ on a new page), and render.log says so. Not covered: a clipped screenshot of a view that loses its size after the page
+ opened while the page keeps its layout (not seen; the size set again at ready held through later window resizes in
+ every probe), and `demo.mjs`, `capture.mjs`, `site.mjs` and `probe.mjs`, which take their own screenshots. Setting the
+ size again also fixes `--scale 2` captures, which were 1x on a Mac every time (a 512x288 render came out 256x144).
+ Measured on a 6-core Intel Mac with a GPU, a 256x144 page rendered with `--workers 3` against a 1-worker reference,
+ every frame compared, under eight `yes` loops plus a looping 4 GB `dd` (load 17-78): 7 of 40 renders had a wrong lane
+ before, 0 of 30 after (5 pages in those 30 runs opened with the 500x57 view and were set right when ready); at
+ `--scale 0.5`, 5 of 20 before, 0 of 20 after. The `dd` alone did it in 1 of 20 (load about 10), the `yes` loops alone
+ in 0 of 20. Waiting for two equal screenshots before the first frame (tried first) does not catch it: two 500x57
+ screenshots are equal. Test: `test_render_speed.py` `TestCaptureSize` (a real window resize after the page opened, at
+ scale 1, 0.5 and 2; each of the ready-time call, the screenshot size check, the seek's and the clipped screenshot's
+ layout checks fails it when removed).
- **Site: "Start here" in four places, the gallery in six shelves, and "New in 0.4" kept low.** A newcomer's first
action sat two diagrams and three tables down the docs map, "Get started" only jumped within the landing, the gallery
was sorted by history (01 to 32) under a 0.2.0 film, a guide page's crumb was a repo path, and the new glossary
(docs/glossary.md) and CONTEXT.md would have built to one page. The docs sidebar's first group is now **Start here**
(Your first video, The map, When something goes wrong, Questions people ask, Glossary, Works with your agent, What's
- new with a version chip), which is also the start of Previous / Next; troubleshooting and the glossary are built,
- and CONTEXT.md moves to `docs/house-vocabulary.html` ("House vocabulary" in Backstage, linked from the glossary).
- The docs map opens with an **Overture · Start here** of three steps (install with Copy, your first video, if
- something goes wrong), and the first-video guide ends on "Next: choose your path". The landing's "Get started"
- opens the first-video guide, and its "New in 0.4" tile (all of 0.4.x) links each released 0.4 section and shows
- five of the new examples. The gallery opens on its intro ("Thirty examples and two demos"), then the tabs and a
- **Start here** shelf named by the kind of video (Launch video, Narrated explainer, Your footage, edited), then six shelves (Explainers, Your footage, Products and brands, Code and data, Social and
- trailers, Looks and motion), each with a line and the guides behind it. The groups and their order live in
- `site/content/gallery.json`, so the examples repository does not change, and the build stops when a card is on no
- shelf or two. The ten 0.4 examples carry a "New in 0.4" badge and a last tab, every card shows its number and one
- duration format (`25 · 2:38`, `02 · 0:45`) and a "Copy the request" button, example pages are titled "Example 25:
- ...", guide pages name their act in the crumb ("Docs / Act IV · Sound and voice / Voice") with a "See it done" line
- of examples, and the docs search opens install, error and first-video questions on the page written for them. The
- film above the gallery is gone (`"gallery_film": null` in `site/config.json`; an object brings one back), the
- footer credits its music only while one is set, and README.md's links to `gallery.html#launch-film` now go to the
- gallery and the film's MP4. The old tab addresses (`gallery.html#data-and-reports`, `#for-developers` ...) open
- All. The build stops when gallery.json's "New in" name is not the newest release's series, so the badges and the
- landing tile cannot name different releases. Test:
+ new with a version chip), which is also the start of Previous / Next; troubleshooting and the glossary are built, and
+ CONTEXT.md moves to `docs/house-vocabulary.html` ("House vocabulary" in Backstage, linked from the glossary). The docs
+ map opens with an **Overture · Start here** of three steps (install with Copy, your first video, if something goes
+ wrong), and the first-video guide ends on "Next: choose your path". The landing's "Get started" opens the first-video
+ guide, and its "New in 0.4" tile (all of 0.4.x) links each released 0.4 section and shows five of the new examples.
+ The gallery opens on its intro ("Thirty examples and two demos"), then the tabs and a **Start here** shelf named by
+ the kind of video (Launch video, Narrated explainer, Your footage, edited), then six shelves (Explainers, Your
+ footage, Products and brands, Code and data, Social and trailers, Looks and motion), each with a line and the guides
+ behind it. The groups and their order live in `site/content/gallery.json`, so the examples repository does not change,
+ and the build stops when a card is on no shelf or two. The ten 0.4 examples carry a "New in 0.4" badge and a last tab,
+ every card shows its number and one duration format (`25 · 2:38`, `02 · 0:45`) and a "Copy the request" button,
+ example pages are titled "Example 25: ...", guide pages name their act in the crumb ("Docs / Act IV · Sound and voice
+ / Voice") with a "See it done" line of examples, and the docs search opens install, error and first-video questions on
+ the page written for them. The film above the gallery is gone (`"gallery_film": null` in `site/config.json`; an object
+ brings one back), the footer credits its music only while one is set, and README.md's links to
+ `gallery.html#launch-film` now go to the gallery and the film's MP4. The old tab addresses
+ (`gallery.html#data-and-reports`, `#for-developers` ...) open All. The build stops when gallery.json's "New in" name
+ is not the newest release's series, so the badges and the landing tile cannot name different releases. Test:
`test_site_build.py` `StartHereAndShelves`, `PeoplePages` `test_glossary_and_house_vocabulary_have_their_own_pages`,
`test_site_search.py` `RealBuild`.
- **A name cleared in `readback.ok` also clears it inside a longer phrase, and `readback.note` keeps a respelled
@@ -365,43 +494,43 @@ All notable changes to showtime. Each entry says what changed and why, so this f
found that newcomers were sent to the 1,382-line README, that troubleshooting answers were written for agents only,
and that EDL, ledger and look signature were used before any page defined them. New pages:
`docs/guides/first-video.md` (a 5-second test video step by step, timed on a 6-core Intel Mac, in the task-guide
- shape), `docs/troubleshooting.md` (twelve symptoms, each with what showtime does today, what to say and the
- command) and `docs/glossary.md` (the reader's glossary with a diagram of the job folder; CONTEXT.md stays the house
- vocabulary and is linked from it).
- The README, the docs map, the guides index and the FAQ link them. The two mode settings are now explained as two:
- quick or studio (how much the agent asks) and quality or lean (how much it checks), in the README, SKILL.md, the
- docs map and modes.md; the docs map no longer says "quick is lean". EDL, ledger and look signature are defined at
- first use (SKILL.md, editing.md, color.md). The FAQ's GPU answer leads with the answer, its language count names the
- eight Kokoro languages and the 32 in all (Kokoro's nine counts American and British English apart), the README's
- scoreboard sentence says what was measured, and "How it works" opens with today's order instead of the 0.2.0
- history. agents.md now says your agent runs setup, with terminal setup only for a sandbox that blocks the download,
- and names the transcription model instead of Whisper. SKILL.md goes from about 1,500 to about 1,490 words with every
- red flag kept: the new definitions are short there (the glossary has the long ones), and the opening line and a few phrases
- are tighter. `check_release` now checks the links and commands of the two new
- docs/ pages. Test: `test_skill_structure.py` `TestCheckersBite` `test_newcomer_pages_are_linked_and_checked`.
-- **Chapter mode: render a film in named pieces and join them with one soundtrack (issue #22).** Rendering
- sections with `--from/--to` and joining them with `edit render` gave loudness steps of 2.6 and 0.7 dB at the
- joins (each span mastered its own audio) and cut fades. `render --chapters` prints the plan from showtime.json
- `"chapters"` (else the film's acts) and says first that on one machine a whole render is faster (measured: see
- render.md § Speed); `render --chapter N --job J` splices chapter N into the job's full render, or without one
- writes a video-only piece in `<job>/work/chapters/<W>x<H>/`; `render --join --job J` byte-joins the pieces at
- their keyframes (or encodes once when their settings differ), builds the soundtrack once for the whole video,
- muxes it and checks every seam against the master (frames, keyframes, the seam frames captured again against a frame inside the
- same piece, so grain or a high CRF passes, loudness step <= 0.1 dB, lag 0 +-1 sample) before naming it `final.mp4`, `kind: "joined"`; `qa` adds a seam section.
- Every whole render now has a keyframe at each chapter start, so after a whole render or a join a later
+ shape), `docs/troubleshooting.md` (twelve symptoms, each with what showtime does today, what to say and the command)
+ and `docs/glossary.md` (the reader's glossary with a diagram of the job folder; CONTEXT.md stays the house vocabulary
+ and is linked from it). The README, the docs map, the guides index and the FAQ link them. The two mode settings are
+ now explained as two: quick or studio (how much the agent asks) and quality or lean (how much it checks), in the
+ README, SKILL.md, the docs map and modes.md; the docs map no longer says "quick is lean". EDL, ledger and look
+ signature are defined at first use (SKILL.md, editing.md, color.md). The FAQ's GPU answer leads with the answer, its
+ language count names the eight Kokoro languages and the 32 in all (Kokoro's nine counts American and British English
+ apart), the README's scoreboard sentence says what was measured, and "How it works" opens with today's order instead
+ of the 0.2.0 history. agents.md now says your agent runs setup, with terminal setup only for a sandbox that blocks the
+ download, and names the transcription model instead of Whisper. SKILL.md goes from about 1,500 to about 1,490 words
+ with every red flag kept: the new definitions are short there (the glossary has the long ones), and the opening line
+ and a few phrases are tighter. `check_release` now checks the links and commands of the two new docs/ pages. Test:
+ `test_skill_structure.py` `TestCheckersBite` `test_newcomer_pages_are_linked_and_checked`.
+- **Chapter mode: render a film in named pieces and join them with one soundtrack (issue #22).** Rendering sections with
+ `--from/--to` and joining them with `edit render` gave loudness steps of 2.6 and 0.7 dB at the joins (each span
+ mastered its own audio) and cut fades. `render --chapters` prints the plan from showtime.json `"chapters"` (else the
+ film's acts) and says first that on one machine a whole render is faster (measured: see render.md § Speed);
+ `render --chapter N --job J` splices chapter N into the job's full render, or without one writes a video-only piece in
+ `<job>/work/chapters/<W>x<H>/`; `render --join --job J` byte-joins the pieces at their keyframes (or encodes once when
+ their settings differ), builds the soundtrack once for the whole video, muxes it and checks every seam against the
+ master (frames, keyframes, the seam frames captured again against a frame inside the same piece, so grain or a high
+ CRF passes, loudness step <= 0.1 dB, lag 0 +-1 sample) before naming it `final.mp4`, `kind: "joined"`; `qa` adds a
+ seam section. Every whole render now has a keyframe at each chapter start, so after a whole render or a join a later
`--chapter N` fix re-renders exactly its frames. A piece cut short is refused with its `--chapter N` command, a
- one-chapter film is refused, and the receipt counts each piece's time once. Pieces carry `sources_hash` (the project's sources, the same on a copy at another path): other
- files warn at the join, another length or size is refused. Tests: `test_chapters.py`.
-- **The join's seam check compares each frame on Windows too.** On the Windows CI runner `render --join` stopped
- at a random frame of the seam check with "could not compare frame 119 of mux.mp4: frame= 1 ... time=00:00:00.00". The PSNR
- comparison gave ffmpeg's `psnr` the captured image at time 0 and the video's frame half a frame later (the seek
- lands between frames), so the one frame `-frames:v 1` keeps went out uncompared, and the real comparison only ran
- when the image's end of stream arrived, after the output had finished. Whether ffmpeg ran it before shutting down
- was thread timing: it did on macOS and Linux and now and then did not on Windows (no PSNR line, exit 0). Both
- inputs now start at time 0, so the first frame is the compared one on any OS, and the error quotes ffmpeg's own
- message instead of its progress line and stream list (`settb=AVTB` also drops psnr's "not matching timebases" warning;
- same values). Test: `test_chapters.py` (`test_frame_psnr_compares_the_frame_it_outputs` holds the image's end of
- stream back 1.5 s, which fails the old graph on any OS, and checks the value; `test_ff_messages_drop_progress`).
+ one-chapter film is refused, and the receipt counts each piece's time once. Pieces carry `sources_hash` (the project's
+ sources, the same on a copy at another path): other files warn at the join, another length or size is refused. Tests:
+ `test_chapters.py`.
+- **The join's seam check compares each frame on Windows too.** On the Windows CI runner `render --join` stopped at a
+ random frame of the seam check with "could not compare frame 119 of mux.mp4: frame= 1 ... time=00:00:00.00". The PSNR
+ comparison gave ffmpeg's `psnr` the captured image at time 0 and the video's frame half a frame later (the seek lands
+ between frames), so the one frame `-frames:v 1` keeps went out uncompared, and the real comparison only ran when the
+ image's end of stream arrived, after the output had finished. Whether ffmpeg ran it before shutting down was thread
+ timing: it did on macOS and Linux and now and then did not on Windows (no PSNR line, exit 0). Both inputs now start at
+ time 0, so the first frame is the compared one on any OS, and the error quotes ffmpeg's own message instead of its
+ progress line and stream list (`settb=AVTB` also drops psnr's "not matching timebases" warning; same values). Test:
+ `test_chapters.py` (`test_frame_psnr_compares_the_frame_it_outputs` holds the image's end of stream back 1.5 s, which
+ fails the old graph on any OS, and checks the value; `test_ff_messages_drop_progress`).
- **`test_signatures.py` checks reading time once per motion feel and template, not twelve times.** On the Windows
nightly the file ran 868 s on its first night (6 Oct), then out of its 900 s on 7 and 8 Oct (680 s on 9 Oct); the
Intel Mac reached 900 s on 9 Oct. It ran a full `showtime check` per look signature, twelve of them, on 4-thread
@@ -452,32 +581,32 @@ All notable changes to showtime. Each entry says what changed and why, so this f
`test_no_cuts_skips_the_walk`.
- **`review-findings` accepts `t=a-b s` ranges as a timestamp, and Polish items get ids.** A finding carrying a range
such as `t=38.73-41.50s` was warned as citing no timestamp (the check only knew `t=3.00s`), and Polish bullets were
- left out of the id scheme, so `showtime review-respond <job> --fixed r1-P1` only printed the list of valid ids
- (issue #48). Ranges (`t=38.73-41.50s`, `t=38.73s-41.50s`, `t=38.73 - 41.50 s`) now count in every finding, and
- Polish bullets are registered as `r1-P1 ...` beside `r1-B1` and `r1-S1`: they are listed by `review-respond`, can be
- marked fixed or waived, and are counted by `review-findings`, but are never open, so they still never gate the
- delivery (and stay out of the receipt's counts and lists and the next round's PREVIOUS list). The pairwise parser
- `review-verdict` reads uses the same timestamp pattern, so a range-timestamped finding is no longer dropped there.
- A Polish bullet without a timestamp now gets the "cites no timestamp" warning too, as CRITIC.md asks of each. Test: `test_review_mode.py`
+ left out of the id scheme, so `showtime review-respond <job> --fixed r1-P1` only printed the list of valid ids (issue
+ #48). Ranges (`t=38.73-41.50s`, `t=38.73s-41.50s`, `t=38.73 - 41.50 s`) now count in every finding, and Polish bullets
+ are registered as `r1-P1 ...` beside `r1-B1` and `r1-S1`: they are listed by `review-respond`, can be marked fixed or
+ waived, and are counted by `review-findings`, but are never open, so they still never gate the delivery (and stay out
+ of the receipt's counts and lists and the next round's PREVIOUS list). The pairwise parser `review-verdict` reads uses
+ the same timestamp pattern, so a range-timestamped finding is no longer dropped there. A Polish bullet without a
+ timestamp now gets the "cites no timestamp" warning too, as CRITIC.md asks of each. Test: `test_review_mode.py`
`TestReviewFindings` `test_time_ranges_count_as_timestamps`, `TestFindingsGate`
`test_polish_ids_register_and_never_gate`.
-- **Voice-led workflows run `voice script --fit S --estimate` before the first synthesis.** `--estimate` already
- prints "cut about N words" and synthesizes nothing, but only `voice.md` mentioned it: the social-short, explainer
- and other voice-led routes went straight to `--fit <seconds>`, so an agent with a slow voice (about 2.6 words/s)
- ran a 1-4 minute fit three times, cutting words between runs, and ended at x1.12 (issue #45). The social-short,
- explainer, repo-explainer, paper-explainer, data-story, localize and manim guides, the scriptwriter and voice
- director briefs now say to estimate first and cut words until it fits, and SKILL.md pipeline step 2 names the estimate and then the real run. Test:
- `test_skill_structure.py` `TestSkillMd` `test_fit_is_estimated_before_synthesis`.
+- **Voice-led workflows run `voice script --fit S --estimate` before the first synthesis.** `--estimate` already prints
+ "cut about N words" and synthesizes nothing, but only `voice.md` mentioned it: the social-short, explainer and other
+ voice-led routes went straight to `--fit <seconds>`, so an agent with a slow voice (about 2.6 words/s) ran a 1-4
+ minute fit three times, cutting words between runs, and ended at x1.12 (issue #45). The social-short, explainer,
+ repo-explainer, paper-explainer, data-story, localize and manim guides, the scriptwriter and voice director briefs now
+ say to estimate first and cut words until it fits, and SKILL.md pipeline step 2 names the estimate and then the real
+ run. Test: `test_skill_structure.py` `TestSkillMd` `test_fit_is_estimated_before_synthesis`.
- **"This look repeats recent videos" names the property that matched, its distance and its threshold.** The warning
- said which aspect repeated (palette, type pair ...) and listed the look's own values, but not what matched against
- the earlier job or how close it was, so after changing colours by hand the warning stayed with no way to tell what
- to change next (issue #47). Each repeat now carries a `why` (in `showtime check`, `history check` and `--json`): the
- palette colours that matched with their distance and the threshold (`3 of 4 colours match (#a ~ #b 12 apart; threshold
- 60, needs 3)`), `fonts identical (Inter)`, the share of camera moves or transition kinds against its limit, the
- scene-length spread against 6 %. A page wearing a look
- signature matches on the signature id in its look comment, not on colours, and says so (changing colours does not
- clear it; `showtime signature` picks another). The `why` names the job it was measured against. Test: `test_variety.py` `TestHistory`
- `test_message_names_the_matched_property_distance_and_threshold`.
+ said which aspect repeated (palette, type pair ...) and listed the look's own values, but not what matched against the
+ earlier job or how close it was, so after changing colours by hand the warning stayed with no way to tell what to
+ change next (issue #47). Each repeat now carries a `why` (in `showtime check`, `history check` and `--json`): the
+ palette colours that matched with their distance and the threshold
+ (`3 of 4 colours match (#a ~ #b 12 apart; threshold 60, needs 3)`), `fonts identical (Inter)`, the share of camera
+ moves or transition kinds against its limit, the scene-length spread against 6 %. A page wearing a look signature
+ matches on the signature id in its look comment, not on colours, and says so (changing colours does not clear it;
+ `showtime signature` picks another). The `why` names the job it was measured against. Test: `test_variety.py`
+ `TestHistory` `test_message_names_the_matched_property_distance_and_threshold`.
- **`render --size` checks the page it renders, and a timing error is not "the layout breaks".** The layout check that
runs before a `--size` render started `check` without `--page`, so it ran on `index.html`: a page whose text runs
off the frame at 9:16 rendered anyway while `index.html` was fine, a broken `index.html` stopped the render of a
@@ -501,13 +630,13 @@ All notable changes to showtime. Each entry says what changed and why, so this f
limits); below 8 threads and with a GPU nothing changes. Test: `test_render_speed.py`
`test_auto_workers_and_software_gl`.
- **`edit render` keeps the sound in sync with the picture on showtime's own renders (issue #38).** A range cut from a
- render made by showtime (`-bf 0`: its video edit list starts at 0, its audio's after the 1024-sample AAC priming) could
- come out with its sound up to 1024 samples (21 ms) early: the input seek that cut each range is not sample-accurate
- on this audio, and its error depends on where it lands (1024 samples at `"start": 0`, the usual case for span or
- chapter files, which also left 21 ms of silence before every cut; 256, 512 or 1024 at some later starts, e.g. 2, 4
- and 8 s). Each range's sound is now decoded from the file's start, with no input seek, and trimmed to the exact
- sample; the video keeps its fast seek. Decoding the AAC of a 10-minute source takes about 1 s, so a range near its
- end renders about 1 s slower. Cached segments are rebuilt once. Test: `test_footage.py` `EdlAudioSyncTest`.
+ render made by showtime (`-bf 0`: its video edit list starts at 0, its audio's after the 1024-sample AAC priming)
+ could come out with its sound up to 1024 samples (21 ms) early: the input seek that cut each range is not
+ sample-accurate on this audio, and its error depends on where it lands (1024 samples at `"start": 0`, the usual case
+ for span or chapter files, which also left 21 ms of silence before every cut; 256, 512 or 1024 at some later starts,
+ e.g. 2, 4 and 8 s). Each range's sound is now decoded from the file's start, with no input seek, and trimmed to the
+ exact sample; the video keeps its fast seek. Decoding the AAC of a 10-minute source takes about 1 s, so a range near
+ its end renders about 1 s slower. Cached segments are rebuilt once. Test: `test_footage.py` `EdlAudioSyncTest`.
- **Extra local voice engines load by name, and doctor stops failing on Kokoro when you chose another engine.**
The engine list was closed in three places (`engines.get()`, the `--engine` choices and `$SHOWTIME_VOICE`), and
doctor failed on Kokoro's model files even after `setup --skip models` with another engine selected. An engine of
@@ -519,12 +648,12 @@ All notable changes to showtime. Each entry says what changed and why, so this f
Kokoro) and lists each extra engine and whether it imports. `references/voice.md` has a "Bring your own voice
engine" section: your engine, your network; showtime ships no network engine. Proposed and designed by @heavygee
in issue #8, who also wrote a matching PR (#36). Test: `test_voice_engines.py`.
-- **The scriptwriter and the storyboard artist get more turns, and the director is told how to stay inside them.** A heavy
- storyboard brief ran out of turns before it finished (issue #42). `scriptwriter` now has `maxTurns: 50` (was 30) and
- `storyboard-artist` `maxTurns: 80` (was 50). `references/crew.md` §3 tells the director to split a heavy brief (the
- board first, the animatic as a second task) and, when a member stops at its cap, to resume it with a follow-up
- `SendMessage` instead of dispatching it again. Test: `test_skill_structure.py` checks that every crew agent
- declares `maxTurns` between 20 and 100.
+- **The scriptwriter and the storyboard artist get more turns, and the director is told how to stay inside them.** A
+ heavy storyboard brief ran out of turns before it finished (issue #42). `scriptwriter` now has `maxTurns: 50` (was 30)
+ and `storyboard-artist` `maxTurns: 80` (was 50). `references/crew.md` §3 tells the director to split a heavy brief
+ (the board first, the animatic as a second task) and, when a member stops at its cap, to resume it with a follow-up
+ `SendMessage` instead of dispatching it again. Test: `test_skill_structure.py` checks that every crew agent declares
+ `maxTurns` between 20 and 100.
- **A fix to a `--size` variant is spliced too.** `render --from/--to --job` spliced a fix into the job's last
full render, but with `--size` it always wrote a span clip, so an audio-only fix to the 9:16 cut
(`<job>/1080x1920.mp4`) took a full re-render (about 2.5 min instead of 43 s for the 16:9 final). With `--size` the
@@ -543,7 +672,8 @@ All notable changes to showtime. Each entry says what changed and why, so this f
- **`voice script --fit` says up front when the narration cannot fit.** It used to synthesize every line, then
re-synthesize them all at up to four speeds, and only then report how many words to cut (issue #28). Now the
characters are counted at the voice's own rate before the first line, a script that is too long gets "cut about N
- words" (and the rushed-speech warning) at once, and `--fit S --estimate` prints that estimate alone without making any audio.
+ words" (and the rushed-speech warning) at once, and `--fit S --estimate` prints that estimate alone without making any
+ audio.
- **`voice_to_music_db` is no longer empty when the music is `ST.score`.** The score is rendered offline and
combined after the mix, so a voice-over mix plus `ST.score` had no music bus and `mix.report.json` said
`"voice_to_music_db": null` (qa's hearing facts read the same field), although the guides tell the reader to
@@ -559,15 +689,16 @@ All notable changes to showtime. Each entry says what changed and why, so this f
working (a page with its own timer loop). `SHOWTIME_TIMEOUT=<seconds>` gives a render or check its caller's limit:
past it the command ends with an error naming where each of its parts is. Tests: `test_pace.py`
`TestFrameNeverComes`, `TestSlowPages`.
-- **`--disable-frame-rate-limit` stays on Linux only.** 0.4.1 shipped it in render's browsers on every OS. With it,
- a renderer keeps spending CPU after the GPU process stops, so on macOS the guard above never saw a stopped GPU
- process (measured on an Intel Mac with a GPU: the stall test fails with the flag and passes without), and it bought
- about 2 % there, inside run-to-run spread, for about 22 % more CPU while rendering; it is the likely cause of the
- stalls on the macOS CI runners, where this has not been re-run. On an 8-thread Linux machine without a GPU it is
- about 10 % faster than without it (5 % faster than 0.4.1, which has the flag but not the guard) and the guard still ends a frame that never comes. `"render"` in
- `scripts/lib/chrome-flags.json` is now per OS like `"gpu"` (`renderFlags()` still takes a plain list): on Linux only;
- off on macOS and Windows, which is untested with the guard and goes back to its state before 0.4.1. Tests:
- `test_pace.py` `test_no_frame_rate_limit_flag`, `test_render_speed.py` `test_auto_workers_and_software_gl`.
+- **`--disable-frame-rate-limit` stays on Linux only.** 0.4.1 shipped it in render's browsers on every OS. With it, a
+ renderer keeps spending CPU after the GPU process stops, so on macOS the guard above never saw a stopped GPU process
+ (measured on an Intel Mac with a GPU: the stall test fails with the flag and passes without), and it bought about 2 %
+ there, inside run-to-run spread, for about 22 % more CPU while rendering; it is the likely cause of the stalls on the
+ macOS CI runners, where this has not been re-run. On an 8-thread Linux machine without a GPU it is about 10 % faster
+ than without it (5 % faster than 0.4.1, which has the flag but not the guard) and the guard still ends a frame that
+ never comes. `"render"` in `scripts/lib/chrome-flags.json` is now per OS like `"gpu"` (`renderFlags()` still takes a
+ plain list): on Linux only; off on macOS and Windows, which is untested with the guard and goes back to its state
+ before 0.4.1. Tests: `test_pace.py` `test_no_frame_rate_limit_flag`, `test_render_speed.py`
+ `test_auto_workers_and_software_gl`.
- **A WebGL canvas that loses its context no longer ships white.** On the Intel Mac CI runner some renders lost
every WebGL context on the GPU, and each of those canvases was captured white with no word from `render`
@@ -595,8 +726,8 @@ All notable changes to showtime. Each entry says what changed and why, so this f
after a silent scene but not directly after it, the line right after the silence lost the pin and the silence was
counted twice: once by the voice holding the gap up to the pin and once as the silent scene's own length. The first
pinned line after the silent scene now counts, even with unpinned lines between them, so the silent scene fills the
- gap before the pin and keeps its length when the gap allows; render.md says so. Test: `test_storyboard.py` `TestSilentShots`
- `test_a_later_pin_holds_the_silent_shot_once`, `test_two_lines_after_a_silent_shot_one_pinned`.
+ gap before the pin and keeps its length when the gap allows; render.md says so. Test: `test_storyboard.py`
+ `TestSilentShots` `test_a_later_pin_holds_the_silent_shot_once`, `test_two_lines_after_a_silent_shot_one_pinned`.
- **The stable `showtime` command keeps the installed skill when two copies have the same version (issue #23).**
On a tie the command used to follow whichever folder ran last, so running a second checkout or a scratch copy of the
installed version re-pointed it for every agent and script sharing the home. Now an installed skill (a plugin, or a
@@ -664,12 +795,12 @@ All notable changes to showtime. Each entry says what changed and why, so this f
number.
- `showtime edit cards suggest` lists card moments in a transcript, locally; `edit check`, `edit view` and qa
(`card_problem`) know cards, and `edit check` flags list items said after their card leaves.
-- **A word behind the speaker, cut out on the CPU.** `showtime footage cutout <clip> [--from A --to B] [-o out]`
- cuts a person out with MODNet portrait matting (Apache-2.0, 26 MB, fetched on first use), smoothed over time and
- reset at every cut, as VP9 with alpha (`--format prores` or `png`), a matte file and a contact sheet. About
- 1.3-1.8 min per minute of 1080p on a 64-core Linux machine with no GPU, about 5.7 min when held to 6 of its cores
- (3.7 with `--size 384`). The EDL card `"type": "behind"` puts a big word between the background (`dim`, `blur`, `ground`, a colour
- or an image) and the speaker; qa warns `behind_hidden` and `matte_flicker`.
+- **A word behind the speaker, cut out on the CPU.** `showtime footage cutout <clip> [--from A --to B] [-o out]` cuts a
+ person out with MODNet portrait matting (Apache-2.0, 26 MB, fetched on first use), smoothed over time and reset at
+ every cut, as VP9 with alpha (`--format prores` or `png`), a matte file and a contact sheet. About 1.3-1.8 min per
+ minute of 1080p on a 64-core Linux machine with no GPU, about 5.7 min when held to 6 of its cores (3.7 with
+ `--size 384`). The EDL card `"type": "behind"` puts a big word between the background (`dim`, `blur`, `ground`, a
+ colour or an image) and the speaker; qa warns `behind_hidden` and `matte_flicker`.
- **A long recording to its best short clips.** `showtime edit moments <transcripts | folder | job>` ranks
whole-sentence moments of `--min`..`--max` seconds by local signals (a hook in the first 3 s, a complete thought,
speaker energy, laughter and applause, one topic; introductions and logistics rank lower) into `moments.json` with
@@ -689,27 +820,27 @@ All notable changes to showtime. Each entry says what changed and why, so this f
fonts.gstatic.com; an offline `--refresh` keeps the fonts already copied (checked by sha256).
- An artboard larger than the frame is no longer cropped, a cursor blink is not taken as the loop, and
`adopt.json` keeps paths relative to the project.
-- **Seven looks in showtime's own WebGL, no GPU needed**: `fluted-glass`, `tilt-shift`, `liquid-metal`,
- `mesh-gradient`, `god-rays`, `marble` and `metaballs`, each with presets built from the theme tokens, the same
- frames with any worker count, and a designed fallback where WebGL is missing. At its default size each adds less
- than 50 ms to a 1080p frame without a GPU (one browser on the 64-core machine; `references/components.md` section
- 7 has the table). A look holds a WebGL context only while its clip is on screen, so twenty looks on one page no
- longer go blank, and on a GPU each look reads its frame back before the screenshot (no stale frames).
- `showtime check` prints each look's estimated cost and warns `look_budget` (over 50 ms), `look_fallback`, `look_contexts`
- (over 8 on screen at once, an error over 14) and `look_lost`. `examples/_looks`.
+- **Seven looks in showtime's own WebGL, no GPU needed**: `fluted-glass`, `tilt-shift`, `liquid-metal`, `mesh-gradient`,
+ `god-rays`, `marble` and `metaballs`, each with presets built from the theme tokens, the same frames with any worker
+ count, and a designed fallback where WebGL is missing. At its default size each adds less than 50 ms to a 1080p frame
+ without a GPU (one browser on the 64-core machine; `references/components.md` section 7 has the table). A look holds a
+ WebGL context only while its clip is on screen, so twenty looks on one page no longer go blank, and on a GPU each look
+ reads its frame back before the screenshot (no stale frames). `showtime check` prints each look's estimated cost and
+ warns `look_budget` (over 50 ms), `look_fallback`, `look_contexts` (over 8 on screen at once, an error over 14) and
+ `look_lost`. `examples/_looks`.
- **Shutter blur on chosen elements.** `data-st-blur` (or `ST.blur(el, {pose})`) smears an element as a 180° shutter
would, only on the frames it moves fast, and lands it sharp; options `shutter`, `samples`, `threshold`, `max`;
- `F.motionBlur` for canvas films. About 8 ms more per blurred word per frame at 1080p without a GPU (one browser on the 64-core Linux machine). check warns
- `blur_text`, `blur_slow`, `blur_container`, `blur_unsampled` and `blur_inline`. The showreel template's flash
- words are now snaps under the blur. `examples/_blur`.
+ `F.motionBlur` for canvas films. About 8 ms more per blurred word per frame at 1080p without a GPU (one browser on the
+ 64-core Linux machine). check warns `blur_text`, `blur_slow`, `blur_container`, `blur_unsampled` and `blur_inline`.
+ The showreel template's flash words are now snaps under the blur. `examples/_blur`.
- **qa hears the mix as a phone speaker does, and the mixer is speaker-safe by default.** The first mix of the 0.4.1
- showreel was almost inaudible on a phone: above 300 Hz it sat 13.6 LU under the full mix. `speaker_loudness`
- measures the mix above 300 Hz and 1 kHz against the full mix: WARN over 10 LU, FAIL over 18 (posted films measure
- 0.7-8.2 LU; a soundtrack showtime did not mix, such as your own song or a footage edit's sound, stays a WARN). `showtime audio mix` (so also `render` of a showtime.json `"audio"` mix; not an `ST.score` bed or the
- built-in fallback mixer) puts a 40 Hz high-pass on everything but the voice and, on a bass-heavy mix, a low shelf on
- the bed; voice-led films change by 0.01 LU. `"master": {"speaker_safe": false}` or
- `--no-speaker-safe` turns it off. The mix report gives each effect its speaker gap and notes a sub hit with
- nothing in the mids (`sub_alone`).
+ showreel was almost inaudible on a phone: above 300 Hz it sat 13.6 LU under the full mix. `speaker_loudness` measures
+ the mix above 300 Hz and 1 kHz against the full mix: WARN over 10 LU, FAIL over 18 (posted films measure 0.7-8.2 LU; a
+ soundtrack showtime did not mix, such as your own song or a footage edit's sound, stays a WARN). `showtime audio mix`
+ (so also `render` of a showtime.json `"audio"` mix; not an `ST.score` bed or the built-in fallback mixer) puts a 40 Hz
+ high-pass on everything but the voice and, on a bass-heavy mix, a low shelf on the bed; voice-led films change by 0.01
+ LU. `"master": {"speaker_safe": false}` or `--no-speaker-safe` turns it off. The mix report gives each effect its
+ speaker gap and notes a sub hit with nothing in the mids (`sub_alone`).
- **The voice-over is heard back.** `voice script` and `voice say` transcribe what they wrote with the local
recognizer and compare it with the script sound by sound, so a name, acronym or number said wrong ("Open A I"
heard as "OpenI") is a WARN with its fix; cached by each line's audio and recognizer. It runs when the local
@@ -753,12 +884,12 @@ All notable changes to showtime. Each entry says what changed and why, so this f
recorded as 0 LUFS. The preview window opens Chrome with its device discovery (Cast) turned off. The test suite skips
the site tests without the examples checkout. `check_release.py --mirror` checks every model and audio mirror
asset, and a failed model download names the missing mirror file.
-- **Docs for people.** An FAQ (GPU, cost, agents, privacy, licences, disk, time, platforms, languages, hand edits,
- the critic, questions, notes) and What's new, first in the site's Start group; ten task guides in `docs/guides/`
- (a talking head with cards, Claude Design to MP4, a long recording to clips, a launch video from a repo, another
- language, a PR video, an explainer that asks, going all out, notes and fixes, a slow machine), each with what to
- say, what you get, measured times naming the machine and the limits, in their own sidebar group after Start. The README, the docs
- maps, SKILL.md, SECURITY and PRIVACY catch up with 0.4.0 and 0.4.1. Site search finds hyphenated names
+- **Docs for people.** An FAQ (GPU, cost, agents, privacy, licences, disk, time, platforms, languages, hand edits, the
+ critic, questions, notes) and What's new, first in the site's Start group; ten task guides in `docs/guides/` (a
+ talking head with cards, Claude Design to MP4, a long recording to clips, a launch video from a repo, another
+ language, a PR video, an explainer that asks, going all out, notes and fixes, a slow machine), each with what to say,
+ what you get, measured times naming the machine and the limits, in their own sidebar group after Start. The README,
+ the docs maps, SKILL.md, SECURITY and PRIVACY catch up with 0.4.0 and 0.4.1. Site search finds hyphenated names
(`pr-video`) and opens the matching section; pages get share tags and a canonical link, and the site has
`sitemap.xml`, `robots.txt` and `llms.txt`.
- **Examples for 0.4.0 and 0.4.1 (#18).** 23, a NASA interview dressed with cards and a word behind the speaker, at
@@ -781,12 +912,12 @@ All notable changes to showtime. Each entry says what changed and why, so this f
- Posters, thumbnails, qa frames and snaps pulled into a JPEG convert the video's colours properly (a saturated
poster was about 6 levels darker than its frame), and qa compares the poster with its exact frame.
- A file that reads above the -1 dBTP ceiling at all after the AAC encode is re-encoded (a GitHub copy read -0.9).
- - `pr-video` shows a description's list item by item ("+ N more" for the rest) instead of the opening paragraph
- cut into frames; the showreel template's data shot fits 1:1 and 4:5; a mix track's `"ending": "song"` keeps the
- song's own ending; a span render with `-o <own name>.mp4` and no `--job` writes that file and never splices into the job's final
- (with `--job` the fix is spliced as before and `-o` is ignored); two renders
- started in the same second no longer share a folder; a scene marked `data-stretch="spread"` spreads its beats
- when it gets longer (the dom template's hero no longer holds still at `--duration 24`).
+ - `pr-video` shows a description's list item by item ("+ N more" for the rest) instead of the opening paragraph cut
+ into frames; the showreel template's data shot fits 1:1 and 4:5; a mix track's `"ending": "song"` keeps the song's
+ own ending; a span render with `-o <own name>.mp4` and no `--job` writes that file and never splices into the job's
+ final (with `--job` the fix is spliced as before and `-o` is ignored); two renders started in the same second no
+ longer share a folder; a scene marked `data-stretch="spread"` spreads its beats when it gets longer (the dom
+ template's hero no longer holds still at `--duration 24`).
- Transcripts say where their language came from (`language_source`), Parakeet v3's language guess works again (it
always said English), a soft first word is kept and a music intro is not transcribed.
- `guide --find` takes several words unquoted; the templates' sample URL is a reserved `.example` name; the site
@@ -798,11 +929,12 @@ All notable changes to showtime. Each entry says what changed and why, so this f
## 0.4.0 (2026-10-05)
-- **Videos that stop and ask.** showtime.json `"questions"` lists stop-and-ask questions: `{id, at, prompt, choices,
- answer, reply, think}`. `at` is seconds or a voice cue (the id of a narration line, `"ask"`, `"ask.start"`,
- `"ask.end+0.4"`), read where the mix plays that line (a `vo-<id>` track of `retime --from-voice` or a track
- playing the line's own file, else the vo.wav track's start), so a re-voice moves every question with its line; `retime -d` moves the ones given in seconds. Proven first in the
- Socratic videos, where a separate page layer drove the exported player; now it is built in:
+- **Videos that stop and ask.** showtime.json `"questions"` lists stop-and-ask questions:
+ `{id, at, prompt, choices, answer, reply, think}`. `at` is seconds or a voice cue (the id of a narration line,
+ `"ask"`, `"ask.start"`, `"ask.end+0.4"`), read where the mix plays that line (a `vo-<id>` track of
+ `retime --from-voice` or a track playing the line's own file, else the vo.wav track's start), so a re-voice moves
+ every question with its line; `retime -d` moves the ones given in seconds. Proven first in the Socratic videos, where
+ a separate page layer drove the exported player; now it is built in:
- `showtime export html` pauses on the question's own frame and asks it in a card (choices, A-C or 1-3, a right or
wrong mark, the reply, Continue), then plays on from the end of the MP4's "pause and think" beat (`at + think`).
Seeking past a question passes it, seeking back asks it again, a restart asks them all; a background tab still
@@ -1011,25 +1143,25 @@ All notable changes to showtime. Each entry says what changed and why, so this f
- **New projects start in a look of their own: look signatures.** In the bake-off three different models made three
near-identical dark-and-gold videos: the launch template's own look, unchanged; the look history only warned
afterwards. Now `showtime new` dresses the page templates (dom, launch, short, data) in one of twelve curated look
- signatures, seven dark and five light (data takes the light ones), each a palette (every text colour at the
- contrast rules: ink 7:1, muted and accent text 4.8:1, the ink on the accent 4.5:1, the product window through the
- brand kit's legibility rules), a type pair from the shipped fonts, a motion feel (the theme's motion tokens) and a
- ground (how much key light, grid and vignette the template paints). The pick is seeded by the folder name
- (`--look-seed`) and avoids the signatures of the last six projects created on the machine (`<history>/picks.json`,
- local, off with the look history) and the palettes and display faces of the last five finished videos. `new`
- prints the look and how to change it; `--look <id>` names one and `--look template` keeps the template's own. A
- brand kit always wins (a kit found for the project stops the pick; `brand apply` replaces a signature), and so does
- a job's style reference. `showtime signature` lists them and `showtime signature apply <project> <id|next|template>`
- swaps one; the MCP `new_project` tool takes `look`. The page gets a `<style id="st-look">` block of theme tokens;
- the four templates read three new ground tokens (`--ground-glow`, `--ground-grid`, `--ground-vignette`, 1 = as
- before); where a template's glow sits under text (short, launch) a signature's glow is lowered, and at launch's
- floor (its drifting key light is the end card's motion) muted and accent text are nudged instead, so every text
- keeps 4.8:1. Light signatures get dark caption ink with an outline in the ground. Cobalt (the widest face) is not
- offered on short. The short template's hook moved inside the vertical safe box with a margin (it sat on its edge;
- other display faces crossed it) and its end card centres in the safe box. The look history records a page's signature, and two pages on one theme in different signatures no
- longer count as a repeated theme. `references/color.md` section 9. `tests/test_signatures.py`: contrast of every
- signature, the seeded rotation away from recent picks and finished looks, the brand kit and --look winning, the
- command, and every signature passing `showtime check` (contrast, layout, phone size) on a sample project.
+ signatures, seven dark and five light (data takes the light ones), each a palette (every text colour at the contrast
+ rules: ink 7:1, muted and accent text 4.8:1, the ink on the accent 4.5:1, the product window through the brand kit's
+ legibility rules), a type pair from the shipped fonts, a motion feel (the theme's motion tokens) and a ground (how
+ much key light, grid and vignette the template paints). The pick is seeded by the folder name (`--look-seed`) and
+ avoids the signatures of the last six projects created on the machine (`<history>/picks.json`, local, off with the
+ look history) and the palettes and display faces of the last five finished videos. `new` prints the look and how to
+ change it; `--look <id>` names one and `--look template` keeps the template's own. A brand kit always wins (a kit
+ found for the project stops the pick; `brand apply` replaces a signature), and so does a job's style reference.
+ `showtime signature` lists them and `showtime signature apply <project> <id|next|template>` swaps one; the MCP
+ `new_project` tool takes `look`. The page gets a `<style id="st-look">` block of theme tokens; the four templates read
+ three new ground tokens (`--ground-glow`, `--ground-grid`, `--ground-vignette`, 1 = as before); where a template's
+ glow sits under text (short, launch) a signature's glow is lowered, and at launch's floor (its drifting key light is
+ the end card's motion) muted and accent text are nudged instead, so every text keeps 4.8:1. Light signatures get dark
+ caption ink with an outline in the ground. Cobalt (the widest face) is not offered on short. The short template's hook
+ moved inside the vertical safe box with a margin (it sat on its edge; other display faces crossed it) and its end card
+ centres in the safe box. The look history records a page's signature, and two pages on one theme in different
+ signatures no longer count as a repeated theme. `references/color.md` section 9. `tests/test_signatures.py`: contrast
+ of every signature, the seeded rotation away from recent picks and finished looks, the brand kit and --look winning,
+ the command, and every signature passing `showtime check` (contrast, layout, phone size) on a sample project.
- **Go all out: the showreel tone.** In a blind vote on "make a 15-second motion graphics showreel ... go all out",
plain Opus beat Opus with showtime: the winner had about 10 shots, a shader, particles and glitch type, while
showtime's defaults pushed restraint and long reading holds. A showreel, hype reel, "go all out" or "show off" brief
@@ -1332,13 +1464,13 @@ Behaviour changes to know about (all deliberate, all security or correctness):
`won't fix: <reason>` about them in `review/round-N/RESPONSE.md` (plain word matching). Quality mode: the
review stays pending; lean mode: `showtime qa` prints a WARN. Later-round critics answer each earlier
finding under `PREVIOUS` (`fixed:` / `not fixed:`).
- - **Four new qa warnings** (`st/qa/floor.py`, up to 20 sampled frames at delivery size, WARN only):
- `player_chrome` (a progress bar with control glyphs at both ends on a dark control overlay, in the same place on 2+ frames),
- `soft_footage` (edge sharpness under 0.75 on most detailed parts of half the frames: re-record at 2x device
- scale), `caption_boxes` (stacked caption boxes of different widths), `empty_borders` (a solid picture filling
- under 70 % of the frame inside flat borders for over 30 % of the video). The footage-only ones skip projects
- whose page plays no `<video>`. On the clip above, qa now warns on three of the four; the owner-approved
- re-cut and every shipped example stay clean.
+ - **Four new qa warnings** (`st/qa/floor.py`, up to 20 sampled frames at delivery size, WARN only): `player_chrome` (a
+ progress bar with control glyphs at both ends on a dark control overlay, in the same place on 2+ frames),
+ `soft_footage` (edge sharpness under 0.75 on most detailed parts of half the frames: re-record at 2x device scale),
+ `caption_boxes` (stacked caption boxes of different widths), `empty_borders` (a solid picture filling under 70 % of
+ the frame inside flat borders for over 30 % of the video). The footage-only ones skip projects whose page plays no
+ `<video>`. On the clip above, qa now warns on three of the four; the owner-approved re-cut and every shipped example
+ stay clean.
## 0.3.1 (2026-09-30)
@@ -1380,15 +1512,18 @@ Behaviour changes to know about (all deliberate, all security or correctness):
`showtime reference`, but its brief said to use your own colours (the run switched to greens), merged the reference's
0.5 s word-per-beat cuts into one 3.7 s shot and called its colour-panel wipes `push`/`whip-pan`, gave no layout or
sound build (the run chose small body text and an acoustic-folk bed), and `short_text` pushed the beat words to 1 s.
- Now `showtime reference` keeps beat cuts separate, names colour-panel wipes (colour, direction, length), samples
- the palette (ground, ink, accent, flat or not), measures alignment, margin and type sizes, and the sound's build
- (kick on the beats, off-beat tick, last hit, silence at the end); the brief says to carry the style over (its
- colours included, unless a brand kit or the user says otherwise) and never the content, and writes `style.css`.
+ Now `showtime reference` keeps beat cuts separate, names colour-panel wipes (colour, direction, length), samples the
+ palette (ground, ink, accent, flat or not), measures alignment, margin and type sizes, and the sound's build (kick on
+ the beats, off-beat tick, last hit, silence at the end); the brief says to carry the style over (its colours included,
+ unless a brand kit or the user says otherwise) and never the content, and writes `style.css`.
`showtime new <template> --job <job>` links that file last and sets the background, so template and theme defaults
yield (`--no-reference-style` skips it). The variety guard treats repeats that follow the job's style reference as
- intended (a note, no alternatives). `showtime check` reads a word-per-beat run as one line (`beat_words` note)
- when its words arrive no faster than 3 per second, and large text in the reference's own colour pair at 3:1 or more (WCAG large text) is a `low_contrast` note instead of an error when `reference-style.css` is linked. Type sizes are now measured from the ink of each line (cap heights; the t10 reference reads 385 / 200 / 85 / 65 / 50 px, the drawn sizes). Route: a router row in SKILL.md, the `reference` Essentials,
- and a line in the launch and social-short workflows.
+ intended (a note, no alternatives). `showtime check` reads a word-per-beat run as one line (`beat_words` note) when
+ its words arrive no faster than 3 per second, and large text in the reference's own colour pair at 3:1 or more (WCAG
+ large text) is a `low_contrast` note instead of an error when `reference-style.css` is linked. Type sizes are now
+ measured from the ink of each line (cap heights; the t10 reference reads 385 / 200 / 85 / 65 / 50 px, the drawn
+ sizes). Route: a router row in SKILL.md, the `reference` Essentials, and a line in the launch and social-short
+ workflows.
- **The reference as a spec, and `showtime reference diff`.** reference.md/reference.json now carry a spec in frames
(every scene change and its kind, shot lengths, element moves with length and easing from the frame-difference
curve, palette roles, layout and type sizes, tempo and every sound hit) with KEEP and CHANGE lists.
@@ -1449,40 +1584,42 @@ Behaviour changes to know about (all deliberate, all security or correctness):
earlier rounds' cells and runs second runs as their own cells, and `round_report.py`, which adds per-run stream
metrics (cost, tokens, calls, images in context, largest context, tool text, full renders, receipt), an isolation
check for runs that touch another showtime folder, and the 0.3.0 release gates as PASS / FAIL / PENDING.
-- **Manim templates pass `manim check` and `qa`.** A fresh `manim new --template example` opened on 0.33 s of black and had
- an 8 s still stretch (check: 2 errors, 4 warnings); it now passes check with 0 errors and 0 warnings in 16:9, 9:16, 1:1
- and 4:5, and its voiced final passes qa with 0 fails and 0 warnings. The cause of the black opening was the kit:
- `beat()` waited out the voice's lead-in before the scene had added anything, so `beat("hook"); add(hook)` still opened
- on an empty frame; on an empty scene `beat()` now holds that lead-in on whatever is add()ed next. The example keeps its
- story and colours with bigger motion on every word (each spoken number drops into the sum over a large running total,
- copies of each term fly down and become its band of tiles, the four terms are boxed as braces read 4 by 4), and its
- line ids are no longer spoken words (`tiling`, `closing`). The pattern templates open on their title at t=0;
- `equation` uses a larger walkthrough (`equation_walkthrough(font_size=)`) and a slow camera push, `graph` fills the area
- under the curve as it is traced (`graph_build(area=True)`), `refine` sits under its title. check's black-frame fix states
- qa's rule (a frame is black only when nothing visible is on it). `tests/test_manim_templates.py`.
-
-- **`manim check` agrees with `qa`.** After its dry run, check renders the draft (the same 480p15 scenes `manim render` caches) and
- runs qa's black and frozen-frame detectors on it with qa's thresholds. Manim's near-black ground with sparse content
- (`black_segment`) and a small `Indicate` on an equation (`frozen`) are now reported before the full render, each with a fix
- (`"light": true`, a bigger visible change); a hold the dry run already named is not repeated. `--no-draft` skips the pass.
- `references/manim.md` points to section 11 for integration (it said 9).
-- **Receipts.** Every job ends with `receipt.md`, `receipt.json` (stable, schema 1) and one line in `share.txt`:
- the request as typed, the assumptions, review rounds, full vs partial renders, the images showtime made for looking,
- wall time from job start to final, and tokens and cost when the host's session log is named. Anything unknown says
- "not reported by this agent"; nothing is estimated. `showtime receipt [job]` regenerates it; `qa` keeps it current,
- `job note --stage deliver`, `deliver exports` and the MCP `receipt` tool finish it. Claude Code: the plugin's Stop hook
- (or `--transcript FILE`) sums the current session's token counts (numbers only, never text) and prices them at
+- **Manim templates pass `manim check` and `qa`.** A fresh `manim new --template example` opened on 0.33 s of black and
+ had an 8 s still stretch (check: 2 errors, 4 warnings); it now passes check with 0 errors and 0 warnings in 16:9,
+ 9:16, 1:1 and 4:5, and its voiced final passes qa with 0 fails and 0 warnings. The cause of the black opening was the
+ kit: `beat()` waited out the voice's lead-in before the scene had added anything, so `beat("hook"); add(hook)` still
+ opened on an empty frame; on an empty scene `beat()` now holds that lead-in on whatever is add()ed next. The example
+ keeps its story and colours with bigger motion on every word (each spoken number drops into the sum over a large
+ running total, copies of each term fly down and become its band of tiles, the four terms are boxed as braces read 4 by
+ 4), and its line ids are no longer spoken words (`tiling`, `closing`). The pattern templates open on their title at
+ t=0; `equation` uses a larger walkthrough (`equation_walkthrough(font_size=)`) and a slow camera push, `graph` fills
+ the area under the curve as it is traced (`graph_build(area=True)`), `refine` sits under its title. check's
+ black-frame fix states qa's rule (a frame is black only when nothing visible is on it).
+ `tests/test_manim_templates.py`.
+
+- **`manim check` agrees with `qa`.** After its dry run, check renders the draft (the same 480p15 scenes `manim render`
+ caches) and runs qa's black and frozen-frame detectors on it with qa's thresholds. Manim's near-black ground with
+ sparse content (`black_segment`) and a small `Indicate` on an equation (`frozen`) are now reported before the full
+ render, each with a fix (`"light": true`, a bigger visible change); a hold the dry run already named is not repeated.
+ `--no-draft` skips the pass. `references/manim.md` points to section 11 for integration (it said 9).
+- **Receipts.** Every job ends with `receipt.md`, `receipt.json` (stable, schema 1) and one line in `share.txt`: the
+ request as typed, the assumptions, review rounds, full vs partial renders, the images showtime made for looking, wall
+ time from job start to final, and tokens and cost when the host's session log is named. Anything unknown says "not
+ reported by this agent"; nothing is estimated. `showtime receipt [job]` regenerates it; `qa` keeps it current,
+ `job note --stage deliver`, `deliver exports` and the MCP `receipt` tool finish it. Claude Code: the plugin's Stop
+ hook (or `--transcript FILE`) sums the current session's token counts (numbers only, never text) and prices them at
dated API list prices, labelled API-equivalent; Codex gives tokens only. `job init --request` keeps the user's words
verbatim, and partial renders (`render --from/--to`) are now recorded in the ledger. Format: `references/receipt.md`.
-- **Phone check.** The audience complaint about agent-made video (text moves too fast to read and is too small on a phone) is now one
- named check. `showtime check` ends with `phone check: PASS` or `FAIL - <items with timestamps>` and writes a `phone` block to
- `report.json`; `showtime qa` prints the same line, quoting that report (PARTIAL when there is none) and adding the caption
- sidecar's line length and reading speed. It joins what already existed: reading time (`short_text`, now per language: 17
- characters/s and 3 words/s, Japanese 4, Chinese 9, Korean 12 characters/s, in `runtime/thresholds.json`), type size (`tiny_text`, now
- in points at a 390 pt wide phone, with a minimum per aspect: 16:9 5 pt, 1:1 10, 4:5 11, 9:16 15; canvas text and captions are judged
- too, and small text is judged over its whole life, not only the sample frames) and the platform UI zones (`safe_zone`, `edge_margin`,
- `control_strip`). New qa rules `phone_size`, `phone_reading`, `phone_zone` (WARN) and `phone_unverified` (INFO). Numbers, sources and
- the calibration on the shipped examples: `references/qa.md`, "Phone check".
+- **Phone check.** The audience complaint about agent-made video (text moves too fast to read and is too small on a
+ phone) is now one named check. `showtime check` ends with `phone check: PASS` or `FAIL - <items with timestamps>` and
+ writes a `phone` block to `report.json`; `showtime qa` prints the same line, quoting that report (PARTIAL when there
+ is none) and adding the caption sidecar's line length and reading speed. It joins what already existed: reading time
+ (`short_text`, now per language: 17 characters/s and 3 words/s, Japanese 4, Chinese 9, Korean 12 characters/s, in
+ `runtime/thresholds.json`), type size (`tiny_text`, now in points at a 390 pt wide phone, with a minimum per aspect:
+ 16:9 5 pt, 1:1 10, 4:5 11, 9:16 15; canvas text and captions are judged too, and small text is judged over its whole
+ life, not only the sample frames) and the platform UI zones (`safe_zone`, `edge_margin`, `control_strip`). New qa
+ rules `phone_size`, `phone_reading`, `phone_zone` (WARN) and `phone_unverified` (INFO). Numbers, sources and the
+ calibration on the shipped examples: `references/qa.md`, "Phone check".
- **Pairwise review.** A model reviewer's absolute score is noisy; its preference between two versions is
steadier, and only when it survives swapping the order. `showtime review-pack <job> --against best` (or
`round-N`, or an older file) pairs the latest render with the best so far as a blind X/Y (random; the key
@@ -1494,9 +1631,9 @@ Behaviour changes to know about (all deliberate, all security or correctness):
`pairwise_summary.json` adds `both_orders`: the arm that won a pair with either arm shown first.
### Lean mode: looks out of the main context, check before render, brief output
-Measured in the 0.2.0 benchmark streams: showtime jobs cost 1.4-4.4x plain Opus on five of six tasks, largely because every
-image opened (2000 px sheets, 1080p stills) and every long tool output stays in the agent's context and is paid for
-on each later call, and runs took more calls (51 vs 13 on the launch task). Nothing was removed; the full output and
+Measured in the 0.2.0 benchmark streams: showtime jobs cost 1.4-4.4x plain Opus on five of six tasks, largely because
+every image opened (2000 px sheets, 1080p stills) and every long tool output stays in the agent's context and is paid
+for on each later call, and runs took more calls (51 vs 13 on the launch task). Nothing was removed; the full output and
the full studio are one flag or one sentence away.
- **`showtime look <project | video | job>`**: one composite of the key frames (the opening frame, each scene's
@@ -1554,7 +1691,15 @@ the full studio are one flag or one sentence away.
share.txt (render keeps it), and `showtime qa` fails a render that copies the reference (`reference_copy`:
sampled-frame SSIM and difference hashes plus cut-rhythm similarity; thresholds in
`references/reference.md`).
-- **`showtime adopt <folder | page | script>`**: a video someone already wrote as a function of time gets showtime's checks, sound, captions, qa, HTML export and review without a rewrite. It detects the contract (an HTML page with `seek`/`__seek`/`render`/`draw(t)`/`setTime(t)`, a page animated only by CSS, Web Animations or requestAnimationFrame on the virtual clock, a Python frame function returning Pillow/numpy/bytes, or a Python script whose own main writes the video) from the page, its local scripts and the render driver next to it, copies the folder (the originals are never changed), and writes a normal project around it. It then checks determinism (each sampled frame captured twice, in two orders) and runs `showtime check`. Every problem is printed as what/why/fix (`needs_setup`, `no_duration`, `outside_ref`, ...). Python runs in a separate process on the copy, with sockets to other machines refused and a time limit. `--refresh` re-adopts after the original changes. `references/adopt.md`.
+- **`showtime adopt <folder | page | script>`**: a video someone already wrote as a function of time gets showtime's
+ checks, sound, captions, qa, HTML export and review without a rewrite. It detects the contract (an HTML page with
+ `seek`/`__seek`/`render`/`draw(t)`/`setTime(t)`, a page animated only by CSS, Web Animations or requestAnimationFrame
+ on the virtual clock, a Python frame function returning Pillow/numpy/bytes, or a Python script whose own main writes
+ the video) from the page, its local scripts and the render driver next to it, copies the folder (the originals are
+ never changed), and writes a normal project around it. It then checks determinism (each sampled frame captured twice,
+ in two orders) and runs `showtime check`. Every problem is printed as what/why/fix (`needs_setup`, `no_duration`,
+ `outside_ref`, ...). Python runs in a separate process on the copy, with sockets to other machines refused and a time
+ limit. `--refresh` re-adopts after the original changes. `references/adopt.md`.
- **Brand first for launches.** `showtime brand capture <repo|url> --job <job>` captures the product before the
storyboard in one step: the palette with roles (the rendered site's ground, ink and accent win over the repo's
CSS), fonts, logo, the wordmark as the site sets it, the code-block look, the product's copy verbatim with
@@ -1609,13 +1754,13 @@ the full studio are one flag or one sentence away.
## 0.2.0: every coding agent, a lighter first run, a real music catalog
-showtime is now a local video studio for your coding agent, not only for Claude Code: describe a video, your
-agent directs, your machine renders. The same repository installs in Claude Code, Codex, Cursor, Devin and OpenCode
-(each made a real test video) and is packaged for Copilot, Gemini CLI, Antigravity, Cline, Kilo Code, Kiro, Zed, Goose,
-Amp, Factory Droid and Qwen Code. The first run fell from about 3 GB (0.1's own `setup --estimate`: 1.3 GB of downloads plus 1.7 GB of
-packages) to about 770 MB on Linux x64 (`setup --plan`; about 560 to 610 MB on macOS and Windows); nothing was
-removed, the rest is fetched the first time a video needs it. Music now comes from a catalog of 249 produced tracks with the credit written for
-you, and Apple Silicon, Linux arm64 and Windows on Arm run end to end in CI.
+showtime is now a local video studio for your coding agent, not only for Claude Code: describe a video, your agent
+directs, your machine renders. The same repository installs in Claude Code, Codex, Cursor, Devin and OpenCode (each made
+a real test video) and is packaged for Copilot, Gemini CLI, Antigravity, Cline, Kilo Code, Kiro, Zed, Goose, Amp,
+Factory Droid and Qwen Code. The first run fell from about 3 GB (0.1's own `setup --estimate`: 1.3 GB of downloads plus
+1.7 GB of packages) to about 770 MB on Linux x64 (`setup --plan`; about 560 to 610 MB on macOS and Windows); nothing was
+removed, the rest is fetched the first time a video needs it. Music now comes from a catalog of 249 produced tracks with
+the credit written for you, and Apple Silicon, Linux arm64 and Windows on Arm run end to end in CI.
Highlights (details in the entries below):
@@ -1953,12 +2098,12 @@ Highlights (details in the entries below):
### Added: a companion site, a visual crew, and diagrams that explain
-- `site/`: a static companion site built by `python3 site/build.py` (landing page with the hero film,
- a gallery that plays every example with filters by use case, one page per example with its HTML
- video embedded, the crew, and every guide in `references/` as a page with a sidebar and search).
- No framework, no trackers, fonts served from the site. The gallery previews each example on hover
- with a silent 4-second clip cut at build time (`site/content/previews.json`). `.github/workflows/pages.yml` builds it and
- downloads the example videos from the media release at deploy time, since they are not in git.
+- `site/`: a static companion site built by `python3 site/build.py` (landing page with the hero film, a gallery that
+ plays every example with filters by use case, one page per example with its HTML video embedded, the crew, and every
+ guide in `references/` as a page with a sidebar and search). No framework, no trackers, fonts served from the site.
+ The gallery previews each example on hover with a silent 4-second clip cut at build time
+ (`site/content/previews.json`). `.github/workflows/pages.yml` builds it and downloads the example videos from the
+ media release at deploy time, since they are not in git.
- README: the crew as an illustrated cast of ten (all optional, said so on the card) and a diagram of
who hands what to whom; diagrams for the pipeline, what runs where, studio mode, the anatomy of an
HTML video and the output formats, each in light and dark and in a narrow layout for phones; the
diff --git a/README.md b/README.md
index 40fbd5e..f74d439 100644
--- a/README.md
+++ b/README.md
@@ -107,6 +107,17 @@ languages or what leaves your machine: the [FAQ](docs/faq.md). Something went wr
> quality (the default) has a critic review every finished video; lean skips the critic unless the video is going
> to be published. Say **"no crew"** to keep the whole job in one session.
+**What's new in 0.4.6** (the list is [below](#new-in-046), and [What's new](docs/whats-new.md) has a short
+paragraph for each):
+
+- **`check` reads the text a page draws on its own canvas.** Text outside the phone's safe box, text too small to read
+ and text over other text are found between its samples and on any canvas, not only the film API's.
+- **X-ray on a phone and in sync.** At 9:16 the sound strip and the part labels sit where a phone shows them, a new
+ 16:9 project passes its own check, and with `"xray".offset_frames` the strip and the piano, drums and guitar follow
+ the recording's clock.
+- **Fixes.** `export html --interactive` packs a page's own fonts, `xray verify` reads the marker on a draft render,
+ installed files match the repository byte for byte, and `setup --home` brings its own ffmpeg.
+
**What's new in 0.4.5** (the list is [below](#new-in-045), and [What's new](docs/whats-new.md) has a short
paragraph for each):
@@ -388,8 +399,8 @@ setup:
is the same server from npm ([@faviovazquez/showtime-mcp](https://www.npmjs.com/package/@faviovazquez/showtime-mcp),
also listed in the [MCP Registry](https://registry.modelcontextprotocol.io/v0.1/servers?search=io.github.FavioVazquez/showtime)
as `io.github.FavioVazquez/showtime` and on [Smithery](https://smithery.ai/servers/favio-vazquezp/showtime)), and
-[`showtime-0.4.5.mcpb`](https://github.com/FavioVazquez/showtime/releases/download/v0.4.5/showtime-0.4.5.mcpb) from
-the v0.4.5 release opens in Claude Desktop with a double click. Setup still runs once on your machine: the
+[`showtime-0.4.6.mcpb`](https://github.com/FavioVazquez/showtime/releases/download/v0.4.6/showtime-0.4.6.mcpb) from
+the v0.4.6 release opens in Claude Desktop with a double click. Setup still runs once on your machine: the
models and tools never travel inside a package. Long tools answer with a task id after about 20 seconds when a
client stops calls early; the `status` tool reports progress and the result. Besides the tools that mirror the commands,
`guide` reads a reference by the piece and `receipt` writes a job's receipt (tokens and cost are "not reported by this
@@ -969,6 +980,49 @@ detectors on it, so a near-black scene or a barely visible change is reported be
<img alt="" src="assets/readme/divider-light.svg" width="100%">
</picture>
+## New in 0.4.6
+
+[What's new](docs/whats-new.md) has a short paragraph for each.
+
+**`check`**
+
+- **Canvas text outside the safe box.** At 9:16, every step of the dense timeline compares each text a page draws on
+ its own canvas with the safe box (x 64-916, y 220-1440 at 1080x1920): one `safe_zone` warning per text, with its span.
+- **Canvas text size.** Raw `fillText`/`strokeText` now feeds the `tiny_text` rule and the phone check, as DOM text and
+ `F.text` already did.
+- **Text over text.** Every text a canvas paints and the DOM's are compared on the whole timeline: a pair that overlaps
+ on two steps in a row is a `text_overlap` warning with when it starts and ends. Text layered on purpose can say so
+ (`F.text(..., {layer: true})`, `F.layer`, `ST.layer`).
+- **A probe that did not run is a warning** (`cut_probe_failed`, `webgpu_probe_failed`), so such a check never reads as
+ clean and `check --strict` fails on it.
+
+**X-ray**
+
+- **9:16.** The sound strip sits above the counters inside the safe box, and the part labels are 44 px in a column at
+ the safe box's edge, with the drawing between the columns. The 9:16 layout change leaves 16:9, 4:5 and 1:1 as
+ they were. A project made with 0.4.5 keeps its copy of the template; `showtime new xray` gets the new layout.
+- **16:9.** A new project passes its own check, and the strip's label is 26 px and fits a long mechanism word.
+- **`"xray".offset_frames`.** The sound strip, `track_until` and the piano, drums and guitar follow the recording's
+ clock (`k.rt`, `k.frameAt(t)` in the drawing kit).
+- **`xray verify`** reads the sync marker on a `--preview` or `--scale` render; the receipt says what "the original" is
+ for a film made from a rendering of data.
+- **`export html --interactive`** packs a page's own fonts, and `export html` run from inside a job writes into that job
+ ([xray](skills/showtime/references/workflows/xray.md)).
+
+**Fixes**
+
+- **Files as installed.** The repository stores every file exactly as it is installed (`.gitattributes` `* -text`,
+ Windows launchers with CRLF), checked by `scripts/check_release.py`.
+- **`setup --home X`** installs ffmpeg into X when a default install exists.
+- **Living diagrams.** Space or Enter on a focused control no longer also fires the scene's key.
+- **The embed element** takes a `file:` address only on a page opened from disk.
+- **`showtime assets icon`** suggests the right name at once for a misspelled one.
+
+<picture>
+ <source media="(prefers-color-scheme: dark)" srcset="assets/readme/divider-dark.svg">
+ <img alt="" src="assets/readme/divider-light.svg" width="100%">
+</picture>
+
## New in 0.4.5
[What's new](docs/whats-new.md) has a short paragraph for each.
diff --git a/benchmarks/harness/common.py b/benchmarks/harness/common.py
index 6a8b169..d08f99a 100755
--- a/benchmarks/harness/common.py
+++ b/benchmarks/harness/common.py
@@ -160,7 +160,11 @@ def load_arms(only: Optional[List[str]] = None) -> Dict:
# ---------------------------------------------------------------- misc
def opaque(name: str, n: int = 8) -> str:
- return "a" + hashlib.sha1(name.encode()).hexdigest()[:n]
+ try: # a label, not security: FIPS builds refuse a plain sha1
+ h = hashlib.sha1(name.encode(), usedforsecurity=False)
+ except TypeError: # Python 3.8 has no usedforsecurity
+ h = hashlib.sha1(name.encode())
+ return "a" + h.hexdigest()[:n]
def now_iso() -> str:
diff --git a/docs/agents.md b/docs/agents.md
index e86adc9..e1ab616 100644
--- a/docs/agents.md
+++ b/docs/agents.md
@@ -317,7 +317,7 @@ Any client that starts local (stdio) servers can use showtime's MCP server on it
([@faviovazquez/showtime-mcp](https://www.npmjs.com/package/@faviovazquez/showtime-mcp), also in the MCP Registry as
`io.github.FavioVazquez/showtime`),
`{"command": "npx", "args": ["-y", "@faviovazquez/showtime-mcp"]}` (see
-[`packages/npm/README.md`](../packages/npm/README.md)), and [`showtime-0.4.5.mcpb`](https://github.com/FavioVazquez/showtime/releases/download/v0.4.5/showtime-0.4.5.mcpb) from the v0.4.5 release, which
+[`packages/npm/README.md`](../packages/npm/README.md)), and [`showtime-0.4.6.mcpb`](https://github.com/FavioVazquez/showtime/releases/download/v0.4.6/showtime-0.4.6.mcpb) from the v0.4.6 release, which
Claude Desktop opens with a double click. Setup still runs once on your machine, because the models and tools
never travel inside a package. Long tools answer with a task id after about
20 s when a client stops calls early; the `status` tool reports progress and the result.
diff --git a/docs/examples/showtime-release-video.yml b/docs/examples/showtime-release-video.yml
index 55a9ffc..4d46081 100644
--- a/docs/examples/showtime-release-video.yml
+++ b/docs/examples/showtime-release-video.yml
@@ -34,7 +34,7 @@ jobs:
- uses: actions/checkout@v7
- id: video
- uses: FavioVazquez/showtime/.github/actions/[email protected]
+ uses: FavioVazquez/showtime/.github/actions/[email protected]
with:
mode: release
# a published release: its tag, name and description come from the event; by hand: these
@@ -69,7 +69,7 @@ jobs:
# runs-on: ubuntu-24.04
# timeout-minutes: 30
# steps:
-# - uses: FavioVazquez/showtime/.github/actions/[email protected]
+# - uses: FavioVazquez/showtime/.github/actions/[email protected]
# with:
# upload: artifact
#
@@ -78,7 +78,7 @@ jobs:
# showtime.json), rendered on every push to main that changes it:
#
# - uses: actions/checkout@v7
-# - uses: FavioVazquez/showtime/.github/actions/[email protected]
+# - uses: FavioVazquez/showtime/.github/actions/[email protected]
# with:
# mode: project
# project: videos/launch
@@ -91,7 +91,7 @@ jobs:
#
# - uses: actions/checkout@v7
# - run: npm install -g @your-agent/cli
-# - uses: FavioVazquez/showtime/.github/actions/[email protected]
+# - uses: FavioVazquez/showtime/.github/actions/[email protected]
# env:
# YOUR_AGENT_API_KEY: ${{ secrets.YOUR_AGENT_API_KEY }}
# with:
diff --git a/docs/github-action.md b/docs/github-action.md
index 42fa4ab..f78a8f8 100644
--- a/docs/github-action.md
+++ b/docs/github-action.md
@@ -5,7 +5,7 @@ and no agent. It installs showtime on the runner, turns the notes into a project
`showtime qa` on the finished file, exports a single-file HTML video, and uploads the result.
```yaml
-- uses: FavioVazquez/showtime/.github/actions/[email protected]
+- uses: FavioVazquez/showtime/.github/actions/[email protected]
```
The complete workflow to copy is [`examples/showtime-release-video.yml`](examples/showtime-release-video.yml).
diff --git a/docs/whats-new.md b/docs/whats-new.md
index 09a42a0..96a3361 100644
--- a/docs/whats-new.md
+++ b/docs/whats-new.md
@@ -3,6 +3,66 @@
What each release changes for you, newest first, one sentence a feature. The
[changelog](../CHANGELOG.md) has every change and the reason for it.
+## 0.4.6
+
+### `check` reads the text a page draws on its own canvas
+
+`check` used to measure only the film API's text, at its sample times. Now every text a page paints on any canvas
+(`fillText`, `strokeText`) is followed on the whole timeline: text outside the 9:16 safe box (a `safe_zone` warning with
+its span), text too small for a phone (`tiny_text`), and text drawn over other text, canvas or DOM (`text_overlap`, with
+when it starts and ends). A counter whose number changes is one text. Text layered on purpose can say so with
+`F.text(..., {layer: true})`, `F.layer` or `ST.layer`. A probe that could not run (`cut_probe_failed`,
+`webgpu_probe_failed`) is now a warning, so such a check never reads as clean.
+
+### X-ray on a phone
+
+At 9:16 the X-ray template's sound strip sits above the counters inside the safe box, and the part labels are 44 px in
+a column at the safe box's edge, ordered so no two leaders cross; the drawing sits between the columns and never moves.
+The 9:16 layout change leaves 16:9, 4:5 and 1:1 as they were. A project made with 0.4.5 keeps its own copy of the
+template: start a new one with `showtime new xray` to get the layout. A new 16:9 project passes its own check, and the
+strip's label fits a long mechanism word.
+
+### X-ray in sync with an offset clip
+
+With `"xray".offset_frames` (the clip starts some frames into the film), the sound strip's ticks and caret,
+`track_until`, and the piano, drums and guitar mechanisms follow the recording's own clock. The drawing kit gives a
+mechanism `k.rt` and `k.frameAt(t)` for its own drawings.
+
+### X-ray tools
+
+`xray verify` reads the sync marker on a `--preview` or `--scale` render. The receipt says what "the original" is when
+the clip's sound is a rendering of data. `export html --interactive` packs the fonts a page names in its own `<style>`,
+and `export html` run from inside a job writes into that job. `xray import` refuses a JSON file with too many object
+keys, and a word in a `strength` column, before it does any work.
+
+### Small fixes
+
+Installed files match the repository byte for byte on every OS. `showtime setup --home X` installs ffmpeg into X even
+when a default install exists. Space or Enter on a focused control of a living diagram no longer also fires the scene's
+key. The X-ray embed element takes a `file:` address only on a page opened from disk. `showtime assets icon` suggests
+the right name at once for a misspelled one. A page address with a malformed `%` escape no longer stops the page
+runtime in preview.
+
+### What changes for you
+
+- `check --strict` fails when the first-frame-after-cut walk or the WebGPU probe could not run (it was info).
+- `check`, `qa --platform reels` and the phone check can report new `text_overlap`, `safe_zone` and `tiny_text`
+ warnings on an existing project that draws its own canvas text.
+- `<showtime-xray src="file:...">` on a web page shows the poster; a page opened from disk still loads the film.
+- `xray import` refuses a word in a `strength` column (on any row, the ones the time map drops too) and a JSON file
+ with more than 1,600,000 colons.
+- `export html --interactive` run from inside a job writes into that job, not a new `showtime-out/` folder.
+- `setup --home X` downloads its own ffmpeg into X instead of using the default install's.
+- Space or Enter on a focused control of a living diagram presses the control only.
+- The repository's files are checked out exactly as stored (`* -text`).
+
+### For contributors
+
+`scripts/check_release.py` now refuses a bullet repeated in the unreleased CHANGELOG section, a file name Windows
+reserves, a credential-shaped literal in a shipped file, a merge-conflict marker left in a file, a routing case that
+does not read its own guide, a workflow guide with no line in `references/index.md`, and a `.gitattributes` line git
+ignores.
+
## 0.4.5
### X-ray from data
diff --git a/gemini-extension.json b/gemini-extension.json
index fd9805a..2910e23 100644
--- a/gemini-extension.json
+++ b/gemini-extension.json
@@ -1,6 +1,6 @@
{
"name": "showtime",
- "version": "0.4.5",
+ "version": "0.4.6",
"description": "A local video studio for your coding agent. Describe a video. Your agent directs. Your machine renders. Motion graphics, voice-over, music, footage editing, captions and platform-ready exports, with no cloud AI services or API keys.",
"mcpServers": {
"showtime": {
diff --git a/packages/npm/package.json b/packages/npm/package.json
index 9427233..04e53b4 100644
--- a/packages/npm/package.json
+++ b/packages/npm/package.json
@@ -1,6 +1,6 @@
{
"name": "@faviovazquez/showtime-mcp",
- "version": "0.4.5",
+ "version": "0.4.6",
"mcpName": "io.github.FavioVazquez/showtime",
"description": "A local video studio for your coding agent: showtime's MCP server and command line. Describe a video. Your agent directs. Your machine renders.",
"license": "MIT",
diff --git a/plugin.json b/plugin.json
index 1a60db8..fd0507b 100644
--- a/plugin.json
+++ b/plugin.json
@@ -1,7 +1,7 @@
{
"$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
"name": "showtime",
- "version": "0.4.5",
+ "version": "0.4.6",
"description": "A local video studio for your coding agent. Describe a video. Your agent directs. Your machine renders. Motion graphics, voice-over, music, footage editing, captions and platform-ready exports, with no cloud AI services or API keys.",
"author": {
"name": "Favio Vazquez",
diff --git a/scripts/check_release.py b/scripts/check_release.py
index b838382..4273c1b 100755
--- a/scripts/check_release.py
+++ b/scripts/check_release.py
@@ -23,7 +23,9 @@ Checks:
routing every workflow guide (references/workflows/*.md) is the guide some eval case must read: a
`Read` grader in benchmarks/routing-eval/ or benchmarks/plugin-eval/ whose pattern matches its
path (one routing case per new feature; ROUTING_LEGACY lists the guides older than the rule),
- and every routing case's guide exists. Skipped where there is no benchmarks/routing-eval/
+ every routing case's guide exists (route-<topic> reads references/workflows/<topic>.md when
+ there is one), and every workflow guide has its line in references/index.md. Skipped where
+ there is no benchmarks/routing-eval/
links every relative link / `references/...` path in SKILL.md and references/ exists; no links
to documentation that moved (MOVED_URLS, e.g. the old Codex docs address)
commands every `showtime <cmd> [sub]` named in SKILL.md, references/ and agents/ exists in the CLI
@@ -39,6 +41,13 @@ Checks:
paths no machine-specific paths (a developer's home folder, temp folders) in shipped files
names no names of outside projects this repo must not mention (list kept encoded below)
conflicts a merge-conflict marker line (<<<<<<< , =======, >>>>>>> ) left in a tracked text file
+ changelog CHANGELOG.md's unreleased section has no bullet twice; warnings for two bullets with the same
+ bold lead and for lines over 120 characters
+ windows no tracked path with a name Windows refuses (CON, PRN, AUX, NUL, COM1-9, LPT1-9 with any
+ extension; reserved characters), and no test that writes a file by such a name (nul.csv)
+ secrets no credential-shaped literal (private key block, JSON web token, database URL with a password,
+ GitHub/AWS/Stripe/Slack/Google/sk-/registry/service keys) in any shipped non-binary file, fake ones included: a
+ mirror's push protection refuses the commit. Tests build them at run time from pieces
terms words CONTEXT.md says to avoid (warning only)
media committed videos under 20 MB, no render work folders, and large example media (over
10 MB, every .mov) listed in examples/MEDIA.json and ignored by git: they ship as release
@@ -529,23 +538,35 @@ def check_routing(f: Findings, evals: Optional[Path] = None, skill: Optional[Pat
if not (evals / ROUTING_EVAL).is_dir():
return
pats = []
+ broken = set() # cases with a pattern that is not a regex: reported once, for that
for case, pat, where in read_patterns(evals):
try:
pats.append((case, re.compile(pat), where))
except re.error as e:
+ broken.add(case)
f.add("routing", "error", "%s: the Read pattern %r is not a regex (%s)" % (case, pat, e), rel(where))
refs = sorted(p.relative_to(skill).as_posix() for p in (skill / "references").rglob("*.md"))
for case_dir in sorted(p for p in (evals / ROUTING_EVAL).iterdir() if (p / "prompt.md").is_file()):
mine = [rx for c, rx, _ in pats if c == case_dir.name]
+ # route-<topic> with a workflow guide of that name must read that guide: a pattern copied from another case
+ # (it names some guide that exists) would otherwise grade the wrong route
+ topic = case_dir.name[len("route-"):] if case_dir.name.startswith("route-") else ""
+ own = "references/workflows/%s.md" % topic
if not mine:
- f.add("routing", "error", "routing case %s has no Read grader naming the guide it must read"
- % case_dir.name, rel(case_dir))
+ if case_dir.name not in broken:
+ f.add("routing", "error", "routing case %s has no Read grader naming the guide it must read"
+ % case_dir.name, rel(case_dir))
elif not any(rx.search(r) for rx in mine for r in refs):
f.add("routing", "error", "routing case %s reads a guide that does not exist (no reference matches %s)"
% (case_dir.name, " or ".join(rx.pattern for rx in mine)), rel(case_dir))
+ elif topic and (skill / own).is_file() and not any(rx.search(own) for rx in mine):
+ f.add("routing", "error", "routing case %s does not read its own guide %s (its pattern matches %s)"
+ % (case_dir.name, own, ", ".join(r for r in refs if any(rx.search(r) for rx in mine))), rel(case_dir))
if not (case_dir / "graders" / "names-the-first-command.md").is_file():
f.add("routing", "error", "routing case %s has no names-the-first-command grader" % case_dir.name,
rel(case_dir))
+ index_md = skill / "references" / "index.md"
+ index = read(index_md) if index_md.is_file() else None
for wf in sorted((skill / "references" / "workflows").glob("*.md")):
topic, path = wf.stem, "references/workflows/" + wf.name
covered = any(rx.search(path) for _, rx, _ in pats)
@@ -554,6 +575,9 @@ def check_routing(f: Findings, evals: Optional[Path] = None, skill: Optional[Pat
"(one case per feature, see its README)" % (wf.name, ROUTING_EVAL, topic), rel(wf))
elif covered and topic in legacy:
f.add("routing", "warning", "%s now has a routing case: take it off ROUTING_LEGACY" % topic, rel(wf))
+ if index is not None and not re.search(r"workflows/%s(?![\w.-])" % re.escape(wf.name), index):
+ f.add("routing", "error", "workflow guide %s has no line in references/index.md: add it to its family there"
+ % wf.name, rel(wf))
# ---------------------------------------------------------------------------
@@ -841,8 +865,117 @@ def check_paths_and_names(f: Findings, files: Sequence[Path]) -> None:
f.add("names", "error", "file name mentions a banned project", rel(p))
-_CONFLICT_OPEN = re.compile(r"^(?:<<<<<<<|>>>>>>>) ", re.M)
-_CONFLICT_MID = re.compile(r"^=======$", re.M)
+CHANGELOG_WIDTH = 120
+
+
+def check_changelog(f: Findings, path: Optional[Path] = None) -> None:
+ """The unreleased section of CHANGELOG.md: no bullet twice (two PRs that each carried the same bullet, or a merge
+ that kept both sides), no top-level bullet whose bold lead repeats another's (warning: often an edited copy), and
+ lines within CHANGELOG_WIDTH characters (warning)."""
+ path = path or REPO / "CHANGELOG.md"
+ if not path.is_file():
+ return
+ lines = read(path).splitlines()
+ start = next((i for i, ln in enumerate(lines) if re.match(r"## \S+ \(unreleased\)\s*$", ln)), None)
+ if start is None:
+ return
+ end = next((i for i in range(start + 1, len(lines)) if lines[i].startswith("## ")), len(lines))
+ bullets: List[Tuple[int, str]] = [] # (1-based line, text with its continuation lines)
+ for i in range(start + 1, end):
+ ln = lines[i]
+ if len(ln) > CHANGELOG_WIDTH:
+ f.add("changelog", "warning", "line of %d characters in the unreleased section (wrap at %d)"
+ % (len(ln), CHANGELOG_WIDTH), "%s:%d" % (rel(path), i + 1))
+ if ln.startswith("- "):
+ bullets.append((i + 1, ln[2:]))
+ elif bullets and ln.startswith(" ") and ln.strip():
+ bullets[-1] = (bullets[-1][0], bullets[-1][1] + " " + ln.strip())
+ elif not ln.strip() or ln.startswith("#"):
+ bullets.append((0, "")) # a blank line or heading ends a bullet
+ seen: Dict[str, int] = {}
+ leads: Dict[str, int] = {}
+ for at, text in bullets:
+ if not at:
+ continue
+ key = " ".join(text.split())
+ if key in seen:
+ f.add("changelog", "error", "this bullet repeats the one at line %d (keep one)" % seen[key],
+ "%s:%d" % (rel(path), at))
+ continue
+ seen[key] = at
+ m = re.match(r"\*\*(.+?)\*\*", key)
+ lead = m.group(1).strip().rstrip(".:").lower() if m else ""
+ if lead and lead in leads:
+ f.add("changelog", "warning", "this bullet's lead repeats the one at line %d: one change, two entries?"
+ % leads[lead], "%s:%d" % (rel(path), at))
+ elif lead:
+ leads[lead] = at
+
+
+# Windows refuses these names with any extension (nul.csv is the device NUL), so a checkout or a test that writes one
+# fails there only: 0.4.5 lost two release CI rounds to a test fixture named nul.csv
+_WIN_FIXTURE = re.compile(r"(?:^|[/\\])(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.[A-Za-z0-9]+)+$", re.I)
+TEST_SOURCES = ("skills/showtime/tests/", "tests/")
+
+
+def _unquoted(literal: str) -> str:
+ """A string literal's text without its prefix and quotes (f'{d}/x.txt' -> {d}/x.txt), for what literal_eval refuses."""
+ return re.sub(r"""^[A-Za-z]*('{3}|"{3}|'|")|('{3}|"{3}|'|")$""", "", literal)
+
+
+def _test_strings(p: Path) -> List[Tuple[int, str]]:
+ """(line, value) of the string literals in a test file: Python by its tokenizer (comments are not strings; an
+ f-string's literal parts count), JavaScript by quoted strings outside // comments. Prose in a string or docstring
+ passes the rule because the reserved name must end the string, after its start, a / or a \\."""
+ text = read(p)
+ out: List[Tuple[int, str]] = []
+ if p.suffix == ".py":
+ import io
+ import tokenize
+ try:
+ fmid = getattr(tokenize, "FSTRING_MIDDLE", None) # Python 3.12+: an f-string's literal parts
+ for tok in tokenize.generate_tokens(io.StringIO(text).readline):
+ if tok.type == tokenize.STRING:
+ try:
+ val = ast.literal_eval(tok.string)
+ except (ValueError, SyntaxError): # an f-string before 3.12: its text, quotes off
+ val = _unquoted(tok.string)
+ if isinstance(val, str):
+ out.append((tok.start[0], val))
+ elif fmid is not None and tok.type == fmid:
+ out.append((tok.start[0], tok.string))
+ except (tokenize.TokenError, IndentationError, SyntaxError):
+ pass
+ return out
+ for i, ln in enumerate(text.splitlines(), 1):
+ code = re.sub(r"(^|\s)//.*$", "", ln)
+ out.extend((i, m.group(2)) for m in re.finditer(r"(['\"`])([^'\"`\n]*)\1", code))
+ return out
+
+
+def check_windows_names(f: Findings, files: Sequence[Path], paths: bool = True) -> None:
+ """No tracked path with a Windows-reserved name (CON, PRN, AUX, NUL, COM1-9, LPT1-9, with or without an extension)
+ or a character Windows refuses, and no file name a test builds from a string literal with a reserved stem.
+ paths=False leaves the tracked paths to the directory check when it runs too (one report per file)."""
+ for p in files:
+ r = rel(p)
+ for part in (r.split("/") if paths else []):
+ if part.lower().split(".", 1)[0] in WIN_RESERVED or any(c in WIN_BAD_CHARS for c in part) \
+ or part.endswith((".", " ")):
+ f.add("windows", "error", "name %r cannot be checked out on Windows" % part, r)
+ if r.startswith(TEST_SOURCES) and p.suffix in (".py", ".mjs", ".js"):
+ for line, val in _test_strings(p):
+ m = _WIN_FIXTURE.search(val.strip())
+ if m:
+ f.add("windows", "error", "a test names the file %r: %s is a device on Windows, so writing it "
+ "fails there (pick another name)" % (val.strip(), m.group(1).upper()), "%s:%d" % (r, line))
+
+
+# git writes "<<<<<<< ours" and ">>>>>>> theirs", but a marker with no label (a hand-made or tool-made conflict) is one
+# too. The check reads files as they are on disk (newline=""), so a CRLF file's marker lines end with \r: matched here
+# rather than relying on read()'s newline translation.
+_CONFLICT_OPEN = re.compile(r"^(?:<<<<<<<|>>>>>>>)(?: |\r?$)", re.M)
+_CONFLICT_MID = re.compile(r"^=======\r?$", re.M)
def check_conflict_markers(f: Findings, files: Sequence[Path]) -> None:
@@ -851,7 +984,8 @@ def check_conflict_markers(f: Findings, files: Sequence[Path]) -> None:
for p in files:
if not is_text(p):
continue
- text = read(p)
+ with open(str(p), encoding="utf-8", errors="replace", newline="") as fh: # as on disk: CRLF stays \r\n
+ text = fh.read()
if "<<<<<<<" not in text and ">>>>>>>" not in text:
continue
opens = list(_CONFLICT_OPEN.finditer(text))
@@ -861,6 +995,44 @@ def check_conflict_markers(f: Findings, files: Sequence[Path]) -> None:
f.add("conflicts", "error", "merge-conflict marker left in the file: %s" % m.group(0).strip(), "%s:%d" % (rel(p), _line(text, m.start())))
+# Credential shapes a mirror's push protection refuses. Tests that need one (the redactors, pr-video's masking) build it
+# at run time from pieces, so no shipped line holds it whole. AWS's documented example key (…EXAMPLE) is a known
+# placeholder and stays allowed. Some patterns are assembled from pieces so this file does not match itself.
+SECRET_SHAPES = [
+ ("a private key block", re.compile("-----BEGIN (?:[A-Z0-9]+ )*PRIVATE " + r"KEY(?: BLOCK)?-----")),
+ ("a JSON web token", re.compile(r"\beyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}")),
+ # a placeholder password (user:password@, :<password>@, :${PW}@, :****@) is documentation, not a credential; the
+ # user may be empty (redis://:pw@host)
+ ("a database URL with a password", re.compile(r"\b(?:postgres(?:ql)?|mysql|mariadb|mongodb(?:\+srv)?|rediss?|amqps?|"
+ r"mssql|sqlserver)://[^\s:/@'\"]*:(?!(?:password|passwd|pass|pw|secret|"
+ r"changeme|example|x+|\*+|<[^>@]*>|\$\{?\w+\}?|\{\w+\})@)[^\s@/'\"]+@")),
+ ("a GitHub token", re.compile(r"\b(?:gh[pousr]_[A-Za-z0-9]{36}|github_pat_[A-Za-z0-9_]{60,})")),
+ ("an AWS access key", re.compile(r"\b(?:AKIA|ASIA)(?![0-9A-Z]{9}EXAMPLE\b)[0-9A-Z]{16}\b")),
+ ("a Stripe key", re.compile(r"\b(?:[sr]k_" + r"(?:live|test)_[0-9A-Za-z]{20,}|whsec_[0-9A-Za-z]{24,})")),
+ ("a Slack token", re.compile(r"\b(?:xox[abposr]-[0-9A-Za-z-]{10,}|xapp-[0-9A-Za-z-]{20,})")),
+ ("a Google key", re.compile(r"\b(?:AIza[0-9A-Za-z_-]{35}\b|GOCSPX-[0-9A-Za-z_-]{28}|ya29\.[0-9A-Za-z_-]{30,})")),
+ ("an API key (sk-...)", re.compile(r"\bsk-(?:ant-|proj-)?[A-Za-z0-9_-]{32,}")),
+ ("a package registry token", re.compile(r"\b(?:npm_[A-Za-z0-9]{36}|pypi-AgE[A-Za-z0-9_-]{50,}|glpat-[A-Za-z0-9_-]{20}|"
+ r"hf_[A-Za-z0-9]{34})\b")),
+ ("a service API token", re.compile(r"\b(?:SG\.[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43}|shp(?:at|ss|ca|pa)_[a-fA-F0-9]{32}|"
+ r"do[opr]_v1_[a-f0-9]{64}|sq0[a-z]{3}-[A-Za-z0-9_-]{22,}|AC[a-f0-9]{32}\b)")),
+]
+
+
+def check_secrets(f: Findings, files: Sequence[Path]) -> None:
+ """No credential-shaped literal in a shipped file (fake ones too: a mirror's push protection cannot tell, and
+ refuses the commit). Every file that is not binary is read, whatever its extension (fixtures are .diff, .jsonl) and
+ size."""
+ for p in files:
+ if is_binary(p):
+ continue
+ for i, line in enumerate(read(p).splitlines(), 1):
+ for label, rx in SECRET_SHAPES:
+ if rx.search(line):
+ f.add("secrets", "error", "%s literal: build it at run time from pieces (\"gh\" + \"p_\" + ...)"
+ % label, "%s:%d" % (rel(p), i))
+
+
def avoid_terms() -> Dict[str, str]:
"""{avoid-word: preferred term} from the `backticked` words of CONTEXT.md `_Avoid_:` lines."""
ctx = REPO / "CONTEXT.md"
@@ -949,13 +1121,42 @@ _REWRITING_ATTRS = re.compile(r"^(?:-?filter\b.*|filter=.*|ident|-ident|working-
r"!?crlf(?:=.*)?|-crlf(?:=.*)?|export-ignore|-export-ignore|export-subst|-export-subst)$")
+# git's attribute names: letters, digits, - . _ and not starting with - (after an optional - or ! prefix), then =value
+_ATTR_TOKEN = re.compile(r"^[-!]?[._A-Za-z0-9][-._A-Za-z0-9]*(?:=.*)?$")
+_ATTR_BLANK = re.compile(r"[ \t\r\n]+") # the only separators git knows (not \xa0, \v ...)
+
+
+def attr_fields(line: str) -> Optional[Tuple[str, List[str]]]:
+ """(pattern, attributes) of a .gitattributes line the way git reads it, or None for a blank or comment line. A
+ pattern in double quotes runs to its closing quote (it may hold spaces: `"a b" text`)."""
+ s = line.lstrip(" \t\r\n")
+ if not s or s.startswith("#"):
+ return None
+ m = re.match(r'"(?:[^"\\]|\\.)*"', s) if s.startswith('"') else re.match(r"[^ \t\r\n]*", s)
+ if not m: # an unclosed quote: no pattern git can read, no attributes
+ return s, []
+ return m.group(0), [a for a in _ATTR_BLANK.split(s[m.end():]) if a]
+
+
+def git_ignored_attr(line: str) -> Optional[str]:
+ """The attribute token that makes git ignore this whole .gitattributes line, or None. A line holding any name git
+ refuses is skipped whole; .gitattributes has comments only on lines of their own, so `* -text # note` is such a
+ line (`#` is not a valid attribute name) and sets nothing (git check-attr: unspecified)."""
+ fields = attr_fields(line)
+ if not fields:
+ return None
+ return next((a for a in fields[1] if not _ATTR_TOKEN.match(a)), None)
+
+
def checkout_rewrites(line: str) -> List[str]:
"""The attributes on one .gitattributes line that change files at checkout (or archive): filter (LFS), ident,
working-tree-encoding, eol, text (set, auto, unspecified or re-enabled after `* -text`; only `-text` and `binary`
- leave bytes alone), the legacy crlf, export-ignore/-subst. A `#` starts a comment only at the line start or after
- whitespace."""
- parts = re.split(r"(?:^|\s)#", line, 1)[0].split()
- return [a for a in parts[1:] if _REWRITING_ATTRS.match(a) and a != "-text"] if len(parts) > 1 else []
+ leave bytes alone), the legacy crlf, export-ignore/-subst. A comment line, or a line git ignores whole
+ (git_ignored_attr), rewrites nothing."""
+ fields = attr_fields(line)
+ if not fields or git_ignored_attr(line):
+ return []
+ return [a for a in fields[1] if _REWRITING_ATTRS.match(a) and a != "-text"]
def check_checkout_bytes(f: Findings, files: Sequence[Path]) -> None:
@@ -963,12 +1164,17 @@ def check_checkout_bytes(f: Findings, files: Sequence[Path]) -> None:
`* -text`, the Windows shims carry CRLF in their bytes and the POSIX scripts carry no CR."""
ga = REPO / ".gitattributes"
attr_files = [ga] + [p for p in files if p.name == ".gitattributes" and p != ga]
- if not ga.is_file() or not re.search(r"(?m)^\*[ \t]+-text[ \t]*(?:[ \t]#.*)?$", read(ga)):
+ # `* -text` alone on its line: with anything after it that is not an attribute (a `# note`), git ignores the line
+ if not ga.is_file() or not re.search(r"(?m)^\*[ \t]+-text[ \t]*$", read(ga)):
f.add("directory", "error", "the root .gitattributes needs a `* -text` line (store files byte-exact)", ".gitattributes")
for g in attr_files:
if not g.is_file():
continue
for i, line in enumerate(read(g).splitlines(), 1):
+ bad_name = git_ignored_attr(line)
+ if bad_name:
+ f.add("directory", "error", "git ignores this whole line (%r is not an attribute name; .gitattributes has no "
+ "comments after a pattern): %s" % (bad_name, line.strip()), "%s:%d" % (rel(g), i))
for bad in checkout_rewrites(line):
f.add("directory", "error", "%s rewrites files at checkout (store them byte-exact): %s" % (bad, line.strip()), "%s:%d" % (rel(g), i))
for p in files:
@@ -1121,7 +1327,8 @@ def check_mirror(f: Findings, assets: Optional[List[Tuple[str, str, Optional[int
def default_checks() -> List[str]:
- default = ["versions", "skill", "routing", "links", "commands", "agents", "guides", "paths", "names", "conflicts", "terms", "media"]
+ default = ["versions", "skill", "routing", "links", "commands", "agents", "guides", "paths", "names", "conflicts", "secrets",
+ "terms", "media", "changelog", "windows"]
if not (REPO / "examples").is_dir():
default.append("directory") # the plugin repository (the examples have their own)
return default
@@ -1150,6 +1357,12 @@ def run_checks(fix: bool = False, set_version: Optional[str] = None,
check_paths_and_names(f, shipped_files())
if "conflicts" in want:
check_conflict_markers(f, shipped_files())
+ if "changelog" in want:
+ check_changelog(f)
+ if "windows" in want:
+ check_windows_names(f, shipped_files(), paths="directory" not in want)
+ if "secrets" in want:
+ check_secrets(f, shipped_files())
if "terms" in want:
check_terms(f)
if "media" in want:
@@ -1261,8 +1474,8 @@ def main(argv: Optional[Sequence[str]] = None) -> int:
" python scripts/check_release.py --check --only commands,links")
ap.add_argument("--check", action="store_true", help="report only; never modify files")
ap.add_argument("--set-version", metavar="X.Y.Z", help="bump every version field to X.Y.Z")
- ap.add_argument("--only", help="comma list: versions,skill,routing,links,commands,agents,guides,paths,names,conflicts,terms,media,"
- "directory,mirror")
+ ap.add_argument("--only", help="comma list: versions,skill,routing,links,commands,agents,guides,paths,names,conflicts,secrets,terms,"
+ "media,changelog,windows,directory,mirror")
ap.add_argument("--mirror", action="store_true", help="also HEAD every model and audio mirror asset on its release "
"(network; run before a release)")
ap.add_argument("--json", action="store_true", help="print findings as JSON")
diff --git a/server.json b/server.json
index 0c6876d..3490d4e 100644
--- a/server.json
+++ b/server.json
@@ -3,7 +3,7 @@
"name": "io.github.FavioVazquez/showtime",
"title": "showtime",
"description": "Local video studio for your coding agent: scenes, voice, music and captions, on your machine.",
- "version": "0.4.5",
+ "version": "0.4.6",
"websiteUrl": "https://faviovazquez.github.io/showtime/",
"repository": {
"url": "https://github.com/FavioVazquez/showtime",
@@ -26,7 +26,7 @@
"registryType": "npm",
"registryBaseUrl": "https://registry.npmjs.org",
"identifier": "@faviovazquez/showtime-mcp",
- "version": "0.4.5",
+ "version": "0.4.6",
"runtimeHint": "npx",
"transport": {
"type": "stdio"
diff --git a/skills/showtime/lib/st/__init__.py b/skills/showtime/lib/st/__init__.py
index 362e298..932c91f 100644
--- a/skills/showtime/lib/st/__init__.py
+++ b/skills/showtime/lib/st/__init__.py
@@ -7,7 +7,7 @@ inside the showtime virtualenv (~/.showtime/venv, Python 3.12).
"""
import os
-__version__ = "0.4.5"
+__version__ = "0.4.6"
# onnxruntime (Kokoro, alignment, stem separation, rembg) ships Microsoft's telemetry client on Linux
# and starts it at import; this turns it off for every process that imports st, and for its children.
diff --git a/skills/showtime/lib/st/assets/icons.py b/skills/showtime/lib/st/assets/icons.py
index c919caf..a9c4256 100644
--- a/skills/showtime/lib/st/assets/icons.py
+++ b/skills/showtime/lib/st/assets/icons.py
@@ -99,6 +99,13 @@ def _rel_path(set_name: str, name: str, variant: Optional[str]) -> str:
raise AssertionError(set_name)
+def _pkg_version(d: Path) -> Optional[str]:
+ try:
+ return str(json.loads((d / "package.json").read_text(encoding="utf-8")).get("version"))
+ except (OSError, ValueError, AttributeError):
+ return None
+
+
def _names_local(set_name: str, variant: Optional[str] = None) -> Optional[List[str]]:
s = SETS[set_name]
if not _seeded(set_name):
@@ -106,6 +113,8 @@ def _names_local(set_name: str, variant: Optional[str] = None) -> Optional[List[
d = _pkg_dir(s["pkg"])
if not d.is_dir():
return None
+ if d == _node_pkg_dir(s["pkg"]) and _pkg_version(d) != s["version"]:
+ return None # an older install's package is not the pinned version's listing
rel = _rel_path(set_name, "__X__", variant)
folder = d / Path(rel).parent
if not folder.is_dir():
@@ -114,10 +123,10 @@ def _names_local(set_name: str, variant: Optional[str] = None) -> Optional[List[
return sorted(p.name[:-len(suffix)] for p in folder.iterdir() if p.name.endswith(suffix))
-def _names_cdn(set_name: str, variant: Optional[str] = None) -> List[str]:
+def _names_cdn(set_name: str, variant: Optional[str] = None, timeout: float = 30, retries: int = 2) -> List[str]:
s = SETS[set_name]
data = net.get_json("https://data.jsdelivr.com/v1/packages/npm/%s@%s?structure=flat" % (s["pkg"], s["version"]),
- ttl=30 * 86400)
+ ttl=30 * 86400, timeout=timeout, retries=retries)
rel = _rel_path(set_name, "__X__", variant)
prefix = "/" + str(Path(rel).parent).replace("\\", "/") + "/"
suffix = Path(rel).name.replace("__X__", "")
@@ -129,10 +138,13 @@ def _names_cdn(set_name: str, variant: Optional[str] = None) -> List[str]:
return sorted(out)
-def names(set_name: str, variant: Optional[str] = None) -> List[str]:
+def names(set_name: str, variant: Optional[str] = None, quick: bool = False) -> List[str]:
+ """Every icon name of a set (and variant). quick: one try with a short timeout (a check that may be skipped)."""
set_name = norm_set(set_name)
local = _names_local(set_name, variant)
- return local if local is not None else _names_cdn(set_name, variant)
+ if local is not None:
+ return local
+ return _names_cdn(set_name, variant, timeout=10, retries=0) if quick else _names_cdn(set_name, variant)
def _tags(set_name: str) -> Dict[str, List[str]]:
@@ -214,26 +226,49 @@ def brand_hex(slug: str) -> Optional[str]:
return None
+def _no_icon(set_name: str, name: str, pool: List[str]) -> ShowtimeError:
+ import difflib
+ close = difflib.get_close_matches(name, pool, n=6, cutoff=0.6) or \
+ [r["name"] for r in search(name, set_name, limit=6)]
+ return ShowtimeError("no icon %r in %s" % (name, set_name),
+ hint=("similar: " + ", ".join(close)) if close else
+ "search with: showtime assets icons <words> --set %s" % set_name)
+
+
+def _have_file(set_name: str, rel: str) -> bool:
+ s = SETS[set_name]
+ return any((base / rel).is_file() for base in (_node_pkg_dir(s["pkg"]), cache_dir(set_name)))
+
+
def raw_svg(set_name: str, name: str, variant: Optional[str] = None) -> str:
set_name = norm_set(set_name)
name = name.strip().lower().replace(" ", "-")
if not re.match(r"^[a-z0-9][a-z0-9._-]*$", name):
raise ShowtimeError("invalid icon name: %r" % name)
rel = _rel_path(set_name, name, variant)
+ pool: Optional[List[str]] = None
+ if not _have_file(set_name, rel):
+ # a name the package does not have is refused from its listing (seeded, or the jsDelivr index cached for 30
+ # days, one quick request) before any fetch: the CDN takes about 40 s to answer a missing file, past the read
+ # timeout, so a misspelled name got a network error and no suggestion (public showtime#78). One try with a
+ # short timeout: an index that is down costs seconds before the file is fetched as before
+ try:
+ pool = names(set_name, variant, quick=True)
+ except Exception as e: # noqa: BLE001 - the listing is a shortcut: offline, down or malformed, fetch and see
+ debug("cannot list %s: %s" % (set_name, e))
+ pool = None
+ if pool and name not in pool:
+ raise _no_icon(set_name, name, pool)
try:
body = _pkg_file(set_name, rel)
except net.HTTPStatusError as e:
if e.status == 404:
- import difflib
- try:
- pool = names(set_name, variant)
- except ShowtimeError:
- pool = []
- close = difflib.get_close_matches(name, pool, n=6, cutoff=0.6) or \
- [r["name"] for r in search(name, set_name, limit=6)]
- raise ShowtimeError("no icon %r in %s" % (name, set_name),
- hint=("similar: " + ", ".join(close)) if close else
- "search with: showtime assets icons <words> --set %s" % set_name)
+ if pool is None:
+ try:
+ pool = names(set_name, variant, quick=True)
+ except ShowtimeError:
+ pool = []
+ raise _no_icon(set_name, name, pool)
raise
return body.decode("utf-8")
diff --git a/skills/showtime/lib/st/assets/net.py b/skills/showtime/lib/st/assets/net.py
index 3597650..895e6b4 100644
--- a/skills/showtime/lib/st/assets/net.py
+++ b/skills/showtime/lib/st/assets/net.py
@@ -186,8 +186,12 @@ def get_json(url: str, *, headers: Optional[Dict[str, str]] = None, ttl: Optiona
timeout=timeout, retries=retries)
except ShowtimeError:
if cp is not None and cp.is_file():
- debug("network failed; using stale cache for %s" % _short(url))
- return json.loads(cp.read_text(encoding="utf-8"))
+ try:
+ data = json.loads(cp.read_text(encoding="utf-8"))
+ debug("network failed; using stale cache for %s" % _short(url))
+ return data
+ except (OSError, ValueError):
+ pass # a corrupt cache entry is no cache: the network error stands
raise
try:
data = json.loads(body.decode("utf-8"))
diff --git a/skills/showtime/lib/st/cli_xray.py b/skills/showtime/lib/st/cli_xray.py
index ef08102..ce01ef2 100644
--- a/skills/showtime/lib/st/cli_xray.py
+++ b/skills/showtime/lib/st/cli_xray.py
@@ -103,7 +103,8 @@ def register(sub: argparse._SubParsersAction) -> None:
n = s.add_parser("notes", help="clip -> notes.json (pitch, onset, tempo map, key, chords) + MIDI, MusicXML, check-notes.jpg",
formatter_class=_F, description=(
"Read the notes an instrument plays (guitar, piano, music box) from the clip's sound, or from a WAV\n"
- "recording with no picture, with Basic Pitch (ONNX, no TensorFlow). Every note keeps frame = floor(t * fps) of the clip. Adds a smooth\n"
+ "recording with no picture, with Basic Pitch (ONNX, no TensorFlow). Every note keeps frame = floor(t * fps): the\n"
+ "clip's frame rate, or the 30 fps grid for a recording with no picture. Adds a smooth\n"
"tempo map (scroll with it, never snap to the last note), eighth-note quantization, the key, a chord per\n"
"beat, the melody (loudest note from E4 up) and bass voices, and with --instrument guitar the string,\n"
"fret and finger of every note (standard tuning, open position first).\n"
diff --git a/skills/showtime/lib/st/job/receipt.py b/skills/showtime/lib/st/job/receipt.py
index 5ccb965..230a38c 100644
--- a/skills/showtime/lib/st/job/receipt.py
+++ b/skills/showtime/lib/st/job/receipt.py
@@ -614,6 +614,11 @@ def card_facts(rec: Dict[str, Any]) -> List[str]:
xr = rec.get("xray")
if xr and xr.get("line"):
out.append("X-ray: %s%s" % (xr["line"], "" if xr.get("status") == "PASS" else " (%s)" % xr.get("status", "").lower()))
+ if xr.get("derived"):
+ out.append("X-ray sound: a rendering (%s); the audio check compares the film with it, not with the original data"
+ % xr["derived"])
+ elif xr.get("events_from"):
+ out.append("X-ray events: from %s, not measured from the sound" % xr["events_from"])
if xr.get("credit"):
out.append("Clip credit: %s" % xr["credit"])
mode = (rec.get("review_mode") or {}).get("mode")
diff --git a/skills/showtime/lib/st/xray.py b/skills/showtime/lib/st/xray.py
index ed5b472..3b3108e 100644
--- a/skills/showtime/lib/st/xray.py
+++ b/skills/showtime/lib/st/xray.py
@@ -435,6 +435,7 @@ MAX_FILM_SECONDS = 24 * 3600 # no data-only film (no --source) is l
MAX_LINES = 2 * 100000 # every line read of a CSV (blank and comment lines too) counts against this
MAX_VALUES = 64 * 100000 # commas in a JSON file (a bound on every value in it) before it is parsed
MAX_CONTAINERS = 8 * 100000 # "{" and "[" in a JSON file (each is a dict or list in memory) before it is parsed
+MAX_KEYS = 16 * 100000 # ":" in a JSON file (a bound on every object key in it) before it is parsed
MAX_DIGITS = 1000 # a run of digits longer than this is not a number a film can hold
MAX_DEPTH = 32 # JSON nesting an event may carry
MAX_FRAME = 10 ** 9 # a film time past this many frames is a mistake in the time map, not a film
@@ -549,6 +550,12 @@ def _json_rows(path: Path, text: str) -> Tuple[List[Dict[str, Any]], List[str]]:
# refused before it is parsed, while a legitimate file (100,000 events, each with arrays of numbers) is not
if text.count("{") + text.count("[") > MAX_CONTAINERS:
raise ShowtimeError("%s holds too many lists or objects (over %d)" % (path.name, MAX_CONTAINERS), hint="keep the peaks, not every sample")
+ # ... and object keys: ONE object with millions of keys passes both counts above (a 42 MB file of 3.5 million keys
+ # took about 930 MB to parse, about 266 bytes a key; this bound keeps it near 400 MB). Colons inside strings count
+ # too (times like 12:30:01, URLs), so it is an upper bound like the commas: 16 per event at the most events
+ if text.count(":") > MAX_KEYS:
+ raise ShowtimeError("%s holds too many object keys (over %d colons, counting those inside strings)" % (path.name, MAX_KEYS),
+ hint="keep the peaks, not every sample; at most %d events" % MAX_EVENTS)
if re.search(r"\d{%d,}" % MAX_DIGITS, text): # before json.loads: older Pythons parse a huge integer in quadratic time
raise ShowtimeError("%s %s" % (path.name, BIG), hint="remove or fix that value")
@@ -685,6 +692,23 @@ def build_import(events_file: Any, *, time_map: Optional[Dict[str, float]] = Non
if v is None:
raise ShowtimeError("%s, event %d: the time %r is not a number" % (path.name, n, r.get(tcol)))
times.append(v)
+ # the strength cells are checked before the source is read (a long recording is decoded only for a good file)
+ blank_cell = lambda raw: raw is None or str(raw).strip() == "" # noqa: E731
+ sv: Optional[List[float]] = None
+ if strength:
+ sv = []
+ for n, r in enumerate(rows, start=1):
+ raw = r.get(strength)
+ v = _num(raw)
+ if v is None and not blank_cell(raw):
+ raise ShowtimeError("%s, event %d: the %s value %r is not a number" % (path.name, n, strength, raw))
+ sv.append(abs(v) if v is not None else 0.0)
+ elif "strength" in cols: # a column named strength sizes the events without the flag: numbers only too
+ for n, r in enumerate(rows, start=1):
+ raw = r.get("strength")
+ if _num(raw) is None and not blank_cell(raw):
+ raise ShowtimeError("%s, event %d: the strength value %r is not a number" % (path.name, n, raw),
+ hint="a column named strength sizes the events (0 to 1); make it a number, or rename it")
src: Dict[str, Any]
x = np.zeros(0, dtype=np.float32)
if source is not None:
@@ -699,19 +723,8 @@ def build_import(events_file: Any, *, time_map: Optional[Dict[str, float]] = Non
"duration": round(float(duration), 3) if duration else None, "width": 0, "height": 0}
sfps = float(src["fps"])
end = float(src["duration"]) if src.get("duration") else None
- sv: Optional[List[float]] = None
- if strength:
- sv = []
- for n, r in enumerate(rows, start=1):
- raw = r.get(strength)
- v = _num(raw)
- if v is None and raw is not None and str(raw).strip() != "":
- raise ShowtimeError("%s, event %d: the %s value %r is not a number" % (path.name, n, strength, raw))
- sv.append(abs(v) if v is not None else 0.0)
- blank = sum(1 for r in rows if r.get(strength) is None or str(r.get(strength)).strip() == "")
- if blank:
- warn("%d event(s) have no %s value: drawn at strength 0" % (blank, strength))
top = max(sv or [0.0]) or 1.0
+ blank = 0 # events kept with no --strength value (a dropped row is not counted)
order = sorted(range(len(rows)), key=lambda k: times[k])
events: List[Dict[str, Any]] = []
dropped: List[Dict[str, Any]] = []
@@ -733,6 +746,7 @@ def build_import(events_file: Any, *, time_map: Optional[Dict[str, float]] = Non
continue
if sv is not None:
st = round(sv[k] / top, 3)
+ blank += 1 if blank_cell(r.get(strength)) else 0
else:
own = _num(r.get("strength"))
st = round(min(1.0, max(0.0, own)), 3) if own is not None else 1.0
@@ -754,6 +768,8 @@ def build_import(events_file: Any, *, time_map: Optional[Dict[str, float]] = Non
c = c + "_data"
e[c] = val
events.append(e)
+ if blank and events:
+ warn("%d event(s) have no %s value: drawn at strength 0" % (blank, strength))
if not events:
raise ShowtimeError("none of the %d events of %s lands inside the film" % (len(rows), path.name),
hint="check --time-map: film t = (t_data - t0) x slow must be 0 or more%s" % (
@@ -983,22 +999,50 @@ def track_frames(frames: Sequence[np.ndarray], ref: int, region: np.ndarray, mas
# ------------------------------------------------------------------ verify
-def _read_marker_levels(video: Path, width: int, height: int) -> np.ndarray:
+def marker_crop(width: int, height: int, scale: float = 1.0) -> Tuple[int, int, int, int]:
+ """(w, h, x, y) of the patch to read for the marker on a film `scale` times the page's size: the whole 6x6 square
+ at 1, else its inside (a scaled-down square is blurred at its edges and lands between pixels)."""
+ if abs(scale - 1.0) < 1e-3:
+ return MARKER_SIZE, MARKER_SIZE, width - MARKER_INSET, height - MARKER_INSET
+ size = MARKER_SIZE * scale
+ half = max(1, int(math.floor(size / 2.0 - 0.75)))
+ cx, cy = width - (MARKER_INSET - MARKER_SIZE / 2.0) * scale, height - (MARKER_INSET - MARKER_SIZE / 2.0) * scale
+ x, y = int(math.floor(cx - half + 0.5)), int(math.floor(cy - half + 0.5))
+ return 2 * half, 2 * half, max(0, x), max(0, y)
+
+
+def _read_marker_levels(video: Path, width: int, height: int, scale: float = 1.0) -> np.ndarray:
"""Mean gray of the marker patch on every frame of the film (one value per frame)."""
import subprocess
- x, y = width - MARKER_INSET, height - MARKER_INSET
+ cw, ch, x, y = marker_crop(width, height, scale)
args = [ff.ffmpeg_path(), "-hide_banner", "-nostdin", "-loglevel", "error", "-i", str(video), "-an",
- "-vf", "crop=%d:%d:%d:%d,format=gray" % (MARKER_SIZE, MARKER_SIZE, x, y),
+ "-vf", "crop=%d:%d:%d:%d,format=gray" % (cw, ch, x, y),
"-f", "rawvideo", "-pix_fmt", "gray", "-"]
cp = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if cp.returncode != 0:
raise ShowtimeError("ffmpeg could not read the film %s: %s" % (video.name, cp.stderr.decode("utf-8", "replace")[-300:]))
px = np.frombuffer(cp.stdout, dtype=np.uint8)
- per = MARKER_SIZE * MARKER_SIZE
+ per = cw * ch
px = px[: (len(px) // per) * per].reshape(-1, per)
return px.mean(axis=1) if len(px) else np.zeros(0)
+def film_scale(job: Path, width: int, height: int) -> float:
+ """How many times the page's size the film is: a --preview (fit to 720p) or --scale render of the project whose
+ showtime.json sets width x height. 1 when the project is not found or the film has another shape (--size)."""
+ doc = project_doc(job)
+ try:
+ pw, ph = float(doc.get("width") or 0), float(doc.get("height") or 0)
+ except (TypeError, ValueError):
+ return 1.0
+ if pw <= 0 or ph <= 0 or width <= 0 or height <= 0:
+ return 1.0
+ sx, sy = width / pw, height / ph
+ if abs(sx - sy) > 0.02 * max(sx, sy): # another aspect: the page was laid out at the film's own size
+ return 1.0
+ return sx if abs(sx - 1.0) > 0.01 else 1.0
+
+
def match_markers(expected: Sequence[int], on: Sequence[int], slack: int = MARKER_SLACK) -> Dict[str, Any]:
"""Pair expected marker frames with ON frames (exact first, then the nearest within `slack`)."""
exp = sorted(set(int(e) for e in expected))
@@ -1142,9 +1186,9 @@ def smoothness_of_profiles(prof: np.ndarray, max_shift: int = 40) -> Dict[str, A
"stall_frames": stalls[:50], "jump_frames": jumps[:50]}
-def project_config(job: Path) -> Dict[str, Any]:
- """The "xray" block of the job's project showtime.json ({"marker", "offset_frames", "band": [y0, y1]}):
- <job>/project/showtime.json first, then any */showtime.json under the job. {} when there is none."""
+def project_doc(job: Path) -> Dict[str, Any]:
+ """The job's project showtime.json that has an "xray" block: <job>/project/showtime.json first, then any
+ */showtime.json under the job. {} when there is none."""
job = Path(job)
cands = [job / "project" / "showtime.json"]
try:
@@ -1155,12 +1199,17 @@ def project_config(job: Path) -> Dict[str, Any]:
for p in cands:
if p.is_file():
d = read_json(p, {})
- x = d.get("xray") if isinstance(d, dict) else None
- if isinstance(x, dict):
- return x
+ if isinstance(d, dict) and isinstance(d.get("xray"), dict):
+ return d
return {}
+def project_config(job: Path) -> Dict[str, Any]:
+ """The "xray" block of the job's project showtime.json ({"marker", "offset_frames", "band": [y0, y1]}), {} when
+ there is none."""
+ return project_doc(job).get("xray") or {}
+
+
def find_film(job: Path) -> Optional[Path]:
from .job import ledger
try:
@@ -1221,9 +1270,15 @@ def verify(job: Any, video: Optional[Any] = None, source: Optional[Any] = None,
pr = ff.probe(film)
W, H = int(pr["width"]), int(pr["height"])
ffps = float(pr.get("fps") or 0)
- levels = _read_marker_levels(film, W, H)
- nfr = len(levels)
+ scale = film_scale(job, W, H)
+ levels = _read_marker_levels(film, W, H, scale)
on = [int(i) for i in np.where(levels > 128)[0]]
+ if scale != 1.0 and not (on and len(on) < len(levels)): # not found at the page's scale: read it as drawn on the film
+ lv1 = _read_marker_levels(film, W, H)
+ on1 = [int(i) for i in np.where(lv1 > 128)[0]]
+ if on1 and len(on1) < len(lv1):
+ scale, levels, on = 1.0, lv1, on1
+ nfr = len(levels)
if skip is None: # --skip, else the project's "xray".skip: events that are not the object's
sk = cfg.get("skip")
skip = list(sk) if isinstance(sk, (list, tuple)) else []
@@ -1248,8 +1303,12 @@ def verify(job: Any, video: Optional[Any] = None, source: Optional[Any] = None,
"events": len(inside), "on_frame": len(m["exact"]), "missing": m["missing"], "extra": m["extra"],
"audio_lag_ms": None, "marker": marker, "off_by": m["near"], "max_offset": m["max_offset"],
"outside_film": len(expected) - len(inside), "skipped": len(skipset), "film": film.name, "film_frames": nfr}
+ if scale != 1.0:
+ res["marker_scale"] = round(scale, 4)
findings: List[Tuple[str, str, str]] = []
notes: List[str] = []
+ if scale != 1.0:
+ notes.append("the film is %.3g times the page's size (a --preview or --scale render): the marker was read there" % scale)
if bad_skip:
notes.append("WARN: skip entries ignored (not an event index of xray.json): %s" % ", ".join(bad_skip))
if len(set(inside)) < len(inside):
@@ -1278,6 +1337,24 @@ def verify(job: Any, video: Optional[Any] = None, source: Optional[Any] = None,
except (TypeError, ValueError):
band = None
res["offset_frames"] = int(offset_frames)
+ # what the film's sound is: the audio check compares the film with the source sound, which says the sync of the
+ # events only when they were measured from that sound (analyze). A rendering of data ("xray".derived) or events
+ # imported from data (xray import) are said in the receipt instead of "the original".
+ derived = cfg.get("derived")
+ derived = " ".join(derived.split())[:200] if isinstance(derived, str) else ""
+ det = doc.get("detector") if isinstance(doc.get("detector"), dict) else {}
+ if derived:
+ res["derived"] = derived
+ notes.append("the clip's sound is a rendering (%s): the audio check compares the film with that rendering, not "
+ "with the original data" % derived)
+ if det.get("engine") == "data":
+ inp = det.get("input") if isinstance(det.get("input"), dict) else {}
+ inp = " ".join(inp["file"].split())[:120] if isinstance(inp.get("file"), str) and inp["file"].strip() else "a data file"
+ res["events_from"] = "data: %s" % inp
+ if not derived:
+ notes.append("the events come from data (%s, xray import), not from the sound: the audio check says the film "
+ "plays its source sound in time, not that the sound matches the data; say what the sound is "
+ "with \"xray\": {\"derived\": \"...\"}" % inp)
if band:
res["smoothness"] = smoothness(film, band)
if not marker:
@@ -1287,7 +1364,7 @@ def verify(job: Any, video: Optional[Any] = None, source: Optional[Any] = None,
findings.append(("FAIL", "xray_sync", "%d missing marker frame(s) %s, %d extra %s" % (
len(m["missing"]), m["missing"][:6], len(m["extra"]), m["extra"][:6])))
if res["audio_lag_ms"] is not None and abs(res["audio_lag_ms"]) > LAG_LIMIT_MS:
- findings.append(("FAIL", "xray_sync", "the film's audio is %.1f ms from the original (limit %g ms)" % (res["audio_lag_ms"], LAG_LIMIT_MS)))
+ findings.append(("FAIL", "xray_sync", "the film's audio is %.1f ms from %s (limit %g ms)" % (res["audio_lag_ms"], _sound_word(res), LAG_LIMIT_MS)))
if audio_unmatched:
findings.append(("WARN", "xray_audio", "the film's sound could not be matched to the clip's"))
if m["near"]:
@@ -1304,18 +1381,24 @@ def verify(job: Any, video: Optional[Any] = None, source: Optional[Any] = None,
return res
+def _sound_word(res: Dict[str, Any]) -> str:
+ """What the film's sound was compared with: a rendering of data, the source sound of imported events, or the original."""
+ return "the rendered sound" if res.get("derived") else "the source sound" if res.get("events_from") else "the original"
+
+
def end_card_line(res: Dict[str, Any]) -> str:
"""The one line for an end card."""
if not res.get("marker"):
- return "%d events measured from the clip (sync not verified: no marker in the film)" % res.get("events", 0)
+ return "%d events %s (sync not verified: no marker in the film)" % (
+ res.get("events", 0), "from data" if res.get("events_from") else "measured from the clip")
lag = res.get("audio_lag_ms")
- tail = "audio %s ms from the original" % ("%.0f" % abs(lag) if abs(lag) >= 10 else "%.1f" % abs(lag)) if lag is not None \
+ tail = "audio %s ms from %s" % ("%.0f" % abs(lag) if abs(lag) >= 10 else "%.1f" % abs(lag), _sound_word(res)) if lag is not None \
else "audio not compared"
return "%d of %d events on their frame · %s" % (res["on_frame"], res["events"], tail)
RECEIPT_KEYS = ("events", "on_frame", "missing", "extra", "audio_lag_ms", "marker", "off_by", "max_offset", "outside_film", "skipped",
- "film", "smoothness", "status", "line", "notes")
+ "film", "smoothness", "status", "line", "notes", "derived", "events_from", "marker_scale")
def receipt_section(job: Path) -> Optional[Dict[str, Any]]:
diff --git a/skills/showtime/library/xray/drums/mechanism.js b/skills/showtime/library/xray/drums/mechanism.js
index de07c08..ff171f9 100644
--- a/skills/showtime/library/xray/drums/mechanism.js
+++ b/skills/showtime/library/xray/drums/mechanism.js
@@ -2,7 +2,7 @@
Design space: 1000 x 440 units (the 9:16 panel, about 0.95 px per unit): a percussion staff on top, a drum kit
seen from above below it (the drummer's seat at the bottom): kick, snare, hi-hat, two mounted toms, floor tom,
crash and ride.
- The staff scrolls left past a fixed playhead on the smooth tempo map (k.beat of the frame's time, never a jump).
+ The staff scrolls left past a fixed playhead on the smooth tempo map (k.beat of k.rt, the recording's time: never a jump).
Each event is a hit: its pieces (notes.json drums[], joined to the event by the runtime) are written at the
playhead in the usual drum key (kick in the bottom space, floor tom, snare in the third space, toms above it,
hi-hat x above the staff with an o when open, crash x on a ledger line), red on the event's frame; on the kit
@@ -40,7 +40,7 @@
}
if (!KEY[p]) p = 'snare';
return { i: i, t: d.t, piece: p, vel: d.velocity == null ? 0.8 : d.velocity, beat: q[i] ? q[i].beat : k.beat(d.t), ev: ev,
- show: ev != null ? k.ev[ev].frame : Math.floor(d.t * k.fps + 1e-9) };
+ show: ev != null ? k.ev[ev].frame : k.frameAt(d.t) };
});
var cols = {};
hits.forEach(function (h) { (cols[h.beat] = cols[h.beat] || { beat: h.beat, hits: [] }).hits.push(h); });
@@ -56,6 +56,8 @@
g.fillStyle = col; g.textAlign = align || 'left'; g.textBaseline = 'alphabetic'; g.globalAlpha *= (k.labelAlpha == null ? 1 : k.labelAlpha);
g.fillText(s, x, y); g.restore();
}
+ // a caption: in the 9:16 panel the page sets it in its caption row at the label size (k.caption), else drawn here
+ function cap(k, s, x, y, px, col, align) { if (k.caption) k.caption(s, align === 'right' ? 'right' : 'left', col); else text(k, s, x, y, px, col, align); }
function head(g, x, y, kind, col) {
if (kind === 'x') { line(g, x - 6.5, y - 6.5, x + 6.5, y + 6.5, col, 2.4); line(g, x - 6.5, y + 6.5, x + 6.5, y - 6.5, col, 2.4); return; }
g.save(); g.translate(x, y); g.rotate(-0.35); g.beginPath(); g.ellipse(0, 0, 9.2, 6.4, 0, 0, Math.PI * 2); g.fillStyle = col; g.fill(); g.restore();
@@ -77,7 +79,7 @@
draw: function (k) {
if (k.view === 'inplace') return;
if (!M) build(k);
- var g = k.g, C = k.C, f = k.f, now = f / k.fps, bNow = k.beat(now), pxb = M.pxb;
+ var g = k.g, C = k.C, f = k.f, now = k.rt, bNow = k.beat(now), pxb = M.pxb;
var o = k.pr(0, 0);
g.save(); g.translate(o[0], o[1]); g.scale(k.scale, k.scale); g.shadowBlur = 0;
var X = function (b) { return PLAY + (b - bNow) * pxb; };
@@ -204,7 +206,7 @@
}
g.restore();
});
- text(k, M.has ? 'PIECES SORTED BY THEIR SOUND' : 'HITS, NO PIECES (NO NOTES.JSON)', 0, 26, 28, C.muted, 'left');
+ cap(k, M.has ? 'PIECES SORTED BY THEIR SOUND' : 'HITS, NO PIECES (NO NOTES.JSON)', 0, 26, 28, C.muted, 'left');
g.restore();
// labels: each piece, red while it rings
var LBL = { crash: [-60, -36], ride: [70, -36], hihat: [-60, 0], tom_high: [-30, -80], tom_mid: [30, -80], snare: [-50, 36],
diff --git a/skills/showtime/library/xray/guitar/mechanism.js b/skills/showtime/library/xray/guitar/mechanism.js
index 0a6a00a..5c0204e 100644
--- a/skills/showtime/library/xray/guitar/mechanism.js
+++ b/skills/showtime/library/xray/guitar/mechanism.js
@@ -2,7 +2,7 @@
Design space: 1000 x 350 units (the 9:16 panel under a 4:3 clip, about 0.95 px per unit): chord names on top,
a six-line tab (string 1, high e, on top) with the right-hand fingers (p i m a) under it, and a fretboard
diagram below in the same orientation, nut on the left, frets 0-12 at their real spacing.
- The tab scrolls left past a fixed playhead on the smooth tempo map (k.beat of the frame's time, never a jump).
+ The tab scrolls left past a fixed playhead on the smooth tempo map (k.beat of k.rt, the recording's time: never a jump).
Each event is a pluck: its notes (notes.json guitar[]: string, fret, finger) are written at the playhead, red on
the event's frame; on the fretboard the fretted dots light while they sound and the plucked string vibrates
from the fret to the bridge, ringing down over about a second.
@@ -29,7 +29,7 @@
var ev = evOf[i];
notes.push({ i: i, t: n.t, end: n.end || n.t + 0.5, conf: n.confidence || 0, beat: q[i] ? q[i].beat : k.beat(n.t),
string: gd.string, fret: gd.fret, finger: gd.finger || '', ev: ev,
- show: ev != null ? k.ev[ev].frame : Math.floor(n.t * k.fps + 1e-9) });
+ show: ev != null ? k.ev[ev].frame : k.frameAt(n.t) });
});
var cols = {}; // one column per beat; one note per string (the surer one)
notes.forEach(function (n) {
@@ -55,6 +55,8 @@
g.fillStyle = col; g.textAlign = align || 'left'; g.textBaseline = 'alphabetic'; g.globalAlpha *= (k.labelAlpha == null ? 1 : k.labelAlpha);
g.fillText(s, x, y); g.restore();
}
+ // a caption: in the 9:16 panel the page sets it in its caption row at the label size (k.caption), else drawn here
+ function cap(k, s, x, y, px, col, align) { if (k.caption) k.caption(s, align === 'right' ? 'right' : 'left', col); else text(k, s, x, y, px, col, align); }
function strY(s) { return TY + (s - 1) * TS; }
function boardY(s) { return FY + (s - 1) * FS; }
@@ -74,7 +76,7 @@
draw: function (k) {
if (k.view === 'inplace') return;
if (!M) build(k);
- var g = k.g, C = k.C, f = k.f, now = f / k.fps, bNow = k.beat(now), pxb = M.pxb;
+ var g = k.g, C = k.C, f = k.f, now = k.rt, bNow = k.beat(now), pxb = M.pxb;
var o = k.pr(0, 0);
g.save(); g.translate(o[0], o[1]); g.scale(k.scale, k.scale); g.shadowBlur = 0;
var X = function (b) { return PLAY + (b - bNow) * pxb; };
@@ -88,7 +90,8 @@
// the six strings of the tab, their names, and the bracket
for (var s = 1; s <= 6; s++) line(g, HX - 8, strY(s), W, strY(s), C.l(.5), 1.3);
line(g, HX - 8, strY(1), HX - 8, strY(6), C.l(.7), 2);
- for (s = 1; s <= 6; s++) text(k, NAMES[s - 1], 14, strY(s) + 9, 26, C.muted, 'left', 600);
+ // (9:16 panel: the names are labels in the page's column, where they can be read; see the end)
+ if (!k.caption) for (s = 1; s <= 6; s++) text(k, NAMES[s - 1], 14, strY(s) + 9, 26, C.muted, 'left', 600);
// the playhead (every pluck flashes it), under the numbers
var ph = k.hot ? k.s : 0;
g.save(); if (ph > 0.05) { g.shadowColor = C.hot; g.shadowBlur = 16 * ph; }
@@ -180,9 +183,11 @@
}
// words: the key and tempo heard
var info = [M.key ? String(M.key).toUpperCase() : null, M.has ? Math.round(M.bpm) + ' BPM' : null].filter(Boolean).join(' · ');
- if (info) text(k, info, 0, 22, 28, C.muted, 'left');
- text(k, 'p i m a: right hand', PLAY + 8, 22, 28, C.muted, 'right');
+ if (info) cap(k, info, 0, 22, 28, C.muted, 'left');
+ // the fingers' key; in the 9:16 panel only when a finger is drawn (its caption row has no room to spare)
+ if (!k.caption || M.notes.some(function (n) { return n.finger; })) cap(k, 'p i m a: right hand', PLAY + 8, 22, 28, C.muted, 'right');
g.restore();
+ if (k.caption) for (var si = 1; si <= 6; si++) k.label(NAMES[si - 1], [HX - 8, strY(si)], 0, 0, false, { keepCase: true });
}
});
})();
diff --git a/skills/showtime/library/xray/piano/README.md b/skills/showtime/library/xray/piano/README.md
index 389fde4..cd1ac1f 100644
--- a/skills/showtime/library/xray/piano/README.md
+++ b/skills/showtime/library/xray/piano/README.md
@@ -7,7 +7,7 @@ fixed playhead, and an 88-key keyboard (A0 to C8, middle C marked).
frame (stems, flags, a beam once the second eighth of a pair is heard, dots, ledger lines, accidentals outside
the key), and their keys go down and light while they sound. Every strike also flashes the playhead, so a
strike with no pitch heard still shows.
-- The staff scrolls on the smooth tempo map (`k.beat` of the frame's time), never by jumping to the last note;
+- The staff scrolls on the smooth tempo map (`k.beat` of `k.rt`, the frame's time on the recording), never by jumping to the last note;
notes sit on their quantized beat (eighths of that map).
- Which notes: from `notes.json` (`showtime xray notes <clip> --job <job> --instrument piano`). Hands: the bass
voice on the bass staff, the melody on the treble staff, other notes with the nearer of the two. Spelling
diff --git a/skills/showtime/library/xray/piano/mechanism.js b/skills/showtime/library/xray/piano/mechanism.js
index e194576..83de72e 100644
--- a/skills/showtime/library/xray/piano/mechanism.js
+++ b/skills/showtime/library/xray/piano/mechanism.js
@@ -1,7 +1,7 @@
/* A piano, written as it is heard (showtime X-ray mechanism library: piano).
Design space: 1000 x 440 units (the 9:16 panel, about 0.95 px per unit), a grand staff on top (treble and bass,
brace, clefs and key signature drawn as paths, no music font needed) and an 88-key keyboard below.
- The staff scrolls left past a fixed playhead on the smooth tempo map (k.beat of the frame's time: never a jump to
+ The staff scrolls left past a fixed playhead on the smooth tempo map (k.beat of k.rt, the recording's time: never a jump to
the latest note). Each event is a strike: its notes (notes.json, joined to the event by the runtime) are written
at the playhead, red on the event's frame, with their stems, flags, beams, dots, ledger lines and accidentals;
their keys go down and light up on the keyboard while they sound.
@@ -59,10 +59,10 @@
if (fifths == null) { fifths = 0; keyName = null; }
var keyAlt = {};
for (var s = 0; s < Math.abs(fifths); s++) keyAlt[fifths > 0 ? SHARPS[s] : FLATS[s]] = fifths > 0 ? 1 : -1;
- var minc = cfg.min_confidence || 0, fps = k.fps;
+ var minc = cfg.min_confidence || 0;
var notes = raw.filter(function (n) { return n.confidence == null || n.confidence >= minc; }).map(function (n, j) {
var i = n.i != null ? n.i : j, qd = q[i], sp = spell(n.pitch, fifths, keyAlt);
- var fr = Math.floor(n.t * fps + 1e-9), ev = evOf[i];
+ var fr = k.frameAt(n.t), ev = evOf[i];
return { i: i, pitch: n.pitch, t: n.t, end: n.end || n.t + 0.3, beat: qd ? qd.beat : k.beat(n.t), dur: qd ? qd.dur_beats : 1,
li: sp.li, alt: sp.alt, step: sp.step, ev: ev, show: ev != null ? k.ev[ev].frame : fr };
});
@@ -166,6 +166,8 @@
g.fillStyle = col; g.textAlign = align || 'left'; g.textBaseline = 'alphabetic'; g.globalAlpha = k.alpha * (k.labelAlpha == null ? 1 : k.labelAlpha);
g.fillText(s, x, y); g.restore();
}
+ // a caption: in the 9:16 panel the page sets it in its caption row at the label size (k.caption), else drawn here
+ function cap(k, s, x, y, px, col, align) { if (k.caption) k.caption(s, align === 'right' ? 'right' : 'left', col); else text(k, s, x, y, px, col, align); }
// ------------------------------------------------------------------ one column of the score (a staff, a beat)
function geom(col, vis) {
@@ -223,7 +225,7 @@
draw: function (k) {
if (k.view === 'inplace') return;
if (!M) build(k);
- var g = k.g, C = k.C, f = k.f, now = f / k.fps, bNow = k.beat(now), pxb = M.pxb, hx = M.hx;
+ var g = k.g, C = k.C, f = k.f, now = k.rt, bNow = k.beat(now), pxb = M.pxb, hx = M.hx;
var o = k.pr(0, 0);
g.save(); g.translate(o[0], o[1]); g.scale(k.scale, k.scale);
var X = function (b) { return PLAY + (b - bNow) * pxb; };
@@ -349,11 +351,11 @@
g.restore();
// words: the key and tempo heard, and where the playhead is
var info = [M.keyName ? M.keyName.toUpperCase() : null, M.has ? Math.round(M.bpm) + ' BPM' : null].filter(Boolean).join(' · ');
- if (info) text(k, info, 0, 26, 30, C.muted, 'left');
+ if (info) cap(k, info, 0, 26, 30, C.muted, 'left');
if (M.meter && bNow >= M.down) {
var rel = bNow - M.down, barN = Math.floor(rel / M.meter) + 1, beatN = Math.floor(rel % M.meter) + 1;
if (M.has && bNow > M.last + M.meter) barN = null;
- if (barN) text(k, 'BAR ' + barN + ' · ' + beatN, PLAY + 8, 26, 30, C.ink, 'right');
+ if (barN) cap(k, 'BAR ' + barN + ' · ' + beatN, PLAY + 8, 26, 30, C.ink, 'right');
}
g.restore();
}
diff --git a/skills/showtime/library/xray/switch/mechanism.js b/skills/showtime/library/xray/switch/mechanism.js
index bd41fe8..a9e4b67 100644
--- a/skills/showtime/library/xray/switch/mechanism.js
+++ b/skills/showtime/library/xray/switch/mechanism.js
@@ -71,7 +71,7 @@
k.ell(PIV[0], PIV[1], 16, 16, snap > 0.05 ? C.hot : C.line, 3, 0, false);
if (snap > 0.05) { g.save(); g.shadowColor = C.hot; g.shadowBlur = 26 * snap; k.dot(CONTACT, Math.max(6, 18 * snap * Math.min(1.6, k.scale + 0.4)), C.h(.9)); g.restore(); }
k.label('pivot', PIV, panel ? -40 : -200, panel ? -190 : -150, false);
- k.label('over-centre spring', [(tail[0] + BLADE0[0]) / 2, (tail[1] + BLADE0[1]) / 2], -160, panel ? 150 : 170, snap > 0.05);
+ k.label(k.reels ? 'spring' : 'over-centre spring', [(tail[0] + BLADE0[0]) / 2, (tail[1] + BLADE0[1]) / 2], -160, panel ? 150 : 170, snap > 0.05);
k.label('contacts', CONTACT, 120, panel ? -150 : 150, closed);
}
});
diff --git a/skills/showtime/mcp/server.mjs b/skills/showtime/mcp/server.mjs
index f1e060d..5563888 100644
--- a/skills/showtime/mcp/server.mjs
+++ b/skills/showtime/mcp/server.mjs
@@ -31,6 +31,7 @@
// audio, transcription, stills and studio tools. Each tool's schema is checked against the command line's own
// flags by tests/test_mcp.py (see `cli` below).
+import crypto from 'node:crypto';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
@@ -624,8 +625,9 @@ const TOOLS = [
if (typeof a.text !== 'string' || !a.text.trim()) throw new InputError('text is empty');
if (a.text.length > 5000) throw new InputError('text is longer than 5000 characters; use voice_script for long narration');
if (a.text.includes('\0')) throw new InputError('text contains a NUL character');
- const tmp = path.join(os.tmpdir(), `showtime-mcp-say-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.txt`);
- fs.writeFileSync(tmp, a.text, 'utf8');
+ // a name nobody can guess, created new (never through a file or link already there), readable by this user only
+ const tmp = path.join(os.tmpdir(), `showtime-mcp-say-${crypto.randomBytes(12).toString('hex')}.txt`);
+ fs.writeFileSync(tmp, a.text, { encoding: 'utf8', flag: 'wx', mode: 0o600 });
ctx.cleanup.push(tmp);
const out = a.output !== undefined ? outputPath(a.output, 'output', ['.wav', '.flac'])
: freshFile(baseDir(), `voice-${slug(a.text)}`, '.wav');
diff --git a/skills/showtime/references/film-api.md b/skills/showtime/references/film-api.md
index 1bea3b7..215ebd3 100644
--- a/skills/showtime/references/film-api.md
+++ b/skills/showtime/references/film-api.md
@@ -28,6 +28,9 @@ function of T**. The same `T` must always give the same pixels, whatever frame w
- Never put arrows, `⌘`, `✓` or other symbols in text: draw them with `F.glyph` (`F.keycap`/`F.keyCombo`
do it for you) (§5)
- Mark UI-mockup detail with `F.decor(() => ...)` or `{decor: true}`, never anything the viewer must read (§5)
+- Text layered over other text on purpose (a stamp over a struck word): `F.layer(() => ...)` or `{layer: true}`;
+ other text whose letters overlap a visible text for a moment, with `F.text` or the canvas's own `g.fillText`, is
+ a `text_overlap` warning (§5)
- Fonts are files, never system fonts: link the Fontsource CSS from `/_lib/` and list the weights in
`Film.start({fonts})`. Declare images in `Film.start({images})` or `F.image()` at setup, not in
`scenes()` (§9)
@@ -50,18 +53,18 @@ function of T**. The same `T` must always give the same pixels, whatever frame w
<!-- section lines: kept current by scripts/check_release.py -->
| Section | Lines |
|---|---|
-| 1. Minimal film | 66-90 |
-| 2. Film.start(options) | 92-117 |
-| 3. Time: progress, windows, keyframes | 119-165 |
-| 4. Scenes and transitions | 167-191 |
-| 5. Text | 193-233 |
-| 6. Shapes, UI pieces and diagrams | 235-263 |
-| 7. Particles, charts, frames and images | 265-292 |
-| 8. Camera and tutorials | 294-382 |
-| 9. Fonts, images and cross-platform rules | 384-396 |
-| 10. Looks and file size | 398-415 |
-| 11. The pure-function-of-T rules (and the pitfalls they prevent) | 417-440 |
-| 12. Recipes | 442-527 |
+| 1. Minimal film | 69-93 |
+| 2. Film.start(options) | 95-120 |
+| 3. Time: progress, windows, keyframes | 122-168 |
+| 4. Scenes and transitions | 170-194 |
+| 5. Text | 196-245 |
+| 6. Shapes, UI pieces and diagrams | 247-275 |
+| 7. Particles, charts, frames and images | 277-304 |
+| 8. Camera and tutorials | 306-394 |
+| 9. Fonts, images and cross-platform rules | 396-408 |
+| 10. Looks and file size | 410-427 |
+| 11. The pure-function-of-T rules (and the pitfalls they prevent) | 429-452 |
+| 12. Recipes | 454-539 |
## 1. Minimal film
@@ -198,8 +201,10 @@ Serif), `mono` (JetBrains Mono). You can also pass any CSS family string.
```js
F.text(str, x, y, {size, weight, family, italic, color, alpha, align: 'left'|'center'|'right',
baseline: 'alphabetic'|'middle'|'top', tracking: -0.02 /* em */, maxWidth /* shrink to fit */,
- stroke, strokeWidth, shadow: {blur, x, y, color} | true, decor /* UI-mockup detail */}) // -> width
+ stroke, strokeWidth, shadow: {blur, x, y, color} | true, decor /* UI-mockup detail */,
+ layer /* over other text on purpose */}) // -> width
F.decor(() => { /* draw a mock app window: its small labels are detail, not copy */ })
+F.layer(() => { /* a word stamped over a struck-out one: text over text on purpose */ })
F.measure(str, opts) ; F.fit(str, maxWidth, opts) /* -> size */ ; F.wrap(str, maxWidth, opts) /* -> lines */
F.paragraph(str, x, y, {width, lineHeight: 1.35, ...text opts}) // -> {lines, height}
F.reveal(str, x, y, p, {by: 'line'|'word'|'char', effect: 'rise'|'fade'|'blur'|'scale'|'slide',
@@ -218,6 +223,13 @@ line; per-character reveals suit only 1-2 word hero titles. Minimum sizes at 108
not copy. Draw it inside `F.decor(() => ...)` or pass `{decor: true}` to one `F.text` call, and
`showtime check` reports its size, contrast and overlaps as notes instead of warnings (the canvas twin of the
DOM's `data-st-decor`). Headlines, captions, numbers and anything the viewer must read are never decor.
+**Text over text:** `showtime check` reads every word drawn on the film canvas, `F.text` and the canvas's own
+`g.fillText`/`g.strokeText` alike, and DOM text over the canvas, at every step of its timeline (not only the
+sampled frames), and reports two texts whose letters overlap for two steps or more as `text_overlap`, with both
+strings and when it starts. The
+same string drawn twice (a shadow or outline pass), decor, and text under a card are not overlaps. Text layered
+over other text on purpose (a stamp over a struck word, a label over a ghost of itself): draw it inside
+`F.layer(() => ...)` or pass `{layer: true}` to one `F.text` call.
In the showreel tone, `{flash: true}` marks a flash word (1-3 words of texture that may leave before its reading
time; the DOM's `data-st-flash`; `pacing.md` §1).
diff --git a/skills/showtime/references/render.md b/skills/showtime/references/render.md
index 1907a72..7d33267 100644
--- a/skills/showtime/references/render.md
+++ b/skills/showtime/references/render.md
@@ -300,21 +300,21 @@ exactly like the renderer and reports findings with the time they happen and a f
| `webgpu` | error / warning | the page asks for WebGPU (`navigator.gpu`, a `webgpu` canvas); the message names the file and line. Check loads the page again with WebGPU gone, as on a machine without a GPU (showtime never needs one): error when no WebGL or 2D canvas of the page draws in its place (the render would be a flat ground), warning when one does (frames differ with and without a GPU). Fix: WebGL or 2D, e.g. showtime's shader layer (`shaderLayer`, motion-craft.md) |
| `font_not_embedded` | warning | text is painted with a system font (differs between Mac, Windows and Linux) |
| `text_off_canvas`, `text_clipped` | error | readable text runs off the frame or is cut by a container at a sample time (decor: info) |
-| `text_overlap` | warning | layout problems at the sample times; overlaps are measured on the painted glyphs (not line boxes, so big display type with tall leading is not a false alarm) and say how deep they are; `text_overlap` also covers text hidden under a badge, callout or pill ("X is hidden under Y"), in canvas films too (an `F.callout` card over readable text drawn before it). Found only mid-transition, they are info notes naming the transition ("mid-transition: push into #demo; the settled frame at 0:04.43 is judged on its own"): check samples the settled frame 2 frames after every transition too |
+| `text_overlap` | warning | layout problems at the sample times; overlaps are measured on the painted glyphs (not line boxes, so big display type with tall leading is not a false alarm) and say how deep they are; `text_overlap` also covers text hidden under a badge, callout or pill ("X is hidden under Y"), in canvas films too (an `F.callout` card over readable text drawn before it). Found only mid-transition, they are info notes naming the transition ("mid-transition: push into #demo; the settled frame at 0:04.43 is judged on its own"): check samples the settled frame 2 frames after every transition too. Between the samples, every step of the dense timeline is checked for text over text as well (DOM text, canvas `F.text` and raw `g.fillText` on any page canvas alike, and DOM text over canvas text, `source: "dom+canvas"`): a pair that overlaps on two steps in a row is one warning with its span ("from 0:03.00 to 0:03.30"); a single-step crossfade is not. Canvas text counts while it is painted and visible: not after its canvas is cleared, reset or painted over by an opaque fill (a `fillRect`, or `rect`/`roundRect` boxes filled as one path with an opaque colour, each covering only itself; not a path with a line or curve in it, not `fill('evenodd')` or `fill(path2D)`, not boxes winding both ways) or a film card, not clipped away (a clip is taken as its path's bounds), not under an opaque element above the canvas (a background, a gradient, a loaded image or video, transparent PNGs included; gradient text, `background-clip: text`, hides nothing and reads at full strength). A labelled counter ("TICK 12", "TICK 13", …) is one text, moving or not, while no other text on its canvas has the same words; labels that share their words ("ORBIT 1", "ORBIT 2") are each their own text, and a counter among them is not held. A bare number ("42") is keyed by where it sits, so one that moves is short findings, or none past 16 px a step. Not seen: canvases in iframes, text drawn on an offscreen buffer and copied with `drawImage`, and `clip(path2D)`. Not overlaps: the same string drawn twice (shadow passes), decor, text under a card, a caption on its own opaque plate over a canvas, DOM text turned far enough that its axis-aligned box is mostly empty (kinetic rows; a sticker tilted a few degrees is still judged), and text layered on purpose (`{layer: true}`, `F.layer`, `ST.layer` around raw canvas calls) |
| `labels_crowded` | warning | SVG labels (chart values and axes, map names) whose painted glyphs touch or sit closer than 0.15em side by side or stacked (`label_gap_em` in `runtime/thresholds.json`); one finding per graphic naming the worst pair. While a chart is still growing or morphing it is an info note. Fix: fewer bars, the default `valueLabels` (auto-thinning), a larger plot, or a line chart |
| `chart_labels_hidden` | warning | the project's CSS hides chart labels while the chart moves (`[data-st-moving] .st-chart-val { opacity: 0 }`): every number blinks off when an item is added and back when it settles. Fix: delete the rule; labels ride their marks through a morph, an added item fades its label in, `count: false` shows real values only |
| `slow_scene` | warning | a scene holds on past its last change (a component or CSS animation ending) and past the reading time of its text by more than 2.5 s (4 s for the last scene, an end card): a slow push keeps it from counting as a still hold, but it plays slow. Fix: a beat about every 2 s (a chart state, a callout or reference line arriving, a highlight, a count-up, the next line), or shorten the scene. `report.pacing` lists them |
| `blur_text`, `blur_slow`, `blur_container`, `blur_unsampled`, `blur_inline` | warning | shutter blur (`data-st-blur`, `F.motionBlur`; stage-api.md § Shutter blur), measured on every frame the element is on screen from its own motion: text the viewer reads is blurred (over 0.4 s in one run, on every frame it shows, or with a threshold under 6 px a frame, so it blurs while it moves slowly); the motion is too slow to need it (at its fastest frame under a quarter of its shorter side a frame, or never fast enough to blur); a scene, a container (more than 60 elements, a canvas or video inside, or a film draw that returns a point instead of a box) or a layer over half the frame; it moves from an `ST.onSeek` handler or a moving ancestor, which the blur cannot pose between frames (its copies never show); an inline box, which CSS never transforms. Numbers in `runtime/thresholds.json` "blur"; report.json `blur` lists each element's peak motion, size and blurred frames |
| `same_frame_entrance` | warning | 3 or more sibling items whose CSS entrance (from opacity 0) starts on the same frame: nothing leads, they land as one block. The message names the frame; fix: stagger them 2-4 frames apart in reading order (`animation-delay: calc(var(--i) * 0.1s)`) |
| `callout_off_target` | warning | canvas film: an `F.callout` card is on screen but its anchor is off the frame (the camera moved away from what it points at), or the card itself runs off the frame |
-| `safe_zone` | warning | vertical video: text outside the box that feed UIs leave free (x 64-916, y 220-1440 at 1080x1920); the message names the edge ("top at y 185 < 220") |
+| `safe_zone` | warning | vertical video: text outside the safe box that feed UIs leave free (x 64-916, y 220-1440 at 1080x1920); the message names the edge ("top at y 185 < 220"). Canvas text is also checked on every step of the dense timeline, on any page canvas (raw `g.fillText` included, not only `F.text`): once per text, with its span ("from 0:03.00 to 0:07.50", or "at times from 0:03.00 to 0:09.00 (2.5 s in all)" when it went back inside in between), when it sits outside on two steps in a row without moving or for 1 s in all (a label sliding in through the margin is not reported); decor, text under 2.2% of the frame's short side and text mostly off the frame are not judged |
| `edge_margin` | warning | landscape: text fully in frame but within 3% of an edge (player controls, overscan); keep 5% (96 px at 1920) |
| `control_strip` | warning | landscape: text under 32 px (at 1080p) in the bottom 8%, where a player's progress bar and controls sit |
| `short_text` | warning | text on screen for less than it takes to read (0.3 s + the longer of characters/17 and words/3, per language, min 1 s; part of the phone check, see qa.md); mark text read along with the voice `data-caption` |
| `beat_words` | note | three or more 1-2 word texts shown one after another, each 0.35-1.2 s (a word per beat): read as one line at no more than words/3 per second, so not `short_text` |
| `flash_text` | note | showreel tone only: flash words (`data-st-flash`, 1-3 words, 24 characters at most, on screen 0.2 s or more) that leave before their reading time on purpose, so not `short_text` (`tones.md`, showreel) |
| `no_hero_line` | warning | showreel tone: every text is a flash word, so no line (the name, the one message) is held its reading time; part of the phone check |
-| `tiny_text` | warning | readable text under the phone minimum: points at 390 pt wide (16:9 5 pt, 1:1 10, 4:5 11, 9:16 15) and at least 2.2 % of the frame height; part of the phone check, `report.phone` has the sizes. UI-mockup detail marked `data-st-decor` is exempt; many small texts become one warning that lists them |
+| `tiny_text` | warning | readable text under the phone minimum: points at 390 pt wide (16:9 5 pt, 1:1 10, 4:5 11, 9:16 15) and at least 2.2 % of the frame height; part of the phone check, `report.phone` has the sizes. measured for DOM text, `F.text` and raw canvas text a page draws itself (`fillText` on any page canvas, on the dense timeline; a counter in one place is one text). UI-mockup detail marked `data-st-decor`, or drawn inside `F.decor`, is exempt; many small texts become one warning that lists them |
| `poster_not_baked` | info | showtime.json `poster` is set, but the frame differs from the opening, so `render` (`--poster-bake auto`) will not bake it into frame 0 (it would flash on autoplay and loops); poster.jpg is still written. Start the video in the poster's state, or `"render": {"poster_bake": "force"}` |
| `dead_air` | error / warning | error: for 1.5 s or more no clip is showing (a gap between scenes, or scenes that end before the video does; canvas: only the flat backdrop is drawn), listed in report.json `timeline_holes` (`from`, `to`, `at_end`, `detail`). Warning: a still hold of `--dead-air` seconds or more (default 2.5 s, the same rule as qa `frozen`, so check catches it before the render), or an end hold over 4 s. Fix: add motion (a slow push-in, drift, a progress element) or another beat, or shorten the scene with `showtime retime`. An overlay page for `--alpha` (`<body data-overlay>` or showtime.json `"overlay": true`) gets `overlay_gap` notes instead |
| `final_hold` | info | a still hold that runs to the end, up to 4 s: fine for an end card (qa has the same rule) |
diff --git a/skills/showtime/references/workflows/xray.md b/skills/showtime/references/workflows/xray.md
index 50e46b6..9117f48 100644
--- a/skills/showtime/references/workflows/xray.md
+++ b/skills/showtime/references/workflows/xray.md
@@ -31,16 +31,16 @@ receipt that proves it.
| Section | Lines |
|---|---|
| Inputs | 45-63 |
-| Steps | 65-94 |
-| Drawing the inside | 96-113 |
-| Verify | 115-124 |
-| Live page | 126-163 |
-| Honesty | 165-176 |
-| See-through | 178-192 |
-| Mechanism library | 194-203 |
-| Credits | 205-209 |
-| Pitfalls | 211-219 |
-| Read next | 221-225 |
+| Steps | 65-96 |
+| Drawing the inside | 98-116 |
+| Verify | 118-128 |
+| Live page | 130-167 |
+| Honesty | 169-180 |
+| See-through | 182-196 |
+| Mechanism library | 198-216 |
+| Credits | 218-222 |
+| Pitfalls | 224-232 |
+| Read next | 234-238 |
## Inputs
@@ -85,7 +85,9 @@ receipt that proves it.
see-through outline, reference-frame pixels; default the tracked region), `panel: true` (16:9 see-through
with the schematic beside the clip), `theme` (`dark` radiograph or `light` blueprint: `new xray --theme`),
`credit` (the clip's credit line; `own: true` for the user's own clip), `receipt`, `measured` (one sentence: how
- the events were measured; the end card and the live page say it).
+ the events were measured; the end card and the live page say it), `derived` (what the clip's sound is when it
+ is a rendering of data, "the signal slowed 100x on a 400 Hz carrier": verify then says the audio is compared with
+ that rendering, not with the original data).
5. A library mechanism: place it and check (`showtime check`, `showtime look`, `showtime snap --at` an event's
time: the struck part must sit on the real one). An object the library lacks: copy the closest
`mechanism.js` and redraw `draw(k)` (§ Drawing the inside).
@@ -108,7 +110,8 @@ receipt that proves it.
- Compare frames, never seconds: `xray.json` gives each event a `frame`; the template adds the film's offset.
- Counters and readouts come from the same events (keystrokes so far, rate, returns). Never a number the clip
did not give.
-- Phone sizes: labels 28 px and up, counters 80 px and up, on 1080x1920.
+- Phone sizes on 1080x1920: text 43 px and up (check's floor), counters 64 px (84 px before 0.4.6, and still at 4:5), all
+ inside the reels box.
- Scrolling bands (a score, a tab, a timeline) follow a smoothed time-to-position curve, never a jump to the
latest event: verify reports stalls and jumps.
@@ -118,7 +121,8 @@ receipt that proves it.
frames. Do not cover it or move it.
- `showtime xray verify <job>` reads that corner on every frame of the final film and compares the white
frames with the events, then cross-correlates the film's audio with the clip's. It prints a line like
- "18 of 18 events on their frame · audio 0.0 ms from the original" and writes it into the job receipt.
+ "18 of 18 events on their frame · audio 0.0 ms from the original" and writes it into the job receipt. It reads a
+ `--preview` or `--scale` render too (the marker at the film's scale), so sync can be checked before the final.
- Missing or extra events, or audio more than 20 ms off: qa FAILs. Fix the page (an event drawn on the wrong
frame, a trimmed clip without its offset), not the receipt.
- No marker (a page you wrote yourself): qa WARNs "unverified". Say so on delivery.
@@ -199,6 +203,15 @@ receipt that proves it.
- The kit `draw(k)` gets: `k.seg/ell/poly/path/dot/label` in design units, `k.env(i)` (0..1, 1 on event i's
frame), `k.cur`/`k.s`/`k.hot` (the event acting now), `k.ch` (its character from `text`), `k.ev[i].notes`
(its pitches from notes.json), `k.n` (events so far), `k.since(i)` (frames), `k.view` (panel or inplace).
+ notes.json times and its tempo map are seconds of the recording: compare them with `k.rt` (this frame's time on
+ the recording) and place one with `k.frameAt(t)` (its film frame), never `k.f / k.fps`, which is early by
+ `"xray".offset_frames`. `k.beat(k.rt)` is the beat now on the tempo map.
+- Words in the drawing: a part's name is `k.label(text, at, dx, dy, on)` (capitals; `{keepCase: true}` as a 6th
+ argument keeps the case, as the guitar's strings e and E); a caption (key, tempo, bar) is `k.caption(text, 'left' or
+ 'right', ink)` when `k.caption` is set (the 9:16 panel: a row over the drawing, at the label size), else your own
+ text. At 9:16 the page puts the labels in one or two columns beside the drawing and never over it, so text drawn
+ at a fixed size inside the drawing is what a phone may not read; there `k.reels` is true, and a short name (the
+ switch's "spring") leaves the drawing more width.
- A new object: start from the closest entry, verify it on a real clip, then add it with its README and the
receipt line: the library grows with every verified X-ray.
diff --git a/skills/showtime/runtime/figure.js b/skills/showtime/runtime/figure.js
index 468b4f0..18a0ef3 100644
--- a/skills/showtime/runtime/figure.js
+++ b/skills/showtime/runtime/figure.js
@@ -364,17 +364,19 @@
});
}
root.addEventListener('keydown', function (e) {
- var tag = (e.target && e.target.tagName) || '';
+ var tag = (e.target && e.target.tagName) || '', role = (e.target && e.target.getAttribute && e.target.getAttribute('role')) || '';
+ // a focused control (a summary, the time slider, a button, a link) keeps its own keys: nothing is typed from there,
+ // and its Space and Enter press it, never a scene key too (a letter it has no use for still reaches the scene)
+ var control = tag === 'SUMMARY' || tag === 'BUTTON' || tag === 'A' || role === 'slider';
touched();
if (e.key === 'Escape') { S.pin = ''; setHover(''); api.focus(null, { at: clock.now() }); dirty = true; ui(); sync(); return; }
if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || e.metaKey || e.ctrlKey || e.altKey) return;
if (e.key === 'ArrowRight' || e.key === 'PageDown') { if (I.steps.length) { e.preventDefault(); enter(S.step + 1); } }
else if (e.key === 'ArrowLeft' || e.key === 'PageUp') { if (I.steps.length) { e.preventDefault(); enter(S.step - 1); } }
- else if (I.keys && I.keys[e.key.toLowerCase()]) pressKey(e.key.toLowerCase());
+ else if (I.keys && I.keys[e.key.toLowerCase()]) { if (!control || (e.key !== ' ' && e.key !== 'Enter')) pressKey(e.key.toLowerCase()); }
else if (TYPE) {
if (e.repeat && e.key.length !== 1) return;
- // a focused control (a summary, the time slider, a button, a link) keeps all of its keys
- if (tag === 'SUMMARY' || tag === 'BUTTON' || tag === 'A' || (e.target.getAttribute && e.target.getAttribute('role') === 'slider')) return;
+ if (control) return;
if (e.key === 'Enter') { e.preventDefault(); typeCh('\n'); }
else if (e.key === 'Backspace') { e.preventDefault(); typeCh('\b'); }
else if (e.key.length === 1) { e.preventDefault(); typeCh(e.key); }
@@ -382,7 +384,6 @@
else if (/^[1-9]$/.test(e.key) && +e.key <= I.steps.length) enter(+e.key - 1);
else if (e.key === 'r' || e.key === 'R') enter(S.step);
else if (e.key === 'l' || e.key === 'L') copyLink();
- else if (I.keys && I.keys[e.key.toLowerCase()]) pressKey(e.key.toLowerCase());
});
['pointerdown', 'wheel', 'touchstart'].forEach(function (ev) { root.addEventListener(ev, function () { touched(); }, { passive: true }); });
host.addEventListener('focusin', function () { touched(); });
diff --git a/skills/showtime/runtime/film.js b/skills/showtime/runtime/film.js
index 7481c99..fbbbb8c 100644
--- a/skills/showtime/runtime/film.js
+++ b/skills/showtime/runtime/film.js
@@ -916,6 +916,8 @@
var r = outRect(x, y, w, h, g), c = { kind: kind, text: String(text || '').slice(0, 60), x: Math.round(r.x), y: Math.round(r.y), w: Math.round(r.w), h: Math.round(r.h), z: S.drawSeq = (S.drawSeq || 0) + 1 };
if (extra) for (var k in extra) c[k] = extra[k];
S.covers.push(c);
+ var ct = stageText(); // the card hides raw canvas text drawn before it, as it hides F.text
+ if (ct && ct.cover) ct.cover(g, x, y, w, h);
}
// Every F.text call of the current frame, in output CSS pixels, for QA tools (Film.frameInfo()).
function recordText(str, x, y, w, o, g) {
@@ -923,7 +925,7 @@
var x0 = al === 'center' ? x - w / 2 : (al === 'right' || al === 'end') ? x - w : x;
var y0 = bl === 'middle' ? y - size * 0.5 : bl === 'top' || bl === 'hanging' ? y : bl === 'bottom' ? y - size : y - size * 0.78;
var r = outRect(x0, y0, w, size, g), m = r.m;
- S.texts.push({
+ var rec = {
text: str.slice(0, 120), x: Math.round(r.x), y: Math.round(r.y),
w: Math.round(r.w), h: Math.round(r.h), z: S.drawSeq = (S.drawSeq || 0) + 1,
size: +(size * (m ? Math.hypot(m.a, m.b) / S.dpr : 1)).toFixed(1), font: g.font,
@@ -931,8 +933,23 @@
cam: +(S.camZoom || 1).toFixed(3),
decor: !!(o.decor || S.decor > 0),
flash: !!o.flash, // a flash word: texture in the showreel tone (scripts/lib/showreel.mjs)
- });
+ layer: !!(o.layer || S.layer > 0), // layered on purpose over other text: not an overlap
+ };
+ glyphBox(rec, g, str, x, y);
+ S.texts.push(rec);
}
+ /** The painted glyphs' box (measureText's actual bounds through the transform) as gx/gy/gw/gh: what overlaps. */
+ function glyphBox(rec, g, str, x, y) {
+ var mt = g.measureText(str), l = mt.actualBoundingBoxLeft, rt = mt.actualBoundingBoxRight;
+ var asc = mt.actualBoundingBoxAscent, desc = mt.actualBoundingBoxDescent;
+ if (!(isFinite(l) && isFinite(rt) && isFinite(asc) && isFinite(desc)) || l + rt <= 0 || asc + desc <= 0) return false;
+ var b = outRect(x - l, y - asc, l + rt, asc + desc, g);
+ rec.gx = Math.round(b.x); rec.gy = Math.round(b.y); rec.gw = Math.round(b.w); rec.gh = Math.round(b.h);
+ return true;
+ }
+ // the stage runtime records every page canvas's fillText/strokeText for check (stage.js canvasText); F.text records
+ // its own text here with more detail, so its calls are marked skip there. F.layer / F.decor tag raw calls too.
+ function stageText() { return root.__stCanvasTextFlags || null; }
/**
* Mark what `draw` paints as UI-mockup detail (the canvas twin of the DOM's data-st-decor): tiny
@@ -941,8 +958,22 @@
* decor. One text: F.text(str, x, y, {decor: true}). Returns what `draw` returns.
*/
F.decor = function (draw) {
+ var ct = stageText();
S.decor = (S.decor || 0) + 1;
- try { return draw(); } finally { S.decor -= 1; }
+ if (ct) ct.decor++;
+ try { return draw(); } finally { S.decor -= 1; if (ct) ct.decor--; }
+ };
+
+ /**
+ * Mark what `draw` paints as text layered over other text on purpose (a word stamped over a struck-out one, a
+ * label printed over a ghost of itself): `showtime check` does not report it as text over text. One text:
+ * F.text(str, x, y, {layer: true}). Raw ctx.fillText calls inside `draw` are covered too. Returns what `draw` returns.
+ */
+ F.layer = function (draw) {
+ var ct = stageText();
+ S.layer = (S.layer || 0) + 1;
+ if (ct) ct.layer++;
+ try { return draw(); } finally { S.layer -= 1; if (ct) ct.layer--; }
};
/**
@@ -974,7 +1005,9 @@
g.lineJoin = 'round';
}
applyShadow(o.shadow);
- rawText(str, x, y, o, tr);
+ var ct = stageText();
+ if (ct) ct.skip++;
+ try { rawText(str, x, y, o, tr); } finally { if (ct) ct.skip--; }
var w = g.measureText(str).width;
if (S.texts && S.texts.length < 400) recordText(str, x, y, w, o, g);
g.restore();
diff --git a/skills/showtime/runtime/stage.js b/skills/showtime/runtime/stage.js
index bdb3425..c8fd30d 100644
--- a/skills/showtime/runtime/stage.js
+++ b/skills/showtime/runtime/stage.js
@@ -33,12 +33,14 @@
var PLAYER = W.__ST_PLAYER__ || null;
var search = '';
try { search = W.location.search || ''; } catch (e) { /* opaque origin */ }
- var params = {};
+ var params = Object.create(null); // own keys only: an inherited Object.prototype.st is not a query value
search.replace(/^\?/, '').split('&').forEach(function (kv) {
if (!kv) return;
var i = kv.indexOf('=');
- var k = decodeURIComponent(i < 0 ? kv : kv.slice(0, i));
- params[k] = i < 0 ? '1' : decodeURIComponent(kv.slice(i + 1));
+ try {
+ var k = decodeURIComponent(i < 0 ? kv : kv.slice(0, i));
+ params[k] = i < 0 ? '1' : decodeURIComponent(kv.slice(i + 1));
+ } catch (e) { /* a malformed escape (?x=%): that pair is skipped, the runtime still starts */ }
});
var EMBED = params.st === 'embed';
var RAW = params.st === 'raw';
@@ -1746,6 +1748,7 @@
return nextFrame().then(nextFrame);
}
async function doSeek(tIn) {
+ canvasText.gen++; // each canvas's text list is replaced on its first draw of this frame
var t = quantize(tIn);
var f = Math.round(t * cfg.fps);
var t0 = real.now();
@@ -1911,6 +1914,236 @@
});
}
+ // ------------------------------------------------------------- canvas text (for showtime check)
+ // Every fillText/strokeText on a page canvas, so `showtime check` finds text drawn over text on canvases too (charts,
+ // overlays and scenes drawn with the canvas's own calls; the film API records its F.text calls itself and marks
+ // them skip). A canvas's list is replaced on its first draw after each seek; a canvas not redrawn keeps what it shows.
+ // by: canvas -> its records, held weakly (a scratch canvas a page drops is not kept alive through a render);
+ // refs: the canvases recorded, as weak references, to walk them
+ var canvasText = { gen: 0, by: new WeakMap(), refs: [], skip: 0, layer: 0, decor: 0, seq: 0,
+ cover: function (g, x, y, w, h) { try { noteCover(g, x, y, w, h); } catch (e) { /* a QA record only */ } } };
+ // per 2D context: the bounds of the path being built (since beginPath) and the clip in force, in canvas pixels, so
+ // text clipped away (an odometer's next digit, a masked reveal) is not on screen. A clip is taken as its path's
+ // bounding box under the transform in force when clip() is called; clip(Path2D) is not known and taken as no clip.
+ var ctxState = new WeakMap(), ctxOf = new WeakMap();
+ function stateOf(g) {
+ var st = ctxState.get(g);
+ if (!st) { st = { p: null, rectOnly: true, rects: [], clip: null, stack: [] }; ctxState.set(g, st); if (g.canvas) ctxOf.set(g.canvas, g); }
+ return st;
+ }
+ function growPath(g, x0, y0, x1, y1) {
+ if (!(isFinite(x0) && isFinite(y0) && isFinite(x1) && isFinite(y1))) return;
+ var st = stateOf(g), q = st.p;
+ if (!q) st.p = [Math.min(x0, x1), Math.min(y0, y1), Math.max(x0, x1), Math.max(y0, y1)];
+ else { q[0] = Math.min(q[0], x0, x1); q[1] = Math.min(q[1], y0, y1); q[2] = Math.max(q[2], x0, x1); q[3] = Math.max(q[3], y0, y1); }
+ }
+ // a user-space box [x0, y0, x1, y1] in canvas pixels through the current transform
+ function devBox(g, b) {
+ var m = g.getTransform(), xs = [], ys = [];
+ [[b[0], b[1]], [b[2], b[1]], [b[0], b[3]], [b[2], b[3]]].forEach(function (pt) { xs.push(m.a * pt[0] + m.c * pt[1] + m.e); ys.push(m.b * pt[0] + m.d * pt[1] + m.f); });
+ return [Math.min.apply(null, xs), Math.min.apply(null, ys), Math.max.apply(null, xs), Math.max.apply(null, ys)];
+ }
+ function boxArea(b) { return Math.max(0, b[2] - b[0]) * Math.max(0, b[3] - b[1]); }
+ function boxMeet(a, b) { return [Math.max(a[0], b[0]), Math.max(a[1], b[1]), Math.min(a[2], b[2]), Math.min(a[3], b[3])]; }
+ function noteClip(g, args) {
+ if (args.length && args[0] && typeof args[0] === 'object') return;
+ var st = stateOf(g);
+ if (!st.p) return;
+ var b = devBox(g, st.p);
+ st.clip = st.clip ? boxMeet(st.clip, b) : b;
+ }
+ function noteCanvasText(g, str, x, y, maxWidth, stroke) {
+ var c = g.canvas;
+ // an OffscreenCanvas, or a canvas not in the document (a scratch buffer), is not on screen
+ if (!c || !c.getBoundingClientRect || !c.isConnected || canvasText.skip > 0) return;
+ str = String(str);
+ if (!str.trim()) return;
+ var rec = canvasText.by.get(c);
+ if (!rec) canvasText.refs.push(W.WeakRef ? new W.WeakRef(c) : { deref: function () { return c; } });
+ if (!rec || rec.gen !== canvasText.gen) { rec = { gen: canvasText.gen, list: [] }; canvasText.by.set(c, rec); }
+ if (rec.list.length >= 1000) return; // check compares 300 a side and says when a frame has more
+ var mt = g.measureText(str), l = mt.actualBoundingBoxLeft, r = mt.actualBoundingBoxRight;
+ var asc = mt.actualBoundingBoxAscent, desc = mt.actualBoundingBoxDescent;
+ if (!(isFinite(l) && isFinite(r) && isFinite(asc) && isFinite(desc)) || l + r <= 0 || asc + desc <= 0) return;
+ if (maxWidth > 0 && l + r > maxWidth) { var k = maxWidth / (l + r); l *= k; r *= k; } // squeezed to maxWidth
+ var b = devBox(g, [x - l, y - asc, x + r, y + desc]), m = g.getTransform();
+ var st = ctxState.get(g);
+ if (st && st.clip) {
+ var cb = boxMeet(b, st.clip);
+ if (boxArea(cb) < 0.1 * boxArea(b)) return; // clipped away
+ b = cb;
+ }
+ var px = /(\d+(?:\.\d+)?)px/.exec(g.font || ''), paint = stroke ? g.strokeStyle : g.fillStyle;
+ rec.list.push({ text: str.slice(0, 120), b: b, size: (px ? +px[1] : 10) * Math.hypot(m.b, m.d), alpha: g.globalAlpha,
+ color: typeof paint === 'string' ? paint : null, layer: canvasText.layer > 0, decor: canvasText.decor > 0, z: ++canvasText.seq });
+ }
+ // the canvas's bitmap is reset (canvas.width/height set, ctx.reset()): its text and clip are gone
+ function forgetCanvas(c) {
+ var rec = canvasText.by.get(c), g = ctxOf.get(c);
+ if (rec) { rec.gen = canvasText.gen; rec.list = []; }
+ if (g) ctxState.delete(g);
+ }
+ // text painted over this frame by an opaque box (a clear, an opaque fillRect, a film card): a record at least half
+ // inside it is gone. A clear or fill of the whole canvas empties the list, so a canvas cleared after a seek that
+ // draws no text shows none.
+ function noteCover(g, x, y, w, h) {
+ var m = g.getTransform();
+ if (m.b !== 0 || m.c !== 0) return; // a rotated box is not judged
+ noteCoverBox(g, devBox(g, [x, y, x + w, y + h]));
+ }
+ // b: a box in canvas pixels
+ function noteCoverBox(g, b) {
+ var c = g.canvas, rec = c && canvasText.by.get(c);
+ if (!rec) return;
+ var st = ctxState.get(g);
+ if (st && st.clip) b = boxMeet(b, st.clip); // a clear or fill reaches only inside the clip
+ // a box with a NaN or infinite side (its own, or its clip's under an overflowing transform) paints nothing, and
+ // would drop every record in the filter below
+ if (!b.every(isFinite)) return;
+ if (b[0] <= 0.5 && b[1] <= 0.5 && b[2] >= c.width - 0.5 && b[3] >= c.height - 0.5) { rec.gen = canvasText.gen; rec.list = []; return; }
+ rec.list = rec.list.filter(function (t) { return boxArea(boxMeet(t.b, b)) < 0.5 * boxArea(t.b); });
+ }
+ function opaqueFill(g) {
+ return g.globalAlpha >= 0.99 && g.globalCompositeOperation === 'source-over' && typeof g.fillStyle === 'string' && canvasAlpha(g.fillStyle) >= 0.99;
+ }
+ function noteCanvasWipe(g, x, y, w, h, fill) {
+ if (fill && !opaqueFill(g)) return;
+ noteCover(g, x, y, w, h);
+ }
+ function canvasAlpha(s) {
+ var m = /^(?:rgba|hsla)\([^)]*[,/]\s*([\d.]+)(%?)\s*\)$/.exec(s) || /^(?:rgb|hsl)\([^)]*\/\s*([\d.]+)(%?)\s*\)$/.exec(s);
+ if (m) return m[2] ? +m[1] / 100 : +m[1];
+ if (/^#[0-9a-f]{8}$/i.test(s)) return parseInt(s.slice(7), 16) / 255;
+ if (/^#[0-9a-f]{4}$/i.test(s)) return parseInt(s[4] + s[4], 16) / 255;
+ return s === 'transparent' ? 0 : 1;
+ }
+ function hookCanvasText() {
+ var P = W.CanvasRenderingContext2D && W.CanvasRenderingContext2D.prototype;
+ if (!P || P.__stText) return;
+ P.__stText = true;
+ // each hook paints first, then only reads the context (a QA record; it never changes what is drawn)
+ function after(name, fn) {
+ var orig = P[name];
+ if (typeof orig !== 'function') return;
+ P[name] = function () {
+ var out = orig.apply(this, arguments);
+ try { fn(this, arguments); } catch (e) { /* a QA record only */ }
+ return out;
+ };
+ }
+ after('fillText', function (g, a) { noteCanvasText(g, a[0], a[1], a[2], a[3], false); });
+ after('strokeText', function (g, a) { noteCanvasText(g, a[0], a[1], a[2], a[3], true); });
+ after('clearRect', function (g, a) { noteCanvasWipe(g, +a[0], +a[1], +a[2], +a[3], false); });
+ after('fillRect', function (g, a) { noteCanvasWipe(g, +a[0], +a[1], +a[2], +a[3], true); });
+ // rectOnly: the path so far is boxes (rect, roundRect; a moveTo alone paints nothing), so an opaque fill() of it is
+ // cards that cover text; each box covers only itself (a path of bars does not cover the labels between them), where
+ // the transform put it when it was added to the path. Boxes that wind both ways (a negative width or height, or a
+ // mirroring transform) cancel where they overlap under the nonzero rule, so such a path is not judged
+ var curve = function (g) { stateOf(g).rectOnly = false; };
+ var box = function (g, a) {
+ var st = stateOf(g), m = g.getTransform(), x = +a[0], y = +a[1], w = +a[2], h = +a[3];
+ var dir = (w < 0) !== (h < 0) !== (m.a * m.d < 0);
+ if (st.rects.length >= 64 || m.b !== 0 || m.c !== 0 || !(isFinite(x) && isFinite(y) && isFinite(w) && isFinite(h)) ||
+ (st.rects.length && dir !== st.dir)) st.rectOnly = false;
+ else st.dir = dir, st.rects.push(devBox(g, [Math.min(x, x + w), Math.min(y, y + h), Math.max(x, x + w), Math.max(y, y + h)]));
+ growPath(g, x, y, x + w, y + h);
+ };
+ after('beginPath', function (g) { var st = stateOf(g); st.p = null; st.rectOnly = true; st.rects = []; });
+ after('rect', box);
+ after('roundRect', box);
+ after('moveTo', function (g, a) { growPath(g, +a[0], +a[1], +a[0], +a[1]); });
+ after('lineTo', function (g, a) { curve(g); growPath(g, +a[0], +a[1], +a[0], +a[1]); });
+ after('arcTo', function (g, a) { curve(g); growPath(g, +a[0], +a[1], +a[2], +a[3]); });
+ after('quadraticCurveTo', function (g, a) { curve(g); growPath(g, +a[0], +a[1], +a[2], +a[3]); });
+ after('bezierCurveTo', function (g, a) { curve(g); growPath(g, +a[0], +a[1], +a[2], +a[3]); growPath(g, +a[4], +a[5], +a[4], +a[5]); });
+ after('arc', function (g, a) { curve(g); growPath(g, +a[0] - +a[2], +a[1] - +a[2], +a[0] + +a[2], +a[1] + +a[2]); });
+ after('ellipse', function (g, a) { curve(g); var rr = Math.max(+a[2], +a[3]); growPath(g, +a[0] - rr, +a[1] - rr, +a[0] + rr, +a[1] + rr); });
+ after('fill', function (g, a) {
+ var st = ctxState.get(g);
+ // not fill(Path2D); not 'evenodd' (overlapping boxes leave their shared part unpainted)
+ if (!st || !st.rectOnly || (a.length && a[0] && (typeof a[0] === 'object' || a[0] === 'evenodd')) || !opaqueFill(g)) return;
+ st.rects.forEach(function (b) { noteCoverBox(g, b); });
+ });
+ after('clip', function (g, a) { noteClip(g, a); });
+ after('save', function (g) { var st = stateOf(g); st.stack.push(st.clip); });
+ after('restore', function (g) { var st = stateOf(g); if (st.stack.length) st.clip = st.stack.pop(); });
+ after('reset', function (g) { if (g.canvas) forgetCanvas(g.canvas); });
+ var CP = W.HTMLCanvasElement && W.HTMLCanvasElement.prototype;
+ ['width', 'height'].forEach(function (name) {
+ var d = CP && Object.getOwnPropertyDescriptor(CP, name);
+ if (!d || !d.set || !d.configurable) return;
+ Object.defineProperty(CP, name, { configurable: true, enumerable: d.enumerable, get: d.get, set: function (v) {
+ d.set.call(this, v);
+ try { forgetCanvas(this); } catch (e) { /* a QA record only */ }
+ } });
+ });
+ }
+ // a point of canvas text is hidden when something opaque is painted above the canvas there (an end card over a
+ // chart), or the canvas is not under it at all (clipped away). null: the point is off the page.
+ function opaqueEl(e) {
+ for (var a = e, op = 1; a && a.nodeType === 1; a = a.parentElement) op *= +W.getComputedStyle(a).opacity;
+ if (op < 0.9) return false;
+ if (e.hasAttribute('data-st-gl')) return true;
+ // a loaded picture or a playing video paints its box (a transparent PNG would not: taken as opaque all the same)
+ if (e.tagName === 'IMG' && e.complete && e.naturalWidth > 0) return true;
+ if (e.tagName === 'VIDEO' && e.readyState >= 2) return true;
+ var cs = W.getComputedStyle(e), bi = cs.backgroundImage;
+ if (/text/.test(cs.webkitBackgroundClip || cs.backgroundClip || '')) return false; // paints its letters, not its box
+ return canvasAlpha(cs.backgroundColor) >= 0.9 || (!!bi && bi !== 'none' && /gradient\(/.test(bi) && !/url\(/.test(bi) && !/transparent|rgba\([^)]*,\s*(0?\.\d+|0)\s*\)/.test(bi));
+ }
+ function hiddenAt(c, x, y) {
+ if (!(x >= 0 && y >= 0 && x < W.innerWidth && y < W.innerHeight)) return null;
+ var stack = document.elementsFromPoint(x, y), root = c.getRootNode && c.getRootNode(), host = root && root.host;
+ for (var i = 0; i < stack.length; i++) {
+ var e = stack[i];
+ // a canvas in a shadow root is hit as its host
+ if (e === c || e.contains(c) || (host && (e === host || e.contains(host)))) return false;
+ if (opaqueEl(e)) return true;
+ }
+ return true;
+ }
+ /** The text on the page's canvases now, in page CSS pixels (alpha includes the canvas element's own opacity). Text
+ * under an opaque element painted above its canvas is left out. */
+ function canvasTexts() {
+ var out = [];
+ // hit testing skips pointer-events: none (cards and overlays often set it): make everything hit-testable meanwhile
+ var hit = document.createElement('style');
+ hit.textContent = '*, *::before, *::after { pointer-events: auto !important; }';
+ (document.head || document.documentElement).appendChild(hit);
+ try { collectCanvasTexts(out); } finally { hit.remove(); }
+ return out;
+ }
+ function collectCanvasTexts(out) {
+ // a canvas taken off the page is forgotten (put back, it is recorded afresh)
+ canvasText.refs = canvasText.refs.filter(function (ref) {
+ var c = ref.deref();
+ if (c && !c.isConnected) canvasText.by.delete(c);
+ return !!c && c.isConnected;
+ });
+ canvasText.refs.forEach(function (ref) {
+ var c = ref.deref(), rec = c && canvasText.by.get(c);
+ if (!rec) return;
+ var rect = c.getBoundingClientRect();
+ if (!(rect.width > 0 && rect.height > 0 && c.width > 0 && c.height > 0)) return;
+ var op = 1;
+ for (var e = c; e && e.nodeType === 1; e = e.parentElement) {
+ var cs = W.getComputedStyle(e);
+ if (cs.display === 'none' || (e === c && cs.visibility === 'hidden')) return;
+ op *= +cs.opacity;
+ }
+ if (op < 0.05) return;
+ var sx = rect.width / c.width, sy = rect.height / c.height, id = c.id ? '#' + c.id : 'canvas';
+ rec.list.forEach(function (t) {
+ var x = rect.left + t.b[0] * sx, y = rect.top + t.b[1] * sy, w = (t.b[2] - t.b[0]) * sx, h = (t.b[3] - t.b[1]) * sy;
+ var tested = 0, hidden = 0;
+ [0.2, 0.5, 0.8].forEach(function (f) { var v = hiddenAt(c, x + w * f, y + h / 2); if (v !== null) { tested++; if (v) hidden++; } });
+ if (tested > 0 && hidden === tested) return;
+ out.push({ text: t.text, x: x, y: y, w: w, h: h, gx: x, gy: y, gw: w, gh: h, size: t.size * sy, alpha: t.alpha * op,
+ color: t.color, layer: t.layer, decor: t.decor, z: t.z, raw: true, canvas: id });
+ });
+ });
+ }
+
var ST = {
__stage: true,
version: VERSION,
@@ -1953,6 +2186,8 @@
ease: ease,
clamp: clamp,
lerp: function (a, b, p) { return a + (b - a) * p; },
+ /** Text drawn on a canvas inside `draw` is layered over other text on purpose: check does not call it an overlap. */
+ layer: function (draw) { canvasText.layer++; try { return draw(); } finally { canvasText.layer--; } },
/** Motion blur on an element while it moves fast (references/stage-api.md § Shutter blur). */
blur: function (target, opts) { return blurApi(target, opts); },
_setPlaying: function (v) { playingHint = !!v; },
@@ -1967,7 +2202,12 @@
scan: blurScan,
};
+ // for tools (showtime check): text on the page's canvases, and the counters the film API sets around its own text
+ W.__stCanvasText = canvasTexts;
+ W.__stCanvasTextFlags = canvasText;
+
if (RENDER) {
+ hookCanvasText();
installShim(RENDER.seed);
holdAnimations();
watchGL();
diff --git a/skills/showtime/runtime/xray-live/embed.js b/skills/showtime/runtime/xray-live/embed.js
index 5b6bee8..f9a7b00 100644
--- a/skills/showtime/runtime/xray-live/embed.js
+++ b/skills/showtime/runtime/xray-live/embed.js
@@ -80,10 +80,11 @@
if (!this._box || this._frame) return this._frame || null;
var src = this.getAttribute('src');
if (!src) return null;
- // a relative, http(s) or file address only (a post opened from disk loads its film): anything else
- // (javascript:, data:, vbscript:) leaves the poster
+ // a relative or http(s) address only, and a file one only from a page opened from disk (a post read offline
+ // loads its film; a web page could never load it): anything else (javascript:, data:, vbscript:) leaves the poster
var url; try { url = new URL(src, location.href); } catch (e) { return null; }
- if (url.protocol !== 'http:' && url.protocol !== 'https:' && url.protocol !== 'file:') return null;
+ var fromDisk = location.protocol === 'file:';
+ if (url.protocol !== 'http:' && url.protocol !== 'https:' && !(url.protocol === 'file:' && fromDisk)) return null;
var hit = parseInt(this.getAttribute('hit'), 10);
var f = D.createElement('iframe');
f.className = 'stx-frame';
diff --git a/skills/showtime/runtime/xray-live/live.js b/skills/showtime/runtime/xray-live/live.js
index a3d4b13..a49521f 100644
--- a/skills/showtime/runtime/xray-live/live.js
+++ b/skills/showtime/runtime/xray-live/live.js
@@ -67,13 +67,13 @@
X.mech.draw = function (k) {
if (!events && k.ev) events = evCopy(k.ev);
var label0 = k.label, mine = [], g = k.g;
- k.label = function (text, at, dx, dy, on) {
+ k.label = function (text, at, dx, dy, on, opts) {
var nm = String(text), isHot = !!hot && nm.toLowerCase() === hot, la = k.labelAlpha, rect = null;
if (partNames.indexOf(nm) < 0) partNames.push(nm);
if (hot && !isHot) k.labelAlpha = (la == null ? 1 : la) * 0.35;
var own = Object.prototype.hasOwnProperty.call(g, 'fillRect'), fr = g.fillRect;
g.fillRect = function (x, y, w, h) { if (!rect) rect = { x: x, y: y, w: w, h: h }; return fr.apply(g, arguments); };
- try { return label0.call(this, text, at, dx, dy, on || isHot); } finally {
+ try { return label0.call(this, text, at, dx, dy, on || isHot, opts); } finally {
if (own) g.fillRect = fr; else delete g.fillRect;
var shown = (la == null ? 1 : la) * (k.alpha == null ? 1 : k.alpha);
k.labelAlpha = la;
diff --git a/skills/showtime/scripts/check.mjs b/skills/showtime/scripts/check.mjs
index a9e29d2..ebc27b7 100644
--- a/skills/showtime/scripts/check.mjs
+++ b/skills/showtime/scripts/check.mjs
@@ -317,6 +317,9 @@ async function main() {
const contrastWorst = new Map(); // lid -> finding data
const unmeasured = new Set();
const layoutSeen = new Set();
+ // text-over-text pairs already reported (by their strings): the dense timeline reports each pair once
+ const overlapSeen = new Set();
+ const pairKey = (a, b) => [String(a).replace(/\s+/g, ' ').trim(), String(b).replace(/\s+/g, ' ').trim()].sort().join('\u0000');
const fontChecked = new Set();
const platformFonts = new Map(); // family -> {custom, glyphs, sample}
let pageFamilies = null; // @font-face families the page has loaded (lowercase), read once
@@ -447,7 +450,7 @@ async function main() {
const bx = { x: 64 * W / 1080, y: 220 * H / 1920, r: (1080 - 164) * W / 1080, b: (1920 - 480) * H / 1920 };
if ((r.x < bx.x - 2 || r.y < bx.y - 2 || r.x + r.w > bx.r + 2 || r.y + r.h > bx.b + 2) && !layoutSeen.has(key('safe'))) {
layoutSeen.add(key('safe'));
- add(dsev('warning'), 'safe_zone', `canvas text "${snip(tx.text)}" is outside the vertical safe zone at ${fmtTime(st)} (${edgesOutside(r, bx)}; app UI covers it)${dnote}`, { t: st, rect: rnd(r), source: 'canvas', text: snip(tx.text, 24),
+ add(dsev('warning'), 'safe_zone', `canvas text "${snip(tx.text)}" is outside the vertical safe zone at ${fmtTime(st)} (${edgesOutside(r, bx)}; app UI covers it)${dnote}`, { t: st, rect: rnd(r), source: 'canvas', text: snip(String(tx.text).replace(/\s+/g, ' ').trim(), 24),
fix: `keep text inside x ${Math.round(bx.x)}-${Math.round(bx.r)}, y ${Math.round(bx.y)}-${Math.round(bx.b)}` });
}
} else if (inside > 0.99) {
@@ -481,6 +484,7 @@ async function main() {
for (let j = i + 1; j < items.length && j < 120; j++) {
const A = items[i].rect, B = items[j].rect;
if (items[i].text === items[j].text) continue; // outline/shadow passes of the same string
+ if (items[i].layer || items[j].layer) continue; // layered over other text on purpose ({layer: true}, F.layer)
if (!items[i].readable || !items[j].readable) continue; // small UI text behind a headline is layering, not a collision
const ox = Math.min(A.x + A.w, B.x + B.w) - Math.max(A.x, B.x), oy = Math.min(A.y + A.h, B.y + B.h) - Math.max(A.y, B.y);
if (ox <= 1 || oy <= 1) continue;
@@ -488,6 +492,7 @@ async function main() {
const k = `canvas:ov:${[items[i].key, items[j].key].sort().join('~')}`;
if (frac > 0.25 && !layoutSeen.has(k)) {
layoutSeen.add(k);
+ overlapSeen.add(pairKey(items[i].text, items[j].text));
add('warning', 'text_overlap', `canvas text "${snip(items[i].text, 30)}" overlaps "${snip(items[j].text, 30)}" (${Math.round(frac * 100)}%) at ${fmtTime(st)}`, { t: st, source: 'canvas',
fix: 'move one of them, or make sure they are not on screen at the same time' });
}
@@ -668,6 +673,7 @@ async function main() {
if (layoutSeen.has(k)) continue;
layoutSeen.add(k);
const A = byBid.get(x), B = byBid.get(y);
+ overlapSeen.add(pairKey(A.text, B.text));
// a chart still growing or morphing (data-st-moving: hbar rows gliding past each other): a note
const mv = A.moving || B.moving ? MOVING_NOTE : '';
(mv ? (sev, code, msg, extra) => add('info', code, msg + mv, extra) : (sev, code, msg, extra) => addD(A.decor || B.decor ? { decor: true } : null, sev, code, msg, extra))('warning', 'text_overlap', `"${snip(A.text, 30)}" overlaps "${snip(B.text, 30)}" (${Math.round(frac * 100)}% of the smaller text's glyphs${px ? `, ${px}px deep` : ''}) at ${fmtTime(st)}`, { t: st, selector: `${A.sel} | ${B.sel}`, overlap_px: px,
@@ -1018,6 +1024,38 @@ async function main() {
const activeClips = []; // per sample: clips ([data-start]) showing
const textShown = []; // per sample: any readable text (DOM or canvas)
// the phone check's size part over the whole timeline: per readable text, its on-screen size at every step
+ // text over text on the grid, not only at the samples: pair -> { a, b, source, first, last, step, run, best, frac,
+ // px, op, done, again }. A step counts toward a run when neither text's opacity moved since the step before (a
+ // collision holds still; a crossfade's texts are fading in and out) or both stayed at 0.5 or more and the one that
+ // moved turned back (a blinking label over a still one), so `best` >= 1 means two settled steps in a row. The first such stretch is the one reported;
+ // `again` says the pair met again later.
+ const ovRuns = new Map();
+ const sbox = { x: 64 * W / 1080, y: 220 * H / 1920, r: (1080 - 164) * W / 1080, b: (1920 - 480) * H / 1920 };
+ const sbRuns = new Map(); // canvas text outside the vertical safe box: id -> { text, start, first, last, total, worst, rect }
+ const wordTracks = new Map(); // labelled numbers on the last step, by words: [{ id, text, x, y }] (trackWords)
+ const ovDropped = { n: 0, t: 0 }; // texts past the pairing cap on the worst step (not checked for overlap)
+ const notePair = (source, a, b, frac, px, gt, si, aa, ba, id) => {
+ // DOM pairs by element (a counter that changes value is one text), canvas pairs by their strings
+ const key = id || pairKey(a, b);
+ const r = ovRuns.get(key) || { a, b, source, first: null, last: gt, step: -2, run: 0, best: 0, frac: 0, px: 0, op: null };
+ if (r.done) { if (r.step !== si - 1) r.again = true; r.step = si; return; }
+ if (r.best >= 1 && r.step !== si - 1) { r.done = true; r.again = true; r.step = si; return; } // a later meeting
+ // held: both still, or both at 0.5 or more with each one that moved having turned back since the step before
+ // (a blink or a pulse; a fade in, a fade out or a crossfade keeps going one way)
+ const da = r.op ? aa - r.op[0] : 0, db = r.op ? ba - r.op[1] : 0;
+ const turned = (d, prev) => Math.abs(d) <= 0.05 || (prev !== undefined && Math.abs(prev) > 0.05 && Math.sign(prev) !== Math.sign(d));
+ const held = r.op && ((Math.abs(da) <= 0.05 && Math.abs(db) <= 0.05) ||
+ (Math.min(r.op[0], r.op[1], aa, ba) >= 0.5 && r.d && r.step === si - 1 && turned(da, r.d[0]) && turned(db, r.d[1])));
+ const settled = r.step === si - 1 && held;
+ r.run = settled ? r.run + 1 : 0;
+ if (settled && r.first === null) r.first = r.prevT;
+ if (r.run > r.best) r.best = r.run;
+ if (frac > r.frac) { r.frac = frac; r.px = px; }
+ r.d = r.step === si - 1 ? [da, db] : null;
+ r.step = si; r.last = gt; r.prevT = gt; r.op = [aa, ba];
+ if (!settled || r.run === 1) { r.a = a; r.b = b; } // the strings as they read when the overlap settled
+ ovRuns.set(key, r);
+ };
const sizeRuns = new Map(); // key -> { text, source, caption, sel, obs: [[t, px]] }
const sizeSeen = (key, text, px, gt, extra) => {
if (!(px > 0)) return;
@@ -1032,7 +1070,18 @@ async function main() {
activeClips.push(await sess.page.evaluate(() => document.querySelectorAll('[data-start][data-active]').length));
await auditCaptionZone(gt);
let anyText = false;
- const snap = await sess.page.evaluate(textSnapshot, { width: W, height: H, full: false });
+ const snap = await sess.page.evaluate(textSnapshot, { width: W, height: H, full: false, overlaps: true });
+ const si = okGrid.length - 1;
+ // canvas text on this step: the stage's records of every page canvas (raw fillText/strokeText), plus the film
+ // API's F.text records below; all in frame pixels
+ const stepTexts = (await sess.page.evaluate(() => (window.__stCanvasText ? window.__stCanvasText() : [])).catch(() => []))
+ .filter((t) => t.x < W && t.y < H && t.x + t.w > 0 && t.y + t.h > 0); // off the frame: not on screen
+ const bidText = new Map(snap.blocks.map((b) => [b.bid, b]));
+ for (const [x, y, frac, px] of snap.overlaps || []) {
+ const A = bidText.get(x), B = bidText.get(y);
+ if (!A || !B || A.decor || B.decor || A.moving || B.moving || A.text === B.text || inTx(gt)) continue;
+ notePair('dom', A.text, B.text, frac, px, gt, si, A.opacity, B.opacity, `dom:${[x, y].sort().join('~')}`);
+ }
for (const blk of snap.blocks) {
if (!blocksById.has(blk.bid)) blocksById.set(blk.bid, blk);
const on = blk.opacity >= 0.5 && blk.onCanvas >= 0.6;
@@ -1045,10 +1094,27 @@ async function main() {
if (last && gt - last[1] <= stepS * 1.5) last[1] = gt; else runs.push([gt, gt]);
vis.set(blk.bid, runs);
}
+ const filmNow = new Set(); // the film API's texts on this step, measured below
if (isFilm) {
const fi = await filmInfo();
auditCovers(fi, gt);
const kx = fi && fi.width ? W / fi.width : 1, ky = fi && fi.height ? H / fi.height : 1;
+ {
+ // text under a card drawn after it (a callout, the step band, a caption plate) is not on screen
+ const cards = ((fi && fi.covers) || []).filter((c) => c.kind !== 'dim');
+ const hidden = (tx, r) => cards.some((c) => {
+ if (!(tx.z < c.z)) return false;
+ const cx = c.x * kx, cy = c.y * ky, cw = c.w * kx, ch = c.h * ky;
+ const ox = Math.min(r.x + r.w, cx + cw) - Math.max(r.x, cx), oy = Math.min(r.y + r.h, cy + ch) - Math.max(r.y, cy);
+ return ox > 0 && oy > 0 && (ox * oy) / (r.w * r.h) >= 0.5;
+ });
+ for (const tx of (fi && fi.texts) || []) {
+ const r = { x: tx.x * kx, y: tx.y * ky, w: tx.w * kx, h: tx.h * ky };
+ if (hidden(tx, r) || r.x >= W || r.y >= H || r.x + r.w <= 0 || r.y + r.h <= 0) continue;
+ const g = tx.gw > 0 ? [tx.gx * kx, tx.gy * ky, tx.gw * kx, tx.gh * ky] : [r.x, r.y, r.w, r.h];
+ stepTexts.push({ ...tx, x: r.x, y: r.y, w: r.w, h: r.h, gx: g[0], gy: g[1], gw: g[2], gh: g[3], size: (tx.size || 0) * ky });
+ }
+ }
const now = new Set();
// text painted on an F.caption plate is the voice's words, read along with it (like DOM data-caption)
const plates = ((fi && fi.covers) || []).filter((c) => c.kind === 'caption');
@@ -1060,7 +1126,7 @@ async function main() {
if (r.w * r.h <= 0 || (ix * iy) / (r.w * r.h) < 0.6) continue;
const k = String(tx.text).replace(/\s+/g, ' ').trim();
if (!k || now.has(k)) continue;
- now.add(k);
+ now.add(k); filmNow.add(k);
anyText = true;
if (tx.decor) cdecor.add(k);
if (tx.flash) cflash.add(k);
@@ -1073,8 +1139,94 @@ async function main() {
cvis.set(k, runs);
}
}
+ // each canvas text's identity across steps: a labelled counter by its words, followed from step to step (see
+ // trackWords) so a sibling with the same words ("Level 9" beside "Level n") does not split it per value
+ const stepIds = new Map(trackWords(wordTracks, stepTexts.filter((tx) => tx && tx.text && !tx.dom).map((tx) => {
+ const text = String(tx.text).replace(/\s+/g, ' ').trim(), r = tx.gw > 0 ? { x: tx.gx, y: tx.gy } : tx;
+ const id = textIdOf(tx, text, r);
+ return { tx, text, x: r.x, y: r.y, id: id[0] === 't' ? `t${tx.canvas || ''}:${text}` : id };
+ })).map((it) => [it.tx, it.id]));
+ // raw canvas text (the stage's records of fillText/strokeText on any page canvas) is measured for size too, by that
+ // identity; a text the film API measured above is not counted twice
+ if (!inTx(gt)) {
+ for (const tx of stepTexts) {
+ if (!tx || !tx.raw || !tx.text || tx.decor || (tx.alpha ?? 1) * colorAlpha(tx.color) < 0.5) continue;
+ const k = String(tx.text).replace(/\s+/g, ' ').trim();
+ if (!k || filmNow.has(k) || !(tx.w > 0 && tx.h > 0)) continue;
+ const ix = Math.max(0, Math.min(tx.x + tx.w, W) - Math.max(tx.x, 0)), iy = Math.max(0, Math.min(tx.y + tx.h, H) - Math.max(tx.y, 0));
+ if ((ix * iy) / (tx.w * tx.h) < 0.6) continue;
+ sizeSeen(`canvas:${stepIds.get(tx)}`, k, tx.size || 0, gt, { source: 'canvas', caption: false });
+ }
+ }
+ // the vertical safe box between the samples too: canvas text (any page canvas, F.text) that feed UI covers.
+ // Per text (its identity from trackWords, above): counted when it sits outside two steps in a row without
+ // moving, or for 1 s in all (a label sliding in through the margin is neither)
+ if (H > W && !inTx(gt)) {
+ for (const tx of stepTexts) {
+ if (!tx || !tx.text || tx.decor || (tx.alpha ?? 1) * colorAlpha(tx.color) < 0.5 || (tx.size || 0) < Math.min(W, H) * 0.022) continue;
+ const g = tx.gw > 0 ? { x: tx.gx, y: tx.gy, w: tx.gw, h: tx.gh } : { x: tx.x, y: tx.y, w: tx.w, h: tx.h };
+ const text = String(tx.text).replace(/\s+/g, ' ').trim();
+ if (!text || g.w <= 1 || g.h <= 1) continue;
+ const ix = Math.max(0, Math.min(g.x + g.w, W) - Math.max(g.x, 0)), iy = Math.max(0, Math.min(g.y + g.h, H) - Math.max(g.y, 0));
+ if ((ix * iy) / (g.w * g.h) < 0.5) continue; // mostly off the frame: on its way in or out
+ const past = Math.max(sbox.x - g.x, sbox.y - g.y, g.x + g.w - sbox.r, g.y + g.h - sbox.b);
+ if (!(past > 2)) continue;
+ const id = stepIds.get(tx), r = sbRuns.get(id) || { text, start: gt, first: null, last: gt, si: -2, at: null, total: 0, worst: 0 };
+ if (r.si === si - 1 && Math.abs(r.at.x - g.x) + Math.abs(r.at.y - g.y) <= 2 && r.first === null) r.first = r.lastT;
+ r.total += stepS;
+ if (past > r.worst) { r.worst = past; r.rect = { ...g }; r.text = text; }
+ r.si = si; r.at = g; r.last = gt; r.lastT = gt;
+ sbRuns.set(id, r);
+ }
+ }
+ if (!inTx(gt)) { // mid-transition the two scenes overlap on purpose, as for DOM pairs
+ const cp = canvasTextPairs(stepTexts, [1, 1], Math.min(W, H) * 0.022, null);
+ if (cp.dropped > ovDropped.n) Object.assign(ovDropped, { n: cp.dropped, t: gt });
+ for (const p of cp) notePair('canvas', p.a, p.b, p.frac, p.px, gt, si, p.aa, p.ba, `cv:${[p.ai, p.bi].sort().join('~')}`);
+ }
+ // DOM text over canvas text (a paragraph over a chart's labels): the DOM blocks' painted glyphs against the
+ // canvas records. A DOM text on its own opaque plate (a caption pill) hides the canvas text under it.
+ if (stepTexts.length && !inTx(gt)) {
+ // a caption on its own plate hides what is under it; other badges over canvas text are reported
+ const domTexts = snap.blocks.filter((b) => !b.decor && !b.moving && !b.rotated && !(b.plate && b.caption) && b.onCanvas > 0 && b.irect && b.irect.w > 1)
+ .map((b) => ({ text: b.text, dom: b.bid, alpha: b.opacity * (b.colorAlpha ?? 1), size: b.fontSize * (b.scale || 1), gx: b.irect.x, gy: b.irect.y, gw: b.irect.w, gh: b.irect.h }));
+ const mp = canvasTextPairs([...domTexts, ...stepTexts], [1, 1], Math.min(W, H) * 0.022, null, true);
+ if (mp.dropped > ovDropped.n) Object.assign(ovDropped, { n: mp.dropped, t: gt });
+ for (const p of mp) {
+ const [d, c] = p.ad ? [p.a, p.b] : [p.b, p.a];
+ notePair('dom+canvas', d, c, p.frac, p.px, gt, si, p.ad ? p.aa : p.ba, p.ad ? p.ba : p.aa, `mix:${p.ad || p.bd}~${p.ad ? p.bi : p.ai}`);
+ }
+ }
textShown.push(anyText);
}
+ // text over text between the samples: a pair on two grid steps in a row or more (a crossfade's single frame is
+ // not a collision), once per pair, with when it starts and how long it lasts
+ for (const [key, r] of ovRuns) {
+ const tk = pairKey(r.a, r.b);
+ if (r.best < 1 || overlapSeen.has(key) || overlapSeen.has(tk)) continue;
+ overlapSeen.add(key);
+ overlapSeen.add(tk);
+ const span = (r.last - r.first >= stepS * 1.5 ? ` from ${fmtTime(r.first)} to ${fmtTime(r.last)}` : ` at ${fmtTime(r.first)}`) + (r.again ? ', and again later' : '');
+ add('warning', 'text_overlap', `${r.source === 'canvas' ? 'canvas text' : 'text'} "${snip(r.a, 30)}" overlaps ${r.source === 'dom+canvas' ? 'canvas text ' : ''}"${snip(r.b, 30)}" (${Math.round(r.frac * 100)}% of the smaller text's glyphs, ${r.px}px deep)${span}`,
+ { t: r.first, source: r.source, grid: true, overlap_px: r.px, texts: [r.a, r.b], until: r.last,
+ fix: `move one of them by at least ${r.px + 4}px, or make sure they are not on screen at the same time; text layered on purpose: {layer: true} (F.text) or F.layer(() => ...)` });
+ }
+ for (const r of sbRuns.values()) {
+ if (r.first === null && r.total < 1 - 1e-6) continue;
+ const t0 = r.first ?? r.start, snipped = snip(r.text, 24);
+ // already reported at a sample time (the same words): one finding per text
+ if (findings.some((f) => f.code === 'safe_zone' && f.source === 'canvas' && f.text === snipped)) continue;
+ // a text that went back inside in between says so: its time outside in all, not one long stretch
+ const gaps = r.total < r.last - r.start - stepS * 1.5;
+ const span = r.last - t0 >= stepS * 1.5 ? `${gaps ? 'at times ' : ''}from ${fmtTime(t0)} to ${fmtTime(r.last)}${gaps ? ` (${(r.total).toFixed(1)} s in all)` : ''}` : `at ${fmtTime(t0)}`;
+ add('warning', 'safe_zone', `canvas text "${snip(r.text)}" is outside the vertical safe zone ${span} (${edgesOutside(r.rect, sbox)}; app UI covers it)`,
+ { t: t0, until: r.last, grid: true, rect: rnd(r.rect), source: 'canvas', text: snipped, past_px: Math.round(r.worst),
+ fix: `keep text inside x ${Math.round(sbox.x)}-${Math.round(sbox.r)}, y ${Math.round(sbox.y)}-${Math.round(sbox.b)}` });
+ }
+ if (ovDropped.n > 0) {
+ add('info', 'text_overlap', `${ovDropped.n} texts on screen at ${fmtTime(ovDropped.t)} were past the ${PAIR_CAP} compared per kind and not checked for text over text`,
+ { t: ovDropped.t, grid: true, dropped: ovDropped.n, fix: 'mark UI-mockup detail as decor (fewer texts to compare), or check that part by eye' });
+ }
// size: judged on the median size over the text's life (an entrance that starts small is not a small text)
for (const [key, r] of sizeRuns) {
const px = r.obs.map((o) => o[1]).sort((x, y) => x - y);
@@ -1405,7 +1557,8 @@ async function main() {
}
} catch (e) {
if (e && e.browserStuck) throw e;
- add('info', 'webgpu_probe_failed', `the WebGPU probe did not run: ${String(e.message || e).split('\n')[0]}`);
+ // a warning, like cut_probe_failed: a probe that did not run is never a clean check
+ add('warning', 'webgpu_probe_failed', `the WebGPU probe did not run: ${String(e.message || e).split('\n')[0]}`);
}
// WebGL looks (fluted-glass, tilt-shift, liquid-metal, mesh-gradient, god-rays, marble, metaballs;
// runtime/effects/gl.js): each one records its size, its passes and what they cost per frame without a GPU
@@ -1487,7 +1640,8 @@ async function main() {
}
} catch (e) {
if (e && e.browserStuck) throw e;
- add('info', 'cut_probe_failed', `the first frames after the cuts were not probed: ${String(e.message || e).split('\n')[0]}`);
+ // a warning, not info: a cut walk that did not run must never read as a clean check (--strict fails on it)
+ add('warning', 'cut_probe_failed', `the first frames after the cuts were not probed: ${String(e.message || e).split('\n')[0]}`);
} finally { if (sess2) { await closeSoon(sess2.close()); sess2 = null; } }
report.timings.cuts = Date.now() - t;
}
@@ -1782,6 +1936,105 @@ function firstFamily(font) {
}
/** Canvas fillStyle ('#rrggbb', '#rgb', 'rgb(a)(...)') -> [r,g,b] or null (gradients/patterns). */
+/** The alpha in a CSS colour string (rgba(), hsla(), #rrggbbaa, #rgba), else 1. */
+function colorAlpha(s) {
+ if (typeof s !== 'string') return 1;
+ const v = s.trim().toLowerCase();
+ let m = /^#([0-9a-f]{4}|[0-9a-f]{8})$/.exec(v);
+ if (m) return parseInt(m[1].length === 4 ? m[1][3] + m[1][3] : m[1].slice(6), 16) / 255;
+ m = /^(?:rgba|hsla)\([^)]*[,/]\s*([\d.]+)(%?)\s*\)$/.exec(v) || /^(?:rgb|hsl)\([^)]*\/\s*([\d.]+)(%?)\s*\)$/.exec(v);
+ if (m) return Math.max(0, Math.min(1, m[2] ? +m[1] / 100 : +m[1]));
+ return 1;
+}
+
+/**
+ * Text drawn over other text on one canvas frame (film texts, F.text and raw fillText/strokeText alike): pairs
+ * whose painted glyph boxes overlap by more than OVERLAP_FRAC of the smaller one, both visible (effective alpha:
+ * globalAlpha x the colour's own alpha, >= 0.15) and at least one solid (>= 0.5) and readable (>= minPx). Not a
+ * collision: the same string twice (shadow or outline passes), decor, {layer: true} / F.layer, text a card hides.
+ * texts: Film.frameInfo().texts or the stage's canvas records; k: [kx, ky] to frame pixels; hidden(tx, rect) -> true
+ * when a card covers it. mixed: the texts include DOM blocks (dom: their bid) and only DOM-over-canvas pairs count.
+ */
+const OVERLAP_FRAC = 0.15, PAIR_CAP = 300, NUMERIC = /^[-+–−]?[\d\s.,:%$€£×x/]*\d[\d\s.,:%$€£×x/]*$/;
+/** A text's identity across grid steps: a DOM block by element; a number (a counter that changes every frame) by where
+ * it sits; a labelled number ("Frame 12", "TICK 175") by its canvas and its words with the digits blanked, moving or
+ * not (see splitSharedWords); any other text by its string. `r`: its box in frame pixels. */
+function textIdOf(tx, text, r) {
+ return tx.dom ? `d${tx.dom}` : NUMERIC.test(text) ? `n${tx.canvas || ''}@${Math.round(r.x / 16)},${Math.round(r.y / 16)}`
+ : /\d/.test(text) ? `m${tx.canvas || ''}:${text.replace(/\d+(?:[.,]\d+)*/g, '#')}` : `t${text}`;
+}
+/** A labelled number is one text by its words alone (a counter, moving or not) only while it is the one text with those
+ * words on its canvas in this step; two labels with the same words ("ORBIT 1", "ORBIT 2") are each their own string,
+ * so each is followed as it moves. `items`: one step's {id, text}; their ids are changed in place. */
+function splitSharedWords(items) {
+ const byWords = new Map();
+ for (const it of items) if (it.id[0] === 'm') byWords.set(it.id, (byWords.get(it.id) || new Set()).add(it.text));
+ for (const it of items) if (it.id[0] === 'm' && byWords.get(it.id).size > 1) it.id = `t${it.text}`;
+ return items;
+}
+/** Labelled numbers followed across grid steps (the safe box and size rules). Texts with the same words on one canvas
+ * ("Level 3", "Level 9") are matched to the last step's texts with those words: the same string first (a label that
+ * moves), then the nearest (a counter whose number changes); a lone one keeps the words' id, as in splitSharedWords,
+ * and each other one gets its own. `tracks`: words id -> last step's list, updated in place; `items`: {id, text, x, y}. */
+function trackWords(tracks, items) {
+ const groups = new Map();
+ for (const it of items) if (it.id[0] === 'm') (groups.get(it.id) || groups.set(it.id, []).get(it.id)).push(it);
+ for (const [words, now] of groups) {
+ const prev = (tracks.get(words) || []).slice(), used = new Set(), out = [], rest = [], fresh = [];
+ const take = (it, i) => { it.id = prev[i].id; used.add(it.id); prev.splice(i, 1); out.push(it); };
+ for (const it of now) { const i = prev.findIndex((p) => p.text === it.text); if (i >= 0) take(it, i); else rest.push(it); }
+ for (const it of rest) {
+ let bi = -1, bd = Infinity;
+ prev.forEach((p, i) => { const d = Math.hypot(p.x - it.x, p.y - it.y); if (d < bd) { bd = d; bi = i; } });
+ if (bi >= 0) take(it, bi); else fresh.push(it);
+ }
+ fresh.sort((a, b) => a.y - b.y || a.x - b.x);
+ let n = 0;
+ for (const it of fresh) {
+ if (used.has(words)) { while (used.has(`${words}#${++n}`)); it.id = `${words}#${n}`; } else it.id = words;
+ used.add(it.id); out.push(it);
+ }
+ tracks.set(words, out.map((it) => ({ id: it.id, text: it.text, x: it.x, y: it.y })));
+ }
+ for (const words of [...tracks.keys()]) if (!groups.has(words)) tracks.delete(words);
+ return items;
+}
+function canvasTextPairs(texts, k, minPx, hidden, mixed) {
+ const items = [];
+ for (const tx of texts || []) {
+ if (!tx || !tx.text || tx.decor || tx.layer) continue;
+ const alpha = (tx.alpha ?? 1) * colorAlpha(tx.color);
+ if (alpha < 0.15) continue;
+ const g = tx.gw > 0 ? { x: tx.gx, y: tx.gy, w: tx.gw, h: tx.gh } : { x: tx.x, y: tx.y, w: tx.w, h: tx.h };
+ const r = { x: g.x * k[0], y: g.y * k[1], w: g.w * k[0], h: g.h * k[1] };
+ if (r.w <= 1 || r.h <= 1 || (hidden && hidden(tx, r))) continue;
+ const text = String(tx.text).replace(/\s+/g, ' ').trim();
+ if (!text) continue; // a space drawn on its own paints nothing
+ items.push({ text, r, alpha, readable: (tx.size || 0) * k[1] >= minPx, dom: tx.dom || null, id: textIdOf(tx, text, r) });
+ }
+ splitSharedWords(items);
+ const out = [];
+ const pair = (A, B) => {
+ if (A.text === B.text) return;
+ if (Math.max(A.alpha, B.alpha) < 0.5 || !(A.readable || B.readable)) return;
+ const ox = Math.min(A.r.x + A.r.w, B.r.x + B.r.w) - Math.max(A.r.x, B.r.x), oy = Math.min(A.r.y + A.r.h, B.r.y + B.r.h) - Math.max(A.r.y, B.r.y);
+ if (ox <= 1 || oy <= 1) return;
+ const frac = (ox * oy) / Math.min(A.r.w * A.r.h, B.r.w * B.r.h);
+ if (frac > OVERLAP_FRAC) out.push({ a: A.text, b: B.text, frac, px: Math.round(Math.min(ox, oy)), aa: A.alpha, ba: B.alpha, ad: A.dom, bd: B.dom, ai: A.id, bi: B.id });
+ };
+ // at most PAIR_CAP texts a side are compared (DOM and canvas each when mixed); out.dropped counts the rest
+ if (mixed) {
+ const dom = items.filter((x) => x.dom), cv = items.filter((x) => !x.dom);
+ out.dropped = Math.max(0, dom.length - PAIR_CAP) + Math.max(0, cv.length - PAIR_CAP);
+ for (const A of dom.slice(0, PAIR_CAP)) for (const B of cv.slice(0, PAIR_CAP)) pair(A, B);
+ } else {
+ out.dropped = Math.max(0, items.length - PAIR_CAP);
+ const some = items.slice(0, PAIR_CAP);
+ for (let i = 0; i < some.length; i++) for (let j = i + 1; j < some.length; j++) pair(some[i], some[j]);
+ }
+ return out;
+}
+
function parseColor(s) {
if (typeof s !== 'string') return null;
const v = s.trim().toLowerCase();
diff --git a/skills/showtime/scripts/export.mjs b/skills/showtime/scripts/export.mjs
index 3a201a4..fa49a57 100644
--- a/skills/showtime/scripts/export.mjs
+++ b/skills/showtime/scripts/export.mjs
@@ -3,10 +3,10 @@ import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { startServer } from './server.mjs';
-import { parseCli, runMain, resolveProject, jobDir, freshPath, info, warn, c, fmtBytes, fmtDuration, parseTime, UserError } from './lib/cli.mjs';
+import { parseCli, runMain, resolveProject, jobDir, freshPath, info, warn, c, fmtBytes, fmtDuration, parseTime, UserError, runPyCli } from './lib/cli.mjs';
import { resolveFF } from './lib/ff.mjs';
import { audioInputs } from './lib/audio.mjs';
-import { resolveJobDir } from './lib/studio/paths.mjs';
+import { resolveJobDir, enclosingJob } from './lib/studio/paths.mjs';
import { probeProject } from './lib/export/probe.mjs';
import { collectFiles, isMedia, isText, isJs, isCss, pruneFontFamilies, preferWoff2 } from './lib/export/collect.mjs';
import { minifyJs, minifyCss, pruneParts } from './lib/export/minify.mjs';
@@ -42,7 +42,8 @@ const SPEC = {
'outside) is written next to the export. --no-questions exports a plain player.',
'The file makes no network request. Default output: ./showtime-out/<title>-<timestamp>/<title>.html',
'A job (folder or name, as qa takes it) exports its project/ folder into the job folder;',
- '`<job> --folder out` writes the folder version to ./out/.',
+ '`<job> --folder out` writes the folder version to ./out/. A project inside a job, or the command run from',
+ 'inside one, writes into that job too (a live page or figure is noted in its job.json).',
'',
'Audio: auto = the procedural score played live (streamed from the first second, tiny file) when',
'that is all the sound, otherwise',
@@ -127,6 +128,25 @@ const SPEC = {
const MB = 1000 * 1000; // decimal MB, like fmtBytes and platform limits
+/** The job folder (one with a job.json) holding p, within 4 levels up and never past showtime-out/; else null. */
+function ledgerJob(p) {
+ const j = enclosingJob(p);
+ return j && fs.existsSync(path.join(j, 'job.json')) ? j : null;
+}
+
+/** True when the project folder dir is inside job, or is the project its job.json or render.json names. */
+export function jobHolds(job, dir) {
+ const real = (q) => { try { return fs.realpathSync(q); } catch { return path.resolve(q); } };
+ const d = real(dir), j = real(job), rel = path.relative(j, d);
+ if (rel === '' || (rel.split(path.sep)[0] !== '..' && !path.isAbsolute(rel))) return true;
+ for (const f of ['job.json', 'render.json']) {
+ let p = null;
+ try { p = JSON.parse(fs.readFileSync(path.join(j, f), 'utf8')).project; } catch { /* no such file */ }
+ if (typeof p === 'string' && p && real(path.resolve(j, p)) === d) return true;
+ }
+ return false;
+}
+
/**
* A job argument -> { job, project } (its project/ folder), or null for a project folder or page. A job without
* a project/ folder is an error that says so (never "start a new project": the job has one somewhere else).
@@ -252,12 +272,25 @@ async function main() {
}
if (out !== want) addWarn(`${want} exists; writing ${path.basename(out)} instead (exports never overwrite)`);
} else {
- const dir = a.job ? resolveJobDir(a.job) : (fromJob && !a['out-dir'] ? fromJob.job : jobDir(proj.slug, a['out-dir']));
+ // a project inside a job, or the command run from inside the job of the project being exported: the export goes
+ // into that job (it used to make a new showtime-out/<title>-<time>/ folder nested in it); run from another
+ // project's job, the page goes where it always did
+ const cwdJob = !a.job && !fromJob && !a['out-dir'] ? enclosingJob(process.cwd()) : null;
+ const inJob = !a.job && !fromJob && !a['out-dir']
+ ? (enclosingJob(proj.dir) || (cwdJob && jobHolds(cwdJob, proj.dir) ? cwdJob : null)) : null;
+ const dir = a.job ? resolveJobDir(a.job) : (fromJob && !a['out-dir'] ? fromJob.job : (inJob || jobDir(proj.slug, a['out-dir'])));
if (!dir || !fs.existsSync(dir)) throw new UserError(`no job named "${a.job}"`, 'list jobs with `showtime job list`');
out = freshPath(path.join(dir, folder ? `${proj.slug}-html` : `${proj.slug}${liveSuffix}.html`));
}
- if (xrayLive) return exportXrayLive({ a, proj, out, title, target, maxMb, warnings, addWarn, T0 });
- if (a.interactive) return exportFigure({ a, proj, out, title, target, maxMb, warnings, addWarn, T0 });
+ // an export written into a job is noted in its job.json (the live page or figure is not a final: an event)
+ const job = ledgerJob(out);
+ const noteExport = job ? async (kind) => {
+ const r = await runPyCli(['job', 'note', job, '--event', `export html --interactive ${path.relative(job, out)} (${kind})`], { timeout: 120000 });
+ if (r.code !== 0) addWarn(`could not record the export in ${path.join(job, 'job.json')}: ${(r.stderr || '').trim().split('\n').pop()}`);
+ return r.code === 0 ? job : null;
+ } : null;
+ if (xrayLive) return exportXrayLive({ a, proj, out, title, target, maxMb, warnings, addWarn, T0, noteExport });
+ if (a.interactive) return exportFigure({ a, proj, out, title, target, maxMb, warnings, addWarn, T0, noteExport });
const workDir = fs.mkdtempSync(path.join(os.tmpdir(), 'showtime-export-'));
const server = await startServer({ root: proj.dir, port: 0 });
@@ -556,7 +589,7 @@ function sizeError(total, maxMb, files, poster, audioPack, { mode, html, scoreOn
runMain(main);
/** --interactive: the live figure, one offline file (scripts/lib/export/figure.mjs). */
-function exportFigure({ a, proj, out, title, target, maxMb, warnings, addWarn, T0 }) {
+async function exportFigure({ a, proj, out, title, target, maxMb, warnings, addWarn, T0, noteExport }) {
// a project still named after the template (or nothing) takes its scene's title: the page's <title> and og:title
const info = sceneInfo(proj.dir);
if (!a.title && info.title && (!title || title === TEMPLATE_TITLE || genericTitle(title) || title === proj.slug)) title = info.title;
@@ -569,7 +602,8 @@ function exportFigure({ a, proj, out, title, target, maxMb, warnings, addWarn, T
}
fs.mkdirSync(path.dirname(out), { recursive: true });
fs.writeFileSync(out, r.html);
- const report = { output: out, interactive: true, page: r.page, bytes: r.bytes, mb: +(r.bytes / MB).toFixed(2), max_mb: maxMb, title, target,
+ const job = noteExport ? await noteExport('the live figure') : null;
+ const report = { output: out, interactive: true, ...(job ? { job } : {}), page: r.page, bytes: r.bytes, mb: +(r.bytes / MB).toFixed(2), max_mb: maxMb, title, target,
files: r.files.length, fonts_dropped: r.fontsDropped, largest: r.files.slice().sort((x, y) => y.bytes - x.bytes).slice(0, 6), warnings, seconds: +((Date.now() - T0) / 1000).toFixed(1) };
if (a.json) process.stdout.write(JSON.stringify(report, null, 2) + '\n');
else {
diff --git a/skills/showtime/scripts/lib/audit.mjs b/skills/showtime/scripts/lib/audit.mjs
index 86dd592..98e6c04 100644
--- a/skills/showtime/scripts/lib/audit.mjs
+++ b/skills/showtime/scripts/lib/audit.mjs
@@ -63,10 +63,14 @@ export function textSnapshot(o) {
}
const cnv = document.createElement('canvas'); cnv.width = cnv.height = 1;
const g = cnv.getContext('2d', { willReadFrequently: true });
+ const rgbaCache = new Map();
function rgba(str) {
+ if (rgbaCache.has(str)) return rgbaCache.get(str);
g.clearRect(0, 0, 1, 1); g.fillStyle = '#000'; g.fillStyle = str; g.fillRect(0, 0, 1, 1);
const d = g.getImageData(0, 0, 1, 1).data;
- return [d[0], d[1], d[2], d[3] / 255];
+ const v = [d[0], d[1], d[2], d[3] / 255];
+ rgbaCache.set(str, v);
+ return v;
}
let nextId = Number(document.documentElement.getAttribute('data-st-next') || 1);
function idOf(el, attr) {
@@ -169,6 +173,7 @@ export function textSnapshot(o) {
function paintsOpaque(e) {
if (e.hasAttribute && e.hasAttribute('data-st-gl')) return true; // a WebGL transition frame (opaque)
const s = cs(e);
+ if (/text/.test(s.webkitBackgroundClip || s.backgroundClip || '')) return false; // gradient text paints its letters only
if (rgba(s.backgroundColor)[3] >= 0.9) return true;
const bi = s.backgroundImage;
return !!bi && bi !== 'none' && /gradient\(/.test(bi) && !/url\(/.test(bi) && !TRANSLUCENT.test(bi);
@@ -256,6 +261,37 @@ export function textSnapshot(o) {
} finally {
hitStyle.remove();
}
+ // turned text: a rotated element's client rects are axis-aligned bounds, taller than its letters by about
+ // width x sin(angle). Text is judged as turned (and left out of box overlaps) when that adds more than half its
+ // own height: kinetic rows at -8 degrees are, a sticker tilted 2 degrees is not. The angle adds up the ancestors'.
+ const angCache = new Map();
+ function angleOf(el) {
+ if (!el || el.nodeType !== 1 || el === document.body) return 0;
+ if (angCache.has(el)) return angCache.get(el);
+ const t = cs(el).transform;
+ let a = 0;
+ if (t && t !== 'none') { try { const m = new DOMMatrix(t); a = Math.atan2(m.b, m.a); } catch { a = 0; } }
+ a += angleOf(el.parentElement);
+ angCache.set(el, a);
+ return a;
+ }
+ function rotatedOf(el) {
+ const a = angleOf(el);
+ if (Math.abs(Math.sin(a)) < 0.005) return false;
+ const w = el.offsetWidth || 0, h = el.offsetHeight || 0;
+ return Math.abs(Math.sin(a)) * w > 0.5 * Math.abs(Math.cos(a)) * h;
+ }
+ // a text on its own opaque plate (a caption pill, a badge): whatever canvas text lies under it is hidden there.
+ // A plate is a small box (<= 25% of the frame) with no canvas inside it (a canvas inside would paint above it).
+ function plateOf(el) {
+ for (let e = el, i = 0; e && e !== document.body && i < 6; e = e.parentElement, i++) {
+ if (e.hasAttribute('data-start')) return false;
+ if (opacity(e) < 0.9 || !paintsOpaque(e)) continue;
+ const r = e.getBoundingClientRect();
+ return r.width * r.height <= 0.25 * W * H && !e.querySelector('canvas');
+ }
+ return false;
+ }
const blocks = new Map();
const leaves = [];
for (const leaf of leafMap.values()) {
@@ -276,6 +312,9 @@ export function textSnapshot(o) {
const fs = (parseFloat(s.fontSize) || 0) * svgScale(leaf.el);
blk.opacity = Math.max(blk.opacity, op);
blk.fontSize = Math.max(blk.fontSize, fs);
+ // text painted by its background (background-clip: text, a gradient title) reads at full strength whatever `color` says
+ blk.colorAlpha = /text/.test(s.webkitBackgroundClip || s.backgroundClip || '') && ((s.backgroundImage && s.backgroundImage !== 'none') || rgba(s.backgroundColor)[3] > 0) ? 1
+ : Math.max(blk.colorAlpha || 0, rgba(s.webkitTextFillColor && s.webkitTextFillColor !== s.color && !/rgba\(0, 0, 0, 0\)/.test(s.webkitTextFillColor) ? s.webkitTextFillColor : s.color)[3]);
if (o.full) {
const outlined = (s.textShadow && s.textShadow !== 'none') || parseFloat(s.webkitTextStrokeWidth) > 0;
const clipText = /text/.test(s.webkitBackgroundClip || s.backgroundClip || '');
@@ -323,12 +362,13 @@ export function textSnapshot(o) {
const iv = blk.ibox || v;
out.push({ bid: blk.bid, text: blk.text, len: blk.len, rect, opacity: +blk.opacity.toFixed(3), fontSize: blk.fontSize, scale: +blk.scale.toFixed(3), decor: blk.decor, flash: blk.flash, sel: blk.sel,
clipped, offCanvas, onCanvas: inside, caption: blk.caption, moving: !!(blk.el.closest && blk.el.closest('[data-st-moving]')), vrect: { x: v.x, y: v.y, w: v.r - v.x, h: v.b - v.y },
- irect: { x: iv.x, y: iv.y, w: Math.max(0, iv.r - iv.x), h: Math.max(0, iv.b - iv.y) } });
+ irect: { x: iv.x, y: iv.y, w: Math.max(0, iv.r - iv.x), h: Math.max(0, iv.b - iv.y) },
+ ...(o.full || o.overlaps ? { rotated: rotatedOf(blk.el), plate: plateOf(blk.el), colorAlpha: +(blk.colorAlpha ?? 1).toFixed(3) } : {}) });
}
const res = { blocks: out };
- if (o.full) {
+ if (o.full || o.overlaps) { // o.overlaps: only the text-over-text pairs (check's dense timeline)
const overlaps = [];
- const vis = out.filter((b) => b.opacity >= 0.5 && b.onCanvas > 0 && b.rect.w * b.rect.h > 4);
+ const vis = out.filter((b) => b.opacity >= 0.5 && b.onCanvas > 0 && b.rect.w * b.rect.h > 4 && !b.rotated);
const byId = new Map([...blocks.values()].map((b) => [b.bid, b.el]));
for (let i = 0; i < vis.length && i < 150; i++) {
for (let j = i + 1; j < vis.length && j < 150; j++) {
@@ -343,6 +383,8 @@ export function textSnapshot(o) {
}
}
res.overlaps = overlaps;
+ }
+ if (o.full) {
// SVG labels (chart values and axes, map names), pair by pair within each <svg>, on their painted
// glyphs. The overlap test above only fires past 15% of the smaller text, so labels that touch or
// sit shoulder to shoulder ("−0.02−0.01") pass it: here glyphs that touch at all, or labels side by
@@ -828,6 +870,7 @@ export function elementSnapshot(o) {
const paintsOpaque = (e) => {
if (e.hasAttribute('data-st-gl') || /^(IMG|VIDEO)$/.test(e.tagName)) return true;
const s = cs(e);
+ if (/text/.test(s.webkitBackgroundClip || s.backgroundClip || '')) return false; // gradient text paints its letters only
if (alphaOf(s.backgroundColor) >= 0.9) return true;
const bi = s.backgroundImage || '';
return /gradient\(/.test(bi) && !/url\(/.test(bi) && !TRANSLUCENT.test(bi);
diff --git a/skills/showtime/scripts/lib/export/collect.mjs b/skills/showtime/scripts/lib/export/collect.mjs
index a3904cc..417be30 100644
--- a/skills/showtime/scripts/lib/export/collect.mjs
+++ b/skills/showtime/scripts/lib/export/collect.mjs
@@ -41,6 +41,15 @@ function abs(spec, fromPath) {
}
/** Rewrite relative/root import specifiers and import.meta.url to absolute virtual URLs. -> {text, deps} */
+/**
+ * The page's own <style> blocks, each replaced by fn(m, attrs, text), never one inside an inline <script> or an HTML
+ * comment: a script's "<style>@font-face { src: url(...) }" string is code and stays byte for byte.
+ */
+export function replaceOwnStyles(html, fn) {
+ return html.replace(/<!--[\s\S]*?-->|<script\b[^>]*>[\s\S]*?<\/script\s*>|<style\b([^>]*)>([\s\S]*?)<\/style>/gi,
+ (m, attrs, text) => (attrs === undefined ? m : fn(m, attrs, text)));
+}
+
export function rewriteJs(text, filePath) {
const deps = new Set();
const fix = (spec) => {
diff --git a/skills/showtime/scripts/lib/export/figure.mjs b/skills/showtime/scripts/lib/export/figure.mjs
index 8dd01e3..287a792 100644
--- a/skills/showtime/scripts/lib/export/figure.mjs
+++ b/skills/showtime/scripts/lib/export/figure.mjs
@@ -7,7 +7,7 @@ import fs from 'node:fs';
import path from 'node:path';
import { skillDir, nodeModulesDir } from '../deps.mjs';
import { UserError } from '../cli.mjs';
-import { addCodePoints, pruneFontFaces } from './collect.mjs';
+import { addCodePoints, pruneFontFaces, replaceOwnStyles } from './collect.mjs';
import { minifyJs, minifyCss } from './minify.mjs';
import { notices } from './build.mjs';
@@ -165,10 +165,17 @@ export function packFigure(o) {
files.push({ url: r.url, bytes: r.buf.length, kind: 'style' });
const k = `\u0000C${styles.length}\u0000`; styles.push({ text: r.text, url: r.url }); return k;
});
+ // the page's own <style> blocks that name a file (a project's @font-face url("fonts/x.woff2"), a background image):
+ // their files are packed like a stylesheet's, relative to the page (the policy allows only data: fonts and images)
+ html = replaceOwnStyles(html, (m, attrs, text) => {
+ if (!/url\(/i.test(text)) return m;
+ const k = `\u0000C${styles.length}\u0000`; styles.push({ text, url: '/figure.html', attrs }); return k;
+ });
// the characters any text can show: the page, its scripts (the scene's words, the figure's own) and styles
const used = new Set();
addCodePoints(used, html.replace(/<[^>]+>/g, ' '));
scripts.forEach((s) => addCodePoints(used, s));
+ styles.forEach((st) => { if (st.attrs !== undefined) addCodePoints(used, st.text); }); // the page's own <style> text (content: "...")
let fontsDropped = 0;
const cssOut = styles.map((st) => {
let css = st.text;
@@ -189,7 +196,7 @@ export function packFigure(o) {
const jsSafe = (t) => t.replace(/<\/(script)/gi, (m, w) => '<\\/' + w).replace(/<!--/g, '<\\x21--');
const jsOut = scripts.map((s) => jsSafe(o.minify === false ? s : minifyJs(s).text));
html = html.replace(/\u0000S(\d+)\u0000/g, (m, i) => `<script>\n${jsOut[+i]}\n</script>`);
- html = html.replace(/\u0000C(\d+)\u0000/g, (m, i) => `<style>\n${cssOut[+i].replace(/<\/style/gi, '<\\/style')}\n</style>`);
+ html = html.replace(/\u0000C(\d+)\u0000/g, (m, i) => `<style${styles[+i].attrs || ''}>\n${cssOut[+i].replace(/<\/style/gi, '<\\/style')}\n</style>`);
const attr = (v) => String(v).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/"/g, '&quot;');
// function replacers throughout: a title with $& or $' is text, never a replacement pattern
if (o.title) html = html.replace(/<title>[^<]*<\/title>/i, () => `<title>${attr(o.title)}</title>`);
diff --git a/skills/showtime/scripts/lib/export/xray.mjs b/skills/showtime/scripts/lib/export/xray.mjs
index 0f0fc6a..2a54efc 100644
--- a/skills/showtime/scripts/lib/export/xray.mjs
+++ b/skills/showtime/scripts/lib/export/xray.mjs
@@ -18,7 +18,7 @@ import { skillDir, nodeModulesDir } from '../deps.mjs';
import { UserError, c, fmtBytes } from '../cli.mjs';
import { showCard, openHint } from '../delight.mjs';
import { figureFile, FIGURE_CSP } from './figure.mjs';
-import { addCodePoints, pruneFontFaces } from './collect.mjs';
+import { addCodePoints, pruneFontFaces, replaceOwnStyles } from './collect.mjs';
import { minifyJs, minifyCss } from './minify.mjs';
import { notices, stageForExport, showtimeVersion, safeJson } from './build.mjs';
import { fitFootage } from './fit.mjs';
@@ -194,6 +194,14 @@ export function packXrayLive(o) {
styles.push({ text: r.text, url: r.url });
return k;
});
+ // the page's own <style> blocks that name a file (a project's @font-face url("fonts/x.woff2"), a background image):
+ // their files are packed like a stylesheet's, relative to the page (the policy allows only data: fonts and images)
+ html = replaceOwnStyles(html, (m, attrs, text) => {
+ if (!/url\(/i.test(text)) return m;
+ const k = `\u0000C${styles.length}\u0000`;
+ styles.push({ text, url: base, attrs });
+ return k;
+ });
// ---- the live page's own parts
const pre = liveFile('pre.js'), liveJs = liveFile('live.js'), liveCss = liveFile('live.css');
@@ -220,6 +228,7 @@ export function packXrayLive(o) {
addCodePoints(used, html.replace(/<[^>]+>/g, ' '));
scripts.forEach((s) => addCodePoints(used, s.text));
addCodePoints(used, liveJs);
+ styles.forEach((st) => { if (st.attrs !== undefined) addCodePoints(used, st.text); }); // the page's own <style> text (content: "...")
Object.values(data).forEach((t) => addCodePoints(used, t)); // showtime.json, xray.json, notes.json (note names: ♯ ♭)
let fontsDropped = 0;
const cssOut = styles.map((st) => {
@@ -239,7 +248,7 @@ export function packXrayLive(o) {
const cfgTag = `<script type="application/json" id="xl-cfg">${safeJson({ data, live })}</script>`;
const jsOut = scripts.map((s) => (s.stage ? `${cfgTag}\n<script>\n${js(pre)}\n</script>\n<script>\n${js(s.text)}\n</script>` : `<script>\n${js(s.text)}\n</script>`));
html = html.replace(/\u0000S(\d+)\u0000/g, (m, i) => jsOut[+i]);
- html = html.replace(/\u0000C(\d+)\u0000/g, (m, i) => `<style>\n${cssOut[+i].replace(/<\/style/gi, '<\\/style')}\n</style>`);
+ html = html.replace(/\u0000C(\d+)\u0000/g, (m, i) => `<style${styles[+i].attrs || ''}>\n${cssOut[+i].replace(/<\/style/gi, '<\\/style')}\n</style>`);
// ---- head: charset, the notice, the policy, the title and the link-preview words
const title = live.title;
@@ -278,7 +287,7 @@ export function packXrayLive(o) {
}
/** The command: pack, fit the clip under --max-mb when it is the reason, write, report. */
-export async function exportXrayLive({ a, proj, out, title, target, maxMb, warnings, addWarn, T0 }) {
+export async function exportXrayLive({ a, proj, out, title, target, maxMb, warnings, addWarn, T0, noteExport }) {
const quiet = !!a.quiet;
const say = (m) => { if (!quiet) console.error(c.dim(m)); };
const p = packXrayLive({ projectDir: proj.dir, config: proj.config || {}, title, prompt: a.prompt, page: a.page, allFonts: !!a['all-fonts'],
@@ -316,7 +325,8 @@ export async function exportXrayLive({ a, proj, out, title, target, maxMb, warni
if (refit.length) addWarn(`the clip was re-encoded for this export only (${refit.map((r) => `${r.kbps} kb/s`).join(', ')}) to stay under ${maxMb} MB; the project's files are unchanged`);
fs.mkdirSync(path.dirname(out), { recursive: true });
fs.writeFileSync(out, html);
- const report = { output: out, interactive: true, kind: 'xray-live', layout: p.live.layout, tracked: p.live.tracked, page: p.page, bytes,
+ const job = noteExport ? await noteExport('the X-ray live page') : null;
+ const report = { output: out, interactive: true, kind: 'xray-live', ...(job ? { job } : {}), layout: p.live.layout, tracked: p.live.tracked, page: p.page, bytes,
mb: +(bytes / MB).toFixed(2), max_mb: maxMb, title: p.live.title, target, files: p.files.length, fonts_dropped: p.fontsDropped,
media: [...p.media].map(([u, m]) => ({ path: u, bytes: m.bytes.length })), footage_refit: refit, made: { prompt: p.live.made.prompt, commands: p.live.made.commands, guessed: p.live.made.guessed, own: p.live.made.own, unknown_mechanisms: unknown },
largest: p.files.slice().sort((x, y) => y.bytes - x.bytes).slice(0, 6), warnings, seconds: +((Date.now() - T0) / 1000).toFixed(1) };
diff --git a/skills/showtime/setup/package.json b/skills/showtime/setup/package.json
index f9e5e47..9f235e1 100644
--- a/skills/showtime/setup/package.json
+++ b/skills/showtime/setup/package.json
@@ -1,6 +1,6 @@
{
"name": "showtime-runtime",
- "version": "0.4.5",
+ "version": "0.4.6",
"private": true,
"description": "Node dependencies for showtime (installed by setup.py into ~/.showtime/node). Versions are pinned exactly. Icon sets are not installed here: they are fetched per icon on first use (manifest.json \"icon_packs\").",
"license": "MIT",
diff --git a/skills/showtime/setup/setup.py b/skills/showtime/setup/setup.py
index 586e863..4db9a37 100755
--- a/skills/showtime/setup/setup.py
+++ b/skills/showtime/setup/setup.py
@@ -1087,6 +1087,15 @@ class Installer:
miss_rec = [f for f in RECOMMENDED_FILTERS if f not in filters] + [e for e in RECOMMENDED_ENCODERS if e not in encoders]
return not miss_req, miss_req, miss_rec, v
+ def other_homes(self) -> List[Path]:
+ """Other showtime installs whose bin folder may be on PATH: the default ~/.showtime and the home the launcher
+ started with (SHOWTIME_HOME before --home replaced it), when they are not this one."""
+ out: List[Path] = []
+ for h in (plat.user_home() / ".showtime", Path(os.path.expanduser(_HOME_BEFORE)) if _HOME_BEFORE else None):
+ if h is not None and not _same_dir(h, self.home) and not any(_same_dir(h, o) for o in out):
+ out.append(h)
+ return out
+
def step_ffmpeg(self) -> Tuple[str, str]:
mode = self.args.ffmpeg
bindir = self.home / "bin"
@@ -1099,7 +1108,13 @@ class Installer:
v, bindir, ("; missing optional: " + ", ".join(rec)) if rec else "")
if mode in ("auto", "system"):
from st.ff import _system_candidates
+ others = [h / "bin" for h in self.other_homes()]
for cand in _system_candidates("ffmpeg"):
+ if any(_same_dir(Path(cand).parent, b) for b in others):
+ # `setup --home X` runs with the default home's bin first on PATH: its ffmpeg is another install's,
+ # not the system's, and X would have none once that install goes (or outside the launcher's PATH)
+ say(" ffmpeg %s belongs to another showtime install: not used, %s gets its own" % (cand, self.home))
+ continue
ok, req, rec, v = self._ff_check(cand)
probe = Path(cand).with_name(plat.exe("ffprobe"))
good_enough = ok and not [r for r in rec if r in ("zscale", "arnndn")] and probe.is_file()
@@ -2101,7 +2116,16 @@ def parse_args(argv: Optional[Sequence[str]] = None) -> argparse.Namespace:
return a
+_HOME_BEFORE: Optional[str] = None # SHOWTIME_HOME as setup found it (the launcher's home), before --home
+
+
+def _same_dir(a: Path, b: Path) -> bool:
+ return os.path.normcase(os.path.realpath(str(a))) == os.path.normcase(os.path.realpath(str(b)))
+
+
def main(argv: Optional[Sequence[str]] = None) -> int:
+ global _HOME_BEFORE
+ _HOME_BEFORE = os.environ.get("SHOWTIME_HOME") or None
args = parse_args(argv)
man = load_manifest()
home = Path(os.path.expanduser(args.home or os.environ.get("SHOWTIME_HOME") or "~/.showtime"))
diff --git a/skills/showtime/templates/tutorial/scenes.js b/skills/showtime/templates/tutorial/scenes.js
index 467256c..165676a 100644
--- a/skills/showtime/templates/tutorial/scenes.js
+++ b/skills/showtime/templates/tutorial/scenes.js
@@ -82,8 +82,11 @@ function drawTutorial(T, g, F) {
g.fillStyle = '#07080b';
g.fillRect(0, 0, F.W, F.H);
g.restore();
- F.reveal('Three steps. That’s it.', F.W / 2, F.H / 2 + 20, F.seg(T, CUE.outro + 0.1, CUE.outro + 0.9), {
- size: 96, weight: 800, align: 'center', tracking: -0.02,
+ // the line sits over the dimmed app on purpose: layered text, not a collision
+ F.layer(function () {
+ F.reveal('Three steps. That’s it.', F.W / 2, F.H / 2 + 20, F.seg(T, CUE.outro + 0.1, CUE.outro + 0.9), {
+ size: 96, weight: 800, align: 'center', tracking: -0.02,
+ });
});
}
}
diff --git a/skills/showtime/templates/xray/README.md b/skills/showtime/templates/xray/README.md
index 5b6a634..407e994 100644
--- a/skills/showtime/templates/xray/README.md
+++ b/skills/showtime/templates/xray/README.md
@@ -17,7 +17,10 @@ changes." (Erik Pålsson / Sounds of Changes, CC BY 3.0: keep the credit if you
- `cue.js`: the beats (the scan, the labels, the end card); set `endcard` to the clip's length.
- `xray.js`: the runtime (layout, drawing kit, the sync marker in the bottom-right corner: never cover it).
-9:16 puts the clip on top and the inside below it (in place as well when tracked), all text inside the reels
-safe box; 16:9 with a track draws in place over the whole frame (`"panel": true` keeps the schematic beside it);
+9:16 puts the clip on top, the inside below it (in place as well when tracked) and the sound strip over the
+counters, all inside the reels safe box (the drawing too: the platform's buttons sit right of x 916) and at
+the phone floor (43 px at 1920), the part labels in a column left of the drawing (two, left and right, when one
+can't hold them) and never over it, the mechanism's captions in a row above; 16:9 with a track draws
+in place over the whole frame (`"panel": true` keeps the schematic beside it);
16:9 without one puts the inside beside the clip. Library: typewriter, musicbox, switch (and the music entries).
The guide: `references/workflows/xray.md` (`showtime guide xray`).
diff --git a/skills/showtime/templates/xray/diagram.html b/skills/showtime/templates/xray/diagram.html
index d3bdfa2..269ee8f 100644
--- a/skills/showtime/templates/xray/diagram.html
+++ b/skills/showtime/templates/xray/diagram.html
@@ -194,7 +194,7 @@
el('receipt').textContent = cfg.receipt || (n + ' ' + nouns[1] + ' measured from the clip’s sound');
el('end-drawn').textContent = [cfg.drawn || 'Inside view: a generic manual typewriter, drawn, not this exact machine.', cfg.credit || ''].join(' ').trim();
var mk = el('xmark'); mk.style.left = (W - 10) + 'px'; mk.style.top = (H - 10) + 'px';
- S = { W: W, H: H, fps: fps, ev: ev, text: text, portrait: portrait, lay: lay, dur: (src.duration || cue('endcard', 9.4)), n: n };
+ S = { W: W, H: H, fps: fps, off: off, ev: ev, text: text, portrait: portrait, lay: lay, dur: (src.duration || Math.max(0.1, cue('endcard', 9.4) - off / fps)), n: n };
// the scene
var ctx = { events: ev, fps: fps, cue: window.CUE || {}, portrait: portrait, region: lay.region, safe: lay.safe, clip: lay.clip,
avoid: portrait ? '.xd-none' : null, theme: Diagram.themes[theme] };
@@ -210,13 +210,15 @@
var hot = cs.getPropertyValue('--xd-hot').trim() || '#FF6A3D', ink = cs.getPropertyValue('--ld-ink').trim() || '#EEF2F8', dim = cs.getPropertyValue('--xd-dim').trim();
g.clearRect(0, 0, w, h);
g.fillStyle = dim; g.fillRect(0, h / 2 - 1, w, 2);
+ // the recording's clock (it starts at film frame "xray".offset_frames), not the film's
+ var at = function (fr) { return Math.max(0, Math.min(1, ((fr - S.off) / S.fps) / S.dur)); };
S.ev.forEach(function (e) {
- var x = Math.round((e.frame / S.fps) / S.dur * (w - 4)) + 2, hh = Math.max(8, (0.3 + 0.7 * (e.strength || 0.5)) * (h - 6)), on = e.frame <= f;
+ var x = Math.round(at(e.frame) * (w - 4)) + 2, hh = Math.max(8, (0.3 + 0.7 * (e.strength || 0.5)) * (h - 6)), on = e.frame <= f;
g.globalAlpha = e.kind === 'skip' ? (on ? 0.55 : 0.25) : (on ? 1 : 0.32);
g.fillStyle = e.kind === 'skip' ? ink : hot; g.fillRect(x - 2, (h - hh) / 2, 4, hh);
});
g.globalAlpha = 1; g.fillStyle = ink;
- g.fillRect(Math.round(Math.min(1, (f / S.fps) / S.dur) * (w - 4)) + 1, 0, 2, h);
+ g.fillRect(Math.round(at(f) * (w - 4)) + 1, 0, 2, h);
}
function frame(t, fr) {
diff --git a/skills/showtime/templates/xray/index.html b/skills/showtime/templates/xray/index.html
index de7e43c..aefc8e5 100644
--- a/skills/showtime/templates/xray/index.html
+++ b/skills/showtime/templates/xray/index.html
@@ -7,7 +7,7 @@
<link rel="stylesheet" href="/_st/themes/fonts/bricolage-grotesque.css">
<link rel="stylesheet" href="/_st/themes/fonts/ibm-plex-mono.css">
<style>
- :root { --line: #8fd3ff; --ink: #e9f3ff; --muted: #a9bdd6; --hot: #ff4a3d; --ground: #070b16; }
+ :root { --line: #8fd3ff; --ink: #e9f3ff; --muted: #a9bdd6; --hot: #ff4a3d; --hotink: #ff7468; --ground: #070b16; }
html, body { margin: 0; background: var(--ground); }
.stage { background: var(--ground); }
.stage { position: relative; width: 100vw; height: 100vh; overflow: hidden; color: var(--ink); font-family: "IBM Plex Mono", monospace; }
@@ -15,24 +15,25 @@
.scan, .xbody { position: absolute; inset: 0; }
/* the radiograph (#clipx): the same clip, filtered by the theme (xray.js), shown only inside the tracked outline */
#cv { position: absolute; left: 0; top: 0; width: 100%; height: 100%; }
- .brand { position: absolute; left: 48px; top: 40px; font: 800 64px/1 "Bricolage Grotesque", sans-serif; text-shadow: 0 2px 18px var(--tagbg); }
+ /* 16:9: text 96 px (5%) from the left edge, the counters above the player controls (bottom 8%), 26 px and up */
+ .brand { position: absolute; left: 96px; top: 40px; font: 800 64px/1 "Bricolage Grotesque", sans-serif; text-shadow: 0 2px 18px var(--tagbg); }
.brand b { color: var(--hot); }
- .tag { position: absolute; left: 50px; top: 116px; font: 500 26px/1 "IBM Plex Mono", monospace; letter-spacing: .06em; text-transform: uppercase;
+ .tag { position: absolute; left: 96px; top: 116px; font: 500 26px/1 "IBM Plex Mono", monospace; letter-spacing: .06em; text-transform: uppercase;
background: var(--tagbg); padding: 9px 12px; border-radius: 4px; }
- .hud { position: absolute; left: 48px; bottom: 40px; display: flex; gap: 22px; align-items: flex-end; }
+ .hud { position: absolute; left: 96px; bottom: 96px; display: flex; gap: 22px; align-items: flex-end; }
.card { background: var(--card); border: 1px solid var(--edge); border-radius: 6px; padding: 14px 18px; min-width: 150px; }
.card b { display: block; font: 800 60px/1 "Bricolage Grotesque", sans-serif; font-variant-numeric: tabular-nums; }
- .card span { display: block; margin-top: 6px; font: 500 24px/1.2 "IBM Plex Mono", monospace; color: var(--muted); letter-spacing: .04em; text-transform: uppercase; }
+ .card span { display: block; margin-top: 6px; font: 500 26px/1.2 "IBM Plex Mono", monospace; color: var(--muted); letter-spacing: .04em; text-transform: uppercase; }
.paper { min-width: 430px; }
.paper b { font: 600 40px/1.25 "IBM Plex Mono", monospace; white-space: pre; }
- .paper b i { color: var(--hot); font-style: normal; }
- .end { position: absolute; top: 0; bottom: 0; right: 0; width: 900px; background: var(--card); z-index: 5; padding: 0 64px; box-sizing: border-box;
+ .paper b i { color: var(--hotink); font-style: normal; }
+ .end { position: absolute; top: 0; bottom: 0; right: 0; width: 900px; background: var(--ground); z-index: 5; padding: 0 64px; box-sizing: border-box;
display: flex; flex-direction: column; justify-content: center; opacity: 0; }
.end h2 { margin: 0; font: 800 84px/1.0 "Bricolage Grotesque", sans-serif; text-wrap: balance; }
- .end h2 em { color: var(--hot); font-style: normal; }
+ .end h2 em { color: var(--hotink); font-style: normal; }
.end p { margin: 26px 0 0; font: 500 26px/1.45 "IBM Plex Mono", monospace; }
.end .receipt { margin-top: 30px; border: 2px solid var(--line); border-radius: 6px; padding: 16px 20px; font: 500 26px/1.45 "IBM Plex Mono", monospace; color: var(--line); }
- .end .muted { color: var(--muted); font-size: 24px; }
+ .end .muted { color: var(--muted); font-size: 26px; }
/* phone (9:16): every word inside the reels safe box (x 64-916, y 220-1440), 43 px and up */
.portrait .brand { left: 64px; font-size: 68px; }
.portrait .tag { left: 64px; font-size: 43px; padding: 6px 12px; letter-spacing: .02em; }
@@ -41,6 +42,10 @@
.portrait .card span { font-size: 43px; letter-spacing: 0; }
.portrait .paper { flex: 1; min-width: 0; }
.portrait .paper b { font-size: 44px; line-height: 84px; }
+ .portrait.reels .card { padding: 8px 16px; } /* 136 px tall with its border: xray.js PHUD */
+ .portrait.reels .card b { font-size: 64px; }
+ .portrait.reels .card span { margin-top: 2px; }
+ .portrait.reels .paper b { font-size: 44px; line-height: 64px; } /* over .portrait.reels .card b */
.portrait .end { left: 0; width: auto; top: 0; bottom: 0; background: var(--ground); padding: 220px 164px 480px 64px; }
.portrait .end h2 { font-size: 92px; }
.portrait .end p, .portrait .end .receipt { font-size: 43px; line-height: 1.3; }
diff --git a/skills/showtime/templates/xray/xray.js b/skills/showtime/templates/xray/xray.js
index 8a95564..225565e 100644
--- a/skills/showtime/templates/xray/xray.js
+++ b/skills/showtime/templates/xray/xray.js
@@ -10,16 +10,25 @@
var X = window.XRAY = { mech: null, ready: false };
X.mechanism = function (m) { X.mech = m; };
+ // 9:16: the sound strip (tick height; the plate's room over the ticks for the caret; the whole plate's height), the
+ // HUD's height (index.html .portrait.reels .card) and the gaps; its labels are S.lpx (the phone floor, 2.2% of the
+ // height, and a pixel: 44 px at 1920)
+ var PSTRIP = { h: 56, pad: 22 }, PHUD = 136, PGAP = 12;
+ // the reels safe box as fractions of the frame (check's: x 64-916, y 220-1440 at 1080x1920)
+ var BOX = { x: 64 / 1080, r: 916 / 1080, y: 220 / 1920, b: 1440 / 1920 };
+ PSTRIP.block = PSTRIP.pad + PSTRIP.h + 16;
+
// palettes: dark = the radiograph (cyan lines on night), light = a blueprint on paper (navy lines); red = acting now
+ // (hotink: the red for text, 4.5:1 on the cards and the end card)
var THEMES = {
- dark: { l: [143, 211, 255], i: [233, 243, 255], bg: [7, 11, 22], h: [255, 74, 61], muted: '#a9bdd6', glow: 8,
+ dark: { l: [143, 211, 255], i: [233, 243, 255], bg: [7, 11, 22], h: [255, 74, 61], hotink: '#ff7468', muted: '#a9bdd6', glow: 8,
filter: 'grayscale(1) invert(1) brightness(.62) contrast(1.7) sepia(1) hue-rotate(165deg) saturate(2.6)' },
- light: { l: [24, 62, 120], i: [18, 30, 52], bg: [244, 240, 231], h: [214, 40, 57], muted: '#55627a', glow: 0,
+ light: { l: [24, 62, 120], i: [18, 30, 52], bg: [244, 240, 231], h: [214, 40, 57], hotink: '#a81b2b', muted: '#465267', glow: 0,
filter: 'grayscale(1) brightness(1.55) contrast(.62) sepia(.25)' }
};
function palette(name) {
var P = THEMES[name] || THEMES.dark, f = function (c) { return function (a) { return 'rgba(' + c.join(',') + ',' + a + ')'; }; };
- var C = { name: THEMES[name] ? name : 'dark', l: f(P.l), i: f(P.i), bg: f(P.bg), h: f(P.h), muted: P.muted, glow: P.glow, filter: P.filter };
+ var C = { name: THEMES[name] ? name : 'dark', l: f(P.l), i: f(P.i), bg: f(P.bg), h: f(P.h), hotink: P.hotink, muted: P.muted, glow: P.glow, filter: P.filter };
C.line = C.l(1); C.soft = C.l(name === 'light' ? .55 : .5); C.faint = C.l(name === 'light' ? .22 : .2); C.hot = C.h(1); C.ink = C.i(1);
C.ground = C.bg(1);
return C;
@@ -59,7 +68,7 @@
function apply(h, x, y) { var w = h[6] * x + h[7] * y + h[8]; return [(h[0] * x + h[1] * y + h[2]) / w, (h[3] * x + h[4] * y + h[5]) / w]; }
function affine(sx, sy, tx, ty) { return [sx, 0, tx, 0, sy, ty, 0, 0, 1]; }
function fit(box, r, pad) { // box [x0,y0,x1,y1] into rect {x,y,w,h}, aspect kept, centred
- var bw = box[2] - box[0], bh = box[3] - box[1], s = Math.min((r.w - 2 * pad) / bw, (r.h - 2 * pad) / bh);
+ var bw = box[2] - box[0], bh = box[3] - box[1], s = Math.max(1e-3, Math.min((r.w - 2 * pad) / bw, (r.h - 2 * pad) / bh));
return affine(s, s, r.x + (r.w - bw * s) / 2 - box[0] * s, r.y + (r.h - bh * s) / 2 - box[1] * s);
}
function bbox(pts) {
@@ -91,15 +100,25 @@
var info = ST.info(), W = info.width, H = info.height, fps = info.fps || 30;
var src = doc.source || {}, sw = src.width || 1920, sh = src.height || 1080, sfps = src.fps || fps;
var m = X.mech, track = doc.track && doc.track.H && doc.track.H.length ? doc.track : null;
- var portrait = H > W * 1.2, inplace = cfg.layout !== 'split' && !!track;
+ // reels: a frame at least 1.6 times as tall as wide (9:16) gets the reels box's layout; 4:5 keeps the portrait one
+ var portrait = H > W * 1.2, reels = H >= W * 1.6, inplace = cfg.layout !== 'split' && !!track;
var clip, panel = null, hud, lay = null;
if (portrait) { // phone: the clip on top, the inside below, all text in the reels safe box
var ch = W * sh / sw, cw = W;
if (ch > H * 0.36) { ch = H * 0.36; cw = ch * sw / sh; }
clip = { x: (W - cw) / 2, y: 0, w: cw, h: ch };
- var top = Math.max(H * 0.115, ch + 28), hudTop = H * 0.75 - 172;
- lay = { brand: top, tag: top + 76, panelTop: top + 150, hud: hudTop };
- panel = { x: 40, y: lay.panelTop, w: W - 80, h: hudTop - 16 - lay.panelTop };
+ var top = Math.max(H * 0.115, ch + 28);
+ if (reels) {
+ // the sound strip sits above the HUD, inside the safe box too: its plate ends PGAP px over the HUD (see strip());
+ // the panel (its frame too) ends at the safe box's right edge: right of it the platform's buttons cover the frame.
+ // A hand-set size too short for this layout gets a thin panel, never a negative (mirrored) one
+ var hudTop = H * 0.75 - PHUD, stripTop = hudTop - PGAP - PSTRIP.block;
+ lay = { brand: top, tag: top + 76, panelTop: top + 150, hud: hudTop, strip: stripTop };
+ panel = { x: 40 * W / 1080, y: lay.panelTop, w: BOX.r * W - 40 * W / 1080, h: Math.max(1, stripTop - PGAP - lay.panelTop) };
+ } else {
+ lay = { brand: top, tag: top + 76, panelTop: top + 150, hud: H * 0.75 - 172 };
+ panel = { x: 40, y: lay.panelTop, w: W - 80, h: lay.hud - 16 - lay.panelTop };
+ }
hud = 'portrait';
} else if (inplace && cfg.panel) { // 16:9 see-through with the panel beside it ("xray": {"panel": true})
var w3 = W * 0.6, h3 = w3 * sh / sw;
@@ -145,13 +164,21 @@
if (kind === 'event' && ti < text.length) o.ch = text[ti++];
return o;
});
+ // 9:16: a first fit; reelsLayout() then makes room for the part labels' columns and the captions
+ var pm = panel ? fit(m.box, panel, reels ? 12 : 24) : null;
+ if (pm && reels) pm[2] += BOX.r * W - 8 * W / 1080 - (m.box[2] * pm[0] + pm[2]);
S = { off: off, W: W, H: H, fps: fps, sfps: sfps, sw: sw, sh: sh, doc: doc, cfg: cfg, m: m, track: track, inplace: inplace,
- clip: clip, panel: panel, hud: hud, lay: lay, place: place, toFilm: toFilm, ev: ev, text: text, portrait: portrait,
- panelMap: panel ? fit(m.box, panel, 24) : null, dur: info.duration, notes: [] };
+ clip: clip, panel: panel, hud: hud, lay: lay, place: place, toFilm: toFilm, ev: ev, text: text, portrait: portrait, reels: reels,
+ panelMap: pm, dur: info.duration, notes: [], lpx: Math.ceil(H * 0.022) + 1 };
attachNotes(notesDoc);
+ if (reels) reelsLayout();
build();
X.ready = true;
}
+ // the recording's clock: the clip starts at film frame "xray".offset_frames, so a time of the recording (xray.json,
+ // notes.json and its tempo map, track_until) sits at film frame floor(t * fps) + off, and film frame f at (f - off) / fps
+ function recTime(f) { return (f - S.off) / S.fps; }
+ function filmFrame(t) { return Math.floor(t * S.fps + 1e-9) + S.off; }
// notes.json (pitches, from `showtime xray notes`): each note joins the event within 3 frames of it, so a
// mechanism can say WHICH tooth, string or key, from the sound itself
function attachNotes(nd) {
@@ -161,7 +188,7 @@
var src = (nd.notes && nd.notes.length ? nd.notes : (nd.drums || []));
S.notes = src.map(function (n, j) {
return { i: n.i != null ? n.i : j, pitch: n.pitch, name: n.name || n.piece, piece: n.piece, t: n.t,
- frame: Math.floor(n.t * S.fps + 1e-9) + S.off, end: n.end, velocity: n.velocity, confidence: n.confidence, hz: n.hz };
+ frame: filmFrame(n.t), end: n.end, velocity: n.velocity, confidence: n.confidence, hz: n.hz };
});
S.notes.forEach(function (n) {
var best = null, bd = 4;
@@ -183,8 +210,8 @@
var v = el(id); v.style.left = px(c.x); v.style.top = px(c.y); v.style.width = px(c.w); v.style.height = px(c.h);
});
el('scan').hidden = !S.inplace;
- var st = el('stage'); st.className = 'stage ' + S.hud + (S.inplace ? ' inplace' : '') + ' ' + C.name;
- [['--line', C.line], ['--ink', C.ink], ['--muted', C.muted], ['--hot', C.hot], ['--ground', C.ground],
+ var st = el('stage'); st.className = 'stage ' + S.hud + (S.reels ? ' reels' : '') + (S.inplace ? ' inplace' : '') + ' ' + C.name;
+ [['--line', C.line], ['--ink', C.ink], ['--muted', C.muted], ['--hot', C.hot], ['--hotink', C.hotink], ['--ground', C.ground],
['--card', C.bg(.84)], ['--edge', C.l(.35)], ['--tagbg', C.bg(.74)]].forEach(function (v) { st.style.setProperty(v[0], v[1]); });
el('clipx').style.filter = C.filter;
var cv = el('cv'); cv.width = S.W; cv.height = S.H;
@@ -222,7 +249,10 @@
var pr = function (x, y) { return apply(map, x, y); };
var scale = Math.sqrt(Math.abs(map[0] * map[4] - map[1] * map[3]));
var K = { g: g, view: view, f: f, t: t, alpha: alpha, C: C, ease: ST.ease, pr: pr, scale: scale, ev: S.ev, text: S.text, notes: S.notes, music: S.music, cfg: S.cfg, fps: S.fps, panel: S.panel,
- labels: view === 'panel' || !S.panel };
+ labels: view === 'panel' || !S.panel,
+ // the recording's clock (notes.json times and its tempo map are seconds of the recording, not the film):
+ // rt is this frame's time on it, frameAt(t) the film frame of a recording time t
+ rt: recTime(f), frameAt: filmFrame, off: S.off };
K.env = function (i) { // 0..1: the motion of event i, 1 exactly on its frame
var d = f - S.ev[i].frame;
if (d < -RISE || d > FALL) return 0;
@@ -242,7 +272,8 @@
S.ev.forEach(function (e, i) { if (e.kind === 'skip') return; var s = K.env(i); if (s > K.s) { K.s = s; K.cur = i; } });
K.hot = K.s > 0.05; K.ch = K.cur >= 0 ? S.ev[K.cur].ch : null; K.kind = K.cur >= 0 ? S.ev[K.cur].kind : null;
K.n = K.count('event');
- var lw = function (w) { return Math.max(1, w * (view === 'panel' ? Math.min(1.6, scale) : Math.min(1.4, scale * 1.2))); };
+ // 9:16 panel: heavier lines, so the drawing outweighs its 44 px labels
+ var lw = function (w) { return view === 'panel' && S.reels ? Math.max(1.5, w * scale * 1.6) : Math.max(1, w * (view === 'panel' ? Math.min(1.6, scale) : Math.min(1.4, scale * 1.2))); };
K.lw = lw;
K.path = function (pts, close) { g.beginPath(); pts.forEach(function (p, i) { var q = pr(p[0], p[1]); if (i) g.lineTo(q[0], q[1]); else g.moveTo(q[0], q[1]); }); if (close) g.closePath(); };
K.seg = function (a, b, col, w) { g.strokeStyle = col; g.lineWidth = lw(w); K.path([a, b]); g.stroke(); };
@@ -253,10 +284,31 @@
g.strokeStyle = col; g.lineWidth = lw(w); K.path(pts, true); g.stroke();
};
K.dot = function (p, r, col) { var q = pr(p[0], p[1]); g.fillStyle = col; g.beginPath(); g.arc(q[0], q[1], r, 0, Math.PI * 2); g.fill(); };
- K.label = function (text, at, dx, dy, on) {
+ // 9:16 panel: the labels sit in one column, each in the row the frame's dry run gave it (labelSlots), and each is
+ // drawn when the mechanism calls it, like at 16:9 (the live page reads a label's plate and dims it on that call)
+ var col = view === 'panel' && S.reels;
+ K.reels = col; // the 9:16 panel: labels in a column beside the drawing (keep names short)
+ // a mechanism's caption (its key, tempo, bar): in the 9:16 panel it goes to the caption row over the drawing, at
+ // the label size (the mechanism draws its own text when this is null, as at 16:9)
+ K.caption = col ? function (text, side, ink) {
+ if (K.collect) { K.caps.push({ s: String(text), side: side }); return; }
+ var px = S.lpx, right = side === 'right';
+ g.save(); g.setTransform(1, 0, 0, 1, 0, 0); g.shadowBlur = 0; g.globalAlpha = alpha * (K.labelAlpha == null ? 1 : K.labelAlpha);
+ g.font = '600 ' + px + 'px "IBM Plex Mono"'; g.fillStyle = ink; g.textBaseline = 'middle'; g.textAlign = right ? 'right' : 'left';
+ g.fillText(String(text), right ? BOX.r * S.W : BOX.x * S.W, S.panel.y + (S.capRow[right ? 'right' : 'left'] + 0.5) * (px + 12) + 1);
+ g.restore();
+ } : null;
+ // opts.keepCase: the label as written (guitar strings: e and E), else in capitals
+ K.label = function (text, at, dx, dy, on, opts) {
if (!K.labels) return;
- var p = pr(at[0], at[1]), r = view === 'panel' ? (S.portrait ? { x: S.W * 0.06, y: S.panel.y, w: S.W * 0.79, h: S.panel.h } : S.panel) : { x: 40, y: 170, w: S.W - 80, h: S.H - 400 };
+ var p = pr(at[0], at[1]), r = view === 'panel' ? (S.reels ? { x: BOX.x * S.W, y: S.panel.y, w: (BOX.r - BOX.x) * S.W, h: S.panel.h } : S.portrait ? { x: S.W * 0.06, y: S.panel.y, w: S.W * 0.79, h: S.panel.h } : S.panel) : { x: 40, y: 170, w: S.W - 80, h: S.H - 400 };
if (p[0] < r.x - 20 || p[0] > r.x + r.w + 20 || p[1] < r.y - 20 || p[1] > r.y + r.h + 20) return;
+ if (col) {
+ var name = opts && opts.keepCase ? String(text) : String(text).toUpperCase(), key = name + '@' + Math.round(p[0]) + ',' + Math.round(p[1]);
+ if (K.collect) K.collect.push({ label: name, p: p, at: at, key: key });
+ else if (K.slots && K.slots[key]) colLabel(K.slots[key], name, p, on);
+ return;
+ }
var size = S.portrait ? 34 : 28;
g.save(); g.font = '600 ' + size + 'px "IBM Plex Mono"'; g.shadowBlur = 0;
var label = String(text).toUpperCase(), w = g.measureText(label).width + 22, hgt = size + 16;
@@ -270,13 +322,186 @@
g.fillText(label, dx < 0 ? x - 11 : x + 11, y + 1);
g.restore();
};
+ // a label in its column: its leader (grey, so the only red lines are the mechanism's own) runs from the label to
+ // the column's edge, then to its part; the part acting now gets a red dot and its label turns red and bold (the
+ // mono font keeps one width in both weights, so a label never shifts when it turns red); at rest, the muted ink.
+ // A right column's plates end at the safe box's right edge; a two-line label is one plate
+ var colLabel = function (q, name, p, on) {
+ var px = S.lpx, x = q.side === 'right' ? BOX.r * S.W - q.w : BOX.x * S.W, edge = q.side === 'right' ? x : x + q.w;
+ g.save(); g.shadowBlur = 0; g.globalAlpha = alpha * (K.labelAlpha == null ? 1 : K.labelAlpha);
+ g.strokeStyle = C.i(on ? .6 : .45); g.lineWidth = 1.5;
+ g.beginPath(); g.moveTo(edge, q.y); g.lineTo(q.ex, q.y); g.lineTo(p[0], p[1]); g.stroke();
+ if (on) { g.fillStyle = C.hot; g.beginPath(); g.arc(p[0], p[1], 5, 0, Math.PI * 2); g.fill(); }
+ g.fillStyle = C.bg(.86); g.fillRect(x, q.y - q.h / 2, q.w, q.h);
+ g.font = (on ? '600' : '500') + ' ' + px + 'px "IBM Plex Mono"'; g.fillStyle = on ? C.hot : C.muted;
+ g.textBaseline = 'middle'; g.textAlign = 'left';
+ q.lines.forEach(function (l, i) { g.fillText(l, x + 11, q.y + 1 + (i - (q.lines.length - 1) / 2) * (px + 2)); });
+ g.restore();
+ };
return K;
}
+ // 9:16 panel: a dry run of the mechanism's drawing on a context that draws nothing collects the labels and captions
+ // it calls (only measureText is real)
+ var dry = null;
+ function dryContext() {
+ if (dry) return dry;
+ var c = document.createElement('canvas').getContext('2d'), st = {}, none = function () { return stub; };
+ var stub = new Proxy(function () {}, { get: function () { return none; }, apply: function () { return stub; } });
+ dry = new Proxy(c, {
+ get: function (o, k) { if (k === 'measureText') return o.measureText.bind(o); if (k in st) return st[k]; return typeof o[k] === 'function' ? none : o[k]; },
+ set: function (o, k, v) { st[k] = v; if (k === 'font') o.font = v; return true; },
+ deleteProperty: function (o, k) { delete st[k]; return true; }
+ });
+ return dry;
+ }
+ function dryRun(f) {
+ var K = kit(dryContext(), 'panel', f, f / S.fps, 1), n = {};
+ K.collect = []; K.caps = [];
+ S.m.draw(K);
+ // a label's id: its name and which call of that name it is in the frame (drums names two parts TOM)
+ K.collect.forEach(function (q) { n[q.label] = (n[q.label] || 0) + 1; q.id = q.label + '#' + n[q.label]; });
+ return K;
+ }
+ // a label's plate: its lines plus `pad` (16 px; 8 or 4 when a column would not hold its labels otherwise, with the
+ // gap between two plates 8, 4 or 2: the text stays 44 px)
+ var PADS = [[16, 8], [8, 4], [4, 2]];
+ function rowH(n, pad) { return S.lpx + pad + (n - 1) * (S.lpx + 2); }
+ // a label's lines: one, or two when it is wider than the layout's limit (split at a space); null when it can't fit
+ function wrapLabel(name, lim) {
+ var g = dryContext(), words = name.split(' '), lines = [], cur = '';
+ g.font = '500 ' + S.lpx + 'px "IBM Plex Mono"';
+ words.forEach(function (w) { var t = cur ? cur + ' ' + w : w; if (cur && g.measureText(t).width > lim) { lines.push(cur); cur = w; } else cur = t; });
+ lines.push(cur);
+ return lines.length <= 2 && lines.every(function (l) { return g.measureText(l).width <= lim; }) ? lines : null;
+ }
+ function labInfo(name, side, lim, pad) {
+ var g = dryContext(), lines = wrapLabel(name, lim) || [name];
+ g.font = '500 ' + S.lpx + 'px "IBM Plex Mono"';
+ var w = Math.max.apply(null, lines.map(function (l) { return g.measureText(l).width; })) + 22;
+ return { lines: lines, w: w, h: rowH(lines.length, pad), side: side };
+ }
+
+ // 9:16 panel, once at setup: the part labels' columns and the captions' rows, from dry runs of sampled frames (every
+ // event's frame and 4 frames after it, and every half second), so the drawing never moves between frames. Labels go
+ // in one column at the reels box's left edge, or in two (left and right, by which half of the drawing their part is
+ // in); a long label wraps to two lines; captions get a row at the panel's top, and a column starts under the rows
+ // whose captions reach over it. Of the layouts whose columns hold every sampled frame's labels, the one with the
+ // largest drawing wins (then fewer columns, then fewer wrapped labels); no column covers the drawing's box
+ function reelsLayout() {
+ var P = S.panel, px = S.lpx, x0 = BOX.x * S.W, xr = BOX.r * S.W, box = S.m.box, bw = box[2] - box[0], bh = box[3] - box[1];
+ var frames = [0], per = [], at = {}, caps = { left: 0, right: 0 }, g = dryContext(), step = Math.max(1, Math.round(S.fps / 2));
+ S.ev.forEach(function (e) { frames.push(e.frame, e.frame + 4); });
+ for (var f = step; f < Math.round(S.dur * S.fps); f += step) frames.push(f);
+ S.capRow = { left: 0, right: 0 };
+ frames.forEach(function (f) {
+ var K = dryRun(f);
+ g.font = '600 ' + px + 'px "IBM Plex Mono"';
+ K.caps.forEach(function (c) { caps[c.side] = Math.max(caps[c.side], g.measureText(c.s).width); });
+ per.push(K.collect.map(function (q) { (at[q.id] = at[q.id] || []).push(q.at[0]); return q.id; }));
+ });
+ // captions: left and right on one row when both fit, else the right one on a second row
+ var both = caps.left && caps.right, two = both && caps.left + caps.right + 24 > xr - x0;
+ S.capRow = { left: 0, right: two ? 1 : 0 };
+ var rows = []; // per caption row, the x span its captions take
+ if (caps.left) rows[0] = [[x0, x0 + caps.left]];
+ if (caps.right) (rows[S.capRow.right] = rows[S.capRow.right] || []).push([xr - caps.right, xr]);
+ var crow = px + 12, band = rows.length * crow;
+ var colTop = function (a, b) { // a column spanning x a..b starts under the last caption row over it
+ var top = P.y;
+ rows.forEach(function (r, i) { if (r && r.some(function (sp) { return sp[0] < b + 10 && sp[1] > a - 10; })) top = P.y + (i + 1) * crow; });
+ return top;
+ };
+ var names = Object.keys(at).sort(), cx = (box[0] + box[2]) / 2, bot = P.y + P.h, nm = function (id) { return id.slice(0, id.lastIndexOf('#')); };
+ var mid = {}; names.forEach(function (n) { mid[n] = at[n].reduce(function (a, b) { return a + b; }, 0) / at[n].length; });
+ var lims = [Infinity]; // wrap limits worth trying: every run of words' width
+ g.font = '500 ' + px + 'px "IBM Plex Mono"';
+ names.forEach(function (n) { var w = nm(n).split(' '); for (var i = 0; i < w.length; i++) for (var j = i + 1; j <= w.length; j++) lims.push(Math.ceil(g.measureText(w.slice(i, j).join(' ')).width)); });
+ lims = lims.filter(function (v, i) { return lims.indexOf(v) === i; }).sort(function (a, b) { return b - a; });
+ var best = null;
+ [1, 2].forEach(function (cols) {
+ lims.forEach(function (lim) { PADS.some(function (pg) {
+ var info = {}, wd = { left: 0, right: 0 }, wraps = 0, ok = true;
+ names.forEach(function (n) {
+ if (!wrapLabel(nm(n), lim)) ok = false;
+ var q = info[n] = labInfo(nm(n), cols === 2 && mid[n] >= cx ? 'right' : 'left', lim, pg[0]);
+ wd[q.side] = Math.max(wd[q.side], q.w); if (q.lines.length > 1) wraps++;
+ });
+ if (!ok || (cols === 2 && !wd.right)) return true;
+ var top = { left: colTop(x0, x0 + wd.left), right: colTop(xr - wd.right, xr) }, over = 0;
+ per.forEach(function (list) {
+ ['left', 'right'].forEach(function (side) {
+ var mine = list.filter(function (n) { return info[n].side === side; });
+ var h = mine.reduce(function (a, n) { return a + info[n].h; }, 0) + pg[1] * Math.max(0, mine.length - 1);
+ over = Math.max(over, h - (bot - top[side]));
+ });
+ });
+ var l = wd.left ? x0 + wd.left + 16 : P.x + 12, r = wd.right ? xr - wd.right - 16 : xr - 8;
+ var s = Math.max(1e-3, Math.min((r - l) / bw, (P.h - band - 24) / bh));
+ var c = { cols: cols, lim: lim, info: info, wd: wd, top: top, l: l, r: r, s: s, over: Math.max(0, over), wraps: wraps, pad: pg[0], gap: pg[1] };
+ var better = !best || (c.over < best.over - 0.5) || (Math.abs(c.over - best.over) <= 0.5 &&
+ (c.s > best.s + 1e-9 || (Math.abs(c.s - best.s) <= 1e-9 && (c.cols < best.cols || (c.cols === best.cols && c.wraps < best.wraps)))));
+ if (better) best = c;
+ return over <= 0; // it fits: no tighter plates
+ }); });
+ });
+ var top = P.y + band, h = P.h - band;
+ if (!names.length) { // no labels: the drawing fills the panel under the captions, at its right edge
+ S.panelMap = fit(box, { x: P.x, y: top, w: P.w, h: h }, 12);
+ S.panelMap[2] += xr - 8 - (box[2] * S.panelMap[0] + S.panelMap[2]);
+ S.lay2 = { cols: 0, info: {}, wd: { left: 0, right: 0 }, top: { left: P.y, right: P.y }, lim: Infinity, pad: 16, gap: 8 };
+ return;
+ }
+ var s = best.s, x = best.wd.right ? (best.l + best.r - bw * s) / 2 : best.r - bw * s; // one column: at the right edge
+ S.panelMap = affine(s, s, x - box[0] * s, top + (h - bh * s) / 2 - box[1] * s);
+ S.lay2 = best;
+ }
+ // this frame's rows: the labels of each column sorted by their part's height and spread so none sit on each other;
+ // two slanted leaders that cross swap places (equal rows swap their heights: each swap makes the leaders shorter in
+ // total, so this ends)
+ function labelSlots(view, f, t, alpha) {
+ var K = dryRun(f), list = K.collect, L = S.lay2, slots = {}, bot = S.panel.y + S.panel.h;
+ var side = function (q) {
+ if (L.info[q.id]) return L.info[q.id].side;
+ return L.cols === 2 && q.at[0] >= (S.m.box[0] + S.m.box[2]) / 2 ? 'right' : 'left';
+ };
+ ['left', 'right'].forEach(function (sd) {
+ var mine = list.filter(function (q) { return side(q) === sd; }), n = mine.length, i, top = L.top[sd];
+ if (!n) return;
+ mine.forEach(function (q) { var o = L.info[q.id] || labInfo(q.label, sd, L.lim, L.pad); q.lines = o.lines; q.w = o.w; q.h = o.h; });
+ mine.sort(function (a, b) { return a.p[1] - b.p[1]; });
+ var place = function () {
+ for (i = 0; i < n; i++) {
+ var q = mine[i], pv = mine[i - 1];
+ q.y = Math.max(top + q.h / 2, Math.min(bot - q.h / 2, q.p[1]), i ? pv.y + pv.h / 2 + L.gap + q.h / 2 : -Infinity);
+ }
+ for (i = n - 1; i >= 0; i--) { var nx = mine[i + 1]; mine[i].y = Math.min(mine[i].y, nx ? nx.y - nx.h / 2 - L.gap - mine[i].h / 2 : bot - mine[i].h / 2); }
+ };
+ place();
+ var ex = sd === 'right' ? BOX.r * S.W - L.wd.right - 10 : BOX.x * S.W + L.wd.left + 10;
+ var cross = function (a, b) {
+ var a0 = [ex, a.y], b0 = [ex, b.y];
+ return sideOf(a0, a.p, b0) * sideOf(a0, a.p, b.p) < 0 && sideOf(b0, b.p, a0) * sideOf(b0, b.p, a.p) < 0;
+ };
+ for (var pass = 0, swapped = true; swapped && pass < n * n; pass++) {
+ swapped = false;
+ for (i = 0; i < n && !swapped; i++) for (var j = i + 1; j < n && !swapped; j++) if (cross(mine[i], mine[j])) {
+ if (mine[i].h === mine[j].h) { var y = mine[i].y; mine[i].y = mine[j].y; mine[j].y = y; }
+ else { var tq = mine[i]; mine[i] = mine[j]; mine[j] = tq; place(); }
+ swapped = true;
+ }
+ }
+ mine.forEach(function (q) { slots[q.key] = { y: q.y, w: q.w, h: q.h, lines: q.lines, side: sd, ex: ex }; });
+ });
+ return slots;
+ }
+ function sideOf(a, b, c) { return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]); }
+
// ------------------------------------------------------------------ per frame
function drawView(g, view, f, t, alpha, clipRect) {
var K = kit(g, view, f, t, alpha);
K.labelAlpha = ST.progress(t, cue('labels', 1.4), cue('labels', 1.4) + 0.6, ST.ease.inOutCubic);
+ if (view === 'panel' && S.reels) K.slots = labelSlots(view, f, t, alpha);
g.save();
if (clipRect) { g.beginPath(); g.rect(clipRect.x, clipRect.y, clipRect.w, clipRect.h); g.clip(); }
g.globalAlpha = alpha; g.lineCap = 'round'; g.lineJoin = 'round';
@@ -286,23 +511,41 @@
}
function strip(g, f, t, alpha) {
- var portrait = S.hud === 'portrait', x0, w, y0, h = portrait ? 150 : 50;
- if (portrait) { x0 = 64; w = S.W * 0.79; y0 = S.H * 0.75 + 70; }
+ var reels = S.hud === 'portrait' && S.reels, x0, w, y0, h = reels ? PSTRIP.h : S.hud === 'portrait' ? 150 : 50, pad = reels ? PSTRIP.pad : 38;
+ if (reels) { x0 = BOX.x * S.W + 16; w = BOX.r * S.W - 16 - x0; y0 = S.lay.strip + PSTRIP.pad; } // its plate (16 px round the ticks) fills the safe box's width
+ else if (S.hud === 'portrait') { x0 = 64; w = S.W * 0.79; y0 = S.H * 0.75 + 70; }
else if (S.hud === 'side') { x0 = S.panel.x; w = S.panel.w; y0 = S.H - 100; }
else { x0 = S.W - 900; w = 852; y0 = S.H - 90; }
- var dur = (S.doc.source && S.doc.source.duration) || S.dur;
+ // with no measured length, the recording is taken to run from its start to the film's end
+ var dur = (S.doc.source && S.doc.source.duration) || Math.max(0.1, S.dur - S.off / S.fps);
+ // where a film frame sits on the recording: the clip starts at film frame "xray".offset_frames, so the strip's
+ // clock is the recording's (frame - off), not the film's; before the clip starts the caret waits at 0
+ var at = function (fr) { return Math.max(0, Math.min(1, recTime(fr) / dur)); };
+ // the label fits its room: a long mechanism word shrinks it to the readable floor (2.2% of the frame height: 24 px
+ // at 1080, 43 px at 1920), then drops "the clip's sound", then cuts the word with an ellipsis; it never runs past
+ // the plate. At 9:16 it sits on the ticks' row, left of them, in at most 56% of the strip
+ var one = String(S.m.one || 'an event'), px = reels ? S.lpx : S.hud === 'portrait' ? 24 : 26, floor = Math.ceil((reels ? S.H : Math.min(S.W, S.H)) * 0.022), room = reels ? w * 0.56 : w;
+ var label = ('the clip’s sound · red = ' + one).toUpperCase(), fits = function () { return g.measureText(label).width <= room; };
+ var fitLabel = function () {
+ g.font = '500 ' + px + 'px "IBM Plex Mono"';
+ while (!fits() && px > floor) { px--; g.font = '500 ' + px + 'px "IBM Plex Mono"'; }
+ if (!fits()) label = ('red = ' + one).toUpperCase();
+ while (!fits() && one.length > 1) { one = one.slice(0, -1); label = ('red = ' + one.replace(/\s+$/, '') + '…').toUpperCase(); }
+ };
g.save(); g.globalAlpha = alpha;
- g.fillStyle = C.bg(.8); g.fillRect(x0 - 16, y0 - 38, w + 32, h + 54);
+ var bx = x0, bw = w; // the ticks' span: the whole strip, or at 9:16 what the label leaves
+ if (reels) { fitLabel(); bx = x0 + g.measureText(label).width + 28; bw = x0 + w - bx; }
+ g.fillStyle = C.bg(.8); g.fillRect(x0 - 16, y0 - pad, w + 32, h + pad + 16);
S.ev.forEach(function (e) {
- var x = x0 + (e.frame / S.fps) / dur * w, hh = Math.max(6, (0.35 + 0.65 * (e.strength || 0.5)) * h);
+ var x = bx + at(e.frame) * bw, hh = Math.max(6, (0.35 + 0.65 * (e.strength || 0.5)) * h);
var on = e.frame <= f, col = e.kind === 'skip' ? (on ? C.i(.55) : C.i(.2)) : (on ? C.hot : C.h(.32));
g.fillStyle = col; g.fillRect(x - 2, y0 + h / 2 - hh / 2, 4, hh);
});
// now: a small caret over the ticks (no axis line, no full-height playhead: it must not read as a player's bar)
- var cx = x0 + Math.min(1, (f / S.fps) / dur) * w;
+ var cx = bx + at(f) * bw;
g.fillStyle = C.ink; g.beginPath(); g.moveTo(cx - 9, y0 - 8); g.lineTo(cx + 9, y0 - 8); g.lineTo(cx, y0 + 4); g.closePath(); g.fill();
- g.font = '500 ' + (portrait ? 24 : 18) + 'px "IBM Plex Mono"'; g.fillStyle = C.muted; g.textBaseline = 'bottom'; g.textAlign = 'left';
- g.fillText(('the clip’s sound · red = ' + (S.m.one || 'an event')).toUpperCase(), x0, y0 - 12);
+ if (reels) { g.fillStyle = C.muted; g.textBaseline = 'middle'; g.textAlign = 'left'; g.fillText(label, x0, y0 + h / 2); }
+ else { fitLabel(); g.fillStyle = C.muted; g.textBaseline = 'bottom'; g.textAlign = 'left'; g.fillText(label, x0, y0 - 12); }
g.restore();
}
@@ -321,8 +564,9 @@
el('xbody').style.clipPath = poly.length > 2 ? 'polygon(' + poly.join(', ') + ')' : 'none';
var sy = S.clip.y + S.clip.h * p;
el('scan').style.clipPath = 'inset(0 0 ' + px(Math.max(0, S.H - sy)) + ' 0)';
- // past "xray".track_until the see-through fades out instead of sliding off the object
- var hold = typeof S.cfg.track_until === 'number' ? 1 - ST.progress(f / S.fps, S.cfg.track_until, S.cfg.track_until + 0.3, ST.ease.inOutCubic) : 1;
+ // past "xray".track_until (the clip's seconds, so on the recording's clock) the see-through fades out instead
+ // of sliding off the object
+ var hold = typeof S.cfg.track_until === 'number' ? 1 - ST.progress(recTime(f), S.cfg.track_until, S.cfg.track_until + 0.3, ST.ease.inOutCubic) : 1;
el('scan').style.opacity = hold.toFixed(3);
drawView(g, 'inplace', f, t, show * hold, { x: 0, y: 0, w: S.W, h: Math.max(0, sy) });
if (p > 0 && p < 1) scanline(g, S.clip.x, S.clip.w, sy);
diff --git a/skills/showtime/tests/test_capture.py b/skills/showtime/tests/test_capture.py
index e362273..93053f1 100644
--- a/skills/showtime/tests/test_capture.py
+++ b/skills/showtime/tests/test_capture.py
@@ -615,7 +615,12 @@ class T3Assets(unittest.TestCase):
self.assertEqual(r["license"], "ISC")
cp = showtime("assets", "icon", "lucide", "rockt", check=False)
self.assertNotEqual(cp.returncode, 0)
- self.assertIn("rocket", cp.stderr) # suggestion
+ with self.subTest("a misspelled name gets a suggestion"):
+ # the suggestion comes from the set's listing before any fetch; only when the listing cannot be read either
+ # (a CI runner's network, public showtime#78) does the command end with the network error
+ if "network error" in cp.stderr:
+ self.skipTest("the icon CDN did not answer: %s" % cp.stderr.strip().splitlines()[-2:])
+ self.assertIn("rocket", cp.stderr)
def test_assets_sheet(self):
"""Contact sheet of a photo folder: EXIF rotation, date, near-duplicates, low-res, clips, paging."""
diff --git a/skills/showtime/tests/test_cards.py b/skills/showtime/tests/test_cards.py
index fe7ee53..ebf93f9 100644
--- a/skills/showtime/tests/test_cards.py
+++ b/skills/showtime/tests/test_cards.py
@@ -584,12 +584,15 @@ class ReelPlacementTest(unittest.TestCase):
"-filter_complex", ";".join(parts) + ";%sformat=rgb24[v]" % cur, "-map", "[v]", "-f", "rawvideo", "-"],
stdout=subprocess.PIPE, check=True).stdout
px = [raw[(k * W * H + (H // 2) * W + W // 2) * 3] for k in range(len(raw) // (W * H * 3))]
- vals = [v if v > 245 else int(round(v / 8.0)) for v in px]
+ # BASE: the white base, not a reel frame (those are at most 29 * 8 = 232). White comes back from yuv420p as 255
+ # here and 253 with some ffmpeg 7.1 builds (an outside run): its exact value is the build's, not the reel's.
+ BASE = "base"
+ vals = [BASE if v > 245 else int(round(v / 8.0)) for v in px]
for p in plan:
f0 = int(round(p["card"]["start"] * float(fps)))
- want = [255] + [i % 30 for i in range(p["offset_frames"], p["offset_frames"] + p["frames"])] + [255]
- self.assertEqual(vals[f0 - 1:f0 + p["frames"] + 1], want, "card %d at frame %d (%s fps)" % (
- p["card"]["index"], f0, rate))
+ want = [BASE] + [i % 30 for i in range(p["offset_frames"], p["offset_frames"] + p["frames"])] + [BASE]
+ self.assertEqual(vals[f0 - 1:f0 + p["frames"] + 1], want, "card %d at frame %d (%s fps); raw %s; frame 0 "
+ "(no card) reads %d" % (p["card"]["index"], f0, rate, px[f0 - 1:f0 + p["frames"] + 1], px[0]))
def test_every_reel_frame_on_its_output_frame(self):
self.placed(Fraction(30), [13, 63, 123, 183]) # 13: start/TB came out 12.999..., truncated a frame early
diff --git a/skills/showtime/tests/test_downloads.py b/skills/showtime/tests/test_downloads.py
index 4fb35fa..4033d3a 100644
--- a/skills/showtime/tests/test_downloads.py
+++ b/skills/showtime/tests/test_downloads.py
@@ -646,6 +646,115 @@ class TestPacksIconsBrowser(unittest.TestCase):
finally:
shutil.rmtree(str(tmp), ignore_errors=True)
+ def test_misspelled_icon_is_refused_from_the_listing(self):
+ """An icon that is not cached yet is checked against the package listing first: a misspelled name gets the
+ suggestion without fetching its file (the CDN takes about 40 s to answer a missing one, past the read timeout:
+ public showtime#78), even when that fetch would time out; a real name is fetched as before."""
+ from unittest import mock
+ from st.assets import icons, net
+ tmp = Path(tempfile.mkdtemp(prefix="st-dl-ic2-"))
+ fetched = []
+ listing = {"files": [{"name": "/icons/rocket.svg"}, {"name": "/icons/zap.svg"}, {"name": "/package.json"}]}
+
+ def get_bytes(url, **kw):
+ fetched.append(url)
+ if url.endswith("/icons/rocket.svg"):
+ return b'<svg xmlns="http://www.w3.org/2000/svg"><path/></svg>', {}
+ raise common.ShowtimeError("network error fetching %s: The read operation timed out" % url)
+ try:
+ with env(SHOWTIME_HOME=tmp / "h", SHOWTIME_NODE_MODULES=tmp / "nm", SHOWTIME_OFFLINE="0"), \
+ mock.patch.object(net, "get_json", lambda url, **kw: listing), \
+ mock.patch.object(net, "get_bytes", get_bytes), mock.patch.object(icons, "_tags", lambda s: {}):
+ with self.assertRaises(common.ShowtimeError) as cm:
+ icons.raw_svg("lucide", "rockt")
+ self.assertIn("no icon 'rockt'", str(cm.exception))
+ self.assertIn("rocket", cm.exception.hint)
+ self.assertEqual(fetched, [], "a name the listing lacks is never fetched")
+ self.assertIn("<svg", icons.raw_svg("lucide", "rocket"))
+ self.assertEqual(len(fetched), 1)
+ self.assertIn("<svg", icons.raw_svg("lucide", "rocket"), "cached now")
+ self.assertEqual(len(fetched), 1)
+ # no listing to read (its request fails too): the file is fetched and its network error comes through
+ def no_listing(url, **kw):
+ raise common.ShowtimeError("network error fetching the listing")
+ with env(SHOWTIME_HOME=tmp / "h2", SHOWTIME_NODE_MODULES=tmp / "nm", SHOWTIME_OFFLINE="0"), \
+ mock.patch.object(net, "get_json", no_listing), mock.patch.object(net, "get_bytes", get_bytes):
+ with self.assertRaises(common.ShowtimeError) as cm:
+ icons.raw_svg("lucide", "rockt")
+ self.assertIn("timed out", str(cm.exception))
+ finally:
+ shutil.rmtree(str(tmp), ignore_errors=True)
+
+ def test_icon_listing_down_or_corrupt(self):
+ """The listing check costs seconds when the index is down (one try, a 10 s timeout, then the file is fetched as
+ before), and a corrupt listing cache with the network failing is no cache (a valid icon is still served, the
+ network error stands for anything else) instead of a ValueError."""
+ from unittest import mock
+ from st.assets import icons, net
+ tmp = Path(tempfile.mkdtemp(prefix="st-dl-ic3-"))
+ calls = []
+ s = icons.SETS["lucide"]
+ listing_url = "https://data.jsdelivr.com/v1/packages/npm/%s@%s?structure=flat" % (s["pkg"], s["version"])
+
+ def get_bytes(url, timeout=30, retries=2, **kw):
+ calls.append((url, timeout, retries))
+ if url.endswith("/icons/rocket.svg"):
+ return b'<svg xmlns="http://www.w3.org/2000/svg"><path/></svg>', "image/svg+xml"
+ raise common.ShowtimeError("network error fetching %s: timed out" % url)
+ try:
+ with env(SHOWTIME_HOME=tmp / "h", SHOWTIME_NODE_MODULES=tmp / "nm", SHOWTIME_OFFLINE="0"), \
+ mock.patch.object(net, "get_bytes", get_bytes):
+ self.assertIn("<svg", icons.raw_svg("lucide", "rocket"))
+ listing = [c for c in calls if c[0] == listing_url]
+ self.assertEqual(len(listing), 1, calls)
+ self.assertLessEqual(listing[0][1], 10)
+ self.assertEqual(listing[0][2], 0, "one try: a dead index costs seconds, not minutes")
+ # a corrupt, expired listing cache and no network: the cache is ignored, the icon is fetched
+ cp = net._cache_path(listing_url)
+ cp.parent.mkdir(parents=True, exist_ok=True)
+ cp.write_text('{"files": [', encoding="utf-8")
+ os.utime(str(cp), (1, 1))
+ self.assertIn("<svg", icons.raw_svg("lucide", "rocket")) # cached icon: no listing needed
+ (icons.cache_dir("lucide") / "icons" / "rocket.svg").unlink()
+ self.assertIn("<svg", icons.raw_svg("lucide", "rocket")) # uncached: the corrupt listing is no listing
+ with self.assertRaises(common.ShowtimeError) as cm:
+ net.get_json(listing_url, ttl=30 * 86400)
+ self.assertIn("network error", str(cm.exception))
+ finally:
+ shutil.rmtree(str(tmp), ignore_errors=True)
+
+ def test_icon_listing_from_an_older_install_or_malformed(self):
+ """An older install's icon package in node_modules (another version than the pin) is not the pinned listing: a
+ newer icon is fetched, not refused. A listing cache of the wrong shape is no listing (the file is fetched)."""
+ from unittest import mock
+ from st.assets import icons, net
+ tmp = Path(tempfile.mkdtemp(prefix="st-dl-ic4-"))
+ svg = b'<svg xmlns="http://www.w3.org/2000/svg"><path/></svg>'
+ fetched = []
+
+ def get_bytes(url, **kw):
+ fetched.append(url)
+ return svg, "image/svg+xml"
+ try:
+ old = tmp / "nm" / "lucide-static"
+ (old / "icons").mkdir(parents=True)
+ (old / "package.json").write_text('{"name": "lucide-static", "version": "1.30.0"}', encoding="utf-8")
+ (old / "icons" / "zap.svg").write_bytes(svg)
+ listing = {"files": [{"name": "/icons/zap.svg"}, {"name": "/icons/a-arrow-down.svg"}]}
+ with env(SHOWTIME_HOME=tmp / "h", SHOWTIME_NODE_MODULES=tmp / "nm", SHOWTIME_OFFLINE="0"), \
+ mock.patch.object(net, "get_json", lambda url, **kw: listing), mock.patch.object(net, "get_bytes", get_bytes):
+ self.assertIsNone(icons._names_local("lucide"), "1.30.0 is not the pinned version")
+ self.assertIn("<svg", icons.raw_svg("lucide", "a-arrow-down")) # newer than the old install: fetched
+ self.assertIn("<svg", icons.raw_svg("lucide", "zap")) # the old install's own file still works
+ for bad in (["a", "b"], {"files": None}, [{"name": 1}]):
+ fetched.clear()
+ with env(SHOWTIME_HOME=tmp / ("h-%d" % len(str(bad))), SHOWTIME_NODE_MODULES=tmp / "none", SHOWTIME_OFFLINE="0"), \
+ mock.patch.object(net, "get_json", lambda url, _b=bad, **kw: _b), mock.patch.object(net, "get_bytes", get_bytes):
+ self.assertIn("<svg", icons.raw_svg("lucide", "rocket"), bad)
+ self.assertEqual(len(fetched), 1, bad)
+ finally:
+ shutil.rmtree(str(tmp), ignore_errors=True)
+
def test_headless_shell_discovery(self):
tmp = Path(tempfile.mkdtemp(prefix="st-dl-br-"))
try:
diff --git a/skills/showtime/tests/test_footage.py b/skills/showtime/tests/test_footage.py
index c6a15f9..23b27da 100644
--- a/skills/showtime/tests/test_footage.py
+++ b/skills/showtime/tests/test_footage.py
@@ -868,6 +868,33 @@ class LatestRenderTest(unittest.TestCase):
self.assertIn("no edit render found", cp.stderr)
self.assertNotIn("Traceback", cp.stderr)
+ def test_trim_refuses_another_spelling_of_the_input(self):
+ """`footage trim -o` naming the input under another spelling is refused and the clip kept (cli_footage's
+ samefile guard): a hard link, and a case variant on a case-insensitive disk (macOS, Windows by default). A
+ spelling this file system does not have is a skipped subtest with its reason (some container mounts refuse
+ hard links; a case-sensitive disk has no case variant)."""
+ root = self.tmp / "trim-same"
+ root.mkdir()
+ clip = root / "clip.mp4"
+ ffrun(["-f", "lavfi", "-i", "testsrc2=s=160x90:r=30:d=1", "-c:v", "libx264", "-preset", "veryfast",
+ "-pix_fmt", "yuv420p", clip])
+ size = clip.stat().st_size
+ link, no_link = root / "same-file.mp4", None
+ try:
+ os.link(clip, link)
+ except (OSError, NotImplementedError, AttributeError) as e:
+ no_link = "no hard links on this file system (%s)" % e
+ case = clip.with_name(clip.name.upper())
+ for kind, other, why_not in (("hard link", link, no_link),
+ ("case variant", case, None if case.exists() else "the disk is case-sensitive")):
+ with self.subTest(kind):
+ if why_not:
+ self.skipTest(why_not)
+ cp = self.run_st("footage", "trim", clip, "-o", other, "--overwrite", check=False)
+ self.assertEqual(cp.returncode, 1, cp.stderr)
+ self.assertIn("the input clip itself", cp.stderr)
+ self.assertEqual(clip.stat().st_size, size)
+
def test_trim_and_scene_ranges(self):
"""05/06/10: `footage trim` cuts a range (frame-accurate) and makes seek-friendly proxies (--width,
short GOP, --webm) without raw ffmpeg; `footage scenes --every` takes --from/--to and a file -o."""
@@ -895,13 +922,7 @@ class LatestRenderTest(unittest.TestCase):
cp = self.run_st("footage", "trim", clip, "-o", clip, "--overwrite", check=False)
self.assertEqual(cp.returncode, 1, cp.stderr)
self.assertIn("the input clip itself", cp.stderr)
- link = root / "same-file.mp4" # another spelling of the input (a hard link; a case variant on a
- os.link(clip, link) # case-insensitive disk): refused, the clip is not overwritten
- size = Path(clip).stat().st_size
- cp = self.run_st("footage", "trim", clip, "-o", link, "--overwrite", check=False)
- self.assertEqual(cp.returncode, 1, cp.stderr)
- self.assertIn("the input clip itself", cp.stderr)
- self.assertEqual(Path(clip).stat().st_size, size)
+ # another spelling of the input (a hard link, a case variant): test_trim_refuses_another_spelling_of_the_input
r = json.loads(self.run_st("footage", "trim", clip, "--webm", "--no-audio", "--to", "1", "-o", root / "cut.webm",
"--overwrite", "--json").stdout)
self.assertEqual(Path(r["output"]), root / "cut.webm")
diff --git a/skills/showtime/tests/test_interactive.py b/skills/showtime/tests/test_interactive.py
index b5c9f0b..ec09c5f 100644
--- a/skills/showtime/tests/test_interactive.py
+++ b/skills/showtime/tests/test_interactive.py
@@ -308,7 +308,7 @@ FIGURE_DRIVER = r"""
import fs from 'node:fs';
import path from 'node:path';
import { pathToFileURL } from 'node:url';
-const [SKILL, ECON, HEAT, ENTER] = process.argv.slice(2);
+const [SKILL, ECON, HEAT, ENTER, SPACE] = process.argv.slice(2);
const imp = (p) => import(pathToFileURL(path.join(SKILL, 'scripts', p)).href);
const { startServer, injectStage } = await imp('server.mjs');
const { openBrowser, openStage } = await imp('lib/stagehost.mjs');
@@ -318,7 +318,7 @@ const wait = (ms) => new Promise((r) => setTimeout(r, ms));
// happens") wait a short bounded time after the state that would have made something happen
const until = (page, fn, arg) => page.waitForFunction(fn, arg, { timeout: 30000, polling: 50 });
const out = { errors: [] };
-const srv = await startServer({ root: ECON }), heat = await startServer({ root: HEAT }), ent = await startServer({ root: ENTER });
+const srv = await startServer({ root: ECON }), heat = await startServer({ root: HEAT }), ent = await startServer({ root: ENTER }), spc = await startServer({ root: SPACE });
const open = async (url, opts = {}, tourAfter = 60000) => {
const ctx = await browser.newContext(Object.assign({ viewport: { width: 1440, height: 900 } }, opts));
await ctx.addInitScript((ms) => { window.SHOWTIME_TEST_TOUR_AFTER = ms; }, tourAfter);
@@ -405,7 +405,9 @@ try {
{ const { ctx, page } = await open(ent.url + '/figure.html#step=gate&permission=allow', { reducedMotion: 'reduce' });
const board = () => page.evaluate(() => [...document.querySelectorAll('.fg-ld [data-ld-tag]')].filter((g) => g.getAttribute('visibility') === 'visible')
.map((g) => [...g.querySelectorAll('text')].filter((t) => t.getAttribute('visibility') === 'visible').map((t) => t.textContent).join('')));
- await until(page, () => Figure.current.S.step === 2);
+ // the step changes before the frame draws its tags: wait for the board itself (a slow runner read it empty)
+ await until(page, () => Figure.current.S.step === 2 && [...document.querySelectorAll('.fg-ld [data-ld-tag]')].some((g) =>
+ g.getAttribute('visibility') === 'visible' && [...g.querySelectorAll('text')].some((t) => t.getAttribute('visibility') === 'visible')));
out.enterAllow0 = { board: await board(), text: await page.evaluate(() => document.querySelector('.fg-step .t').textContent) };
const shows = (t) => until(page, (x) => [...document.querySelectorAll('.fg-ld [data-ld-tag]')].some((g) => g.getAttribute('visibility') === 'visible'
&& [...g.querySelectorAll('text')].some((e) => e.getAttribute('visibility') === 'visible' && e.textContent === x)), t);
@@ -416,6 +418,23 @@ try {
out.enterButtonsAfter = await page.evaluate(() => [...document.querySelectorAll('.fg-keybtns button')].length);
out.enterNo = { board: await board(), text: await page.evaluate(() => document.querySelector('.fg-step .t').textContent) };
await ctx.close(); }
+ // the same scene with Space and Enter as its keys: a focused summary, slider, button or link keeps its own Space and
+ // Enter (they press it), so the scene's key does not fire from there; from the page it does
+ { const { ctx, page } = await open(spc.url + '/figure.html');
+ await page.evaluate(() => { Figure.current.setKnob('permission', 'ask'); Figure.current.enter(2); });
+ out.spaceOnControls = await page.evaluate(() => {
+ const res = [String(Figure.current.state.answer)];
+ for (const html of ['<details><summary>Narration</summary>x</details>', '<div role="slider" tabindex="0"></div>', '<button type="button">b</button>', '<a href="#x">a</a>']) {
+ const w = document.createElement('div'); w.innerHTML = html; document.querySelector('.fg').appendChild(w);
+ const t = w.firstChild.firstChild && w.firstChild.firstChild.nodeType === 1 ? w.firstChild.firstChild : w.firstChild;
+ for (const key of [' ', 'Enter']) { t.dispatchEvent(new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true })); res.push(String(Figure.current.state.answer)); }
+ w.remove();
+ }
+ document.body.dispatchEvent(new KeyboardEvent('keydown', { key: ' ', bubbles: true, cancelable: true }));
+ res.push(String(Figure.current.state.answer));
+ return res;
+ });
+ await ctx.close(); }
{ const { ctx, page } = await open(heat.url + '/figure.html'); out.walkHeat = await page.evaluate(() => Figure.current.walk()); out.heatTitle = await page.evaluate(() => document.title); await ctx.close(); }
// 6. the film of the tour: the same t from different frames, and the tour's values on the board
{ const cfg = JSON.parse(fs.readFileSync(path.join(ECON, 'showtime.json'), 'utf8'));
@@ -430,7 +449,7 @@ try {
.map((g) => [...g.querySelectorAll('text')].filter((t) => t.getAttribute('visibility') === 'visible').map((t) => t.textContent).join('')));
await sess.close(); }
out.inject = { live: injectStage('<html data-st-live><head></head></html>').includes('stage.js'), film: injectStage('<html><head></head></html>').includes('stage.js') };
-} finally { await browser.close(); await srv.close?.(); await heat.close?.(); await ent.close?.(); }
+} finally { await browser.close(); await srv.close?.(); await heat.close?.(); await ent.close?.(); await spc.close?.(); }
console.log(JSON.stringify(out));
process.exit(0);
"""
@@ -450,7 +469,14 @@ class TestFigure(unittest.TestCase):
heat, enter = TMP / "heat", TMP / "enter"
showtime("new", "diagram", heat, "--theme", "white")
showtime("new", "diagram", enter, "--example", "enter", "--theme", "white")
- cls.r = run_driver(FIGURE_DRIVER, econ_project(), heat, enter)
+ # the same scene answered with Space and Enter instead of A and D
+ space = TMP / "space-keys"
+ showtime("new", "diagram", space, "--example", "enter", "--theme", "white")
+ js = (space / "scene.js").read_text(encoding="utf-8")
+ assert js.count("a: { label: 'Allow'") == 1 and js.count("d: { label: 'Deny'") == 1, "the Enter example's keys moved"
+ (space / "scene.js").write_text(js.replace("a: { label: 'Allow'", "' ': { label: 'Allow'")
+ .replace("d: { label: 'Deny'", "enter: { label: 'Deny'"), encoding="utf-8")
+ cls.r = run_driver(FIGURE_DRIVER, econ_project(), heat, enter, space)
def test_no_page_errors_and_no_stage(self):
self.assertEqual(self.r["errors"], [])
@@ -527,6 +553,15 @@ class TestFigure(unittest.TestCase):
self.assertTrue(p["chips"], "the board's words are chips under the figure")
self.assertTrue(all(bg for _, bg in p["chips"]), "each chip in its tag's colour: %s" % p["chips"])
+ def test_a_focused_control_keeps_space_and_enter(self):
+ # a scene whose keys are Space and Enter: on a focused summary, slider, button or link they press it, and the
+ # scene's key does not fire too; from the page, Space is the scene's key (letters on a focused knob still reach
+ # the scene: the Enter example's D after a click on its setting, test_enter_settings_and_answers_agree)
+ on = self.r["spaceOnControls"]
+ self.assertNotEqual(on[0], "yes")
+ self.assertEqual(set(on[:-1]), {on[0]}, on)
+ self.assertEqual(on[-1], "yes", "from the page, Space is the scene's key")
+
def test_walk_finds_nothing_on_the_examples(self):
w = self.r["walk"]
self.assertGreaterEqual(w["states"], 60)
diff --git a/skills/showtime/tests/test_mcp.py b/skills/showtime/tests/test_mcp.py
index 1ade4a3..5bf74b9 100644
--- a/skills/showtime/tests/test_mcp.py
+++ b/skills/showtime/tests/test_mcp.py
@@ -254,6 +254,31 @@ class TestProtocol(unittest.TestCase):
self.assertIn(want, text_of(step))
self.assertFalse(any(self.tmp.iterdir()), "a rejected call must not write anything")
+ @unittest.skipIf(os.name == "nt", "POSIX file modes")
+ def test_voice_say_text_file_is_private(self):
+ """voice_say hands its text to `showtime voice say --file`: a new file (flag wx) with a random name, readable by
+ this user only (0600), removed afterwards. A stand-in Python records what the command was given."""
+ rec = self.tmp / "voice-say.json"
+ fake = self.tmp / "fake-python"
+ fake.write_text("#!%s\nimport json, os, stat, sys\nf = [x[7:] for x in sys.argv if x.startswith('--file=')][0]\n"
+ "json.dump({'name': os.path.basename(f), 'mode': stat.S_IMODE(os.stat(f).st_mode),\n"
+ " 'text': open(f, encoding='utf-8').read(), 'path': f}, open(%r, 'w'))\n"
+ % (sys.executable, str(rec)), encoding="utf-8")
+ fake.chmod(0o755)
+ try:
+ out = mcp([call("voice_say", {"text": "hello there", "output": str(self.tmp / "v.wav")})], self.tmp,
+ env=dict(self.env, SHOWTIME_MCP_TOOLS="all", SHOWTIME_PYTHON=str(fake)))
+ self.assertTrue(rec.is_file(), json.dumps(out["results"][1])[:1500])
+ got = json.loads(rec.read_text(encoding="utf-8"))
+ self.assertRegex(got["name"], r"^showtime-mcp-say-[0-9a-f]{24}\.txt$")
+ self.assertEqual(got["mode"], 0o600)
+ self.assertEqual(got["text"], "hello there")
+ self.assertFalse(os.path.exists(got["path"]), "the text file is removed after the call")
+ finally:
+ for p in (rec, fake):
+ if p.exists():
+ p.unlink()
+
def test_audio_search_produced_catalog(self):
"""audio_search with catalog=true or a use searches the produced-music catalog (no download)."""
diff --git a/skills/showtime/tests/test_os_install.py b/skills/showtime/tests/test_os_install.py
index 1770827..43d8b61 100644
--- a/skills/showtime/tests/test_os_install.py
+++ b/skills/showtime/tests/test_os_install.py
@@ -305,6 +305,47 @@ class TestOldFfmpeg(Tmp):
self.assertEqual(rows["ffmpeg version"]["status"], "warn")
self.assertIn("showtime setup --ffmpeg static", rows["ffmpeg version"]["hint"])
+ def test_other_installs_ffmpeg_is_not_the_system_one(self):
+ """`setup --home X` with a default install present: the launcher puts ~/.showtime/bin first on PATH, and its
+ ffmpeg was taken as "the system ffmpeg", so X got none of its own (and none at all where that folder is not on
+ PATH). Another showtime home's bin (the default one, or the launcher's SHOWTIME_HOME) is never the system."""
+ su = setup_mod()
+ default, ws, sysdir = self.tmp / "user", self.tmp / "proj" / ".showtime", self.tmp / "usr-bin"
+ exes = {}
+ for name, d in (("default", default / ".showtime" / "bin"), ("ws", ws / "bin"), ("system", sysdir)):
+ d.mkdir(parents=True)
+ for n in ("ffmpeg", "ffprobe"):
+ (d / n).write_text("#!/bin/sh\nexit 0\n")
+ (d / n).chmod(0o755)
+ exes[name] = str(d / "ffmpeg")
+
+ def step(home, cands, before=None):
+ inst = su.Installer(su.parse_args(["--home", str(home), "--ffmpeg", "system"]))
+ err = io.StringIO()
+ with mock.patch.object(su, "_HOME_BEFORE", before), \
+ mock.patch.object(su.plat, "user_home", lambda: default), \
+ mock.patch.object(su.Installer, "_ff_check", lambda self, exe, timeout=30: (True, [], [], "9.0.2")), \
+ mock.patch("st.ff._system_candidates", lambda name: list(cands)), redirect_stdout(err), \
+ redirect_stderr(err):
+ status, detail = inst.step_ffmpeg()
+ homes = inst.other_homes()
+ return status, detail, (inst.state.data.get("ffmpeg") or {}).get("path"), homes, err.getvalue()
+
+ x = self.tmp / "X"
+ status, detail, used, homes, said = step(x, [exes["default"], exes["system"]])
+ self.assertEqual((status, used), ("ok", exes["system"]), detail)
+ self.assertEqual(homes, [default / ".showtime"])
+ self.assertIn("belongs to another showtime install", said)
+ # only the other install's: no system ffmpeg (auto would download X's own)
+ status, detail, used, _h, _s = step(x, [exes["default"]])
+ self.assertEqual(status, "fail", detail)
+ # the launcher's own home (a project's .showtime) is another install too
+ status, detail, used, homes, _s = step(x, [exes["ws"], exes["system"]], before=str(ws))
+ self.assertEqual((status, used), ("ok", exes["system"]), detail)
+ self.assertEqual(homes, [default / ".showtime", ws])
+ # setup for the default home itself: no other home to skip
+ self.assertEqual(step(default / ".showtime", [exes["system"]], before=str(default / ".showtime"))[3], [])
+
# ------------------------------------------------------------------ 5. a failed loudness reading is not 0 LUFS
diff --git a/skills/showtime/tests/test_pace.py b/skills/showtime/tests/test_pace.py
index 9cc72c0..129b0b2 100644
--- a/skills/showtime/tests/test_pace.py
+++ b/skills/showtime/tests/test_pace.py
@@ -152,7 +152,8 @@ console.log(JSON.stringify({ factor: pace.factor, summary: S.paceSummary([{ pace
# The guard's fake-browser runs (node only). Every wait is derived from stagehost's own SHOT_IDLE_MS under the test
# scale: idle = SHOT_IDLE_MS x scale (each read of the browser's work may take that long too), a browser that
- # answers nothing is stuck once it has said nothing for 2 x idle, and the work is read every POLL_MS.
+ # answers nothing is stuck once it has said nothing for 2 x idle, and each read starts POLL_MS after the previous
+ # one ended (not every POLL_MS): reads a browser never answers end (POLL_MS + idle) apart.
GUARD_JS = """
const S = await import(%s);
const never = () => new Promise(() => {});
@@ -220,14 +221,16 @@ out.silent.noWork = cache.noWork === true;
silent browser, not the cap (the cap check came first: a busy machine's late tick, a cap set low, or a size
read that used most of a shot's shared budget then got the less helpful reason). The browser does not
answer; each unanswered read takes the idle time, so the reads end about (poll + idle) apart and the silence
- is known at the third. The cap falls between the second and the third (at 2.6 x (poll + idle)): it is
- reached on the tick that finds the silence, with 0.6 x (poll + idle) to spare for late timers before the
- second. Idle 6 s here (scale 0.2): 3.6 s to spare, over three times the late timers that ended the old cap
- test on a loaded Windows runner (at least about 1 s)."""
+ is known at the third. The cap falls between the second and the third (at 2.9 x (poll + idle)): it is
+ reached on the tick that finds the silence, which never comes before poll + 3 x idle (timers do not fire
+ early; 2.9 x (poll + idle) is below that while poll < idle / 19), and the late timers before the second tick may add up to 0.9 x (poll + idle) before that tick meets the
+ cap without the silence (the case would then end on the cap). Idle 6 s here (scale 0.2): 5.4 s to spare, over
+ five times the late timers that ended the old cap test on a loaded Windows runner (at least about 1 s); it was
+ 3.6 s at 2.6 x."""
scale = 0.2
idle = shot_idle_ms() * scale
step = self.POLL_MS + idle
- cap_ms = int(2.6 * step)
+ cap_ms = int(2.9 * step)
r = self.guard(scale, cap_ms, """
const b = fake(never), cache = {};
out.both = await run(b, never(), cache);
@@ -323,32 +326,38 @@ process.exit(0);
self.assertGreater(paced["pace"]["frame_ms"], 50, paced)
self.assertGreater(paced["factor"], 1, paced)
+ # The open-deadline tests' page waits longer than the page-open deadline allows, on any machine. The deadline is
+ # OPEN_S here (5 min on a real machine), and the page's own load gets 3/5 of it (stagehost PAGE_LOAD_MS): at 3 s
+ # that was 1.8 s, and under a 6-core Mac's 6 busy loops 5 of 15 checks failed their load ("page.goto: Timeout
+ # 1800ms exceeded", check's ready_failed) instead of reaching the deadline. At 10 s the load gets 6 s. The page
+ # waits SLOW_OPEN_MS, past one try's deadline even at the pace ceiling (x5: 50 s), so it is never ready in time.
+ # The page's own cap on an ST.waitFor gate (stage.js ready(): pacedRace(..., 60000, 'ST.waitFor: ...'), 60 s x the
+ # page's pace) is past that deadline too, so the open deadline always ends the try first.
+ OPEN_S = 10
+ SLOW_OPEN_MS = 120000
+
def test_first_page_open_deadline(self):
"""render's first page has the workers' page-open deadline (5 min; SHOWTIME_TEST_OPEN_TIMEOUT shortens
it): a browser that never answers while it opens the page is given up, the page tried once more in a new
browser, and then the render fails with the deadline instead of waiting with none (the first page and
the WebGL probe had no deadline of their own)."""
- proj = self.tmp / "slowopen"
- write(proj / "showtime.json", json.dumps({"width": 320, "height": 180, "fps": 10, "duration": 0.5, "background": "#202830"}))
- write(proj / "index.html", HEAD + "</head><body><script>"
- "ST.waitFor(new Promise((r) => setTimeout(r, 20000)), 'slow open');\n"
- "ST.onSeek(() => {});</script></body></html>")
+ proj = self.slow_open_project("slowopen")
cp = showtime("render", proj, "-o", self.tmp / "slowopen.mp4", "--no-check", "--workers", "1",
- env=dict(ENV, SHOWTIME_TEST_OPEN_TIMEOUT="3"), timeout=300)
+ env=dict(ENV, SHOWTIME_TEST_OPEN_TIMEOUT=str(self.OPEN_S)), timeout=300)
self.assertNotEqual(cp.returncode, 0, cp.stdout[-1500:])
self.assertIn("trying once more in a new browser", cp.stderr)
self.assertEqual(cp.stderr.count("trying once more"), 1, cp.stderr[-2000:])
# the deadline is x the page's pace (a busy runner's frames raise it while the page waits)
self.assertRegex(cp.stderr, r"timed out after \d+s( \(x[\d.]+ for this page's pace\))?: opening the page")
- # names the step (on a fast machine the page's own 20 s wait; a slow one may still be setting the tab up)
+ # names the step (on a fast machine the page's own wait; a slow one may still be setting the tab up)
self.assertRegex(cp.stderr, STUCK_AT)
def slow_open_project(self, name):
proj = self.tmp / name
write(proj / "showtime.json", json.dumps({"width": 320, "height": 180, "fps": 10, "duration": 0.5, "background": "#202830"}))
write(proj / "index.html", HEAD + "</head><body><script>"
- "ST.waitFor(new Promise((r) => setTimeout(r, 20000)), 'slow open');\n"
- "ST.onSeek(() => {});</script></body></html>")
+ "ST.waitFor(new Promise((r) => setTimeout(r, %d)), 'slow open');\n"
+ "ST.onSeek(() => {});</script></body></html>" % self.SLOW_OPEN_MS)
return proj
def test_check_open_deadline(self):
@@ -357,11 +366,11 @@ process.exit(0);
macOS CI runner's check outlived its caller's 5 minutes)."""
proj = self.slow_open_project("slowcheck")
cp = showtime("check", proj, "--json", "--no-determinism", "--no-timeline", "--no-history", "--samples", "2",
- env=dict(ENV, SHOWTIME_TEST_OPEN_TIMEOUT="3"), timeout=300)
+ env=dict(ENV, SHOWTIME_TEST_OPEN_TIMEOUT=str(self.OPEN_S)), timeout=300)
self.assertNotEqual(cp.returncode, 0, cp.stdout[-1500:])
self.assertEqual(cp.stderr.count("trying once more in a new browser"), 1, cp.stderr[-2000:])
self.assertIn("the browser stopped answering", cp.stderr)
- # names the step (on a fast machine the page's own 20 s wait; a slow one may still be setting the tab up)
+ # names the step (on a fast machine the page's own wait; a slow one may still be setting the tab up)
self.assertRegex(cp.stderr, STUCK_AT)
self.assertIn("in a new browser too", cp.stderr)
@@ -404,8 +413,9 @@ process.exit(0);
rep = json.loads(cp.stdout)
soft = [f for f in rep["findings"] if f["code"] in ("cut_probe_failed", "determinism_incomplete")]
self.assertTrue(soft, [(f["code"], f["message"][:120]) for f in rep["findings"]])
+ self.assertIn("cut_probe_failed", {f["code"] for f in soft}, soft) # the cut walk's second page hangs too
for f in soft:
- self.assertIn(f["severity"], ("info", "warning"), f)
+ self.assertEqual(f["severity"], "warning", f) # never info: a skipped cut walk or determinism load is not ok
self.assertIn("could not open", f["message"])
self.assertNotIn("the browser stopped answering", cp.stderr)
@@ -415,7 +425,7 @@ process.exit(0);
page opens, check gives it up at the deadline, kills it and finishes in a new browser; stopped after the
image lab page opened, the watchdog ends check with an error naming its last step. Each returns in under 120 s
(about 25 s on a quiet Mac) and leaves no stopped browser of its own behind.
- The open deadline is 20 s here, not 3 s: a stopped browser never answers, so any deadline finds it and a
+ The open deadline is 20 s here (OPEN_S elsewhere): a stopped browser never answers, so any deadline finds it and a
longer one only costs that wait; the healthy browser that replaces it must open its page inside the same
deadline, and on a busy macOS CI runner a fresh browser took over 3 s just to create its context and tab
(the 0.4.2 release PR). The page's own load gets 3/5 of it (PAGE_LOAD_MS: 1.8 s at 3 s, 12 s here), and the
@@ -473,9 +483,11 @@ class TestSizeReadWaitsForTheFrame(unittest.TestCase):
shrinks what the guard allows the browser to answer it (SystemInfo.getProcessInfo): one read may take the idle
time (SHOT_IDLE_MS x scale) and a browser silent for twice that is stuck. At 0.05 that was 1.5 s and 3 s, and on
a loaded Windows runner two late answers ended a busy read as "the browser did not say what it was doing"
- (nightly 14 Oct); on a real machine they are 15 s and 60 s. At 0.25 they are 7.5 s and 15 s: reads every 5 s
- start at 5 s, so the browser cannot be found silent before about 27 s, after the page lets go. The stopped page
- keeps 0.05 (it fails in seconds: the idle window is 1.5 s)."""
+ (nightly 14 Oct); on a real machine they are 15 s and 60 s. At 0.25 they are 7.5 s and 15 s: the first read
+ starts at 5 s and an unanswered one ends 7.5 s later, the next starts 5 s after that, so unanswered reads end at
+ 12.5, 25 and 37.5 s, and the silence (every read for 15 s unanswered) is found at 37.5 s at the earliest, well
+ after the page lets go (about 20 s: 15 s plus the 5 s margin, at pace 1). The stopped page keeps 0.05 (it fails
+ in seconds: the idle window is 1.5 s)."""
OLD_READ_MS = 60000 # the read's flat deadline before guardShot (x the page's pace)
BUSY_MARGIN_MS = 5000 # the page is held this long past the old deadline
@@ -498,12 +510,15 @@ class TestSizeReadWaitsForTheFrame(unittest.TestCase):
def run_shot(self, stop, scale):
# the main thread is held right after the seek returns (a task queued by a call that returns at once, not
# onSeek, which would hold the seek itself and raise the page's pace), then a clipped screenshot is taken;
- # it is held past the old deadline at the pace the page measured (the pace does not change after the seek)
+ # it is held past the old deadline at the pace the page measured (the pace does not change after the seek).
+ # Software GL (gpu off), as on the runner without a GPU of #14: what is tested is the read waiting out a busy
+ # main thread, and a macos-14 runner's virtual GPU once stalled the screenshot right after the hold ("did no
+ # work for 10 s", public showtime#78), which this test does not cover (TestFrameNeverComes does)
code = """
const S = await import(%s);
const { startServer } = await import(%s);
const server = await startServer({ root: %s, port: 0 });
-const b = await S.openBrowser({});
+const b = await S.openBrowser({ gpu: 'off' });
const stop = %s;
let out, extra = {}, stopped = [];
try {
diff --git a/skills/showtime/tests/test_pacing.py b/skills/showtime/tests/test_pacing.py
index eacaa4f..47336c4 100644
--- a/skills/showtime/tests/test_pacing.py
+++ b/skills/showtime/tests/test_pacing.py
@@ -51,6 +51,17 @@ def showtime(*args, check=True, timeout=600):
return cp
+def check_json(p, *args):
+ """`showtime check <p> --json`, run once more when the machine's network changed during the first run: Chrome then
+ aborts the page's loads, even from 127.0.0.1, with net::ERR_NETWORK_CHANGED (a CI runner's network event: one
+ macos-15-intel nightly in 21, 15 Oct). Only that error earns the second run, and the second run is the report:
+ any other failed load, or the same error twice, still fails the test."""
+ rep = json.loads(showtime("check", p, "--json", *args, check=False).stdout)
+ if any(f["code"] == "request_failed" and "net::ERR_NETWORK_CHANGED" in f["message"] for f in rep["findings"]):
+ rep = json.loads(showtime("check", p, "--json", *args, check=False).stdout)
+ return rep
+
+
HEAD = """<!doctype html><html lang="en"><head><meta charset="utf-8"><title>pacing</title>
<script src="/_st/stage.js"></script><link rel="stylesheet" href="/_st/themes/editorial.css">
<script type="module" src="/_st/components/index.js"></script>
@@ -193,8 +204,7 @@ class PacingChecks(unittest.TestCase):
p.mkdir()
(p / "showtime.json").write_text(json.dumps(dict({"width": 1920, "height": 1080, "fps": 30, "duration": dur}, **extra)), encoding="utf-8")
(p / "index.html").write_text(HEAD.replace("@BODY@", body), encoding="utf-8")
- cp = showtime("check", p, "--json", "--no-determinism", check=False)
- cls.rep[name] = json.loads(cp.stdout)
+ cls.rep[name] = check_json(p, "--no-determinism")
@classmethod
def tearDownClass(cls):
@@ -239,7 +249,7 @@ class PacingChecks(unittest.TestCase):
html = (p / "index.html").read_text(encoding="utf-8")
self.assertIn('data-dur="10.88"', html)
self.assertIn('data-st="typewriter" data-at="5.36"', html)
- rep = json.loads(showtime("check", p, "--json", "--no-determinism", check=False).stdout)
+ rep = check_json(p, "--no-determinism")
bad = [(f["code"], f["message"][:100]) for f in rep["findings"] if f["severity"] in ("error", "warning")]
self.assertEqual(bad, [])
diff --git a/skills/showtime/tests/test_pr_video.py b/skills/showtime/tests/test_pr_video.py
index 0fb888a..bf1c7d3 100644
--- a/skills/showtime/tests/test_pr_video.py
+++ b/skills/showtime/tests/test_pr_video.py
@@ -188,7 +188,7 @@ class TestSecrets(unittest.TestCase):
cases = {
"headers = {'Authorization': 'token %s'}" % tok: True,
'password: "correct-horse-battery"': True,
- "DATABASE_URL=postgres://admin:[email protected]/app": True,
+ "DATABASE_URL=postgres://admin:" + "[email protected]/app": True, # built in pieces (check_release secrets)
"export STRIPE_SECRET=sk_live_" + "0" * 24: True,
"SECRET_KEY=8f2a9c1e7b3d4a6f": True,
"token = get_token(session)": False,
@@ -205,7 +205,8 @@ class TestSecrets(unittest.TestCase):
self.assertNotIn("correct-horse", out)
def test_private_key_block_and_description(self):
- body = "Rotates the key.\n-----BEGIN RSA PRIVATE KEY-----\nMIIEow\nabc\n-----END RSA PRIVATE KEY-----\nDone."
+ key = "RSA PRIVATE " + "KEY-----" # built in pieces (check_release secrets)
+ body = "Rotates the key.\n-----BEGIN " + key + "\nMIIEow\nabc\n-----END " + key + "\nDone."
out, n = pv.mask_text(body)
self.assertEqual(n, 4)
self.assertNotIn("MIIEow", out)
diff --git a/skills/showtime/tests/test_receipt.py b/skills/showtime/tests/test_receipt.py
index 4009424..a153b86 100644
--- a/skills/showtime/tests/test_receipt.py
+++ b/skills/showtime/tests/test_receipt.py
@@ -83,7 +83,7 @@ def asst(mid, model, ts, inp=0, out=0, cr=0, cc=None, cc_split=None, searches=0,
"message": {"id": mid, "model": model, "role": "assistant", "content": [{"type": "text", "text": text}], "usage": u}}
-SECRET_PROMPT = "SECRET-PROMPT-TEXT sk-ant-api03-abcdefghijklmnopqrstuvwxyz0123456789"
+SECRET_PROMPT = "SECRET-PROMPT-TEXT sk-ant-" + "api03-abcdefghijklmnopqrstuvwxyz0123456789" # in pieces (check_release secrets)
def claude_fixture(root: Path) -> Path:
diff --git a/skills/showtime/tests/test_render.py b/skills/showtime/tests/test_render.py
index d701e3a..28b652b 100644
--- a/skills/showtime/tests/test_render.py
+++ b/skills/showtime/tests/test_render.py
@@ -722,6 +722,370 @@ Film.start({ look: 'paper', fonts: ['650 1em "Inter Variable"'], scenes: functio
self.assertFalse(any("Faint side note" in m for c, _, m in msgs if c == "low_contrast"), msgs)
self.assertTrue(any(c == "dimmed_text" for c, _, _ in msgs), msgs)
+ def test_13c_check_canvas_text_over_text_between_samples(self):
+ """Canvas text drawn over other text is reported even when the scene paints it with the canvas's own fillText
+ (not F.text) and only between the sampled frames: two raw labels collide from 3.0 to 3.4 s (a canvas chart
+ label over a faint note), and a faint F.text (alpha .35) sits under a red one from 4.5 s. Labels apart, a shadow pass
+ of the same string, text layered on purpose (F.layer, {layer: true}, ST.layer around raw calls), decor drawn raw
+ inside F.decor and a crossfade (both texts' opacity moving) are not reported."""
+ proj = self.tmp / "filmtextover"
+ write(proj / "showtime.json", json.dumps({"width": 1280, "height": 720, "fps": 30, "duration": 6}))
+ write(proj / "index.html", """<!doctype html><html><head><link rel="stylesheet" href="/_lib/@fontsource-variable/inter/index.css">
+<script src="/_st/stage.js"></script><script src="/_st/film.js"></script></head><body><script>
+Film.start({ look: 'dark', design: [1280, 720], fonts: ['600 1em "Inter Variable"'], scenes: function (T, g, F) {
+ g.save(); g.textBaseline = 'middle'; g.font = '600 34px "Inter Variable"'; g.fillStyle = '#ff5a4f';
+ g.fillText('BELOW THRESHOLD: NO RESULT', 640, 300);
+ if (T >= 3.0 && T < 3.4) { g.font = '500 26px "Inter Variable"'; g.fillStyle = 'rgba(143,211,255,.7)'; g.fillText('FAINT: A SECOND MEASUREMENT,', 640, 296); }
+ g.restore();
+ if (T >= 4.5) { F.text('Peak strain', 100, 520, { size: 48, weight: 700, color: '#ff5a4f' }); F.text('faint caption below', 110, 512, { size: 40, alpha: 0.35, color: '#ffffff' }); }
+ F.text('Left label', 100, 150, { size: 40 }); F.text('Right label', 900, 150, { size: 40 });
+ g.save(); g.font = '700 44px "Inter Variable"'; g.fillStyle = 'rgba(0,0,0,.6)'; g.fillText('Shadowed', 103, 653); g.fillStyle = '#ffffff'; g.fillText('Shadowed', 100, 650); g.restore();
+ F.layer(function () { F.text('DRAFT', 880, 610, { size: 90, weight: 800, color: '#ff3030' }); });
+ F.text('Final figures', 890, 590, { size: 40 });
+ F.text('Stamp', 300, 430, { size: 60, weight: 800, color: '#ff3030', layer: true }); F.text('Under stamp', 305, 422, { size: 40 });
+ g.save(); g.font = '700 44px "Inter Variable"'; g.fillStyle = '#ffffff';
+ ST.layer(function () { g.fillText('Raw stamp', 620, 430); }); g.fillText('Raw under', 625, 424);
+ F.decor(function () { g.fillText('UI detail', 950, 430); }); g.restore(); F.text('Over UI', 955, 425, { size: 30 });
+ g.save(); g.font = '600 30px "Inter Variable"'; g.fillStyle = '#8fd3ff'; g.textBaseline = 'middle'; g.fillText('Under the callout', 350, 660); g.restore();
+ F.callout(700, 600, 520, 660, 'Click here', { p: 1, size: 30 }); // its card hides the raw label drawn before it
+ if (T >= 1.0 && T < 2.0) { F.text('Fading out', 100, 370, { size: 40, alpha: 2 - T }); F.text('Fading in', 105, 365, { size: 40, alpha: T - 1 }); }
+} });
+</script></body></html>""")
+ rep = json.loads(showtime("check", proj, "--json", "--no-determinism", "--samples", "2", check=False).stdout)
+ ov = [f for f in rep["findings"] if f["code"] == "text_overlap"]
+ raw = [f for f in ov if "BELOW THRESHOLD: NO RESULT" in f["message"] and "FAINT: A SECOND MEASUREMENT" in f["message"]]
+ self.assertEqual(len(raw), 1, ov)
+ self.assertEqual(raw[0]["severity"], "warning")
+ self.assertIn("from 0:03", raw[0]["message"])
+ self.assertAlmostEqual(raw[0]["t"], 3.0, delta=0.11)
+ faint = [f for f in ov if "Peak strain" in f["message"] and "faint caption below" in f["message"]]
+ self.assertEqual(len(faint), 1, ov)
+ self.assertIn("from 0:04", faint[0]["message"])
+ for word in ("Left label", "Right label", "Shadowed", "DRAFT", "Final figures", "Stamp", "Raw stamp", "UI detail", "Under the callout"):
+ self.assertFalse([f for f in ov if word in f["message"]], (word, ov))
+ # a crossfade is not a collision on the timeline grid (the samples' older canvas rule can still catch one
+ # mid-fade at a sample time)
+ self.assertFalse([f for f in ov if "Fading" in f["message"] and f.get("grid")], ov)
+
+ def test_13d_check_dom_text_over_canvas_text(self):
+ """A DOM paragraph over a canvas label is text over text too (chart labels under a vertical video's
+ paragraphs): reported from when it starts. So is a canvas counter under a fixed heading, once (its value changes
+ every frame), two labels with the same words, still or moving, each on its own, and a sticker tilted 2 degrees
+ over a heading. A caption on its own opaque plate hides the canvas
+ text under it, rows of kinetic type turned -8 degrees are judged on their letters, not their axis-aligned boxes,
+ DOM text at 8% colour alpha is not readable, and a space drawn on its own is not a text: none of those is
+ reported."""
+ proj = self.tmp / "domovercanvas"
+ write(proj / "showtime.json", json.dumps({"width": 1280, "height": 720, "fps": 30, "duration": 4}))
+ write(proj / "index.html", """<!doctype html><html><head><link rel="stylesheet" href="/_lib/@fontsource-variable/inter/index.css">
+<style>.ov{position:fixed;z-index:5;margin:0;font:500 30px/1.2 "Inter Variable";color:#fff;white-space:nowrap}
+#pill{left:700px;top:560px;padding:10px 18px;background:#111;border-radius:10px}
+.row{left:-40px;width:1400px;font:800 64px/1 "Inter Variable";transform:rotate(-8deg);transform-origin:0 0}</style>
+<script src="/_st/stage.js"></script><script src="/_st/film.js"></script></head><body>
+<p class="ov" style="left:100px;top:280px">Two lines will become one.</p>
+<div class="ov" id="pill" data-caption>Captions sit on a plate</div>
+<p class="ov row" style="top:170px">TYPE IN MOTION TYPE IN MOTION</p>
+<p class="ov row" style="top:230px;left:560px;width:700px">REEL 2026 REEL</p>
+<p class="ov" style="left:300px;top:420px;font-size:40px">RESULTS TWENTY SIX</p>
+<p class="ov" style="left:420px;top:428px;font-size:30px;color:#ff0;transform:rotate(2deg)">STICKER!</p>
+<p class="ov" style="left:900px;top:300px;color:rgba(255,255,255,.08)">Nearly invisible</p>
+<p class="ov" style="left:900px;top:400px">Fixed heading</p>
+<p class="ov" style="left:100px;top:540px">Counter band heading</p>
+<p class="ov" style="left:100px;top:345px">Station band heading over both</p>
+<p class="ov" style="left:700px;top:632px">Orbit band heading over the labels</p>
+<p class="ov" style="left:900px;top:480px;background:linear-gradient(90deg,#f0f,#0ff);-webkit-background-clip:text;background-clip:text;color:transparent">Gradient title</p>
+<script>
+Film.start({ look: 'dark', design: [1280, 720], fonts: ['600 1em "Inter Variable"'], scenes: function (T, g, F) {
+ g.save(); g.textBaseline = 'middle'; g.font = '600 30px "Inter Variable"'; g.fillStyle = '#8fd3ff';
+ if (T >= 2.0) g.fillText('SERIES B', 140, 300);
+ g.fillText('Keep it under 15 minutes', 560, 575); // its left part outside the pill, the rest under it
+ g.fillText(' ', 160, 640); g.fillText('Solo label', 140, 650);
+ g.fillText('UNDER FAINT', 905, 318); g.fillText('Under gradient', 905, 498);
+ g.fillText('TICK ' + Math.floor(T * 30), 110, 558); // a labelled counter
+ g.save(); g.globalAlpha = 0.95 - T * 0.1; g.fillText('STATION 1', 110, 363); g.restore(); // same words, two places,
+ g.fillText('STATION 2', 400, 363); // one fading
+ g.fillText('ORBIT 1', 710 + 220 * (T % 2), 650); g.fillText('ORBIT 2', 1150 - 220 * (T % 2), 650); // moving 22 px a step
+ g.font = '700 40px "Inter Variable"'; g.fillText(String(Math.floor(T * 30)), 905, 420); // a counter, new every frame
+ g.restore();
+} });
+</script></body></html>""")
+ rep = json.loads(showtime("check", proj, "--json", "--no-determinism", "--samples", "2", check=False).stdout)
+ ov = [f for f in rep["findings"] if f["code"] == "text_overlap"]
+ para = [f for f in ov if "Two lines" in f["message"] and "SERIES B" in f["message"]]
+ self.assertEqual(len(para), 1, ov)
+ self.assertEqual(para[0]["source"], "dom+canvas")
+ self.assertIn("overlaps canvas text", para[0]["message"])
+ self.assertAlmostEqual(para[0]["t"], 2.0, delta=0.11)
+ # a sticker tilted 2 degrees is judged by its box (rows at -8 degrees are not); a counter is one text
+ self.assertTrue([f for f in ov if "STICKER!" in f["message"] and "RESULTS TWENTY SIX" in f["message"]], ov)
+ # gradient text (background-clip: text, color transparent) reads at full strength
+ self.assertTrue([f for f in ov if "Gradient title" in f["message"] and "Under gradient" in f["message"]], ov)
+ counter = [f for f in ov if "Fixed heading" in f["message"]]
+ self.assertEqual(len(counter), 1, ov)
+ self.assertEqual(len([f for f in ov if "Counter band heading" in f["message"]]), 1, ov)
+ # labels with the same words in two places are two texts: the still one under the band is reported
+ self.assertEqual(len([f for f in ov if "Station band" in f["message"] and "STATION 2" in f["message"]]), 1, ov)
+ # and each is followed as it moves (a new 16 px cell every step): both moving labels under the band are reported
+ for lab in ("ORBIT 1", "ORBIT 2"):
+ self.assertEqual(len([f for f in ov if "Orbit band" in f["message"] and lab in f["message"]]), 1, (lab, ov))
+ for word in ("Captions sit", "Keep it under", "TYPE IN MOTION", "REEL 2026", "Solo label", '""', "UNDER FAINT", "Nearly invisible"):
+ self.assertFalse([f for f in ov if word in f["message"]], (word, ov))
+
+ def test_13e_check_canvas_text_hidden_or_wiped_is_not_on_screen(self):
+ """On a plain canvas page (no film API), canvas text counts only while it is painted and visible: a label the
+ page stops drawing after a reset (`canvas.width = w`, redrawn on every seek), a label under an opaque card or
+ image painted above the canvas, a label under an opaque tooltip box drawn after it, and an odometer digit
+ clipped away are not on screen, so text over where they were is no collision. A DOM text over a visible canvas
+ label, a pulsing label over a still one and a badge (not a caption) half over a label are."""
+ proj = self.tmp / "canvaswiped"
+ write(proj / "showtime.json", json.dumps({"width": 960, "height": 540, "fps": 30, "duration": 4}))
+ write(proj / "index.html", """<!doctype html><html><head><link rel="stylesheet" href="/_lib/@fontsource-variable/inter/index.css">
+<style>body{margin:0;background:#0b0d12;font-family:"Inter Variable"}#cv,#cv2{position:fixed;left:0;top:0;width:960px;height:540px}
+.ov{position:fixed;z-index:3;margin:0;font:600 24px/1.2 "Inter Variable";color:#fff;white-space:nowrap}
+#card{position:fixed;left:0;top:200px;width:300px;height:160px;background:#000;z-index:2}
+#pic{position:fixed;left:660px;top:200px;width:280px;height:80px;z-index:2}
+#badge{left:760px;top:490px;padding:2px 8px;background:#e33;border-radius:6px;font-size:20px}</style>
+<script src="/_st/stage.js"></script></head><body>
+<canvas id="cv" width="960" height="540"></canvas><canvas id="cv2" width="960" height="540"></canvas><div id="card"></div>
+<img id="pic" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==">
+<p class="ov" id="late" style="left:330px;top:42px">Late heading</p>
+<p class="ov" style="left:30px;top:232px">End card line</p>
+<p class="ov" style="left:330px;top:232px">Real collision</p>
+<p class="ov" style="left:670px;top:222px">On the image</p>
+<p class="ov" id="badge">NEW</p>
+<p class="ov" style="left:30px;top:470px">Over the kept label</p>
+<p class="ov" style="left:360px;top:134px">Over the gap</p>
+<p class="ov" style="left:140px;top:104px">Hole watcher</p>
+<script>
+var c2 = document.getElementById('cv2'), g = document.getElementById('cv').getContext('2d'), g2 = c2.getContext('2d');
+var late = document.getElementById('late');
+ST.onSeek(function (t) {
+ c2.width = 960; // this canvas is reset on every seek and draws no text from 2 s on
+ g2.fillStyle = '#ffd38f'; g2.font = '600 24px "Inter Variable"'; g2.textBaseline = 'middle';
+ if (t < 2) g2.fillText('Gone after 2 s', 340, 58);
+ late.style.opacity = t >= 2 ? '1' : '0';
+ g.clearRect(0, 0, 960, 540);
+ g.fillStyle = '#8fd3ff'; g.font = '600 24px "Inter Variable"'; g.textBaseline = 'middle';
+ g.fillText('Axis label', 40, 60);
+ g.fillText('Under the card', 40, 250);
+ g.fillText('Bare label', 340, 250);
+ g.fillText('Under the image', 675, 240);
+ g.fillText('Axis under tooltip', 670, 60);
+ g.fillStyle = '#222'; g.fillRect(660, 40, 280, 40); // an opaque tooltip box over the axis label
+ g.fillStyle = '#ffffff'; g.fillText('Tooltip: 42 units', 670, 62);
+ g.fillStyle = '#8fd3ff'; g.fillText('Under the pill', 670, 140);
+ g.fillStyle = '#333'; g.beginPath(); g.roundRect(660, 120, 280, 40, 12); g.fill(); // a pill drawn as a path
+ g.fillStyle = '#ffffff'; g.fillText('Pill: 7 items', 672, 142);
+ g.fillStyle = '#8fd3ff'; g.fillText('Between the bars', 360, 150);
+ g.fillStyle = '#8fd3ff'; g.fillText('Under the stray pill', 340, 300);
+ g.fillStyle = '#333'; g.beginPath(); g.roundRect(330, 285, 280, 30, 8); g.moveTo(900, 500); g.fill(); // a moveTo paints nothing
+ g.fillStyle = '#ffffff'; g.fillText('Stray: 3 items', 342, 302);
+ g.fillStyle = '#8fd3ff'; g.fillText('HOLE', 150, 120);
+ g.fillStyle = '#333'; g.beginPath(); g.rect(30, 100, 200, 40); g.rect(130, 100, 200, 40); g.fill('evenodd'); // 130-230 unpainted
+ g.fillStyle = '#8fd3ff'; g.fillText('Under the moved box', 340, 345);
+ g.save(); g.fillStyle = '#333'; g.beginPath(); g.rect(330, 330, 280, 30); g.setTransform(1, 0, 0, 1, 0, -200); g.fill(); g.restore();
+ g.fillStyle = '#ffffff'; g.fillText('Moved: 9 items', 342, 347); // the rect was painted where the path was built
+ g.fillStyle = '#333'; g.beginPath(); g.rect(330, 130, 20, 40); g.rect(600, 130, 20, 40); g.fill(); // two bars, one path
+ g.save(); g.beginPath(); g.rect(660, 330, 120, 40); g.clip(); // an odometer: the next digit waits below, clipped
+ g.font = '700 40px "Inter Variable"'; g.fillText('7', 670, 350); g.fillText('8', 670, 400); g.restore();
+ g.fillStyle = '#8fd3ff'; g.font = '600 24px "Inter Variable"'; g.fillText('COUNT LABEL', 662, 400);
+ g.fillText('Still label', 676, 456);
+ // the pulsing label blinks between grid steps (0.1 s apart here)
+ g.save(); g.globalAlpha = Math.round(t * 10) % 2 ? 0.6 : 1; g.fillStyle = '#ffffff'; g.fillText('Pulsing label', 670, 460); g.restore();
+ g.fillText('Partly under the badge', 700, 505);
+ g.fillText('Kept outside the clip', 40, 485);
+ g.save(); g.beginPath(); g.rect(0, 0, 8, 8); g.clip(); g.clearRect(0, 0, 960, 540); g.restore(); // clears 8 px only
+ g.font = '600 8px "Inter Variable"';
+ for (var i = 0; i < 305; i++) g.fillText('.', 10 + (i % 61) * 10, 384 + Math.floor(i / 61) * 12); // past the cap
+});
+</script></body></html>""")
+ rep = json.loads(showtime("check", proj, "--json", "--no-determinism", "--samples", "2", check=False).stdout)
+ ov = [f for f in rep["findings"] if f["code"] == "text_overlap"]
+ for a, b in (("Real collision", "Bare label"), ("Pulsing label", "Still label"), ("NEW", "Partly under the badge"),
+ ("Over the kept label", "Kept outside the clip"), ("Over the gap", "Between the bars"), ("Hole watcher", "HOLE")):
+ hit = [f for f in ov if a in f["message"] and b in f["message"]]
+ self.assertEqual(len(hit), 1, (a, b, ov))
+ self.assertEqual([f for f in ov if "Real collision" in f["message"]][0]["source"], "dom+canvas")
+ for word in ("Gone after", "Under the card", "End card line", "Late heading", "Axis label", "Under the image",
+ "On the image", "Axis under tooltip", "COUNT LABEL", "Under the pill", "Under the stray pill",
+ "Under the moved box"):
+ self.assertFalse([f for f in ov if word in f["message"]], (word, ov))
+ # more texts than check compares: said once, as a note
+ cap = [f for f in ov if f.get("dropped")]
+ self.assertEqual(len(cap), 1, ov)
+ self.assertEqual(cap[0]["severity"], "info")
+ self.assertIn("not checked for text over text", cap[0]["message"])
+
+ def test_13e2_check_canvas_fills_that_leave_text_visible_hide_nothing(self):
+ """A canvas fill hides the text under it only when it surely paints over it: not a box with a NaN side (it paints
+ nothing; before, it dropped every text on the canvas), nor one inside a clip an overflowing transform made NaN, not a path with a curve in it (here a circle cut out of a
+ box), not a translucent fill (a path or a fillRect), not two boxes that wind opposite ways (they cancel), and a gradient title
+ (background-clip: text) does not hide the DOM text under it. Each label stays, so the DOM text over it is a
+ collision."""
+ proj = self.tmp / "canvasnocover"
+ write(proj / "showtime.json", json.dumps({"width": 960, "height": 540, "fps": 30, "duration": 3}))
+ write(proj / "index.html", """<!doctype html><html><head><link rel="stylesheet" href="/_lib/@fontsource-variable/inter/index.css">
+<style>body{margin:0;background:#0b0d12;font-family:"Inter Variable"}#cv{position:fixed;left:0;top:0;width:960px;height:540px}
+.ov{position:fixed;z-index:3;margin:0;font:600 24px/1.2 "Inter Variable";color:#fff;white-space:nowrap}
+#title{z-index:4;font-size:30px;background:#0b0d12 linear-gradient(90deg,#f0f,#0ff);-webkit-background-clip:text;background-clip:text;color:transparent}</style>
+<script src="/_st/stage.js"></script></head><body>
+<canvas id="cv" width="960" height="540"></canvas>
+<p class="ov" style="left:30px;top:48px">NaN watcher</p>
+<p class="ov" style="left:500px;top:48px">Clip watcher</p>
+<p class="ov" style="left:150px;top:148px">Peek watcher</p>
+<p class="ov" style="left:30px;top:248px">Over the glass</p>
+<p class="ov" style="left:500px;top:248px">Over the tint</p>
+<p class="ov" style="left:30px;top:348px">Cancel watcher</p>
+<p class="ov" style="left:30px;top:448px">Plain under the title</p>
+<p class="ov" id="title" style="left:24px;top:440px">Gradient heading</p>
+<script>
+var g = document.getElementById('cv').getContext('2d');
+ST.onSeek(function (t) {
+ g.clearRect(0, 0, 960, 540);
+ g.font = '600 24px "Inter Variable"'; g.textBaseline = 'middle';
+ g.fillStyle = '#8fd3ff'; g.fillText('Behind the NaN', 40, 60);
+ g.fillStyle = '#333'; g.fillRect(NaN, 0, 10, 10); g.beginPath(); g.rect(30, NaN, 300, 40); g.fill();
+ g.fillStyle = '#8fd3ff'; g.fillText('Behind the big clip', 510, 60);
+ // a clip whose box overflows: rotated and scaled, its far corner is Infinity - Infinity (NaN) in frame pixels
+ g.save(); g.rotate(Math.PI / 4); g.scale(1e30, 1e30); g.beginPath(); g.rect(0, 0, 1e300, 1e300); g.clip();
+ g.setTransform(1, 0, 0, 1, 0, 0); g.fillStyle = '#333'; g.fillRect(900, 500, 20, 20); g.restore();
+ g.fillStyle = '#8fd3ff'; g.fillText('Peek', 152, 160); // seen through the hole the circle cuts out of the rectangle
+ g.fillStyle = '#333'; g.beginPath(); g.rect(30, 140, 300, 40); g.moveTo(220, 160); g.arc(180, 160, 40, 0, 2 * Math.PI, true); g.fill();
+ g.fillStyle = '#8fd3ff'; g.fillText('Under the glass', 40, 260);
+ g.fillStyle = 'rgba(0, 0, 0, 0.5)'; g.beginPath(); g.roundRect(30, 240, 300, 40, 8); g.fill();
+ g.fillStyle = '#8fd3ff'; g.fillText('Under the tint', 510, 260);
+ g.fillStyle = 'rgba(0, 0, 0, 0.5)'; g.fillRect(500, 240, 300, 40); // a translucent fillRect
+ g.fillStyle = '#8fd3ff'; g.fillText('Cancelled box', 40, 360);
+ g.fillStyle = '#333'; g.beginPath(); g.rect(30, 340, 300, 40); g.rect(330, 340, -300, 40); g.fill(); // nonzero: 0
+ g.fillStyle = '#8fd3ff'; g.fillText('Gradient witness', 40, 460);
+});
+</script></body></html>""")
+ rep = json.loads(showtime("check", proj, "--json", "--no-determinism", "--samples", "2", check=False).stdout)
+ ov = [f for f in rep["findings"] if f["code"] == "text_overlap"]
+ for a, b in (("NaN watcher", "Behind the NaN"), ("Clip watcher", "Behind the big clip"), ("Peek watcher", "Peek"), ("Over the glass", "Under the glass"), ("Over the tint", "Under the tint"),
+ ("Cancel watcher", "Cancelled box"), ("Plain under the title", "Gradient witness")):
+ hit = [f for f in ov if a in f["message"] and "\"%s\"" % b in f["message"]]
+ self.assertEqual(len(hit), 1, (a, b, ov))
+
+ def test_13f_check_canvas_text_outside_the_vertical_safe_box(self):
+ """In a vertical frame, canvas text drawn by the page itself (not the film API) outside the safe box feed UI
+ leaves free is reported from check's whole-timeline grid, once per text with its span: a label held under the
+ bottom rail and a counter past the right rail ("Year n", one text while its number changes); two labels with the
+ same words ("Gate 1", "Gate 2") held below the safe box are two texts, one finding each, and a counter beside a
+ label with its words ("Level n" past the right rail, "Level 5" above the safe box until it goes) is still one
+ text. A label sliding in through the margin, one parked mostly off the frame, small UI detail and text inside
+ the safe box are not; in a film, F.text outside the safe box is one finding (the sample rule's, also with a
+ double space in it), and raw text inside F.decor is UI detail."""
+ proj = self.tmp / "canvassafe"
+ write(proj / "showtime.json", json.dumps({"width": 540, "height": 960, "fps": 30, "duration": 3}))
+ write(proj / "index.html", """<!doctype html><html><head><link rel="stylesheet" href="/_lib/@fontsource-variable/inter/index.css">
+<style>body{margin:0;background:#0b0d12}#cv{position:fixed;left:0;top:0;width:540px;height:960px}</style>
+<script src="/_st/stage.js"></script></head><body><canvas id="cv" width="540" height="960"></canvas>
+<script>
+var g = document.getElementById('cv').getContext('2d');
+ST.onSeek(function (t) {
+ g.clearRect(0, 0, 540, 960);
+ g.fillStyle = '#ffffff'; g.font = '600 24px "Inter Variable"'; g.textBaseline = 'middle'; g.textAlign = 'left';
+ g.fillText('Inside the safe box', 60, 400);
+ g.fillText('Held below the safe box', 60, 800); // the safe box ends at y 720 here (1440 of 1920)
+ g.fillText('Gate 1', 60, 860); g.fillText('Gate 2', 300, 860); // same words: each its own text
+ g.fillText('Sliding in', Math.min(60, -150 + t * 600), 300); // through the left margin in a third of a second
+ g.fillText('Parked off the frame', -200, 500); // mostly past the left edge (a camera move left it there)
+ g.textAlign = 'right'; g.fillText('Year ' + (1990 + Math.floor(t * 10)), 530, 200); // past x 458
+ g.fillText('Level ' + (10 + Math.floor(t * 10)), 530, 600); // a counter past x 458, its number changing every step
+ g.textAlign = 'left'; if (t < 1.5) g.fillText('Level 5', 60, 60); // a still label with its words above the safe box, gone halfway
+ g.textAlign = 'left'; g.font = '600 8px "Inter Variable"'; g.fillText('tiny axis note', 4, 940);
+});
+</script></body></html>""")
+ rep = json.loads(showtime("check", proj, "--json", "--no-determinism", "--samples", "2", check=False).stdout)
+ sz = [f for f in rep["findings"] if f["code"] == "safe_zone"]
+ self.assertEqual(len([f for f in sz if f.get("text") == "Held below the safe box"]), 1, sz)
+ held = [f for f in sz if f.get("text") == "Held below the safe box"][0]
+ self.assertTrue(held.get("grid"), held)
+ self.assertEqual(held["severity"], "warning")
+ self.assertIn("bottom at y", held["message"])
+ self.assertLess(held["t"], 0.3, held)
+ year = [f for f in sz if f.get("text", "").startswith("Year")]
+ self.assertEqual(len(year), 1, sz)
+ self.assertLess(year[0]["t"], 0.5, year) # one text from its first steps, while the number changes
+ self.assertGreater(year[0]["until"] - year[0]["t"], 2, year)
+ for word in ("Gate 1", "Gate 2", "Level 5"):
+ self.assertEqual(len([f for f in sz if f.get("text") == word]), 1, (word, sz))
+ level = [f for f in sz if f.get("text", "").startswith("Level") and f.get("text") != "Level 5"]
+ self.assertEqual(len(level), 1, sz) # not split per value by its same-words sibling
+ self.assertGreater(level[0]["until"] - level[0]["t"], 2, level)
+ for word in ("Inside the safe box", "Sliding in", "tiny axis note", "Parked off the frame"):
+ self.assertFalse([f for f in sz if word in f["message"]], (word, sz))
+ # the phone check counts it (its zone part)
+ self.assertTrue(any("Held below the safe box" in (i.get("message") or "") for i in rep["phone"]["items"]), rep["phone"])
+ # a film: F.text outside the safe box is reported once (the sample rule's finding, not again from the grid); raw
+ # canvas text drawn inside F.decor is UI detail
+ film = self.tmp / "filmsafe"
+ write(film / "showtime.json", json.dumps({"width": 540, "height": 960, "fps": 30, "duration": 3}))
+ write(film / "index.html", """<!doctype html><html><head><link rel="stylesheet" href="/_lib/@fontsource-variable/inter/index.css">
+<script src="/_st/stage.js"></script><script src="/_st/film.js"></script></head><body><script>
+Film.start({ look: 'dark', design: [540, 960], fonts: ['600 1em "Inter Variable"'], scenes: function (T, g, F) {
+ F.text('Film label low', 60, 820, { size: 26 });
+ F.text('Spaced label low', 300, 900, { size: 26 });
+ g.save(); g.font = '600 26px "Inter Variable"'; g.fillStyle = '#ffffff';
+ F.decor(function () { g.fillText('UI detail low', 60, 880); }); g.restore();
+ F.text('Film label inside', 60, 400, { size: 26 });
+} });
+</script></body></html>""")
+ rep = json.loads(showtime("check", film, "--json", "--no-determinism", "--samples", "2", check=False).stdout)
+ sz = [f for f in rep["findings"] if f["code"] == "safe_zone"]
+ self.assertEqual(len([f for f in sz if "Film label low" in f["message"]]), 1, sz)
+ self.assertEqual(len([f for f in sz if "Spaced" in f["message"]]), 1, sz) # one key for both rules
+ for word in ("UI detail low", "Film label inside"):
+ self.assertFalse([f for f in sz if word in f["message"]], (word, sz))
+
+ def test_13g_check_raw_canvas_text_size_on_the_timeline(self):
+ """Canvas text a page draws itself (raw fillText, no film API) is measured for size on check's whole-timeline grid,
+ as DOM and F.text are: a tiny held label is one tiny_text warning, a counter in one place is one text, a readable
+ or faint label or one mostly off the frame is not reported. In a film, an F.text is measured once (not again as
+ the raw draw under it) and raw text inside F.decor is UI detail."""
+ import re
+ raw = self.tmp / "rawtiny"
+ write(raw / "showtime.json", json.dumps({"width": 960, "height": 540, "fps": 30, "duration": 3}))
+ write(raw / "index.html", """<!doctype html><html><head><link rel="stylesheet" href="/_lib/@fontsource-variable/inter/index.css">
+<style>body{margin:0;background:#0b0d12}#cv{position:fixed;left:0;top:0;width:960px;height:540px}</style>
+<script src="/_st/stage.js"></script></head><body><canvas id="cv" width="960" height="540"></canvas>
+<script>
+var g = document.getElementById('cv').getContext('2d');
+ST.onSeek(function (t) {
+ g.clearRect(0, 0, 960, 540); g.textBaseline = 'middle'; g.fillStyle = '#e8edf5';
+ g.font = '600 6px "Inter Variable"'; g.fillText('tiny raw caption', 40, 60);
+ g.font = '600 30px "Inter Variable"'; g.fillText('Readable raw label', 40, 160);
+ g.font = '600 7px "Inter Variable"'; g.fillText(String(100 + Math.floor(t * 10)), 40, 260); // a counter
+ g.save(); g.globalAlpha = 0.3; g.font = '600 6px "Inter Variable"'; g.fillText('faint raw note', 40, 360); g.restore();
+ g.font = '600 6px "Inter Variable"'; g.fillText('mostly off the frame', 950, 460);
+});
+</script></body></html>""")
+ rep = json.loads(showtime("check", raw, "--json", "--no-determinism", "--samples", "2", check=False).stdout)
+ tiny = [f for f in rep["findings"] if f["code"] == "tiny_text" and f["severity"] == "warning"]
+ hit = [f for f in tiny if "tiny raw caption" in f["message"]]
+ self.assertEqual(len(hit), 1, tiny)
+ self.assertEqual(hit[0].get("source"), "canvas")
+ self.assertEqual(len([f for f in tiny if re.search(r'"1\d\d"', f["message"])]), 1, tiny)
+ for word in ("Readable raw label", "faint raw note", "mostly off the frame"):
+ self.assertFalse([f for f in tiny if word in f["message"]], (word, tiny))
+ film = self.tmp / "filmtiny"
+ write(film / "showtime.json", json.dumps({"width": 960, "height": 540, "fps": 30, "duration": 3}))
+ write(film / "index.html", """<!doctype html><html><head><link rel="stylesheet" href="/_lib/@fontsource-variable/inter/index.css">
+<script src="/_st/stage.js"></script><script src="/_st/film.js"></script></head><body><script>
+Film.start({ look: 'dark', design: [960, 540], fonts: ['600 1em "Inter Variable"'], scenes: function (T, g, F) {
+ F.text('film tiny note', 40, 60, { size: 6 });
+ F.text('Film readable', 40, 160, { size: 30 });
+ g.save(); g.font = '600 6px "Inter Variable"'; g.fillStyle = '#ffffff';
+ F.decor(function () { g.fillText('decor tiny detail', 40, 260); }); g.restore();
+} });
+</script></body></html>""")
+ rep = json.loads(showtime("check", film, "--json", "--no-determinism", "--samples", "2", check=False).stdout)
+ tiny = [f for f in rep["findings"] if f["code"] == "tiny_text" and f["severity"] == "warning"]
+ self.assertEqual(len([f for f in tiny if "film tiny note" in f["message"]]), 1, tiny)
+ for word in ("Film readable", "decor tiny detail"):
+ self.assertFalse([f for f in tiny if word in f["message"]], (word, tiny))
+
def test_14_check_judges_settled_frame_after_transition(self):
"""Text sliding through the vertical safe zone during a push transition is a note naming the
transition; the settled frame after it is sampled and passes."""
diff --git a/skills/showtime/tests/test_render_speed.py b/skills/showtime/tests/test_render_speed.py
index a02d5e3..84a7958 100644
--- a/skills/showtime/tests/test_render_speed.py
+++ b/skills/showtime/tests/test_render_speed.py
@@ -338,7 +338,9 @@ class TestRender(unittest.TestCase):
r1, _ = render(self.proj, o / "w1" / "final.mp4", "--gpu", "off", "--workers", 1, "--no-audio", env=seq_env)
self.assertEqual(r3["encode"], {"codec": "libx264", "preset": "veryfast", "crf": 16, "during_capture": True})
self.assertEqual(r1["encode"], {"codec": "libx264", "preset": "veryfast", "crf": 16})
- self.assertEqual((r3["workers"], r3["workers_why"]), (3, "--workers 3"))
+ self.assertEqual(r3["workers"], 3)
+ # a container's memory or CPU limit adds a note after the flag (render.mjs: "--workers 3; memory limit ...")
+ self.assertRegex(r3["workers_why"], r"^--workers 3(; .+)?$")
self.assertTrue(r3["browser"]["software_gl"])
self.assertEqual(r3["frames"], 150)
self.assertEqual(md5(r3["output"]), md5(r1["output"]), "same bytes: 3 workers + encode during capture vs 1 worker + encode after")
diff --git a/skills/showtime/tests/test_repro.py b/skills/showtime/tests/test_repro.py
index 3b7937c..733333b 100644
--- a/skills/showtime/tests/test_repro.py
+++ b/skills/showtime/tests/test_repro.py
@@ -597,7 +597,8 @@ class TestRedaction(unittest.TestCase):
self.assertEqual(red("see http://localhost:3000/login?next=/admin&t=abc#x now"), "see http://localhost:3000/login now")
self.assertEqual(red("navigating to /api/users?id=7"), "navigating to /api/users")
self.assertEqual(red("expected /^Welcome?/i"), "expected /^Welcome?/i")
- self.assertIn(rp.MASK, red("Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NSJ9.abcdefghijklmno"))
+ jwt = "eyJhbGciOiJIUzI1NiJ9" + ".eyJzdWIiOiIxMjM0NSJ9.abcdefghijklmno" # in pieces (check_release secrets)
+ self.assertIn(rp.MASK, red("Authorization: Bearer " + jwt))
def test_paths_show_their_last_part(self):
red = rp.Redactor()
diff --git a/skills/showtime/tests/test_runtime.py b/skills/showtime/tests/test_runtime.py
index 01468b0..7869b53 100644
--- a/skills/showtime/tests/test_runtime.py
+++ b/skills/showtime/tests/test_runtime.py
@@ -124,6 +124,13 @@ PAGES["crop.html"] = page(
'A small fridge running backwards, all winter long</p></section>',
{"width": 1920, "height": 1080, "fps": 30, "duration": 2})
PAGES["index.html"] = PAGES["square.html"]
+# the stage's URL query: a page script that set Object.prototype.st must not make the stage read st=embed (the query
+# is a map with no prototype), and a malformed escape (%) must not stop the runtime
+QUERY_HEAD = '<!doctype html><html><head><meta charset="utf-8">'
+PAGES["inherit.html"] = (QUERY_HEAD + '<script>Object.prototype.st = "embed";</script><script src="/_st/stage.js"></script>'
+ '</head><body><p>inherit</p></body></html>')
+PAGES["badquery.html"] = (QUERY_HEAD + '<script>window.__errs = []; addEventListener("error", (e) => __errs.push(String(e.message)));'
+ '</script><script src="/_st/stage.js"></script></head><body><p>q</p></body></html>')
PROBE = r"""
import path from 'node:path';
@@ -198,6 +205,17 @@ try {
const fs = await import('node:fs');
fs.writeFileSync(path.join(dir, 'crop-frame.png'), await s.shot({ format: 'png' }));
await s.close();
+ // the query: an inherited st does not count (the page opened on its own goes to the player), a bad escape is skipped
+ const qctx = await newCaptureContext(b.browser, { css: { width: 320, height: 200 }, dpr: 1 });
+ let qp = await qctx.newPage();
+ await qp.goto(server.url + '/inherit.html');
+ await qp.waitForURL(/\/_st\/preview/, { timeout: 15000 }).catch(() => {});
+ R.inheritUrl = new URL(qp.url()).pathname;
+ qp = await qctx.newPage();
+ await qp.goto(server.url + '/badquery.html?x=%&__proto__=polluted&st=raw');
+ R.badQuery = await qp.evaluate(() => ({ st: typeof window.ST, errs: window.__errs, polluted: ({}).polluted === undefined ? null : 'yes',
+ path: location.pathname }));
+ await qctx.close();
R.redact = [redactUrl('http://127.0.0.1:4000/board/?k=s3cret&view=1#c2'), redactUrl('https://me:[email protected]/a?token=x')];
} finally { await b.browser.close(); await server.close(); }
console.log(JSON.stringify(R));
@@ -253,6 +271,13 @@ class RuntimeFixes(unittest.TestCase):
self.assertEqual(self.R["chart"]["vals"], 0)
self.assertEqual(self.R["chart"]["cu"], "13,7")
+ def test_query_has_no_prototype_and_bad_escapes_are_skipped(self):
+ # an inherited Object.prototype.st is not st=embed: the page opened on its own goes to the player
+ self.assertEqual(self.R["inheritUrl"], "/_st/preview")
+ # ?x=% (a malformed escape) is skipped: the runtime still loads (st=raw keeps the page), nothing polluted
+ self.assertEqual(self.R["badQuery"], {"st": "object", "errs": [], "polluted": None, "path": "/badquery.html"},
+ self.R["badQuery"])
+
def test_late_defined_component_mounts(self):
L = self.R["late"]
self.assertEqual(L["badge"], "mounted")
diff --git a/skills/showtime/tests/test_skill_structure.py b/skills/showtime/tests/test_skill_structure.py
index d67d76a..9257a50 100644
--- a/skills/showtime/tests/test_skill_structure.py
+++ b/skills/showtime/tests/test_skill_structure.py
@@ -26,6 +26,7 @@ import shutil
import sys
import tempfile
import unittest
+from unittest import mock
from pathlib import Path
TESTS_DIR = Path(__file__).resolve().parent
@@ -106,9 +107,8 @@ class TestRepoHygiene(unittest.TestCase):
self.assertRegex(text, r"(?m)^\*\s+-text\s*$")
for line in text.splitlines():
self.assertEqual(cr.checkout_rewrites(line), [], line)
- import subprocess
- tracked = subprocess.run(["git", "ls-files", "-z"], cwd=str(REPO), stdout=subprocess.PIPE, check=True).stdout.decode("utf-8").split("\0")
- tracked = [t for t in tracked if t and (REPO / t).is_file()]
+ # the shipped files (git's list, or a walk of the folder where there is no .git: a tarball on another machine)
+ tracked = [cr.rel(p) for p in cr.shipped_files()]
shims = [t for t in tracked if t.lower().endswith((".cmd", ".bat", ".ps1"))]
posix = [t for t in tracked if t.endswith(".sh") or t == "skills/showtime/bin/showtime"]
self.assertTrue(shims and posix)
@@ -120,13 +120,40 @@ class TestRepoHygiene(unittest.TestCase):
def test_checkout_rewrite_check_and_mutants(self):
import shutil
+ import subprocess
import tempfile
for line in ("*.cmd text eol=crlf", "* text=auto eol=lf", "*.a filter=lfs diff=lfs merge=lfs", "*.b ident",
"*.c working-tree-encoding=UTF-16", "d export-ignore", "e export-subst", "*.f eol=lf", "*.g text=auto",
"*.i crlf", "*.j -crlf", "*.k crlf=input", "*.l !text", "*.m text", "*.n !crlf", "a#b text eol=lf"):
self.assertNotEqual(cr.checkout_rewrites(line), [], line)
- for line in ("* -text", "*.png binary", "# *.cmd text eol=crlf", "", "*.h -text # eol=lf", "a#b -text", "*.png binary # text"):
+ for line in ("* -text", "*.png binary", "# *.cmd text eol=crlf", "", "*.h -text # eol=lf", "a#b -text", "*.png binary # text",
+ "*.cmd text eol=crlf # git ignores this line whole"):
self.assertEqual(cr.checkout_rewrites(line), [], line)
+ for line in ('"a b" text eol=crlf', '"a b" text'): # a quoted pattern with a space is still checked
+ self.assertNotEqual(cr.checkout_rewrites(line), [], line)
+ GA_CASES = (("* -text # note", "#"), ("* -text #note", "#note"), ("*.x text bad$name", "bad$name"), ("* -text", None),
+ ("a#b -text", None), ("* -text x=#y !eol a.b_c-d", None), ("# * -text # x", None), ("", None),
+ ('"a b" text', None), ('"a b" text eol=crlf', None), ('"a\\"b c" -text', None), ("* --text", "--text"),
+ ("* -", "-"), ("* !-x", "!-x"), ("* -text\xa0x", "-text\xa0x"), ("*\t-text", None), ("[attr]bin -text -diff", None))
+ for line, bad in GA_CASES:
+ self.assertEqual(cr.git_ignored_attr(line), bad, line)
+ git = shutil.which("git")
+ if git: # the same verdicts from git itself: it names the token it refuses and leaves the line's attributes unset
+ g = Path(tempfile.mkdtemp(prefix="st-ga-git-"))
+ try:
+ subprocess.run([git, "init", "-q", str(g)], check=True)
+ for line, _bad in GA_CASES:
+ if not line or line.startswith("#"):
+ continue
+ (g / ".gitattributes").write_text(line + "\n", encoding="utf-8")
+ cp = subprocess.run([git, "check-attr", "text", "--", "a.cmd"], cwd=str(g), stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE, encoding="utf-8", env=dict(os.environ, LC_ALL="C", LANGUAGE=""))
+ refused = "is not a valid attribute name" in cp.stderr
+ self.assertEqual(refused, cr.git_ignored_attr(line) is not None, (line, cp.stdout, cp.stderr))
+ if refused:
+ self.assertIn("text: unspecified", cp.stdout, line)
+ finally:
+ shutil.rmtree(str(g), ignore_errors=True)
d = Path(tempfile.mkdtemp(prefix="st-ga-"))
real = cr.REPO
try:
@@ -156,9 +183,12 @@ class TestRepoHygiene(unittest.TestCase):
(d / "run.sh").write_bytes(b"#!/bin/sh\r\n")
self.assertTrue(any("CR bytes" in m for m in errors()), errors())
(d / "run.sh").write_bytes(files["run.sh"])
- # mutants 4-5: no `* -text` in the root, and a nested .gitattributes
+ # mutants 4-5: no `* -text` in the root (or one git ignores: a comment after it), and a nested .gitattributes
(d / ".gitattributes").write_text("*.png binary\n", encoding="utf-8")
self.assertTrue(any("needs a `* -text`" in m for m in errors()), errors())
+ (d / ".gitattributes").write_text("* -text # stored byte-exact\n", encoding="utf-8")
+ self.assertTrue(any("needs a `* -text`" in m for m in errors()), errors())
+ self.assertTrue(any("git ignores this whole line" in m for m in errors()), errors())
(d / ".gitattributes").write_text("* -text\n", encoding="utf-8")
(d / "sub").mkdir()
(d / "sub" / ".gitattributes").write_text("*.x text\n", encoding="utf-8")
@@ -357,6 +387,120 @@ class TestCheckersBite(unittest.TestCase):
finally:
shutil.rmtree(str(d), ignore_errors=True)
+ def test_routing_reads_its_own_guide_and_reports_once(self):
+ # a route-<topic> case must read references/workflows/<topic>.md (not any guide that exists); a pattern that is
+ # not a regex is one error, not two; a workflow guide needs its line in references/index.md
+ import shutil
+ import tempfile
+ d = Path(tempfile.mkdtemp(prefix="st-route2-"))
+ try:
+ skill, evals = d / "skill", d / "benchmarks"
+ (skill / "references" / "workflows").mkdir(parents=True)
+ for t in ("alpha", "beta", "gamma"):
+ (skill / "references" / "workflows" / (t + ".md")).write_text("# x\n", encoding="utf-8")
+ (skill / "references" / "index.md").write_text("- workflows/alpha.md\n- workflows/beta.md\n- workflows/gamma.md.bak\n",
+ encoding="utf-8") # gamma.md.bak is not gamma.md
+
+ def case(name, pattern):
+ g = evals / "routing-eval" / name / "graders"
+ g.mkdir(parents=True)
+ (g.parent / "prompt.md").write_text("---\nruns: 3\n---\n\nMake a video.\n", encoding="utf-8")
+ (g / "reads-the-guide.md").write_text("---\ntype: tool_used\ntool: Read\ninput_match: '%s'\n---\n"
+ % pattern, encoding="utf-8")
+ (g / "names-the-first-command.md").write_text("---\ntype: regex\ntarget: last_message\n"
+ "pattern: 'x'\n---\n", encoding="utf-8")
+ case("route-alpha", r"workflows/alpha\.md")
+ case("route-beta", r"workflows/alpha\.md") # copied from route-alpha: names a guide, not its own
+ case("route-gamma", r"workflows/(gamma\.md") # not a regex
+ case("route-delta", r"workflows/gamma\.md") # no workflows/delta.md: any guide that exists will do
+ f = cr.Findings()
+ cr.check_routing(f, evals=evals, skill=skill, legacy=set())
+ errs = sorted(i["message"] for i in f.errors())
+ self.assertEqual(len(errs), 4, fmt(f.items))
+ self.assertIn("route-gamma: the Read pattern", errs[0]) # once: no "has no Read grader" too
+ self.assertIn("route-beta does not read its own guide references/workflows/beta.md "
+ "(its pattern matches references/workflows/alpha.md)", errs[1])
+ self.assertIn("beta.md has no routing eval case", errs[2]) # so nothing reads beta.md
+ self.assertIn("gamma.md has no line in references/index.md", errs[3])
+ finally:
+ shutil.rmtree(str(d), ignore_errors=True)
+
+ def test_changelog_rule(self):
+ import tempfile
+ d = Path(tempfile.mkdtemp(prefix="st-changelog-"))
+ try:
+ log = d / "CHANGELOG.md"
+ log.write_text("# Changelog\n\n## 9.9.9 (unreleased)\n\n"
+ "- **Fixed: a widget.** It now turns\n the right way.\n"
+ "- **New: a gadget.** It hums.\n"
+ "- **Fixed: a widget.** It now turns the\n right way.\n" # the same bullet, rewrapped
+ "- **Fixed: a widget:** it also stops.\n" # same lead, other text
+ "- " + "long " * 30 + "\n\n"
+ "## 9.9.8 (2000-01-01)\n\n- **New: a gadget.** It hums.\n- **New: a gadget.** It hums.\n",
+ encoding="utf-8")
+ f = cr.Findings()
+ cr.check_changelog(f, log)
+ self.assertEqual([(i["message"], i["where"].rsplit(":", 1)[1]) for i in f.errors()],
+ [("this bullet repeats the one at line 5 (keep one)", "8")], fmt(f.items))
+ warns = sorted((i["where"].rsplit(":", 1)[1], i["message"]) for i in f.items if i["level"] == "warning")
+ self.assertEqual([w[0] for w in warns], ["10", "11"], fmt(f.items))
+ self.assertIn("lead repeats the one at line 5", warns[0][1])
+ self.assertIn("line of 152 characters", warns[1][1])
+ # released sections are history: their repeats are not this check's business; no unreleased section, no finding
+ log.write_text("## 9.9.8 (2000-01-01)\n\n- a\n- a\n", encoding="utf-8")
+ f = cr.Findings()
+ cr.check_changelog(f, log)
+ self.assertEqual(f.items, [])
+ self.assertIn("changelog", cr.default_checks())
+ self.assertEqual(cr.run_checks(only=["changelog"]).items, [], "the real CHANGELOG passes, warnings included")
+ finally:
+ import shutil
+ shutil.rmtree(str(d), ignore_errors=True)
+
+ def test_windows_names_rule(self):
+ import tempfile
+ d = Path(tempfile.mkdtemp(prefix="st-winnames-"))
+ try:
+ tests = d / "skills" / "showtime" / "tests"
+ tests.mkdir(parents=True)
+ dev = "n" + "ul" # built here so this file names no such file itself
+ py = tests / "test_x.py"
+ py.write_text("# a comment may say %s.csv\nA = '%s.csv'\nB = 'data/%s.json'\nC = 'Aux.Txt'\n"
+ "D = 'null.csv'\nE = 'console.log'\nF = '%s'\ndef t():\n \"\"\"docstring %s.csv\"\"\"\n"
+ "G = f'{d}/%s.txt'\n"
+ % (dev, dev, dev.upper(), dev, dev, dev), encoding="utf-8")
+ js = tests / "x.mjs"
+ js.write_text("// %s.csv in a comment\nconst a = `com1.txt`, b = 'lpt9.log';\n" % dev, encoding="utf-8")
+ other = d / "scripts" / "y.py" # not a test: its strings are not file names it writes
+ other.parent.mkdir()
+ other.write_text("A = '%s.csv'\n" % dev, encoding="utf-8")
+ bad = d / "examples" / ("C" + "ON.md")
+ bad.parent.mkdir()
+ bad.write_text("x\n", encoding="utf-8")
+ with mock.patch.object(cr, "REPO", d):
+ f = cr.Findings()
+ cr.check_windows_names(f, [py, js, other, bad])
+ got = sorted(i["where"] for i in f.errors())
+ self.assertEqual(got, ["examples/C" + "ON.md", "skills/showtime/tests/test_x.py:10", "skills/showtime/tests/test_x.py:2",
+ "skills/showtime/tests/test_x.py:3", "skills/showtime/tests/test_x.py:4",
+ "skills/showtime/tests/x.mjs:2", "skills/showtime/tests/x.mjs:2"], fmt(f.items))
+ # an f-string before Python 3.12 is one STRING token literal_eval refuses: its text is scanned without quotes
+ self.assertEqual(cr._unquoted("f'{d}/x.txt'"), "{d}/x.txt") # noqa: SLF001
+ self.assertEqual(cr._unquoted('rf"""a\\b.txt"""'), "a\\b.txt") # noqa: SLF001
+ # with the directory check running too, the tracked path is left to it (one report), the test names stay
+ with mock.patch.object(cr, "REPO", d):
+ f = cr.Findings()
+ cr.check_windows_names(f, [py, bad], paths=False)
+ self.assertEqual(sorted(i["where"] for i in f.errors()), ["skills/showtime/tests/test_x.py:10",
+ "skills/showtime/tests/test_x.py:2", "skills/showtime/tests/test_x.py:3",
+ "skills/showtime/tests/test_x.py:4"], fmt(f.items))
+ self.assertTrue(all(i["check"] == "windows" for i in f.items))
+ self.assertIn("windows", cr.default_checks())
+ self.assertEqual(cr.run_checks(only=["windows"]).errors(), [], "the real repository passes")
+ finally:
+ import shutil
+ shutil.rmtree(str(d), ignore_errors=True)
+
def test_banned_and_path_rules(self):
import codecs
import tempfile
@@ -387,16 +531,88 @@ class TestCheckersBite(unittest.TestCase):
tail.write_text("x = 1\n%s main\n" % mark(">"), encoding="utf-8")
heading = d / "ok.md"
heading.write_text("Title\n%s\n\ntext\n" % mark("="), encoding="utf-8")
+ # no label on the markers (the old rule missed them), in a CRLF file, and alone in a .py file; and a
+ # labelled conflict with CRLF line ends: the check reads files as on disk, so its "=======\r" line is matched
+ # by the pattern itself, not thanks to a newline translation (written as bytes: no translation here either)
+ crlf = d / "crlf.md"
+ crlf.write_bytes(("x\r\n%s HEAD\r\nours\r\n%s\r\ntheirs\r\n%s main\r\n" % (mark("<"), mark("="), mark(">"))).encode())
+ bare = d / "bare.txt"
+ bare.write_bytes(("a\r\n%s\r\nours\r\n%s\r\ntheirs\r\n%s\r\n" % (mark("<"), mark("="), mark(">"))).encode())
+ nolabel = d / "nolabel.py"
+ nolabel.write_text("x = 1\n%s\ny = 2\n" % mark("<"), encoding="utf-8")
f = cr.Findings()
- cr.check_conflict_markers(f, [bad, tail, heading])
+ cr.check_conflict_markers(f, [bad, tail, heading, bare, nolabel, crlf])
where = sorted((Path(i["where"].rsplit(":", 1)[0]).name, i["where"].rsplit(":", 1)[1]) for i in f.errors())
- self.assertEqual([i["check"] for i in f.errors()], ["conflicts"] * 4, fmt(f.items))
- self.assertEqual(where, [("merged.md", "2"), ("merged.md", "4"), ("merged.md", "6"), ("tail.py", "2")])
+ self.assertEqual([i["check"] for i in f.errors()], ["conflicts"] * 11, fmt(f.items))
+ self.assertEqual(where, [("bare.txt", "2"), ("bare.txt", "4"), ("bare.txt", "6"), ("crlf.md", "2"),
+ ("crlf.md", "4"), ("crlf.md", "6"), ("merged.md", "2"), ("merged.md", "4"),
+ ("merged.md", "6"), ("nolabel.py", "2"), ("tail.py", "2")])
+ self.assertTrue(all(not i["message"].endswith("\r") for i in f.errors()), fmt(f.items))
self.assertIn("conflicts", cr.default_checks())
finally:
import shutil
shutil.rmtree(str(d), ignore_errors=True)
+ def test_secret_shaped_literals_are_errors(self):
+ """A credential-shaped literal in any shipped text file (a .diff or .jsonl fixture too) is an error, fake or
+ not: a mirror's push protection refuses the commit. Built from pieces at run time, the same value passes."""
+ import tempfile
+ d = Path(tempfile.mkdtemp(prefix="st-secrets-"))
+ try:
+ # one of each SECRET_SHAPES entry, in its order (all built here from pieces)
+ shapes = ["-----BEGIN RSA PRIVATE " + "KEY-----",
+ "Bearer eyJhbGciOiJIUzI1NiJ9" + ".eyJzdWIiOiIxMjM0NSJ9.abcdefghijklmno",
+ "DATABASE_URL=postgres://admin:" + "[email protected]/app",
+ "token = 'gh" + "p_" + "a1B2" * 9 + "'",
+ "pat = github" + "_pat_" + "A1b2C3d4E5" * 7,
+ "AKIA" + "Z7Q2R4T6Y8U0W1E3",
+ "STRIPE=sk" + "_live_" + "0a1B2c3D4e5F6g7H8i9J0k1L",
+ "SLACK=xo" + "xb-" + "1234567890-abcdefghij",
+ "maps key AI" + "za" + "SyA1b2C3d4E5f6G7h8I9j0K1l2M3n4O5p6Q",
+ "sk-ant-" + "api03-abcdefghijklmnopqrstuvwxyz0123456789",
+ "OPENAI=sk-" + "proj-" + "abcdefghijklmnopqrstuvwxyz012345",
+ "-----BEGIN PGP PRIVATE " + "KEY BLOCK-----",
+ "REDIS_URL=redis://:" + "s3cretpw@cache:6379",
+ "STRIPE_TEST=sk" + "_test_" + "0a1B2c3D4e5F6g7H8i9J0k1L",
+ "HOOK=wh" + "sec_" + "0a1B2c3D4e5F6g7H8i9J0k1L2m",
+ "APP=xa" + "pp-" + "1-A0B1C2D3E4-1234567890-abcdef",
+ "CLIENT=GOC" + "SPX-" + "a1B2c3D4e5F6g7H8i9J0k1L2m3N4",
+ "NPM=np" + "m_" + "a1B2c3D4e5F6g7H8i9J0k1L2m3N4o5P6q7R8",
+ "GL=glp" + "at-" + "a1B2c3D4e5F6g7H8i9J0",
+ "SENDGRID=S" + "G." + "a1B2c3D4e5F6g7H8i9J0k1" + "." + "a1B2c3D4e5F6g7H8i9J0k1L2m3N4o5P6q7R8s9T0u1V2w",
+ # one line per alternative inside a label, so a pattern that can never fire fails here too
+ "OAUTH=ya" + "29." + "a1B2c3D4e5F6g7H8i9J0k1L2m3N4o5P6q7R8",
+ "PYPI=py" + "pi-AgE" + "IcHlwaS5vcmcCJDA1YjNjZTQ5LTA0MjUtNDk3Yi04ZmFmLTI4NDNlYTMyNmRiZQ",
+ "HF=h" + "f_" + "aBcdEfGhIjKlMnOpQrStUvWxYz12345678",
+ "SHOP=shp" + "at_" + "0123456789abcdef0123456789abcdef",
+ "DO=do" + "p_v1_" + "0123456789abcdef" * 4,
+ "SQUARE=sq0" + "idp-" + "a1B2c3D4e5F6g7H8i9J0k1",
+ "TWILIO=A" + "C" + "0123456789abcdef0123456789abcdef"]
+ bad = d / "fixture.diff"
+ bad.write_text("".join("+%s\n" % s for s in shapes), encoding="utf-8")
+ ok = d / "test_ok.py"
+ ok.write_text('KEY = "AKIA" + "IOSFODNN7EXAMPLE"\nAWS = "AKIA' + 'IOSFODNN7EXAMPLE"\n'
+ 'URL = "postgres://" + user + ":" + pw + "@db/app"\nMAX_TOKENS = 4096\n'
+ '# docs: postgres://user:password@localhost/db, mysql://app:<password>@db/app, '
+ 'redis://:${REDIS_PASSWORD}@cache:6379, redis://:****@cache\n', encoding="utf-8")
+ blob = d / "blob.bin"
+ blob.write_bytes(b"\0" + shapes[0].encode())
+ f = cr.Findings()
+ cr.check_secrets(f, [bad, ok, blob])
+ where = [(Path(i["where"].rsplit(":", 1)[0]).name, int(i["where"].rsplit(":", 1)[1])) for i in f.errors()]
+ self.assertEqual(where, [("fixture.diff", n) for n in range(1, len(shapes) + 1)], fmt(f.items))
+ self.assertEqual({i["check"] for i in f.errors()}, {"secrets"})
+ labels = {i["message"].split(" literal:")[0] for i in f.errors()}
+ self.assertEqual(labels, {label for label, _rx in cr.SECRET_SHAPES}) # every shape is planted
+ self.assertIn("secrets", cr.default_checks())
+ # run_checks runs it (on the shipped files)
+ with mock.patch.object(cr, "shipped_files", lambda: [bad, ok]):
+ got = cr.run_checks(only=["secrets"])
+ self.assertEqual(len(got.errors()), len(shapes), fmt(got.items))
+ finally:
+ import shutil
+ shutil.rmtree(str(d), ignore_errors=True)
+
def test_people_guides_are_checked(self):
# docs/guides/*.md (task guides for people) go through the links and commands checks too
self.assertIn(cr.REPO / "docs" / "guides" / "README.md", cr.people_docs())
diff --git a/skills/showtime/tests/test_xray.py b/skills/showtime/tests/test_xray.py
index e6af515..24f7240 100644
--- a/skills/showtime/tests/test_xray.py
+++ b/skills/showtime/tests/test_xray.py
@@ -83,6 +83,18 @@ def make_film(path: Path, audio: Path, flashes, seconds=5.0, delay_ms=0.0, marke
return path
+def make_scaled_film(path: Path, audio: Path, flashes, page_w: int, page_h: int, seconds=5.0) -> Path:
+ """A page_w x page_h page with the 6x6 marker at (page_w - 10, page_h - 10) on the given frames, scaled down to
+ the 320x180 film the way a --preview render is (bicubic, a draft encode)."""
+ enable = "+".join("eq(n,%d)" % f for f in flashes)
+ vf = "drawbox=x=%d:y=%d:w=6:h=6:color=white:t=fill:enable='%s',scale=%d:%d,format=yuv420p" % (
+ page_w - 10, page_h - 10, enable, W, H)
+ ff.run_ffmpeg(["-f", "lavfi", "-i", "color=c=0x101418:s=%dx%d:r=%d:d=%g" % (page_w, page_h, FPS, seconds), "-i", str(audio),
+ "-vf", vf, "-c:v", "libx264", "-preset", "veryfast", "-crf", "23",
+ "-c:a", "pcm_s16le", "-shortest", str(path)])
+ return path
+
+
def within(a, b, tol):
return abs(a - b) <= tol
@@ -434,6 +446,35 @@ class Verify(unittest.TestCase):
self.assertEqual(r2["status"], "FAIL")
self.assertEqual(xray.project_config(self.tmp / "nowhere"), {})
+ def test_a_preview_render_is_read_at_the_films_scale(self):
+ # --preview fits the film to 720p: a 1080p page's 6x6 marker is 4x4 there, 6.7 px from the corner, and blurred
+ for page in ((480, 270), (640, 360)): # x 2/3 (1080p -> 720p) and x 1/2
+ j = self.job("scaled-%d" % page[0])
+ (j / "project").mkdir()
+ write_json(j / "project" / "showtime.json", {"width": page[0], "height": page[1], "xray": {"marker": True}})
+ film = make_scaled_film(j / "preview.mkv", self.wav, self.frames, *page)
+ r = xray.verify(j, film)
+ self.assertTrue(r["marker"], r)
+ self.assertEqual((r["on_frame"], r["missing"], r["extra"], r["status"]), (6, [], [], "PASS"), r)
+ self.assertAlmostEqual(r["marker_scale"], W / page[0], places=3)
+ self.assertTrue(any("times the page's size" in n for n in r["notes"]), r["notes"])
+ # a film the page was laid out for at its own size (another shape, --size) is read at the corner as drawn
+ j = self.job("othershape")
+ (j / "project").mkdir()
+ write_json(j / "project" / "showtime.json", {"width": 1080, "height": 1920, "xray": {"marker": True}})
+ r = xray.verify(j, make_film(j / "final.mkv", self.wav, self.frames))
+ self.assertEqual((r["on_frame"], r["status"]), (6, "PASS"), r)
+ self.assertNotIn("marker_scale", r)
+
+ def test_marker_crop_stays_inside_the_scaled_square(self):
+ self.assertEqual(xray.marker_crop(1920, 1080), (6, 6, 1910, 1070)) # the page's own size: the whole square
+ for s in (2 / 3.0, 0.5, 2.0, 0.75):
+ w, h, x, y = xray.marker_crop(1280, 720, s)
+ x0, x1 = 1280 - 10 * s, 1280 - 4 * s # the scaled square's left and right edges
+ self.assertGreaterEqual(w, 2)
+ self.assertTrue(x0 <= x and x + w <= x1 + 1e-9, (s, x, w, x0, x1))
+ self.assertTrue(720 - 10 * s <= y and y + h <= 720 - 4 * s + 1e-9, (s, y, h))
+
def test_skipped_events_carry_no_marker(self):
j = self.job("skip")
(j / "project").mkdir()
@@ -527,6 +568,55 @@ class Verify(unittest.TestCase):
film2 = make_film(j / "final2.mkv", self.wav, self.frames, delay_ms=12)
self.assertTrue(within(xray.verify(j, film2)["audio_lag_ms"], 12.0, 1.5))
+ def test_a_derived_sound_is_said_in_the_line_and_the_receipt(self):
+ from st.job import receipt
+ # the clip's sound is a rendering of data: the audio check passes against it, so the receipt says what it is
+ j = self.job("derived")
+ (j / "project").mkdir()
+ write_json(j / "project" / "showtime.json", {"xray": {"marker": True, "credit": "Synthetic clicks, CC0.",
+ "derived": "the signal slowed 100x on a 400 Hz carrier"}})
+ r = xray.verify(j, make_film(j / "final.mkv", self.wav, self.frames))
+ self.assertEqual(r["status"], "PASS", r)
+ self.assertEqual(r["derived"], "the signal slowed 100x on a 400 Hz carrier")
+ self.assertTrue(r["line"].endswith("ms from the rendered sound"), r["line"])
+ self.assertNotIn("original", r["line"])
+ self.assertTrue(any("not with the original data" in n for n in r["notes"]), r["notes"])
+ late = xray.verify(j, make_film(j / "late.mkv", self.wav, self.frames, delay_ms=40)) # off: said the same way
+ self.assertTrue(any("ms from the rendered sound (limit" in f["message"] for f in late["findings"]), late["findings"])
+ xray.verify(j, make_film(j / "final.mkv", self.wav, self.frames))
+ facts = receipt.card_facts({"xray": xray.receipt_section(j)})
+ self.assertIn("X-ray sound: a rendering (the signal slowed 100x on a 400 Hz carrier); the audio check compares "
+ "the film with it, not with the original data", facts)
+ # events imported from data (xray import): not measured from the sound, so not "from the original" either
+ j2 = self.job("imported")
+ doc = json.loads((j2 / "xray" / "xray.json").read_text(encoding="utf-8"))
+ doc["detector"] = {"engine": "data", "min_gap": None, "sensitivity": None, "from": 0.0, "to": None, "note": "n",
+ "time_map": {"slow": 1.0, "t0": 0.0}, "input": {"file": "peaks.csv", "sha256": "0" * 64,
+ "column": "t", "rows": 6}}
+ write_json(j2 / "xray" / "xray.json", doc)
+ r2 = xray.verify(j2, make_film(j2 / "final.mkv", self.wav, self.frames))
+ self.assertEqual((r2["status"], r2["events_from"]), ("PASS", "data: peaks.csv"), r2)
+ self.assertNotIn("derived", r2)
+ self.assertTrue(r2["line"].endswith("ms from the source sound"), r2["line"])
+ self.assertTrue(any("not from the sound" in n for n in r2["notes"]), r2["notes"])
+ self.assertIn("X-ray events: from data: peaks.csv, not measured from the sound",
+ receipt.card_facts({"xray": xray.receipt_section(j2)}))
+ nomark = xray.verify(j2, make_film(j2 / "plain.mkv", self.wav, [], marker=False))
+ self.assertEqual(nomark["line"], "6 events from data (sync not verified: no marker in the film)")
+ # a hand-edited detector that is not an object, or an input file name that is not a short string, is no crash
+ for det in ("data", {"engine": "data", "input": "peaks.csv"}, {"engine": "data", "input": {"file": "x\n" * 400}}):
+ doc["detector"] = det
+ write_json(j2 / "xray" / "xray.json", doc)
+ r4 = xray.verify(j2, make_film(j2 / "final.mkv", self.wav, self.frames))
+ self.assertEqual(r4["status"], "PASS", r4)
+ self.assertLessEqual(len(r4.get("events_from", "")), 130, r4.get("events_from"))
+ # a clip measured from its own sound keeps "from the original" and no extra receipt line
+ j3 = self.job("measured")
+ r3 = xray.verify(j3, make_film(j3 / "final.mkv", self.wav, self.frames))
+ self.assertTrue(r3["line"].endswith("ms from the original"), r3["line"])
+ self.assertFalse(any(f.startswith("X-ray sound") or f.startswith("X-ray events")
+ for f in receipt.card_facts({"xray": xray.receipt_section(j3)})))
+
def test_events_beyond_the_film_are_not_counted(self):
j = self.job("short", self.frames + [900])
film = make_film(j / "final.mkv", self.wav, self.frames)
@@ -992,6 +1082,39 @@ class Import(unittest.TestCase):
def test_a_strength_cell_that_is_not_a_number_is_refused(self):
self._refused([self._csv("sg.csv", "t,h\n1,5\n2,loud\n3,7\n"), "--strength", "h"], "event 2: the h value 'loud' is not a number", "sg")
+ def test_an_implicit_strength_column_takes_numbers_only(self):
+ # a column named strength sizes the events without --strength: a word there was drawn at 1.0, silently
+ self._refused([self._csv("isg.csv", "t,strength\n1,0.5\n2,loud\n3,0.7\n")],
+ "event 2: the strength value 'loud' is not a number", "isg")
+ doc = xray.import_events(self._csv("isg2.csv", "t,strength\n1,0.5\n2,\n3,7\n"), self.tmp / "isg2")
+ self.assertEqual([e["strength"] for e in doc["events"]], [0.5, 1.0, 1.0]) # blank: the default, clamped to 1
+
+ def test_a_bad_strength_cell_is_refused_before_the_source_is_read(self):
+ from st.audio import wav
+ calls = []
+ real = wav.load
+ wav.load = lambda *a, **k: calls.append(a) or real(*a, **k)
+ try:
+ for name, text, flag in (("bs.csv", "t,h\n1,5\n2,loud\n", ["--strength", "h"]), ("bs2.csv", "t,strength\n1,x\n", [])):
+ with self.assertRaises(ShowtimeError) as cm:
+ xray.build_import(self._csv(name, text), source=self.wav, strength=flag[1] if flag else None)
+ self.assertIn("is not a number", str(cm.exception))
+ self.assertEqual(calls, [], "the recording was decoded before the bad cell was refused")
+ xray.build_import(self._csv("bs3.csv", "t,h\n1,5\n"), source=self.wav, strength="h")
+ self.assertEqual(len(calls), 1, "a good file still reads its source")
+ finally:
+ wav.load = real
+
+ def test_the_blank_count_leaves_out_dropped_rows(self):
+ j = self.tmp / "sg-drop"
+ # rows 1 and 2 are blank; row 1 falls before film time 0 (t0 = 1) and is dropped: one event has no value
+ cp = st("xray", "import", self._csv("sg3.csv", "t,h\n0.5,\n2,\n3,4\n"), "--strength", "h", "--time-map", "1,1",
+ "--job", j, check=False)
+ self.assertEqual(cp.returncode, 0, cp.stderr)
+ self.assertIn("1 event(s) have no h value: drawn at strength 0", cp.stderr)
+ doc = json.loads((j / "xray" / "xray.json").read_text())
+ self.assertEqual(([e["strength"] for e in doc["events"]], len(doc["dropped"])), ([0.0, 1.0], 1))
+
def test_a_blank_strength_cell_is_zero_with_a_warning(self):
j = self.tmp / "sg-blank"
cp = st("xray", "import", self._csv("sg2.csv", "t,h\n1,5\n2,\n3, \n4,10\n"), "--strength", "h", "--job", j, check=False)
@@ -1014,7 +1137,9 @@ class Import(unittest.TestCase):
flat = " ".join(out.split())
self.assertIn("WAV", flat)
self.assertIn("no picture", flat)
- self.assertNotIn("the video you filmed\n", out)
+ self.assertIn("the video you filmed (with its sound), or a WAV or other recording with no picture", flat)
+ self.assertIn("the 30 fps grid", flat) # a recording with no picture has no frames of its own
+ self.assertNotIn("floor(t * fps) of the clip", flat)
def test_time_map_keeps_an_omitted_part(self):
self.assertEqual(xray.parse_time_map(",5"), {"slow": 1.0, "t0": 5.0})
@@ -1171,6 +1296,23 @@ class ReaderLimits(unittest.TestCase):
rows = ",".join('{"t":%d.5,"spectrum":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]}' % k for k in range(xray.MAX_EVENTS))
self.assertEqual(len(xray.read_event_rows(self.f("spectra.json", "[" + rows + "]"))[0]), xray.MAX_EVENTS)
+ def test_one_wide_object_is_refused_before_it_is_parsed(self):
+ """One object with more keys than MAX_KEYS (a single container, fewer commas than MAX_VALUES) is refused before
+ json parses it; the most events with 8 colons each (keys, times, URLs) stay well under the bound."""
+ from unittest import mock
+ # room for 16 colons an event at the most events (keys plus times and URLs inside strings: a realistic event
+ # with a timestamp, a URL, a label and a note has about 8)
+ self.assertGreaterEqual(xray.MAX_KEYS, 16 * xray.MAX_EVENTS)
+ self.assertLess(xray.MAX_KEYS, xray.MAX_VALUES)
+ wide = self.f("wide.json", "{" + ",".join('"k%d":0' % k for k in range(xray.MAX_KEYS + 1)) + "}")
+ with mock.patch.object(xray.json, "loads", side_effect=AssertionError("parsed")):
+ self.refused(wide, "too many object keys")
+ # the most events, each with a timestamp, a URL, a label and a note (8 colons an event), are read
+ row = '{"t":%d.5,"at":"2026-10-15T12:30:01","url":"https://data.example/run/7","label":"peak","note":"x"}'
+ text = "[" + ",".join(row % k for k in range(xray.MAX_EVENTS)) + "]"
+ self.assertEqual(text.count(":"), 8 * xray.MAX_EVENTS)
+ self.assertEqual(len(xray.read_event_rows(self.f("realistic.json", text))[0]), xray.MAX_EVENTS)
+
def test_a_huge_integer_is_refused_before_json_parses_it(self):
from unittest import mock
with mock.patch.object(xray.json, "loads", side_effect=AssertionError("parsed")):
diff --git a/skills/showtime/tests/test_xray_live.py b/skills/showtime/tests/test_xray_live.py
index bd89e32..36a01f5 100644
--- a/skills/showtime/tests/test_xray_live.py
+++ b/skills/showtime/tests/test_xray_live.py
@@ -37,11 +37,16 @@ LAUNCHER = SKILL / "lib" / "st" / "launcher.py"
LIVE = SKILL / "runtime" / "xray-live"
sys.path.insert(0, str(SKILL / "lib"))
+from st import platform as plat # noqa: E402
from st.launcher import build_env, showtime_home # noqa: E402
FAST = "--fast" in sys.argv
ENV = build_env(showtime_home())
NODE = shutil.which("node", path=ENV.get("PATH"))
+# the browser the drivers' openBrowser would start (stagehost: $SHOWTIME_CHROME, a system Chrome, Playwright's)
+BROWSER = plat.find_chrome(ENV.get("PLAYWRIGHT_BROWSERS_PATH"))
+NO_BROWSER = "--fast: no browser" if FAST else ("needs node" if not NODE else ("needs Chromium (showtime setup)"
+ if not BROWSER else ""))
TMP = Path(tempfile.mkdtemp(prefix="st-xray-live-"))
@@ -140,6 +145,117 @@ class TestCli(unittest.TestCase):
cp = showtime("export", "html", proj, "--interactive", "--out-dir", jobs, "--json")
self.assertTrue(json.loads(cp.stdout)["output"].endswith("-live.html"))
+ def test_the_pages_own_font_faces_are_packed(self):
+ # #71: a project's own @font-face in the page's <style> (url("fonts/...")) is packed like the theme fonts; the
+ # page's policy allows only data: fonts, so a font left as a file never loads. The living diagram's figure too.
+ face = b"wOF2" + bytes(range(60)) # synthetic bytes: packing never parses a font
+ b64 = __import__("base64").b64encode(face).decode()
+ for tpl, page in (("xray", "index.html"), ("diagram", "figure.html")):
+ proj = TMP / ("ownfont-" + tpl)
+ showtime("new", tpl, proj)
+ (proj / "fonts").mkdir()
+ (proj / "fonts" / "own face.woff2").write_bytes(face)
+ html = (proj / page).read_text(encoding="utf-8")
+ style = ('<style media="all">@font-face { font-family: "Own Face"; src: url("fonts/own%20face.woff2") '
+ 'format("woff2"); } h1, .brand { font-family: "Own Face", sans-serif; }</style>\n</head>')
+ (proj / page).write_text(html.replace("</head>", style, 1), encoding="utf-8")
+ out = TMP / ("ownfont-" + tpl + ".html")
+ showtime("export", "html", proj, "--interactive", "-o", out, "--json")
+ got = out.read_text(encoding="utf-8")
+ self.assertIn("url(data:font/woff2;base64,%s)" % b64, got, tpl)
+ self.assertNotIn("own%20face.woff2", got, tpl)
+ self.assertIn('<style media="all">', got, "the block keeps its attributes")
+ # a page font that is not there stops the export with its name, instead of a page that falls back
+ (proj / "fonts" / "own face.woff2").unlink()
+ cp = showtime("export", "html", proj, "--interactive", "-o", TMP / ("ownfont-miss-" + tpl + ".html"), check=False)
+ self.assertNotEqual(cp.returncode, 0, tpl)
+ self.assertIn("own face.woff2", unquote(cp.stdout + cp.stderr), tpl)
+
+ def test_an_inline_script_is_never_rewritten(self):
+ # #71 review: the page's <style> packing must not reach into an inline <script> whose text holds "<style>",
+ # "@font-face" or "url(": the script stays byte for byte (its url names no file, so a rewrite would also fail)
+ script = ('<script>window.__css = \'<style>@font-face { font-family: "Code Face"; src: url("fonts/none.woff2"); }'
+ '</style>\'; window.__u = "url(x)";</script>')
+ for tpl, page in (("xray", "index.html"), ("diagram", "figure.html")):
+ proj = TMP / ("inlinescript-" + tpl)
+ showtime("new", tpl, proj)
+ html = (proj / page).read_text(encoding="utf-8")
+ (proj / page).write_text(html.replace("</body>", script + "\n</body>", 1), encoding="utf-8")
+ out = TMP / ("inlinescript-" + tpl + ".html")
+ showtime("export", "html", proj, "--interactive", "-o", out, "--json")
+ self.assertIn(script, out.read_text(encoding="utf-8"), tpl)
+
+ def test_a_page_style_cannot_reach_outside_the_project(self):
+ # #71 review: a url() in the page's own <style> is read only inside the project; an encoded ".." that climbs
+ # out stops the export by its name, and a plain "../.." stays at the project's root (no such file there)
+ face = b"wOF2" + bytes(range(60, 120))
+ b64 = __import__("base64").b64encode(face).decode()
+ for tpl, page in (("xray", "index.html"), ("diagram", "figure.html")):
+ proj = TMP / "climb" / tpl / "proj"
+ showtime("new", tpl, proj)
+ (proj.parent / "outside.woff2").write_bytes(face)
+ (proj.parent.parent / "outside.woff2").write_bytes(face)
+ html = (proj / page).read_text(encoding="utf-8")
+ for i, url in enumerate(("../outside.woff2", "%2e%2e/outside.woff2", "..%2foutside.woff2",
+ "/_st/%2e%2e/%2e%2e/outside.woff2")):
+ style = '<style>@font-face { font-family: "Far"; src: url("%s"); }</style>\n</head>' % url
+ (proj / page).write_text(html.replace("</head>", style, 1), encoding="utf-8")
+ out = TMP / "climb" / ("%s-%d.html" % (tpl, i))
+ cp = showtime("export", "html", proj, "--interactive", "-o", out, check=False)
+ where = (tpl, url, (cp.stdout + cp.stderr)[-600:])
+ self.assertNotEqual(cp.returncode, 0, where)
+ self.assertIn("outside.woff2", unquote(cp.stdout + cp.stderr), where)
+ self.assertFalse(out.exists() and b64 in out.read_text(encoding="utf-8"), where)
+
+ def test_from_inside_a_job_it_writes_into_the_job(self):
+ # #72: run from a job folder (or on a project inside one), the live page lands in the job, noted in job.json,
+ # never in a new showtime-out/ folder nested inside it
+ base = TMP / "jobs72"
+ base.mkdir(exist_ok=True)
+ job = Path(json.loads(showtime("job", "init", "live72", "--base", base, "--no-check", "--json").stdout)["job"])
+ showtime("new", "xray", job / "project")
+ for cwd, arg in ((job, "project"), (TMP, str(job / "project"))):
+ cp = subprocess.run([sys.executable, str(LAUNCHER), "export", "html", arg, "--interactive", "--json"], env=ENV,
+ cwd=str(cwd), stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf-8",
+ errors="replace", timeout=300)
+ self.assertEqual(cp.returncode, 0, cp.stderr[-2000:])
+ rep = json.loads(cp.stdout)
+ self.assertEqual(Path(rep["output"]).parent.resolve(), job.resolve(), (cwd, rep["output"]))
+ self.assertEqual(Path(rep["job"]).resolve(), job.resolve())
+ self.assertFalse((job / "showtime-out").exists(), "no nested showtime-out folder")
+ self.assertFalse((TMP / "showtime-out").exists(), "the project's job wins over the folder it was run from")
+ hist = [h["event"] for h in json.loads((job / "job.json").read_text(encoding="utf-8"))["history"]]
+ self.assertEqual(len([h for h in hist if h.startswith("export html --interactive ") and "live" in h]), 2, hist)
+
+ def test_from_a_job_only_its_own_project_goes_in(self):
+ # #72 review: the folder the command runs from picks the job only for that job's own project (kept elsewhere
+ # and named by job.json "project"); another project exported from inside a job goes where it always did
+ base = TMP / "jobs72b"
+ base.mkdir(exist_ok=True)
+ own, other = TMP / "own72", TMP / "other72"
+ showtime("new", "xray", own)
+ showtime("new", "xray", other)
+ job = Path(json.loads(showtime("job", "init", "live72b", "--base", base, "--project", own, "--no-check",
+ "--json").stdout)["job"])
+
+ def export(arg):
+ cp = subprocess.run([sys.executable, str(LAUNCHER), "export", "html", str(arg), "--interactive", "--json"],
+ env=ENV, cwd=str(job), stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf-8",
+ errors="replace", timeout=300)
+ self.assertEqual(cp.returncode, 0, cp.stderr[-2000:])
+ return json.loads(cp.stdout)
+
+ rep = export(own)
+ self.assertEqual(Path(rep["output"]).parent.resolve(), job.resolve(), rep["output"])
+ self.assertEqual(Path(rep["job"]).resolve(), job.resolve())
+ rep = export(other)
+ out = Path(rep["output"]).resolve()
+ self.assertNotEqual(out.parent, job.resolve(), "another project's page is not written into this job")
+ self.assertEqual(out.parent.parent.name, "showtime-out", out)
+ self.assertFalse(rep.get("job"), rep)
+ hist = [h["event"] for h in json.loads((job / "job.json").read_text(encoding="utf-8"))["history"]]
+ self.assertEqual(len([h for h in hist if h.startswith("export html --interactive ")]), 1, hist)
+
def test_diagram_layout(self):
_, out, rep = sample("diagram")
self.assertEqual(rep["layout"], "diagram")
@@ -262,7 +378,7 @@ console.log(JSON.stringify(out));
"""
[email protected](FAST or not NODE, "--fast: no browser")
[email protected](NO_BROWSER, NO_BROWSER)
class TestTouch(unittest.TestCase):
def test_play_it(self):
proj, _, _ = sample()
@@ -300,15 +416,27 @@ class TestTouch(unittest.TestCase):
EMBED = r"""
import path from 'node:path';
import { pathToFileURL } from 'node:url';
-const [SKILL, HOST] = process.argv.slice(2);
+const [SKILL, HOST, HOW] = process.argv.slice(2);
const { openBrowser } = await import(pathToFileURL(path.join(SKILL, 'scripts', 'lib', 'stagehost.mjs')).href);
const { browser } = await openBrowser({ headless: true, args: ['--allow-file-access-from-files'] });
const out = { logs: [] };
+let server = null;
try {
+ let url = pathToFileURL(HOST).href;
+ if (HOW === 'http') { // the host served over http from its own folder (127.0.0.1 only)
+ const http = await import('node:http'), fs = await import('node:fs');
+ server = http.createServer((q, s) => {
+ const f = path.join(path.dirname(HOST), decodeURIComponent(new URL(q.url, 'http://x').pathname));
+ fs.readFile(f, (err, b) => { if (err) { s.statusCode = 404; s.end(); return; }
+ s.setHeader('content-type', f.endsWith('.js') ? 'text/javascript' : 'text/html; charset=utf-8'); s.end(b); });
+ });
+ await new Promise((r) => server.listen(0, '127.0.0.1', r));
+ url = 'http://127.0.0.1:' + server.address().port + '/' + path.basename(HOST);
+ }
const ctx = await browser.newContext({ viewport: { width: 1000, height: 800 } });
const pg = await ctx.newPage();
pg.on('pageerror', (e) => out.logs.push(String(e.message || e)));
- await pg.goto(pathToFileURL(HOST).href);
+ await pg.goto(url);
out.loaded = await pg.evaluate(() => [...document.querySelectorAll('showtime-xray')].map((el) => {
const f = el.load(false);
return f ? { src: f.getAttribute('src'), sandbox: f.getAttribute('sandbox'), h: f.style.height } : null;
@@ -319,12 +447,142 @@ try {
out.frames = await pg.evaluate(() => document.querySelectorAll('showtime-xray iframe').length);
} catch (e) { out.error = String(e && e.stack || e); }
await browser.close();
+if (server) server.close();
console.log(JSON.stringify(out));
"""
[email protected](FAST or not NODE, "--fast: no browser")
+COPY = r"""
+import path from 'node:path';
+import { pathToFileURL } from 'node:url';
+const [SKILL, HOST, GRANT] = process.argv.slice(2);
+const { openBrowser } = await import(pathToFileURL(path.join(SKILL, 'scripts', 'lib', 'stagehost.mjs')).href);
+const { browser } = await openBrowser({ headless: true });
+const out = { logs: [] };
+let server = null;
+try {
+ // the host served over http from its own folder (127.0.0.1 only), the way a site embeds the page
+ const http = await import('node:http'), fs = await import('node:fs');
+ server = http.createServer((q, s) => {
+ const f = path.join(path.dirname(HOST), decodeURIComponent(new URL(q.url, 'http://x').pathname));
+ fs.readFile(f, (err, b) => { if (err) { s.statusCode = 404; s.end(); return; }
+ s.setHeader('content-type', f.endsWith('.js') ? 'text/javascript' : 'text/html; charset=utf-8'); s.end(b); });
+ });
+ await new Promise((r) => server.listen(0, '127.0.0.1', r));
+ const origin = 'http://127.0.0.1:' + server.address().port;
+ const ctx = await browser.newContext({ viewport: { width: 1000, height: 900 } });
+ if (GRANT === 'grant') await ctx.grantPermissions(['clipboard-read', 'clipboard-write'], { origin });
+ // a host that refuses the clipboard (a browser setting, a policy): writeText rejects, in every frame
+ if (GRANT === 'refuse') await ctx.addInitScript(() => { Object.defineProperty(navigator, 'clipboard', { configurable: true,
+ value: { writeText: () => Promise.reject(new DOMException('refused', 'NotAllowedError')) } }); });
+ const pg = await ctx.newPage();
+ pg.on('pageerror', (e) => out.logs.push(String(e.message || e)));
+ await pg.goto(origin + '/' + path.basename(HOST));
+ await pg.evaluate(() => document.querySelector('showtime-xray').load(false));
+ const fr = await (await pg.waitForSelector('showtime-xray iframe')).contentFrame();
+ await fr.waitForFunction(() => window.xrayLive && document.querySelector('.xl-embed'), null, { timeout: 30000, polling: 100 });
+ out.sandbox = await pg.evaluate(() => document.querySelector('showtime-xray iframe').getAttribute('sandbox'));
+ // real clicks in the frame (the clipboard needs the gesture): open the embed snippets, press the first Copy. The
+ // page posts its height to the host as it starts and as the panel opens, and the host resizes the frame: a click
+ // aimed while the frame moves on the host lands on nothing (the frame's own stability check cannot see that), so
+ // each click waits for the page to be ready and for the frame's place on the host to hold still for 250 ms
+ await fr.evaluate(() => Promise.race([window.xrayLive.ready,
+ new Promise((ok, no) => setTimeout(() => no(new Error('the page did not start in 30 s')), 30000))]));
+ // each settle forgets the last place first, so it always needs two equal reads 250 ms apart
+ const settle = async () => { await pg.evaluate(() => { window.__frameAt = null; });
+ await pg.waitForFunction(() => { const r = document.querySelector('showtime-xray iframe').getBoundingClientRect();
+ const k = [r.y, r.height, scrollY].join(); const same = k === window.__frameAt; window.__frameAt = k; return same; },
+ null, { timeout: 10000, polling: 250 }); };
+ // say which way a step failed: the panel toggled closed, emptied, or the frame hidden or resized on the host
+ const failed = async (e) => {
+ const st = await fr.evaluate(() => ({ expanded: document.querySelector('.xl-embed').getAttribute('aria-expanded'),
+ hidden: document.querySelector('.xl-share').hidden, what: document.querySelector('.xl-share').getAttribute('data-what'),
+ copies: document.querySelectorAll('.xl-copy').length, inPanel: document.querySelectorAll('.xl-share .xl-copy').length,
+ ready: !!(window.xrayLive && document.querySelector('.xl-veil') && document.querySelector('.xl-veil').hidden) })).catch((x) => String(x));
+ const host = await pg.evaluate(() => { const f = document.querySelector('showtime-xray iframe'), r = f.getBoundingClientRect(), c = getComputedStyle(f);
+ return [Math.round(r.y), Math.round(r.height), c.display, c.visibility, scrollY]; }).catch((x) => String(x));
+ return new Error(e.message.split('\n')[0] + ' | frame ' + JSON.stringify(st) + ' | host ' + JSON.stringify(host));
+ };
+ await settle();
+ await fr.click('.xl-embed');
+ try { await fr.waitForSelector('.xl-share:not([hidden]) .xl-copy', { timeout: 10000 }); } catch (e) { throw await failed(e); }
+ await settle();
+ // the share panel's own Copy (a field outside the panel has one too), and wait for one of Copy's two answers: the
+ // page's start hint sits in the same toast, so "any text" could read the hint
+ try { await fr.click('.xl-share .xl-field .xl-copy', { timeout: 15000 }); } catch (e) { throw await failed(e); }
+ try {
+ await fr.waitForFunction(() => ['Copied', 'Press Ctrl+C or \u2318C to copy'].includes(document.querySelector('.xl-toast').textContent),
+ null, { timeout: 10000, polling: 50 });
+ } catch (e) {
+ const shown = await fr.evaluate(() => document.querySelector('.xl-toast').textContent).catch((x) => String(x));
+ throw new Error('Copy gave no answer in 10 s; the toast reads ' + JSON.stringify(shown));
+ }
+ out.toast = await fr.evaluate(() => document.querySelector('.xl-toast').textContent);
+ out.field = await fr.evaluate(() => { const t = document.querySelector('.xl-share .xl-field textarea'), a = document.activeElement;
+ return { value: t.value, focused: a === t, start: t.selectionStart, end: t.selectionEnd }; });
+ out.clip = GRANT === 'grant' ? await pg.evaluate(() => navigator.clipboard.readText()).catch((e) => 'unreadable: ' + e) : null;
+} catch (e) { out.error = String(e && e.stack || e); }
+await browser.close();
+if (server) server.close();
+console.log(JSON.stringify(out));
+"""
+
+
[email protected](NO_BROWSER, NO_BROWSER)
class TestEmbed(unittest.TestCase):
+ def test_a_web_page_never_takes_a_file_address(self):
+ """Served over http, the element loads a relative address and leaves the poster for a file: one (only a page
+ opened from disk may name a film on disk; a web page could never load it, and now it says so by not trying)."""
+ _, live, _ = sample()
+ shutil.copy(str(LIVE / "embed.js"), str(TMP / "embed.js"))
+ host = TMP / "embed-host-http.html"
+ host.write_text('<!doctype html><meta charset="utf-8"><script src="embed.js"></script><body style="width:900px">'
+ '<showtime-xray src="%s" ratio="16/9"></showtime-xray><showtime-xray src="%s" ratio="16/9">'
+ '</showtime-xray>' % (live.name, live.as_uri()), encoding="utf-8")
+ drv = TMP / "embed.mjs"
+ drv.write_text(EMBED, encoding="utf-8")
+ cp = subprocess.run([NODE, str(drv), str(SKILL), str(host), "http"], env=ENV, cwd=str(TMP),
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf-8", errors="replace", timeout=300)
+ self.assertEqual(cp.returncode, 0, cp.stderr[-2000:])
+ r = json.loads(cp.stdout.strip().splitlines()[-1])
+ self.assertNotIn("error", r, r.get("error"))
+ self.assertEqual(r["logs"], [], "no page error")
+ self.assertIsNotNone(r["loaded"][0], "a relative address loads from a web page")
+ self.assertTrue(r["loaded"][0]["src"].startswith("http://127.0.0.1:"), r["loaded"][0])
+ self.assertIsNone(r["loaded"][1], "a file: address from a web page leaves the poster")
+
+ def test_copy_buttons_in_the_sandboxed_frame(self):
+ """In the frame embed.js makes (sandbox allow-scripts, an opaque origin), a real click on Copy copies (checked on
+ the clipboard where the test may read it), and a host that refuses the clipboard gets the text selected with how
+ to copy it: never "Copied" with nothing copied."""
+ _, live, _ = sample()
+ shutil.copy(str(LIVE / "embed.js"), str(TMP / "embed.js"))
+ host = TMP / "copy-host.html"
+ host.write_text('<!doctype html><meta charset="utf-8"><script src="embed.js"></script><body style="width:900px">'
+ '<showtime-xray src="%s" ratio="16/9"></showtime-xray>' % live.name, encoding="utf-8")
+ drv = TMP / "copy.mjs"
+ drv.write_text(COPY, encoding="utf-8")
+ seen = {}
+ for how in ("plain", "grant", "refuse"):
+ cp = subprocess.run([NODE, str(drv), str(SKILL), str(host), how], env=ENV, cwd=str(TMP), stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE, encoding="utf-8", errors="replace", timeout=300)
+ self.assertEqual(cp.returncode, 0, cp.stderr[-2000:])
+ r = json.loads(cp.stdout.strip().splitlines()[-1])
+ self.assertNotIn("error", r, r.get("error"))
+ self.assertEqual(r["logs"], [], "no page error")
+ self.assertEqual(r["sandbox"], "allow-scripts")
+ self.assertIn("<showtime-xray", r["field"]["value"], "the first field is the embed snippet")
+ self.assertIn(r["toast"], ("Copied", "Press Ctrl+C or \u2318C to copy"), (how, r["toast"]))
+ if how == "grant":
+ self.assertEqual(r["toast"], "Copied", r)
+ self.assertEqual(r["clip"], r["field"]["value"], "the sandboxed frame's copy is on the clipboard")
+ if r["toast"] != "Copied":
+ self.assertTrue(r["field"]["focused"], (how, r["field"]))
+ self.assertEqual((r["field"]["start"], r["field"]["end"]), (0, len(r["field"]["value"])),
+ "the whole snippet is selected, ready for Ctrl+C")
+ seen[how] = r["toast"]
+ self.assertEqual(seen["refuse"], "Press Ctrl+C or \u2318C to copy", "a refused clipboard selects the text")
+
def test_sources_and_the_sandboxed_frame(self):
_, live, _ = sample()
host = TMP / "embed-host.html"
@@ -351,7 +609,7 @@ class TestEmbed(unittest.TestCase):
self.assertTrue(r["resized"], "the sandboxed page still reports its height to the host")
[email protected](FAST or not NODE, "--fast: no browser")
[email protected](NO_BROWSER, NO_BROWSER)
class TestBrowser(unittest.TestCase):
def test_jump_lands_on_the_peak(self):
_, out, _ = sample()
diff --git a/skills/showtime/tests/test_xray_made.py b/skills/showtime/tests/test_xray_made.py
index 7542945..ec9704e 100644
--- a/skills/showtime/tests/test_xray_made.py
+++ b/skills/showtime/tests/test_xray_made.py
@@ -33,12 +33,17 @@ REPO = SKILL.parents[1]
LAUNCHER = SKILL / "lib" / "st" / "launcher.py"
sys.path.insert(0, str(SKILL / "lib"))
+from st import platform as plat # noqa: E402
from st.launcher import build_env, showtime_home # noqa: E402
ENV = build_env(showtime_home())
TMP = Path(tempfile.mkdtemp(prefix="st-xray-made-"))
FAST = "--fast" in sys.argv
NODE = shutil.which("node", path=ENV.get("PATH"))
+# the browser the page driver's openBrowser would start (stagehost: $SHOWTIME_CHROME, a system Chrome, Playwright's)
+BROWSER = plat.find_chrome(ENV.get("PLAYWRIGHT_BROWSERS_PATH"))
+NO_BROWSER = "--fast: no browser" if FAST else ("needs node" if not NODE else ("needs Chromium (showtime setup)"
+ if not BROWSER else ""))
def showtime(*args, check=True, timeout=300):
@@ -278,7 +283,7 @@ class TestMeasuredAndCommands(unittest.TestCase):
self.assertEqual(rep["made"]["prompt"], "shown prompt")
self.assertIn("config prompt zq81", out.read_text(encoding="utf-8"), "showtime.json's xray block is packed whole")
- @unittest.skipIf(FAST or not NODE, "--fast: no browser")
+ @unittest.skipIf(NO_BROWSER, NO_BROWSER)
def test_the_page_says_it(self):
steps = ["showtime xray import peaks.csv --job <job> --time-map 100,-0.14", "showtime render <job>/project --job <job>"]
_, _, out = self.export(variant(self.base, "p1", {"measured": None, "made": {"mechanism": "typewriter", "commands": steps}},
diff --git a/skills/showtime/tests/test_xray_template.py b/skills/showtime/tests/test_xray_template.py
index 7b7ed89..6dd1c4b 100644
--- a/skills/showtime/tests/test_xray_template.py
+++ b/skills/showtime/tests/test_xray_template.py
@@ -26,6 +26,7 @@ import subprocess
import sys
import tempfile
import unittest
+from collections import Counter
from pathlib import Path
TESTS_DIR = Path(__file__).resolve().parent
@@ -211,6 +212,550 @@ console.log(JSON.stringify({ xray: urls({ xray: {} }), plain: urls({}), none: ur
"""
+STRIP = r"""
+import path from 'node:path';
+import { pathToFileURL } from 'node:url';
+const [SKILL, PROJ, W, H, TIMES] = process.argv.slice(2);
+const S = await import(pathToFileURL(path.join(SKILL, 'scripts', 'lib', 'stagehost.mjs')).href);
+const { startServer } = await import(pathToFileURL(path.join(SKILL, 'scripts', 'server.mjs')).href);
+const server = await startServer({ root: PROJ, port: 0 });
+const b = await S.openBrowser({});
+const out = {};
+try {
+ const sess = await S.openStage(b.browser, { url: server.url, page: 'index.html', config: { width: +W, height: +H, fps: 30, duration: 16.4 } });
+ await sess.page.evaluate(() => {
+ window.__calls = [];
+ for (const id of ['cv', 'strip-cv']) {
+ const c = document.getElementById(id);
+ if (!c) continue;
+ const g = c.getContext('2d');
+ for (const n of ['fillRect', 'moveTo']) {
+ const o = g[n].bind(g);
+ g[n] = (...a) => { window.__calls.push([id, n, ...a.map(Number), c.width]); return o(...a); };
+ }
+ const ft = g.fillText.bind(g); // a text: where it starts and how wide it is
+ g.fillText = (s, x, y) => { window.__calls.push([id, 'fillText', +x, +y, g.measureText(s).width, c.width]); return ft(s, x, y); };
+ }
+ });
+ for (const t of TIMES.split(',').map(Number)) {
+ await sess.page.evaluate(() => { window.__calls = []; });
+ await sess.seek(t);
+ out[t] = await sess.page.evaluate(() => [window.__calls, (document.getElementById('scan') || {}).style?.opacity ?? null]);
+ }
+ await sess.close();
+} catch (e) { out.error = String(e.stack || e); }
+await b.browser.close(); await server.close();
+process.stdout.write(JSON.stringify(out) + '\n', () => process.exit(0)); // a pipe: exit only once it is written (64 KB+)
+"""
+
+
+MECH_TRACE = r"""
+import path from 'node:path';
+import { pathToFileURL } from 'node:url';
+const [SKILL, PROJ, W, H, TIMES, OUT] = process.argv.slice(2);
+const fs = await import('node:fs');
+const S = await import(pathToFileURL(path.join(SKILL, 'scripts', 'lib', 'stagehost.mjs')).href);
+const { startServer } = await import(pathToFileURL(path.join(SKILL, 'scripts', 'server.mjs')).href);
+const server = await startServer({ root: PROJ, port: 0 });
+const b = await S.openBrowser({});
+const out = {};
+try {
+ const sess = await S.openStage(b.browser, { url: server.url, page: 'index.html', config: { width: +W, height: +H, fps: 30, duration: 16.4 } });
+ // every path, text and transform the mechanism's draw(k) makes, numbers rounded (what it draws, not how bright)
+ await sess.page.evaluate(() => {
+ const m = window.XRAY.mech, draw = m.draw, g = document.getElementById('cv').getContext('2d');
+ let on = false;
+ for (const n of ['moveTo', 'lineTo', 'rect', 'arc', 'fillText', 'translate', 'scale', 'quadraticCurveTo', 'bezierCurveTo', 'ellipse']) {
+ const o = g[n].bind(g);
+ g[n] = (...a) => { if (on) window.__trace.push([n, ...a.map((v) => (typeof v === 'number' ? Math.round(v * 100) / 100 : String(v)))]); return o(...a); };
+ }
+ m.draw = (k) => { on = true; try { return draw(k); } finally { on = false; } };
+ });
+ for (const t of TIMES.split(',').map(Number)) {
+ await sess.page.evaluate(() => { window.__trace = []; });
+ await sess.seek(t);
+ out[t] = await sess.page.evaluate(() => window.__trace);
+ }
+ await sess.close();
+} catch (e) { out.error = String(e.stack || e); }
+await b.browser.close(); await server.close();
+fs.writeFileSync(OUT, JSON.stringify(out)); // a file: a trace is longer than a pipe takes before exit
+process.exit(0);
+"""
+
+
[email protected](not NODE or FAST, "needs node and a browser")
+class TestMusicOnTheRecordingClock(unittest.TestCase):
+ """B11b: notes.json times and its tempo map are seconds of the recording. The piano, drums and guitar placed a
+ lone note (one no event took) at floor(t * fps), and scrolled the staff by the film's time, so with
+ "xray".offset_frames both ran that many frames early. With offset 90 (the clip 3 s into the film) a mechanism
+ must draw at film time t + 3 s exactly what it draws at t with no offset: the kit's k.rt and k.frameAt(t)."""
+
+ OFF = 90
+ TIMES = (1.5, 2.1, 2.4, 3.3, 4.75, 6.2) # recording times around the lone notes (2.2 s, 4.65 s)
+ TEMPO = {"bpm": 96, "map": [[0.0, 0.0], [1.25, 2.0], [2.5, 4.0], [4.0, 6.4], [9.5, 15.2]]}
+
+ def music(self, mech):
+ # two lone notes, each more than 0.2 s from every event of the template's xray.json (no event takes them)
+ notes = [{"i": 0, "t": 2.2, "end": 2.9, "pitch": 60, "confidence": 0.9},
+ {"i": 1, "t": 4.65, "end": 5.0, "pitch": 64, "confidence": 0.9}]
+ doc = {"tempo": self.TEMPO, "key": "C"}
+ if mech == "drums":
+ doc["drums"] = [{"i": 0, "t": 2.2, "piece": "snare", "velocity": 0.9},
+ {"i": 1, "t": 4.65, "piece": "kick", "velocity": 0.8}]
+ else:
+ doc["notes"] = notes
+ if mech == "guitar":
+ doc["guitar"] = [{"i": 0, "string": 2, "fret": 1}, {"i": 1, "string": 1, "fret": 0}]
+ return doc
+
+ def trace(self, mech, off):
+ d = TMP / ("music-%s-%d" % (mech, off))
+ if not d.exists():
+ showtime("new", "xray", d, "--mechanism", mech)
+ (d / "notes.json").write_text(json.dumps(self.music(mech)), encoding="utf-8")
+ cfg = json.loads((d / "showtime.json").read_text(encoding="utf-8"))
+ cfg["xray"]["offset_frames"] = off
+ cfg["duration"] = 16.4
+ (d / "showtime.json").write_text(json.dumps(cfg), encoding="utf-8")
+ cue = (d / "cue.js").read_text(encoding="utf-8")
+ cue = re.sub(r"duration: [\d.]+", "duration: 16.4", re.sub(r"endcard: [\d.]+", "endcard: 13.4", cue))
+ (d / "cue.js").write_text(cue, encoding="utf-8")
+ cfg = json.loads((d / "showtime.json").read_text(encoding="utf-8"))
+ drv = TMP / "mechtrace.mjs"
+ drv.write_text(MECH_TRACE, encoding="utf-8")
+ times = [round(t + off / 30, 4) for t in self.TIMES]
+ cp = subprocess.run([NODE, str(drv), str(SKILL), str(d), str(cfg["width"]), str(cfg["height"]),
+ ",".join(map(str, times)), str(d / "trace.json")], env=ENV, stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE, encoding="utf-8", errors="replace", timeout=300)
+ self.assertEqual(cp.returncode, 0, cp.stderr[-2000:])
+ r = json.loads((d / "trace.json").read_text(encoding="utf-8"))
+ self.assertNotIn("error", r, r.get("error"))
+ return [r[str(int(t)) if t == int(t) else str(t)] for t in times] # JSON keys as JS writes numbers
+
+ def test_events_are_clear_of_the_lone_notes(self):
+ ev = [e["t"] for e in json.loads((TEMPLATE / "xray.json").read_text(encoding="utf-8"))["events"]]
+ for t in (2.2, 4.65):
+ self.assertGreater(min(abs(t - e) for e in ev), 0.2, t)
+
+ def test_piano_drums_guitar_offset_draws_the_same_later(self):
+ for mech in ("piano", "drums", "guitar"):
+ base, late = self.trace(mech, 0), self.trace(mech, self.OFF)
+ for t, a, b in zip(self.TIMES, base, late):
+ self.assertTrue(a, (mech, t, "the mechanism drew nothing"))
+ if a != b:
+ diff = next(i for i, (x, y) in enumerate(zip(a, b)) if x != y) if len(a) == len(b) else None
+ self.fail("%s at recording %.1f s: %d calls with no offset, %d with offset %d (first difference at "
+ "%s: %s vs %s)" % (mech, t, len(a), len(b), self.OFF, diff,
+ a[diff] if diff is not None else "-", b[diff] if diff is not None else "-"))
+
+
[email protected](not NODE or FAST, "needs node and a browser")
+class TestStripOffset(unittest.TestCase):
+ """The sound strip is the recording's timeline. With "xray".offset_frames the clip starts that many frames into
+ the film, so a tick sits at (its film frame - offset) and the caret at (the film frame - offset) over the
+ recording's length: every tick inside the strip, the caret at its start before the clip begins and still moving
+ near the end (it used to place both by film time: late ticks past the strip's end, the caret stuck at the end)."""
+
+ OFF = 90 # the clip starts 3 s into the film
+ TIMES = (2.0, 10.0, 11.0, 12.0)
+
+ def project(self, name, *extra, doc=None, xray=None, times=None):
+ d = TMP / name
+ showtime("new", "xray", d, *extra)
+ if doc:
+ x = json.loads((d / "xray.json").read_text(encoding="utf-8"))
+ doc(x)
+ (d / "xray.json").write_text(json.dumps(x), encoding="utf-8")
+ cfg = json.loads((d / "showtime.json").read_text(encoding="utf-8"))
+ cfg["xray"]["offset_frames"] = self.OFF
+ cfg["xray"].update(xray or {})
+ cfg["duration"] = 16.4
+ (d / "showtime.json").write_text(json.dumps(cfg), encoding="utf-8")
+ cue = (d / "cue.js").read_text(encoding="utf-8")
+ cue = re.sub(r"duration: [\d.]+", "duration: 16.4", re.sub(r"endcard: [\d.]+", "endcard: 13.4", cue))
+ (d / "cue.js").write_text(cue, encoding="utf-8")
+ drv = TMP / "strip.mjs"
+ drv.write_text(STRIP, encoding="utf-8")
+ cp = subprocess.run([NODE, str(drv), str(SKILL), str(d), str(cfg["width"]), str(cfg["height"]),
+ ",".join(map(str, times or self.TIMES))], env=ENV, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
+ encoding="utf-8", errors="replace", timeout=300)
+ self.assertEqual(cp.returncode, 0, cp.stderr[-2000:])
+ r = json.loads(cp.stdout.strip().splitlines()[-1])
+ self.assertNotIn("error", r, r.get("error"))
+ return {float(k): v for k, v in r.items()}
+
+ def check(self, ticks, caret, dur=None):
+ doc = json.loads((TEMPLATE / "xray.json").read_text(encoding="utf-8"))
+ dur, last = dur or doc["source"]["duration"], doc["events"][-1]["frame"]
+ for t in self.TIMES:
+ self.assertEqual(len(ticks[t]), len(doc["events"]), (t, ticks[t]))
+ self.assertTrue(all(-0.01 <= x <= 1.01 for x in ticks[t]), ("a tick past the strip", t, ticks[t]))
+ self.assertAlmostEqual(max(ticks[t]), last / 30 / dur, delta=0.02)
+ self.assertAlmostEqual(caret[2.0], 0, delta=0.01, msg="before the clip starts the caret waits at 0")
+ c = [caret[t] for t in self.TIMES[1:]]
+ for t, x in zip(self.TIMES[1:], c):
+ self.assertAlmostEqual(x, (t * 30 - self.OFF) / 30 / dur, delta=0.02, msg=(t, c))
+ self.assertTrue(c[0] < c[1] < c[2] < 1, ("the caret keeps moving to the end", c))
+
+ def xray_strip(self, r):
+ ticks, caret = {}, {}
+ for t, (calls, _) in r.items():
+ # the plate: (x0 - 16, y0 - pad, w + 32, h + pad + 16), 104 px tall at 16:9 (pad 38, ticks 50), 94 at 9:16
+ # (pad 22, ticks 56); at 9:16 the label sits on the ticks' row and the ticks start 28 px after it
+ bg = [c for c in calls if c[0] == "cv" and c[1] == "fillRect" and c[5] in (104, 94)]
+ self.assertTrue(bg, (t, "no strip background"))
+ _, _, bx, by, bw, bh, _ = bg[-1]
+ pad = 38 if bh == 104 else 22
+ x0, y0, w, h = bx + 16, by + pad, bw - 32, bh - pad - 16
+ lab = [c for c in calls if c[0] == "cv" and c[1] == "fillText" and abs(c[2] - x0) < 0.01 and abs(c[3] - (y0 + h / 2)) < 0.01]
+ sx = x0 + lab[0][4] + 28 if lab else x0
+ sw = x0 + w - sx
+ ticks[t] = [(c[2] + 2 - sx) / sw for c in calls
+ if c[0] == "cv" and c[1] == "fillRect" and c[4] == 4 and abs(c[3] + c[5] / 2 - (y0 + h / 2)) < 0.6]
+ mv = [c for c in calls if c[0] == "cv" and c[1] == "moveTo" and abs(c[3] - (y0 - 8)) < 0.01]
+ self.assertEqual(len(mv), 1, (t, mv))
+ caret[t] = (mv[0][2] + 9 - sx) / sw
+ return ticks, caret
+
+ def diagram_strip(self, r):
+ ticks, caret = {}, {}
+ for t, (calls, _) in r.items():
+ sc = [c for c in calls if c[0] == "strip-cv" and c[1] == "fillRect"]
+ self.assertTrue(sc, (t, "no strip drawn"))
+ w = sc[0][-1]
+ ticks[t] = [(c[2] + 2 - 2) / (w - 4) for c in sc if c[4] == 4]
+ cr = [c for c in sc if c[4] == 2 and c[3] == 0]
+ self.assertEqual(len(cr), 1, (t, cr))
+ caret[t] = (cr[0][2] - 1) / (w - 4)
+ return ticks, caret
+
+ def test_xray_page(self):
+ self.check(*self.xray_strip(self.project("stripoff")))
+
+ def test_diagram_page(self):
+ self.check(*self.diagram_strip(self.project("stripoffd", "--layout", "diagram")))
+
+ @staticmethod
+ def no_length(x):
+ x["source"].pop("duration", None)
+
+ def test_no_measured_length(self):
+ """With no source.duration the recording is taken to run from the clip's start to the film's end (the
+ diagram: to the endcard), so the strip still spans the recording, not the recording plus the offset."""
+ self.check(*self.xray_strip(self.project("stripoffn", doc=self.no_length)), dur=16.4 - self.OFF / 30)
+ self.check(*self.diagram_strip(self.project("stripoffnd", "--layout", "diagram", doc=self.no_length)),
+ dur=13.4 - self.OFF / 30)
+
+ def test_track_until_on_the_clip_clock(self):
+ """"xray".track_until is the clip's seconds: with the clip 3 s into the film the see-through fades out at
+ film time track_until + 3 s, not at track_until (it used to vanish 3 s early)."""
+ def track(x):
+ x["track"] = {"H": [[1, 0, 0, 0, 1, 0, 0, 0, 1]] * 283, "region": [[100, 80], [540, 80], [540, 280], [100, 280]]}
+ r = self.project("stripofft", doc=track, xray={"track_until": 5.0}, times=(7.0, 8.0, 8.15, 8.6))
+ op = {t: float(v[1]) for t, v in r.items()}
+ self.assertEqual(op[7.0], 1.0, op) # clip 4.0 s: still tracked
+ self.assertEqual(op[8.0], 1.0, op) # clip 5.0 s: the fade starts
+ self.assertTrue(0 < op[8.15] < 1, op) # clip 5.15 s: fading
+ self.assertEqual(op[8.6], 0.0, op) # clip 5.6 s: gone
+
+CANVAS_TEXT = r"""
+import path from 'node:path';
+import { pathToFileURL } from 'node:url';
+const [SKILL, PROJ, W, H, T] = process.argv.slice(2);
+const S = await import(pathToFileURL(path.join(SKILL, 'scripts', 'lib', 'stagehost.mjs')).href);
+const { startServer } = await import(pathToFileURL(path.join(SKILL, 'scripts', 'server.mjs')).href);
+const server = await startServer({ root: PROJ, port: 0 });
+const b = await S.openBrowser({});
+let out = {};
+try {
+ const sess = await S.openStage(b.browser, { url: server.url, page: 'index.html', config: { width: +W, height: +H, fps: 30, duration: 12.8 } });
+ await sess.page.evaluate(() => {
+ window.__texts = [];
+ const g = document.getElementById('cv').getContext('2d'), o = g.fillText.bind(g);
+ g.fillText = (...a) => { window.__texts.push([String(a[0]), g.font, g.measureText(String(a[0])).width]); return o(...a); };
+ });
+ await sess.seek(+T);
+ out = { texts: await sess.page.evaluate(() => window.__texts) };
+ await sess.close();
+} catch (e) { out.error = String(e.stack || e); }
+await b.browser.close(); await server.close();
+console.log(JSON.stringify(out));
+process.exit(0);
+"""
+
+
+LABELS = r"""
+import path from 'node:path';
+import { pathToFileURL } from 'node:url';
+const [SKILL, PROJ, W, H, TIMES] = process.argv.slice(2);
+const S = await import(pathToFileURL(path.join(SKILL, 'scripts', 'lib', 'stagehost.mjs')).href);
+const { startServer } = await import(pathToFileURL(path.join(SKILL, 'scripts', 'server.mjs')).href);
+const server = await startServer({ root: PROJ, port: 0 });
+const b = await S.openBrowser({});
+const out = {};
+try {
+ const sess = await S.openStage(b.browser, { url: server.url, page: 'index.html', config: { width: +W, height: +H, fps: 30, duration: 12.8 } });
+ await sess.page.evaluate(() => {
+ window.__ops = [];
+ const g = document.getElementById('cv').getContext('2d');
+ for (const n of ['beginPath', 'moveTo', 'lineTo', 'stroke', 'strokeRect', 'fillRect']) {
+ const o = g[n].bind(g);
+ g[n] = (...a) => { window.__ops.push([n, ...a.map(Number)]); return o(...a); };
+ }
+ const ft = g.fillText.bind(g);
+ g.fillText = (s, x, y) => { window.__ops.push(['fillText', String(s), +x, +y, g.font]); return ft(s, x, y); };
+ });
+ for (const t of TIMES.split(',').map(Number)) {
+ await sess.page.evaluate(() => { window.__ops = []; });
+ await sess.seek(t);
+ out[t] = await sess.page.evaluate(() => window.__ops);
+ }
+ await sess.close();
+} catch (e) { out.error = String(e.stack || e); }
+await b.browser.close(); await server.close();
+process.stdout.write(JSON.stringify(out) + '\n', () => process.exit(0));
+"""
+
+
[email protected](not NODE or FAST, "needs node and a browser")
+class TestFreshProjectChecks(unittest.TestCase):
+ """A fresh 16:9 X-ray project passes its own check (#68: the brand 48 px from the edge, the counters in the player
+ controls' strip, 24 px labels, the end card over the drawing's labels, the red letter under 4.5:1), and the sound
+ strip's label, drawn on the canvas where check's size rule does not look, is readable (#73: it was 18 px)."""
+
+ LAYOUT = {"low_contrast", "control_strip", "edge_margin", "text_overlap", "tiny_text", "safe_zone", "text_off_canvas"}
+
+ def test_the_strip_label_is_readable(self):
+ d = TMP / "label169"
+ showtime("new", "xray", d, "--aspect", "16:9")
+ drv = TMP / "canvastext.mjs"
+ drv.write_text(CANVAS_TEXT, encoding="utf-8")
+ cp = subprocess.run([NODE, str(drv), str(SKILL), str(d), "1920", "1080", "5"], env=ENV, stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE, encoding="utf-8", errors="replace", timeout=300)
+ self.assertEqual(cp.returncode, 0, cp.stderr[-2000:])
+ r = json.loads(cp.stdout.strip().splitlines()[-1])
+ self.assertNotIn("error", r, r.get("error"))
+ sizes = {t: float(re.search(r"([\d.]+)px", f).group(1)) for t, f, _ in r["texts"]}
+ label = [t for t in sizes if t.startswith("THE CLIP")]
+ self.assertEqual(len(label), 1, sizes)
+ self.assertGreaterEqual(sizes[label[0]], 26, sizes)
+ self.assertTrue(all(v >= 25 for v in sizes.values()), ("canvas text under 25 px at 16:9", sizes))
+
+ def strip_label(self, d, w, h):
+ drv = TMP / "canvastext.mjs"
+ drv.write_text(CANVAS_TEXT, encoding="utf-8")
+ cp = subprocess.run([NODE, str(drv), str(SKILL), str(d), str(w), str(h), "5"], env=ENV, stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE, encoding="utf-8", errors="replace", timeout=300)
+ self.assertEqual(cp.returncode, 0, cp.stderr[-2000:])
+ r = json.loads(cp.stdout.strip().splitlines()[-1])
+ self.assertNotIn("error", r, r.get("error"))
+ label = [(t, float(re.search(r"([\d.]+)px", f).group(1)), wd) for t, f, wd in r["texts"]
+ if t.startswith(("THE CLIP", "RED = "))]
+ self.assertEqual(len(set(label)), 1, r["texts"])
+ return label[0]
+
+ def test_a_long_mechanism_word_fits_the_strip(self):
+ """#73 follow-up: the label is the mechanism's own word ("one"), so a long one ran past the strip's plate. It
+ shrinks to the floor (2.2% of the frame height: 24 px at 16:9, 43 px at 9:16), then drops "the clip's sound",
+ then ends in an ellipsis, inside its room (the strip's 852 px at 16:9; at 9:16, on the ticks' row, 56% of the
+ strip, which is 78% of the width)."""
+ word = "a hammer striking the left string group" # 39 characters: too long for the full label at 24 px
+ cases = (("16:9", 1920, 1080, 852, "a soft tap on the left key row", "THE CLIP"), # 30: shrinks, keeps it all
+ ("16:9", 1920, 1080, 852, word, "RED = " + word.upper()),
+ ("16:9", 1920, 1080, 852, " ".join([word] * 3), "RED = A HAMMER"),
+ ("9:16", 1080, 1920, 1080 * 0.78 * 0.56, " ".join([word] * 3), "RED = A HAMMER"))
+ for i, (aspect, w, h, room, one, starts) in enumerate(cases):
+ d = TMP / ("longlabel%d" % i)
+ showtime("new", "xray", d, "--aspect", aspect)
+ mech = d / "mechanism.js"
+ js = mech.read_text(encoding="utf-8")
+ self.assertIn("one: 'a keystroke'", js)
+ mech.write_text(js.replace("one: 'a keystroke'", "one: %r" % one), encoding="utf-8")
+ text, px, width = self.strip_label(d, w, h)
+ where = (aspect, one, text, px, width)
+ self.assertTrue(text.startswith(starts), where)
+ self.assertGreaterEqual(px, math.ceil(h * 0.022), where)
+ self.assertLessEqual(width, room, where)
+ if len(one) > 60:
+ self.assertTrue(text.endswith("\u2026"), where)
+ if i == 0:
+ self.assertLess(px, 26, ("the 30-character word is meant to need the shrink", where))
+
+ def canvas_ops(self, d, times="2,6,9"):
+ drv = TMP / "labels.mjs"
+ drv.write_text(LABELS, encoding="utf-8")
+ cp = subprocess.run([NODE, str(drv), str(SKILL), str(d), "1080", "1920", times], env=ENV, stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE, encoding="utf-8", errors="replace", timeout=300)
+ self.assertEqual(cp.returncode, 0, cp.stderr[-2000:])
+ r = json.loads(cp.stdout.strip().splitlines()[-1])
+ self.assertNotIn("error", r, r.get("error"))
+ return r
+
+ def columns(self, where, ops):
+ """The part labels' plates (in a column at the reels box's left edge, x 64, or ending at its right edge, x 916;
+ one or two lines of 44 px, padded 16, 8 or 4 px), their lines of text and their leaders, checked: inside the
+ box, none on another, no two leaders of a column crossing."""
+ plates = [o[1:5] for o in ops if o[0] == "fillRect" and o[4] in (60, 106, 52, 98, 48, 94) and 760 < o[2] < 1190
+ and (abs(o[1] - 64) < 0.01 or abs(o[1] + o[3] - 916) < 0.01)]
+ self.assertTrue(plates, where)
+ for i, a in enumerate(plates):
+ self.assertTrue(64 - 0.01 <= a[0] and a[0] + a[2] <= 916 + 0.01, (where, a))
+ for b in plates[i + 1:]:
+ apart = a[0] + a[2] <= b[0] or b[0] + b[2] <= a[0] or a[1] + a[3] + 2 - 0.01 <= b[1] or b[1] + b[3] + 2 - 0.01 <= a[1]
+ self.assertTrue(apart, (where, "labels on each other", a, b))
+ texts = []
+ for o in ops:
+ if o[0] == "fillText":
+ for x, y, w, h in plates:
+ if abs(o[2] - (x + 11)) < 0.01 and y < o[3] < y + h:
+ self.assertIn(" 44px", o[4], (where, o))
+ texts.append(o)
+ paths, cur = [], None
+ for o in ops:
+ if o[0] == "beginPath":
+ cur = []
+ elif o[0] in ("moveTo", "lineTo") and cur is not None:
+ cur.append((o[1], o[2]))
+ elif o[0] == "stroke" and cur is not None:
+ paths.append(cur)
+ cur = None
+ # each leader: moveTo(the plate's edge, its row) -> lineTo(the column's edge, its row) -> lineTo(its part)
+ leaders = [p for p in paths if len(p) == 3 and p[0][1] == p[1][1]
+ and any(abs(p[0][1] - (y + h / 2)) < 0.01 and min(abs(p[0][0] - x), abs(p[0][0] - x - w)) < 0.01 for x, y, w, h in plates)]
+ self.assertEqual(len(leaders), len(plates), (where, leaders))
+
+ def crosses(a, b):
+ side = lambda p, q, o: (q[0] - p[0]) * (o[1] - p[1]) - (q[1] - p[1]) * (o[0] - p[0])
+ return side(a[0], a[1], b[0]) * side(a[0], a[1], b[1]) < 0 and side(b[0], b[1], a[0]) * side(b[0], b[1], a[1]) < 0
+
+ slants = [(p[1], p[2]) for p in leaders]
+ bad = [(a, b) for i, a in enumerate(slants) for b in slants[i + 1:] if a[0][0] == b[0][0] and crosses(a, b)]
+ self.assertEqual(bad, [], (where, "leaders cross"))
+ return plates, texts, leaders, paths
+
+ def test_9x16_part_labels_in_columns(self):
+ """9:16 (the X-ray as the hero): the part labels sit in a column at the reels box's left edge (x 64), 44 px
+ (the phone floor), a long one on two lines, none on another, and no two leaders cross; parts at rest in weight
+ 500, the ones acting now in 600; no column covers the drawing, and the drawing stays left of x 916, where the
+ platform's buttons begin."""
+ d = TMP / "labels916"
+ showtime("new", "xray", d, "--aspect", "9:16")
+ r = self.canvas_ops(d)
+ words = sorted("PRINT POINT MAINSPRING TYPEBARS KEY LEVERS ESCAPEMENT".split())
+ weights = {}
+ for t, ops in r.items():
+ plates, texts, leaders, paths = self.columns(("typewriter", t), ops)
+ self.assertEqual(len(plates), 5, (t, plates))
+ self.assertTrue(all(abs(x - 64) < 0.01 for x, _, _, _ in plates), (t, "one column, on the left", plates))
+ self.assertEqual(sorted(w for o in texts for w in o[1].split()), words, (t, texts))
+ weights.setdefault(t, []).extend(o[4].split()[0] for o in texts)
+ # the drawing (every other path in the panel) clear of the column's plates
+ right = max(x + w for x, _, w, _ in plates)
+ pts = [q for p in paths if p not in leaders for q in p if 760 < q[1] < 1190] # the panel, over the strip
+ self.assertTrue(pts)
+ self.assertGreaterEqual(min(x for x, _ in pts), right, (t, "the column covers the drawing"))
+ self.assertLessEqual(max(x for x, _ in pts), 916, (t, "the drawing runs under the platform's buttons"))
+ self.assertEqual(set(weights["6"]), {"500"}, weights) # 6 s: every part at rest
+ self.assertIn("600", weights["9"], weights) # 9 s: a keystroke, its parts red and bold
+ frames = [o for ops in r.values() for o in ops if o[0] == "strokeRect" and 760 < o[2] < 1200]
+ self.assertTrue(frames)
+ self.assertLessEqual(max(o[1] + o[3] for o in frames), 916, ("the panel's frame runs under the buttons", frames))
+
+ def test_9x16_more_labels_than_one_column_holds(self):
+ """The drums name 8 parts, more than one column holds at 44 px: a second column at the safe box's right edge, each
+ part's label on its side; the drums' caption sits in a row over the columns at 44 px (it was 28 px, under the
+ first label). The guitar's string names (e B G D A E, 26 px on lines 21 px apart) are labels in the column,
+ their case kept."""
+ d = TMP / "drums916"
+ showtime("new", "xray", d, "--aspect", "9:16", "--mechanism", "drums")
+ for t, ops in self.canvas_ops(d, "2,6").items():
+ plates, texts, _, _ = self.columns(("drums", t), ops)
+ left = [p for p in plates if abs(p[0] - 64) < 0.01]
+ self.assertEqual((len(left), len(plates) - len(left)), (4, 4), (t, plates))
+ self.assertEqual(sorted(w for o in texts for w in o[1].split()),
+ sorted("CRASH RIDE HI-HAT TOM TOM SNARE FLOOR TOM KICK".split()), (t, texts))
+ cap = [o for o in ops if o[0] == "fillText" and o[1].startswith(("HITS, NO PIECES", "PIECES SORTED"))]
+ self.assertEqual(len(cap), 1, (t, cap))
+ self.assertIn("600 44px", cap[0][4], cap)
+ self.assertAlmostEqual(cap[0][2], 64, delta=0.01, msg=cap)
+ self.assertLessEqual(cap[0][3] + 22, min(y for _, y, _, _ in plates), (t, "the caption on a label", cap, plates))
+ g = TMP / "guitar916"
+ showtime("new", "xray", g, "--aspect", "9:16", "--mechanism", "guitar")
+ for t, ops in self.canvas_ops(g, "6").items():
+ plates, texts, _, _ = self.columns(("guitar", t), ops)
+ self.assertEqual([o[1] for o in sorted(texts, key=lambda o: o[3])], list("eBGDAE"), (t, texts))
+ small = [o for o in ops if o[0] == "fillText" and re.search(r" (\d+(\.\d+)?)px", o[4]) and float(re.search(r" (\d+(\.\d+)?)px", o[4]).group(1)) < 43
+ and 760 < o[3] < 1300 and o[1].strip()]
+ self.assertEqual(small, [], (t, "text under 43 px in the panel"))
+ # with notes.json (the key and tempo: a caption over the column) six 60 px rows no longer fit under it: the plates
+ # tighten (8 px of padding) and stay under the caption, none on another
+ (g / "notes.json").write_text(json.dumps({"tempo": {"bpm": 96}, "key": "C", "notes": [{"i": 0, "t": 2.2, "pitch": 60}],
+ "guitar": [{"i": 0, "string": 2, "fret": 1}]}), encoding="utf-8")
+ for t, ops in self.canvas_ops(g, "6").items():
+ plates, texts, _, _ = self.columns(("guitar with notes", t), ops)
+ self.assertEqual([o[1] for o in sorted(texts, key=lambda o: o[3])], list("eBGDAE"), (t, texts))
+ cap = [o for o in ops if o[0] == "fillText" and "BPM" in o[1]]
+ self.assertEqual(len(cap), 1, (t, cap))
+ self.assertIn("600 44px", cap[0][4], cap)
+ self.assertLessEqual(cap[0][3] + 22, min(y for _, y, _, _ in plates), (t, "the caption on a label", cap, plates))
+ self.assertEqual({h for _, _, _, h in plates}, {52}, (t, plates))
+
+ def test_fresh_16x9_projects_pass_check(self):
+ self.fresh_projects_pass_check("16:9")
+
+ def test_fresh_9x16_projects_pass_check(self):
+ """9:16: the sound strip and every label sit inside the reels safe box (the strip was under it, y 1472-1676)
+ and at the phone floor (43 px at 1920; the labels were 24-34 px), and the part labels do not overlap."""
+ self.fresh_projects_pass_check("9:16")
+
+ # 4:5 and 1:1 keep the portrait and wide layouts as they were (the reels layout is 9:16 only): their findings, per
+ # mechanism and kind, as on 0.4.5's code; they may only go down (the fix is its own change, with a critic round)
+ RATCHET = {
+ ("drums", "1:1"): {"text_overlap": 1, "tiny_text": 1}, ("drums", "4:5"): {"safe_zone": 3, "text_overlap": 1, "tiny_text": 2},
+ ("guitar", "1:1"): {"text_overlap": 1, "tiny_text": 1}, ("guitar", "4:5"): {"safe_zone": 3, "text_overlap": 6, "tiny_text": 1},
+ ("musicbox", "1:1"): {"text_overlap": 2, "tiny_text": 1}, ("musicbox", "4:5"): {"safe_zone": 3, "text_overlap": 1, "tiny_text": 1},
+ ("piano", "1:1"): {"text_overlap": 1, "tiny_text": 1}, ("piano", "4:5"): {"safe_zone": 3, "tiny_text": 1},
+ ("switch", "1:1"): {"text_overlap": 2, "tiny_text": 1}, ("switch", "4:5"): {"safe_zone": 3, "text_overlap": 2, "tiny_text": 1},
+ ("typewriter", "1:1"): {"text_overlap": 2, "tiny_text": 1}, ("typewriter", "4:5"): {"safe_zone": 3, "text_overlap": 1, "tiny_text": 1},
+ }
+
+ def test_every_mechanism_at_every_aspect(self):
+ """Every mechanism in the library at 9:16, 4:5 and 1:1: 9:16 passes check (0 layout findings); 4:5 and 1:1 have
+ no more findings of any kind than RATCHET."""
+ mechs = sorted(p.parent.name for p in LIBRARY.glob("*/mechanism.js"))
+ self.assertEqual(sorted({m for m, _ in self.RATCHET}), mechs, "a mechanism without its row in RATCHET")
+
+ def one(cell):
+ m, aspect = cell
+ d = TMP / ("mx-%s-%s" % (m, aspect.replace(":", "x")))
+ showtime("new", "xray", d, "--aspect", aspect, "--mechanism", m)
+ cp = showtime("check", d, "--json", check=False, timeout=900)
+ rep = json.loads(cp.stdout[cp.stdout.index("{"):])
+ return cell, [f for f in rep["findings"] if f["severity"] == "error" or (f["severity"] == "warning" and f.get("code") in self.LAYOUT)]
+
+ import concurrent.futures
+ cells = [(m, a) for m in mechs for a in ("9:16", "4:5", "1:1")]
+ with concurrent.futures.ThreadPoolExecutor(3) as ex:
+ for (m, aspect), found in ex.map(one, cells):
+ if aspect == "9:16":
+ self.assertEqual(["%s: %s" % (f.get("code"), f.get("message")) for f in found], [], (m, aspect))
+ continue
+ got, cap = Counter(f.get("code") for f in found), self.RATCHET[(m, aspect)]
+ worse = {k: (v, cap.get(k, 0)) for k, v in got.items() if v > cap.get(k, 0)}
+ self.assertEqual(worse, {}, (m, aspect, "more findings than before", [f.get("message") for f in found]))
+
+ def fresh_projects_pass_check(self, aspect):
+ for name, extra in (("check", ()), ("checklight", ("--theme", "light"))):
+ d = TMP / (name + aspect.replace(":", "x"))
+ showtime("new", "xray", d, "--aspect", aspect, *extra)
+ cp = showtime("check", d, "--json", check=False, timeout=600)
+ rep = json.loads(cp.stdout[cp.stdout.index("{"):])
+ bad = ["%s %s: %s" % (f["severity"], f.get("code"), f.get("message")) for f in rep["findings"]
+ if f["severity"] == "error" or (f["severity"] == "warning" and f.get("code") in self.LAYOUT)]
+ self.assertEqual(bad, [], (aspect, name))
+
+
@unittest.skipIf(not NODE, "needs node")
class TestOptionalNotes(unittest.TestCase):
"""xray.js fetches notes.json in case `showtime xray notes` wrote one; without it the project is fine."""