Skip to content

Commit aaf1a50

Browse files
4akloonclaudecursoragent
authored
Variable stroke width (0.6.0) (#10)
* Add variable font prototype master builder * Wind ring's inner contour oppositely so it fills as an annulus * Add variable font prototype merge script * Add Phase 0 validity, correctness and size gates * Fix gate_correctness float/int asymmetry and gate_size CFF boilerplate Round-trip variable-font instances through io.BytesIO before measuring outlines, so glyf's in-memory float coordinates get the same quantization as the compiled static comparison target. Narrow outline_bytes to charstring bytecode (CFF/CFF2) and glyf+gvar table length, excluding CFF1 top-dict metadata that CFF2 has no operators for, so the size ratio measures scaling cost rather than dropped boilerplate. * Add variable stroke render matrix harness Adds the Task 4 gate: an integration_test that renders the ProtoGvar and ProtoCff2 prototype fonts side by side against three CFF static references, asserting the wght axis actually moves pixels (the check a silently-ignored axis would otherwise slip past), a fill stays put, and out-of-range weights clamp. Scaffolds macos/ios/android platform folders for example/ (it was web-only before this task) so the harness can run natively, and copies the five Task 1-3 prototype fonts into example/fonts/proto/ since they are gitignored at their tool/variable_prototype/out/ source and the render matrix needs to be re-runnable from a checkout. Excludes example/fonts/proto/ from the published package via .pubignore. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * Fix render matrix to capture the probe box, not the whole window RepaintBoundary sat under a bare Container beneath MaterialApp.home, which hands down tight constraints; BoxConstraints.enforce clamped the requested 96x96 up to the full window, so every threshold in the suite compared against a denominator dominated by an untouched background. Every measurement in the previous commit is void: the axis assertion could not pass even for a perfect engine, and the other three could not fail even for a broken one. Wraps the boundary in Center so it receives its own constraints, makes capture() verify the size it got rather than trust it, drops the alpha byte from difference() (constant 255, pure dilution), and switches every threshold to a multiple of a same-run "how much does rebuilding the font at 1.33 vs 2.0 actually move the raster" measurement instead of an absolute pixel-fraction constant, with a floor that catches a font failing to load. Also drops the .pubignore exclusion for example/fonts/proto/, since pubspec.yaml declares those five files as font assets and pub publish ships the pubspec - excluding the assets without excluding the reference to them breaks AssetBundle.build for anyone running the example from a published install. Deletes the three DEVELOPMENT_TEAM lines from the iOS project file rather than blanking them, restoring the stock template exactly. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * Judge each variable format against static masters of its own outline type ProtoStatic133/150/200 were all CFF masters, so every assertion judging ProtoGvar (a glyf/TrueType font) against them measured the gap between the package's two writers, not variation quality - a gap the reviewer confirmed is width-independent and present even on a glyph with zero deltas in every master. Registers ProtoCff133/150/200 and ProtoGlyf133/150/200 separately and has the test pair each candidate with the static prefix of its own outline format via a _Candidate record, so the "matches static" and "axis" assertions measure interpolation instead of writer drift. The previously proposed per-width cubic-to-quadratic mechanism for that gap does not hold: quad structure is identical across widths and the masters are affine to within one font unit. The real cause is a lazy-Iterable bug in the package's own TrueType writer that skips the conversion entirely, which is out of scope for this task and is left untouched. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * Record variable font format decision Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * Commit the plan-once probe behind the gvar size figure Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * Record offset subdivision as a replayable plan * Tighten the affine-in-distance tolerance and document offset_plan.dart's public API Bound the affine-in-distance test to the measured float32 residual (~1.9e-6) rather than a margin against coordinate scale, and add dartdoc to OffsetPiece.evaluate, OffsetPlan.pieces, and OffsetPlan.evaluate. * Record straight-segment classification as a contour shape * Force a recorded closing-point drop instead of re-deciding it on replay * Plan stroked path topology once and evaluate it per width * Fix two width-dependent branches in StrokeJoiner The round join's arc sweep and the coincidence test's absolute threshold were not width-invariant despite being asserted as such: the sweep was recovered from atan2 of offset points whose float32 rounding scales with the radius, landing an ordinary 90 degree corner on the knife edge of arcToCubics' ceil; the coincidence threshold compared a squared distance that scales with radius squared against a fixed constant. Derive the sweep from incoming/outgoing directly and scale the threshold by radius squared instead. Fixes a latent inconsistency in stroke_joiner_test.dart's joinOuter fixture (from did not match vertex + radius * leftNormal(incoming), confirmed against a real offset chain) that the old round join never noticed because it read from/to positions only. Extends stroke_plan_test.dart's topology sweep to a chevron (exact 90 degree corner) and a near-collinear corner, across the full cap/join matrix, so both fixes have a regression test; without them the sweep fails on the chevron and near-collinear paths respectively. * Regenerate example font and note the round-join behaviour change Critical 1 (fix round 1) legitimately changes CFF output for icons with an exact-90 degree round join: the arc's segment count now comes from the source tangents rather than from offset coordinates whose floating-point error scaled with the stroke width. That makes the checked-in example fixture stale, not the code wrong, so regenerate it via example/tool/generate.dart and record the behaviour change in CHANGELOG.md. * Give an exact quarter-turn arc an epsilon against ceil's knife edge arcToCubics split an arc into ceil(sweep / 90°) cubics, but sweep arrives as the difference of two atan2 calls on float32-rounded unit tangents, so an exact 90° corner lands a hair above or below the boundary depending on which way the rounding fell. Landing above doubled the segment count for what is geometrically one quarter turn - and both of this repo's own round-joined right angles (arrow_right, check) land on the expensive side. Subtract a small epsilon from the ratio before rounding up, sized from the actual float32 error measured through the real tangent chain (worst case ~2.15e-7 across 100k sampled orientations and radii 1-1000), with a decade of margin. A genuinely-larger sweep (91°) and a round cap's exact -pi sweep are unaffected - the epsilon is four orders of magnitude smaller than the smallest real excess it has to keep catching. Floor the segment count at 1 so a tiny-but-nonzero sweep can't round down to zero. Regenerate example/fonts/my_icons.otf: both arrow_right and check lose the doubled arc segment (-3 points each). * Re-derive the quarter-turn epsilon from real coordinate scales The epsilon added for the exact-90deg round-join fix was sized from a synthetic sweep that only varied orientation and leg length, with the corner pinned at the origin - it missed catastrophic cancellation in tangentAt's p1 - p0, which dominates once a corner sits far from the origin (two large, closely-spaced float32 coordinates subtracted to recover a short leg). That measurement's ceiling (2.15e-7) was already contradicted by arrow_right's own real excess (2.68e-7) in the original report. Re-measured both ends properly: the noise, by sweeping vertex offsets 0-2000 and leg lengths 0.5-50 through the real tangent chain (500k samples, worst positive excess 3.39e-4); and how much excess is geometrically free to absorb, by measuring the single-cubic approximation's own error growth (negligible - 1.2% over baseline - all the way out to several percent, with the real ceiling being the 91deg boundary this rule must still distinguish, not the geometry). That gives a window of roughly 1e-3 to 5e-3; chose 2e-3, ~5.9x above the measured noise and ~5.6x below the 91deg boundary. Added a lower-bound-guard test (a tiny sweep must not raw-ceil to zero segments) and a far-from-origin join test that fails at the old epsilon and passes at the new one. Narrowed the CHANGELOG claim to the coordinate range this was actually validated against instead of an unqualified "always". No fixture change - both real example icons' excess is far below either epsilon value. * Build point-compatible glyph masters for a stroke width range * Share one fitting transform across glyph masters Add GlyphPlacement and GlyphFitting.placementFor so a single scale and offset, derived from one reference master, can be applied to several masters that share topology. Fitting each master independently would scale a thicker stroke's bigger ink box differently than a thinner one's, moving the centreline between them and bending every interpolated width. placementFor mirrors resize()/center() exactly, including resize's near-identity early return, so placementFor(g).apply(g) reproduces fit(g). * Fix GlyphPlacement corrupting bounds for non-translating fittings GlyphPlacement.apply always translated, even by zero, but _translate's bounds formula (lifted from GlyphTransform.center to stay byte-identical with it) rebuilds the rectangle from bounds.bottom where Rectangle's constructor expects top — so a zero translate still reset the rectangle's origin. Invisible for NormalizedFitting, whose fit() always calls center() too, so both sides carried the same defect and cancelled; real for ArtboardFitting, whose fit() never translates at all. Add an explicit translates flag rather than inferring "skip the translate" from offsetX/offsetY being zero, since NormalizedFitting can legitimately compute a zero offset for an already-centred glyph. GlyphTransform.center's own bottom-as-top formula is left alone: it is pre-existing and the single-width byte-identity test depends on it. * Pin the affinity of stroke geometry in the width * Threshold parallel-tangent detection on float32 noise, not kZeroLength approximateOffset compared the raw, -9-scaled determinant against kZeroLength (1e-12), a length-scale constant unrelated to that quantity. Vector2 is float32-backed, so a mathematically straight edge's tangents round to values one ULP apart, putting the determinant six orders of magnitude above that threshold — the code took the near-singular 2x2 solve instead of the exact parallel fallback, amplifying rounding noise by ~1e6. Threshold the normalised cross product instead (dimensionless, reads as sin(angle) without the incidental -9), against an epsilon of 2e-3 sized from measurement on both sides: the worst noise a mathematically parallel pair of tangents produces across a wide sweep of directions and coordinate scales (2.8e-4), and the point past which the 2x2 solve - built on the same near-singular determinant - stops being reliably better than the fallback (~1e-3 to 7e-3). Fixes the affinity-test failure added in the prior commit: the triangle fixture's worst residual drops from 0.322 to 4.26e-6, and its two affected edges collapse from 193/66 offset pieces to 1 each. Regenerates example/fonts/my_icons.otf (arrow_right 376->37 points, check 97->22; plus/menu unaffected) and extends the existing Unreleased changelog entry. * Address review of the parallel-tangent epsilon fix State the load-bearing reason the fix is correct rather than just quieter: the fallback branch's alpha/beta depend only on the source curve, so every emitted control point is exactly affine in the stroke width, while the solve branch divides by the same near-singular determinant that makes the noise problem amplify in the first place. Routing near-parallel geometry to the fallback moves it onto the branch that is structurally affine, not merely a less noisy one. Close two test gaps the review found: stroke_affinity_test.dart only ever exercised (round, round), leaving SVG's actual defaults (butt, miter) - and the miter/bevel/butt/square branches entirely - unguarded; and every one of its per-segment loops was bounded by the output's own length, so it passed vacuously on empty output. Now loops three (cap, join) combinations covering every branch, and asserts each fixture's expected contour count. Verified against the same mutations the review used (miter tip, bevel join, butt cap, square cap): all four now fail the test; previously none did. Pin the epsilon from above with a shallow-arc case in offset_approximation_test.dart (cross ~1e-2 must still take the 2x2 solve), verified against epsilon mutations up to 5e-1. Correct the documented noise floor (2.8e-4 -> 3.66e-4, matching the closed form) and its margin (7x -> 5.5x) in both the doc comment and the CHANGELOG; fix the CHANGELOG's self-contradiction between "distorted control points" and "shape unaffected" (the shape does move, slightly, toward the true offset, well inside the existing curve tolerance); and correct "two affected edges" to describe the one edge that is actually offset twice (once per contour direction). * Add fvar table with a literal stroke width axis * Fix fvar instanceSize: spec's formula applies with zero instances too * Add STAT table for the stroke width axis * Regenerate variable-prototype fonts and retire the gvar render matrix candidate example/fonts/proto/ still held fonts built before 0.5.2 and before this branch's geometry fixes, so the render matrix was testing stale artefacts. Rebuilding from tool/variable_prototype/ reconfirms uniE002 (ring) is still point-incompatible across glyf masters, so varLib still drops its gvar variation entirely (documented in tool/variable_prototype/README.md). Task 5 already ruled out gvar; keeping it as a render-matrix candidate would make the standing gate red on every run for a defect that has no planned fix, so drop the ProtoGvar/ProtoGlyf* families and the gvar candidate along with it. * Validate generated fonts against fonttools in CI The package's own reader agreeing with its own writer proves nothing about the outside world. tool/oracle/validate_font.py loads a font with fonttools, round-trips it, and for a variable font asserts a STAT table exists and its axis range is non-empty. CI runs it against example/fonts/my_icons.otf (static — fvar/STAT aren't wired into the builder yet) and example/fonts/proto/variable_cff2.otf, the one real variable font in the repo, so the oracle's variable branch is actually exercised rather than merely written. * Wire the variable stroke render matrix into CI example/integration_test/variable_stroke_test.dart exists and passes locally but nothing ran it automatically, so a regression could sit unnoticed. Add a job that installs Flutter and a chromedriver matched to the runner's Chrome major version (via the Chrome for Testing catalog, so it doesn't depend on apt happening to ship a compatible pair), then runs the matrix on Chrome/ CanvasKit via `flutter drive` — the one leg of the platform matrix that needs no emulator or extra OS runner. macOS/iOS, Android and Chrome/skwasm are deliberately left out, each with a comment explaining why (macOS/iOS need a macOS runner, Android needs a slow emulator boot, skwasm's flutter-drive output can't be attributed per test). Linux and Windows desktop were never covered even during Phase 0 measurement. Absence is documented rather than left to read as a silent pass. * Exclude native example scaffolding and dev tooling from the published package example/android, example/ios and example/macos (~90 generated Gradle/Xcode files) exist only so the render matrix has somewhere to run, and tool/ (Phase 0 fonttools prototypes, the fonttools oracle) is repo-only tooling. Neither belongs in a pure-Dart package's tarball. /tool/ is anchored to the repo root so it does not also swallow example/tool/, which example/pubspec.yaml's own tooling still needs. * Add a virtual display for the web render-matrix job's headed Chrome Verified against a real run on GitHub's ubuntu-latest: flutter drive -d chrome launches Chrome headed regardless (flutter/flutter#95085 — its own headless plumbing for drive doesn't reliably take effect), so it failed with "Missing X server or $DISPLAY" and never reached the test. Wrap the drive invocation in xvfb-run so Chrome has a virtual display to open a window against. * Drive the web render matrix via -d web-server, not -d chrome Verified against a real run on GitHub's ubuntu-latest: -d chrome connects to Chrome as the running device through DWDS's own debug-service handshake, which threw AppConnectionException and then hung indefinitely rather than failing (reproduced identically on macOS locally with matched Chrome/ chromedriver versions, so it isn't runner-specific). -d web-server --browser-name=chrome sidesteps DWDS entirely for driving: flutter_tools serves the app over plain HTTP and the webdriver package drives a chromedriver-controlled browser session against it directly. Verified locally: passes in well under a minute. The virtual-display workaround from the previous commit is no longer needed with this device and is removed. * Flag that the OTF writer and reader silently drop fvar/STAT _kTableTagsToEncode and the reader's table-tag switch both predate the variable-width axis work and have no entries for fvar/STAT. Right now that is harmless, but Phase 4 will build both tables and insert them into tableMap — at which point encodeToBinary would drop them from the font with no error, and OTFReader would drop them on the way back in, so the package could not even read its own output. Comment both sites so whoever wires the axis in cannot miss the two lists they need to extend. * Document that the oracle's variable-font branch cannot yet fail CI's fonttools oracle only exercises its fvar branch against example/fonts/proto/variable_cff2.otf, which fontTools' own varLib built, not this package — fontify_plus does not emit fvar/STAT yet. The workflow file already says so in a comment; the script itself, which is what anyone extending the oracle will actually open, did not. State the caveat in the docstring, and what turns the gate real: a font this package generated once Phase 4 lands. * Pin offset plans to the range maximum, and test that it matters Point counts are fixed by whatever distance a plan is built at, so every structural test — piece count, affine interpolation, topology — passes identically whether the plan was built at the range's minimum or its maximum. Only geometric fidelity tells the two apart, and only over a range wide enough to separate them: at the 1.33-2.0 stroke widths this package ships today the two are indistinguishable, but at 0.5-6.0 a plan built at the minimum strays up to ~4.8x kCurveTolerance from the true offset while one built at the maximum stays inside it. Phase 4 is what makes a wider range configurable, so this has to be pinned, and demonstrated, before then. test/src/svg/stroke/stroke_plan_test.dart's topology test built its plan at _widths.first — the minimum — and swept upward; it passed regardless, which is the direct proof that a structural check alone cannot enforce this. Build it at _widths.last instead, matching the discipline the new geometric test requires. * Move the parallel-tangent epsilon fixture off a hair-trigger boundary The "genuinely diverge" test's shallow-arc fixture crossed at 1.0013e-2 — only ~0.1% above 1e-2 purely by float32/cubic-approximation rounding. That margin is so thin that mutating _kParallelTangentEpsilon to exactly 0.01 (the value someone reaching for "a bit bigger than 2e-3" is likely to type) survived undetected, saved only by which way the rounding happened to fall; a mutation to 1.02e-2 was caught only because it landed on the other side of that same accident. Verified by temporarily setting the constant to each value and running this test: 1e-2 passed (undetected), 1.02e-2 failed (caught) — confirming the review's numbers. Moving the fixture up, as suggested, does not fix this: it raises the fixture's own cross product further above 0.01, which only widens the range of undetected mutations (re-verified — 1.02e-2 then also survives). Closing the gap requires moving the cross product below 0.01 instead, so the 0.01 mutation pushes it into the fallback branch and breaks the midpoint assertion. math.asin(9.5e-3) does that with a deliberate ~5% margin; re-verified against both 1e-2 and 1.02e-2 with the same method. * Drop an unreachable branch and assert contour lengths stay matched _offsetSide's `if (offset.isEmpty) continue;` cannot run: OffsetPlan.evaluate always returns one cubic per recorded piece, and CubicOffsetter._plan always records at least one. Its rationale was true of the old _offset API this plan/evaluate split replaced, not of this one — and were it ever reachable, skipping straight to the next segment would join against segments[i - 1].tangentAt(1) while result.last actually came from segment i - 2, which is wrong. Remove it rather than carry a stale justification for dead code. The affinity test's per-segment loop was bounded only by actual[c].length, so a regression that shortened a contour's tail at one width but not another — exactly the join/cap width-invariance the plan/evaluate split leans on — would pass with zero assertions made on the missing tail. Assert low[c].length and high[c].length match actual[c].length first. * Refresh the Phase 0 prototype README's stale outstanding-work notes The closing "what this does not establish" section still listed the stale proto fonts and the ProtoGlyf*/ProtoGvar retirement as outstanding; commit c1b5a16 did both. The opening line's "Nothing here is shipped" was also out of date — the regenerated fonts under example/fonts/proto/ ride in the pub tarball and gate CI. This is the first document a Phase 4 implementer reads, so it should describe the current state, not Phase 0's. * Choose charstring operators from every master at once The CFF shorthands encode a dropped delta as an implicit zero, so picking them from one master's coordinates would silently discard a movement another master makes. Replace `char_string_shorthand.dart` with `char_string_form.dart`, which decides the operator and the surviving operand indices from all masters at once, and route both the encoder and `CharStringOptimizer`'s two value-dependent passes through that one decision. A single master reduces every joint test to its own, so the emitted bytes are unchanged. Co-Authored-By: Claude Opus 5 <[email protected]> * Cover the joint merge with two masters that disagree Every multi-master fixture so far produced either hlineto/vlineto, which are never merged, or a lone rlineto/rrcurveto with no adjacent twin, so the merge in `_compactSameOperators` was only ever reached with a single master — where appending master 0's operands and appending each master's own are indistinguishable. Two mutations of that loop survived the whole suite, including byte identity. Add a diagonal three-point fixture that merges two rlineto commands, and a seven-point two-cubic fixture whose curves both take vvcurveto with no leading delta and therefore merge, and assert each master's merged operands separately. Both mutations now fail. Co-Authored-By: Claude Opus 5 <[email protected]> * Emit blend where two masters disagree Merges the per-master command streams produced by toCharStringCommandsForMasters into one CFF2 charstring: a command every master agrees on passes through unchanged, one that varies becomes a blend operator carrying the default values, the per-region deltas, and the operand count, followed by the drawing operator with no operands of its own. Also threads a regionCount parameter through CharStringInterpreterLimits and CharStringOptimizer so the argument-stack limit accounts for the extra operands a blend adds — without it the optimizer can merge a command past 256 operands, which then can't be blended without overflowing CFF2's 513-operand stack. * Pin the blend divergence guard down with an operator-only mismatch The guard at char_string_blend.dart that rejects masters diverging in operator or operand count had no test isolating the operator half: one existing case differed in operand count too, and the matcher was a bare throwsArgumentError, which also accepts the RangeError that an out-of-bounds index throws when the check is missing entirely. Add a same-operand-count, different-operator case (hlineto vs vlineto) and tighten the matcher to require an ArgumentError whose message actually says "diverge", so a weakened or deleted guard fails loudly instead of being masked by an accidental crash. Also: cover the empty-masters guard, add a three-master case that pins the delta loop's operand-major/region-minor ordering (previously indistinguishable from the alternative at regionCount == 1), resolve the code comment that deferred that ordering question, correct two inaccurate doc comments (the stack-limit field's meaning once regions exist, and the per-value delta cost), document the aliasing blendCommands relies on, and guard CharStringInterpreterLimits against a negative regionCount dividing by zero. * Give CFF2 a variation store and per-master charstrings * Reject region counts the CFF2 store builder cannot encode, and test the stack limit that guards against them * Encode fvar and STAT, and write the axis name record fvar and STAT were assembled elsewhere but missing from the encoder's tag allowlist, so a variable font would have been written with no axis and no error. Register both (last, so static fonts' byte layout is untouched) and thread an axisName through NamingTable.create so fvar's axisNameID and STAT's valueNameID resolve to a real name-table string, which OTS requires. The read side stays a documented gap: OTFReader has no case for either tag, so a read-modify-write round trip on a variable font silently drops both tables. Tracked in #12. * Hide the encode-set test alias from the public API, and fix stale comments debugTableTagsToEncode's own doc comment claimed it wasn't public API, but it was reachable through fontify_plus.dart's export chain — a downstream package could depend on it, and dartdoc would render it on pub.dev. Hide it on the otf/otf.dart export in src/otf.dart instead; the test that needs it imports the source file directly, like other tests in this repo already do for non-exported internals. Also correct three comments that drifted from what the code now does: reader.dart's dropped-table case logs a warning, so it isn't silent the way the write-side gap is; otf.dart's "last, so order is unchanged" parenthetical implied the encode set's iteration order matters when it doesn't, since encodeToBinary sorts the directory regardless; and naming_table_format0_test.dart still described strokeWidthAxis as contributed by another table, when NamingTableFormat0 has written it itself since the axisName parameter was added. Rename the os2_builder_test case that claimed to test "regardless of the wght axis range" to what it actually asserts, since buildOS2Table takes no such argument. * Look tables up by tag with the type checked, not with a cast `OpenTypeFont`'s thirteen table getters were each `tableMap[tag] as T`, which collapses three unrelated situations into one `TypeError` naming neither tag nor type: the tag is absent, the tag holds a different kind of table, or the caller asked for a table this font format does not have at all. `FontTables` owns the tag map and answers the third case honestly: `glyf`, `loca`, `cff`, `cff2` are now nullable, because a CFF font genuinely has no glyf and a TrueType font genuinely has no CFF. The tables every font must carry go through `require`, which names the missing tag and distinguishes absence from a type mismatch. `fvar` and `STAT` get the same nullable accessors, which the builder wiring will want next. `_encodeTables`' `(table as CalculatableOffsets)` sat one line under an `is CalculatableOffsets` test; it is now a pattern that binds the typed name from the same runtime check, since `CalculatableOffsets` is not a subtype of `FontTable` and so cannot promote. `OpenTypeFont.tableMap` keeps its shape as a read-only map view, so the callers that iterate or count tables are untouched. Co-Authored-By: Claude Opus 5 <[email protected]> * Read config values through typed readers instead of casting them `resolveFontJob` reached into the merged map with `merged[field] as bool?`. That is safe only because `coerceJobValues` ran first, which the compiler cannot see through a `Map<JobField, Object?>` — so a value that ever reached a read without being coerced would surface as a bare `_TypeError` naming neither the key nor the expected type. `readBool`/`readInt`/`readString` and their `require` counterparts re-check and throw the same `FontifyException`, naming the config key, that every other config mistake produces. The re-check costs nothing at config sizes. `parseArgsAndConfig` reads argv through `ArgResults.flag`/`option` rather than casting the `dynamic` from `argResults[...]`. Co-Authored-By: Claude Opus 5 <[email protected]> * Announce the OpenTypeFont API breaks, and drop the last table-map casts from tests Two changes from the previous two commits are source-breaking for a package published at 0.5.2 whose `OpenTypeFont` carries `{@category api}`, and neither was in the CHANGELOG: `glyf`/`loca`/`cff`/`cff2` went non-nullable to nullable, so a downstream `font.glyf.glyphList` stops compiling on upgrade. `tableMap` became an unmodifiable view, which is the worse of the two because it gives no compile-time warning at all: a write still compiles and now throws `UnsupportedError` at runtime. Both entries spell out the migration. The tests kept ten `font.tableMap[tag] as XTable` reads in `ttf_test.dart` and two more in `otf_builder_test.dart` — the exact pattern this refactor exists to delete, sitting beside the helper that models the replacement. They now go through the typed accessors. The `name` one stays a `require<NamingTableFormat0>`: its assertions read format-0 fields, so it does mean to pin down the subtype. `job_values_test.dart`'s "uncoercible value" test passed before this refactor too — `_coerceField` rejects the value before any reader runs, so the readers' re-check is unreachable from `resolveFontJob`. Renamed to what it actually covers, with a note pointing at the tests that do exercise the reader path. Co-Authored-By: Claude Opus 5 <[email protected]> * Name OS/2's constructor parameters so neighbours cannot transpose OS2Table took 39 positional parameters, about thirty of them adjacent ints. ySubscriptXSize/ySubscriptYSize are neighbours of the same type, as are the four ulUnicodeRange fields, the two ulCodePageRange fields and the sTypo*/usWin* runs, so swapping any adjacent pair compiled, analyzed clean and shipped a font wrong in a way only rendering would reveal. The two call sites -- os2_builder.dart and os2_reader.dart -- had to agree on all 39 by position. Values move verbatim; no encoded field order changes. Co-Authored-By: Claude Opus 5 <[email protected]> * Group OS/2's fields by the version that introduced them The class doc already stated the rule -- everything past version 0 is nullable because a lower-version table simply ends early -- but nine independently-nullable fields express it as nine independent choices, so sxHeight set while ulCodePageRange1 is null was constructible even though OpenType cannot produce it. Each version's addition is now its own object, and a null group means the table stops there. version stays a stored int rather than being derived from the highest non-null group. test/assets/test_cff2_font.otf is a version-3 table: OpenType 3 adds no fields over 2, this package's version map has no entry for either, so it is read with the version-1 group and nothing above it. Deriving would rewrite its version field from 3 to 1 on the way out. size is now counted from the groups present instead, which agrees with the old version-driven sum for every table the reader can build, and the encoder's nine force-unwraps are gone with it: a group that is there is the table's own statement that its version declares those fields. Field offsets and write order are unchanged; the example font still regenerates byte for byte. Co-Authored-By: Claude Opus 5 <[email protected]> * Name the wide positional constructors the OS/2 audit turned up Same hazard, thirteen more classes: HeaderTable took fourteen positional parameters (nineteen on its private constructor), HorizontalHeaderTable and MaximumProfileTable.v1 fifteen, CmapSegmentMappingToDeltaValuesTable thirteen, CFF1Table eleven, PostScriptTableHeader nine after a Revision, SimpleGlyphFlag seven bools in a row, and CFF2Table, NameRecord, NamingTableFormat0Header, LookupTable, GlyphSubstitutionTableHeader, CmapSegmentedCoverageTable and ItemVariationStore between four and nine. Every one of them had a run of adjacent same-typed parameters where a transposition compiles and analyzes clean. The table record entry stays positional where a constructor takes one -- it is the odd type out and never confusable with the fields. Values move verbatim: no field, name, type or encoded offset changes. Constructors of five parameters or fewer were audited and left; the report lists them with a verdict each. Co-Authored-By: Claude Opus 5 <[email protected]> * Nest the OS/2 version groups and reject a version that lies Review found the type-safety claim was false and the refactor had turned a loud failure into a silent one. Two fixes. The groups nest now -- OS2Version1Fields owns the version-4 group, which owns the version-5 group -- because OpenType's versions are cumulative. A higher group has nowhere to live except inside a lower one, so sxHeight set while ulCodePageRange1 is absent no longer type-checks, by construction rather than by check. version4 and version5 stay on the table as shorthand getters; the reader, encoder and builder walk the nesting itself. Nesting cannot enforce that `version` agrees with the groups, because `version` is stored rather than derived. That check now throws TableDataFormatException instead of asserting. The old encoder force-unwrapped each optional field, so a version-5 table missing its version-5 group crashed on the spot; an assert restored nothing in a release build, where the grouped code would instead have emitted a 96-byte table whose version field claimed 100 bytes of content. Verified under plain `dart run` and an AOT-compiled binary, both with asserts off. The round-trip fixture gave equal values to fields that must be distinguishable -- ulUnicodeRange2/3/4 all zero, usDefaultChar and usBreakChar both 32, sTypoAscender and usWinAscent both 800 -- so four field-mapping mutations survived the whole suite. All 38 fields now hold distinct values, and a field-by-field comparison runs beside the byte comparison: an encoder that writes two fields to one offset round-trips its own bytes perfectly and loses a value, which only the field comparison catches. Also corrects what the docs claim about `size` on a corrupt table whose version reads back negative: 78 bytes and a version-0-shaped encode, where the pre-refactor code measured 0 and failed mid-encode. Co-Authored-By: Claude Opus 5 <[email protected]> * Name every remaining constructor whose neighbours share a type The previous round used "six or more positional parameters" as the audit's threshold. The brief's criterion is the transposition itself -- adjacent parameters of the same type -- and a count appears nowhere in it. The substitution left nineteen constructors meeting the stated criterion, including the worst trap the audit found: GlyphHeader(numberOfContours, xMin, yMin, xMax, yMax) orders the same four concepts differently from GenericGlyphMetrics(xMin, xMax, yMin, yMax), so a maintainer fresh from one writes the other's order and every glyph's bounds interleave x and y, with a clean analyze. Converted, on the real criterion: GlyphHeader, GenericGlyphMetrics, Outline, SimpleGlyph, OffsetTable, TableRecordEntry, CmapSegment, CmapByteEncodingTable, CharacterToGlyphTableHeader, EncodingRecord, SequentialMapGroup, CFF1TableHeader, CFF2TableHeader, CFFIndex, ItemVariationData, VariationRegionList, RegionAxisCoordinates, CoverageTableFormat1, FeatureTable, LanguageSystemTable, ScriptTable and LigatureSubstitutionSubtable. Left, each for a reason that is not a count: Cubic(p0, p1, p2, p3) and CFFOperator(context, b0, b1) take an indexed sequence, where the name is the index and naming protects nothing; every other three-or-more constructor -- LookupListTable, FeatureListTable, ScriptListTable, PostScriptVersion20, CharacterToGlyphTable, HorizontalMetricsTable, NamingTableFormat0, PostScriptTable, CFFIndexWithData, GenericGlyph -- has distinct types at every adjacency, so a transposition does not compile. Two-parameter constructors are pairs, not lists. 188 call sites were compared against the previous revision expression by expression: labels added, no value moved. Co-Authored-By: Claude Opus 5 <[email protected]> * Close the last four same-typed adjacencies the audit missed Re-review ran an independent mechanical audit and found three constructors that fit none of the categories the CHANGELOG listed as exhaustive, plus the one I had flagged as weakest and then left anyway. Same species as the round-1 finding: a doc claiming a completeness the code did not have. SimpleGlyphFlag.createForPoint(x, y, isOnCurve) is an x/y adjacency -- the exact trap this work set out to close -- and is called from glyph_true_type_encoding.dart as createForPoint(relX[i], relY[i], ...), the same interleaved-x/y context cited as the reason to convert GlyphHeader. CFFOperand.fromByteData and CharStringOperand.fromByteData each take an adjacent offset and b0. HorizontalHeaderTable.create takes adjacent ascender and descender, passed as bare literals at five sites, where a swap compiles into a negative ascender that only byte identity would catch. Two constructors in lib/ still have three or more positional parameters with a same-typed adjacency, and the CHANGELOG and report now name both rather than leaning on categories: Cubic(p0, p1, p2, p3), whose parameters are an indexed sequence, and IndexToLocationTable.fromByteData, which the re-review judged defensible -- one library call site, distinctly-named locals, and a swapped 0/1 format flag against a glyph count that fails loudly. 43 call sites compared against the previous revision expression by expression: labels added, no value moved. Co-Authored-By: Claude Opus 5 <[email protected]> * Assemble a variable font from two masters Every piece existed separately: point-compatible masters, blended CFF2 charstrings, the variation store, fvar, STAT, the axis name record and the encoder registration. This is the first time they are put together into a font. OpenTypeFontBuilder and OpenTypeFont.createFromGlyphs take minGlyphList and strokeWidthRange. glyphList stays the default master (the maximum width), because that is what fvar's default instance selects and what head, hhea and hmtx are computed from -- advances do not vary with the axis, which is why no HVAR is written. Both masters are fitted with one placement, taken from the default master. Fitting the thinner master independently would scale it up to fill the same em band, moving the centreline between the masters and bending every interpolated width -- a font that parses, sanitizes and renders correctly at both endpoints and subtly wrong everywhere else. The test asserts it on geometry read back out of the charstrings: the minimum master's ink box strictly inside the maximum's, with the same centre. Both assertions fail if the placement is not shared. StrokeWidthRange is exported so callers can name the new parameter's type. Co-Authored-By: Claude Opus 5 <[email protected]> * Let the oracle demand a variable font, and correct its stale caveat The docstring said fontify_plus emits no fvar/STAT and pointed at two call sites as evidence; both are now wired, so the claim was false. It also promised the branch would become a real gate once the builder emitted the tables -- half of which has now happened, while CI still feeds it the varLib fixture. Say what is true instead, and say plainly what this script still does not check. --variable makes the assertion explicit rather than leaving a silently static build to pass as "static font, parses and round-trips"; without it the script behaves exactly as before. The axis name is checked too: OTS rejects a variable font whose axisNameID resolves to no name record, and this task is what started writing that record. Co-Authored-By: Claude Opus 5 <[email protected]> * Pin which master the shared transform comes from, and stop claiming advances are the em Review found four green assertions that were false or absent. The advance-width justification was wrong on the default path. It said the advance is the em square, so it cannot vary with the axis. Under normalize: true -- the default -- advanceWidthOverrides is all null and each custom glyph advances by its own ink width: 947, 1000, 958, 1000 for the four example icons. The no-HVAR conclusion holds for a different reason, that hmtx is written once and so is axis-invariant by construction. Corrected in the builder and in the CHANGELOG, where it was shipping text a reader could have laid out a 1em grid on. Nothing pinned that the shared placement comes from the *default* master. Taking it from minGlyphList instead left the whole suite, byte identity and the oracle green while every icon overflowed the em by 6-8%. Now checked on all four example icons, including the two already sitting exactly on 1000 with no slack to hide it. Nothing pinned that STAT agrees with fvar. Building STAT from a different range passed everything, leaving format 1 axis values off the axis where style matching offers instances no coordinate can select. This is the task whose job is making the separately built tables agree. The centre tolerance's comment blamed round-cap geometry. check's masters agree to 16 digits at full precision; its 0.5 is entirely integer truncation. The glyph with genuine geometric drift is arrow_right at 0.962, which truncates to exactly 1.0 and passed only because closeTo is inclusive. The comment now names both mechanisms, the assertion covers all four icons, and the tolerance moves to 2 -- off the boundary, and still 17x below the 34-unit failure it guards. Also: say in test 8 that its strict > depends on metrics truncating each extreme independently, so a future task making them exact turns it red while improving the code; cover normalize: false, the one reachable combination the file missed; and drop the k prefix from a non-const final. Co-Authored-By: Claude Opus 5 <[email protected]> * Take a stroke width range through the public API * Pin the default-master identity and the charcode-bearing glyph list Neither svgToOtf's "which master is default" wiring nor its "which list carries charcodes" wiring had a test that could tell an inversion from success: swapping glyphList/minGlyphList, or leaking minGlyphList out as result.glyphList, left the whole suite green. Add tests that compare result.glyphList against an independently built max master, and that exercise generateFlutterClass on a range-built result, so both inversions now fail loudly. Also extend the mixed-width-warning coverage to two files, and add the same-name-twice case that is what actually distinguishes logger.w from logger.logOnce, since two different files' messages never collide either way. * Accept stroke_width_range from YAML and the CLI Exposes svgToOtf's existing strokeWidthRange as stroke_width_range in the font-set YAML config (also allowed in defaults:, since a config usually shares one icon library and range across its font sets) and as --stroke-width-range on the CLI. YAML takes a two-element list of numbers; the CLI takes the same pair as one comma-separated string. There is no built-in default, since the range sets both the variation's delta magnitude and how deeply every glyph is subdivided. resolveFontJob duplicates svgToOtf's outline_strokes/opentype conflict checks so a config-file mistake fails as a FontifyException naming the YAML keys involved, rather than a stack trace from inside font generation. StrokeWidthRange's own ArgumentError (min <= 0, max <= min) is now caught during coercion and rethrown as a FontifyException naming the config key and the offending value. * Reject non-finite stroke_width_range endpoints during coercion NaN and Infinity both parse as num, and YAML's .nan/.inf arrive as non-finite doubles directly, so neither was caught by the "must be a number" check. StrokeWidthRange's own min <= 0 / max <= min guards don't catch every non-finite case either (NaN <= 0 is false, and an infinite low endpoint is never <= a finite max), so a non-finite range used to reach font generation and fail there with an unrelated internal error instead of the config error this coercion layer exists to produce. Also documents --stroke-width-range / stroke_width_range in doc/cli.md, which listed every other flag and config key but this one. * Document the stroke width axis in the generated class Co-authored-by: Cursor <[email protected]> * Document the variable stroke width axis and cut 0.6.0 Co-authored-by: Cursor <[email protected]> * Gate the package's own variable font on size, oracle and render Co-authored-by: Cursor <[email protected]> * Make BinaryCodable hierarchy constructors const Subclasses that extend BinaryCodable cannot be const until the base declares an explicit const constructor; the implicit one is not. Co-authored-by: Cursor <[email protected]> * Make OTF BinaryCodable leaf constructors const FontTable stays non-const because entry is reassigned during encode. CFFDictEntry is const-capable but its operandList is mutated in place; the CFF2 builder keeps a growable list so recalculateOffsets can clear it. Co-authored-by: Cursor <[email protected]> * Make remaining value-type constructors const Job, CLI, metrics, and exception types with all-final fields, plus the call sites prefer_const_constructors now allows. Co-authored-by: Cursor <[email protected]> * Extract CharStringFormChooser for across-master form choice Co-authored-by: Cursor <[email protected]> * Extract CharStringBlender with regionCount property Co-authored-by: Cursor <[email protected]> * Replace multi-master extension with CharStringEncoder Co-authored-by: Cursor <[email protected]> * Extract SingleRegionVariationStore builder class Co-authored-by: Cursor <[email protected]> * Coordinate regionCount via Cff2RegionContext Co-authored-by: Cursor <[email protected]> * Extract GlyphMasterBuilder for stroke-width masters Co-authored-by: Cursor <[email protected]> * Prefer const CharStringFormChooser in form tests Co-authored-by: Cursor <[email protected]> * Keep SingleRegionVariationStore normalized coords as class constants Co-authored-by: Cursor <[email protected]> * Pin regionCount rejection to SingleRegionVariationStore by name Co-authored-by: Cursor <[email protected]> * Close final-review gate holes so package bugs can turn CI red Rebuild proto fonts in CI before the oracle and render matrix, install fonttools before dart test so the subset size gate runs, require the default-endpoint static reference without a silent fallback, and assert fvar/STAT appear in the encoded SFNT directory. Co-authored-by: Cursor <[email protected]> * Install root package deps before rebuilding proto fonts on CI Co-authored-by: Cursor <[email protected]> * Remove stray line that broke ci.yml YAML parsing Co-authored-by: Cursor <[email protected]> * Tighten the 0.6.0 changelog to release notes, not a design essay Co-authored-by: Cursor <[email protected]> * Format files that CI's dart format check rejected Co-authored-by: Cursor <[email protected]> * Fix broken # comments in variable stroke render matrix test Co-authored-by: Cursor <[email protected]> * Make proto ring a real stroke so variable fonts carry blends Pre-offset filled contours have no stroke for GlyphMasterBuilder to vary, so CI-rebuilt variable fonts ignored the axis on ring and the render matrix failed. Co-authored-by: Cursor <[email protected]> --------- Co-authored-by: Claude Opus 5 (1M context) <[email protected]> Co-authored-by: Cursor <[email protected]>
1 parent 5a8e23c commit aaf1a50

324 files changed

Lines changed: 14331 additions & 1913 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.github/workflows/ci.yml‎

Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,9 +36,127 @@ jobs:
3636
- name: Analyze
3737
run: dart analyze --fatal-infos
3838

39+
# fonttools before dart test so variable_size_gate_test's pyftsubset
40+
# half is not skipped on the stable job that also runs the oracle.
41+
- uses: actions/setup-python@v5
42+
if: matrix.sdk == 'stable'
43+
with:
44+
python-version: '3.12'
45+
46+
- name: Install fonttools and opentype-sanitizer
47+
if: matrix.sdk == 'stable'
48+
run: pip install fonttools opentype-sanitizer
49+
3950
- name: Run tests
4051
run: dart test
4152

53+
# Independent OTF / variable-font checks against fonts this package
54+
# just built (not committed fixtures, not varLib). Rebuilds protos so
55+
# a writer regression turns this job red even if binary assets are stale.
56+
- name: Rebuild package-built proto fonts
57+
if: matrix.sdk == 'stable'
58+
run: python3 tool/build_proto_fonts.py
59+
60+
- name: Validate generated fonts against fonttools
61+
if: matrix.sdk == 'stable'
62+
run: |
63+
python3 tool/oracle/validate_font.py example/fonts/my_icons.otf
64+
python3 tool/oracle/validate_font.py \
65+
--variable example/fonts/proto/variable_cff2.otf \
66+
--static-prefix example/fonts/proto/static_
67+
68+
variable-stroke-render-matrix:
69+
name: Variable stroke render matrix (web)
70+
runs-on: ubuntu-latest
71+
steps:
72+
- uses: actions/checkout@v5
73+
74+
- uses: subosito/flutter-action@v2
75+
with:
76+
channel: stable
77+
78+
- run: flutter config --enable-web
79+
80+
- name: Install a chromedriver matching this runner's Chrome
81+
run: |
82+
set -euo pipefail
83+
chrome_version="$(google-chrome --version | grep -oE '[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+')"
84+
chrome_major="${chrome_version%%.*}"
85+
echo "Runner Chrome: $chrome_version (major $chrome_major)"
86+
driver_url="$(curl -fsSL https://googlechromelabs.github.io/chrome-for-testing/known-good-versions-with-downloads.json \
87+
| jq -r --arg major "$chrome_major" \
88+
'[.versions[] | select(.version | startswith($major + "."))] | last | .downloads.chromedriver[] | select(.platform=="linux64") | .url')"
89+
echo "chromedriver: $driver_url"
90+
mkdir -p "$RUNNER_TEMP/chromedriver"
91+
curl -fsSL "$driver_url" -o "$RUNNER_TEMP/chromedriver.zip"
92+
unzip -j -o "$RUNNER_TEMP/chromedriver.zip" "*/chromedriver" -d "$RUNNER_TEMP/chromedriver"
93+
chmod +x "$RUNNER_TEMP/chromedriver/chromedriver"
94+
echo "$RUNNER_TEMP/chromedriver" >> "$GITHUB_PATH"
95+
96+
- name: Start chromedriver
97+
run: |
98+
chromedriver --port=4444 &
99+
for _ in $(seq 1 30); do
100+
curl -sf http://localhost:4444/status && exit 0
101+
sleep 1
102+
done
103+
echo "chromedriver never became ready" >&2
104+
exit 1
105+
106+
- name: Install example dependencies
107+
working-directory: example
108+
run: flutter pub get
109+
110+
# Root package config for `dart run bin/fontify_plus.dart` inside
111+
# build_proto_fonts.py — example/ flutter pub get does not create it.
112+
- name: Install package dependencies
113+
run: dart pub get --no-example
114+
115+
# Rebuild proto assets with the package CLI so the matrix judges this
116+
# commit's writer, not a stale committed fixture.
117+
- name: Rebuild package-built proto fonts
118+
run: python3 tool/build_proto_fonts.py
119+
120+
# `-d chrome` treats Chrome as the running device and connects to it
121+
# through DWDS's own debug-service handshake — verified against a real
122+
# run on this workflow's ubuntu-latest runner, that handshake throws
123+
# AppConnectionException and the process then hangs indefinitely
124+
# instead of failing (also reproduced locally on macOS with matched
125+
# Chrome/chromedriver versions, so this isn't runner-specific). `-d
126+
# web-server --browser-name=chrome` sidesteps DWDS for driving
127+
# entirely: flutter_tools serves the app over plain HTTP and the
128+
# `webdriver` package drives a chromedriver-controlled browser session
129+
# against it directly — the actual mechanism CI recipes for this use in
130+
# practice, unlike `-d chrome`'s development-workflow path.
131+
- name: Run the variable stroke render matrix on Chrome (CanvasKit)
132+
working-directory: example
133+
run: |
134+
flutter drive \
135+
--driver=test_driver/integration_test.dart \
136+
--target=integration_test/variable_stroke_test.dart \
137+
-d web-server --browser-name=chrome --headless \
138+
--web-port=8765 --driver-port=4444
139+
140+
# NOT COVERED by this workflow, and not silently assumed to pass:
141+
# - Chrome/skwasm (`flutter drive ... -d chrome --wasm`): same runner,
142+
# no extra infrastructure, but `flutter drive`'s web output
143+
# aggregates all assertions into one pass/fail block per run and
144+
# was unreliable to parse per-test even locally (task-4-report.md).
145+
# Left out to avoid a gate that can't localize its own failures.
146+
# - macOS desktop / iOS simulator: needs a macOS runner
147+
# (`runs-on: macos-latest`) plus, for iOS, a booted simulator; adds
148+
# real minutes to every push. A future job can add
149+
# `runs-on: macos-latest` and `flutter test ... -d macos` cheaply;
150+
# iOS additionally needs `xcrun simctl boot`.
151+
# - Android emulator: needs `reactivecircus/android-emulator-runner`
152+
# or equivalent, which boots a full AVD (KVM acceleration only
153+
# available on Linux runners, several minutes per boot) — slow
154+
# enough that Task 14 does not add it as a blocking gate.
155+
# - Linux and Windows desktop: Task 4 never ran these either (no
156+
# target existed on the Darwin host that measured the matrix); the
157+
# evidence gap documented in tool/variable_prototype/README.md
158+
# stands.
159+
42160
publish-dry-run:
43161
name: Publish dry-run
44162
runs-on: ubuntu-latest

‎.pubignore‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,17 @@ docs/
55
# Scratch and tooling that only matters in the repo.
66
.github/
77
CONTRIBUTING.md
8+
9+
# Native platform scaffolding for the Flutter example, kept in the repo only
10+
# so example/integration_test/variable_stroke_test.dart has somewhere to run
11+
# as a standing CI gate (android/ios/macos). None of it is needed to use the
12+
# example as sample code, and it is ~90 generated Gradle/Xcode files that add
13+
# nothing for a pure-Dart package's tarball.
14+
/example/android/
15+
/example/ios/
16+
/example/macos/
17+
18+
# Phase 0/Phase 3 dev tooling (fonttools prototypes, the fonttools oracle).
19+
# Anchored to the repo root so it does not also match example/tool/, which
20+
# example/pubspec.yaml's own tooling still needs.
21+
/tool/

‎CHANGELOG.md‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,36 @@
11
# Changelog
22

3+
## 0.6.0
4+
5+
* **Variable stroke width.** `stroke_width_range` (YAML),
6+
`--stroke-width-range` (CLI), or `strokeWidthRange` (`svgToOtf` /
7+
`createFromGlyphs`) emits a CFF2 variable font whose `wght` axis is the
8+
literal stroke width in SVG units — e.g. `Icon(MyIcons.home, size: 16,
9+
weight: 1.33)`. Requires `outline_strokes` and `opentype` (defaults). See
10+
`doc/variable_stroke.md`. Generated Flutter classes document the axis when
11+
a range is set. Without a range, static output stays byte-identical.
12+
* **Smaller fonts for everyone** (why this is a minor bump): offsetter fixes
13+
drop redundant subdivision on near-straight edges and exact 90° round
14+
joins. Example font 3112 → 2272 B; `arrow_right` 376 → 37 points, `check`
15+
97 → 22. Rendered shape is essentially unchanged.
16+
* **Breaking:** `OS2Table` uses named parameters and nested version groups
17+
(`version0` / `version1` / `version4` / `version5`). Read fields via
18+
`table.version0.…` or the `version4?` / `version5?` shorthands. A
19+
`version` that disagrees with the groups throws
20+
`TableDataFormatException`.
21+
* **Breaking for `src/` importers:** many other wide positional constructors
22+
now take named parameters (same hazard: adjacent same-typed args). Encoded
23+
layout unchanged; only `src/` imports are affected.
24+
* **Breaking:** `OpenTypeFont.glyf` / `.loca` / `.cff` / `.cff2` are nullable;
25+
use `?.` or `font.tables.require<…>(tag)`. New nullable `.fvar` / `.stat`.
26+
Missing required tables throw `TableDataFormatException` instead of
27+
`TypeError`.
28+
* **Breaking (runtime only):** `OpenTypeFont.tableMap` is read-only. Use
29+
`OpenTypeFont.tables` (`lookup` / `require`) instead of casting map values.
30+
Do not mutate `tableMap` after construction.
31+
* Known limits: this package writes `fvar`/`STAT` but does not read them back
32+
yet (#12). OS/2 v2/v3 round-trip truncation is pre-existing (#13).
33+
334
## 0.5.2
435

536
* Fix TrueType (`useOpenType: false`) output storing SVG cubic control points

‎README.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,15 @@ conversion leaves them invisible. fontify_plus outlines strokes by default
5252
data as fill geometry. Details, limitations, and troubleshooting:
5353
[doc/stroked_icons.md](doc/stroked_icons.md).
5454

55+
## Variable stroke width
56+
57+
Configure a minimum and maximum stroke width to emit a CFF2 variable font
58+
whose `wght` axis is the literal width in SVG units — `Icon(MyIcons.home,
59+
size: 16, weight: 1.33)` renders the icon drawn at width 1.33. YAML:
60+
`stroke_width_range: [1.33, 2]`; CLI: `--stroke-width-range=1.33,2`; API:
61+
`strokeWidthRange: StrokeWidthRange(1.33, 2)`. Requires outlining and OpenType
62+
outlines (both defaults). Full guide: [doc/variable_stroke.md](doc/variable_stroke.md).
63+
5564
## Glyph sizing
5665

5766
By default each glyph is scaled so its longest side fills the em square

‎doc/api.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ Converts a map of SVG strings into an OpenType font.
5959
| `normalize` | `bool?` | `true` | Scale each glyph so its longest side fills the em square, then centre it. |
6060
| `useOpenType` | `bool?` | `true` | Emit CFF (OpenType) outlines. When `false`, TrueType outlines are generated with cubic-to-quadratic approximation. |
6161
| `fontName` | `String?` | `null` | PostScript / family name for the generated font. |
62+
| `strokeWidthRange` | `StrokeWidthRange?` | `null` | Build a variable font whose `wght` axis is the stroke width (`min` and `max` in SVG units). Omit for a static font. See [Variable stroke width](variable_stroke.md). |
6263

6364
Returns a `SvgToOtfResult` containing:
6465

@@ -77,6 +78,7 @@ Emits Dart source for a class of `IconData` constants.
7778
| `package` | `String?` | `null` | Package name when the font is provided through a dependency. |
7879
| `fontFileName` | `String?` | `null` | Font file name referenced in generated docs. |
7980
| `indent` | `int?` | `2` | Leading spaces for class members. |
81+
| `strokeWidthRange` | `StrokeWidthRange?` | `null` | When set, documents the variable `wght` axis in the class comment. |
8082

8183
Returns the class file contents as a `String`.
8284

‎doc/cli.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ fontify_plus assets/svg/ fonts/my_icons_font.otf \
2222
| `--[no-]normalize` | Scale each glyph so its longest side fills the em square (default on). |
2323
| `--[no-]outline-strokes` | Convert stroked paths to filled regions (default on). |
2424
| `--[no-]opentype` | Emit CFF outlines (default on). |
25+
| `--stroke-width-range=<min,max>` | Build a variable font whose `wght` axis is the stroke width, in the SVG's own units (e.g. `1.33,2`). The maximum is the default instance. Omit for a static font. See [Variable stroke width](variable_stroke.md). |
2526
| `-r`, `--recursive` | Recursively search for `.svg` files. |
2627
| `-v`, `--verbose` | Print every log message. |
2728
| `-z`, `--config-file=<path>` | Path to a yaml config file (`pubspec.yaml` and `fontify_plus.yaml` are checked by default). |
@@ -50,11 +51,20 @@ fontify_plus:
5051
brand:
5152
input_svg_dir: assets/brand/
5253
output_font_file: fonts/brand.otf
54+
stroke_width_range: [1.33, 2]
5355
```
5456
5557
`input_svg_dir` and `output_font_file` are required per font set. CLI flags
5658
merge on top of `defaults` and per-font values (only flags you pass override).
5759

60+
`stroke_width_range` takes a two-element list of numbers (`[min, max]`) and
61+
builds a variable font whose `wght` axis is the stroke width instead of one
62+
fixed width; it is also allowed in `defaults` for font sets that share an
63+
icon library and range. There is no built-in default. Requires
64+
`outline_strokes` and `opentype` to stay on (their defaults) — pairing it
65+
with `outline_strokes: false` or `opentype: false` is rejected. Details:
66+
[Variable stroke width](variable_stroke.md).
67+
5868
```sh
5969
fontify_plus # all sets
6070
fontify_plus --font=icons # one set

‎doc/getting_started.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ runFontJob(FontJob(
5555
## Where to go next
5656

5757
- **API Usage** — parameters on `svgToOtf` and `generateFlutterClass`.
58+
- **Variable stroke width** — `wght` axis as literal stroke width.
5859
- **Stroked Icons** — why outline-style SVGs need stroke conversion.
5960
- **Glyph Sizing** — artboard mapping vs `--normalize`.
6061
- **CLI & Config** — flags and the yaml config file.

‎doc/stroked_icons.md‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
# Stroked Icons
22

3-
A font glyph is a filled region. The format has no concept of stroke width,
4-
line caps, or joins — only enclosed area matters.
3+
A font glyph is a filled region. The OpenType format still has no notion of
4+
line caps or joins — only enclosed area matters — but a **variable font** can
5+
now vary the stroke width that outlining is done at. See
6+
[Variable stroke width](variable_stroke.md).
57

68
## Centreline strokes
79

0 commit comments

Comments
 (0)