Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
ui-kit: fit drifted 2:3 sheets, allow partial kits, refuse painted checkerboards, and publish each kit whole in a fresh directory
Soohong Kimc49a159d5028
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4546e64..449b243 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -11,6 +11,11 @@ All notable public changes to `sprite-gen` are recorded here. Versions track the- **New: `slice-sheet --scale sheet` keeps the sizes a sheet was drawn at, and `--fit contain` keeps every cut whole.** The default gives each cell's main subject the target height on its own, so the props of one sheet came out the same height, and lets the canvas cut whatever that scale puts past its edge, so a subject wider than the canvas lost its sides. `--scale sheet` takes one factor for the whole sheet (the tallest main subject reaches `--target-height`), so a prop drawn twice as tall stays twice as tall. `--fit contain` lowers the factor until the whole cut fits the canvas, with the main subject still centred on its base; with `--scale sheet` the sheet takes the smallest factor any cell fits at. Every cell of a sheet keeps one canvas size, so a game pack that gives the cells one `display` height keeps their sizes too ([sheet-slicing](docs/sheet-slicing.md#props-and-icons-sheet-scale-and-contain-fit)).- **New: `slice-sheet` writes `<prefix>slice-sheet.json`.** It names the scale and fit, the sheet's factor and where it came from, and per cell the factor, the main subject's size on the sheet and on the canvas, the cut's box on the canvas, the `anchor` (the centre of the main subject's base, ready for a game pack's `images[].anchor`) and `clipped_px`, the pixels the canvas cut ([report](docs/sheet-slicing.md#report)). A run also prints a line for each cell the canvas cut. The PNGs of a default run are unchanged byte for byte; a sheet with an empty cell now fails before any cell is written, where it used to write the cells before it.- **New: a 2:3 UI kit sheet holds the whole kit: bar fills, an item slot, a counter plate, on and off dots and a joystick.** `gen --layout-guide ui-kit --aspect-ratio 2:3` draws the square layout's seven frames at the same places and, in a band below them, `hp_bar_fill` and `xp_bar_fill` (`x`), `slot` and `badge` (`xy`), `pip_on`, `pip_off`, `joystick_base` and `joystick_knob` (`none`, so round parts keep their proportions; the guide draws them as circles, and a cut with filled corners, a round part drawn on a square plate, makes the report `needs-review`). `ui-kit` picks the layout from the sheet's shape, so a square sheet is cut, measured and packed exactly as before. Padding is measured only for elements that hold content; fills, dots and joystick parts get `0`. Each fill's report entry has `inside`: its bar frame, that frame's content rectangle and the factor that makes the fill as tall as it, and the report is `needs-review` when the fill's ends would overflow it. `game-pack` (still version 2) stores each fill at exactly its frame's content rectangle, ends kept and middle columns repeated or dropped, with `inside` in its entry, and refuses a fill whose frame is missing or whose ends do not fit ([ui-kit](docs/ui-kit.md#fills), [game-pack](docs/game-pack.md#version-2-manifest)).+- **Behavior change: a 2:3 UI kit sheet that leaves a band element out still makes a kit, without it.** The seven frames (`panel`, `button`, `button_pressed`, `card`, `hp_bar_frame`, `xp_bar_frame`, `timer_badge`) are required: an empty frame box still fails `ui-kit` with `<element>: its box holds no element; generate the sheet again`, now naming every empty frame box at once (`panel, card: their boxes hold no element; …`). The eight band elements (the fills, the slot, the badge, the dots and the joystick parts) are optional: an empty band box leaves that element out. It gets no PNG and no `elements` entry, the report names it under `missing` (every 2:3 report has `missing`, `[]` when nothing is missing), and the command's line ends with `; missing, left out of the kit: …`. `status` stays about the elements that are there. `game-pack` is unchanged: it packs the elements a report has, so a missing element has no `ui.nine_slice` entry and a game falls back for exactly that part. A square sheet's report, elements and packs are unchanged byte for byte, and its report has no `missing` ([ui-kit](docs/ui-kit.md#missing-elements)).+- **Behavior change: `ui-kit` writes a kit whole into a new directory and refuses one that holds anything.** `--out-dir` must not exist yet or be an empty directory. One that holds an earlier kit or any other file is refused with its name and what it holds, and left as it was, where a rerun used to rewrite the kit in place one file at a time and a failure partway left two kits mixed under one report. The kit is written into a hidden directory beside `--out-dir` and renamed into place in one step, so a run that fails or is killed at any step leaves either nothing or the whole kit, and of two runs into one new `--out-dir` the second is refused. A `--report` outside `--out-dir` must be a new path: it takes its name after the rename, in a step that fails when another run took the name first. One step publishes the kit, the rename or, with the report outside, the report's own step: a run that fails or is stopped with Ctrl-C before it takes everything it made back out, and one stopped after it leaves the whole kit and its report, so a report never names a PNG that is not there. A killed run can leave its hidden directory (`.<out-dir>.ui-kit-*`) or report temp beside them, and, with the report outside, the whole kit without its report. A run that is interrupted again while it is removing what it made (for example, a second Ctrl-C during that clean-up) cannot finish the clean-up either: it can leave the same things a killed run leaves, and never leaves part of a kit under `--out-dir`'s own name: `--out-dir` holds nothing or the whole kit ([ui-kit](docs/ui-kit.md#split-the-sheet)).+- **Fix: a UI kit sheet drawn a few percent shorter than its guide is cut instead of refused.** An image model may draw the layout a few percent shorter than the guide; the lower an element, the farther it sits above its box, until its centroid lies in the widened box above its own. That box held two elements and the element's own box none, so `ui-kit` refused the sheet with `<element>: its box holds no element` although every element was drawn. When a box is left empty, `ui-kit` now fits the layout to the drawing (a scale and an offset along x and y, least squares from the box centres to what the boxes hold, repeated until the assignment comes out the same) and assigns the parts again. The fit is kept when it leaves fewer required boxes empty, or as many and fewer boxes in all. A kept fit is in the report as `layout_fit`, and each `box` is then the fitted box. A sheet whose every box holds its element is cut exactly as before ([ui-kit](docs/ui-kit.md#a-drawing-that-drifted-from-the-layout)).+- **Behavior change: a key background painted as a transparency checkerboard is refused before keying.** Asked for a magenta or green key, a model sometimes paints the grey and white checkerboard editors show behind transparent pixels. The matte read the checkerboard as the key and keyed nearly the whole image away, so a UI kit sheet had nothing left to cut. Every chroma key in `gen` now checks the raw first (`chroma.painted_checkerboard`: two greys alternating in squares of one size along a horizontal edge and a vertical edge), and fails with its own reason, `chroma: the background is a painted transparency checkerboard (… px squares along the … edges), not the magenta key the image was asked for; keying it would erase the image — generate it again`, publishing nothing. A ref run whose raw is a drawn checkerboard was keyed before; it is refused now. Key backgrounds, plain or striped grey backgrounds, and a checkered subject inside a key background are not refused ([gen](docs/gen.md#transparent-output--strategy-per-provider)).+- **Tests** — `tests/frames/test_ui_kit.py` (the frames required and the band optional; an empty band box, several, or the whole band leaves those elements out of the report, the PNGs and the pack; an empty frame box, alone, several at once, or on a squeezed sheet (each frame in turn), refuses the sheet by that frame's name; a kit is written into a new or empty directory, and one that holds a kit, any other file or a hidden one, or a file at its path, is refused and left byte for byte as it was; one failure, interrupt or kill injected just before or just after each filesystem step of the publish, with the report in and outside `--out-dir` and `--out-dir` absent or empty (and removed first, as on Windows), leaves nothing before the step that publishes the kit and the whole kit from it on; an interrupt of any kind (SIGINT, SIGTERM through a handler that exits, any other exception) at each step from the rename on, with no function replaced, the same; a sweep in which an interrupt of each kind (SIGINT, SIGTERM through a handler that exits, any other exception) is raised once per run at each line, and at each instruction, of the publish, with the report in and outside `--out-dir` and `--out-dir` absent, empty, or empty and removed first, and every run ends with that interrupt and leaves either the start, with nothing hidden, or the whole kit; a run whose `--out-dir` or outside report another run reaches first is refused and removes what it made; a 2:3 sheet drawn 7 % shorter than its guide, which the layout's own boxes refuse, is fitted and every element is cut whole inside its fitted box; a square report has no `missing`), `tests/gen/test_painted_checkerboard.py` (checkerboards of 8, 12 and 32 px squares at any phase and greys, with elements across two edges, are found; key, plain grey, gradient and striped backgrounds and a chessboard inside a key background are not; `key_transparent` and a `--layout-guide ui-kit` run refuse a checkerboard before the matte runs and publish nothing), and the drawn-checkerboard ref run in `tests/gen/test_gen.py`, which now refuses.- **Tests** — `tests/background/test_tile_xy.py` (an exact doubly periodic crop, a join that stays visible on one axis names that axis, the cyclic seam), `tests/frames/test_alpha_floor.py` (a haze ring cleared, thin strokes and their anti-aliased edges kept), `tests/frames/test_ui_kit.py` (a synthetic sheet on the layout: insets to the pixel over corner ornaments, a long flourish, a bar's end gem and cap; badge padding inside its ring; a packed kit at four scales keeps ornament fringes out of the stretched middle; a report in, beside, below or above `--out-dir` names the PNGs from its own directory and packs the same bytes), `tests/frames/test_slice_sheet_transparent.py`, `tests/compose/test_game_pack_v2.py` (the manifest field by field, refusals, and a version 1 manifest and page pixels frozen from 2.44.0), `tests/compose/test_game_pack_audio.py` (a version 1 pack with sound keeps its file list, manifest bytes and page pixels from 2.44.0; a version 2 pack with sound adds only its tile files) the `--layout-guide ui-kit` cases in `tests/gen/test_layout_guide.py` (square and 2:3, any other ratio refused), the 2:3 sheet in `tests/frames/test_ui_kit.py` (every element cut from a synthetic sheet; fills fit their frame's content area in the report and, packed at three scales, to the pixel with their ends unchanged; dots and joystick parts never stretch and one drawn on a square plate is flagged; slot and plate insets to the pixel; a square sheet's report, element pixels and packs frozen from before the 2:3 sheet) and the fill cases in `tests/compose/test_game_pack_v2.py`, and `tests/frames/test_slice_sheet_scale.py` (synthetic sheets: drawn heights kept within a pixel with `--scale sheet`, after the alpha cleanup too; a 2:1 subject whole on a square canvas with `--fit contain` while the default still cuts it and says so; one factor every cut fits; sliced cells packed as game-pack `images` keep one size and stand on the reported anchor; refusals).- Bump audio processing recipe to version 4, measure BS.1770-4 loudness over normalized PCM frames and gated blocks, support a peak-limited loudness goal, normalize loudnorm-unanalysable short clips via limiter passes instead of refusing them, encode AAC using `-aac_coder fast`, record `normalization.pcm_lufs` and `pcm_true_peak_dbtp` required to load version 4 bundles, keep recipe version 3 bundles loadable in game packs by their own rule (target loudness, decoded files re-measured with loudnorm), reject recipe version 1-2 bundles, and reject recipe version 1-3 output directories in `sprite-gen sound` while reusing cached provider audio.diff --git a/SKILL.md b/SKILL.mdindex d76c577..2e998b6 100644--- a/SKILL.md+++ b/SKILL.md@@ -120,7 +120,7 @@ hold the arms still, and check the loop with `handed-check --state walk`.| Engine exports | `export-aseprite`, `export-pngs` | [engine-export](docs/engine-export.md) || Background recipe or repeating tile | existing `gen` / `cutout`, then optional `background-tile` | [asset-tools](docs/asset-tools.md#background-recipe) || Ground tile that repeats both ways | `gen` (opaque), then `background-tile --axis xy` | [asset-tools](docs/asset-tools.md#both-axes-a-ground-tile) |-| Game UI kit: panel, buttons, card, HP/XP bar frames and fills, timer badge, item slot, counter plate, on/off dots, joystick base and knob as sliced elements | `gen --transparent --aspect-ratio 2:3 --layout-guide ui-kit` (`1:1`: the seven frames alone), then `ui-kit` | [ui-kit](docs/ui-kit.md) |+| Game UI kit: panel, buttons, card, HP/XP bar frames and fills, timer badge, item slot, counter plate, on/off dots, joystick base and knob as sliced elements | `gen --transparent --aspect-ratio 2:3 --layout-guide ui-kit` (`1:1`: the seven frames alone), then `ui-kit`; the seven frames are required, and a band element whose box is empty is left out and named under `missing` | [ui-kit](docs/ui-kit.md#missing-elements) || Props or icons on a transparent sheet | `slice-sheet --chroma-key none --alpha-floor 64`, props with `--scale sheet --fit contain`, icons with `--fit contain` | [sheet-slicing](docs/sheet-slicing.md#props-and-icons-sheet-scale-and-contain-fit) || Painted props, a ground tile and a UI kit in a game pack | `game-pack` request version 2 (`images`, `tiles`, `ui`) | [game-pack](docs/game-pack.md#version-2-images-tiles-and-ui) || Standalone projected shadow | `shadow` | [asset-tools](docs/asset-tools.md#projected-shadows) |@@ -130,7 +130,7 @@ hold the arms still, and check the loop with `handed-check --state walk`.Say a thing once: what an option says, leave out of the prompt. `--direction`, `--facing`, `--handed`, the key background and `video --direction side` each add their own sentence after your text, in one place; without `--handed` every prompt is 2.22.0's, byte for byte, and only the handed sentences are left out where your text already has them. Your prompt carries the subject, its design and its pose. Text that says the opposite of an option ("facing left" with `--facing right`, the item on the other wrist) is sent as written with a warning (`extra.prompt_notes`, `video-prompt`'s `warnings`): fix the prompt, do not send it — [prompt-assembly](docs/prompt-assembly.md).-`gen --transparent` with `--ref` plans a chroma key (adding the key's background line to a prompt that names none), and publishes a result that already came back transparent on its own alpha instead of keying its outline away; `alpha.strategy_source` in the report says which (`refs-attached` keyed, `refs-attached-raw-alpha` not) — [gen](docs/gen.md#transparent-output--strategy-per-provider).+`gen --transparent` with `--ref` plans a chroma key (adding the key's background line to a prompt that names none), and publishes a result that already came back transparent on its own alpha instead of keying its outline away; `alpha.strategy_source` in the report says which (`refs-attached` keyed, `refs-attached-raw-alpha` not). A key background painted as a transparency checkerboard is refused before keying (`chroma: the background is a painted transparency checkerboard …`): generate again — [gen](docs/gen.md#transparent-output--strategy-per-provider).Use existing automatic pipeline stages for background removal, extraction, alignment and export. Do not ask users to select each script. For a direct utility request, run that utility; no unrelated generation questions are needed. Preserve the row pipeline and component extraction for image sprites. One-shot grid generation and fixed cell cutting are not an alternative sprite-generation route.diff --git a/docs/game-pack.md b/docs/game-pack.mdindex ebdfdd5..8b21336 100644--- a/docs/game-pack.md+++ b/docs/game-pack.md@@ -271,7 +271,7 @@ What each field means, with no reading left to the consumer:* `ui.icons[*].size` is the stored frame size; icons are drawn as they are.* The atlas frames of images, UI elements and icons have `trimmed: false`, `rotated: false` and the same one-pixel extrusion as animation frames. UI element and icon frames have the pivot `{x: 0.5, y: 0.5}`.-The UI kit element names are fixed by the [`ui-kit` layout](ui-kit.md#layout): `panel`, `button`, `button_pressed`, `card`, `hp_bar_frame`, `xp_bar_frame` and `timer_badge` from a square sheet, and from a 2:3 sheet those seven and `hp_bar_fill`, `xp_bar_fill`, `slot`, `badge`, `pip_on`, `pip_off`, `joystick_base` and `joystick_knob`. Their `stretch` is part of the layout: the frames, buttons, slot and badge are `"xy"`; the two bar frames and the two fills `"x"`; the timer badge, the pips and the joystick base and knob `"none"`. The fills, the pips and the joystick parts hold no content, so their padding is `0`. These names are additive: the manifest stays version 2, and a kit from a square sheet packs to the same manifest and the same atlas pixels as before.+The UI kit element names are fixed by the [`ui-kit` layout](ui-kit.md#layout): `panel`, `button`, `button_pressed`, `card`, `hp_bar_frame`, `xp_bar_frame` and `timer_badge` from a square sheet, and from a 2:3 sheet those seven and `hp_bar_fill`, `xp_bar_fill`, `slot`, `badge`, `pip_on`, `pip_off`, `joystick_base` and `joystick_knob`. Their `stretch` is part of the layout: the frames, buttons, slot and badge are `"xy"`; the two bar frames and the two fills `"x"`; the timer badge, the pips and the joystick base and knob `"none"`. The fills, the pips and the joystick parts hold no content, so their padding is `0`. These names are additive: the manifest stays version 2, and a kit from a square sheet packs to the same manifest and the same atlas pixels as before. A 2:3 sheet may leave an optional element out ([missing elements](ui-kit.md#missing-elements)): the report then names it under `missing` and has no entry for it, and the pack has no `ui.nine_slice` entry and no atlas frame for it. A game falls back for exactly the parts `nine_slice` lacks.## Audio Assets and Playbackdiff --git a/docs/gen.md b/docs/gen.mdindex 75b3557..e608760 100644--- a/docs/gen.md+++ b/docs/gen.md@@ -315,7 +315,7 @@ strategy it can execute, and `--alpha-mode auto` (the default) follows it:| Strategy | Who | What happens | Refused when ||---|---|---|---|| `native` | `codex` (**first choice**, 2026-09-08), `openai` (`background: transparent`) | On codex the transport prompt asks image_gen for a genuinely transparent background (the bundled `imagegen` skill honours "transparent background" and keeps the generated alpha; codex reports `transparentBackground: true` on the completed item); on openai the request carries `background: transparent` with `output_format: png`, which the API answers with a real alpha channel. Either way the decoded PNG's alpha is **measured**: no alpha band or `alpha_zero_pct: 0.0` refuses to publish, RGB under alpha 0 is scrubbed, partial alpha (1–254) is left as produced and reported as `partial_alpha_pct`. | The model drew a checkerboard / flat background (RGB image) — nothing can recover alpha from that, so the run fails instead of silently keying. |-| `chroma` | `grok` (only option), `codex` with `--alpha-mode chroma` | Generate on a `#FF00FF` (or `#00FF00`) background — pick the key by subject colour (magenta subjects → green key) — and matte it out through the frame extractor's canonical YCbCr matte (`remove_chroma_background_ycbcr`), which keys from the background chroma it detects on the borders (`detect_background_key_ycc`) rather than from the pure key alone — the RGB matte behind `cutout`/`extract`/`slice-sheet` does the same since 2026-09-11 (`detect_background_key_rgb`), so every chroma path tolerates the slightly-off green/magenta generators actually paint. Gradients and texture within that chroma family are supported. | `alpha_zero_pct: 0.0` after keying, or stale RGB under alpha 0. |+| `chroma` | `grok` (only option), `codex` with `--alpha-mode chroma` | Generate on a `#FF00FF` (or `#00FF00`) background — pick the key by subject colour (magenta subjects → green key) — and matte it out through the frame extractor's canonical YCbCr matte (`remove_chroma_background_ycbcr`), which keys from the background chroma it detects on the borders (`detect_background_key_ycc`) rather than from the pure key alone — the RGB matte behind `cutout`/`extract`/`slice-sheet` does the same since 2026-09-11 (`detect_background_key_rgb`), so every chroma path tolerates the slightly-off green/magenta generators actually paint. Gradients and texture within that chroma family are supported. | `alpha_zero_pct: 0.0` after keying, or stale RGB under alpha 0; and, before keying, a background painted as a transparency checkerboard (below). |- **`auto` steps down to `chroma` when `--ref` is attached**, on either native provider. Measured2026-09-08 (plan `sprite-gen/parts-rig`): codex `image_gen` with reference images@@ -354,7 +354,8 @@ strategy it can execute, and `--alpha-mode auto` (the default) follows it:Keying it reads the RGB left under alpha 0 as the background colour and mattes theoutline and light fills away. A raw with no alpha band or no alpha-0 pixel — a drawncheckerboard, a key background, an opaque RGBA — is `no-alpha` and keyed as before- (`strategy_source: "refs-attached"`). Alpha 0 that misses either bar is `ambiguous`:+ (`strategy_source: "refs-attached"`), but a painted checkerboard is refused before+ keying (below). Alpha 0 that misses either bar is `ambiguous`:keyed as before, with a `warning` in the report and on stderr. The verdict and itsnumbers are in `alpha.raw_alpha` on every ref run that planned the key. The checkbelongs to `auto`'s step down only — `--alpha-mode chroma` keys whatever comes back.@@ -372,6 +373,23 @@ strategy it can execute, and `--alpha-mode auto` (the default) follows it:the native request (`--alpha-mode native`), both came back with real alpha 3/3 —no checkerboard in 6 runs, against 5 of 6 on 2026-09-08. The step down is keptuntil a larger measurement replaces that one.+- **A painted transparency checkerboard is refused before keying.** Asked for a key+ background, a model sometimes paints the grey and white checkerboard that editors show+ behind transparent pixels instead. The matte reads the key off the borders, so it reads+ the checkerboard and keys nearly the whole image away: a UI kit sheet keyed that way has+ nothing left to cut. Every chroma key checks the raw first+ (`chroma.painted_checkerboard`). Each edge is read on its 8 nearest lines. A line is+ a checkerboard row when at least 90 % of it is grey (channels within 24 of each other),+ it holds two greys at least 12 apart (10th and 90th percentiles), and it changes from+ one to the other in at least 6 runs between changes, whose median is 4 to 128 px and+ three quarters of which lie within a quarter of it (or 2 px). A checkerboard alternates along both axes, so+ the raw is one when the top or bottom edge and the left or right edge show it. Stripes+ alternate along one axis only, a key background is not grey, and a checkered subject+ inside a key background does not reach the edges. The run then fails with its own+ reason, before anything is published:+ `chroma: the background is a painted transparency checkerboard (8 px squares along the+ top, bottom, left and right edges), not the magenta key the image was asked for; keying+ it would erase the image — generate it again`. A caller generates again.- `--alpha-mode chroma` on codex is for prompts that already carry a key background(the sprite-row pipeline today): the native request is **not** added to the promptand the raw is keyed like a grok run.diff --git a/docs/ui-kit.md b/docs/ui-kit.mdindex 81d88ff..cc23730 100644--- a/docs/ui-kit.md+++ b/docs/ui-kit.md@@ -1,8 +1,8 @@# `ui-kit` — one painted sheet to nine-slice UI elements-> Owns: The UI kit layout guide, splitting a transparent UI kit sheet into elements, nine-slice insets, content padding and fills · Index: [docs/README.md](README.md)+> Owns: The UI kit layout guide, splitting a transparent UI kit sheet into elements, writing a kit whole into a new directory, fitting the layout to a drawing that drifted from it, required and missing elements, nine-slice insets, content padding and fills · Index: [docs/README.md](README.md)-A game UI kit is one transparent image with every part of a game's menus and HUD on it: a panel, a button and its pressed state, a card frame, two bar frames and a timer badge, and on the taller sheet the two bars' fills, an item slot, a counter plate, a lit and an unlit dot, and a touch joystick's base and knob. `gen --layout-guide ui-kit` asks the image model to draw each element in a fixed box. `ui-kit` cuts the sheet along those boxes, measures where each element may stretch, and writes one PNG per element with a JSON report. [`game-pack`](game-pack.md#version-2-images-tiles-and-ui) reads that report.+A game UI kit is one transparent image with every part of a game's menus and HUD on it: a panel, a button and its pressed state, a card frame, two bar frames and a timer badge, and on the taller sheet the two bars' fills, an item slot, a counter plate, a lit and an unlit dot, and a touch joystick's base and knob. `gen --layout-guide ui-kit` asks the image model to draw each element in a fixed box. `ui-kit` cuts the sheet along those boxes, measures where each element may stretch, and writes one PNG per element with a JSON report. [`game-pack`](game-pack.md#version-2-images-tiles-and-ui) reads that report. The seven frames are the kit; the taller sheet's other eight elements are optional, so a sheet that leaves one of them out still makes a kit, without it ([missing elements](#missing-elements)).## Generate the sheet@@ -15,6 +15,8 @@ sprite-gen gen --provider openai --quality high --transparent --aspect-ratio 2:3The sheet's shape chooses the layout. `--aspect-ratio 2:3` draws the whole kit; `--aspect-ratio 1:1` (or no ratio) draws the seven frames alone, the layout every square sheet has had. Every provider that takes a ratio takes both.+The guide is an attached image, so `--transparent` keys the sheet out of a magenta background by default ([gen](gen.md#transparent-output--strategy-per-provider)). A model sometimes paints the grey and white checkerboard that editors show behind transparent pixels instead of that background. Keying the checkerboard would erase the sheet, so `gen` refuses it before keying, with its own reason (`chroma: the background is a painted transparency checkerboard …`). Generate the sheet again.+## LayoutThe guide and the splitter read one table (`sprite_gen.frames.ui_kit.LAYOUT`). Boxes are in pixels of a sheet 1024 px wide: 1024 × 1024 for the square sheet, 1024 × 1536 for the 2:3 sheet. They scale with the sheet's size, and neighbouring boxes are 48 px apart. The square sheet holds the first seven elements. The 2:3 sheet holds the same seven at the same places and the other eight in a band below them. `ui-kit` reads a sheet's shape to know which: square or 2:3, each within 1 %; any other shape is refused. So a square sheet drawn before the 2:3 sheet existed is cut, measured and packed exactly as before.@@ -37,7 +39,7 @@ The guide and the splitter read one table (`sprite_gen.frames.ui_kit.LAYOUT`). B| `joystick_base` | 2:3 | 704, 1024, 272, 272 (circle) | `none` | `0` | a round touch joystick base || `joystick_knob` | 2:3 | 768, 1344, 144, 144 (circle) | `none` | `0` | the joystick's round knob |-`stretch` is how a game may resize the element: `xy` as a nine-slice, `x` in width only (a three-slice), `none` not at all. Round parts (`timer_badge`, the pips, the joystick base and knob) are `none`, so they are only ever drawn at their own proportions. `stretch` belongs to the layout, not to the measurement; so does whether padding is measured: an element that holds no content (a fill, a pip, a joystick part) gets a padding of `0` on every side. The two pips have boxes of one size, so a row of dots can swap one for the other in place.+`stretch` is how a game may resize the element: `xy` as a nine-slice, `x` in width only (a three-slice), `none` not at all. Round parts (`timer_badge`, the pips, the joystick base and knob) are `none`, so they are only ever drawn at their own proportions. `stretch` belongs to the layout, not to the measurement; so does whether padding is measured: an element that holds no content (a fill, a pip, a joystick part) gets a padding of `0` on every side. The two pips have boxes of one size, so a row of dots can swap one for the other in place. The seven elements on both sheets are required, and the eight on the 2:3 sheet alone are optional ([missing elements](#missing-elements)).The guide draws the pips and the joystick base and knob as the circles their boxes hold, and asks for them as circles with nothing square around them. A model may still draw a round part on a square plate that fills its box, so the splitter checks: when more than a quarter of the area outside the ellipse a round part's cut holds (the ellipse touching the cut's four sides) is opaque, at alpha 128 or more, the report is `needs-review` with `<element>: its corners are filled`. Regenerate the sheet; a plate behind a dot or a joystick shows as a square in the game. The timer badge keeps the square sheet's box and is not checked, so square sheets cut as they always have.@@ -47,17 +49,56 @@ The guide draws the pips and the joystick base and knob as the circles their boxsprite-gen ui-kit --sheet uikit.png --out-dir ui/```-The command writes `ui/<element>.png` for every element the sheet's layout holds and `ui/ui-kit.json`. It never changes the sheet and refuses an output directory that holds the sheet. Options:+The command writes `ui/<element>.png` for every element the sheet's layout holds (but a [missing](#missing-elements) one) and `ui/ui-kit.json`. Options:* `--alpha-floor N` (default `64`, `0` turns it off) and `--alpha-edge N` (default `2`): the [alpha cleanup](#alpha-cleanup) that runs before anything is cut.-* `--report PATH`: write the JSON report elsewhere (default `<out-dir>/ui-kit.json`); it must end in `.json`. Each element's `file` in it then leads from the report's directory to the PNG in `--out-dir`.+* `--report PATH`: write the JSON report elsewhere (default `<out-dir>/ui-kit.json`); it must end in `.json`, and outside `--out-dir` it must be a path that does not exist yet. Each element's `file` in it then leads from the report's directory to the PNG in `--out-dir`.++A kit is written whole into a new directory. `--out-dir` must not exist yet, or be an empty directory; one that holds anything, an earlier kit or any other file, is refused with its name and what it holds, and left as it was. Write each kit into a directory of its own, or remove the old one first. The command never changes the sheet, and a refused sheet writes nothing.++The kit (every element PNG, and the report when it is in `--out-dir`) is written into a hidden directory beside `--out-dir`, `.<name>.ui-kit-<random>`, which then takes `--out-dir`'s name in one rename. A report outside `--out-dir` is written to a hidden temp file beside it first and given its own name after the rename, in a step that fails when that name has been taken, so no run replaces another's report.++One step publishes the kit: that rename, or with the report outside `--out-dir`, the step that gives the report its name. A run that fails, or is stopped with Ctrl-C, before that step removes everything it made: the kit, the directories it created, its hidden directory and temp file; an empty `--out-dir` it was given is left empty. Stopped after that step, the command still exits with the interruption, but the kit is published: the run removes nothing but its temp file, and the whole kit and its report stay. So `--out-dir` holds either nothing or the whole kit, never part of one, and a report never names a PNG that is not there. When two runs write into one new `--out-dir`, the one whose kit lands second is refused and removes its own; the same holds for two runs and one outside report.++A run that is killed, rather than failing, cannot clean up after itself:++* It can leave its hidden `.<name>.ui-kit-<random>` directory beside `--out-dir`, or a hidden `.<report>.<random>.tmp` file beside an outside report, and the directories it created; remove them. Under `--out-dir`'s own name it never leaves anything but the whole kit.+* With the report outside `--out-dir`, a run killed between the rename and the step that publishes the kit leaves the whole kit in `--out-dir` and no report. Remove the directory and run again.+* On Windows, a rename takes no existing directory's name, not even an empty one's, so an empty `--out-dir` is removed just before the rename (a run that fails puts it back). A run killed at that moment leaves no `--out-dir`.+* A run that is interrupted again while it is removing what it made (for example, a second Ctrl-C during that clean-up) cannot finish the clean-up either. It can leave the same things a killed run leaves: its hidden staging directory or hidden report temp file beside the output, the directories it created, with an outside report the whole kit without its report, and on Windows no `--out-dir`. It never leaves part of a kit under `--out-dir`'s own name: `--out-dir` holds nothing or the whole kit.++The steps of the cut:1. **Alpha cleanup.** Faint haze between elements would join them, so it is cleared first (below).2. **Parts.** Pixels with alpha above zero form 8-connected parts. A part smaller than 16 pixels is dropped and counted.-3. **Assignment.** Each part goes to the box that contains its centroid, with every box widened by half the gap (24 px at 1024). A part whose centroid lies in no widened box is reported under `unassigned`; it makes the report `needs-review` when it has at least 16 pixels.-4. **Crop.** An element is the bounding box of its box's parts, so ornaments that reach past the box stay whole. A box with no part fails the command: the sheet has to be generated again.+3. **Assignment.** Each part goes to the box that contains its centroid, with every box widened by half the gap (24 px at 1024). When that leaves a box empty, the layout is [fitted to the drawing](#a-drawing-that-drifted-from-the-layout) and the parts are assigned again. A part whose centroid lies in no widened box is reported under `unassigned`; it makes the report `needs-review` when it has at least 16 pixels.+4. **Crop.** An element is the bounding box of its box's parts, so ornaments that reach past the box stay whole. A box with no part fails the command when its element is required (the sheet has to be generated again), and leaves its element out when it is optional ([missing elements](#missing-elements)).5. **Insets** and **padding** are measured on the cropped element (below).+### A drawing that drifted from the layout++An image model may draw the layout a little off. The whole drawing can come out a few percent shorter than the guide, and then the lower an element is, the farther it sits above its box, until its centroid lies in the widened box above its own: that box holds two elements, and the element's own box none. So, when a box is left empty:++1. **Fit.** Along x and along y, take the scale and offset that move the layout's box centres closest (least squares) to the centres of what the boxes hold (the bounding box of each box's parts). Along an axis on which every box that holds parts is centred on one line, take an offset alone.+2. **Assign again.** Move every box by the fit, its position and its size, and its widening by half the gap with it, and assign the parts to the moved boxes.+3. Repeat from the new assignment until it comes out the same, at most 8 rounds. Fewer than 3 boxes that hold parts, or a scale that is not positive, end it without a fit.+4. **Keep it or not.** The fitted assignment replaces the layout's own when it leaves fewer required boxes empty, or as many and fewer boxes in all.++A sheet whose every box holds its element is never fitted, so it is cut exactly as before. A kept fit is in the report as `layout_fit`, and each element's `box` is then its fitted box. The tests draw a 2:3 sheet 7 % shorter than its guide, from the top edge down. Assigned to the layout's own boxes, three boxes are left empty (`badge`, `pip_off` and `joystick_knob`), two hold two elements each, and the upper fill lies in no box; the fitted boxes find all fifteen elements whole.++## Missing elements++The seven frames are the kit, and each is required: `panel`, `button`, `button_pressed`, `card`, `hp_bar_frame`, `xp_bar_frame` and `timer_badge`. When a frame's box is empty, after the fit, `ui-kit` writes nothing and fails with `<element>: its box holds no element; generate the sheet again`, or, for several, `panel, card: their boxes hold no element; generate the sheet again`.++The eight elements of the 2:3 band are optional: the two fills, the slot, the badge, the two dots and the joystick base and knob. When one's box is empty, the kit is made without it:++* It has no PNG and no entry in `elements`. The report names it under `missing`, in layout order. A 2:3 report always has `missing` (`[]` when nothing is missing); a square report has none, as before, since a square sheet's elements are all required.+* The command exits `0`, and its line ends with `; missing, left out of the kit: pip_off`.+* A missing element is not a measurement to review: `status` and `review_reasons` are about the elements that are there.+* [`game-pack`](game-pack.md#version-2-manifest) packs the elements the report has, so a missing element has no `ui.nine_slice` entry, and a game falls back for exactly that part. A game that needs both dots, or both joystick parts, falls back for both when one of them is missing.++The whole kit is drawn in one image call, so a model that leaves one box of the band empty costs that element, not the kit. Generate the sheet again to get it.+## InsetsInsets are measured only along the axes the layout lets the element stretch; the others are `0`. Along x (columns; y is the same with rows):@@ -144,16 +185,24 @@ Solid pixels and edge pixels are never changed, so a stroke stays whole as long}```-`box` is the layout box scaled to this sheet and `rect` the element's bounding box, both in sheet pixels. A fill also has [`inside`](#fills); no other element has it. `file` is the element PNG's path from the report's own directory, with `/` separators: `panel.png` when the report is in `--out-dir` (the default), `../elements/panel.png` for `--out-dir elements --report reports/kit.json`. A reader joins it to the report's directory, as [`game-pack`](game-pack.md#version-2-request) does, so a report and its elements move together. `size`, `insets` and `padding` are in pixels of the element PNG. Elements appear in layout order. `status` is `needs-review` when any `review_reasons` apply; the PNGs are written either way, so the elements can be inspected.+`box` is the layout box scaled to this sheet (its fitted box when the report has `layout_fit`) and `rect` the element's bounding box, both in sheet pixels. A fill also has [`inside`](#fills); no other element has it. `file` is the element PNG's path from the report's own directory, with `/` separators: `panel.png` when the report is in `--out-dir` (the default), `../elements/panel.png` for `--out-dir elements --report reports/kit.json`. A reader joins it to the report's directory, as [`game-pack`](game-pack.md#version-2-request) does, so a report and its elements move together. `size`, `insets` and `padding` are in pixels of the element PNG. Elements appear in layout order. `status` is `needs-review` when any `review_reasons` apply; the PNGs are written either way, so the elements can be inspected.++A 2:3 report also has `missing`, the optional elements whose boxes were empty, in layout order ([missing elements](#missing-elements)). When the layout was [fitted to the drawing](#a-drawing-that-drifted-from-the-layout), the report has `layout_fit`, after `missing` and before `elements`; for a synthetic 1024 × 1536 sheet drawn 7 % shorter than its guide:++```json+"layout_fit": { "scale": { "x": 0.9969, "y": 0.9301 }, "offset": { "x": -0.2, "y": 0.0 } }+```++A layout box at (x, y, w, h), scaled to the sheet, was fitted to (x · scale.x + offset.x, y · scale.y + offset.y, w · scale.x, h · scale.y). `offset` is in sheet pixels, rounded to a tenth; `scale` is rounded to four decimals.Like every measurement here, `pass` means the numbers found nothing to flag. Look at the elements stretched to a few sizes before shipping them.## Python API-* `sprite_gen.frames.ui_kit.split_ui_kit(image, *, alpha_floor=64, alpha_edge=2) -> (elements, report)`: the elements as images by name, and the report as written to its default place, `<out-dir>/ui-kit.json` (each `file` is `<element>.png`), without `sheet`.+* `sprite_gen.frames.ui_kit.split_ui_kit(image, *, alpha_floor=64, alpha_edge=2) -> (elements, report)`: the elements as images by name, and the report as written to its default place, `<out-dir>/ui-kit.json` (each `file` is `<element>.png`), without `sheet`. A missing optional element is in neither; a `ValueError` when a required box is empty.* `sprite_gen.frames.ui_kit.report_file(report, png) -> str` and `element_path(report, file) -> Path`: the `file` a report at `report` gives an element PNG, and the PNG a report's `file` names.* `sprite_gen.frames.ui_kit.measure_insets(image, stretch) -> (insets, notes)` and `measure_padding(image) -> (padding, notes)`: the measures above on one element image, with the review notes they raise.* `sprite_gen.frames.ui_kit.content_rect(record)` and `fit_inside(fill, frame, name) -> (inside, note)`: an element record's content rectangle, and a fill's `inside` with its review note.-* `sprite_gen.frames.ui_kit.sheet_layout(size) -> (reference_size, slots)`: the layout a sheet of that size holds; a `ValueError` for a shape that is neither square nor 2:3.+* `sprite_gen.frames.ui_kit.sheet_layout(size) -> (reference_size, slots)`: the layout a sheet of that size holds; a `ValueError` for a shape that is neither square nor 2:3. Each slot's `optional` says whether a sheet may leave it out.* `sprite_gen.frames.ui_kit.boxes(size)`, `draw_guide(path, size)` and `guide_text(size)`: the boxes a sheet of that size holds, the guide image and its prompt paragraph (`size` defaults to the square sheet).* `sprite_gen.frames.alpha_floor.clear_haze(image, *, floor=64, edge=2) -> (image, report)`.diff --git a/sprite_gen/frames/ui_kit.py b/sprite_gen/frames/ui_kit.pyindex f2ad22f..d3347ce 100644--- a/sprite_gen/frames/ui_kit.py+++ b/sprite_gen/frames/ui_kit.py@@ -5,27 +5,36 @@ docs/ui-kit.md is the contract. One table (`LAYOUT`) is the layout: `gen --layoudraws it (`draw_guide`) and says it (`guide_text`), and the splitter cuts along it. A sheet's shapesays which part of the table it holds (`SHEETS`): a square sheet the seven frames, a 2:3 sheet thesame frames at the same places and the fills, slot, badge, pips and joystick below them. The sheet's-alpha haze is cleared first (`alpha_floor.clear_haze`), parts are assigned to boxes by centroid,-and each element's insets and content padding are measured on its own pixels; a fill is fitted to its-bar frame's content area. The report names each element PNG by its path from the report's own-directory (`report_file`, `element_path`).+alpha haze is cleared first (`alpha_floor.clear_haze`), parts are assigned to boxes by centroid+(when a box is left empty, again to the layout fitted to the drawing, `_fit_layout`), and each+element's insets and content padding are measured on its own pixels; a fill is fitted to its bar+frame's content area. The frames are required; an optional element whose box is empty is left out+and named under `missing`. The report names each element PNG by its path from the report's own+directory (`report_file`, `element_path`). A kit is written whole into a new or empty output+directory (`_write_kit`): staged in a hidden directory beside it and renamed into place in one step.+That rename, or with the report outside the directory the link that names the report, publishes the+kit: a run that fails or is interrupted before it leaves nothing, one after it the whole kit, and a+killed run, or one interrupted again while it cleans up, never part of one. A directory that holds+anything is refused."""from __future__ import annotationsimport argparse+import contextlibimport ioimport jsonimport os+import secrets+import shutilfrom dataclasses import dataclassfrom pathlib import Path-from typing import Any+from typing import Any, Callablefrom PIL import Image, ImageDrawfrom sprite_gen._deps import npfrom sprite_gen.frames.alpha_floor import clear_haze-from sprite_gen.spec.runio import acquire_run_dir_lock, atomic_write_set, release_run_dir_lockREFERENCE = 1024GAP = 48@@ -38,11 +47,19 @@ PADDING_SPAN = 96# A round part whose cut is more than this opaque outside the ellipse its bounding box holds was drawn on a# square plate, not as a circle (docs/ui-kit.md "Layout").ROUND_CORNER_FILL = 0.25+# Fitting the layout to a drawing that drifted from it (docs/ui-kit.md "Split the sheet"): at most this many+# rounds of fit and assignment, from at least this many boxes that hold parts.+FIT_ROUNDS = 8+FIT_MIN_BOXES = 3GUIDE_BACKGROUND = (0xF6, 0xF6, 0xF6)GUIDE_BOX = (0x2F, 0x80, 0xED)STRETCHES = ("xy", "x", "none")SIDES = ("left", "right", "top", "bottom")REPORT_KIND = "sprite-gen-ui-kit"+# A kit's staging directory takes the output directory's name with one rename. POSIX rename(2) takes the name of an+# absent or empty directory and fails on any other; Windows takes no existing directory's name, so an empty output+# directory is removed just before the rename there (Python docs, os.rename).+RENAME_ONTO_EMPTY_DIR = os.name != "nt"@dataclass(frozen=True)@@ -59,6 +76,9 @@ class Slot:inside: str | None = None# A round part: the guide draws a circle in its box, and a cut with filled corners is flagged.round: bool = False+ # An optional element: when its box is empty the kit is made without it and the report names it under+ # `missing`; an empty box of a required element refuses the sheet (docs/ui-kit.md "Missing elements").+ optional: bool = FalseLAYOUT = (@@ -79,22 +99,22 @@ LAYOUT = (# The band below the square, on the 2:3 sheet only.Slot("hp_bar_fill", (48, 1024, 608, 64), "x", "the long thin box at the top left of the band","the health bar's fill alone, a bare strip of colour with no frame, rim or end pieces around it",- content=False, inside="hp_bar_frame"),+ content=False, inside="hp_bar_frame", optional=True),Slot("xp_bar_fill", (48, 1136, 608, 64), "x", "the long thin box below it","the experience bar's fill alone, the same kind of bare strip in its own colour", content=False,- inside="xp_bar_frame"),+ inside="xp_bar_frame", optional=True),Slot("slot", (48, 1248, 192, 192), "xy", "the square box below them at the left",- "a square item slot frame with an empty centre"),+ "a square item slot frame with an empty centre", optional=True),Slot("badge", (288, 1248, 176, 112), "xy", "the small wide box to its right",- "a small counter plate with an empty centre"),+ "a small counter plate with an empty centre", optional=True),Slot("pip_on", (512, 1248, 96, 96), "none", "the small circle to the right of that",- "a small round indicator dot, lit", content=False, round=True),+ "a small round indicator dot, lit", content=False, round=True, optional=True),Slot("pip_off", (512, 1392, 96, 96), "none", "the small circle below it",- "the same dot unlit", content=False, round=True),+ "the same dot unlit", content=False, round=True, optional=True),Slot("joystick_base", (704, 1024, 272, 272), "none", "the large circle at the right of the band",- "a round touch joystick base", content=False, round=True),+ "a round touch joystick base", content=False, round=True, optional=True),Slot("joystick_knob", (768, 1344, 144, 144), "none", "the smaller circle below it",- "the joystick's round knob", content=False, round=True),+ "the joystick's round knob", content=False, round=True, optional=True),)FRAME_COUNT = 7# Sheet shape -> (the size the layout's boxes are given at, the slots it holds). The 2:3 sheet keeps the@@ -128,6 +148,11 @@ def _rect(x: int, y: int, w: int, h: int) -> dict[str, int]:return {"x": int(x), "y": int(y), "w": int(w), "h": int(h)}+def _element_png(name: str) -> str:+ """The file name of an element's PNG in the output directory."""+ return f"{name}.png"++def _places(slots: tuple[Slot, ...]) -> str:return "; ".join(f"in {slot.where}, {slot.what}" for slot in slots)@@ -338,6 +363,75 @@ def _parts(mask: Any) -> list[dict[str, Any]]:return parts+def _assign(parts: list[dict[str, Any]], scaled: dict[str, tuple[float, float, float, float]],+ reach: tuple[float, float]) -> tuple[dict[str, list[dict[str, Any]]], list[dict[str, Any]]]:+ """Each part to the box, widened by ``reach`` along x and y, that holds its centroid (the first in layout+ order): the parts by box, and the parts in no box."""+ assigned: dict[str, list[dict[str, Any]]] = {name: [] for name in scaled}+ loose = []+ rx, ry = reach+ for part in parts:+ cx, cy = part["centroid"]+ owner = next((name for name, (x, y, w, h) in scaled.items()+ if x - rx <= cx < x + w + rx and y - ry <= cy < y + h + ry), None)+ (assigned[owner] if owner is not None else loose).append(part)+ return assigned, loose+++def _fit(assigned: dict[str, list[dict[str, Any]]],+ scaled: dict[str, tuple[float, float, float, float]]) -> tuple[tuple[float, float], ...] | None:+ """The scale and offset along x and y that move the layout's box centres closest (least squares) to the+ centres of what each box holds; None from fewer than FIT_MIN_BOXES boxes that hold parts."""+ centres, drawn = [], []+ for name, parts in assigned.items():+ if parts:+ x, y, w, h = scaled[name]+ x0, y0 = min(part["bbox"][0] for part in parts), min(part["bbox"][1] for part in parts)+ x1, y1 = max(part["bbox"][2] for part in parts), max(part["bbox"][3] for part in parts)+ centres.append((x + w / 2, y + h / 2))+ drawn.append(((x0 + x1) / 2, (y0 + y1) / 2))+ if len(centres) < FIT_MIN_BOXES:+ return None+ centres_array, drawn_array = np.asarray(centres), np.asarray(drawn)+ fit = []+ for axis in (0, 1):+ box, held = centres_array[:, axis], drawn_array[:, axis]+ if np.ptp(box) < 1: # every box centred on one line along this axis: an offset alone+ fit.append((1.0, float(np.mean(held - box))))+ else:+ scale, offset = np.polyfit(box, held, 1)+ fit.append((float(scale), float(offset)))+ return tuple(fit)+++def _fit_layout(parts: list[dict[str, Any]], scaled: dict[str, tuple[float, float, float, float]], reach: float,+ assigned: dict[str, list[dict[str, Any]]], required: set[str]) -> tuple[Any, ...] | None:+ """Fit the layout to a drawing that drifted from it (docs/ui-kit.md "Split the sheet"). Fit the boxes to what+ they hold, assign the parts to the fitted boxes, and again, until the assignment repeats. Returns the fit,+ the fitted boxes, and their assignment and loose parts; None unless the fitted boxes leave fewer ``required``+ boxes empty than the layout's own boxes did, or as many and fewer boxes in all."""++ def empty(held: dict[str, list[dict[str, Any]]]) -> tuple[int, int]:+ return sum(not held[name] for name in required), sum(not parts for parts in held.values())++ current, found = assigned, None+ for _ in range(FIT_ROUNDS):+ fit = _fit(current, scaled)+ if fit is None or min(fit[0][0], fit[1][0]) <= 0:+ break+ (sx, tx), (sy, ty) = fit+ moved = {name: (x * sx + tx, y * sy + ty, w * sx, h * sy) for name, (x, y, w, h) in scaled.items()}+ following, loose = _assign(parts, moved, (reach * sx, reach * sy))+ found = (fit, moved, following, loose)+ repeated = all(list(map(id, following[name])) == list(map(id, current[name])) for name in scaled)+ current = following+ if repeated:+ break+ if found is None or empty(found[2]) >= empty(assigned):+ return None+ return found++def split_ui_kit(image: Image.Image, *, alpha_floor: int = 64,alpha_edge: int = 2) -> tuple[dict[str, Image.Image], dict[str, Any]]:"""Cut ``image`` along the layout: element images by name, and the report as written to its default@@ -349,29 +443,33 @@ def split_ui_kit(image: Image.Image, *, alpha_floor: int = 64,if alpha_floor:rgba, cleanup = clear_haze(rgba, floor=alpha_floor, edge=alpha_edge)pixels = np.asarray(rgba)- scaled = boxes((width, height))+ scaled: dict[str, tuple[float, float, float, float]] = dict(boxes((width, height)))reach = GAP / 2 * width / REFERENCE- assigned: dict[str, list[dict[str, Any]]] = {name: [] for name in scaled}- dropped, unassigned, reasons = 0, [], []- for part in _parts(pixels[..., 3] > 0):- if part["pixels"] < MIN_PART:- dropped += 1- continue- cx, cy = part["centroid"]- owner = next((name for name, (x, y, w, h) in scaled.items()- if x - reach <= cx < x + w + reach and y - reach <= cy < y + h + reach), None)- if owner is None:- x0, y0, x1, y1 = part["bbox"]- unassigned.append({"rect": _rect(x0, y0, x1 - x0, y1 - y0), "pixels": part["pixels"]})- reasons.append(f"a part of {part['pixels']} pixels at ({x0}, {y0}) lies in no box")- continue- assigned[owner].append(part)+ every = _parts(pixels[..., 3] > 0)+ kept = [part for part in every if part["pixels"] >= MIN_PART]+ dropped = len(every) - len(kept)+ assigned, loose = _assign(kept, scaled, (reach, reach))+ required = {slot.name for slot in slots if not slot.optional}+ fitted = (_fit_layout(kept, scaled, reach, assigned, required) if any(not held for held in assigned.values())+ else None)+ if fitted is not None:+ fit, scaled, assigned, loose = fitted+ unassigned, reasons = [], []+ for part in loose:+ x0, y0, x1, y1 = part["bbox"]+ unassigned.append({"rect": _rect(x0, y0, x1 - x0, y1 - y0), "pixels": part["pixels"]})+ reasons.append(f"a part of {part['pixels']} pixels at ({x0}, {y0}) lies in no box")+ missing = [slot.name for slot in slots if not assigned[slot.name]]+ refused = [name for name in missing if name in required]+ if refused:+ holds = "its box holds" if len(refused) == 1 else "their boxes hold"+ raise ValueError(f"{', '.join(refused)}: {holds} no element; generate the sheet again")elements: dict[str, Image.Image] = {}records: dict[str, Any] = {}for slot in slots:parts = assigned[slot.name]if not parts:- raise ValueError(f"{slot.name}: its box holds no element; generate the sheet again")+ continuex0 = min(part["bbox"][0] for part in parts)y0 = min(part["bbox"][1] for part in parts)x1 = max(part["bbox"][2] for part in parts)@@ -387,8 +485,8 @@ def split_ui_kit(image: Image.Image, *, alpha_floor: int = 64,reasons += [f"{slot.name}: {note}" for note in inset_notes + padding_notes + round_notes]elements[slot.name] = elementrecords[slot.name] = {- "file": f"{slot.name}.png",- "box": _rect(*scaled[slot.name]),+ "file": _element_png(slot.name),+ "box": _rect(*(round(value) for value in scaled[slot.name])),"rect": _rect(x0, y0, x1 - x0, y1 - y0),"size": {"w": x1 - x0, "h": y1 - y0},"stretch": slot.stretch,@@ -397,10 +495,10 @@ def split_ui_kit(image: Image.Image, *, alpha_floor: int = 64,"parts": len(parts),}for slot in slots:- if slot.inside is not None:+ if slot.inside is not None and slot.name in records:records[slot.name]["inside"], note = fit_inside(records[slot.name], records[slot.inside], slot.inside)reasons += [f"{slot.name}: {note}"] if note else []- report = {+ report: dict[str, Any] = {"kind": REPORT_KIND,"version": 1,"sheet_size": [width, height],@@ -409,8 +507,16 @@ def split_ui_kit(image: Image.Image, *, alpha_floor: int = 64,"alpha_cleanup": cleanup,"dropped_parts": dropped,"unassigned": unassigned,- "elements": records,}+ # a layout with optional elements always says which are missing; a square sheet's elements are all required+ if any(slot.optional for slot in slots):+ report["missing"] = missing+ if fitted is not None:+ (sx, tx), (sy, ty) = fit+ # `+ 0.0`: an offset that rounds to zero is written 0.0, never -0.0+ report["layout_fit"] = {"scale": {"x": round(sx, 4), "y": round(sy, 4)},+ "offset": {"x": round(tx, 1) + 0.0, "y": round(ty, 1) + 0.0}}+ report["elements"] = recordsreturn elements, report@@ -443,6 +549,152 @@ def element_path(report: Path, file: str) -> Path:return Path(report).parent / file+def _taken(out_dir: Path) -> str | None:+ """What keeps a kit out of ``out_dir``, said of it, or None when it is absent or an empty directory."""+ if not os.path.lexists(out_dir):+ return None+ if not out_dir.is_dir():+ return "is a file"+ with os.scandir(out_dir) as entries:+ held = sorted(entry.name for entry in entries)+ if not held:+ return None+ return f"holds {held[0]}" + (f" and {len(held) - 1} more" if len(held) > 1 else "")+++def _make_new(path: Path, make: Callable[[Path], object], remove: Callable[[Path], object],+ made: list[tuple[Callable[[Path], object], Path]]) -> None:+ """``make(path)`` for a path that must be new. ``(remove, path)`` goes on ``made`` just before the call, so that a+ run interrupted right after it still removes what it made, and comes back off when the path existed: what another+ process made is not this run's to remove."""+ made.append((remove, path))+ try:+ make(path)+ except FileExistsError:+ made.pop()+ raise+++def _make_dirs(directory: Path, made: list[tuple[Callable[[Path], object], Path]]) -> None:+ """Create ``directory`` and its missing parents, putting each one this run creates on ``made`` (`_make_new`)."""+ missing = []+ while not os.path.lexists(directory):+ missing.append(directory)+ directory = directory.parent+ for path in reversed(missing):+ try:+ _make_new(path, os.mkdir, os.rmdir, made) # removed only while empty: never what another process put there+ except FileExistsError:+ continue # another process made it+++def _write_new(path: Path, data: bytes) -> None:+ fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_BINARY", 0), 0o666)+ with os.fdopen(fd, "wb") as handle:+ handle.write(data)+ handle.flush()+ os.fsync(handle.fileno())+++def _linked(report: Path, temp: Path) -> bool:+ """Whether ``report`` is this run's ``temp`` file under its own name. When that cannot be read and the report+ exists, it may be."""+ try:+ return os.path.samestat(os.lstat(report), os.lstat(temp))+ except OSError:+ return os.path.lexists(report)+++def _rename_in(staging: Path, out_dir: Path, given_empty: bool) -> None:+ """Give ``staging`` the name ``out_dir``, removing an empty ``out_dir`` first where a rename cannot take its name.+ A ValueError when another run's kit took the name first. Its try statement is kept out of `_write_kit`'s, which+ holds none (see there)."""+ try:+ if given_empty and not RENAME_ONTO_EMPTY_DIR:+ os.rmdir(out_dir)+ os.rename(staging, out_dir)+ except OSError as exc:+ taken = os.path.lexists(staging) and _taken(out_dir) # only when the rename did not happen+ if taken:+ raise ValueError(f"--out-dir {out_dir} was filled while this kit was cut: it {taken}; "+ "nothing was written") from exc+ raise+++def _link_report(temp: Path, report: Path) -> None:+ """Give the finished ``temp`` its own name, ``report``; a ValueError when another run's report took it first.+ Its try statement is kept out of `_write_kit`'s, as `_rename_in`'s is."""+ try:+ os.link(temp, report)+ except FileExistsError as exc:+ raise ValueError(f"--report {report} appeared while this kit was cut; nothing was written") from exc+++def _write_kit(out_dir: Path, files: dict[str, bytes], report: Path | None, report_data: bytes) -> None:+ """Publish a kit whole into ``out_dir``, absent or empty. ``files`` (paths inside it) are written into a hidden+ staging directory beside it, which then takes its name with one rename. A ``report`` outside it is written to a+ hidden temp file beside it and linked to its own name after the rename; the link fails when that name exists, so+ no run replaces another's report.++ One step publishes the kit: the rename, or with a report outside, the link. Before it, a run that fails or is+ interrupted removes everything it made (the kit it renamed in, the directories it created, its staging directory+ and temp file) and puts back an empty out-dir it was given; from it on, it removes nothing but its temp file.++ Python can raise an interrupt at any instruction: a signal's handler, or a tracer's, runs between any two. So the+ one ``except`` below covers every instruction from the first name the run creates to the end of the publish, and+ no try statement is nested in its own: a nested ``try:`` line compiles to an instruction that no handler covers,+ so an exception raised there would leave without the clean-up. The rename's and the link's own try statements are+ in `_rename_in` and `_link_report`, whose exceptions reach this handler at their call. No step is recorded after+ its call: ``renaming`` and ``linking`` are set before theirs and the filesystem says whether it happened, and+ each name the run creates goes on ``made`` before the call that creates it.++ A killed run, or one interrupted again while it removes what it made, leaves no part of a kit under the out-dir's+ name: at most its hidden staging directory or temp file beside them and the directories it created, or, stopped+ between the rename and the link, the whole kit without its report."""+ given_empty = out_dir.is_dir()+ tag = secrets.token_hex(6)+ staging = out_dir.parent / f".{out_dir.name}.ui-kit-{tag}"+ temp = None if report is None else report.parent / f".{report.name}.{tag}.tmp"+ made: list[tuple[Callable[[Path], object], Path]] = []+ renaming = linking = False+ try:+ _make_dirs(out_dir.parent, made)+ _make_new(staging, os.mkdir, lambda path: shutil.rmtree(path, ignore_errors=True), made)+ for name, data in files.items():+ target = staging / name+ if target.parent != staging: # a report in a directory of its own inside the out-dir+ target.parent.mkdir(parents=True, exist_ok=True)+ _write_new(target, data)+ if temp is not None:+ _make_dirs(temp.parent, made)+ _make_new(temp, lambda path: _write_new(path, report_data), os.unlink, made)+ renaming = True+ _rename_in(staging, out_dir, given_empty)+ if temp is not None:+ linking = True+ _link_report(temp, report)+ with contextlib.suppress(OSError):+ os.unlink(temp) # published: the temp is a second name of the report+ except BaseException:+ renamed = renaming and not os.path.lexists(staging) # the staging directory took the out-dir's name+ published = renamed if temp is None else linking and _linked(report, temp)+ if published:+ if temp is not None:+ with contextlib.suppress(OSError):+ os.unlink(temp)+ raise+ if renamed:+ with contextlib.suppress(OSError):+ os.rename(out_dir, staging)+ if given_empty and not os.path.lexists(out_dir):+ with contextlib.suppress(OSError):+ os.mkdir(out_dir)+ for remove, path in reversed(made):+ with contextlib.suppress(OSError):+ remove(path)+ raise++def _publish(*, sheet: Path, out_dir: Path, alpha_floor: int = 64, alpha_edge: int = 2,report: Path | None = None) -> int:sheet = Path(sheet).expanduser().resolve()@@ -454,6 +706,12 @@ def _publish(*, sheet: Path, out_dir: Path, alpha_floor: int = 64, alpha_edge: iraise ValueError("the output directory must not hold the sheet; choose a new directory")if report_path.suffix.lower() != ".json":raise ValueError("--report must be a .json path")+ taken = _taken(out_dir)+ if taken:+ raise ValueError(f"--out-dir {out_dir} {taken}; a kit is written whole into a new or empty directory")+ inside = report_path.is_relative_to(out_dir)+ if not inside and os.path.lexists(report_path):+ raise ValueError(f"--report {report_path} already exists; a report outside --out-dir is written to a new path")with Image.open(sheet) as image:if image.format != "PNG" or getattr(image, "n_frames", 1) != 1:raise ValueError("--sheet must be a single-frame PNG")@@ -463,37 +721,34 @@ def _publish(*, sheet: Path, out_dir: Path, alpha_floor: int = 64, alpha_edge: i# wherever --report puts the report, each `file` leads from it to the PNG written in out_dirwritten["elements"] = {name: {**record, "file": report_file(report_path, out_dir / record["file"])}for name, record in measured["elements"].items()}- payloads: dict[Path, bytes | str] = {}+ files: dict[str, bytes] = {}for name, element in elements.items():png = io.BytesIO()element.save(png, format="PNG")- payloads[out_dir / measured["elements"][name]["file"]] = png.getvalue()- payloads[report_path] = json.dumps(written, indent=2, allow_nan=False) + "\n"- locked = []- try:- for directory in sorted({out_dir, report_path.parent}):- directory.mkdir(parents=True, exist_ok=True)- acquire_run_dir_lock(directory, "ui-kit")- locked.append(directory)- atomic_write_set(payloads)- finally:- for directory in reversed(locked):- release_run_dir_lock(directory)- print(f"ui-kit: {written['status']} — {len(elements)} elements in {out_dir} (report: {report_path})")+ files[measured["elements"][name]["file"]] = png.getvalue()+ report_data = (json.dumps(written, indent=2, allow_nan=False) + "\n").encode("utf-8")+ if inside:+ files[report_path.relative_to(out_dir).as_posix()] = report_data+ _write_kit(out_dir, files, None if inside else report_path, report_data)+ missing = written.get("missing") or []+ left_out = f"; missing, left out of the kit: {', '.join(missing)}" if missing else ""+ print(f"ui-kit: {written['status']} — {len(elements)} elements in {out_dir} (report: {report_path}){left_out}")return 0def add_arguments(parser: argparse.ArgumentParser) -> None:parser.add_argument("--sheet", required=True, type=Path,- help="transparent square PNG drawn with `gen --layout-guide ui-kit`")+ help="transparent square or 2:3 PNG drawn with `gen --layout-guide ui-kit`")parser.add_argument("--out-dir", required=True, type=Path,- help="directory for <element>.png and ui-kit.json; must not hold the sheet")+ help="a new or empty directory for <element>.png and ui-kit.json; "+ "one that holds anything is refused")parser.add_argument("--alpha-floor", type=int, default=64,help="alpha haze cleanup floor, 1..255 (0 turns the cleanup off)")parser.add_argument("--alpha-edge", type=int, default=2,help="faint pixels this close to a solid pixel are its edge and are kept")parser.add_argument("--report", type=Path,- help="JSON report (default: <out-dir>/ui-kit.json); its element paths are relative to it")+ help="JSON report (default: <out-dir>/ui-kit.json), a new path when outside --out-dir; "+ "its element paths are relative to it")def run(**kwargs: Any) -> int:diff --git a/sprite_gen/gen/chroma.py b/sprite_gen/gen/chroma.pyindex fb3f971..b0351dc 100644--- a/sprite_gen/gen/chroma.py+++ b/sprite_gen/gen/chroma.py@@ -10,7 +10,8 @@No silent success on either path: an output with no measurable transparent area,no alpha channel at all, or transparent pixels that retain RGB fails before any-output is published.+output is published. A key background painted as a transparency checkerboard+(`painted_checkerboard`) is refused before it is keyed, with its own reason."""from __future__ import annotations@@ -21,6 +22,7 @@ from typing import Anyfrom PIL import Image+from sprite_gen._deps import npfrom sprite_gen.frames.extract import remove_chroma_background_ycbcrfrom sprite_gen.spec.runio import atomic_save_image@@ -121,6 +123,66 @@ def alpha_verdict(alpha: Image.Image) -> dict[str, Any]:"border_alpha_zero_pct": round(border_alpha_zero_pct, 2)}+# A painted transparency checkerboard (`painted_checkerboard`): the grey and white squares an editor shows+# behind transparent pixels, painted where a key background was asked for; the matte would key nearly the whole+# image away. Each edge is read on its CHECKER_LINES nearest lines; a line is a checkerboard row when nearly+# all of it is grey, it holds two greys at least CHECKER_STEP apart, and it alternates between them at least+# CHECKER_MIN_RUNS times in runs of one length (most within a quarter of their median, which lies in+# CHECKER_SQUARE).+CHECKER_LINES = 8+CHECKER_GREY = 24+CHECKER_GREY_SHARE = 0.9+CHECKER_STEP = 12+CHECKER_MIN_RUNS = 6+CHECKER_SQUARE = (4, 128)+CHECKER_REGULAR = 0.75+++def _checker_square(line: Any) -> int | None:+ """The square size of a checkerboard row along ``line`` (pixels x RGB), or None when it is not one."""+ if ((line.max(axis=-1) - line.min(axis=-1)) <= CHECKER_GREY).mean() < CHECKER_GREY_SHARE:+ return None+ luma = line.mean(axis=-1)+ low, high = np.percentile(luma, (10, 90))+ if high - low < CHECKER_STEP:+ return None+ runs = np.diff(np.flatnonzero(np.diff((luma > (low + high) / 2).astype(np.int8))))+ if len(runs) < CHECKER_MIN_RUNS:+ return None+ median = float(np.median(runs))+ if not CHECKER_SQUARE[0] <= median <= CHECKER_SQUARE[1]:+ return None+ if (np.abs(runs - median) <= max(2.0, median / 4)).mean() < CHECKER_REGULAR:+ return None+ return round(median)+++def painted_checkerboard(image: Image.Image) -> dict[str, Any] | None:+ """Whether ``image``'s background is a painted transparency checkerboard: ``{"edges", "square_px"}`` or None.++ An edge shows the checkerboard when one of its CHECKER_LINES nearest lines is a checkerboard row+ (`_checker_square`). A checkerboard alternates along both axes, so the image is one when the top or the bottom+ edge and the left or the right edge show it; stripes alternate along one axis only. `square_px` is the median+ square size of the edges that show it. A key background is not grey, and a subject drawn inside it does not+ reach the edges."""+ rgb = np.asarray(image.convert("RGB")).astype(np.int16)+ columns = rgb.transpose(1, 0, 2)+ lines = {"top": rgb[:CHECKER_LINES], "bottom": rgb[::-1][:CHECKER_LINES],+ "left": columns[:CHECKER_LINES], "right": columns[::-1][:CHECKER_LINES]}+ squares = {}+ for edge, band in lines.items():+ found = next((square for square in map(_checker_square, band) if square is not None), None)+ if found is not None:+ squares[edge] = found+ if not ({"top", "bottom"} & set(squares) and {"left", "right"} & set(squares)):+ return None+ return {"edges": list(squares), "square_px": round(float(np.median(list(squares.values()))))}+++def _and_list(items: list[str]) -> str:+ return items[0] if len(items) == 1 else f"{', '.join(items[:-1])} and {items[-1]}"++def write_white_check(image: Image.Image, path: Path) -> None:bg = Image.new("RGBA", image.size, (255, 255, 255, 255))bg.alpha_composite(image)@@ -141,11 +203,21 @@ def key_transparent(`decontam` is the edge decontamination pass after the matte, reported under`decontam`: "off" (the default) publishes the matte as it is, "auto" runs it whereit applies, "palette" demands it. Raises SystemExit before publishing if no- measurable transparent area was made, or if a transparent pixel keeps non-zero RGB.+ measurable transparent area was made, or if a transparent pixel keeps non-zero RGB, and+ before keying if the background is a painted transparency checkerboard (`painted_checkerboard`)."""if key not in KEYS:raise SystemExit(f"chroma: unknown key {key!r}; expected one of {sorted(KEYS)}")source = Image.open(input_path).convert("RGBA")+ # The matte reads its key off the borders: on a painted checkerboard it reads the checkerboard and keys the+ # whole image away, so the image is refused before keying and the caller generates it again.+ checker = painted_checkerboard(source)+ if checker is not None:+ raise SystemExit(+ f"chroma: the background is a painted transparency checkerboard ({checker['square_px']} px squares "+ f"along the {_and_list(checker['edges'])} edges), not the {key} key the image was asked for; keying it "+ "would erase the image — generate it again"+ )source_pixels = source.load()warnings: list[str] = []decontam_stats: dict[str, Any] = {}diff --git a/tests/frames/test_ui_kit.py b/tests/frames/test_ui_kit.pyindex 0842e79..ea69570 100644--- a/tests/frames/test_ui_kit.py+++ b/tests/frames/test_ui_kit.py@@ -13,11 +13,34 @@ plate with corner ornaments, two pips and a joystick base and knob drawn as discits bar frame's content area exactly, in the report and in the pack; round parts never stretch.A square sheet's report, element pixels and packs are frozen from the splitter before the tallsheet existed.++The seven frames are the kit: an empty frame box refuses the sheet. The band's elements are+optional: an empty band box leaves that element out of the report and the pack and names it under+`missing`. A sheet drawn a few percent shorter than the guide, so that the lower elements'+centres lie in the boxes above theirs, is fitted to the drawing before its parts are assigned.++A kit is written whole into a new or empty directory: one that holds anything is refused and left as+it was. The kit is published at one step, the rename that gives it the out-dir's name or, with the+report outside, the link that gives the report its name. A failure, an interrupt or a kill just+before or just after any filesystem step of the publish leaves nothing before that step and the whole+kit from it on; an interrupt of any kind at any line or instruction of the publish leaves nothing or+the whole kit; and a run that another run's kit or report reaches first takes its own back out."""+import contextlib+import copy+import errnoimport hashlib+import ioimport jsonimport math+import os+import re+import shutil+import signal+import sys+from collections import Counter+from pathlib import Pathimport numpy as npimport pytest@@ -102,12 +125,17 @@ PLAN = {"panel": dict(k=18, flourish=60), "button": dict(k=12), "button_pressed""joystick_knob": dict(color=KNOB)}-def synthetic_sheet(*, size=(SIZE, SIZE), haze=True, noise=True, stray=False, missing=None, crest=False):+def synthetic_sheet(*, size=(SIZE, SIZE), haze=True, noise=True, stray=False, missing=(), crest=False,+ squeeze=1.0):+ """The sheet, and where each element was drawn. `missing` names the boxes left empty; `squeeze` draws+ the layout that much shorter, from the top edge down, as image models draw it."""+ missing = {missing} if isinstance(missing, str) else set(missing)pixels = np.zeros((size[1], size[0], 4), dtype=np.uint8)drawn = {}for name, (bx, by, bw, bh) in ui_kit.boxes(size).items():- if name == missing:+ if name in missing:continue+ by, bh = round(by * squeeze), round(bh * squeeze)x, y, w, h = bx + 4, by + 4, bw - 8, bh - 8params = PLAN[name]if name.endswith("bar_frame"):@@ -281,7 +309,7 @@ def test_a_large_part_outside_every_box_is_reported():def test_an_empty_box_fails():image, _ = synthetic_sheet(missing="button_pressed")- with pytest.raises(ValueError, match="button_pressed"):+ with pytest.raises(ValueError, match="^button_pressed: its box holds no element; generate the sheet again$"):ui_kit.split_ui_kit(image)@@ -303,6 +331,8 @@ def test_cli_writes_element_pngs_and_a_report_the_pack_reads(tmp_path):assert report["kind"] == "sprite-gen-ui-kit" and report["version"] == 1assert report["sheet"] == str(sheet.resolve()) and report["sheet_size"] == [SIZE, SIZE]assert list(report["elements"]) == FRAMES+ # every element of a square sheet is required, so its report has no `missing`, as before the 2:3 sheet+ assert "missing" not in report and "layout_fit" not in reportassert sorted(p.name for p in out.iterdir()) == sorted([f"{name}.png" for name in FRAMES] + ["ui-kit.json"])cleaned, _ = ui_kit.clear_haze(image.convert("RGBA"), floor=64, edge=2)for name, entry in report["elements"].items():@@ -453,6 +483,8 @@ def test_tall_sheet_cuts_every_element_of_the_whole_kit():assert report["sheet_size"] == list(TALL)assert list(report["elements"]) == list(elements) == FRAMES + BANDassert report["unassigned"] == [] and report["dropped_parts"] == 0+ # nothing is missing, and every box held its element, so the layout was not fitted+ assert report["missing"] == [] and "layout_fit" not in reportfor name in FRAMES + BAND:entry = report["elements"][name]assert entry["file"] == f"{name}.png" and entry["parts"] == 1@@ -519,12 +551,570 @@ def test_slot_and_badge_insets_cover_their_corner_ornaments_and_padding_keeps_coassert edge + k <= entry["padding"][side] <= edge + k + 4, (name, side, entry["padding"])-def test_an_empty_box_of_the_band_fails():- image, _ = synthetic_sheet(size=TALL, missing="joystick_knob")- with pytest.raises(ValueError, match="joystick_knob"):+def test_the_frames_are_required_and_the_band_is_optional():+ assert [slot.name for slot in ui_kit.LAYOUT if not slot.optional] == FRAMES+ assert [slot.name for slot in ui_kit.LAYOUT if slot.optional] == BAND++[email protected]("missing", ["joystick_knob", "pip_off", "xp_bar_fill", ("slot", "badge"), tuple(BAND)])+def test_an_empty_box_of_the_band_leaves_that_element_out_of_the_kit(missing):+ gone = [missing] if isinstance(missing, str) else list(missing)+ image, drawn = synthetic_sheet(size=TALL, missing=missing)+ elements, report = ui_kit.split_ui_kit(image)+ kept = [name for name in FRAMES + BAND if name not in gone]+ assert report["missing"] == gone+ assert list(report["elements"]) == list(elements) == kept+ # a missing element is not a measurement to review: the elements that are there are measured as ever+ assert report["status"] == "pass", report["review_reasons"]+ assert "layout_fit" not in report+ for name in kept:+ assert all(0 <= value <= 2 for value in offset(report, drawn, name)), name++[email protected]("name", FRAMES)+def test_an_empty_frame_box_of_the_tall_sheet_still_refuses_the_sheet(name):+ image, _ = synthetic_sheet(size=TALL, missing=name)+ with pytest.raises(ValueError, match=f"^{name}: its box holds no element; generate the sheet again$"):+ ui_kit.split_ui_kit(image)+++def test_every_empty_frame_box_is_named_and_an_empty_band_box_is_not():+ image, _ = synthetic_sheet(size=TALL, missing=("panel", "card", "pip_on"))+ with pytest.raises(ValueError, match="^panel, card: their boxes hold no element; generate the sheet again$"):ui_kit.split_ui_kit(image)+SQUEEZE = 0.93+++def test_a_sheet_drawn_shorter_than_the_guide_is_fitted_before_its_parts_are_assigned():+ # Drawn 7 % shorter from the top edge down, the lower pip's and the lower fill's centres lie in the+ # widened boxes above theirs (half the gap, 12 px here): assigned by the layout's own boxes, three boxes+ # would be empty (badge, pip_off, joystick_knob), two would hold two elements each, and the upper fill+ # would lie in no box.+ image, drawn = synthetic_sheet(size=TALL, squeeze=SQUEEZE)+ boxes, reach = ui_kit.boxes(TALL), 12+ for name, above in (("pip_off", "pip_on"), ("xp_bar_fill", "hp_bar_fill")):+ _, y, _, h = drawn[name]+ _, ay, _, ah = boxes[above]+ assert ay - reach <= y + h / 2 < ay + ah + reach, name+ elements, report = ui_kit.split_ui_kit(image)+ assert report["missing"] == [] and report["unassigned"] == []+ assert list(elements) == FRAMES + BAND+ for name in FRAMES + BAND:+ entry = report["elements"][name]+ assert entry["parts"] == 1, name+ assert all(0 <= value <= 2 for value in offset(report, drawn, name)), name+ # each element's box is its layout box moved onto the drawing, and the drawn element lies inside it+ x, y, w, h = drawn[name]+ box = entry["box"]+ assert box["x"] - 2 <= x and x + w <= box["x"] + box["w"] + 2, name+ assert box["y"] - 2 <= y and y + h <= box["y"] + box["h"] + 2, name+ fit = report["layout_fit"]+ assert set(fit) == {"scale", "offset"}+ assert abs(fit["scale"]["x"] - 1) < 0.005 and abs(fit["offset"]["x"]) < 2+ assert abs(fit["scale"]["y"] - SQUEEZE) < 0.005 and abs(fit["offset"]["y"]) < 3+++def test_a_squeezed_sheet_with_an_empty_band_box_is_fitted_and_names_it():+ image, drawn = synthetic_sheet(size=TALL, squeeze=SQUEEZE, missing="joystick_knob")+ elements, report = ui_kit.split_ui_kit(image)+ assert report["missing"] == ["joystick_knob"] and "layout_fit" in report+ assert list(elements) == [name for name in FRAMES + BAND if name != "joystick_knob"]+ assert all(report["elements"][name]["parts"] == 1 for name in elements)++[email protected]("name", FRAMES)+def test_a_squeezed_sheet_with_an_empty_frame_box_still_refuses_it(name):+ # fitting the layout to the drawing never fills an empty frame's box with a neighbour: the sheet is refused+ # by that frame's own name+ image, _ = synthetic_sheet(size=TALL, squeeze=SQUEEZE, missing=name)+ with pytest.raises(ValueError, match=f"^{name}: its box holds no element; generate the sheet again$"):+ ui_kit.split_ui_kit(image)+++def test_the_cli_names_the_missing_elements_and_writes_no_png_for_them(tmp_path, capsys):+ image, _ = synthetic_sheet(size=TALL, missing=("pip_off", "joystick_knob"))+ sheet = tmp_path / "uikit.png"+ image.save(sheet)+ out = tmp_path / "ui"+ assert ui_kit.main(["--sheet", str(sheet), "--out-dir", str(out)]) == 0+ report = json.loads((out / "ui-kit.json").read_text())+ assert report["missing"] == ["pip_off", "joystick_knob"]+ kept = [name for name in FRAMES + BAND if name not in report["missing"]]+ assert sorted(p.name for p in out.iterdir()) == sorted([f"{name}.png" for name in kept] + ["ui-kit.json"])+ assert capsys.readouterr().out.rstrip().endswith("; missing, left out of the kit: pip_off, joystick_knob")+++def tree(root):+ """The visible files (by their bytes) and directories (None) under ``root``, and the hidden entries apart:+ each by its path, not what it holds."""+ visible, hidden = {}, []+ for path in sorted(root.rglob("*")):+ rel = path.relative_to(root)+ if any(part.startswith(".") for part in rel.parts):+ if not any(part.startswith(".") for part in rel.parts[:-1]):+ hidden.append(rel.as_posix())+ continue+ visible[rel.as_posix()] = path.read_bytes() if path.is_file() else None+ return visible, hidden+++def test_a_kit_is_written_into_a_new_or_empty_out_dir_and_one_that_holds_anything_is_refused(tmp_path):+ # A rerun into the directory an earlier kit filled, with another sheet, is refused by the directory's name and+ # leaves it byte for byte as it was, as does any other file in it, a hidden one too, or a file at its path. An+ # empty directory takes a kit, a refused sheet writes nothing, and a --report outside --out-dir must be new.+ sheet, out = tmp_path / "uikit.png", tmp_path / "ui"++ def run(out_dir, size=TALL, missing=(), report=None):+ synthetic_sheet(size=size, missing=missing)[0].save(sheet)+ return ui_kit.main(["--sheet", str(sheet), "--out-dir", str(out_dir)]+ + (["--report", str(report)] if report else []))++ def refused(out_dir, held):+ return (rf"^ui-kit: --out-dir {re.escape(str(out_dir.resolve()))} {held}; "+ "a kit is written whole into a new or empty directory$")++ assert run(out) == 0+ kit = tree(out)+ for size, missing in ((TALL, "pip_off"), ((SIZE, SIZE), ())):+ with pytest.raises(SystemExit, match=refused(out, "holds badge.png and 15 more")):+ run(out, size, missing)+ assert tree(out) == kit+ for name in ("logo.png", ".hidden"):+ other = tmp_path / f"other{name}"+ other.mkdir()+ (other / name).write_bytes(b"not a kit")+ with pytest.raises(SystemExit, match=refused(other, f"holds {re.escape(name)}")):+ run(other)+ assert tree(other) == (({}, [name]) if name.startswith(".") else ({name: b"not a kit"}, []))+ (tmp_path / "taken").write_bytes(b"a file")+ with pytest.raises(SystemExit, match=refused(tmp_path / "taken", "is a file")):+ run(tmp_path / "taken")+ assert (tmp_path / "taken").read_bytes() == b"a file"+ (tmp_path / "empty").mkdir()+ assert run(tmp_path / "empty", missing="pip_off") == 0+ kept = [name for name in FRAMES + BAND if name != "pip_off"]+ assert sorted(tree(tmp_path / "empty")[0]) == sorted([f"{name}.png" for name in kept] + ["ui-kit.json"])+ with pytest.raises(SystemExit, match="^ui-kit: panel: its box holds no element; generate the sheet again$"):+ run(tmp_path / "new", missing="panel")+ assert not (tmp_path / "new").exists()+ report = tmp_path / "kit.json"+ report.write_text("{}\n")+ with pytest.raises(SystemExit, match=rf"^ui-kit: --report {re.escape(str(report.resolve()))} already exists; "+ "a report outside --out-dir is written to a new path$"):+ run(tmp_path / "elements", report=report)+ assert report.read_text() == "{}\n" and not (tmp_path / "elements").exists()+ # no hidden directory or temp file of a run is left anywhere+ assert [path.name for path in tmp_path.rglob(".*") if path.name != ".hidden"] == []+++# the out-dir and the report (None: in the out-dir) of each placement; the outside one's directories are made by+# the run, so a run that fails must remove them again+PUBLISH_PLACES = {"inside": ("ui", None), "outside": ("kit/elements", "reports/kit.json")}+FS_CALLS = ("open", "fsync", "rename", "replace", "link", "unlink", "rmdir", "mkdir")+KILLED = 97+++class Faults:+ """Every filesystem call the publish makes once the sheet is cut, counted. The k-th one fails once, just before it+ runs or just after it returned: by an OSError (EIO), by a real SIGINT, which Python's own handler raises as+ KeyboardInterrupt, or by ending the process there, as a kill would."""++ def __init__(self, monkeypatch, cut):+ self.armed, self.calls, self.fail_at, self.when, self.mode, self.fired = False, [], None, None, None, False+ for name in FS_CALLS:+ monkeypatch.setattr(os, name, self.wrap(name, getattr(os, name)))++ def split_then_arm(image, **kwargs):+ self.armed = True+ return cut[0], copy.deepcopy(cut[1])++ monkeypatch.setattr(ui_kit, "split_ui_kit", split_then_arm)++ def fail(self, name):+ self.fired = True+ if self.mode == "kill":+ os._exit(KILLED)+ if self.mode == "interrupt":+ signal.raise_signal(signal.SIGINT)+ raise OSError(errno.EIO, f"injected {name} failure")++ def wrap(self, name, call):+ def faulty(*args, **kwargs):+ if not self.armed:+ return call(*args, **kwargs)+ paths = [Path(str(arg)).name for arg in args[:2] if isinstance(arg, (str, os.PathLike))]+ self.calls.append(f"{name}({', '.join(paths)})")+ here = len(self.calls) == self.fail_at+ if here and self.when == "before":+ self.fail(name)+ result = call(*args, **kwargs)+ if here and self.when == "after":+ if name == "open":+ os.close(result) # the run never gets it, so it would stay open in this process+ self.fail(name)+ return result+ return faulty++ def run(self, args, fail_at=None, when=None, mode=None):+ """The command's exit code, its refusal or "KeyboardInterrupt"; a kill runs it in a child process and gives+ the child's code."""+ self.calls, self.fail_at, self.when, self.mode, self.fired = [], fail_at, when, mode, False+ if mode != "kill":+ interrupt = signal.signal(signal.SIGINT, signal.default_int_handler)+ try:+ return ui_kit.main(args)+ except SystemExit as exc:+ return str(exc)+ except KeyboardInterrupt:+ return "KeyboardInterrupt"+ finally:+ self.armed = False+ signal.signal(signal.SIGINT, interrupt)+ pid = os.fork()+ if pid == 0:+ code = 1+ try:+ sys.stdout = sys.stderr = io.StringIO()+ code = ui_kit.main(args)+ finally:+ os._exit(code)+ self.armed = False+ return os.waitstatus_to_exitcode(os.waitpid(pid, 0)[1])+++def files_of(state):+ return {path: data for path, data in state.items() if data is not None}+++# A kill forks the test process, which pytest-xdist runs with threads of its own: the child makes only the publish's+# filesystem calls and leaves by os._exit, and one that hung would end the test by its timeout.[email protected]("ignore:This process .* is multi-threaded, use of fork:DeprecationWarning")[email protected]("mode", ["raise", "interrupt", pytest.param("kill", marks=pytest.mark.skipif(+ not hasattr(os, "fork"), reason="a kill is a child process ended at the fault"))])[email protected]("when", ["before", "after"])[email protected]("start", ["absent", "empty", "empty, removed first"])[email protected]("placement", sorted(PUBLISH_PLACES))+def test_a_failure_an_interrupt_or_a_kill_at_any_step_of_the_publish_leaves_nothing_or_the_whole_kit(+ tmp_path, monkeypatch, placement, start, when, mode):+ # Each filesystem call of the publish fails once, just before it runs or just after it returned, in a copy of the+ # same start. One of those calls publishes the kit: the rename that gives it --out-dir's name or, with the report+ # outside, the link that gives the report its name. An error or an interrupt before that leaves the start exactly,+ # with nothing hidden; from it on, the whole kit, and an interrupt still ends the run. A kill leaves what the run+ # had made: the start, the whole kit or, killed between the rename and the link, the whole --out-dir and no+ # report yet; never part of a kit under the out-dir's name, and nothing hidden but the run's own staging+ # directory or report temp beside them. "removed first" is the Windows rename, which takes no existing+ # directory's name, so an empty --out-dir is removed just before it.+ out_rel, report_rel = PUBLISH_PLACES[placement]+ sheet = tmp_path / "uikit.png"+ image, _ = synthetic_sheet(size=TALL, missing="pip_off")+ image.save(sheet)+ faults = Faults(monkeypatch, ui_kit.split_ui_kit(image))+ if start == "empty, removed first":+ monkeypatch.setattr(ui_kit, "RENAME_ONTO_EMPTY_DIR", False)+ template = tmp_path / "start"+ template.mkdir()+ if start != "absent":+ (template / out_rel).mkdir(parents=True)++ def copy_of_start(name):+ return Path(shutil.copytree(template, tmp_path / name))++ def args(root):+ return (["--sheet", str(sheet), "--out-dir", str(root / out_rel)]+ + (["--report", str(root / report_rel)] if report_rel else []))++ before, _ = tree(template)+ reference = copy_of_start("reference")+ assert faults.run(args(reference)) == 0+ calls = faults.calls+ complete, litter = tree(reference)+ assert litter == []+ report = report_rel or f"{out_rel}/ui-kit.json"+ kit_files = [path for path in files_of(complete) if path != report]+ assert len(kit_files) == 14 and report in complete+ # the sweep reaches each file of the kit, the rename of the out-dir and the report's own commit+ reached = {name for call in calls for name in call[call.index("(") + 1:-1].split(", ")}+ assert {Path(path).name for path in kit_files} | {Path(out_rel).name, Path(report).name} <= reached, calls++ def naming(op, target):+ """The number of the call ``op(…, target)``, which gives ``target`` its name."""+ return next(k for k, call in enumerate(calls, 1) if call.startswith(f"{op}(") and call.endswith(f", {target})"))++ renamed = naming("rename", Path(out_rel).name)+ published = naming("link", Path(report_rel).name) if report_rel else renamed+ without_report = {path: data for path, data in files_of(complete).items() if path != report}+ beside = [f"{Path(out_rel).parent / f'.{Path(out_rel).name}.ui-kit-'}".removeprefix("./")]+ if report_rel:+ beside.append(f"{Path(report_rel).parent / f'.{Path(report_rel).name}.'}".removeprefix("./"))+ for k, call in enumerate(calls, 1):+ root = copy_of_start(f"k{k}")+ outcome = faults.run(args(root), fail_at=k, when=when, mode=mode)+ after, hidden = tree(root)+ where = (k, when, call, outcome, sorted(after), hidden)++ def ran(step):+ return step < k or (step == k and when == "after")++ assert all(any(entry.startswith(prefix) for prefix in beside) for entry in hidden), where+ if mode == "kill":+ assert outcome == KILLED, where+ left = complete if ran(published) else without_report if ran(renamed) else before+ assert files_of(after) == files_of(left), where+ directories = {path for path, data in after.items() if data is None}+ kept = {path for path, data in before.items() if data is None}+ if start == "empty, removed first":+ kept.discard(out_rel)+ assert kept <= directories <= kept | {path for path, data in complete.items() if data is None}, where+ continue+ assert faults.fired, where+ if mode == "interrupt":+ assert outcome == "KeyboardInterrupt", where+ else:+ assert outcome in (0, f"ui-kit: [Errno {errno.EIO}] injected {call[:call.index('(')]} failure"), where+ if ran(published):+ # hidden: only the report's temp, when removing it after the kit was published is what failed+ assert after == complete and (hidden == [] or (+ report_rel and mode == "raise" and all(entry.startswith(beside[-1]) for entry in hidden))), where+ else:+ assert outcome != 0 and after == before and hidden == [], where+++class Halt(BaseException):+ """An exception of no standard kind."""+++# How each kind of interrupt arrives and what it ends the run with: a real signal through its handler (Python's own+# for SIGINT; for SIGTERM, one that exits, as a service installs), or an exception of no standard kind.+INTERRUPTS = {+ "SIGINT": (signal.SIGINT, signal.default_int_handler, KeyboardInterrupt),+ "SIGTERM": (signal.SIGTERM, lambda signum, frame: sys.exit(128 + signum), SystemExit),+ "BaseException": (None, None, Halt),+}++[email protected]("kind", sorted(INTERRUPTS))[email protected]("placement", sorted(PUBLISH_PLACES))+def test_any_interrupt_from_the_rename_on_leaves_nothing_before_the_kit_is_published_and_the_whole_kit_after(+ tmp_path, placement, kind):+ # Nothing is replaced: a profile hook sees the real filesystem calls of a run on a whole sheet, and the interrupt+ # arrives just before each one from the rename that gives the kit --out-dir's name on, or just after it returned.+ # Before the step that publishes the kit (that rename, or with the report outside, the link that gives the report+ # its name) the run leaves nothing; from it on, the whole kit, its report naming only files that are there.+ out_rel, report_rel = PUBLISH_PLACES[placement]+ sheet = tmp_path / "uikit.png"+ synthetic_sheet(size=TALL)[0].save(sheet)+ signum, handler, ends = INTERRUPTS[kind]+ watched = {id(getattr(os, name)): name for name in FS_CALLS}++ def publish(root, point=None):+ """Run the command into ``root``, interrupted at ``point``: the k-th call and "c_call", just before it, or+ "c_return", just after it returned. Answers the calls the run made, by name, and what ended it."""+ root.mkdir()+ names = []++ def hook(frame, event, arg):+ if event not in ("c_call", "c_return") or id(arg) not in watched:+ return+ if event == "c_call":+ names.append(watched[id(arg)])+ if (len(names), event) == point:+ sys.setprofile(None)+ if signum is None:+ raise Halt+ signal.raise_signal(signum)++ previous = signal.signal(signum, handler) if signum is not None else None+ sys.setprofile(hook)+ try:+ ended = ui_kit.main(["--sheet", str(sheet), "--out-dir", str(root / out_rel)]+ + (["--report", str(root / report_rel)] if report_rel else []))+ except BaseException as exc:+ ended = exc+ finally:+ sys.setprofile(None)+ if signum is not None:+ signal.signal(signum, previous)+ return names, ended++ names, ended = publish(tmp_path / "reference")+ assert ended == 0+ complete = tree(tmp_path / "reference")+ report = tmp_path / "reference" / (report_rel or f"{out_rel}/ui-kit.json")+ elements = json.loads(report.read_text())["elements"]+ out = (tmp_path / "reference" / out_rel).resolve()+ assert len(elements) == 15 and {ui_kit.element_path(report, entry["file"]).resolve()+ for entry in elements.values()} == {out / f"{name}.png" for name in elements}+ assert sorted(path.name for path in out.iterdir()) == sorted(+ [f"{name}.png" for name in elements] + ([] if report_rel else ["ui-kit.json"]))+ renamed = names.index("rename") + 1+ published = names.index("link") + 1 if report_rel else renamed+ for k in range(renamed, len(names) + 1):+ for event in ("c_call", "c_return"):+ root = tmp_path / f"{k}-{event}"+ _, ended = publish(root, (k, event))+ where = (k, names[k - 1], event, repr(ended), tree(root))+ assert isinstance(ended, ends) and (signum != signal.SIGTERM or ended.code == 128 + signum), where+ assert tree(root) == (complete if k > published or (k == published and event == "c_return")+ else ({}, [])), where+++# Interrupted after a file is opened and before its with statement holds it, or as that statement closes it, a run+# leaves the file object to be closed when the run's frames go, which Python reports as an unclosed file.[email protected]("ignore:unclosed file:ResourceWarning")[email protected]("kind", sorted(INTERRUPTS))[email protected]("granularity", ["line", "instruction"])[email protected]("start", ["absent", "empty", "empty, removed first"])[email protected]("placement", sorted(PUBLISH_PLACES))+def test_an_interrupt_at_any_line_or_instruction_of_the_publish_leaves_nothing_or_the_whole_kit(+ tmp_path, monkeypatch, placement, start, granularity, kind):+ # Python may raise an interrupt at any instruction: a signal's handler runs between instructions, and so does a+ # tracer's or a debugger's callback, which can receive the signal or raise its own exception there. A tracer on the+ # publish's own functions raises the interrupt once per run, at one line, or one instruction, of the publish, each+ # in turn. Every run ends with that interrupt and leaves the start exactly, with nothing hidden, or the whole kit.+ # The publish is given a small kit directly (one run per instruction); with the report inside --out-dir, it is in+ # a directory of its own there. What ended a run is kept without its traceback, so the run's frames, and a file+ # object only they hold, go when the run ends; a run interrupted between opening a file and wrapping the descriptor+ # cannot close it, so each descriptor the run opened and left open is closed after it.+ out_rel, report_rel = PUBLISH_PLACES[placement]+ signum, handler, ends = INTERRUPTS[kind]+ if start == "empty, removed first":+ monkeypatch.setattr(ui_kit, "RENAME_ONTO_EMPTY_DIR", False)+ event = "line" if granularity == "line" else "opcode"+ data = b'{"kind": "sprite-gen-ui-kit"}\n'+ opened, open_fd = [], os.open++ def recorded_open(*args, **kwargs):+ fd = open_fd(*args, **kwargs)+ opened.append((fd, os.fstat(fd)))+ return fd++ monkeypatch.setattr(os, "open", recorded_open)++ def publish(root, target=None):+ """Publish the kit into ``root``, interrupted at ``target``, one event of the run: (function, instruction+ offset, occurrence). Answers the tree before and after, the run's events as such targets with where each+ was, whether the interrupt was raised, and what ended the run (0 when nothing did)."""+ root.mkdir()+ if start != "absent":+ (root / out_rel).mkdir(parents=True)+ report = root / report_rel if report_rel else None+ files = {"one.png": b"one", "two.png": b"two"} | ({} if report else {"reports/kit.json": data})+ given = tree(root)+ seen, events, raised = Counter(), [], []+ opened.clear()++ def each(frame, what, arg):+ if what == event:+ key = (id(frame.f_code), frame.f_lasti)+ seen[key] += 1+ events.append((*key, seen[key], f"{frame.f_code.co_name}:{frame.f_lineno}@{frame.f_lasti}"))+ if events[-1][:3] == target and not raised:+ raised.append(True)+ sys.settrace(None)+ if signum is None:+ raise Halt+ signal.raise_signal(signum)+ return each++ def calls(frame, what, arg):+ if frame.f_code.co_filename != ui_kit.__file__:+ return None+ if event == "opcode":+ frame.f_trace_opcodes, frame.f_trace_lines = True, False+ return each++ previous = signal.signal(signum, handler) if signum is not None else None+ tracer = sys.gettrace()+ sys.settrace(calls)+ try:+ ui_kit._write_kit(root / out_rel, files, report, data)+ ended = 0+ except BaseException as exc:+ ended = exc.with_traceback(None)+ finally:+ sys.settrace(tracer)+ if signum is not None:+ signal.signal(signum, previous)+ for fd, stat in opened:+ with contextlib.suppress(OSError): # closed by the run: gone, or another file's number now+ if os.path.samestat(os.fstat(fd), stat):+ os.close(fd)+ return given, tree(root), events, bool(raised), ended++ # the first opcode-traced run of a function reports none of its instructions on Python 3.12, and some from 3.13+ publish(tmp_path / "warm-up")+ before, complete, events, _, ended = publish(tmp_path / "reference")+ assert ended == 0 and complete[1] == [] and complete != before+ assert {Path(path).name for path in files_of(complete[0])} == {"one.png", "two.png", "kit.json"}+ missed, bad = [], []+ for n, (*target, at) in enumerate(events):+ given, after, _, raised, ended = publish(tmp_path / f"{n}", tuple(target))+ if not raised: # the run never reached that event (see below)+ missed.append(at)+ continue+ assert given == before+ if not (isinstance(ended, ends) and (signum != signal.SIGTERM or ended.code == 128 + signum)+ and after in (before, complete)):+ bad.append((f"{at}#{target[2]}", repr(ended), sorted(after[0]), after[1]))+ assert bad == []+ # Every line event of the reference run recurs in a faulted one. A tracer's instruction events can differ a little+ # between runs on Python 3.13 and later, so one a faulted run never reaches gets no interrupt; most do.+ assert (missed == [] if granularity == "line" else len(missed) < len(events) / 2), missed++[email protected]("placement", sorted(PUBLISH_PLACES))+def test_a_kit_that_reaches_the_out_dir_first_refuses_this_run_and_stays_whole(tmp_path, monkeypatch, placement):+ # Two runs into one new --out-dir: the other run's kit lands there just before this run renames its own in.+ # This run is refused, removes what it made (its staging directory, the report's directory) and leaves the+ # other kit as it was.+ out_rel, report_rel = PUBLISH_PLACES[placement]+ sheet, other = tmp_path / "uikit.png", tmp_path / "other"+ synthetic_sheet(size=TALL)[0].save(sheet)+ assert ui_kit.main(["--sheet", str(sheet), "--out-dir", str(other)]) == 0+ synthetic_sheet(size=TALL, missing="pip_off", noise=False)[0].save(sheet)+ out = (tmp_path / out_rel).resolve()+ rename = os.rename++ def the_other_kit_first(src, dst, *args, **kwargs):+ if Path(dst) == out and not out.exists():+ shutil.copytree(other, out)+ return rename(src, dst, *args, **kwargs)++ monkeypatch.setattr(os, "rename", the_other_kit_first)+ with pytest.raises(SystemExit, match=rf"^ui-kit: --out-dir {re.escape(str(out))} was filled while this kit "+ r"was cut: it holds badge\.png and 15 more; nothing was written$"):+ ui_kit.main(["--sheet", str(sheet), "--out-dir", str(out)]+ + (["--report", str(tmp_path / report_rel)] if report_rel else []))+ assert tree(out) == tree(other)+ assert [path.name for path in tmp_path.rglob(".*")] == []+ assert not (tmp_path / "reports").exists()+++def test_a_report_that_appears_first_refuses_this_run_and_is_kept(tmp_path, monkeypatch):+ # Two runs with their own --out-dir and one --report outside them: the other run's report lands just before+ # this run's own. This run is refused, takes its kit back out, and the other report stays as it was.+ sheet, out, report = tmp_path / "uikit.png", tmp_path / "elements", tmp_path / "reports" / "kit.json"+ synthetic_sheet(size=TALL)[0].save(sheet)+ theirs = b'{"kind": "sprite-gen-ui-kit", "the other run": true}\n'+ link = os.link++ def the_other_report_first(src, dst, *args, **kwargs):+ if Path(dst) == report.resolve() and not report.exists():+ report.write_bytes(theirs)+ return link(src, dst, *args, **kwargs)++ monkeypatch.setattr(os, "link", the_other_report_first)+ with pytest.raises(SystemExit, match=rf"^ui-kit: --report {re.escape(str(report.resolve()))} appeared while "+ "this kit was cut; nothing was written$"):+ ui_kit.main(["--sheet", str(sheet), "--out-dir", str(out), "--report", str(report)])+ assert report.read_bytes() == theirs+ assert not out.exists()+ assert sorted(path.relative_to(tmp_path).as_posix() for path in tmp_path.rglob("*")) == [+ "reports", "reports/kit.json", "uikit.png"]++def test_a_fill_whose_ends_do_not_fit_its_bar_frame_is_flagged():image, drawn = synthetic_sheet(size=TALL, noise=False, haze=False)pixels = np.asarray(image).copy()@@ -599,6 +1189,17 @@ def test_a_packed_fill_is_stored_as_its_bar_frames_content_area(tmp_path, scale)assert np.array_equal(cells[:, rect["w"] - right:], ends[:, resized.width - right:])[email protected]("missing", ["pip_off", "xp_bar_fill", ("joystick_base", "joystick_knob"), tuple(BAND)])+def test_a_partial_kit_packs_only_the_elements_it_holds(tmp_path, missing):+ gone = {missing} if isinstance(missing, str) else set(missing)+ result, out = pack_tall_kit(tmp_path, 0.5, missing=missing)+ nine = result["ui"]["nine_slice"]+ assert set(nine) == set(FRAMES + BAND) - gone+ # the manifest names only frames the atlas holds, and the written manifest is the one returned+ assert {name for page in result["textures"] for name in page["frames"]} == {f"ui/{name}" for name in nine}+ assert json.loads((out / "game-pack.json").read_text())["ui"]["nine_slice"] == nine++@pytest.mark.parametrize("scale", [1, 0.5, 0.37])def test_packed_round_parts_keep_their_aspect(tmp_path, scale):result, out = pack_tall_kit(tmp_path, scale)diff --git a/tests/gen/test_gen.py b/tests/gen/test_gen.pyindex 62d8ae7..e5f11af 100644--- a/tests/gen/test_gen.py+++ b/tests/gen/test_gen.py@@ -703,9 +703,8 @@ def test_ref_run_publishes_a_real_alpha_raw_without_keying_its_outline(assert "publishing its own alpha" in capsys.readouterr().err[email protected]("raw", [_checkerboard_raw, _key_background_raw], ids=["checkerboard", "key-background"])-def test_ref_run_still_keys_a_raw_with_no_alpha(tmp_path: Path, monkeypatch, raw) -> None:- fake, rc, out, report = _ref_run(tmp_path, monkeypatch, raw())+def test_ref_run_still_keys_a_raw_with_no_alpha(tmp_path: Path, monkeypatch) -> None:+ fake, rc, out, report = _ref_run(tmp_path, monkeypatch, _key_background_raw())assert rc == 0payload = json.loads(report.read_text(encoding="utf-8"))@@ -720,6 +719,14 @@ def test_ref_run_still_keys_a_raw_with_no_alpha(tmp_path: Path, monkeypatch, rawassert Image.open(out).getpixel((0, 0)) == (0, 0, 0, 0) # the background was keyed out+def test_ref_run_refuses_a_drawn_checkerboard_instead_of_keying_it(tmp_path: Path, monkeypatch) -> None:+ # a drawn checkerboard is no alpha either, so it is not published on its own alpha; and it is not the key+ # the run asked for, so it is refused before keying (tests/gen/test_painted_checkerboard.py)+ with pytest.raises(SystemExit, match=r"^chroma: the background is a painted transparency checkerboard \(8 px"):+ _ref_run(tmp_path, monkeypatch, _checkerboard_raw())+ assert not (tmp_path / "asset.png").exists() and not (tmp_path / "report.json").exists()++def test_key_background_ref_run_keeps_its_outline(tmp_path: Path, monkeypatch) -> None:_, _, out, _ = _ref_run(tmp_path, monkeypatch, _key_background_raw())published = Image.open(out)diff --git a/tests/gen/test_painted_checkerboard.py b/tests/gen/test_painted_checkerboard.pynew file mode 100644index 0000000..e8ea78a--- /dev/null+++ b/tests/gen/test_painted_checkerboard.py@@ -0,0 +1,152 @@+# SPDX-License-Identifier: Apache-2.0+"""A painted transparency checkerboard is refused before it is keyed, with its own reason.++Asked for a key background, an image model sometimes paints the grey and white checkerboard an+editor shows behind transparent pixels instead. The matte reads its key off the borders, so it+reads the checkerboard as the background and keys nearly the whole image away; the result has no+subject left to cut. `chroma.painted_checkerboard` recognises the checkerboard along the image's+edges and `key_transparent` refuses it before keying, so a caller can generate again. A key+background, a plain light background, stripes, and a checkered subject inside a key background are+not a painted checkerboard. Every sheet here is synthetic.+"""++from __future__ import annotations++import json+from pathlib import Path++import numpy as np+import pytest+from PIL import Image++from sprite_gen import gen+from sprite_gen.gen import base as gen_base+from sprite_gen.gen import chroma as chroma_mod+from sprite_gen.gen.base import GenRequest++FRAME = (110, 70, 40)+FACE = (20, 80, 90)+RED = (200, 30, 40)+MAGENTA = (255, 0, 255)+++def checkerboard(size=(256, 384), square=12, levels=(254, 227), shift=(0, 0)):+ width, height = size+ yy, xx = np.indices((height, width))+ odd = ((xx + shift[0]) // square + (yy + shift[1]) // square) % 2 == 1+ grey = np.where(odd, levels[1], levels[0]).astype(np.uint8)+ return np.repeat(grey[..., None], 3, axis=-1)+++def with_elements(rgb):+ """A few UI elements drawn on the background, away from its edges."""+ rgb = rgb.copy()+ rgb[40:120, 30:200] = FRAME+ rgb[50:110, 40:190] = FACE+ rgb[300:330, 30:200] = RED+ return rgb+++def image(rgb):+ return Image.fromarray(np.ascontiguousarray(rgb), "RGB")++[email protected](("square", "levels", "shift"), [+ (12, (254, 227), (0, 0)),+ (8, (255, 204), (3, 5)),+ (32, (153, 102), (17, 9)),+])+def test_a_painted_checkerboard_is_recognised_along_the_edges(square, levels, shift):+ found = chroma_mod.painted_checkerboard(image(with_elements(checkerboard(square=square, levels=levels, shift=shift))))+ assert found == {"edges": ["top", "bottom", "left", "right"], "square_px": square}+++def test_an_element_across_two_edges_leaves_the_checkerboard_recognised():+ rgb = with_elements(checkerboard())+ rgb[0:20, :] = FRAME # along the whole top edge+ rgb[:, 0:20] = FACE # down the whole left edge+ found = chroma_mod.painted_checkerboard(image(rgb))+ assert found == {"edges": ["bottom", "right"], "square_px": 12}++[email protected]("background", [+ pytest.param(lambda: np.full((384, 256, 3), MAGENTA, dtype=np.uint8), id="magenta key"),+ pytest.param(lambda: np.full((384, 256, 3), (0, 255, 0), dtype=np.uint8), id="green key"),+ pytest.param(lambda: np.full((384, 256, 3), 240, dtype=np.uint8), id="plain light grey"),+ pytest.param(lambda: np.repeat(np.linspace(200, 255, 256).astype(np.uint8)[None, :, None], 384, 0)+ .repeat(3, -1), id="grey gradient"),+ # grey stripes alternate along one axis only; a checkerboard alternates along both+ pytest.param(lambda: np.where((np.indices((384, 256))[1] // 12 % 2 == 1)[..., None], 227, 254)+ .astype(np.uint8).repeat(3, -1), id="vertical stripes"),+ pytest.param(lambda: np.where((np.indices((384, 256))[0] // 12 % 2 == 1)[..., None], 227, 254)+ .astype(np.uint8).repeat(3, -1), id="horizontal stripes"),+])+def test_other_backgrounds_are_not_a_painted_checkerboard(background):+ assert chroma_mod.painted_checkerboard(image(with_elements(background()))) is None+++def test_a_checkered_subject_on_a_key_background_is_keyed(tmp_path):+ rgb = np.full((384, 256, 3), MAGENTA, dtype=np.uint8)+ rgb[100:280, 40:220] = checkerboard(size=(180, 180), square=20) # a chessboard, inside the key+ src = tmp_path / "board.png"+ image(rgb).save(src)+ assert chroma_mod.painted_checkerboard(Image.open(src)) is None+ stats = chroma_mod.key_transparent(src, tmp_path / "out.png", key="magenta")+ keyed = np.asarray(Image.open(tmp_path / "out.png").convert("RGBA"))+ assert keyed[0, 0, 3] == 0 and keyed[190, 130, 3] == 255+ assert 40 < stats["alpha_zero_pct"] < 80+++def test_key_transparent_refuses_a_painted_checkerboard_before_keying(tmp_path, monkeypatch):+ src = tmp_path / "raw.png"+ image(with_elements(checkerboard())).save(src)+ out = tmp_path / "out.png"++ def no_matte(*args, **kwargs):+ raise AssertionError("a painted checkerboard must be refused before the matte runs")++ monkeypatch.setattr(chroma_mod, "remove_chroma_background_ycbcr", no_matte)+ with pytest.raises(SystemExit) as refused:+ chroma_mod.key_transparent(src, out, key="magenta")+ assert str(refused.value) == (+ "chroma: the background is a painted transparency checkerboard (12 px squares along the top, bottom, left "+ "and right edges), not the magenta key the image was asked for; keying it would erase the image — "+ "generate it again")+ assert not out.exists()+++class _CheckerboardProvider:+ """A provider that answers the request for a key background with a painted checkerboard."""++ name = "fake"+ transparency = gen_base.TRANSPARENCY_NATIVE++ def generate(self, request: GenRequest, workdir: Path):+ image(with_elements(checkerboard())).save(request.raw)+ return gen_base.ProviderRun(provider=self.name, elapsed_seconds=0.1, model=request.model)+++def test_a_ui_kit_generation_that_comes_back_on_a_checkerboard_is_refused(tmp_path, monkeypatch):+ # the layout guide is an attached image, so `auto` keys the result (`refs-attached`): the checkerboard is+ # refused with its own reason instead of being keyed into an empty sheet, and nothing is published+ monkeypatch.setattr(gen, "_make_provider", lambda name, *, keep_session: _CheckerboardProvider())+ out, report = tmp_path / "uikit.png", tmp_path / "report.json"+ with pytest.raises(SystemExit, match=r"^chroma: the background is a painted transparency checkerboard"):+ gen.run(provider="fake", prompt="A game UI kit in brass and walnut.", out=out, report=report,+ transparent=True, layout_guide="ui-kit", aspect_ratio="2:3")+ assert not out.exists() and not report.exists()+++def test_a_ui_kit_generation_on_a_key_background_is_keyed_as_before(tmp_path, monkeypatch):+ class _KeyProvider(_CheckerboardProvider):+ def generate(self, request, workdir):+ image(with_elements(np.full((384, 256, 3), MAGENTA, dtype=np.uint8))).save(request.raw)+ return gen_base.ProviderRun(provider=self.name, elapsed_seconds=0.1, model=request.model)++ monkeypatch.setattr(gen, "_make_provider", lambda name, *, keep_session: _KeyProvider())+ out, report = tmp_path / "uikit.png", tmp_path / "report.json"+ assert gen.run(provider="fake", prompt="A game UI kit in brass and walnut.", out=out, report=report,+ transparent=True, layout_guide="ui-kit", aspect_ratio="2:3") == 0+ alpha = json.loads(report.read_text(encoding="utf-8"))["alpha"]+ assert alpha["strategy"] == "chroma" and alpha["strategy_source"] == "refs-attached"+ assert 50 < alpha["alpha_zero_pct"] < 90