Skip to content
Back to skills

Text Metrics

ASecurity

Baseline, half-leading, and font-face resolution for Label and captured (browser-imported) text — the arithmetic that decides where a glyph lands and how wide the box must be, plus the measure-vs-paint divergences that make text clip or sit low without any test going red.

  • 23 stars
  • 0 votes
  • 0 copies
  • 5 views
  • Added September 20, 2026
toolsrustgophpc++bashreactawsgitapibackend

Works with

  • cursor
  • cli
  • api

Security analysis

A100/100

Scanned November 9, 2026

npx -y skills add danielraffel/pulp --skill text-metrics --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Text Metrics?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Text Metrics
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/danielraffel-text-metrics/badge)](https://www.skillsdirectory.com/skills/danielraffel-text-metrics)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: text-metrics
description: Baseline, half-leading, and font-face resolution for Label and captured (browser-imported) text — the arithmetic that decides where a glyph lands and how wide the box must be, plus the measure-vs-paint divergences that make text clip or sit low without any test going red.
---

# Text metrics: baselines, half-leading, and face resolution

This skill covers `core/view/src/widgets/label.cpp` and the captured-text path
that design import feeds it. It exists because four separate bugs in this area
all shared one shape: **the number was wrong but nothing failed**, because the
test asserted the same rule of thumb the code used.

## Captured boxes: read the baseline off the BOTTOM

A captured line's baseline comes from `captured_baseline_offset()` and
`captured_baseline()` in `pulp/view/text_line_metrics.hpp`, pure functions;
`Label` only gathers their inputs.

`TextShaper` / `PreparedText::ascent()` and `descent()` are the face's
**worst-case glyph extents** (the larger of fTop/fAscent, fBottom/fDescent).
That is right for sizing a box that must never clip a glyph and wrong for
placing a CSS baseline. A captured line box is the rect Chromium gave the text
run, its content area: `round(fAscent) + round(fDescent)` tall **whatever the
line-height**, plus an ascent adjustment Blink applies on macOS to Times,
Helvetica and Courier (Times 16px: 12 + 4 + 2 = 18), with the baseline the
descent above the rect's bottom. So the captured branch places the baseline at

```
baseline_y = box.bottom - descent
             descent = measured LineMetrics descent, else round(typographic_descent())
```

- The browser's **measured** line metrics (`LineMetrics`, recorded by the
  capture from canvas `fontBoundingBox*`) win whenever present. They carry
  Blink's rounding and its per-face macOS adjustments, which no font table
  states.
- Otherwise the face's **typographic** descent
  (`PreparedText::typographic_descent()`, fDescent), rounded to a whole CSS px,
  never the clip-safe glyph bounding box.
- With no real face metrics either, the ink is centred in the box (unclamped).

This is measured, not derived. Two independent probes agree:

- a zero-size `vertical-align: baseline` probe captured through the importer:
  Arial, Arial Bold, Inter, Georgia, Verdana, Times, Helvetica, Courier, the
  default serif, 11-32px, `line-height: normal` and explicit;
- a CDP probe at emulated DPR 2 (Chrome 151), 216 cases: Arial, Inter,
  Georgia, Verdana, Times, Helvetica, Courier, `serif`, `system-ui` at 11, 13,
  16, 17, 22 and 32px, line-height `normal`, `1.0`, `1.5` and `40px`. The text
  range's client rect was exactly canvas `fontBoundingBoxAscent + Descent`
  tall in 216/216, and the baseline sat the measured descent above its bottom
  in 216/216. A line-height never makes the rect taller, so a half-leading
  split inside the rect has nothing to split. That probe cannot tell the
  measured rules apart (bottom minus measured descent and top plus measured
  ascent coincide there); it does discriminate the fallbacks. With the faces'
  CoreText fAscent/fDescent and no measured metrics, `bottom - round(fDescent)`
  was exact in 192/192 cases (Inter excluded: it is not installed
  system-wide, so CoreText substitutes Helvetica), while the old
  rounded-ascent/half-leading fallback was exact in 96/192 and up to 2.86 px
  high on Times, Helvetica, Courier and `serif`.
- The fallback is wrong where Chromium's descent is not the file's: Arial
  16px under `@font-face { descent-override: 40% }` gives a 20px rect with its
  baseline 14px down, while `bottom - round(fDescent)` puts it at 17.
  `captured_baseline_offset`'s test pins both that miss and the measured fix.

Rules that look equivalent are not:

| rule | Arial / Georgia / Verdana | Times, Helvetica, Courier |
|---|---|---|
| `top + round(fAscent) + half-leading` | right | **1-2px high** |
| `top + worst-case ascent` (the old code) | 1px high (Arial Bold 24) | high |
| `bottom - round(fDescent)` | right | right |
| `bottom - measured descent` | right | right |

Worked example, Inter 12px in a captured 15px box:

| quantity | value |
|---|---|
| captured line box height | 15.0 |
| `font_size` | 12.0 |
| Inter's worst-case glyph ascent (fTop) at 12px | 13.294921875 (≈1.108 em) |
| Inter's worst-case ink at 12px | 17.162109 (≈1.43 em) |
| Inter's typographic ascent / descent (fAscent / fDescent) at 12px | 11.625 / 2.906 |
| **buggy** `max(0,(15−12)/2) + 13.2949` | **14.794922** |
| **still wrong** `(15−17.1621)/2 + 13.2949` (worst-case extents) | **12.213867** |
| **Chromium** `15 − round(2.906)` (bottom minus rounded fDescent) | **12.0** |

The rounding is in CSS px even at DPR 2 (Arial Bold 24px gives a 27px rect;
device-px rounding would give 26.5). Known limits, all measured on macOS
Chromium: Linux Blink moves a unit from ascent to descent when the descent
rounds down under subpixel positioning; an `@font-face` with
`descent-override`/`size-adjust` makes Chromium's descent the override value
while the label still reads the file's `fDescent` when nothing was measured.
Measure before extending the rule to those cases. The native (uncaptured)
branch is different: it has no box from Chromium and still centres the real
ink, and its half-leading surplus must be measured against the same ink it
then descends by.

**Negative half-leading is legal and must not be clamped.** A face whose ink
exceeds the box has negative leading, and CSS lets the glyphs overflow the box
evenly, top and bottom.

`1.5 + 0.85 * font_size` is the rule of thumb the native branch replaced. If
you see `0.85` anywhere near a baseline, it is measuring an em box while
descending by a real ascent. It is wrong even when the test agrees with it.

## Captured baselines snap on the captured frame's grid

Chromium paints each captured line with its baseline on a whole CSS px of the
page. `captured_baseline()` takes the grid's origin as `root_y`: the label's
offset from its **captured frame**, the nearest ancestor with
`captured_frame_root()` set. Every import lane marks its root: the native
materializer and the C++ codegen call `set_captured_frame_root(true)`, the JS
codegen emits `setCapturedFrameRoot('', true)`. It is deliberately separate
from `subpixel_layout()`, which a hand-built tree can set without being a
captured frame; an import lane that skips the marker snaps to the tree top. Never
sum offsets up to the application root: an import mounted at y=10.5, or under
a scaled or animating host, then snaps against the host's grid and its text
moves by a pixel. Native, non-captured text is not snapped at all.

## Measure and paint must resolve the SAME font family

Every metric entry point — `intrinsic_width()`, `intrinsic_height()`,
`measured_height()`, `baseline_offset()`, `resolve_text_style()` — walks
`own → inherited → "Inter"`. `Label::paint()` did not: it resolved
`own → "Inter"`, skipping the inherited step. Anything that inherited its face
was therefore **measured in one font and drawn in another**.

Consequence, and why it is nearly invisible: the box is sized correctly for the
inherited face, so a wider painted face simply overflows and clips. It clips
*visibly* only where the element has no slack.

- A bare `<span>` is sized to exactly its text — zero slack — so it clips on
  screen. `SNAPSHOT` at JetBrains Mono 10px is `8 × 6.0 = 48.0` exactly; paint
  used proportional Inter, whose caps are wider, and the tail vanished.
- The same element inside a button with 8–11px padding absorbs the mismatch and
  is *silently wrong* rather than visibly clipped. Do not read "only one label
  clips" as "only one label is broken."

Fix shape: one `effective_font_family()` helper, used by paint and every metric,
so the walk cannot drift again.

The same rule holds one level down, for the FACE a family resolves to. The
resolver reaches `system-ui` through CoreText's UI-font API at the exact
weight, but SkParagraph finds families by name, so the paragraph path sees the
private `.AppleSystemUIFont`. The CoreText manager's style set for that name
holds only the named instances, so a weight between them (250) shaped in the
nearest one (200) while the resolver measured an interpolated 250, which is
what Chrome draws; and `matchFamilyStyle` by that name returns null for the
rest of the process once such a weight has been asked for. The font collection
now consults `make_system_ui_font_manager` (`core/canvas/src/system_ui_typeface.hpp`)
first. Compare a family's paragraph face with its resolver face per weight,
names and advances, before trusting either. A subclass of `SkFontMgr` (or of
SkParagraph's `TypefaceFontProvider`) must live in a TU built with `-fno-rtti`:
the prebuilt Skia exports no type info for them and the link fails. Keep that
TU free of anything that can throw (`std::vector`, `std::string`, inline
helpers that use them): a throw site compiled without RTTI emits hidden copies
of `std::exception`'s type info, the linker binds the whole binary's catch
clauses to them, and a `std::runtime_error` thrown anywhere else then escapes
`catch (const std::exception&)`. Put such code in an ordinary TU, as
`font_weight_match.cpp` does, and check with `nm -m <tu>.o | grep __ZTISt`.

The weight a family resolves is the other half of the face. CoreText (and
every platform manager's `matchFamilyStyle`) takes the NEAREST weight; CSS
Fonts 4 searches in a fixed direction: from 400 to 500 it tries heavier faces
up to 500, then lighter, then heavier; below 400 lighter first; above 500
heavier first. Helvetica Neue ships Medium (500) and Bold (700), so at 600
CoreText picks Medium and Chromium picks Bold. The import painted lighter and
narrower (dx -0.54 CSS px, ink 0.858 against the capture) and, because the
resolved face no longer matched the capture's recorded face, Label rejected the
captured basis and placed the baseline natively (dy +0.45 at whole-pixel
tops). `css_match_font_weight()` in `core/canvas/src/font_weight_match.hpp`
is the one matcher: the resolver (and so `resolved_face_identity()`), the
paragraph collection's default manager and bundled families all go through it.
Never call `mgr->matchFamilyStyle()` directly for a named family; the face it
returns is the face the captured-basis check will disagree with. When a weight
looks wrong, ask the same question at 700 first: if 700 is exact and 600 is
not, the family is missing the weight and the matcher is deciding.

## The CoreGraphics host measures through the face CoreText paints

The rule above has a second half that lives below the family name: the
measuring backend must resolve the same *face* the painting backend draws.
The CoreGraphics host paints text through CoreText. A lite editor (the macOS
default; see the `view-bridge` skill's editor stack section) also measures
through CoreText (`TextShaper`'s `PULP_TEXT_SHAPER_SKIA == 0` branch), so the
line box comes from the glyphs actually drawn. That is a deliberate choice:
measure equals paint.

A full-stack build still measures through Skia's `SkFontMgr`, and for some
families and weights Skia resolves a different face than CoreText paints:

- "Helvetica Neue" 600 at 12 px: Skia ascent 13.92, width 116.7; the painted
  face ascent 13.69, width 120.0.
- JetBrains Mono at 9 px: Skia adds 0.12 px of leading the painted face lacks.

Captured text is not affected: a Label reuses a capture's line breaks only
when `resolved_face_identity()` matches the capture's face, and the lite stack
answers that through CoreText (`coretext_face_postscript_name`), the face it
paints. When the lite answer was empty, every captured label re-broke with its
own measurement and the design panels moved by whole labels (0.31% and 0.47%
of pixels on PulpDesignSynth and PulpDesignArp); with the answer they match the
full build: 0 pixels on PulpDesignSynth, and on PulpDesignArp a bold 9 px "07"
whose identical glyphs sit 1 capture px lower. That label asks for
JetBrainsMono-Bold, which Pulp does not bundle; Skia falls back to Menlo-Bold
and CoreText to the bundled Regular, so the full build places CoreText-painted
glyphs with Menlo's metrics. A lite-vs-full diff on a design panel is a
regression to chase unless the differing text resolves to a face Pulp does not
bundle: check `resolved_face_identity()` on each stack against the capture's
`lineBoxBasis.resolvedFace` before concluding either.
`pulp-test-face-identity-full` and `-lite` hold the bundled faces' identities
equal across the two stacks. Text measured without a capture can still differ
by up to 1 logical px for the system families listed above.

## Font smoothing is per draw, and the preblend is per surface

`-webkit-font-smoothing: antialiased` is two settings, owned by two layers.
Glyph hinting is per draw: `Canvas::set_font_smoothing(antialiased)` makes
SkiaCanvas shape and measure with hinting off on both text paths, SkParagraph
and glyph fallback. The canvas keeps the last value, so a caller that sets it
resets it; Label does this around its own paint. The contrast and gamma
preblend is a property of the surface (`TextRasterPolicy`,
`pulp/canvas/text_raster_policy.hpp`). Only both together reproduce
Chromium's antialiased glyphs. Hinting off on a `legacy` surface still paints
heavy, and a `chromium` surface with hinting on is not exact either. When an
imported label's ink is off by about a fifth, check its `font_smoothing`
attribute and the surface's policy before you look at weight or face.

## A Label with element children does not paint at its own origin

A `Label` that carries both text and element children is a flex container whose
own text is an **anonymous inline box** — a real item on the flex line, sized and
positioned by the layout pass alongside the element children. Painting that text
at the Label's content origin (`bounds()`) instead of at the box layout reserved
for it puts the text and the first child at the same coordinates, and they
overlap.

So the paint path has to take the text box as a parameter rather than read
`bounds()`. Every `bounds().width` / `bounds().height` inside the text painter is
a latent instance of this bug: wrap width, alignment origin, the `x` for centre
and right alignment, the available width for ellipsis, and the vertical baseline
arithmetic all mean *the text box*, not the widget. A Label with no element
children has a text box equal to its bounds, which is why the wrong version looks
correct in every fixture that does not mix text and children.

The related layout-side fact, which is what makes this easy to misdiagnose:
`build_yoga_subtree` attaches a measure func only when `!has_managed_children`.
A Label with both text and element children therefore contributes **zero layout
weight for its own text** — the anonymous box gets no intrinsic size from the
shaper. A test that only asserts child geometry passes while the text is
unplaced, so assert the text box itself.

## Padding reaches a Label's text only through the captured line box

Yoga insets a view's **children** by its padding. A `Label`'s own string is not a
child, so nothing in layout moves it: the native paint path anchors its
alignment `x` and its baseline arithmetic at the box it is handed, which for a
label with no anonymous inline box of its own is the **border** box.

A captured browser line box is measured as `rect - ownerBounds`, and
`ownerBounds` is the owner's border box — so `padding-left` and `padding-top`
are already baked into every captured `left`/`top`. The two paint paths
therefore disagree by exactly the padding, and the disagreement is invisible for
as long as the cache is honored, because only the native path is wrong.

That makes it look like a cache bug when the cache is what was hiding it. A
label whose captured basis is stale — a basis captured against a truncated
string, say — correctly falls back to native painting, and the same text jumps
left by `padding-left` and up by `padding-top` while its siblings, whose caches
are still valid, do not move. The symptom presents as one item in a row being
misaligned, so the instinct is to weaken the predicate that rejected the stale
basis. Do not: that predicate is right, and weakening it paints stale geometry.

Two consequences when touching this code:

- Resolve padding the way `yoga_layout()` resolves it — a percent `Dimension`
  wins, otherwise the per-edge float with the uniform value as its fallback, and
  percent resolves against the **parent's** width. A second resolution rule here
  drifts from layout silently.
- Apply it only when `!has_own_text_box()`. Layout already inset an anonymous
  inline box, so padding applied again doubles it.

A fixture with zero padding cannot see any of this. Give the label real padding
and assert the draw origin on both branches of the cache predicate.

## A retyped single captured line keeps its box; only its width is re-measured

`cached_line_layout_usable()` honors a captured browser line box while the
label's transformed text equals the string it was captured for. When the copy
changes (`Label::set_text` sets `cached_line_basis_retired_`), what happens
next depends on what the change could have done to the LINE COUNT:

- **One captured line, no wrap, no newline, no attributed runs** -- the box is
  still where Chromium put that text, so `layout_from_cached_lines()` keeps the
  box's `top`/`height` (the captured vertical placement) and re-measures the
  live text with the shaper for its width. The left edge is the captured one
  moved by the width change under the label's alignment (`x_offset = left +
  (box.width - new_width) * {0, .5, 1}`), so a centred caption stays centred.
- **Anything else** (several boxes, a soft wrap, a `\n`, attributed text)
  reflows natively, because the captured boxes no longer describe the lines.

The earlier rule -- refuse a retired basis for good and paint natively --
re-centred the caption from native face metrics, which sit visibly higher
than Chromium's line box, so a modulated readout ("32 BANDS" playing "64
BANDS") jumped up the moment the LFO started and dropped back when it stopped.
The native path and the captured path place a single line differently
(`(content_h - text_h)/2 + half_leading + ascent` vs `box.top + half_leading +
ascent`); keeping the box is what keeps the caption still.

The boxes are deliberately never cleared on a text change: the responsive
reflow still reads their line count and wrap intent, and the
`line_break_path_counts().reflowed` accounting that
`test_design_import_codegen_layout_text.cpp` pins must keep reporting a reflow
for the multi-line case. `set_cached_line_boxes()` clears the retired flag
when a fresh capture arrives. Regressions: `Label keeps a retyped single
captured line where Chromium put it` and `Label re-centres a retyped captured
line on the captured box` in `test/test_widgets_label.cpp`.

## Gotchas

- **On Apple the CoreGraphics canvas paints through a CoreText registry, not
  CTFontCreateWithName.** CoreText answers `CTFontCreateWithName("Inter")` with
  Helvetica, because Inter (Pulp's default UI family) is bundled, not
  installed. So an AutoUi editor measured Inter (through Skia) and painted
  Helvetica, and without Skia it was not measured at all (0.85 em / 0.6 em
  guesses), putting labels 2-4 pt high. `core/canvas/platform/mac/coretext_text.mm`
  holds the bundled fonts and every `register_font()` face; the CG canvas
  paints through it and TextShaper measures through it when Skia is absent,
  with Skia's CoreText metric definitions (bounding-box extents). The faces live
  in Pulp's own table, never `CTFontManagerRegisterGraphicsFont`, so a plug-in
  cannot add fonts to its host. What holds it: the PulpGain editor renders
  pixel-identically with and without Skia; `test_coretext_text.cpp` pins the
  Skia and CoreText metrics to within 0.01; and the AutoUi Skia-vs-CoreGraphics
  case in `test_auto_ui.cpp` compares every label's ink box. The two rasterizers
  still differ by about one device pixel vertically (baseline rounding), which
  is not a measurement drift.

- **`SkiaCanvas::fill_text` must land the baseline exactly on `y`, and
  SkParagraph rounds it.** SkParagraph draws a line's glyphs `round(ascent)`
  below the paragraph's top, regardless of `ParagraphStyle`'s rounding hack,
  while `getAlphabeticBaseline()` reports the unrounded ascent. Painting the
  top at `y - getAlphabeticBaseline()` therefore put every fillText up to half
  a unit off `y` — low when the ascent rounds up, high when it rounds down —
  so a correct `baseline_y` from Label still painted a device pixel off for
  some face/size pairs and not others. `make_paragraph` returns the rounded
  value; `test_canvas_fonts.cpp` "fill_text places the alphabetic baseline at
  y" pins both directions. When a baseline looks off by a pixel, sweep the
  label's top in 1/16 px steps and read where the glyph rows switch: a switch
  that is not at the half-pixel is an offset between the requested and drawn
  baseline, not a metrics bug.

- **`white-space` is inherited, and wrapping is `soft_wraps()`, not
  `multi_line()`.** The React and DOM importers stamp `white-space: normal` on
  every text element they create, so `multi_line()` is true for nearly every
  imported Label even inside a `nowrap` container. `Label::soft_wraps()` applies
  the inheritance (own mode `normal` defers to the nearest ancestor that set
  another one) and is what measurement, the measure cache and paint read. A
  symptom of reading `multi_line()` instead: an absolutely positioned
  auto-width box (a tooltip) collapses to its padding while its text paints at
  full width outside it, because the text wrapped into whatever room the
  containing block offered.
- **Captured line boxes in tests are usually hand-authored fixtures, not real
  Chromium captures.** `single.text_line_boxes.push_back({0,0,53.6719f,15.0f,...})`
  is a literal. An expectation written beside it encodes whatever rule the author
  believed, so a green test proves self-consistency, not correctness. Before
  trusting one, back-solve it: does the expected number equal the CSS formula
  with the *real* face metrics, or does it equal a rule of thumb?
- **Font metrics here are deterministic across platforms.** Linux CI and local
  macOS produced `14.794921875` to the last digit. So a cross-platform
  disagreement in a text test is a real logic difference, never "the platforms
  resolve different fallback faces" — check that excuse before believing it.
  It also means `margin(0.01f)` is a safe tolerance; you do not need a loose one.
- **Attributed text keeps its own height source.** `single_line_text_height` is
  `has_attributed_ ? automatic_lh : single_line_ink_height`; changing the
  half-leading reference does not disturb the attributed path.
- Widths come from the captured `basis.width` in `capturedTextBindings`
  (`native-ui/materialized/runtime.js`), which records what Chromium actually
  measured per span: `basis.width`, `resolved_face`, `resolved_faces[]`, and the
  full `requested.*` block. That is the ground truth for "how wide should this
  text be" — not a re-measurement.
- **`font_size` is the em square, not the ink — never centre against it.**
  Vertically centring a single line with `(box_height - font_size) * 0.5` places
  the glyphs by a ratio the face does not actually have, so two labels centred in
  equal boxes paint their ink at visibly different heights. The ink box is the
  resolved face's `ascent + descent`; centre against that and add `ascent` to
  reach the baseline. The historic `font_size * 0.85` first-line rule is the same
  mistake in closed form: it is right only for a face whose ascent happens to be
  0.85 em, and wrong by a few pixels for every face that is not. Keep 0.85 solely
  as the no-Skia / unresolved-family fallback, and flag it (`FaceMetrics::real`)
  so callers can tell a measured number from a guessed one.
- **Face metrics must be cached against the font-registration generation, not
  just the face key.** Registering a font resamples the resolved typeface, so a
  cache keyed only on family/size/weight/slant keeps serving *fallback* metrics
  forever to any Label that first painted before an async `register_font_url()`
  landed — the text silently keeps the 0.85 guess even though the real face
  arrived. Include `canvas::font_registration_generation()` in the cache key.
- **Measure the face, not the string.** Shape a single space to get ascent and
  descent: the metrics belong to the face, so a per-string measurement both costs
  more and defeats the cache on any label whose text changes every frame. Where a
  shaped layout already exists (wrapped or attributed text), read its first
  line's ascent instead of measuring the face a second time.
- **`intrinsic_width()` is a layout contract, not a measurement — a multi-line
  Label reports 0 on purpose.** Returning 0 is what lets the parent's available
  width drive wrapping, so anything asking "how wide is this text" gets zero for
  every wrapped label and, if it treats that as an answer, silently skips them.
  A layout-box dump of one real panel was blind on 63% of its text runs for
  exactly this reason, and read as a clean result. Ask
  `painted_text_extents(available_width)` instead: it shapes and lays out at the
  width the Label was given, applies the line clamp and text-align, and returns
  `measured=false` for empty text so "unknown" is distinguishable from "zero
  sized". Do not fix the blindness by making `intrinsic_width()` return a number
  for the multi-line case — that breaks wrapping.

- **Three consumers must agree or the bug is invisible.** `intrinsic_height()`
  sizes the box, `baseline_y()` is what Yoga gets for `align-items: baseline`,
  and `paint()` places the ink. If they do not derive from one line box, the
  layout is self-consistent and still paints text off-centre, and the inspector's
  caret and selection band drift off the glyphs they are supposed to sit on.

- **`painted_text_extents().ink` is read from pixels, not derived.** Paint
  centres a line block taller than its box over it, so a wrapped readout in a
  short box inks above its top; a captured layout draws Chromium's line boxes
  rather than a native re-shape; and glyphs overhang their advance. Each of
  those is a placement rule of `paint_text_()`, so with Skia the extents paint
  the text once into a scratch raster and read back the touched pixels,
  restoring the selection geometry and line-break counters paint records.
  `width`, `height` and `line_count` follow the captured line boxes when the
  captured layout is usable. Do not re-derive the ink from line heights: that
  is the drift this replaced, and it reported 0 for every ink above the box.
- **`TextShaper::prepare()` is not cheap on a warm cache — do not call it from a
  measurement path more than once.** The name suggests a lookup, but every call
  re-validates the UTF-8, re-allocates, and re-segments the string, taking a
  per-segment `std::lock_guard` on the way; the cache is keyed per *segment
  width*, so repeated `prepare()` calls for the same label all pay full price. A
  single layout pass asks each `Label` for its size five times — the Yoga build
  walk calls `intrinsic_width()` and `intrinsic_height()`, the measure callback
  calls both again, and `measured_height(w)` follows — so a naive implementation
  shapes every label roughly five times per pass. That is the single largest
  cost in `View::layout_children()`; a tree of a few hundred labels can spend a
  quarter of a 60 fps frame budget in it.
- **Memoize measurement against a fully resolved basis, and fail closed.** The
  memo key must hold the values the measurement actually depends on *after* the
  inheritance cascade has run — the resolved font size and letter spacing, not
  the label's own possibly-unset fields — plus
  `canvas::font_registration_generation()`. Keying on resolved values makes the
  basis self-invalidating: an ancestor changing the inherited font size lands as
  a basis mismatch on the next measurement, with no notification path required.
  Attributed text carries its own metrics source and must opt out of the memo
  rather than be approximated by it.

- **`baseline_y()` is the TOP-ALIGNED baseline and ignores box height entirely
  — `paint()` does not.** Yoga's baseline channel gets `ascent` alone, while the
  painter resolves `rs.baseline_y` against `bounds().height` per vertical-align
  (`height - ink_h + ascent` for bottom, `(height - ink_h) * 0.5 + ascent` for
  middle). The two therefore agree only when the Label paints top-aligned, so a
  bottom- or middle-aligned Label inside `align-items: baseline` is aligned on a
  baseline its own glyphs do not sit on. That is deliberate — the CSS baseline
  of a box is a layout property the parent reads before the child's own
  alignment resolves — but it means a baseline-row drift is NOT automatically a
  metrics bug. Check the child's vertical-align before touching either path,
  and do not "fix" `baseline_y()` to consult `bounds()`: it is called during
  measurement, when the box height is not yet known.

- **`AtMost` offers an upper bound, not an assignment.** CSS resolves an
  at-most width to `min(max-content, available)`, so echoing the whole offered
  width back from the measure callback is wrong for any leaf whose intrinsic
  width is 0. A soft-wrapping Label reports 0 on purpose (its parent decides
  where lines break), so the naive echo made every auto-width *ancestor* of such
  a label stretch to fill its slot instead of hugging its text — the label
  itself looked correct, which is why this reads as a container bug rather than
  a text one. Ask `Label::max_content_width()` for the unwrapped advance and
  clamp it to the offer.

- **Max-content is the widest hard-break SEGMENT, not the full string advance.**
  The shaper gives `\n` no advance of its own, so `prepare(whole_string)
  .total_width()` silently sums every line into one impossibly wide number for
  any label carrying an explicit newline. Split on `\n` and take the widest
  segment — but only once the label actually paints as lines: a single-line
  Label that has been handed a string with a newline in it draws the whole
  advance, and measuring it as segments reserves less than paint draws and
  clips. Both branches must agree with `intrinsic_height()` about which case
  they are in.

- **A vertical Label's horizontal footprint is its line height, not its
  advance.** When `paint()` rotates text 90°, reporting the shaped advance as
  max-content makes Yoga reserve the full string length as *width* and starves
  every sibling in the row. Check `text_direction_` before returning an advance
  from any width path.

- **SkParagraph's `LineMetrics::fHeight` is ONE line's height, whatever
  `Metrics.h` says.** The header documents it as the paragraph height through
  the current line; `TextLine::getMetrics` assigns the line's own advance.
  Reading it as a running total made every equal-height line after the first
  contribute nothing, and a later fallback-face line (Thai then CJK, both 22px
  at 16px) lose its descent. `paragraph_text_extents()` holds the max-over-lines
  rule as a pure function; the `[skia]` control in `test_text_shaper.cpp` pins
  the library's per-line semantics so a Skia bump that changes them fails
  there, not in a layout. An all-Latin multi-line test cannot see this bug:
  equal lines give the same max under both readings.

- **A text write into a pinned captured box must not dirty layout.** The
  materializer passes `wrap_on_cache_miss` for every non-nowrap single-line
  capture, so `captured_wrap_fallback()` is true on most imported text, and
  that alone used to send every `set_text` through `invalidate_layout()`. On the
  example instrument and MIDI-effect panels, 34 of 44 and 59 of 68 slot writes
  cost a full Yoga pass on each frame. `Label::set_text` now requests paint only
  when width and height are both fixed, the Label is not a baseline
  participant, has no children and no text slot of its own, and either holds
  captured line boxes or changes between two non-empty copies. "Fixed" is what
  `yoga_layout()` hands Yoga as a number: a px size through `preferred_*`
  (a px `dim_*` alone is never applied), a viewport size, or a percent whose
  every ancestor up to the root fixes that axis. A percent under an auto-sized
  parent is not fixed. Without captured boxes, a centred lone Label gets an
  anonymous text slot from layout that is sized from its copy, so new copy
  moves layout output inside a pinned box. The older single-line fast path
  skipped that layout and painted into the stale slot (72 px wide for a
  277 px string). Any Label with `has_own_text_box()` now lays out on a text
  write. The benchmark's
  reported `layout_passes` cannot see any of this, because its step and
  `render_frame` lay out unconditionally. Count `tree_layout_generation()`
  changes per write instead.

## Selection geometry is recorded at PAINT, and only paint can record it

`Label` implements `SelectableText` (`core/view/include/pulp/view/selectable_text.hpp`)
by appending one `SelectableLine` next to every `fill_text` it emits. That looks
like an odd place to put it until you try the alternative: the only moment at
which the **painted** line string, its **draw origin**, and a live `Canvas` to
ask `text_x_for_byte()` all exist together is immediately before the draw call.
Re-deriving the same geometry from `text_` afterwards reproduces neither the
text-transform, nor the shaper's break positions, nor the line clamp, nor the
ellipsis — so the band would sit on glyphs that are not there.

**The recorder is gated, and the gate is a performance contract, not a
preference.** It calls `canvas.text_x_for_byte()` once per grapheme cluster, so
running it on every Label in every Pulp UI would add real per-paint work to
trees that will never be selected. `Label::is_selectable()` resolves to the
nearest enclosing `View::set_text_selection_region()` — walked, never cached, so
a reparent cannot leave a stale answer — with a per-Label `SelectionPolicy`
override in both directions. Outside a region a Label paints exactly the
commands it painted before this existed, which is also what keeps a drag on a
value readout from becoming a text selection.

Consequences that are easy to get wrong:

- **Offsets are into `text_`, not into `display_text`.** They only coincide
  because all three `TextTransform` cases are per-`char` `toupper`/`tolower`/
  capitalize, which are byte-length preserving for every input. **A
  locale-aware or Unicode-correct transform would break that silently** —
  `ß`→`SS` grows by a byte and every offset after it would be wrong, with
  nothing failing. If you make the transform Unicode-correct, the recorder has
  to carry an explicit display→source offset map.
- **A shaped line's source offset cannot be accumulated from line lengths.**
  `TextShaper` drops the whitespace it broke at, so consecutive
  `ShapedLayout::Line::text` values are not contiguous in the source. The
  recorder scans forward (`display_text.find(line, cursor)`) instead. Summing
  `line.size()` drifts by one byte per soft break, which looks correct on the
  first line and progressively wrong after it.
- **Only what is PAINTED is selectable.** A clamped or ellipsised Label
  deliberately reports less than its full string, and the appended U+2026 is
  never recorded — it is not in the source. That is the intended contract: you
  cannot select text that is not on screen.
- **Three paint paths do not record, and say so rather than guessing.**
  Attributed runs (`paint_attributed_lines_`), rotated vertical text, and a
  Label whose inline editor is open all leave `SelectableLayout::measured`
  false. Vertical is the interesting one: the canvas is already rotated at that
  point, so any coordinate recorded there would be in a space the pointer never
  arrives in. `measured == false` means UNKNOWN, never "no text" — the same
  distinction `PaintedTextExtents::measured` carries, and for the same reason.
- **Use `canvas.text_x_for_byte()`, never a sum of `measure_text()` prefixes.**
  The two disagree by exactly the kerning and ligature adjustments, which is
  the difference between a band that sits on the glyphs and one that creeps.
  `ShapedOffsetCanvas` in `test/support/text_editor_test_utils.hpp` exists to
  make that divergence visible in a test; a Label that re-summed advances fails
  against it and passes against `RecordingCanvas`.
- **Boundaries are grapheme clusters (`canvas::cluster_step`), not bytes.** A
  byte offset inside a multi-byte sequence has no x of its own, and handing one
  out lets a selection slice a UTF-8 sequence in half on the way to the
  clipboard.

Two traps found while covering this, both worth knowing before you touch it:

- **`View::wants_mouse_input()` is vestigial — overriding it routes nothing.**
  `View::hit_test` gates only on `visible_` / `enabled_` / `hit_testable_` /
  `pointer_events_`; it never consults `wants_mouse_input()`. Roughly sixty
  classes override it and only `virtual_list` / `virtual_grid` read it. A Label
  is therefore already a pointer target whether or not it wants to be, so
  selection had to be gated by the content region rather than by that
  predicate.
- **A fixture that paints every widget cannot see the fallback that matters.**
  `full_range`'s unmeasured branch is what makes a never-painted middle widget
  contribute its whole string, and it sat at 0% coverage behind a 94%
  aggregate precisely because every fixture painted everything. If you add a
  document-order case, leave at least one widget unpainted on purpose.

`TextEditor` publishes the same capability from its existing private
`LayoutSnapshot`, and `char_index_at_point()` is now public for the same
reason. The two must agree: `pulp-test-selectable-text` walks the whole run
asserting `selectable_index_at_point()` and `char_index_at_point()` return the
same byte at every x. If you touch either hit-test, that is the test that
notices.

## SkiaCanvas paragraphs are cached, and the paint is not in the key

`SkiaCanvas` text that goes through SkParagraph (`fill_text`, `stroke_text`,
`measure_text`, `measure_text_full`, `text_x_for_byte`) looks its laid-out
paragraph up in the process-wide `ParagraphCache`
(`pulp/canvas/paragraph_cache.hpp`). It has to be process-wide: hosts build a
new `SkiaCanvas` every frame, so a per-canvas cache never hits.

- **Anything `build_paragraph` reads must be in `ParagraphKey`.** Adding an
  input to the paragraph build without adding it to the key paints a stale
  layout for every run that differed only in that input, and nothing fails
  unless a test draws two runs that differ in exactly that input. The variant
  cases in `test_paragraph_cache.cpp` do that per field; add one with the
  field. Wrap width, text-align and line height are deliberately absent: the
  paragraph is laid out at infinite width, left-aligned, and the caller aligns
  the run.
- **Key on the resolved family stack, not the CSS string.** Generic keywords
  map to platform families through state that does not bump
  `font_registration_generation()` (the test-only generic override), so the
  same CSS string can resolve differently within one process.
- **The generation is not redundant with the primary typeface.** A
  registration can change only a fallback entry in the stack (a glyph the
  primary lacks), leaving the primary face and every other key input equal.
- **Never update a cached paragraph's foreground paint.**
  `Paragraph::updateForegroundPaint` rewrites the text styles but not the
  text-blob records `TextLine` fills on the first paint, which carry the paint
  they were built with, so a second colour silently paints in the first. The
  cache builds paragraphs with no foreground paint and draws them through a
  `ParagraphPainter` that applies the caller's paint to each glyph run.
- **Every use holds the entry's mutex** (`ParagraphUse`): SkParagraph mutates
  itself on first paint and in queries such as `getRectsForRange`. Never hold
  two uses at once; the same key twice on one thread waits on itself.
- **Key floats must be canonical.** The key compares floats by value and
  hashes them by bits, so a NaN letter spacing (script can send one through
  `setTextRuns`) never found its own entry, piled one in per paint, and then
  crashed eviction; `-0` and `+0` hashed apart. `make_paragraph` replaces
  non-finite size and spacing and folds `-0` to `+0` before building the key.
- **Eviction is a segmented LRU on purpose.** A meter readout is a new string
  every frame; with plain LRU it flushes every label that is not repainted
  each frame. New entries start on probation and are protected on a second
  lookup. Admitting only on a second miss instead would shape every stable
  label twice and fail the benchmark's zero-build steady-state frame.
- **Unspaced text the primary face cannot cover never reaches SkParagraph.**
  `fill_text` sends it to the per-run SkShaper fallback, so a cache test that
  draws a missing glyph must add letter spacing (or a feature) to exercise the
  cache at all.

## How to verify a change here

A baseline change that does not move a number is not a fix. Measure before and
after, and state both.

```bash
tools/scripts/confirm_failure.sh \
  --file core/view/src/widgets/label.cpp \
  --break "<perl -0pi -e to restore the old formula>" \
  --build-dir build --target pulp-test-design-import \
  --test ./build/test/pulp-test-design-import
```

Do **not** hand-roll this with `cp`/`.bak` and `touch`: restoring a source within
the same filesystem second leaves make comparing equal mtimes, so the object is
judged current and the binary keeps the old code. A stale object during the
*break* step makes the control falsely pass, which reads as "my test does not
cover this" and sends you to rewrite a test that was already correct.

Suites that cover this surface: `pulp-test-design-import`,
`pulp-test-selectable-text`, `pulp-test-widgets-label`, `pulp-test-typography-inheritance`,
`pulp-test-widget-metrics`, `pulp-test-canvas-fonts`, `pulp-test-text-shaper`,
`pulp-test-bidi-text`. They are registered by **target** name in
`test/cmake/view_widget_bridge_tests.cmake` — grepping cmake for a test's
*filename* finds nothing and looks like the suite does not exist.

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in tools →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.