diff --git a/.github/osv-scanner.toml b/.github/osv-scanner.toml index 7555ed41..9264e1e5 100644 --- a/.github/osv-scanner.toml +++ b/.github/osv-scanner.toml @@ -21,9 +21,13 @@ # request against requirements-semgrep.in, and this entry has nothing left to # hide - remove it then. If that has not happened by the date below, the weekly # scan goes red again, which is the reminder. +# +# The reminder came on 2026-11-16, and semgrep 1.185.0 of 2026-11-10, the +# newest on PyPI that day, still asks for mcp==1.29.0 and +# opentelemetry-api~=1.37.0. Every date in this file moved four weeks on. [[IgnoredVulns]] id = "GHSA-84m7-p3x7-pcfv" -ignoreUntil = 2026-11-15 +ignoreUntil = 2026-12-14 reason = "semgrep pins mcp==1.29.0 in every release, and the advisory is about an MCP HTTP server, which semgrep scan never starts" # opentelemetry-api 1.37.0, in requirements-semgrep.txt for the scanner and @@ -42,9 +46,20 @@ reason = "semgrep pins mcp==1.29.0 in every release, and the advisory is about a # moves its pins, and both come back on one reminder. [[IgnoredVulns]] id = "GHSA-xcq7-p3pf-p88h" -ignoreUntil = 2026-11-15 +ignoreUntil = 2026-12-14 reason = "semgrep pins opentelemetry-api~=1.37.0 in every release, and the advisory is about parsing an inbound tracestate header in a server, which semgrep scan never runs" +# A second advisory against opentelemetry-api 1.37.0, found by the weekly scan +# of 2026-11-16, fixed in 1.45.2. The same class as the entry above: parsing an +# inbound traceparent header takes quadratic time, reached through +# TraceContextTextMapPropagator.extract() in a server receiving requests. +# semgrep 1.185.0 still asks for ~=1.37.0, and semgrep scan receives no +# request. The same date as the rest, for the same one reminder. +[[IgnoredVulns]] +id = "GHSA-mf5v-w3w3-f6cg" +ignoreUntil = 2026-12-14 +reason = "semgrep pins opentelemetry-api~=1.37.0 in every release, and the advisory is about parsing an inbound traceparent header in a server, which semgrep scan never runs" + # Three more advisories against mcp 1.29.0, published 2026-11-02, all fixed in # the same 1.30.0 as the first entry above. # @@ -65,15 +80,15 @@ reason = "semgrep pins opentelemetry-api~=1.37.0 in every release, and the advis # its pin, and all of them come back on one reminder. [[IgnoredVulns]] id = "GHSA-5h93-6whr-6q8j" -ignoreUntil = 2026-11-15 +ignoreUntil = 2026-12-14 reason = "semgrep pins mcp==1.29.0 in every release, and the advisory is about the MCP client following cross-origin redirects, which semgrep scan never starts" [[IgnoredVulns]] id = "GHSA-rwrf-2pqf-9j8j" -ignoreUntil = 2026-11-15 +ignoreUntil = 2026-12-14 reason = "semgrep pins mcp==1.29.0 in every release, and the advisory is about the MCP client fetching server-chosen $ref addresses, which semgrep scan never starts" [[IgnoredVulns]] id = "GHSA-w4fh-qvv9-3v23" -ignoreUntil = 2026-11-15 +ignoreUntil = 2026-12-14 reason = "semgrep pins mcp==1.29.0 in every release, and the advisory is about an MCP server checking bearer tokens, which semgrep scan never starts" diff --git a/.github/race-weights b/.github/race-weights index d9578771..e4e1579f 100644 --- a/.github/race-weights +++ b/.github/race-weights @@ -12,6 +12,8 @@ # scaled up by its part: on 2026-11-12 the listed tests of two parts on an AMD # EPYC 9V74 took 1/1.20 and 1/1.15 of their weights. # Listed: every test that took 10 s or more. "unlisted" is the mean of the rest. +# TestSmallestIsTheSmallestFile came on 2026-11-16: 79.3 s in a part whose +# listed tests took 0.61 of their weights, so 130.1. # # A test that is not here and takes 60 s or more fails its part with the line # to add. A test that is here and no longer exists fails every part. @@ -23,6 +25,7 @@ unlisted 0.58 162.6 TestEveryScreenStillDrawsItsStoredPicture 142.2 TestEveryTileOfAFilmIsGav1dsCodingOfItsPixelsAndDecodesAsItDoesAlone 134.0 TestEveryAvifRungStillFitsInsideItsDeclaredCeilings +130.1 TestSmallestIsTheSmallestFile 130.0 TestTheMinimumThisToolPrintsStandsWhateverTheSeedIs 124.3 TestFreeBoxesCarryPaddingOfAnyLength 99.9 TestEveryBase64TextSizeIsExact diff --git a/.github/workflows/osv-weekly.yml b/.github/workflows/osv-weekly.yml index 26df7305..33d48fa3 100644 --- a/.github/workflows/osv-weekly.yml +++ b/.github/workflows/osv-weekly.yml @@ -102,7 +102,7 @@ jobs: - name: upload to the Security tab if: ${{ !cancelled() && hashFiles('osv-results.sarif') != '' }} - uses: github/codeql-action/upload-sarif@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1 + uses: github/codeql-action/upload-sarif@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3 with: sarif_file: osv-results.sarif category: osv-scanner diff --git a/CHANGELOG.md b/CHANGELOG.md index 2f388397..463787af 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -59,6 +59,24 @@ because it turns other people's test suites red. ### Added +- **Placeholder pictures.** `--set content=placeholder` on `png`, `jpg` and + `svg` draws a flat colour with words in the middle, for laying out a page + before the real pictures exist. The words are the picture's size unless + `text` says otherwise, and `{width}`, `{height}`, `{index}` and + `{index:04}` in it become each file's size and number. `background` and + `foreground` take a colour such as `cccccc`, and `guides` draws a frame, + both diagonals and a circle. In a recipe write a colour without the `#` or + in quotes, because YAML reads `#` as the start of a comment. The test + pattern is unchanged. + +- **`smallest` as a size.** `--size smallest`, or `size: smallest` in a + recipe, makes each picture as small as it can be at the `width` and + `height` you set, in all ten picture formats, and `--dry-run` still says the + size to the byte. With the label on, the label states the file's size and + its numerals change how a PNG or a JPG compresses, so it can carry up to + about a kilobyte more than its picture needs. With `--clean` the file is the + picture alone. + - **Generate into the same folder again.** A run into an output directory that already holds an earlier run is added beside it: every name of the run, its manifest's too, gets a number, such as `files-2_0001.pdf` and diff --git a/README.md b/README.md index f1107301..46bbae09 100644 --- a/README.md +++ b/README.md @@ -50,6 +50,9 @@ needs it finds out it exists. the right extension. - **Take settings per format** - image dimensions, JPEG quality, PDF pages, spreadsheet rows and columns. +- **Draw placeholder pictures** - a flat colour with its size written in the + middle, for laying out a page before the real pictures exist, as PNG, JPG or + SVG and as small as the picture allows. - **Fit into CI** - an exit code for every ending, machine readable output, and nothing on standard output when a run fails. - **Clean up after itself** - `verify` tells you nothing moved, `cleanup` @@ -207,6 +210,13 @@ tfg cleanup ./logs/manifest.json --yes logs matches ./logs/manifest.json: 10000 files checked ``` +**4. Make placeholders for a page.** Six pictures of 1200 by 630 that say +`Hero 1` to `Hero 6`, each as small as it can be: + +``` +tfg generate --format png --size smallest --count 6 --set content=placeholder --set width=1200 --set height=630 --set "text=Hero {index}" --out ./hero +``` + **Sizes count in 1024s**, the way your file manager does, so `2mb` means 2097152 bytes. A plain byte count works too: `--size 2097152`. @@ -360,7 +370,7 @@ tfg generate --format txt --size 1mb settings come from the flags | flag | what it does | |---|---| | `--format ` | format of the files, for example `txt` | -| `--size ` | exact size of every file, such as `10mb` or a plain byte count | +| `--size ` | exact size of every file, such as `10mb` or a plain byte count. `smallest` makes each picture as small as it can be at the `width` and `height` you set | | `--size-range ` | a size drawn per file from a range, such as `1kb-8kb`. The draw comes from the seed | | `--boundary ` | three files around a limit: one byte under, the limit, one byte over | | `--count ` | how many files to produce. Default `1` | @@ -621,7 +631,7 @@ next to the recipe. Give an absolute path, or `--out`, when you want it fixed. | `id` | names the target, and is the anchor its seeds are derived from | | `format` | one of the formats below | | `count` | how many files. Default `1` | -| `size` | exact size of every file | +| `size` | exact size of every file, or `smallest` for a picture with its `width` and `height` set | | `size-range` | a size drawn per file from a range, such as `1kb-8kb` | | `boundary` | three files around a limit: under, at, over | | `contains` | for archives: entries of `format`, `count` and `size` | @@ -718,9 +728,11 @@ recipe. `tfg formats ` prints the allowed range or list for each: | format | settings | |---|---| | `pdf` | `pages`, `page_size`, `orientation`, `rotate`, `pdf_version`, and the document properties `title`, `author`, `subject`, `keywords`, `creator`, `producer`, `created`, `modified` | -| `png`, `bmp`, `tiff`, `webp` | `width`, `height` | +| `png` | `width`, `height`, `content`, `text`, `background`, `foreground`, `guides` | +| `bmp`, `tiff`, `webp` | `width`, `height` | | `gif` | `width`, `height`, `frames` | -| `avif`, `jpg`, `jxl` | `width`, `height`, `quality` | +| `jpg` | `width`, `height`, `quality`, `content`, `text`, `background`, `foreground`, `guides` | +| `avif`, `jxl` | `width`, `height`, `quality` | | `ico` | `width`, `height`, `embed` | | `wav` | `sample_rate`, `bit_depth`, `channels`, `content` | | `webm`, `mp4` | `width`, `height`, `duration`, `change_interval`, `frame_rate`, `keyframe_interval`, `quality` | @@ -737,7 +749,7 @@ recipe. `tfg formats ` prints the allowed range or list for each: | `geojson` | `geometry`, `formatting`, `precision`, `altitude`, `vertices`, `holes`, `winding`, `antimeridian`, `unlocated`, `ids`, `bbox` | | `otlp` | `signal`, `formatting`, `batch`, `start`, `rate`, `depth`, `status_mix`, `level_mix`, `trace_context`, `metric_kind`, `temporality`, `exemplars`, `interval`, `id_encoding`, `enum_encoding`, `key_case`, `large_numbers`, `bom`, `time_order`, `end_before_start`, `empty_envelope`, `body`, `non_finite` | | `eml` | `body`, `layout`, `text_encoding`, `charset`, `headers`, `recipients`, `line_endings`, `attachments`, `attachment_format`, `attachment_size`, `filename_style`, `message_depth`, `inline`, `inline_format`, `inline_size` | -| `svg` | `width`, `height` | +| `svg` | `width`, `height`, `content`, `text`, `background`, `foreground`, `guides` | | `html` | `structure`, `nesting`, `characters`, `elements`, `links`, `bom`, `formatting`, `styles`, `inline`, `inline_format`, `inline_size` | | `yaml`, `toml` | none in this build - the document is a fixed shape, and a size is the only thing to ask for | diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.md index d72b3a89..aa35ef2a 100644 --- a/THIRD-PARTY-NOTICES.md +++ b/THIRD-PARTY-NOTICES.md @@ -290,7 +290,7 @@ is the module's own MIT, carried unchanged. | `github.com/yuin/goldmark` | v1.8.2 | MIT | (c) 2019 Yusuke Inuzuka | | `golang.org/x/image` | v0.46.0 | BSD-3-Clause | 2009 The Go Authors. | | `golang.org/x/net` | v0.62.0 | BSD-3-Clause | 2009 The Go Authors. | -| `golang.org/x/sys` | v0.49.0 | BSD-3-Clause | 2009 The Go Authors. | +| `golang.org/x/sys` | v0.50.0 | BSD-3-Clause | 2009 The Go Authors. | The five licence texts follow, one copy each. They differ only in the copyright line, which is in the table above for every module. @@ -612,7 +612,7 @@ THE SOFTWARE. --- -## Files the window binary carries that are not code +## Files the binaries carry that are not code The toolkit compiles fonts and drawings into the binary. They are not modules, so a list of modules never mentions them - which is how they shipped unnamed @@ -621,7 +621,8 @@ images arrive this way from the toolkit, and their licences ask for their notices to travel with them. Two more font files arrive from a package of this project itself: Inter, the face the window has been set in since 2026-09-15, is embedded by `internal/gui/font` rather than by the toolkit, and is listed -here under the same rule. +here under the same rule. So is one file made from one of them, the outlines +of the letters a placeholder picture is drawn with, which both binaries carry. What is listed here was measured by asking the compiler which files each package embeds, not by reading its source. The copyright lines were read out of @@ -632,15 +633,20 @@ the font files themselves. | Noto Sans, four styles | `fyne.io/fyne/v2/theme` | OFL-1.1 | Copyright 2015 Google Inc. All Rights Reserved. | | Inter Symbols, the toolkit's symbol glyphs only | `fyne.io/fyne/v2/theme` | OFL-1.1 | (c) 2020 The Inter Project Authors | | Inter, Regular and Bold, the text of the window - static instances from the v4.1 release of github.com/rsms/inter | `internal/gui/font` in this project | OFL-1.1 | Copyright 2016 The Inter Project Authors | +| Inter Bold outlines, the letters of a placeholder picture - 548 characters of the Inter Bold file above, as whole numbers | `internal/format/placeholder/glyphs` in this project | OFL-1.1 | Copyright 2016 The Inter Project Authors | | DejaVu Sans Mono for Powerline | `fyne.io/fyne/v2/theme` | Bitstream-Vera | (c) 2003 Bitstream, Inc. DejaVu changes are in the public domain | | EmojiOne Color | `fyne.io/fyne/v2/theme` | MIT, and read the note below | Copyright 2016 Adobe Systems Incorporated | | Fyne icon set, 96 drawings and one image | `fyne.io/fyne/v2/theme` | BSD-3-Clause | (C) 2018 Fyne.io developers (see AUTHORS) | | Fyne translations, 15 files of toolkit wording | `fyne.io/fyne/v2/lang` | BSD-3-Clause | (C) 2018 Fyne.io developers (see AUTHORS) | | Fyne shaders, 14 programs that draw the screen | `fyne.io/fyne/v2/internal/painter/gl` | BSD-3-Clause | (C) 2018 Fyne.io developers (see AUTHORS) | -`tfg`, the command line binary, embeds none of this. It has no toolkit in it. +`tfg`, the command line binary, has no toolkit in it and carries one file of +this list: the Inter Bold outlines. They are a Modified Version in the terms +of the Open Font License - a subset of the font's letters written in another +format, each shape point for point the font's own - so they travel under that +licence, reproduced below, with the font's copyright line. -None of the three fonts under the Open Font License declares a Reserved Font +None of the fonts under the Open Font License declares a Reserved Font Name - checked in the licence file of each and in the name table of each font file - so the identifier above is OFL-1.1 rather than OFL-1.1-RFN. Inter is a trademark of Rasmus Andersson. @@ -663,7 +669,7 @@ and only those were replaced by their plain equivalents. ### SIL Open Font License 1.1 -Applies to Noto Sans, to Inter Symbols and to Inter. +Applies to Noto Sans, to Inter Symbols, to Inter and to the Inter Bold outlines. ``` ------------------------------ @@ -937,8 +943,9 @@ above. ## Not used -`tfg`, the command line binary, embeds no fonts, images, sound or other -third party assets. The window binary does, and they are listed above. The pixel +`tfg`, the command line binary, embeds no font files, images, sound or other +third party assets apart from the Inter Bold outlines listed above. The window +binary does, and they are listed above. The pixel font that draws the label on a generated image is drawn in this repository, in `internal/format/imagelabel/font.go`, so that a font licence is not a question this project has to answer. The filler vocabulary is a short list of ordinary diff --git a/go.mod b/go.mod index ae306763..c26f5962 100644 --- a/go.mod +++ b/go.mod @@ -94,7 +94,8 @@ require ( github.com/gen2brain/jxl v0.2.0 github.com/goccy/go-yaml v1.19.2 github.com/nicksnyder/go-i18n/v2 v2.7.0 - golang.org/x/sys v0.49.0 + golang.org/x/image v0.46.0 + golang.org/x/sys v0.50.0 golang.org/x/text v0.43.0 ) @@ -127,7 +128,6 @@ require ( github.com/srwiley/rasterx v0.0.0-20220730225603-2ab79fcdd4ef // indirect github.com/stretchr/testify v1.11.1 // indirect github.com/yuin/goldmark v1.8.2 // indirect - golang.org/x/image v0.46.0 // indirect golang.org/x/net v0.62.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/go.sum b/go.sum index 061edca5..16531a00 100644 --- a/go.sum +++ b/go.sum @@ -74,8 +74,8 @@ golang.org/x/image v0.46.0 h1:b1+oYj0Jbp6K5MDT4i4/eZpYlk3V8SJhhDKh6LBHAyQ= golang.org/x/image v0.46.0/go.mod h1:3B3W05VGVQyuXucLINLjXKrqISASfi4Xj+iCVkLMwew= golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY= golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= -golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA= -golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs= +golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc= golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= diff --git a/internal/cli/generate.go b/internal/cli/generate.go index ae7fbeb3..086a752f 100644 --- a/internal/cli/generate.go +++ b/internal/cli/generate.go @@ -54,7 +54,7 @@ func generateFlagSet(errOut io.Writer, g *generateOpts) (*flag.FlagSet, func(io. fs.StringVar(&g.presetID, "preset", "", "build the set a named test question calls for. Run \"tfg preset list\" to see them") fs.StringVar(&g.formatID, "format", "", "format of the files to produce, for example txt") - fs.StringVar(&g.sizeStr, "size", "", "exact size of each file. Units count in 1024s, so 10mb is 10485760 bytes. Also accepts a plain byte count") + fs.StringVar(&g.sizeStr, "size", "", "exact size of each file. Units count in 1024s, so 10mb is 10485760 bytes. Also accepts a plain byte count, or smallest for a picture with its width and height set") fs.StringVar(&g.sizeRange, "size-range", "", "a size drawn from a range for each file, as 1kb-8kb. The draw comes from the seed, so the same seed gives the same sizes") fs.StringVar(&g.boundary, "boundary", "", "three files around a limit: one byte under it, the limit itself, one byte over") fs.IntVar(&g.count, "count", 1, "how many files to produce") @@ -352,6 +352,7 @@ func targetsFromFlags(g *generateOpts, given map[string]bool, errOut io.Writer) ID: g.id, Format: g.formatID, Sizes: sizes, + Smallest: g.sizeStr == core.SizeSmallest, Range: engine.SizeRange{Used: g.sizeRange != "", Min: rangeLow, Max: rangeHigh}, BoundaryLimit: boundaryLimit, NameTmpl: g.name, @@ -404,6 +405,11 @@ func sizesFromFlags(g *generateOpts, errOut io.Writer) (sizes []int64, low, high } return sizes, 0, 0, limit, ExitOK + case g.sizeStr == core.SizeSmallest: + // The count alone, as for a range. The engine plans each file at the + // smallest its format makes (engine.Target.Smallest). + return engine.Uniform(g.count, 0), 0, 0, 0, ExitOK + default: bytesWanted, err := core.ParseSize(g.sizeStr) if err != nil { @@ -548,6 +554,7 @@ func engineTarget(t recipe.Target, label bool) engine.Target { Sizes: t.Sizes, Contains: contentsOf(t), SizeFromContents: t.SizeFromContents, + Smallest: t.Smallest, Range: engine.SizeRange(t.Range), BoundaryLimit: t.BoundaryLimit, NameTmpl: t.Name, diff --git a/internal/core/size.go b/internal/core/size.go index 4f4b78ff..3f20a3c6 100644 --- a/internal/core/size.go +++ b/internal/core/size.go @@ -7,6 +7,14 @@ import ( "strings" ) +// SizeSmallest is the word a size can be instead of a number: the smallest +// file the format makes at its settings, with nothing added to reach a size. +// For a picture with its width and height set, that is the picture alone - a +// placeholder as a page would get it. It is not a number, so ParseSize refuses +// it and the two places that read a size ask for it by name first: a recipe +// (recipe.resolveSize) and the --size flag. docs/PLACEHOLDER-2026-11-14.md. +const SizeSmallest = "smallest" + // ParseSize turns a human written size into an exact number of bytes. // // 10mb -> 10 485 760 diff --git a/internal/damage/refusals.go b/internal/damage/refusals.go index def30e23..f42db116 100644 --- a/internal/damage/refusals.go +++ b/internal/damage/refusals.go @@ -305,9 +305,10 @@ func (e *EatenError) Said() core.Said { } // SizeConflict is the refusal a chain earns by changing the length of a file -// whose size comes from what it holds, or nil. -func (c Chain) SizeConflict(sizeFromContents bool) *NeedsSizeError { - if !sizeFromContents { +// whose size comes from what it holds, or that is the smallest its format +// makes, or nil. +func (c Chain) SizeConflict(sizeFromContents, smallest bool) *NeedsSizeError { + if !sizeFromContents && !smallest { return nil } steps, err := c.steps() @@ -316,7 +317,7 @@ func (c Chain) SizeConflict(sizeFromContents bool) *NeedsSizeError { } for _, s := range steps { if s.d.Length != nil { - return &NeedsSizeError{Damage: s.d.ID} + return &NeedsSizeError{Damage: s.d.ID, Smallest: smallest} } } return nil @@ -331,6 +332,10 @@ func (c Chain) SizeConflict(sizeFromContents bool) *NeedsSizeError { // section 4.8). type NeedsSizeError struct { Damage string + // Smallest says the target asked for the smallest file rather than for + // what it holds. The size is known there, so the reason is a different + // one: a cut or a tail makes the file something smallest does not say. + Smallest bool } // AboutSetting puts this on the size box, because naming a size is the half @@ -340,6 +345,10 @@ func (e *NeedsSizeError) AboutSetting() string { return "size" } func (e *NeedsSizeError) What() string { return e.what().String() } func (e *NeedsSizeError) what() core.Said { + if e.Smallest { + return core.Says("damage.NeedsSizeSmallestWhat", "%s changes the length of the file, and this target asks for the smallest file its format makes", + core.A("Damage", e.Damage)) + } return core.Says("damage.NeedsSizeWhat", "%s changes the length of the file, and this target takes its size from what it holds", core.A("Damage", e.Damage)) } @@ -347,6 +356,9 @@ func (e *NeedsSizeError) what() core.Said { func (e *NeedsSizeError) Why() string { return e.why().String() } func (e *NeedsSizeError) why() core.Said { + if e.Smallest { + return core.Says("damage.NeedsSizeSmallestWhy", "a file cut short or carrying more bytes is no longer the smallest one, so the two say different things about its size") + } return core.Says("damage.NeedsSizeWhy", "that size is only known once the file is written, so there is no length to work from") } diff --git a/internal/engine/crash.go b/internal/engine/crash.go index 68f1e17d..2466c030 100644 --- a/internal/engine/crash.go +++ b/internal/engine/crash.go @@ -83,7 +83,14 @@ const ( // // The context reaches a container's own planning (format.PlanWith), so a stop // lands between two of the files inside it rather than after the last. -func planWithoutCrashing(ctx context.Context, desc format.Descriptor, r format.Request) (p format.Plan, err error) { +func planWithoutCrashing(ctx context.Context, desc format.Descriptor, r format.Request) (format.Plan, error) { + return planGuarded(desc, func() (format.Plan, error) { return format.PlanWith(ctx, desc.Generator, r) }) +} + +// planGuarded runs one way of planning a file of desc, a panic in it becoming +// an ordinary error - the one plan above, or the walk to the smallest size +// that plans the file several times on its way (planFile). +func planGuarded(desc format.Descriptor, plan func() (format.Plan, error)) (p format.Plan, err error) { defer func() { v := recover() if v == nil { @@ -91,7 +98,7 @@ func planWithoutCrashing(ctx context.Context, desc format.Descriptor, r format.R } err = &GeneratorCrashError{Format: desc.ID, While: crashPlanning, Value: v} }() - return format.PlanWith(ctx, desc.Generator, r) + return plan() } // writeWithoutCrashing is the same around the write, so a crash costs one file diff --git a/internal/engine/damage.go b/internal/engine/damage.go index e2f0f76f..0db04c9a 100644 --- a/internal/engine/damage.go +++ b/internal/engine/damage.go @@ -57,7 +57,7 @@ func prepareDamage(t *Target, desc format.Descriptor) (format.Descriptor, error) if eaten := t.Damage.Eaten(); eaten != nil { return desc, eaten } - if sized := t.Damage.SizeConflict(t.SizeFromContents); sized != nil { + if sized := t.Damage.SizeConflict(t.SizeFromContents, t.Smallest); sized != nil { return desc, sized } if !t.Damage.ChangesLength() { @@ -84,19 +84,35 @@ func prepareDamage(t *Target, desc format.Descriptor) (format.Descriptor, error) // still applies to the finished archive, and the check that it moved a byte // still runs - what is missing is only the early refusal. // +// A target asking for the smallest file is left alone here for the same +// reason, its Sizes are a count, and asked per file instead (planFile): its +// size is known once each file is planned, still before the first byte. A +// 1x1 BMP is 58 B, and zero-head with 4096 B would blank all 58 and leave a +// manifest promising 4096. +// // A chain that changes the length is left to the format it plans through // (damagedformat.go), which knows the format's floor as well as the damage's // and names the larger. Asked here, a PNG with junk appended would be told 64 // B is enough and then refused at 64 B for needing 138. func checkDamageFloor(t *Target) error { - if len(t.Damage) == 0 || t.SizeFromContents || t.Damage.ChangesLength() { + if t.SizeFromContents || t.Smallest { + return nil + } + return checkFloorOf(t, t.Sizes...) +} + +// checkFloorOf refuses a file smaller than the damage it was given, for a +// chain that keeps the length. Several sizes in one call, so a target of a +// million files works its floor out once. +func checkFloorOf(t *Target, sizes ...int64) error { + if len(t.Damage) == 0 || t.Damage.ChangesLength() { return nil } floor, owner, err := t.Damage.Floor() if err != nil { return err } - for _, size := range t.Sizes { + for _, size := range sizes { if size < floor { return &damage.TooSmallError{Damage: owner, Requested: size, Floor: floor} } diff --git a/internal/engine/drawsizes.go b/internal/engine/drawsizes.go index 75104294..b5fc0c10 100644 --- a/internal/engine/drawsizes.go +++ b/internal/engine/drawsizes.go @@ -110,7 +110,7 @@ func firstWritable(ctx context.Context, desc format.Descriptor, r format.Request // refusal about the size, so firstWritable hands it straight back. func drawSizes(ctx context.Context, t *Target, desc format.Descriptor, targetSeed uint64) error { damaged := t.Damage.Label() - first := requestFor(t, core.FileSeed(targetSeed, 0), damaged) + first := requestFor(t, 0, core.FileSeed(targetSeed, 0), damaged) // The low end is judged against what this format can do AT ALL, and that // check is older than the snapping below it. The two answer different @@ -151,7 +151,7 @@ func drawSizes(ctx context.Context, t *Target, desc format.Descriptor, targetSee want = t.Range.Min + int64(r.Uint64N(span+1)) } - req := requestFor(t, core.FileSeed(targetSeed, i), damaged) + req := requestFor(t, i, core.FileSeed(targetSeed, i), damaged) got, err := firstWritable(ctx, desc, req, want, t.Range.Max) if err != nil && want > t.Range.Min { diff --git a/internal/engine/engine.go b/internal/engine/engine.go index 7ce12f68..5708ffa0 100644 --- a/internal/engine/engine.go +++ b/internal/engine/engine.go @@ -40,6 +40,15 @@ type Target struct { // from Contains. The entries in Sizes then only carry the count, and their // value is not read. SizeFromContents bool + // Smallest says no size was named and each file is the smallest its + // format makes at its settings (core.SizeSmallest). Sizes then only carry + // the count, as for SizeFromContents, and the size comes from planning - + // so a dry run still reports it to the byte (AR10). + // + // Apart from SizeFromContents rather than a second spelling of it, because + // a container with an empty list of contents is a legal archive with + // nothing in it, and the two must not read as one. + Smallest bool // Range says the sizes are drawn rather than stated, and Sizes then arrives // carrying only the count. // @@ -300,6 +309,9 @@ func settleTarget(ctx context.Context, t *Target, opt Options, seen map[string]b if len(t.Contains) > 0 && desc.Container == nil { return format.Descriptor{}, &format.NotAContainerError{Format: t.Format, Containers: format.Containers()} } + if err := checkSmallest(t, desc); err != nil { + return format.Descriptor{}, err + } desc, err = prepareDamage(t, desc) if err != nil { diff --git a/internal/engine/plantarget.go b/internal/engine/plantarget.go index 54458096..a86591ce 100644 --- a/internal/engine/plantarget.go +++ b/internal/engine/plantarget.go @@ -42,9 +42,9 @@ func (pl *planning) files(ctx context.Context, t *Target, desc format.Descriptor for idx, size := range t.Sizes { fileSeed := core.FileSeed(targetSeed, idx) - r := requestFor(t, fileSeed, damaged) + r := requestFor(t, idx, fileSeed, damaged) r.Bytes = size - p, err := planWithoutCrashing(ctx, desc, r) + p, err := planFile(ctx, t, desc, r) if err != nil { return atTarget(position, t, err) } @@ -182,9 +182,11 @@ func (pl *planning) startList(ctx context.Context) error { // generator settles. // // damaged is t.Damage.Label(), asked once a target by the caller rather than -// once a file, because it resolves every entry against the registry. -func requestFor(t *Target, seed uint64, damaged string) format.Request { +// once a file, because it resolves every entry against the registry. idx is +// the file's place in t from nought, as renderName takes it. +func requestFor(t *Target, idx int, seed uint64, damaged string) format.Request { return format.Request{ + Number: idx + 1, SizeFromContents: t.SizeFromContents, Contains: t.Contains, Seed: seed, diff --git a/internal/engine/smallest.go b/internal/engine/smallest.go new file mode 100644 index 00000000..a607df3c --- /dev/null +++ b/internal/engine/smallest.go @@ -0,0 +1,69 @@ +package engine + +import ( + "context" + "strings" + + "github.com/donislawdev/TestingFilesGenerator/internal/core" + "github.com/donislawdev/TestingFilesGenerator/internal/format" +) + +// The fifth way of stating a size (ARCHITECTURE.md section 9, AR10): a target +// says smallest and each file is the smallest its format makes at its +// settings. The rule AR10 exists for still holds - the size is known while +// planning, so a dry run reports it to the byte and nothing is written before +// a refusal - because the plan of a picture with its width and height set +// encodes the picture and knows what it comes to. +// +// For pictures only, and only with their width and height known: the owner's +// decision of 2026-11-14 (docs/PLACEHOLDER-2026-11-14.md section 10). Without +// them a picture is chosen to fit the bytes asked for, so there is nothing to +// be the smallest of, and the smallest file of the other formats is an answer +// nobody has asked a question for yet. + +// checkSmallest refuses smallest for a target it cannot answer. +func checkSmallest(t *Target, desc format.Descriptor) error { + if !t.Smallest { + return nil + } + if !strings.HasPrefix(desc.MediaType, "image/") { + return &RecipeError{Setting: format.SettingSize, + Detail: core.Says("engine.SmallestNotAPicture", "target %q asks for the smallest %s file, and smallest is for pictures", core.A("Target", t.ID), core.A("Format", desc.ID)), + Because: core.Says("engine.SmallestNotAPictureWhy", "a picture with its width and height set has one smallest file, the picture with nothing added to reach a size"), + Remedy: core.Says("engine.SmallestNotAPictureFix", "Give the target a size such as 2mb, or choose a picture format")} + } + for _, side := range []string{"width", "height"} { + if t.Properties[side] == "" && declaredDefault(desc, side) == "" { + return &RecipeError{Setting: format.SettingSize, + Detail: core.Says("engine.SmallestNeedsASize", "target %q asks for the smallest %s and does not say how large the picture is", core.A("Target", t.ID), core.A("Format", desc.ID)), + Because: core.Says("engine.SmallestNeedsASizeWhy", "without a width and a height the picture is chosen to fit the bytes asked for, so there is no picture to be the smallest of"), + Remedy: core.Says("engine.SmallestNeedsASizeFix", "Set width and height, such as width 1920 and height 1080, or give the target a size")} + } + } + return nil +} + +// declaredDefault is what a format declares a setting to be when nothing says, +// or nothing when it works the value out itself. +func declaredDefault(desc format.Descriptor, name string) string { + for _, p := range desc.Properties { + if p.Name == name { + return p.Default + } + } + return "" +} + +// planFile is the plan of one file: at the size asked for, or at the smallest +// its format makes when the target says smallest - and then held to the floor +// of its damage, which checkDamageFloor could not ask before the size existed. +func planFile(ctx context.Context, t *Target, desc format.Descriptor, r format.Request) (format.Plan, error) { + if !t.Smallest { + return planWithoutCrashing(ctx, desc, r) + } + p, err := planGuarded(desc, func() (format.Plan, error) { return desc.PlanSmallest(ctx, r) }) + if err != nil { + return p, err + } + return p, checkFloorOf(t, p.Bytes) +} diff --git a/internal/format/format.go b/internal/format/format.go index 548e8b2d..e1d3e202 100644 --- a/internal/format/format.go +++ b/internal/format/format.go @@ -521,35 +521,55 @@ func (p Property) Allowed() string { // difference costs twelve on its own - so this steps by one when a refusal // names nothing higher, rather than assuming the answer only ever grows. func (d Descriptor) SmallestAccepted(r Request) int64 { - r.SizeFromContents = false + p, err := d.smallest(d.Generator.Plan, r) + if err != nil { + // Refused for a reason that is not about size - a property this + // request cannot have, say - or never settled. The structural floor is + // the honest answer left. + return d.MinBytes + } + return p.Bytes +} + +// PlanSmallest is the plan of the smallest file this format makes for a +// request shaped like r, which is what a size of core.SizeSmallest asks for. +// +// The same walk as SmallestAccepted, and the plan it ends on rather than the +// number, so the file is planned once rather than walked to and planned again. +// A refusal that is not about the size is handed back as it is - a colour the +// format cannot read is the answer somebody needs, not a floor. +func (d Descriptor) PlanSmallest(ctx context.Context, r Request) (Plan, error) { + return d.smallest(func(r Request) (Plan, error) { return PlanWith(ctx, d.Generator, r) }, r) +} + +// smallestRounds is far more than any format needs: each round either settles +// or jumps to a number the format itself named. It is here so that a generator +// whose refusals ever cycle costs a refusal rather than a run that never ends. +const smallestRounds = 64 - // Sixty four rounds is far more than any format needs: each round either - // settles or jumps to a number the format itself named. It is here so that - // a generator whose refusals ever cycle costs a wrong number rather than a - // run that never ends. +// smallest walks plan from nought to the first size it accepts. +func (d Descriptor) smallest(plan func(Request) (Plan, error), r Request) (Plan, error) { + r.SizeFromContents = false size := int64(0) - for round := 0; round < 64; round++ { + for round := 0; round < smallestRounds; round++ { r.Bytes = size - if _, err := d.Generator.Plan(r); err == nil { - return size - } else { - var below *BelowMinimumError - if !errors.As(err, &below) { - // Refused for a reason that is not about size - a property this - // request cannot have, say. The structural floor is the honest - // answer left. - return d.MinBytes - } - if below.Minimum > size { - size = below.Minimum - continue - } - // The refusal names nothing above where we already are, so this is - // a size inside a band the format cannot reach. Step past it. - size++ + p, err := plan(r) + if err == nil { + return p, nil + } + var below *BelowMinimumError + if !errors.As(err, &below) { + return Plan{}, err + } + if below.Minimum > size { + size = below.Minimum + continue } + // The refusal names nothing above where we already are, so this is a + // size inside a band the format cannot reach. Step past it. + size++ } - return d.MinBytes + return Plan{}, core.Defect(fmt.Errorf("%s: the smallest file did not settle in %d rounds, the last at %d B", d.ID, smallestRounds, size)) } // PropertyNames is the declared keys, in the order the format listed them. @@ -692,6 +712,11 @@ type Request struct { // format that leaves this alone writes as it always did, and the cut the // manifest reports says so (docs/TRUNCATE-2026-11-11.md section 7.2). CutAt int64 + // Number is the file's place in its target, counted from one as its name + // counts it - hero_0007.png is number 7. Zero for a file that is not one + // of a target's own, such as a picture inside an archive. Read by a + // placeholder that writes {index} into its picture, and by nothing else. + Number int // Properties are format specific settings, straight from the recipe. Properties map[string]string } diff --git a/internal/format/jpg/jpg.go b/internal/format/jpg/jpg.go index 37884806..2c7249d3 100644 --- a/internal/format/jpg/jpg.go +++ b/internal/format/jpg/jpg.go @@ -27,6 +27,7 @@ import ( "github.com/donislawdev/TestingFilesGenerator/internal/format" "github.com/donislawdev/TestingFilesGenerator/internal/format/imagedim" "github.com/donislawdev/TestingFilesGenerator/internal/format/imagelabel" + "github.com/donislawdev/TestingFilesGenerator/internal/format/placeholder" ) const ( @@ -117,7 +118,7 @@ func init() { }, Label: format.LabelVisible, Oracle: "pillow", - Properties: []format.Property{ + Properties: append([]format.Property{ imagedim.Width(imagedim.Side{Largest: maxDimension, Detail: "How wide the picture is. Left out, a size is chosen that fits the bytes you asked for."}), imagedim.Height(imagedim.Side{Largest: maxDimension, @@ -127,7 +128,7 @@ func init() { Min: minQuality, Max: maxQuality, Default: strconv.Itoa(defaultQuality), Detail: "How much detail survives compression, from 1 to 100. JPEG throws detail away by design, so a low number gives a visibly softer picture. It changes how large the picture encodes to, not the size of the file you asked for.", }, - }, + }, placeholder.Properties()...), JointLimits: []format.JointLimit{{ Of: "width", By: "height", Max: maxPixels, Unit: "megapixels", Per: 1_000_000, Base: "pixels", @@ -145,6 +146,10 @@ type memo struct { quality int seed uint64 label string + // look is what the picture shows, and text the words of a placeholder + // with this file's numbers in them. A test picture has neither. + look placeholder.Settings + text string // body is the exact number of bytes the encoded picture takes, start // marker included. Worked out during planning so that a size this format // cannot reach is refused before any file exists. @@ -201,6 +206,10 @@ func segmentsFor(extra int64) (segments int, payload int64) { } func (generator) Plan(r format.Request) (format.Plan, error) { + look, err := placeholder.Read("jpg", r.Properties) + if err != nil { + return format.Plan{}, err + } label := "" if r.Label { label = r.LabelText("jpg") @@ -211,7 +220,7 @@ func (generator) Plan(r format.Request) (format.Plan, error) { return format.Plan{}, err } - m, err := chooseSize(r, label, quality) + m, err := chooseSize(r, label, quality, look) if err != nil { return format.Plan{}, err } @@ -258,19 +267,34 @@ func (generator) Plan(r format.Request) (format.Plan, error) { } } m.segments, m.padPayload = segmentsFor(r.Bytes - bare) + p.Holds = holdsPerPixel * int64(w) * int64(h) + + m.claim(&p, label) + p.Memo = m + return p, nil +} - if r.Label && !imagelabel.Fits(w, len(label)) { +// claim says in the plan whether the picture carries its label, and for a +// placeholder what it shows, each in the words of the package that draws it. +// label is empty when the request asked for none. +func (m memo) claim(p *format.Plan, label string) { + w, h := m.width, m.height + if m.look.Placeholder() { + drawn := placeholder.Measure(w, h, m.look.Look(m.text, label)) + p.Properties[format.PropertyLabelEmbedded], p.Notes = placeholder.Claim(drawn, label, w, h, p.Notes) + m.look.Describe(p.Properties, m.text, drawn) + return + } + if label != "" && !imagelabel.Fits(w, len(label)) { p.Notes = append(p.Notes, format.Note{ Code: "label_omitted", Detail: core.Says("format.ThePictureIsPxWideAnd", "The picture is %d px wide and the label needs more room, so this file carries no visible label. Its name and the manifest still identify it.", core.A("Width", w)), }) } - labelled := r.Label && imagelabel.Fits(w, len(label)) + labelled := label != "" && imagelabel.Fits(w, len(label)) labelled, p.Notes = imagelabel.Claim(labelled, w, h, len(label), p.Notes) p.Properties[format.PropertyLabelEmbedded] = labelled - p.Memo = m - p.Holds = holdsPerPixel * int64(w) * int64(h) - return p, nil + m.look.Describe(p.Properties, "", placeholder.Drawn{}) } // holdsPerPixel is what writing one of these holds at once for each pixel of @@ -343,7 +367,10 @@ var sizeLadder = [][2]int{ } // chooseSize settles the picture size and measures what it encodes to. -func chooseSize(r format.Request, label string, q int) (memo, error) { +func chooseSize(r format.Request, label string, q int, look placeholder.Settings) (memo, error) { + at := func(w, h int) memo { + return memo{width: w, height: h, quality: q, seed: r.Seed, label: label, look: look, text: look.Expand(r.Number, w, h)} + } _, wSet := r.Properties["width"] _, hSet := r.Properties["height"] @@ -359,7 +386,7 @@ func chooseSize(r format.Request, label string, q int) (memo, error) { if err := checkJointLimits(w, h); err != nil { return memo{}, err } - m := memo{width: w, height: h, quality: q, seed: r.Seed, label: label} + m := at(w, h) body, err := encodedSize(m) if err != nil { return memo{}, err @@ -370,7 +397,7 @@ func chooseSize(r format.Request, label string, q int) (memo, error) { var smallest memo for _, rung := range sizeLadder { - m := memo{width: rung[0], height: rung[1], quality: q, seed: r.Seed, label: label} + m := at(rung[0], rung[1]) body, err := encodedSize(m) if err != nil { return memo{}, err @@ -407,6 +434,10 @@ func qualityOf(props map[string]string) (int, error) { // requested size. func picture(m memo) image.Image { img := image.NewRGBA(image.Rect(0, 0, m.width, m.height)) + if m.look.Placeholder() { + placeholder.Draw(img, m.look.Look(m.text, m.label)) + return img + } // The seed shifts the gradient, so two seeds give visibly different // pictures rather than the same picture with different padding. off := int(m.seed % 256) @@ -572,49 +603,3 @@ func writeComments(ctx context.Context, w io.Writer, seed uint64, segments int, } return nil } - -// counter counts bytes and keeps none. -type counter struct{ n int64 } - -func (c *counter) Write(p []byte) (int, error) { - c.n += int64(len(p)) - return len(p), nil -} - -// headSkipper drops the first keep bytes and passes the rest through, so the -// encoder's own start marker does not follow the padding we already wrote. -// -// It also holds on to what it dropped, because a stream that does not begin -// with the start marker means the encoder changed under us, and writing the -// rest of it after our own marker would produce a file nobody could read. -type headSkipper struct { - w io.Writer - keep int - head []byte - written int64 -} - -func (h *headSkipper) Write(p []byte) (int, error) { - n := len(p) - if len(h.head) < h.keep { - take := h.keep - len(h.head) - if take > len(p) { - take = len(p) - } - h.head = append(h.head, p[:take]...) - p = p[take:] - } - if len(p) == 0 { - return n, nil - } - written, err := h.w.Write(p) - h.written += int64(written) - return n, err -} - -func (h *headSkipper) check() error { - if len(h.head) != soiSize || h.head[0] != 0xFF || h.head[1] != 0xD8 { - return core.Defect(fmt.Errorf("jpg: the encoder did not begin with the start of image marker, got % x", h.head)) - } - return nil -} diff --git a/internal/format/jpg/stream.go b/internal/format/jpg/stream.go new file mode 100644 index 00000000..43ac45e0 --- /dev/null +++ b/internal/format/jpg/stream.go @@ -0,0 +1,57 @@ +package jpg + +import ( + "fmt" + "io" + + "github.com/donislawdev/TestingFilesGenerator/internal/core" +) + +// What the encoder's stream passes through on its way to a file: a count +// while planning, and the start marker taken off while writing. + +// counter counts bytes and keeps none. +type counter struct{ n int64 } + +func (c *counter) Write(p []byte) (int, error) { + c.n += int64(len(p)) + return len(p), nil +} + +// headSkipper drops the first keep bytes and passes the rest through, so the +// encoder's own start marker does not follow the padding we already wrote. +// +// It also holds on to what it dropped, because a stream that does not begin +// with the start marker means the encoder changed under us, and writing the +// rest of it after our own marker would produce a file nobody could read. +type headSkipper struct { + w io.Writer + keep int + head []byte + written int64 +} + +func (h *headSkipper) Write(p []byte) (int, error) { + n := len(p) + if len(h.head) < h.keep { + take := h.keep - len(h.head) + if take > len(p) { + take = len(p) + } + h.head = append(h.head, p[:take]...) + p = p[take:] + } + if len(p) == 0 { + return n, nil + } + written, err := h.w.Write(p) + h.written += int64(written) + return n, err +} + +func (h *headSkipper) check() error { + if len(h.head) != soiSize || h.head[0] != 0xFF || h.head[1] != 0xD8 { + return core.Defect(fmt.Errorf("jpg: the encoder did not begin with the start of image marker, got % x", h.head)) + } + return nil +} diff --git a/internal/format/placeholder/draw.go b/internal/format/placeholder/draw.go new file mode 100644 index 00000000..ad06ca98 --- /dev/null +++ b/internal/format/placeholder/draw.go @@ -0,0 +1,386 @@ +package placeholder + +import ( + "image" + "image/color" + "strings" + + "github.com/donislawdev/TestingFilesGenerator/internal/format/placeholder/glyphs" + "github.com/donislawdev/TestingFilesGenerator/internal/format/placeholder/raster" +) + +// Look is what one placeholder picture shows. Text is already expanded - the +// tokens of the setting replaced for this file. +type Look struct { + Text string + Label string + Background color.RGBA + Foreground color.RGBA + Guides bool +} + +// Drawn is what a picture ended up carrying. A text or a label that does not +// fit is left out rather than squeezed below what can be read, and the caller +// says so in the manifest (rule 6). +type Drawn struct { + Text bool + Label bool +} + +// MinType is the smallest size of type, in pixels to the em, a text or a label +// is set in. Below it the capitals are under seven pixels tall and a digit is +// a smudge, so the words are left out and the manifest says why. +const MinType = 10 + +// The share of the picture the text may take: four fifths of the width, and a +// line a quarter of the height. A label is a quarter of the size of the text +// and may take nine tenths of the width. +const ( + textWidthNum, textWidthDen = 8, 10 + lineHeightDen = 4 + labelShareDen = 4 + labelWidthNum, labelWidthDen = 9, 10 +) + +type line struct { + text string + size int64 // pixels to the em, 0 when the line is not drawn + x int64 // left end of the pen, in coordinates + baseline int64 // in coordinates + // span is how wide the line is taken to be, in units of the font: its + // advance, or for the label the bound labelAdvance gives. + span int64 +} + +type layout struct { + main, label line + plate image.Rectangle +} + +// Measure is what Draw would carry on a picture of w by h, without drawing - +// what a plan asks before any pixel exists. +func Measure(w, h int, l Look) Drawn { + lay := arrange(glyphs.Inter(), int64(w), int64(h), l) + return Drawn{Text: lay.main.size > 0, Label: lay.label.size > 0} +} + +func arrange(f *glyphs.Face, w, h int64, l Look) layout { + upm := int64(f.UnitsPerEm) + var lay layout + if adv := f.Advance(l.Text); adv > 0 { + lay.main = line{text: l.Text, span: adv, size: readable(min(textWidthNum*w*upm/(textWidthDen*adv), + h*upm/(lineHeightDen*int64(f.Ascent+f.Descent))))} + } + if adv := labelAdvance(f, l.Label); adv > 0 { + lay.label = line{text: l.Label, span: adv, size: readable(min(max(lay.main.size/labelShareDen, MinType), + labelWidthNum*w*upm/(labelWidthDen*adv)))} + } + top, bottom := block(f, lay, h) + if bottom > h*raster.One && lay.label.size > 0 { + // The label goes first. It says what the file is, the text is what + // the picture is for. + lay.label = line{} + top, bottom = block(f, lay, h) + } + lay.main.baseline = top + capOf(f, lay.main.size) + lay.label.baseline = bottom - descOf(f, lay.label.size) + lay.main.x = centred(f, lay.main, w) + lay.label.x = centred(f, lay.label, w) + lay.plate = plateOf(lay, w, h, top, bottom) + return lay +} + +// readable is size, or nought when it is below the smallest type set. +func readable(size int64) int64 { + if size < MinType { + return 0 + } + return size +} + +func capOf(f *glyphs.Face, size int64) int64 { + return int64(f.CapHeight) * size * raster.One / int64(f.UnitsPerEm) +} + +func descOf(f *glyphs.Face, size int64) int64 { + return int64(f.Descent) * size * raster.One / int64(f.UnitsPerEm) +} + +// block is where the lines stand together, centred on the height: from the +// top of the capitals of the first to the foot of the descenders of the last, +// with half a capital between them. +func block(f *glyphs.Face, lay layout, h int64) (top, bottom int64) { + height, last := int64(0), lay.main.size + if lay.main.size > 0 { + height += capOf(f, lay.main.size) + } + if lay.label.size > 0 { + height += capOf(f, lay.main.size)/2 + capOf(f, lay.label.size) + last = lay.label.size + } + top = (h*raster.One - height) / 2 + return top, top + height + descOf(f, last) +} + +// numerals are the characters a label's numbers are written in: the size in +// decimal and the seed in hexadecimal. +const numerals = "0123456789abcdef" + +// labelAdvance is how wide the label is taken to be wherever its width decides +// something - its size and the plate behind it: every numeral counted as the +// widest of them. +// +// The label states a seed in eight numerals, and which ones came up changes +// how wide they are - measured on 2026-11-14, a drawing's smallest size moved +// by 2.5 kB between ten seeds while its picture stayed the same. A layout +// taken from the real width would make what a file of these settings needs +// depend on its seed, and the smallest size the tool announces has to hold +// for every seed. The cost is a label a hair smaller where the width is what +// limits it. The letters of words that happen to be numerals, such as the a of +// damage, are counted the same way, which only widens the bound. +func labelAdvance(f *glyphs.Face, label string) int64 { + widest := int64(0) + for _, r := range numerals { + if g, ok := f.Glyph(r); ok { + widest = max(widest, int64(g.Advance)) + } + } + var adv int64 + for _, r := range label { + if strings.ContainsRune(numerals, r) { + adv += widest + } else if g, ok := f.Glyph(r); ok { + adv += int64(g.Advance) + } + } + return adv +} + +// centred is where the pen starts for ln to stand in the middle of the width. +func centred(f *glyphs.Face, ln line, w int64) int64 { + return (w*raster.One - f.Advance(ln.text)*ln.size*raster.One/int64(f.UnitsPerEm)) / 2 +} + +// plateOf is the rectangle of background the lines stand on, an eighth of the +// larger size clear around them, inside the picture. +func plateOf(lay layout, w, h, top, bottom int64) image.Rectangle { + if lay.main.size == 0 && lay.label.size == 0 { + return image.Rectangle{} + } + pad := max(lay.main.size, lay.label.size) / 8 * raster.One + x0, x1 := w*raster.One, int64(0) + for _, ln := range []line{lay.main, lay.label} { + if ln.size > 0 { + left := (w*raster.One - ln.span*ln.size*raster.One/int64(glyphs.Inter().UnitsPerEm)) / 2 + x0, x1 = min(x0, left), max(x1, w*raster.One-left) + } + } + return image.Rect(int((x0-pad)>>raster.Frac), int((top-pad)>>raster.Frac), + int((x1+pad+raster.One-1)>>raster.Frac), int((bottom+pad+raster.One-1)>>raster.Frac)). + Intersect(image.Rect(0, 0, int(w), int(h))) +} + +// Scene is a placeholder of w by h as shapes rather than pixels. Draw fills +// these and a format that draws in vectors writes them, so a drawing and a +// picture of one look are the same shapes to the 256th of a pixel. +// +// Laid out in order: the background over the whole picture, the guides in the +// foreground colour, the plate in the background colour, then the text and the +// label in the foreground colour. +type Scene struct { + // Guides are the frame, the two diagonals and the circle, each filled on + // its own - see guides. Nil without guides. + Guides []*raster.Path + // Plate is the background the lines stand on, so a guide never runs + // through a letter. Empty without guides, where nothing runs there. + Plate image.Rectangle + // Text is the outline of the words, nil when they did not fit. + Text *raster.Path + // Label is the outline of the label, nil when it did not fit or there is + // none. LabelSize and LabelBaseline are where it stands - pixels to the em + // and 256ths of a pixel down - for a format that writes it as words rather + // than as shapes. It stands in the middle of the width. + Label *raster.Path + LabelSize int64 + LabelBaseline int64 + Drawn Drawn +} + +// Shapes is the scene of l on a picture of w by h. +func Shapes(w, h int, l Look) Scene { + var s Scene + if l.Guides { + s.Guides = guides(int64(w), int64(h)) + } + f := glyphs.Inter() + lay := arrange(f, int64(w), int64(h), l) + if l.Guides { + s.Plate = lay.plate + } + if lay.main.size > 0 { + s.Text = textPath(f, lay.main) + } + if lay.label.size > 0 { + s.Label = textPath(f, lay.label) + s.LabelSize, s.LabelBaseline = lay.label.size, lay.label.baseline + } + s.Drawn = Drawn{Text: s.Text != nil, Label: s.Label != nil} + return s +} + +// Draw paints l over the whole of img: the scene of its size, filled. +func Draw(img *image.RGBA, l Look) Drawn { + b := img.Bounds() + w, h := b.Dx(), b.Dy() + s := Shapes(w, h, l) + fillRect(img, image.Rect(0, 0, w, h), l.Background) + plot := func(x, y int, a uint8) { blend(img, x, y, l.Foreground, a) } + for _, g := range s.Guides { + raster.Fill(g, w, h, plot) + } + fillRect(img, s.Plate, l.Background) + for _, ln := range []*raster.Path{s.Text, s.Label} { + if ln != nil { + raster.Fill(ln, w, h, plot) + } + } + return s.Drawn +} + +// fillRect sets every pixel of r to c, opaque. +func fillRect(img *image.RGBA, r image.Rectangle, c color.RGBA) { + for y := r.Min.Y; y < r.Max.Y; y++ { + row := img.Pix[y*img.Stride+r.Min.X*4 : y*img.Stride+r.Max.X*4] + for x := 0; x < len(row); x += 4 { + row[x], row[x+1], row[x+2], row[x+3] = c.R, c.G, c.B, 255 + } + } +} + +// blend lays colour c over the pixel at x, y with coverage a out of 255. +func blend(img *image.RGBA, x, y int, c color.RGBA, a uint8) { + i := y*img.Stride + x*4 + p := img.Pix[i : i+4 : i+4] + k, rest := int(a), 255-int(a) + p[0] = uint8((int(c.R)*k + int(p[0])*rest + 127) / 255) + p[1] = uint8((int(c.G)*k + int(p[1])*rest + 127) / 255) + p[2] = uint8((int(c.B)*k + int(p[2])*rest + 127) / 255) + p[3] = 255 +} + +// textPath is the outline of one line of text, the pen moving in units of the +// font so rounding never builds up along a long line. No kerning - see +// glyphs.Face.Advance. +func textPath(f *glyphs.Face, ln line) *raster.Path { + p := raster.NewPath() + upm := int64(f.UnitsPerEm) + var pen int64 + for _, r := range ln.text { + g, _ := f.Glyph(r) + at := func(pt glyphs.Point) (int64, int64) { + return ln.x + (pen+int64(pt.X))*ln.size*raster.One/upm, + ln.baseline + int64(pt.Y)*ln.size*raster.One/upm + } + outline(p, g, at) + pen += int64(g.Advance) + } + return p +} + +// outline adds the contours of one letter, its points placed by at. +func outline(p *raster.Path, g glyphs.Glyph, at func(glyphs.Point) (int64, int64)) { + k := 0 + for _, op := range g.Ops { + switch op { + case glyphs.MoveTo: + p.MoveTo(at(g.Points[k])) + case glyphs.LineTo: + p.LineTo(at(g.Points[k])) + case glyphs.QuadTo: + cx, cy := at(g.Points[k]) + x, y := at(g.Points[k+1]) + p.QuadTo(cx, cy, x, y) + k++ + } + k++ + } + p.Close() +} + +// guides is the frame along the edges, the two diagonals and the circle that +// touches the frame: after an upload a missing edge is a crop, diagonals that +// no longer meet at the centre are a crop off centre, and an oval is a +// stretch. +// +// Four outlines filled one by one rather than one outline. Where two shapes +// wound in opposite directions overlap, the non-zero rule counts the overlap +// as outside, and the first drawing had a pale dot wherever a diagonal +// crossed the circle. Drawn one over the other they cannot cancel, and the +// colour laid twice is the same colour. +func guides(w, h int64) []*raster.Path { + t := max(1, min(w, h)/200) * raster.One + W, H := w*raster.One, h*raster.One + + frame := raster.NewPath() + rect := func(x0, y0, x1, y1 int64) { + frame.MoveTo(x0, y0) + frame.LineTo(x1, y0) + frame.LineTo(x1, y1) + frame.LineTo(x0, y1) + frame.Close() + } + rect(0, 0, W, t) + rect(0, H-t, W, H) + rect(0, t, t, H-t) + rect(W-t, t, W, H-t) + out := []*raster.Path{frame} + + length := raster.Isqrt(w*w + h*h) + if length > 0 { + ox, oy := h*t/(2*length), w*t/(2*length) + bar := func(x0, y0, x1, y1, sx, sy int64) *raster.Path { + p := raster.NewPath() + p.MoveTo(x0+sx, y0+sy) + p.LineTo(x1+sx, y1+sy) + p.LineTo(x1-sx, y1-sy) + p.LineTo(x0-sx, y0-sy) + p.Close() + return p + } + out = append(out, bar(0, 0, W, H, ox, -oy), bar(W, 0, 0, H, -ox, -oy)) + } + + ring := raster.NewPath() + cx, cy := W/2, H/2 + r := min(W, H) / 2 + circle(ring, cx, cy, r, false) + if r > t { + circle(ring, cx, cy, r-t, true) + } + return append(out, ring) +} + +// circle adds a circle of radius r as eight quadratic arcs, clockwise on +// screen, or the other way round to cut a hole. The arcs stray from the true +// circle by under a thousandth of the radius. +func circle(p *raster.Path, cx, cy, r int64, reverse bool) { + // cos 45 and tan 22.5 degrees as fractions of 65536. + d := r * 46341 / 65536 + k := r * 27146 / 65536 + on := [8][2]int64{{r, 0}, {d, d}, {0, r}, {-d, d}, {-r, 0}, {-d, -d}, {0, -r}, {d, -d}} + ctl := [8][2]int64{{r, k}, {k, r}, {-k, r}, {-r, k}, {-r, -k}, {-k, -r}, {k, -r}, {r, -k}} + if !reverse { + p.MoveTo(cx+on[0][0], cy+on[0][1]) + for i := 0; i < 8; i++ { + n := on[(i+1)%8] + p.QuadTo(cx+ctl[i][0], cy+ctl[i][1], cx+n[0], cy+n[1]) + } + } else { + p.MoveTo(cx+on[0][0], cy+on[0][1]) + for i := 7; i >= 0; i-- { + n := on[i] + p.QuadTo(cx+ctl[i][0], cy+ctl[i][1], cx+n[0], cy+n[1]) + } + } + p.Close() +} diff --git a/internal/format/placeholder/glyphs/carry.go b/internal/format/placeholder/glyphs/carry.go new file mode 100644 index 00000000..9610f7bc --- /dev/null +++ b/internal/format/placeholder/glyphs/carry.go @@ -0,0 +1,15 @@ +package glyphs + +import "github.com/donislawdev/TestingFilesGenerator/internal/legal" + +// The outlines announce themselves to the licence registry the moment this +// package is linked, which is how "tfg license" and the bill of materials know +// that a binary carries a part of Inter. internal/gui/font/carry.go says why +// it is done this way rather than read from the build. +func init() { + legal.Carrying(packagePath) +} + +// packagePath is this package as go list spells it, which is the spelling the +// registry entry carries. +const packagePath = "github.com/donislawdev/TestingFilesGenerator/internal/format/placeholder/glyphs" diff --git a/internal/format/placeholder/glyphs/fromttf/fromttf.go b/internal/format/placeholder/glyphs/fromttf/fromttf.go new file mode 100644 index 00000000..e596eb56 --- /dev/null +++ b/internal/format/placeholder/glyphs/fromttf/fromttf.go @@ -0,0 +1,185 @@ +// Package fromttf turns a TrueType font into the outline file package glyphs +// reads. It runs when the file is made and when a guard checks the file still +// is the font - it is never part of a binary, which is why it may parse a font +// with golang.org/x/image while the binaries do not. +package fromttf + +import ( + "bytes" + "encoding/binary" + "errors" + "fmt" + + "golang.org/x/image/font" + "golang.org/x/image/font/sfnt" + "golang.org/x/image/math/fixed" + + "github.com/donislawdev/TestingFilesGenerator/internal/core" + "github.com/donislawdev/TestingFilesGenerator/internal/format/placeholder/glyphs" +) + +// Range is a run of letters, both ends included. +type Range struct{ First, Last rune } + +// Subset is what the placeholder typeface carries: printable ASCII, the +// Latin-1 and Latin Extended-A letters (Polish, Czech, Turkish and the rest +// of Europe), Greek, the Cyrillic of Russian, Ukrainian, Belarusian, Serbian +// and Bulgarian, and the punctuation a product name or a caption uses. A +// letter of a range the font does not carry is left out rather than drawn as +// an empty box, and a text asking for it is refused. +var Subset = []Range{ + {0x0020, 0x007E}, + {0x00A0, 0x00FF}, + {0x0100, 0x017F}, + {0x0370, 0x03FF}, + {0x0400, 0x045F}, + {0x2010, 0x2027}, + {0x2030, 0x2030}, + {0x2039, 0x203A}, + {0x20AC, 0x20AC}, + {0x2116, 0x2116}, + {0x2122, 0x2122}, +} + +// Encode is the outline file of the letters of ranges, read from ttf. +// +// Every number is read at a size of one pixel per unit of the font, where +// the library's arithmetic is exact, and refused if it is not a whole number +// of units - the file says what the font says, not a rounding of it. +func Encode(ttf []byte, ranges []Range) ([]byte, error) { + f, err := sfnt.Parse(ttf) + if err != nil { + return nil, err + } + e := &encoder{f: f, ppem: fixed.I(int(f.UnitsPerEm()))} + m, err := f.Metrics(&e.buf, e.ppem, font.HintingNone) + if err != nil { + return nil, err + } + e.out.WriteString(glyphs.Magic) + e.out.WriteByte(glyphs.Version) + e.put(uint16(f.UnitsPerEm())) + e.put(e.units(m.Ascent, "the ascent")) + e.put(e.units(m.Descent, "the descent")) + e.put(e.units(m.CapHeight, "the cap height")) + + letters, err := e.letters(ranges) + if err != nil { + return nil, err + } + e.put(uint16(len(letters))) + for _, l := range letters { + e.letter(l) + } + if e.err != nil { + return nil, e.err + } + return e.out.Bytes(), nil +} + +// encoder is one Encode in progress. The first refusal sticks in err and +// everything after it is skipped, so each step reads as what it writes. +type encoder struct { + f *sfnt.Font + buf sfnt.Buffer + ppem fixed.Int26_6 + out bytes.Buffer + err error +} + +type found struct { + r rune + x sfnt.GlyphIndex +} + +func (e *encoder) put(v any) { + if e.err == nil { + _ = binary.Write(&e.out, binary.LittleEndian, v) + } +} + +// units is v in units of the font, which it has to be exactly. +func (e *encoder) units(v fixed.Int26_6, what string) int16 { + u := int64(v) / 64 + switch { + case e.err != nil: + case v%64 != 0: + e.err = core.Defect(fmt.Errorf("%s is %d/64 of a unit, not a whole number", what, v)) + case u < -32768 || u > 32767: + e.err = core.Defect(fmt.Errorf("%s is %d units, past what the file holds", what, u)) + } + return int16(u) +} + +// letters is every letter of ranges the font carries, in order. +func (e *encoder) letters(ranges []Range) ([]found, error) { + var out []found + for _, r := range runes(ranges) { + x, err := e.f.GlyphIndex(&e.buf, r) + if err != nil { + return nil, err + } + if x != 0 { + out = append(out, found{r, x}) + } + } + if len(out) > 0xFFFF { + return nil, core.Defect(errors.New("more letters than the file counts")) + } + return out, nil +} + +// runes is every letter of ranges, in order. +func runes(ranges []Range) []rune { + var out []rune + for _, rg := range ranges { + for r := rg.First; r <= rg.Last; r++ { + out = append(out, r) + } + } + return out +} + +// letter writes the record of one letter: its advance and its outline. +func (e *encoder) letter(l found) { + adv, err := e.f.GlyphAdvance(&e.buf, l.x, e.ppem, font.HintingNone) + if err == nil { + var segs sfnt.Segments + segs, err = e.f.LoadGlyph(&e.buf, l.x, e.ppem, nil) + e.put(uint32(l.r)) + e.put(uint16(e.units(adv, fmt.Sprintf("the advance of %U", l.r)))) + e.put(uint16(len(segs))) + for _, s := range segs { + e.segment(l.r, s) + } + } + if err != nil && e.err == nil { + e.err = err + } +} + +// ops is what each kind of step of the font is in the file, and how many +// points it carries. A cubic curve is missing because TrueType has none. +var ops = map[sfnt.SegmentOp]struct { + op glyphs.Op + points int +}{ + sfnt.SegmentOpMoveTo: {glyphs.MoveTo, 1}, + sfnt.SegmentOpLineTo: {glyphs.LineTo, 1}, + sfnt.SegmentOpQuadTo: {glyphs.QuadTo, 2}, +} + +func (e *encoder) segment(r rune, s sfnt.Segment) { + o, ok := ops[s.Op] + if !ok { + if e.err == nil { + e.err = core.Defect(fmt.Errorf("%U has a cubic curve, and a TrueType font has none", r)) + } + return + } + e.put(byte(o.op)) + for p := 0; p < o.points; p++ { + e.put(e.units(s.Args[p].X, fmt.Sprintf("a point of %U", r))) + e.put(e.units(s.Args[p].Y, fmt.Sprintf("a point of %U", r))) + } +} diff --git a/internal/format/placeholder/glyphs/glyphs.go b/internal/format/placeholder/glyphs/glyphs.go new file mode 100644 index 00000000..6b5570e3 --- /dev/null +++ b/internal/format/placeholder/glyphs/glyphs.go @@ -0,0 +1,226 @@ +// Package glyphs is the typeface a placeholder picture is written in: the +// outlines of Inter as whole numbers in the units of the font, read from a +// file this package embeds. +// +// Why outlines as data and not a font read at run time. A picture is bytes +// somebody's suite holds a hash of (D11), so the pixels of a letter cannot be +// allowed to move when a library that reads fonts is updated - and that +// library would come in through the window toolkit, which updates it on its +// own schedule. The shapes are read out of internal/gui/font once, by +// glyphs/fromttf, and drawn by internal/format/placeholder/raster, which is +// whole number arithmetic only, so the same letter is the same pixels on every +// system and every version (docs/PLACEHOLDER-2026-11-14.md, sections 5 and 12). +// +// The file holds a subset: Latin with the letters of the European languages, +// Greek, Cyrillic and the punctuation a label or a product name uses. A text +// outside it is refused before anything is written, never drawn with a box in +// place of a letter. +package glyphs + +import ( + _ "embed" + "encoding/binary" + "fmt" + + "github.com/donislawdev/TestingFilesGenerator/internal/core" +) + +// File is what the outline file holds, embedded so the command line and the +// window draw the same letters. +// +//go:embed inter.outlines +var File []byte + +// Op is what one step of an outline does. +type Op uint8 + +const ( + // MoveTo starts a contour at one point. + MoveTo Op = iota + // LineTo draws a straight line to one point. + LineTo + // QuadTo draws a quadratic curve through a control point to an end point. + QuadTo +) + +// Point is a place in the units of the font, with the baseline at y zero and +// y growing downwards, the way pixel rows count. +type Point struct{ X, Y int32 } + +// Glyph is one letter: how far the pen moves after it, and its outline. +type Glyph struct { + Advance int32 + Ops []Op + // Points holds one point for a MoveTo and a LineTo and two for a QuadTo, + // control point first, in the order of Ops. + Points []Point +} + +// Face is the typeface as a whole: its measures and its letters. +type Face struct { + // UnitsPerEm is how many units of the font make the size of the type. + UnitsPerEm int32 + // Ascent and Descent are how far the tallest and the deepest letters + // reach above and below the baseline, both positive. + Ascent, Descent int32 + // CapHeight is how tall a capital letter is. + CapHeight int32 + + glyphs map[rune]Glyph +} + +// Glyph is the letter r, and false when the face does not carry it. +func (f *Face) Glyph(r rune) (Glyph, bool) { + g, ok := f.glyphs[r] + return g, ok +} + +// Missing is every letter of s the face does not carry, each once, in the +// order they first appear. +func (f *Face) Missing(s string) []rune { + var out []rune + seen := map[rune]bool{} + for _, r := range s { + if _, ok := f.glyphs[r]; !ok && !seen[r] { + seen[r] = true + out = append(out, r) + } + } + return out +} + +// Count is how many letters the face carries. +func (f *Face) Count() int { return len(f.glyphs) } + +// Advance is how wide s is set in the units of the font. +// +// Without kerning. Inter adjusts pairs such as A and V in its GPOS table, and +// golang.org/x/image v0.46.0, which reads the font when the outline file is +// made, finds none of them there - measured on 2026-11-14, "not found" for +// AV, To, Ty, LT and Wa (tools/probes/placeholder/kern). The pictures drawn +// without it were looked at the same day and read well, so the file carries +// no pairs rather than a section nothing could fill. +func (f *Face) Advance(s string) int64 { + var w int64 + for _, r := range s { + w += int64(f.glyphs[r].Advance) + } + return w +} + +// inter is the face the embedded file holds, read when the program starts. +// +// At start rather than at first use, so there is nothing to share between the +// writers that draw at once - reading 97 KB of outlines costs well under a +// millisecond, and a lazily read face would be the one piece of state the +// pictures of a run share. A file that does not read is a defect of this build +// rather than something a person brought about - +// TestThePlaceholderTypefaceIsInter holds it to the font it came from - so a +// build that cannot read its own letters stops at start, as one that cannot +// state the minimum of a format does (format.Register). +var inter = mustDecode(File) + +func mustDecode(b []byte) *Face { + f, err := Decode(b) + if err != nil { + panic(fmt.Sprintf("glyphs: the embedded outlines do not read: %v", err)) + } + return f +} + +// Inter is the face the embedded file holds. +func Inter() *Face { return inter } + +// Magic opens every outline file, and Version is the layout this package +// reads. +const ( + Magic = "tfgglyph" + Version = 1 +) + +// Decode reads an outline file. The layout, little endian: +// +// "tfgglyph" u8 version +// u16 units per em, i16 ascent, i16 descent, i16 cap height +// u16 glyph count, then per glyph, by rune: +// u32 rune, u16 advance, u16 step count, then per step +// u8 op and one i16 x, y pair, two for a curve +// +// Every refusal is a defect: the only file this ever reads is the one the +// build embeds. +func Decode(b []byte) (*Face, error) { + r := reader{b: b} + if string(r.take(len(Magic))) != Magic || r.u8() != Version { + return nil, core.Defect(fmt.Errorf("the file is not version %d of %s", Version, Magic)) + } + f := &Face{ + UnitsPerEm: int32(r.u16()), + Ascent: int32(r.i16()), + Descent: int32(r.i16()), + CapHeight: int32(r.i16()), + glyphs: map[rune]Glyph{}, + } + n := int(r.u16()) + for i := 0; i < n && r.err == nil; i++ { + ch, g, err := r.glyph() + if err != nil { + return nil, err + } + if _, dup := f.glyphs[ch]; dup { + return nil, core.Defect(fmt.Errorf("letter %U is in the file twice", ch)) + } + f.glyphs[ch] = g + } + switch { + case r.err != nil: + return nil, r.err + case len(r.b) != r.at: + return nil, core.Defect(fmt.Errorf("%d bytes follow the last record", len(r.b)-r.at)) + case f.UnitsPerEm <= 0: + return nil, core.Defect(fmt.Errorf("the file says a size of type is %d units", f.UnitsPerEm)) + } + return f, nil +} + +// glyph reads one letter's record. +func (r *reader) glyph() (rune, Glyph, error) { + ch := rune(r.u32()) + g := Glyph{Advance: int32(r.u16())} + steps := int(r.u16()) + for s := 0; s < steps && r.err == nil; s++ { + op := Op(r.u8()) + points, ok := pointsOf[op] + if !ok { + return 0, Glyph{}, core.Defect(fmt.Errorf("letter %U has a step %d this build does not know", ch, op)) + } + g.Ops = append(g.Ops, op) + for k := 0; k < points; k++ { + g.Points = append(g.Points, Point{X: int32(r.i16()), Y: int32(r.i16())}) + } + } + return ch, g, nil +} + +// pointsOf is how many points each step carries. +var pointsOf = map[Op]int{MoveTo: 1, LineTo: 1, QuadTo: 2} + +type reader struct { + b []byte + at int + err error +} + +func (r *reader) take(n int) []byte { + if r.err != nil || r.at+n > len(r.b) { + r.err = core.Defect(fmt.Errorf("the file ends in the middle of a record, at byte %d", r.at)) + return make([]byte, n) + } + out := r.b[r.at : r.at+n] + r.at += n + return out +} + +func (r *reader) u8() uint8 { return r.take(1)[0] } +func (r *reader) u16() uint16 { return binary.LittleEndian.Uint16(r.take(2)) } +func (r *reader) i16() int16 { return int16(r.u16()) } +func (r *reader) u32() uint32 { return binary.LittleEndian.Uint32(r.take(4)) } diff --git a/internal/format/placeholder/glyphs/inter.outlines b/internal/format/placeholder/glyphs/inter.outlines new file mode 100644 index 00000000..a01b5d2e Binary files /dev/null and b/internal/format/placeholder/glyphs/inter.outlines differ diff --git a/internal/format/placeholder/placeholder.go b/internal/format/placeholder/placeholder.go new file mode 100644 index 00000000..eb0f85c3 --- /dev/null +++ b/internal/format/placeholder/placeholder.go @@ -0,0 +1,11 @@ +// Package placeholder draws the picture a designer or a front end puts where a +// real image will go: a flat background, what the picture is for written +// large across the middle, and on request the guides that show after an +// upload whether the picture was cropped or stretched. +// +// Every picture format of this build draws it through here, so the look, the +// settings and what reaches the manifest are one declaration rather than ten +// kept alike (docs/PLACEHOLDER-2026-11-14.md). The letters are Inter, as +// outlines in package glyphs, and are drawn by package raster with whole +// numbers only, so the pixels are the same on every system (D11). +package placeholder diff --git a/internal/format/placeholder/raster/raster.go b/internal/format/placeholder/raster/raster.go new file mode 100644 index 00000000..a86fd983 --- /dev/null +++ b/internal/format/placeholder/raster/raster.go @@ -0,0 +1,356 @@ +// Package raster turns outlines into how much of each pixel they cover, with +// whole numbers only. +// +// Whole numbers because the pixels are bytes somebody holds a hash of (D11). +// Go lets a compiler fuse a multiplication and an addition into one +// instruction where the processor has one, and arm64 has one, so the same +// floating point rasteriser can give a Mac different pixels from a PC. Here +// every step is an integer operation the language defines exactly, so a +// letter is the same pixels on every system (docs/PLACEHOLDER-2026-11-14.md +// section 5). +// +// How it covers a pixel. Each row of pixels is sampled along Rows lines, and +// along each line the inside of the outline is measured to a 1/One of a pixel, +// by the non-zero winding rule. A pixel's coverage is the share of it those +// spans cover. Memory is one row of the outline's width, whatever its height, +// so a line of text across a 20000 pixel picture costs a row, not a picture. +package raster + +import "slices" + +const ( + // Frac is how many bits of a coordinate are a fraction of a pixel. + Frac = 8 + // One is one pixel in coordinates. + One = 1 << Frac + // Rows is how many lines each row of pixels is sampled along. + Rows = 16 + + full = Rows * One +) + +type edge struct { + x0, y0, x1, y1 int64 + dir int +} + +// Path is an outline in coordinates: pixels times One, y growing downwards. +// Contours close themselves - a MoveTo or the end of the path joins the last +// point back to the first. +type Path struct { + edges []edge + // segs is the outline as it was drawn, curves and all, for a format that + // writes shapes rather than pixels (Segments). + segs []Segment + startX, startY int64 + curX, curY int64 + open bool + minX, minY int64 + maxX, maxY int64 + empty bool +} + +// NewPath is an empty outline. +func NewPath() *Path { return &Path{empty: true} } + +// Op is what one segment of an outline does. +type Op uint8 + +// The four things an outline does, as an SVG path names them. +const ( + OpMove Op = iota + OpLine + OpQuad + OpClose +) + +// Segment is one step of an outline as it was drawn: to X, Y, through CX, CY +// for a curve. +type Segment struct { + Op Op + CX, CY, X, Y int64 +} + +// Segments is the outline as it was drawn, every contour ending in OpClose. The +// curves are the curves rather than the lines Fill covers, so a drawing in +// vectors keeps them smooth at any scale. +func (p *Path) Segments() []Segment { + p.Close() + return p.segs +} + +// MoveTo starts a contour at x, y. +func (p *Path) MoveTo(x, y int64) { + p.Close() + p.segs = append(p.segs, Segment{Op: OpMove, X: x, Y: y}) + p.startX, p.startY, p.curX, p.curY = x, y, x, y + p.open = true + p.grow(x, y) +} + +// LineTo draws a straight line from the current point to x, y. +func (p *Path) LineTo(x, y int64) { + p.segs = append(p.segs, Segment{Op: OpLine, X: x, Y: y}) + p.lineTo(x, y) +} + +func (p *Path) lineTo(x, y int64) { + p.addEdge(p.curX, p.curY, x, y) + p.curX, p.curY = x, y + p.grow(x, y) +} + +// QuadTo draws a quadratic curve from the current point through the control +// point cx, cy to x, y, as straight lines short enough that no point of the +// curve is further than a sixteenth of a pixel from them. +func (p *Path) QuadTo(cx, cy, x, y int64) { + p.segs = append(p.segs, Segment{Op: OpQuad, CX: cx, CY: cy, X: x, Y: y}) + x0, y0 := p.curX, p.curY + n := QuadLines(x0, y0, cx, cy, x, y) + nn := n * n + for i := int64(1); i <= n; i++ { + a, b, c := (n-i)*(n-i), 2*i*(n-i), i*i + p.lineTo(divRound(a*x0+b*cx+c*x, nn), divRound(a*y0+b*cy+c*y, nn)) + } + p.grow(cx, cy) +} + +// QuadLines is how many straight lines QuadTo draws a curve from x0, y0 +// through cx, cy to x, y as. +// +// The curve's second derivative is 2(P0-2P1+P2), and a curve flattened into n +// lines of equal parameter strays from each by at most an eighth of that over +// n squared - dev/(4n^2) with dev the LENGTH of P0-2P1+P2. The length and not +// its larger coordinate: the two differ by up to the square root of two, and +// a curve bent along a diagonal strayed 22/256 px with the coordinate, +// measured 2026-11-16. So n = sqrt(dev/(4*tol)) with tol a sixteenth of a +// pixel, One/16, and 4*tol is One/4. The length rounded up, so the count is +// never short. +// +// Capped at 256, so a curve hundreds of pixels across costs a bounded number +// of lines and strays a little further than the tolerance instead. The +// squares fit: P0-2P1+P2 is at most four coordinates long, and for a side of +// a million pixels that is about 1.0e9 here, whose square is 1.05e18 against +// the 9.2e18 an int64 holds. +func QuadLines(x0, y0, cx, cy, x, y int64) int64 { + dx, dy := x0-2*cx+x, y0-2*cy+y + dev := isqrt(dx*dx+dy*dy) + 1 + return min(isqrt(dev/(One/4))+1, 256) +} + +// Close joins the current point back to where its contour started. +func (p *Path) Close() { + if p.open { + p.segs = append(p.segs, Segment{Op: OpClose}) + } + if p.open && (p.curX != p.startX || p.curY != p.startY) { + p.addEdge(p.curX, p.curY, p.startX, p.startY) + } + p.curX, p.curY = p.startX, p.startY + p.open = false +} + +func (p *Path) addEdge(x0, y0, x1, y1 int64) { + if y0 == y1 { + return + } + dir := 1 + if y0 > y1 { + x0, y0, x1, y1 = x1, y1, x0, y0 + dir = -1 + } + p.edges = append(p.edges, edge{x0, y0, x1, y1, dir}) +} + +func (p *Path) grow(x, y int64) { + if p.empty { + p.minX, p.maxX, p.minY, p.maxY = x, x, y, y + p.empty = false + return + } + p.minX, p.maxX = min(p.minX, x), max(p.maxX, x) + p.minY, p.maxY = min(p.minY, y), max(p.maxY, y) +} + +type crossing struct { + x int64 + dir int +} + +// Fill measures the outline over a picture width by height pixels and calls +// plot for every pixel it covers, with how much of it from 1 to 255. Rows go +// top to bottom and pixels left to right, each pixel once. +func Fill(p *Path, width, height int, plot func(x, y int, alpha uint8)) { + p.Close() + box, ok := p.box(int64(width), int64(height)) + if !ok { + return + } + f := newFiller(p.edges, box) + for row := box.top; row < box.bottom; row++ { + f.row(row) + f.emit(row, plot) + } +} + +// box is the part of a picture an outline can touch, in whole pixels. +type box struct{ left, right, top, bottom int64 } + +func (p *Path) box(width, height int64) (box, bool) { + if p.empty || len(p.edges) == 0 || width <= 0 || height <= 0 { + return box{}, false + } + b := box{ + left: clamp(floorDiv(p.minX, One), 0, width), + right: clamp(floorDiv(p.maxX, One)+1, 0, width), + top: clamp(floorDiv(p.minY, One), 0, height), + bottom: clamp(floorDiv(p.maxY, One)+1, 0, height), + } + return b, b.left < b.right && b.top < b.bottom +} + +// filler is one Fill in progress: the edges by where they start, the ones the +// current sampling line crosses, and the coverage of the current row. +type filler struct { + box box + edges []edge + next int + active []edge + cross []crossing + part []int64 + whole []int64 +} + +func newFiller(edges []edge, b box) *filler { + span := b.right - b.left + f := &filler{box: b, edges: slices.Clone(edges), part: make([]int64, span+1), whole: make([]int64, span+1)} + slices.SortFunc(f.edges, byStart) + return f +} + +// byStart orders edges by every field, so two edges starting at one height +// are taken in the same order on every system. +func byStart(a, b edge) int { + for _, d := range [4][2]int64{{a.y0, b.y0}, {a.x0, b.x0}, {a.y1, b.y1}, {a.x1, b.x1}} { + if c := cmp64(d[0], d[1]); c != 0 { + return c + } + } + return a.dir - b.dir +} + +// row samples one row of pixels along Rows lines. +func (f *filler) row(row int64) { + clear(f.part) + clear(f.whole) + for k := int64(0); k < Rows; k++ { + f.line(row*One + k*(One/Rows) + One/(2*Rows)) + } +} + +// line measures the inside of the outline along one sampling line at y. +func (f *filler) line(y int64) { + for f.next < len(f.edges) && f.edges[f.next].y0 <= y { + f.active = append(f.active, f.edges[f.next]) + f.next++ + } + f.active = slices.DeleteFunc(f.active, func(e edge) bool { return e.y1 <= y }) + f.cross = f.cross[:0] + for _, e := range f.active { + x := e.x0 + floorDiv((y-e.y0)*(e.x1-e.x0), e.y1-e.y0) + f.cross = append(f.cross, crossing{x, e.dir}) + } + slices.SortFunc(f.cross, func(a, b crossing) int { + if c := cmp64(a.x, b.x); c != 0 { + return c + } + return a.dir - b.dir + }) + lo, hi := f.box.left*One, f.box.right*One + winding := 0 + var from int64 + for _, c := range f.cross { + was := winding + winding += c.dir + if was == 0 && winding != 0 { + from = c.x + } else if was != 0 && winding == 0 { + cover(f.part, f.whole, clamp(from, lo, hi)-lo, clamp(c.x, lo, hi)-lo) + } + } +} + +// emit hands the coverage of one finished row to plot. +func (f *filler) emit(row int64, plot func(x, y int, alpha uint8)) { + var run int64 + for i := int64(0); i < f.box.right-f.box.left; i++ { + run += f.whole[i] + c := run + f.part[i] + if c <= 0 { + continue + } + if a := min((c*255+full/2)/full, 255); a > 0 { + plot(int(f.box.left+i), int(row), uint8(a)) + } + } +} + +// cover adds the span from a to b, in coordinates from the left edge of the +// outline, to one sampling line: the pixels at its ends in part, the whole +// pixels between as a step in whole that the row sums up. +func cover(part, whole []int64, a, b int64) { + if b <= a { + return + } + ia, ib := a>>Frac, b>>Frac + if ia == ib { + part[ia] += b - a + return + } + part[ia] += One - (a & (One - 1)) + whole[ia+1] += One + whole[ib] -= One + part[ib] += b & (One - 1) +} + +func cmp64(a, b int64) int { + switch { + case a < b: + return -1 + case a > b: + return 1 + } + return 0 +} + +func clamp(v, lo, hi int64) int64 { return min(max(v, lo), hi) } + +// floorDiv is a / b rounded down, b positive. +func floorDiv(a, b int64) int64 { + q := a / b + if (a%b != 0) && (a < 0) { + q-- + } + return q +} + +// divRound is a / b to the nearest whole number, halves up, b positive. +func divRound(a, b int64) int64 { return floorDiv(2*a+b, 2*b) } + +// isqrt is the whole part of the square root of v, v not negative. +func isqrt(v int64) int64 { + if v < 2 { + return max(v, 0) + } + x := v + y := (x + 1) / 2 + for y < x { + x = y + y = (x + v/x) / 2 + } + return x +} + +// Isqrt is the whole part of the square root of v, for the shapes drawn +// beside the letters, which need a length. +func Isqrt(v int64) int64 { return isqrt(v) } diff --git a/internal/format/placeholder/settings.go b/internal/format/placeholder/settings.go new file mode 100644 index 00000000..3c71accf --- /dev/null +++ b/internal/format/placeholder/settings.go @@ -0,0 +1,405 @@ +package placeholder + +import ( + "fmt" + "image/color" + "strconv" + "strings" + "unicode/utf8" + + "github.com/donislawdev/TestingFilesGenerator/internal/core" + "github.com/donislawdev/TestingFilesGenerator/internal/format" + "github.com/donislawdev/TestingFilesGenerator/internal/format/placeholder/glyphs" +) + +// Setting names, public under rule 10. foreground rather than text_color: it +// pairs with background, it colours the guides as well as the words, and it +// keeps out of the colour and color spelling the manifest already has one of +// (colour_type). +const ( + SettingContent = "content" + SettingText = "text" + SettingBackground = "background" + SettingForeground = "foreground" + SettingGuides = "guides" +) + +// The two values of content. test is what every picture format drew before +// placeholders existed, to the byte (D11), and stays the default. +const ( + ContentTest = "test" + ContentPlaceholder = "placeholder" +) + +// The tokens text understands. {index:04} is spelled as in a name template, so +// a file called hero_0007.png can say 0007 in its picture. +const ( + tokenIndex = "{index}" + tokenIndexPadded = "{index:04}" + tokenWidth = "{width}" + tokenHeight = "{height}" +) + +// The defaults. The text is the size with a multiplication sign between, as +// people write it - U+00D7, spelled in bytes so this file stays ASCII. +const ( + DefaultText = tokenWidth + " \xc3\x97 " + tokenHeight + DefaultBackground = "cccccc" + DefaultForeground = "555555" +) + +// MaxText is how many characters text may have. One line on a picture, so a +// hundred is more than any layout uses - the ceiling exists because the value +// is typed by somebody and drawn on every file (rule 23). +const MaxText = 100 + +// shapeColour is what a colour has to look like, said once for both colours - +// the site translates it as one term. +const shapeColour = "a colour such as cccccc or ccc" + +// Group is the heading the settings stand under on both surfaces. +const Group = "Placeholder" + +// Properties declares the five settings. One declaration for every picture +// format, so the names and what they take cannot differ between them. +func Properties() []format.Property { + return []format.Property{ + { + Name: SettingContent, Kind: format.PropertyChoice, + Choices: []string{ContentTest, ContentPlaceholder}, + Default: ContentTest, + Detail: "What the picture shows. test is a pattern for checking how a file is read. placeholder is a flat colour with words in the middle, for laying out a page before the real pictures exist.", + Group: Group, + }, + { + Name: SettingText, Kind: format.PropertyText, + Shape: fmt.Sprintf("one line of up to %d characters", MaxText), + Default: DefaultText, + Detail: "The words in the middle of a placeholder. {width} and {height} become the size of the picture, {index} the number of the file and {index:04} the same number with four digits.", + Group: Group, + }, + { + Name: SettingBackground, Kind: format.PropertyText, + Shape: shapeColour, + Default: DefaultBackground, + Detail: "The colour of a placeholder, such as cccccc or ccc. In a recipe write it without # or in quotes, because # starts a comment there.", + Group: Group, + }, + { + Name: SettingForeground, Kind: format.PropertyText, + Shape: shapeColour, + Default: DefaultForeground, + Detail: "The colour of the words and the guides on a placeholder, written the same way as background.", + Group: Group, + }, + { + Name: SettingGuides, Kind: format.PropertyBool, + Default: "false", + Detail: "Draws a frame along the edges of a placeholder, both diagonals and a circle touching its shorter sides, so you can see where a page crops or stretches the picture.", + Group: Group, + }, + } +} + +// Settings is what the five settings asked for, read and checked. +type Settings struct { + Content string + // Text is the template, tokens and all. Expand puts a file's numbers in. + Text string + Background color.RGBA + Foreground color.RGBA + Guides bool +} + +// Placeholder reports whether the picture is a placeholder rather than the +// test pattern. +func (s Settings) Placeholder() bool { return s.Content == ContentPlaceholder } + +// Read is the five settings of one request, each checked and with its default +// where it is left out. owner is the format that refuses a value. +// +// The declaration checks what it can say on its own - the two words content +// takes, true or false. The rest is checked here because it is more than a +// shape: whether the typeface has the letters, whether a token exists, whether +// a setting that changes nothing was set. The engine asks the declaration and +// then the plan, so a recipe gets both before any file exists. +func Read(owner string, props map[string]string) (Settings, error) { + s := Settings{Content: ContentTest, Text: DefaultText} + if v := props[SettingContent]; v != "" { + if err := allowed(owner, SettingContent, v); err != nil { + return Settings{}, err + } + s.Content = v + } + if !s.Placeholder() { + return s, nothingToChange(owner, props) + } + if v := props[SettingText]; v != "" { + if err := checkText(owner, v); err != nil { + return Settings{}, err + } + s.Text = v + } + var err error + if s.Background, err = colourOf(owner, SettingBackground, DefaultBackground, props); err != nil { + return Settings{}, err + } + if s.Foreground, err = colourOf(owner, SettingForeground, DefaultForeground, props); err != nil { + return Settings{}, err + } + if v := props[SettingGuides]; v != "" { + if err := allowed(owner, SettingGuides, v); err != nil { + return Settings{}, err + } + s.Guides = v == "true" + } + return s, nil +} + +// allowed asks the declaration of one setting, for a caller that did not come +// through the registry - a guard, or a format reading its own request. +func allowed(owner, name, v string) error { + for _, p := range Properties() { + if p.Name == name { + if bad := p.Allows(v); !bad.IsZero() { + return &format.PropertyValueError{Format: owner, Key: name, Value: v, Reason: bad, Remedy: p.Instead()} + } + return nil + } + } + return core.Defect(fmt.Errorf("placeholder: %q is not one of its settings", name)) +} + +// nothingToChange refuses a placeholder setting on a test picture. It would be +// read, accepted and ignored, and somebody would wait for a colour that never +// comes - a setting that does nothing has to say so. +// +// guides is refused only when it asks for guides. A window sends every switch +// in the position it shows (parts.boolField), so guides=false arrives with +// every picture made there, and it asks for exactly what a test picture has. +func nothingToChange(owner string, props map[string]string) error { + for _, name := range []string{SettingText, SettingBackground, SettingForeground, SettingGuides} { + v, ok := props[name] + if ok && !(name == SettingGuides && v == "false") { + return &format.PropertyValueError{ + Format: owner, Key: name, Value: v, + Reason: core.Says("placeholder.OnlyOnAPlaceholder", "it only changes a placeholder, and content is test"), + Remedy: core.Says("placeholder.SetContentPlaceholder", "Set content to placeholder, or leave the line out"), + } + } + } + return nil +} + +// colourOf reads one colour, or its default when it is left out. +// +// Present and empty is refused rather than read as left out, which is what +// every other setting does with it. A colour is the one value people write +// with a # in front, and in a recipe that is a comment: background: #ff0000 +// arrives as nothing, and a grey picture with no word of why is exactly the +// silence rule 6 forbids. Measured on 2026-11-14 with a text setting, which +// took its default the same way. A window never sends an empty box. +func colourOf(owner, name, fallback string, props map[string]string) (color.RGBA, error) { + v, ok := props[name] + if !ok { + c, _ := parseColour(fallback) + return c, nil + } + if v == "" { + return color.RGBA{}, &format.PropertyValueError{ + Format: owner, Key: name, Value: v, + Reason: core.Says("placeholder.ColourIsEmpty", "it is empty, and in a recipe # starts a comment, so a colour written after it is not read"), + Remedy: core.Says("placeholder.WriteTheColourWithoutHash", "Write the colour without the # or in quotes, such as %s: ff0000 or %s: \"#ff0000\"", core.A("Name", name), core.A("Name2", name)), + } + } + c, good := parseColour(v) + if !good { + return color.RGBA{}, &format.PropertyValueError{ + Format: owner, Key: name, Value: v, + Reason: core.Says("placeholder.NotAColour", "it has to be a colour written as six hex digits such as cccccc, or three such as ccc"), + Remedy: core.Says("placeholder.WriteAColourSuchAs", "Write a colour such as %s, with or without a # in front", core.A("Default", fallback)), + } + } + return c, nil +} + +// parseColour reads rrggbb or rgb, with one # in front or none, in either +// case. Three digits mean each one twice, as on the web: ccc is cccccc. +func parseColour(v string) (color.RGBA, bool) { + v = strings.TrimPrefix(v, "#") + if len(v) == 3 { + v = string([]byte{v[0], v[0], v[1], v[1], v[2], v[2]}) + } + if len(v) != 6 { + return color.RGBA{}, false + } + // Each channel on its own and eight bits wide, so every number parsed fits + // the byte it goes into and no conversion narrows it. One number of + // twenty four bits cut into three was the same colours, and CodeQL could + // not see that six digits bound it (go/incorrect-integer-conversion, #250). + var rgb [3]uint8 + for i := range rgb { + n, err := strconv.ParseUint(v[2*i:2*i+2], 16, 8) + if err != nil { + return color.RGBA{}, false + } + rgb[i] = uint8(n) + } + return color.RGBA{R: rgb[0], G: rgb[1], B: rgb[2], A: 255}, true +} + +// Hex is a colour as the manifest records it: six lower case digits, whatever +// spelling the recipe used. +func Hex(c color.RGBA) string { return fmt.Sprintf("%02x%02x%02x", c.R, c.G, c.B) } + +// checkText refuses a text that is too long, names a token that does not +// exist, or has a character the typeface cannot draw. +func checkText(owner, v string) error { + refuse := func(reason, remedy core.Said) error { + return &format.PropertyValueError{Format: owner, Key: SettingText, Value: v, Reason: reason, Remedy: remedy} + } + if n := utf8.RuneCountInString(v); n > MaxText { + return refuse(core.Says("placeholder.TextTooLong", "it has %d characters and a placeholder takes up to %d", core.A("Count", n), core.A("Most", MaxText)), + core.Says("placeholder.ShortenTheText", "Write a shorter text, one line that fits across the picture")) + } + literal, unknown := withoutTokens(v) + if unknown != "" { + return refuse(core.Says("placeholder.UnknownToken", "it has %s, which is not a token this build understands", core.A("Token", unknown)), + core.Says("placeholder.TheTokensAre", "The tokens are {width}, {height}, {index} and {index:04}")) + } + if missing := glyphs.Inter().Missing(literal); len(missing) > 0 { + return refuse(core.Says("placeholder.NoLetterFor", "the typeface has no letter for %s", core.A("Characters", runeList(missing))), + core.Says("placeholder.UseLettersItHas", "Use the Latin, Greek or Cyrillic alphabet, digits and common punctuation, all on one line")) + } + return nil +} + +// withoutTokens is the text with every token taken out, and the first brace +// that does not open a token, from that brace to the one closing it or to the +// end. A brace left in would be drawn as written, and somebody would get a +// picture saying {idx} rather than the number they meant - the same reason a +// name template refuses one. +// +// One pass over the text as written, left to right as Expand reads it. Taking +// the tokens out one kind after another let the removal of one make another: +// {width{index}} lost {index}, became {width}, lost that too and was accepted, +// and Expand then drew {width1}. +func withoutTokens(v string) (literal, unknown string) { + var b strings.Builder + for i := 0; i < len(v); { + if v[i] != '{' && v[i] != '}' { + b.WriteByte(v[i]) + i++ + continue + } + t := tokenAt(v[i:]) + if t == "" { + return b.String(), strayBrace(v[i:]) + } + i += len(t) + } + return b.String(), "" +} + +// strayBrace is what a refusal quotes of s, which starts with a brace that +// opens no token: up to the brace closing it, or the start of s when nothing +// closes it or the brace is itself a closing one. +func strayBrace(s string) string { + if end := strings.IndexByte(s, '}'); s[0] == '{' && end >= 0 { + return s[:end+1] + } + return brief(s) +} + +// tokenAt is the token s starts with, or nothing. Nothing for a closing +// brace too, since every token opens with one. +func tokenAt(s string) string { + for _, t := range []string{tokenIndexPadded, tokenIndex, tokenWidth, tokenHeight} { + if strings.HasPrefix(s, t) { + return t + } + } + return "" +} + +// brief is the start of s for a refusal to quote: up to twenty bytes, cut +// where a character starts so the quote is still text. +func brief(s string) string { + cut := min(len(s), 20) + for cut < len(s) && !utf8.RuneStart(s[cut]) { + cut-- + } + return s[:cut] +} + +// runeList names characters for a refusal: each one quoted, with its code +// point, because the ones the typeface lacks are often ones nobody can see - +// a tab, a zero width space. The first five, and an ellipsis for the rest, +// which needs no word in any language. +func runeList(rs []rune) string { + const most = 5 + parts := make([]string, 0, most+1) + for i, r := range rs { + if i == most { + parts = append(parts, "...") + break + } + parts = append(parts, fmt.Sprintf("%q (U+%04X)", r, r)) + } + return strings.Join(parts, ", ") +} + +// Expand is the text of one file: number is the file's number in its target, +// counted from one as its name counts it. +func (s Settings) Expand(number, width, height int) string { + return strings.NewReplacer( + tokenIndexPadded, fmt.Sprintf("%04d", number), + tokenIndex, strconv.Itoa(number), + tokenWidth, strconv.Itoa(width), + tokenHeight, strconv.Itoa(height), + ).Replace(s.Text) +} + +// Look is what one file of these settings shows. +func (s Settings) Look(text, label string) Look { + return Look{Text: text, Label: label, Background: s.Background, Foreground: s.Foreground, Guides: s.Guides} +} + +// Describe adds the settings to what reaches the manifest. content always, so +// a test reads the same key from every picture. The rest only for a +// placeholder, where they describe what is in it: the text as drawn, the +// colours as six digits, and whether the text and the label fitted. +func (s Settings) Describe(props map[string]any, text string, drawn Drawn) { + props[SettingContent] = s.Content + if !s.Placeholder() { + return + } + props[SettingText] = text + props[SettingBackground] = Hex(s.Background) + props[SettingForeground] = Hex(s.Foreground) + props[SettingGuides] = s.Guides + props["text_drawn"] = drawn.Text +} + +// Claim is what a plan says about a placeholder of width by height: whether +// it carries the label, and a note for the text and for the label each that +// did not fit. Neither is squeezed below what can be read, and neither is left +// out in silence (rule 6). One place for every picture format, so the words +// cannot come apart between them. +func Claim(drawn Drawn, label string, width, height int, notes []format.Note) (bool, []format.Note) { + if !drawn.Text { + notes = append(notes, format.Note{ + Code: "text_omitted", + Detail: core.Says("placeholder.TextOmitted", "The picture is %d by %d px and its text needs more room, so this placeholder carries no text. A larger picture or a shorter text has room for it.", + core.A("Width", width), core.A("Height", height)), + }) + } + if label != "" && !drawn.Label { + notes = append(notes, format.Note{ + Code: "label_omitted", + Detail: core.Says("placeholder.LabelOmitted", "The picture is %d by %d px and the label needs more room, so this file carries no visible label. Its name and the manifest still identify it.", + core.A("Width", width), core.A("Height", height)), + }) + } + return drawn.Label, notes +} diff --git a/internal/format/png/png.go b/internal/format/png/png.go index a2c070b0..36a4cbc3 100644 --- a/internal/format/png/png.go +++ b/internal/format/png/png.go @@ -19,6 +19,7 @@ import ( "github.com/donislawdev/TestingFilesGenerator/internal/format" "github.com/donislawdev/TestingFilesGenerator/internal/format/imagedim" "github.com/donislawdev/TestingFilesGenerator/internal/format/imagelabel" + "github.com/donislawdev/TestingFilesGenerator/internal/format/placeholder" ) const ( @@ -95,12 +96,12 @@ func init() { }, Label: format.LabelVisible, Oracle: "pillow", - Properties: []format.Property{ + Properties: append([]format.Property{ imagedim.Width(imagedim.Side{Largest: maxDimension, Detail: "How wide the picture is. Left out, a size is chosen that fits the bytes you asked for."}), imagedim.Height(imagedim.Side{Largest: maxDimension, Detail: "How tall the picture is. Left out, a size is chosen that fits the bytes you asked for."}), - }, + }, placeholder.Properties()...), JointLimits: []format.JointLimit{{ Of: "width", By: "height", Max: maxPixels, Unit: "megapixels", Per: 1_000_000, Base: "pixels", @@ -117,6 +118,10 @@ type memo struct { width, height int seed uint64 label string + // look is what the picture shows, and text the words of a placeholder + // with this file's numbers in them. A test picture has neither. + look placeholder.Settings + text string // body is the number of bytes the encoded picture takes before the closing // chunk. Worked out during planning so that a size this format cannot // reach is refused before any file exists. @@ -165,18 +170,24 @@ func checkJointLimits(w, h int) error { } func (generator) Plan(r format.Request) (format.Plan, error) { + look, err := placeholder.Read("png", r.Properties) + if err != nil { + return format.Plan{}, err + } label := "" if r.Label { label = r.LabelText("png") } - m, err := chooseSize(r, label) + m, err := chooseSize(r, label, look) if err != nil { return format.Plan{}, err } m.cutAt = r.CutAt w, h := m.width, m.height - body := m.body + if err := m.settle(r); err != nil { + return format.Plan{}, err + } p := format.Plan{ Bytes: r.Bytes, @@ -191,8 +202,18 @@ func (generator) Plan(r format.Request) (format.Plan, error) { }, } + m.claim(&p, label) + p.Memo = m + p.Holds = holdsPerPixel * int64(w) * int64(h) + return p, nil +} + +// settle decides whether the file carries a padding chunk and how much, or +// refuses a size this picture cannot reach. +func (m *memo) settle(r format.Request) error { + w, h := m.width, m.height // What the picture takes on its own, closing chunk included. - bare := body + iendSize + bare := m.body + iendSize switch { case !m.bodyKnown: @@ -208,7 +229,7 @@ func (generator) Plan(r format.Request) (format.Plan, error) { m.withPad = false case r.Bytes < bare: - return format.Plan{}, &format.BelowMinimumError{ + return &format.BelowMinimumError{ Format: "PNG", Requested: r.Bytes, Minimum: bare, @@ -220,7 +241,7 @@ func (generator) Plan(r format.Request) (format.Plan, error) { // Between the two lies a gap of eleven byte counts that no // combination of chunks can hit, because the smallest chunk that // exists is an empty one and it costs twelve bytes. - return format.Plan{}, &format.BelowMinimumError{ + return &format.BelowMinimumError{ Format: "PNG", Requested: r.Bytes, Minimum: bare + chunkOverhead, @@ -232,7 +253,7 @@ func (generator) Plan(r format.Request) (format.Plan, error) { m.withPad = true m.padData = r.Bytes - bare - chunkOverhead if m.padData > maxChunkData { - return format.Plan{}, &format.AboveMaximumError{ + return &format.AboveMaximumError{ Format: "PNG", Requested: r.Bytes, // The ceiling is what this generator can reach at these @@ -246,19 +267,30 @@ func (generator) Plan(r format.Request) (format.Plan, error) { } } } + return nil +} - if r.Label && !imagelabel.Fits(w, len(label)) { +// claim says in the plan whether the picture carries its label, and for a +// placeholder what it shows, each in the words of the package that draws it. +// label is empty when the request asked for none. +func (m memo) claim(p *format.Plan, label string) { + w, h := m.width, m.height + if m.look.Placeholder() { + drawn := placeholder.Measure(w, h, m.look.Look(m.text, label)) + p.Properties[format.PropertyLabelEmbedded], p.Notes = placeholder.Claim(drawn, label, w, h, p.Notes) + m.look.Describe(p.Properties, m.text, drawn) + return + } + if label != "" && !imagelabel.Fits(w, len(label)) { p.Notes = append(p.Notes, format.Note{ Code: "label_omitted", Detail: core.Says("format.ThePictureIsPxWideAnd", "The picture is %d px wide and the label needs more room, so this file carries no visible label. Its name and the manifest still identify it.", core.A("Width", w)), }) } - labelled := r.Label && imagelabel.Fits(w, len(label)) + labelled := label != "" && imagelabel.Fits(w, len(label)) labelled, p.Notes = imagelabel.Claim(labelled, w, h, len(label), p.Notes) p.Properties[format.PropertyLabelEmbedded] = labelled - p.Memo = m - p.Holds = holdsPerPixel * int64(w) * int64(h) - return p, nil + m.look.Describe(p.Properties, "", placeholder.Drawn{}) } // holdsPerPixel is what writing one of these holds at once for each pixel of @@ -382,7 +414,10 @@ var sizeLadder = [][2]int{ // the largest rung down until one fits, which is what lets a request for a // few hundred bytes succeed rather than being told the default picture is too // big for it. -func chooseSize(r format.Request, label string) (memo, error) { +func chooseSize(r format.Request, label string, look placeholder.Settings) (memo, error) { + at := func(w, h int) memo { + return memo{width: w, height: h, seed: r.Seed, label: label, look: look, text: look.Expand(r.Number, w, h)} + } _, wSet := r.Properties["width"] _, hSet := r.Properties["height"] @@ -403,7 +438,7 @@ func chooseSize(r format.Request, label string) (memo, error) { if err := checkJointLimits(w, h); err != nil { return memo{}, err } - m := memo{width: w, height: h, seed: r.Seed, label: label} + m := at(w, h) body, err := encodedBodySize(m) if err != nil { return memo{}, err @@ -431,15 +466,18 @@ func chooseSize(r format.Request, label string) (memo, error) { // when the picture is smallest, and a picture is never smaller than // nothing. Bounding it that way costs a fallback to the slow path for a // sliver of sizes just under two gigabytes and keeps the refusal honest. - if r.Bytes >= ladderCeiling+iendSize+chunkOverhead && + // + // A placeholder takes the slow path. ladderCeiling was measured on the + // test pattern, and a placeholder's text and guides are not that picture. + if !look.Placeholder() && r.Bytes >= ladderCeiling+iendSize+chunkOverhead && r.Bytes-iendSize-chunkOverhead <= maxChunkData { rung := sizeLadder[0] - return memo{width: rung[0], height: rung[1], seed: r.Seed, label: label}, nil + return at(rung[0], rung[1]), nil } var smallest memo for _, rung := range sizeLadder { - m := memo{width: rung[0], height: rung[1], seed: r.Seed, label: label} + m := at(rung[0], rung[1]) body, err := encodedBodySize(m) if err != nil { return memo{}, err @@ -462,6 +500,10 @@ func chooseSize(r format.Request, label string) (memo, error) { // the padding chunk carries the difference. func picture(m memo) image.Image { img := image.NewRGBA(image.Rect(0, 0, m.width, m.height)) + if m.look.Placeholder() { + placeholder.Draw(img, m.look.Look(m.text, m.label)) + return img + } // The seed shifts the gradient, so two seeds give visibly different // pictures rather than the same picture with different padding. off := int(m.seed % 256) diff --git a/internal/format/registry.go b/internal/format/registry.go index 7af74b13..8846f97e 100644 --- a/internal/format/registry.go +++ b/internal/format/registry.go @@ -152,6 +152,8 @@ func RequestKey(id string, r Request) (string, bool) { // its length and with it the smallest file that carries it. Where the cut // falls changes how a format lays the file out. fmt.Fprintf(&b, " %d %q %d", r.OnDisk, r.Damage, r.CutAt) + // The number is a word of a placeholder's text where {index} asks for it. + fmt.Fprintf(&b, " %d", r.Number) for _, name := range names { fmt.Fprintf(&b, " %q=%q", name, r.Properties[name]) } diff --git a/internal/format/svgfile/placeholder.go b/internal/format/svgfile/placeholder.go new file mode 100644 index 00000000..650cc978 --- /dev/null +++ b/internal/format/svgfile/placeholder.go @@ -0,0 +1,227 @@ +package svgfile + +import ( + "context" + "fmt" + "io" + // D11 promises the same bytes from the same seed. Nothing here makes a + // secret. + // nosemgrep: go.lang.security.audit.crypto.math_random.math-random-used + "math/rand/v2" + "strconv" + "strings" + + "github.com/donislawdev/TestingFilesGenerator/internal/core" + "github.com/donislawdev/TestingFilesGenerator/internal/format" + "github.com/donislawdev/TestingFilesGenerator/internal/format/placeholder" + "github.com/donislawdev/TestingFilesGenerator/internal/format/placeholder/raster" +) + +// A placeholder drawing is the shapes the picture formats fill with pixels, +// written as shapes (placeholder.Shapes): the same outlines to the 256th of a +// pixel, so a page laid out with the SVG and with the PNG looks the same, and +// the letters are Inter on every machine rather than whatever font the viewer +// has. docs/PLACEHOLDER-2026-11-14.md. +// +// The words go into a title as well, which is what a screen reader and a +// search read. The padding goes into the description, which no renderer +// draws: unlike the test drawing, more bytes must not mean more shapes here, +// or a placeholder of 2 MB would be covered in circles. +// +// The label is the one thing written as words, a text element in Inter where +// the viewer has it, as the label of the test drawing is. Drawn as outlines it +// was as long in bytes as the shapes of the numerals the seed came up with, +// and measured on 2026-11-14 the smallest drawing moved by 2.5 kB between ten +// seeds - a size the tool announced would be refused for the next file. As +// words it is as long as its characters, and its place is worked out from a +// width that does not depend on them either (placeholder.labelAdvance). + +const ( + // unitScale turns the coordinates of an outline, 256ths of a pixel, into + // the pixels of the drawing. Exact in decimal, as every power of two is, + // so every coordinate is a whole number in the file. + unitScale = `transform="scale(0.00390625)"` + + descOpen = "" + descTail = "\n" + rootClose +) + +// planPlaceholder is Plan for content: placeholder. +func planPlaceholder(r format.Request, w, h int, look placeholder.Settings) (format.Plan, error) { + label := "" + if r.Label { + label = r.LabelText("svg") + } + text := look.Expand(r.Number, w, h) + body, drawn := drawing(w, h, look.Look(text, label)) + least := int64(len(declaration)+len(rootOpen(w, h))+len(body)+len(descOpen)) + int64(len(descTail)) + if r.Bytes < least { + return format.Plan{}, &format.BelowMinimumError{ + Format: "SVG", + Requested: r.Bytes, + Minimum: least, + Reason: core.Says("format.APlaceholderPictureHolds", "a placeholder picture holds its shapes, its words and its label, and a %dx%d one needs that much", core.A("Width", w), core.A("Height", h)), + Hint: core.Says("format.AskForBOrMore", "Ask for %d B or more.", core.A("Min", least)), + } + } + p := format.Plan{ + Bytes: r.Bytes, + Exact: true, + Determinism: format.DeterminismByte, + Properties: map[string]any{ + "encoding": "utf-8", + "line_ending": "lf", + Width: w, + Height: h, + "view_box": fmt.Sprintf("0 0 %d %d", w, h), + }, + } + p.Properties[format.PropertyLabelEmbedded], p.Notes = placeholder.Claim(drawn, label, w, h, p.Notes) + look.Describe(p.Properties, text, drawn) + // The length of the drawing rather than the drawing, which is a few + // kilobytes of outline: a plan holds its memo until the file is written, + // and a run plans every file before it writes one. + p.Memo = memo{seed: r.Seed, width: w, height: h, look: look, text: text, label: label, body: int64(len(body))} + return p, nil +} + +// writePlaceholder is Write for content: placeholder. +func writePlaceholder(ctx context.Context, out io.Writer, p format.Plan, m memo) error { + body, _ := drawing(m.width, m.height, m.look.Look(m.text, m.label)) + if int64(len(body)) != m.body { + return core.Defect(fmt.Errorf("svg: the placeholder came to %d B where planning said %d B", len(body), m.body)) + } + head := make([]byte, 0, len(declaration)+len(body)+256) + head = append(head, declaration...) + head = append(head, rootOpen(m.width, m.height)...) + head = append(head, body...) + head = append(head, descOpen...) + if err := core.WriteAll(out, head); err != nil { + return err + } + return core.FillRecords(ctx, out, core.NewRand(m.seed), p.Bytes-int64(len(head)), description{}) +} + +// drawing is the placeholder between the root element and the description: +// its words as a title, the background, the guides, the plate, the words and +// the label, in the order placeholder.Scene lays them. +func drawing(w, h int, l placeholder.Look) ([]byte, placeholder.Drawn) { + s := placeholder.Shapes(w, h, l) + bg, fg := "#"+placeholder.Hex(l.Background), "#"+placeholder.Hex(l.Foreground) + b := make([]byte, 0, 4096) + b = append(b, ""...) + b = append(b, escapeText(l.Text)...) + b = append(b, "\n"...) + b = fmt.Appendf(b, ``+"\n", w, h, bg) + b = appendShapes(b, fg, s.Guides) + if !s.Plate.Empty() { + b = fmt.Appendf(b, ``+"\n", + s.Plate.Min.X, s.Plate.Min.Y, s.Plate.Dx(), s.Plate.Dy(), bg) + } + if s.Text != nil { + b = appendShapes(b, fg, []*raster.Path{s.Text}) + } + if s.Label != nil { + b = appendLabel(b, w, s, l.Label, fg) + } + return b, s.Drawn +} + +// appendLabel writes the label as a text element, centred on the width and on +// the baseline the scene gives it, rounded to a whole pixel. None of its +// numbers depends on the label's characters, so its length is the label's +// length and the fixed text around it. +func appendLabel(b []byte, w int, s placeholder.Scene, label, fill string) []byte { + x := strconv.Itoa(w / 2) + if w%2 == 1 { + x += ".5" + } + y := (s.LabelBaseline + raster.One/2) >> raster.Frac + b = fmt.Appendf(b, ``, + x, y, s.LabelSize, fill) + b = append(b, escapeText(label)...) + return append(b, "\n"...) +} + +// appendShapes writes outlines as one group of paths filled in one colour. +// Each is a path of its own for the reason guides are filled one by one: two +// shapes wound in opposite directions cancel where they overlap. +func appendShapes(b []byte, fill string, paths []*raster.Path) []byte { + if len(paths) == 0 { + return b + } + b = fmt.Appendf(b, ``+"\n", fill, unitScale) + for _, p := range paths { + b = append(b, ``+"\n"...) + } + return append(b, "\n"...) +} + +// appendPathData writes an outline as SVG path data, in whole 256ths of a +// pixel. +func appendPathData(b []byte, segs []raster.Segment) []byte { + for i, s := range segs { + if i > 0 { + b = append(b, ' ') + } + switch s.Op { + case raster.OpMove: + b = appendPoint(append(b, 'M'), s.X, s.Y) + case raster.OpLine: + b = appendPoint(append(b, 'L'), s.X, s.Y) + case raster.OpQuad: + b = appendPoint(append(appendPoint(append(b, 'Q'), s.CX, s.CY), ' '), s.X, s.Y) + case raster.OpClose: + b = append(b, 'Z') + } + } + return b +} + +func appendPoint(b []byte, x, y int64) []byte { + return strconv.AppendInt(append(strconv.AppendInt(b, x, 10), ' '), y, 10) +} + +// escapeText is text as the content of an element. The words of a placeholder +// are typed by somebody, and a file served from a site opens in a browser: +//