Skip to content

Commit 8e7fbd9

Browse files
DocAtPromptclaude
andcommitted
media: the check reaches a document generator too (§ 12.1, § 7)
The gap the preset guard found yesterday: § 12.1 read marks from a *blade* — build the geometry, take page 0, call `generate` — and a document generator refuses `generate` by design, so the check raised on one and the document pre-flight never called it. A calendar's weights and colours were measured against no medium at all. The sample now branches on the document seam and walks `pages()`, keeping one mark per distinct stroke width and colour. Two calls inside that, both in decision 49: - **Every page, not the first of each `kind`.** Nine pages instead of 456 was right there and would have been wrong: a marked day carries its own colour and appears only on the pages holding that date, so a birthday in May would go unmeasured while January passed. The full walk costs 0.17 s once per run (a calendar build: 1.6 s → 1.8 s), and memory stays at a dozen marks. - **A page's `background` is a colour.** The title page's full-sheet fill is a page property the handle paints, not a mark — and on a grayscale screen it is precisely what goes flat. `_document_preflight` now calls the check and folds its findings into the notices, so `--strict` guards a calendar the way it guards a sheet. The findings are real. A calendar on a landscape reMarkable 2 says that its link blue #2f5686 and a birthday's #cc4488 are 21 grey levels apart and will read as one tone, and that the weekend shade all but vanishes. Nothing said that before. `test_every_shipped_preset_is_clean_on_its_own_medium` loses its skip — that skip was the bug. 1087 tests green, ruff clean. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
1 parent 0e2dba5 commit 8e7fbd9

7 files changed

Lines changed: 219 additions & 23 deletions

File tree

‎ctrlgrid/media.py‎

Lines changed: 48 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
from typing import TYPE_CHECKING
2222

2323
from ctrlgrid.errors import DefinitionError
24-
from ctrlgrid.marks import Arc, Dot, Polygon, Segment
24+
from ctrlgrid.marks import Arc, Dot, Point, Polygon, Segment
2525
from ctrlgrid.writers import WriterQuery
2626

2727
if TYPE_CHECKING:
@@ -170,8 +170,15 @@ def _colour_findings(marks: list[object], document: Document) -> list[str]:
170170

171171

172172
def _sample(document: Document, q: WriterQuery):
173-
"""The marks of page 0, to read weights and colours off (§ 12.1)."""
173+
"""The marks to read weights and colours off (§ 12.1).
174+
175+
A blade fills one pattern area with one repeating pattern, so page 0 shows
176+
everything it has. A **document generator** owns heterogeneous pages
177+
instead (§ 7), and there every page is walked — see `_document_sample` for
178+
why one page per kind would be cheaper and wrong.
179+
"""
174180
from ctrlgrid import generators
181+
from ctrlgrid.document import is_document_generator
175182
from ctrlgrid.pages import Geometry, page_contexts
176183

177184
geometry = Geometry.of(
@@ -182,11 +189,49 @@ def _sample(document: Document, q: WriterQuery):
182189
blade_axes=document.axes,
183190
density=document.device.density if document.device else None,
184191
)
185-
page = next(page_contexts(count=1, snap=geometry.pixel_snap))
186192
blade = generators.get(document.generator)
193+
if is_document_generator(blade):
194+
return _document_sample(document, blade, geometry, q)
195+
page = next(page_contexts(count=1, snap=geometry.pixel_snap))
187196
return blade.generate(document.config, area=geometry.area, page=page, q=q)
188197

189198

199+
def _document_sample(document: Document, blade: object, geometry, q: WriterQuery):
200+
"""One mark per distinct stroke width and colour, across **every** page.
201+
202+
Every page, not the first of each `kind`: a marked day carries its own
203+
colour and appears on exactly the pages holding that date, so a shortcut
204+
would measure January and miss a birthday in May — the silent almost-right
205+
of § 5.1. The full walk of a 456-page year planner costs about a fifth of a
206+
second, once per run, and only one mark per distinct (weight, colour) is
207+
kept, so a document is no heavier here than a sheet.
208+
209+
A page's `background` is a colour too. The handle paints that fill rather
210+
than the generator (§ 3.3), so it is no mark — but on a grayscale screen it
211+
is exactly what goes flat, and § 12.1 has to say so.
212+
"""
213+
seen: set[tuple] = set()
214+
for page in blade.pages(document.config, area=geometry.area, q=q):
215+
if page.background is not None:
216+
key = ("background", page.background)
217+
if key not in seen:
218+
seen.add(key)
219+
yield Segment(
220+
start=Point(0, 0), end=Point(0, 0), weight=0.0, color=page.background
221+
)
222+
for mark in page.marks:
223+
key = (
224+
type(mark).__name__,
225+
getattr(mark, "weight", None),
226+
getattr(mark, "diameter", None),
227+
getattr(mark, "color", None),
228+
)
229+
if key in seen:
230+
continue
231+
seen.add(key)
232+
yield mark
233+
234+
190235
def _weights(marks: list[object]) -> set[tuple[float, str]]:
191236
"""Distinct stroke widths and dot diameters, labelled in points.
192237

‎ctrlgrid/pages.py‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -902,6 +902,15 @@ def _document_preflight(
902902
blade.check(document.config, area=geometry.area, q=probe)
903903
_refuse_writer_cannot_render_document(document, blade, geometry, q, probe)
904904

905+
# § 12.1 reaches a document too: its pages are walked for the weights and
906+
# colours the medium has to carry. A round-to-zero stroke raises, the rest
907+
# become notices, and `--strict` turns them into errors — the same
908+
# treatment the blade path gets, from the same function.
909+
from ctrlgrid.media import media_findings
910+
911+
findings = media_findings(document, probe, strict=document.strict)
912+
geometry = replace(geometry, notices=geometry.notices + tuple(findings))
913+
905914
# The optional header/footer are constant across a document (§ 7), so they
906915
# are measured once here — against a context whose count is the real page
907916
# total, and with the generator's own placeholders (`{year}`). Measured in

‎docs/CLAUDE.md‎

Lines changed: 2 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ needs a human *and* the user has chosen to defer PyPI for now (see *Not done*).
3939
uv sync --extra dev && uv run pytest && uv run ruff check .
4040
```
4141

42-
1081 tests, all green, ruff clean. Sixty-odd commits on `main`, linear history,
42+
1087 tests, all green, ruff clean. Sixty-odd commits on `main`, linear history,
4343
pushed to **[github.com/DocAtPrompt/ctrlgrid](https://github.com/DocAtPrompt/ctrlgrid)**
4444
(public); CI runs green there on Linux (3.11–3.13), macOS and Windows. Fifteen
4545
presets — one per generator (`lines`, `dots`, `polar`, `form`, `maze`,
@@ -99,15 +99,6 @@ says so.
9999

100100
### Not done
101101

102-
**The media check does not reach a document generator.** § 12.1 samples a
103-
blade's marks against the medium, and `calendar` has no single pattern area to
104-
sample — it owns its pages. So `calendar-a4` is the one preset
105-
`test_every_shipped_preset_is_clean_on_its_own_medium` skips, and the skip says
106-
so in place rather than passing quietly. Fixing it means sampling a document's
107-
pages the way the capability pre-flight samples one page's marks; small, and
108-
nobody has needed it yet because the calendar is drawn for paper and pen tablets
109-
at weights well above the threshold.
110-
111102
**Two small edges of M5 remain**, and each names why:
112103

113104
- **`quirks` ships empty** (decision 31). § 9.2 provides the field with a Boox
@@ -223,7 +214,7 @@ and knows nothing about margins.
223214
| `clip.py` | Liang–Barsky in exact rationals, shared by `perspective` and slanted `lines` |
224215
| `ruler.py` | the edge scale's ladder: tick positions, exact labels, the strip it needs (§ 8.12) |
225216
| `images.py` | PNG sources: signature check, pixel size, aspect (§ 5.2, § 13) |
226-
| `media.py` | the media check: resolution and colour findings (§ 12.1) |
217+
| `media.py` | the media check: resolution and colour findings (§ 12.1), for blades **and** documents — a document's pages are all walked, one mark kept per distinct weight and colour (decision 49) |
227218
| `impose.py` | N-up layout, the 100 % fit check, crop marks (§ 14) |
228219
| `fonts.py` | font files: `fsType` licence check, version, coverage (§ 10.3) |
229220
| `cover.py` | the cover sheet: calibration figures, the stroke-weight ladder, settings summary (§ 8.8) |

‎docs/implementation-decisions.md‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -879,3 +879,34 @@ Snapping needed no new machinery: a slanted family reports no periodic axis at
879879
all, so § 8.3's existing handling applies unchanged and the handle never learns
880880
what an angle is. `governing: true` and `law: log10` are refused on a slanted
881881
family for the same reason — both name an axis that is not there.
882+
883+
884+
## 49. The media check walks every page of a document (§ 12.1, § 7)
885+
886+
§ 12.1 measures a definition against its medium by reading marks, and it read
887+
them from a *blade*: build the geometry, take page 0's context, call `generate`.
888+
A document generator refuses `generate` by design — it owns pages — so the check
889+
raised on one, and the document pre-flight never called it. A calendar's weights
890+
and colours were therefore measured against nothing at all, which the new
891+
"every shipped preset is clean on its own medium" test found by having to skip
892+
`calendar-a4`.
893+
894+
The sample now branches on the document seam and walks `pages()`, keeping **one
895+
mark per distinct stroke width and colour**. Two calls inside that are worth
896+
recording:
897+
898+
**Every page, not the first of each `kind`.** `DocumentPage.kind` is right there
899+
and sampling one page per kind would be nine pages instead of 456. It would also
900+
be wrong: a marked day carries its own colour and appears only on the pages
901+
holding that date, so a birthday in May would go unmeasured while January passed.
902+
The full walk costs about 0.17 s once per run — a calendar build went from 1.6 s
903+
to 1.8 s — and the memory stays at a dozen marks because only distinct
904+
(weight, colour) survive.
905+
906+
**A page's `background` counts as a colour.** The title page's full-sheet fill is
907+
a page property the handle paints (§ 3.3), not a mark, so a mark-only sample
908+
would miss it — and on a grayscale screen that fill is exactly what goes flat.
909+
910+
The findings are real, not theoretical: a calendar on a landscape reMarkable 2
911+
now says that its link blue `#2f5686` and a birthday's `#cc4488` are 21 grey
912+
levels apart and will read as one tone. Nothing said that before.

‎docs/pflichtenheft-vorlagengenerator.md‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2199,6 +2199,18 @@ sichtbar wäre — und beim PDF-Weg (§ 9.2), der der übliche ist, nie.
21992199
Grundlage ist eine **Auflösung je Medium**: bei Geräteprofilen `density`, bei
22002200
Papierformaten ein angenommener Druckwert (`assumed_dpi`, § 9.1, typisch 600).
22012201

2202+
**Auch Dokumentgeneratoren werden geprüft** (§ 7, festgelegt beim Bau 2026-07).
2203+
Eine Klinge füllt eine Musterfläche mit einem sich wiederholenden Muster —
2204+
Seite 0 zeigt alles, was sie hat. Ein Dokument besitzt dagegen ungleiche Seiten,
2205+
deshalb werden **alle** Seiten durchlaufen und je Stärke und Farbe eine Marke
2206+
behalten. Nicht eine Seite je Seitenart: die eigene Farbe eines markierten Tages
2207+
steht nur auf den Seiten dieses Datums, ein Geburtstag im Mai bliebe also
2208+
ungemessen — das stille „fast richtig" aus § 5.1. Der volle Durchlauf eines
2209+
Jahresplaners mit 456 Seiten kostet etwa zwei Zehntelsekunden, einmal pro Lauf.
2210+
Die **Hintergrundfarbe einer Seite** zählt dabei als Farbe mit, obwohl der Griff
2211+
sie malt und sie keine Marke ist: auf einem Graustufenschirm ist gerade sie es,
2212+
die zu Brei wird.
2213+
22022214
#### Auflösungsbedingte Befunde
22032215

22042216
| Befund | Bedeutung |
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# The media check for document generators — design
2+
3+
**Date:** 2026-07-25. Small, and it closes the gap the preset guard found:
4+
§ 12.1 never reaches a document generator, so a calendar's weights and colours
5+
are measured against no medium at all.
6+
7+
## Why it is missing
8+
9+
`media.py` reads a *blade's* marks — `_sample` builds a geometry, takes page 0's
10+
context and calls `generate`. A document generator refuses `generate` by design
11+
(it owns pages), so `media_findings` raises on one, and `_document_preflight`
12+
never calls it. Both halves have to change.
13+
14+
## What it will do
15+
16+
1. **`_sample` learns the document seam.** For a document generator it walks
17+
`blade.pages(cfg, area, q)` — the same seam the capability check already
18+
samples — and keeps **one representative mark per distinct (kind, weight,
19+
colour)**. Bounded memory (a dozen marks, not the 74 580 a year planner
20+
draws), and complete: every page is looked at.
21+
22+
2. **Every page, not one per page kind.** Sampling the first page of each kind
23+
would be cheaper and would silently miss the case that matters — a marked
24+
day's own colour appears only on the pages carrying that date, so a birthday
25+
in May would go unmeasured. The full walk costs 0.17 s on a 456-page
26+
calendar, once per run.
27+
28+
3. **A page's `background` is a colour too.** The title page's full-sheet fill
29+
is a page property the handle paints, not a mark, so the walk feeds it into
30+
the colour findings as well — on a grayscale device that fill is precisely
31+
the thing that turns to mud.
32+
33+
4. **`_document_preflight` runs the check** and folds its findings into the
34+
geometry's notices, exactly as `preflight` does, so `--strict` works there
35+
too and the run report says the same kind of thing for both paths.
36+
37+
Spacing findings need no work: they read `periodic_axes`, and a document
38+
reports none — a calendar has no repeating step to land on a pixel grid.
39+
40+
## Tests
41+
42+
- a document on a grayscale device names a colour that appears **only on a late
43+
page** — the one-page-per-kind shortcut would pass this and be wrong;
44+
- a hairline in a document raises the round-to-zero error, as it does for a blade;
45+
- `calendar-a4` on paper is clean, and `test_every_shipped_preset_is_clean_on_its_own_medium`
46+
drops its skip — the skip is the bug this fixes;
47+
- `--strict` turns a document's finding into an error.

‎tests/test_media.py‎

Lines changed: 70 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@
2020

2121
import pytest
2222

23-
from ctrlgrid.document import is_document_generator
2423
from ctrlgrid.errors import DefinitionError
2524
from ctrlgrid.loader import loads
2625
from ctrlgrid.media import media_findings
@@ -145,18 +144,10 @@ def test_every_shipped_preset_is_clean_on_its_own_medium(self) -> None:
145144
# A preset is documentation (§ 9.3), and one that warns about itself
146145
# teaches the wrong thing. This caught a 0.1pt stroke — 0.83px at
147146
# 600 dpi — in two presets on the day it was written.
148-
from ctrlgrid.generators import get
149147
from ctrlgrid.loader import load_preset, preset_names
150148

151149
for name in preset_names():
152150
document = load_preset(name)
153-
if is_document_generator(get(document.generator)):
154-
# The media check samples a blade's marks, and a document
155-
# generator has no single pattern area to sample — it owns its
156-
# pages. So `calendar-a4` is not covered here, and nothing else
157-
# covers it either: § 12.1 does not reach document generators
158-
# yet. Recorded rather than quietly skipped.
159-
continue
160151
assert media_findings(document, Q) == [], f"{name} warns about itself"
161152

162153

@@ -196,3 +187,73 @@ def test_a_round_to_zero_stops_the_preflight(self, tmp_path: Path) -> None:
196187
with pytest.raises(DefinitionError):
197188
build(document, PdfWriter(path))
198189
assert not path.exists()
190+
191+
192+
class TestDocumentGenerators:
193+
"""§ 12.1 for a generator that owns its pages (§ 7).
194+
195+
The check reads marks, and a document has no single pattern area to read
196+
them from — it has pages. Every page is walked, not one per page kind: a
197+
marked day's own colour appears only on the pages carrying that date, so a
198+
shortcut would measure January and miss a birthday in May.
199+
"""
200+
201+
CALENDAR = (
202+
"generator: calendar\nyear: 2026\n"
203+
"holiday_color: '#fce9e4'\n"
204+
"holidays:\n"
205+
" - {date: 2026-05-03, label: 'a birthday', color: '#cc4488'}\n"
206+
"notes: {count: 2}\n"
207+
)
208+
209+
def test_a_colour_that_appears_only_on_a_late_page_is_still_found(self) -> None:
210+
# The birthday is in May; its colour is on no page before it. On a
211+
# grayscale device it turns to mud, and that has to be said.
212+
notes = findings(GRAY + self.CALENDAR)
213+
assert any("#cc4488" in note for note in notes)
214+
215+
def test_the_title_pages_full_sheet_colour_counts_as_a_colour(self) -> None:
216+
# The fill is a page property the handle paints, not a mark — but on a
217+
# grayscale screen it is exactly what goes flat.
218+
notes = findings(
219+
GRAY + self.CALENDAR + "title_page: {title: '2026', background: '#2f3a48'}\n"
220+
)
221+
assert any("#2f3a48" in note for note in notes)
222+
223+
def test_a_calendar_on_paper_says_nothing(self) -> None:
224+
from ctrlgrid.loader import load_preset
225+
226+
assert media_findings(load_preset("calendar-a4"), Q) == []
227+
228+
def test_strict_turns_a_documents_finding_into_an_error(self) -> None:
229+
document = loads(GRAY + self.CALENDAR, None, source="test")
230+
with pytest.raises(DefinitionError):
231+
media_findings(document, Q, strict=True)
232+
233+
234+
class TestDocumentsInTheRun:
235+
"""The check has to be *called* on the document path, not merely callable.
236+
237+
A calendar wants a wide sheet — the twelve mini-months of its year page are
238+
refused on a portrait e-ink screen (§ 9) — so the medium here is a landscape
239+
reMarkable 2, which is also the case a user would actually meet.
240+
"""
241+
242+
ON_A_GRAYSCALE_SCREEN = (
243+
"version: 1\npage:\n device: remarkable-2\n orientation: landscape\n"
244+
" margin: 0mm\n"
245+
"generator: calendar\nyear: 2026\n"
246+
"holidays:\n - {date: 2026-05-03, label: 'a birthday', color: '#cc4488'}\n"
247+
)
248+
249+
def test_the_preflight_reports_a_documents_findings_as_notices(self) -> None:
250+
document = loads(self.ON_A_GRAYSCALE_SCREEN, None, source="test")
251+
geometry, _contexts, _bands, _cover = preflight(document, Q)
252+
# The link blue and the birthday pink read as one tone there — a real
253+
# finding, and one nothing said before the check reached documents.
254+
assert any("#cc4488" in note for note in geometry.notices)
255+
256+
def test_strict_stops_a_document_run_at_the_preflight(self) -> None:
257+
document = loads(self.ON_A_GRAYSCALE_SCREEN, {"strict": True}, source="test")
258+
with pytest.raises(DefinitionError):
259+
preflight(document, Q)

0 commit comments

Comments
 (0)