The text engine
How a text node becomes glyphs and then pixels: the four text seams, the font libraries behind them, flattening, shaping, line breaking, glyph rasterisation, and every cache on the way.
The text engine turns the text inside an inline formatting context into shaped glyphs, breaks them
into lines, and rasterises the glyphs for painting. Shaping and line breaking run in the f.layout
step of the frame, when the
layout engine measures a paragraph. Glyph
rasterisation runs later, in f.paint. Layout and paint reach the engine only through four traits,
so neither depends on a font library.
The sections follow one paragraph from a text node to pixels, then list the caches on the way and
what each kind of change costs.
Crates
| Crate | Contains |
|---|---|
zgui-text-style | Text properties lowered from the cascade, and the shaping and breaking hashes over them |
zgui-text | The contracts: four seams, the value types on both sides, the paragraph cache |
zgui-text-parley | The implementation. The only crate in the workspace that depends on a font engine |
zgui-layout, zgui-paint and zgui-style depend only on zgui-text. They shape, break, read glyph
positions and read face metrics through its traits, and their test suites run without any font file.
The pipeline
A paragraph moves through these stages:
| Stage | Where | Produces |
|---|---|---|
| Flatten | crates/zgui-layout/src/inline/content/generate.rs | Generated: the string, the map, the runs, the inline items |
| Shape | crates/zgui-text-parley/src/shape/build.rs | ShapedParagraph<ShapedLayout> |
| Break | crates/zgui-text-parley/src/shape/breaking.rs | BrokenParagraph |
| Line boxes | crates/zgui-layout/src/inline/lines.rs | CSS line boxes with baselines and ink extents |
| Place | crates/zgui-paint/src/content/glyphs/place.rs | PlacedGlyph: an atlas tile and a rectangle |
| Emit | crates/zgui-paint/src/emit/text.rs | Sprites, vector items, decoration lines |
A glyph is one drawable shape in a font file, identified by an index within that file. It is not a character: one character can be several glyphs, several characters can be one glyph, and the same character maps to different glyphs in different faces.
The four seams
Each seam is a trait in crates/zgui-text/src.
| Seam | File | Called by | Other implementations |
|---|---|---|---|
FontMetricsSource | metrics/source.rs | The cascade, to resolve ex, ch, cap, ic | FixedMetrics |
FontSource | font/source.rs | Face resolution and @font-face | — |
ParagraphShaper | paragraph/shaper.rs | Layout: once per paragraph, then once per width | MonoShaper |
GlyphRaster | glyph/raster.rs | Paint: once per distinct glyph | MonoRaster, NoRaster |
MonoShaper and MonoRaster live in crates/zgui-testkit-scene/src/shaper/. Every character is one
cluster, 8 device pixels wide and 16 tall at the initial size, drawn as a filled rectangle. Layout and
paint tests use them to assert exact glyph positions without opening a font.
FontSource
pub type FontData = Arc<dyn AsRef<[u8]> + Send + Sync>;
pub trait FontSource: Send + Sync + 'static {
fn register(&self, data: FontData, family: Option<Ident>)
-> Result<SmallVec<[FaceId; 4]>, FontError>;
fn unregister(&self, family: Ident);
fn resolve(&self, query: &FaceQuery<'_>) -> Option<FaceId>;
fn resolve_for(&self, query: &FaceQuery<'_>, character: char) -> Option<FaceId>;
fn face(&self, id: FaceId) -> Option<FaceRecord>;
fn generic_family(&self, generic: GenericFamily) -> Option<Ident>;
}- All methods take
&self. Style resolution runs on several threads, so implementations lock internally. resolve_forexists because fallback is per character: a Latin sentence with one emoji resolves to two faces.- A
FaceIdis opaque and only meaningful to the source that issued it. FaceRecordreports the face's actual weight, slant and width. Comparing them with the requested values tells the caller that synthesis is needed.
FontMetricsSource
pub trait FontMetricsSource: Send + Sync + 'static {
fn face_metrics(&self, query: &FaceQuery<'_>, size: CssPx, vertical: bool) -> FaceMetrics;
fn base_size(&self, generic: GenericFamily) -> CssPx;
}Resolving ex, ch, cap and ic requires opening a face. This seam lets the cascade do that without
depending on a font library. Equal arguments must return equal metrics while the set of registered
faces is unchanged; otherwise one element could get two computed styles.
FixedMetrics (crates/zgui-text/src/metrics/fixed.rs) answers fixed fractions of the size
(x-height 0.5, cap height 0.7, ascent 0.8, descent 0.2), so cascade tests are machine-independent.
ParagraphShaper
pub trait ParagraphShaper {
type Engine;
fn shape(&mut self, content: &ParagraphContent<'_>) -> ShapedParagraph<Self::Engine>;
fn shape_keyed(&mut self, key: ParagraphKey, content: &ParagraphContent<'_>)
-> ShapedParagraph<Self::Engine>; // default: shape + debug_assert on the key
fn fork(&self) -> Option<Self> where Self: Sized; // default: None
fn break_lines(&mut self, shaped: &mut ShapedParagraph<Self::Engine>,
request: &BreakRequest<'_>) -> BrokenParagraph;
fn strut(&mut self, style: &TextStyle) -> StrutMetrics;
fn visit_line(&self, shaped: &ShapedParagraph<Self::Engine>, line: u16,
visit: &mut dyn FnMut(ShapedRun<'_>));
fn visit_clusters(&self, shaped: &ShapedParagraph<Self::Engine>, line: u16,
visit: &mut dyn FnMut(ClusterRun<'_>));
}shapeandbreak_linesare separate because their costs differ by more than an order of magnitude. All caching below depends on breaking without reshaping.Engineis the shaper's private shaped form. Forzgui-text-parleyit isShapedLayout: aparley::Layout, the byte length of the directional prefix, the last break, and whether any run may wrap.shape_keyedlets a caller that already computed theParagraphKeyskip rehashing the paragraph.forkreturns a second shaper over the same font data with its own scratch space, for shaping on worker threads.Nonekeeps shaping on the caller's thread.- The visitors take
&self, so painting can read glyph positions while the shaper is also used for measuring. They are callbacks rather than slice-returning methods so no per-line allocation is needed. visit_lineyields glyphs (what is painted).visit_clustersyields clusters (what can be selected). On ligatures and combining marks they differ, and a caret may not land inside a cluster.
GlyphRaster
pub trait GlyphRaster: Send + Sync + 'static {
fn raster(&self, key: &GlyphKey) -> Option<GlyphImage>;
fn outline(&self, key: &OutlineKey) -> Option<GlyphOutline>;
}- One glyph at a time, by value. Nothing here knows about atlases or the GPU.
- Equal keys produce identical bytes. Every input the rasteriser reads is in the key, which is what makes caching its output safe.
outlineis required, not defaulted. A rasteriser that silently returned no outlines would make every rotated, gradient-filled or very large run invisible.NoRasteris used before a font engine is configured. It reports every glyph as absent.
Absent and blank are different results throughout: a space rasterises to a valid image with zero
extent, while a face without the glyph returns None. The glyph cache relies on this to remember that a
space draws nothing.
Font libraries
crates/zgui-text-parley/Cargo.toml is the only manifest that names these.
| Library | Version | Role |
|---|---|---|
parley | 0.11.1 | Text layout: styled ranges, bidi, script segmentation, shaping, line breaking, alignment, justification |
fontique | 0.11.1, patched | Font collection: system enumeration, registration, family and attribute matching, per-script fallback |
harfrust | 0.12 (via parley) | The OpenType shaper parley calls. Not named by any zgui crate |
skrifa | 0.44 | Font-file reader: face metrics (metrics/read.rs) and glyph outlines (raster/outline.rs) |
swash | 0.2 | CPU rasteriser: hinting, coverage and colour rendering (raster/glyphs.rs), script lookup |
kurbo | 0.13 | Bézier paths. zgui-text re-exports it so GlyphRaster implementors use the same version |
The workspace manifest declares parley = "0.11.0"; Cargo.lock resolves 0.11.1.
The fontique patch
The workspace patches fontique with a vendored copy (vendor/fontique, [patch.crates-io], changes
marked ZGUI-PATCH:). Upstream clears a collection's query state at the start and end of every query,
and parley runs one query per paragraph. sans-serif resolves to around two hundred families on a
typical system, so every paragraph rebuilt that list, and every digit (which parley checks as a
possible emoji) rebuilt it again with emoji families appended. The patch keeps query state across
queries:
- The current family list and the last three are reused, with the faces they loaded.
- The fallback list is rebuilt only when its script or locale changes.
- A generation counter, raised by every collection mutation, discards stale state, so an unregistered face is never used again.
The patch only applies when building the zgui workspace. Applications using the published crates get
upstream fontique (same fonts, slower resolution) unless they add the same patch entry pointing at the
zgui repository; vendor/README.md shows how.
The font system
FontSystem (crates/zgui-text-parley/src/system/mod.rs) is one collection per application. It
implements FontSource and FontMetricsSource, and Shaper and Rasteriser are built from it, so a
registered face is visible to all four seams.
fontique needs &mut even for lookups, while the cascade queries metrics from many threads. So the
collection, its source cache and the face table sit behind one Mutex, with a metrics memo behind an
RwLock in front. FontSystem::lock_acquisitions() counts lock acquisitions so tests can check that the
memo works: the count should track distinct queries, not calls.
The collection is created shared, so the shaper's clone and every fork see faces registered later. The source cache is shared too, so one font file is one blob everywhere; downstream caches keyed by blob identity would otherwise treat the same face as different fonts per shaper.
System and registered fonts
Enumeration::System uses the operating system's faces plus registrations. Enumeration::Registered
(the default) uses registrations only, so the same registrations give the same advances and pixels on
every machine. Tests and reference images use it. In this mode, registering a family also binds it to every
generic role nothing else has claimed, so an unstyled document (which resolves to serif) still finds
a face. Applications choose with zgui::app::Fonts::system() or Fonts::shipped_only().
Matching and fallback
FaceQuery holds only what selects a face: family list, weight, slant, width, variations, language.
first_match (font/query.rs) walks the family list in order and returns the first face the
collection matches.
resolve_for adds a character and sets a fallback key from its script. script_of (font/script.rs)
converts the OpenType tag (arab) that character properties use to the ISO 15924 code (Arab) that
fallback lists use, by uppercasing the first letter. Versioned tags such as dev2 map to no list and
get no fallback rather than a wrong one.
Under Registered there is no system fallback list, so the registered families are swept instead.
That sweep is bounded by what the application registered, which is why it only happens in that mode.
Synthetic bold and italic
When no face covers the requested weight or slant, the run reports synthesis:
- Bold: strokes are thickened by
SYNTHETIC_BOLD_RATIO = 0.02of the size. - Italic: each glyph is sheared forward about its own origin by the angle fontique reports. The shear is per glyph, not per run, so letters lean instead of the whole line.
Both values are in GlyphKey and OutlineKey, so synthesised glyphs are separate cache entries.
The metrics memo
face_metrics hashes the query, size and writing mode into a MemoKey and answers from an
FxHashMap behind an RwLock (metrics/memo.rs). Only a miss takes the collection lock.
Registering or unregistering a family calls forget_metrics() and clears the memo, because the best
match for a query may have changed.
A query that matches nothing returns default metrics (optional fields absent, zero ascent) rather than failing, so a document using a missing family still cascades.
Flattening a paragraph
An inline formatting context lays out text, images and nested spans as lines. To the layout around
it, it is one leaf box. Its contents are flattened into one string in
crates/zgui-layout/src/inline/content/generate.rs. Flattening changes the text:
- Under
white-space-collapse: collapse, runs of spaces, tabs and newlines become one space. Runs at the start, at the end and after a forced break are removed. - Under
preserve, a tab becomes a jump to the next tab stop. text-transformchanges letters.
Each of these moves byte offsets, so the map from the generated string back to the source is built while the string is built.
pub struct ParagraphContent<'a> {
pub text: &'a str, // the generated string
pub map: &'a TextMap, // generated offsets → source positions
pub runs: &'a [StyledRun], // ascending, covering the string with no gaps
pub boxes: &'a [InlineBoxGeometry], // atomic inlines between the words
pub paragraph: &'a ParagraphStyle,
pub scale: f32, // device pixels per CSS pixel
}TextMap (crates/zgui-text/src/map/mod.rs) is a sorted list of Segments. Each records that a
stretch of the generated string is a verbatim copy of a source run's bytes. Adjacent stretches merge,
so uncollapsed text costs one entry. to_source and to_generated convert in each direction by binary
search. Their _snapped variants return the nearest real position instead of None, for hit testing on
a collapsed space and for a caret at the end of a field.
ParagraphContent::runs_are_well_formed checks that runs cover the string. Callers check it; shapers
assume it.
The flattened form is memoised beside its box (inline/content/memo.rs) and reused across layout
passes until its boxes, styles or device scale change. Style lowering (inline/content/styles.rs)
happens once per distinct computed style, not once per box.
Shaping
Shaping turns characters into positioned glyphs by running the font's OpenType tables. It cannot be
done per character: faces substitute glyphs in context (fi ligatures, Arabic joining forms), position
glyphs relative to each other (kerning, mark attachment), and some scripts reorder. A string's advance
is not the sum of its characters' advances.
parley first splits the text into runs that share one face, script, direction and style, and the shaper processes one run at a time.
Single-style fast path. When every non-empty run has the same style and brush (the common case for
labels and plain paragraphs), shape/build.rs resolves that style once and builds the layout with
parley's style-run builder over the whole string. Otherwise it uses the ranged builder and pushes each
run's properties over its range. Both produce the same layout; the fast path skips per-property pushes
and range splitting.
Base direction
The bidirectional algorithm orders mixed right-to-left and left-to-right text relative to a paragraph
base direction. zgui-text-parley forces the base direction by prefixing a directional mark (U+200F
or U+200E) to the string it hands parley (crates/zgui-text-parley/src/direction/mod.rs).
It does not wrap the paragraph in an isolate pair. The bidi paragraph-level rule skips everything inside an isolate, so an isolate around the whole paragraph hides every strong character and the base level falls back to left-to-right. The text still reorders correctly but aligns to the wrong edge.
The mark has no source position. Every line and cluster range is reported with the prefix length
subtracted (crates/zgui-text-parley/src/shape/lines.rs), so callers see one byte space only.
Controls::Verbatim disables the prefix for callers that emit their own controls.
Shaping keys and breaking keys
Breaking decides where lines end, using glyphs that shaping already produced. It changes no glyph.
On a thousand words, shaping costs about 28 times as much as breaking (crates/zgui-text/src/lib.rs).
Layout asks a paragraph for its size at many widths while it resolves flex or grid, so those questions
must cost breaks, not shapes.
zgui-text-style therefore hashes text style into two keys (crates/zgui-text-style/src/key/):
| Key | Covers |
|---|---|
ShapingKey | What decides which glyphs exist and how wide they are: family, size, weight, slant, width, font-synthesis-weight, optical sizing, variations, features, variant, language, letter-spacing, word-spacing, line-height, word-break, white-space handling, text-transform. On the paragraph: direction and writing mode |
BreakingKey | What only decides where lines end: overflow-wrap, text-wrap-mode, line-break. On the paragraph: text-align, text-align-last, text-justify, text-indent |
TextStyle::hash_shaping and hash_breaking (and the ParagraphStyle equivalents) are the only place
a property is assigned to one side. Direction and writing mode are shaping properties because they
change bidi resolution, mirroring and which advance table is read.
TextDamage::between(old, new) classifies a style change as None, Rebreak or Reshape by comparing
the two keys, not by consulting a property list.
Colour and brush slots
Colour is in neither key. A run's paint is lowered separately into TextPaint, and each distinct
cascade result claims a brush slot in a table that lives as long as the document. Shaped glyphs
store the slot number, not a colour. A theme change rewrites table entries and recolours every cached
paragraph without reshaping.
The slot number itself is part of the paragraph key, because the shaped glyphs name it. If two
contexts with the same text and style but different slots shared an entry, both would draw through
whichever slot shaped first. An element that has to move to a different slot (because the slot it
shared cannot be rewritten for it alone) therefore reshapes. zgui-layout/src/text/reshape.rs limits
that to the affected boxes: the element's own text boxes and the ancestors sized from them. The
style engine describes when an element moves.
The paragraph cache
ParagraphCache<E> (crates/zgui-text/src/paragraph/cache.rs) maps ParagraphKey to shaped
paragraphs. ParagraphKey::of(content) digests everything a shape depends on:
| Input | Why |
|---|---|
| The generated string | — |
| The device scale | Hinting changes the glyphs |
| The paragraph's shaping properties | Direction and writing mode |
Each run's extent, ShapingKey and brush slot, in order | Moving a run boundary changes which characters shape together; slots are baked into glyphs |
| Each atomic inline's id, offset and width | Content widths include the boxes |
The TextMap segments | A shaped result carries its map. Two sources can flatten to the same string (leading whitespace collapse), and sharing would misplace carets and hit tests |
Box height is not in the key. It only moves lines and belongs to the break request.
The key is computed in two parts. ContentKey covers everything except inline-box widths and is stored
in a OnceLock on the flattened Generated value, so a large string is hashed once.
ContentKey::with_boxes folds in the current widths for each measurement. shape_keyed passes the
finished key to the shaper.
ParagraphCache::insert takes the key from the shaped value, so a paragraph cannot be filed under a
wrong key.
Pre-shaping on workers
When the application has a layout pool, the
runtime shapes dirty paragraphs before layout asks for them. crates/zgui-layout/src/text/preshape.rs
walks the dirty region and collects dirty paragraphs with no inline boxes. It flattens them on the
frame thread, because flattening claims brush slots and slot assignment must stay deterministic.
Paragraphs::pre_shape then skips keys already in the cache and shapes the misses:
- 16 or more misses (
PRE_SHAPE_MIN_MISSES): on forked shapers on the layout pool. Each worker keeps its fork and scratch space across frames. Results are inserted in request order, so the cache ends up exactly as serial shaping would leave it. - Fewer than 16, or a shaper that cannot fork: serially on the frame thread, which still warms the
cache. Measured with the
label-churnbench, waking workers for 4–12 short labels made the frame 1.9× slower at the median.
Paragraphs with atomic inlines are not pre-shaped, because their key includes inline widths that layout has not measured yet. They are shaped by whichever layout worker reaches them.
During parallel layout, each batch worker has its own paragraph cache, and batch workers never claim
brush slots. A paragraph probed on one worker may be kept by another; the keeping pass calls
shape_keyed again, which is a lookup if that measurer already has it and a shape otherwise.
Eviction
Live inline resolutions hold the keys they use. Replacing a resolution releases its old key, but reclamation waits until fragment diffing has finished, so a new paragraph cannot reuse a slot that an old fragment still compares against.
The runtime budget (SHAPED_PARAGRAPHS = 16_384, crates/zgui-runtime/src/budget/limits.rs) evicts
only inactive entries, least recently used first, via ParagraphCache::evict_inactive. Exceeding
the budget never invalidates the live layout tree; a document with more active paragraphs than the
budget stays above it.
Window::forget_caches is all-or-nothing: it can drop active shaping, so it marks the whole layout tree
dirty.
Line breaking
A shaped paragraph holds one current break, because parley draws glyphs from its own laid-out form.
That suits the pass whose lines will be painted, but not measurement probes. So ShapedParagraph also
keeps the last four breaks (crates/zgui-text/src/paragraph/recall.rs, REMEMBERED = 4), keyed by
BreakingKey. This recall buffer stops min-content, max-content and final-width probes from evicting
each other.
Four covers the three questions layout asks repeatedly (min-content, max-content, height at the final width) plus one extra width from a nested grid. It is bounded because a window being resized proposes a new width every frame.
ShapedParagraph::plan_break decides every breaking pass:
pub enum Plan<'a> {
Reflected, // the current break already answers the request
Recalled(&'a BrokenParagraph),// a remembered break answers it (probes only)
Owed, // a breaking pass is needed, and has been counted
}- Only
OwedbumpsCounter::TextRebroken.ShapedParagraph::newis the only constructor and bumpsCounter::TextShaped. Together they count every pass. Recalledis offered only to probe requests (BreakRequest::probing). Answering from the buffer does not change parley's laid-out form, which is fine for "how big would it be" and wrong for the pass that will be painted.- Intrinsic-size probes are answered from
ShapedParagraph::content_widthswithout breaking at all (crates/zgui-layout/src/inline/measure.rs).
| Request | Cost |
|---|---|
| Same content, style and width | Reflected: one hash and one comparison |
Same content, a previously probed width, probe = true | Recalled: scan of at most four entries |
| Same content, new width | Owed: one breaking pass |
New content, new ShapingKey, new brush slot, new inline-box width, or new device scale | A full shape, then a break |
BreakingKey for a request (paragraph/key.rs::breaking_key) combines the paragraph's and runs'
breaking properties, each inline box's width, height and shift, the max advance, the indent basis and
the line bands (narrowed widths beside floats).
No-wrap paragraphs with inline boxes
parley allows a break after every inline box regardless of wrap mode. For a paragraph where no run may
wrap (ShapedLayout::wraps is false) and that contains inline boxes, shape/breaking.rs first breaks
with no width limit and then breaks at the larger of the requested width and the full width. The line
stays on one line, keeps its own width, and still overflows its box for clipping and ellipsis.
Shape and break from layout
zgui_text::lay_out(shaper, cache, content, request) hashes the content, shapes it if it is new, and
breaks it at the requested width. zgui-layout performs the two steps separately through
MeasureContent::shape and MeasureContent::break_lines, because one measure call shapes once and
may break several times. Paragraphs<S, R> (crates/zgui-layout/src/text/paragraphs.rs) holds the
shaper, its cache, the brush table and the worker forks. The cache lives there so the shaper can be
swapped; the brush table lives there because it must outlive every cached paragraph.
Line metrics and line boxes
FaceMetrics always carries ascent, descent and line_gap. The rest are Options: x_height
(ex), zero_advance (ch), cap_height (cap), ic_width (ic), underline and strikeout offset
and thickness, and the two MATH-table script percentages (always None from zgui-text-parley).
None means the face does not carry the metric, not zero. Each has a *_or_fallback method:
| Metric | Fallback |
|---|---|
x_height | X_HEIGHT_FALLBACK = 0.5 × size |
zero_advance | ZERO_ADVANCE_FALLBACK = 0.5 × size, or the full size for upright vertical text |
cap_height | The face's ascent |
ic_width | The full size (ideographs are square) |
| Decoration thickness | DECORATION_THICKNESS_FALLBACK = 1/14 × size |
| Underline offset | UNDERLINE_OFFSET_FALLBACK = -1/9 × size |
The strut and leading
The strut is the invisible zero-width box every line box is at least as tall as, so an empty line does not collapse.
StrutMetrics holds the face's ascent and descent, the resolved line height, the x-height and the font
size. Leading is the line height minus the face's content area (ascent + descent), split equally
above and below: half_leading(), ascent() and descent() return those values. Leading is negative
when line-height is tighter than the face. zgui-text-parley measures the strut by
laying out x and caches it by ShapingKey (shape/strut.rs).
parley clamps a negative leading to zero when it reports where a line starts. CSS does not: with a tight
line height the glyphs extend outside the line box, above and below. shape/lines.rs::top recomputes the
line top with the negative leading kept (repeating parley's rounding of ascent and descent), and both
LineGeometry::top and glyph positions use it.
Line boxes
LineGeometry reports, per line: the byte range of the generated string, top and baseline from the
top of the paragraph, height, width (content advance before alignment) and offset (inset from the
start edge after alignment and indent).
- The baseline comes from the line's contents, never from the font size: tall inline images and superscripts make lines taller.
offsetis parley's alignment offset plus the line's minimum inline coordinate, which is non-zero when the line is narrowed beside a float.
zgui-layout stacks these into LineBoxes. Each line box records its extents (how far the line
reaches above and below its baseline) and its ink: the union of the extents and the content area of
every run on the line. With a line height tighter than the face, ink extends past the line box.
fragment/ink.rs::of_line turns that into the rectangle damage uses, adding room for glyphs leaning
past their advance (0.25 × the ink height, the tangent of a synthesised italic's 14°), one device pixel
for rounding, and text shadows. The rectangle is mapped through the box's transform, so damage covers
overhanging glyphs wherever the box is drawn.
parley offers two walks over a line: by run, or by positioned item (which visits every glyph). Over a long paragraph the second costs four times what the break itself costs. It is only needed to locate atomic inlines, so it is used only when the context contains one.
Atomic inlines
An atomic inline is a non-text item on the line that is not broken internally: an image, an
inline-block, a form control.
pub struct InlineBoxGeometry {
pub id: u64,
pub offset: usize, // byte offset in the generated string
pub width: CssPx, // margin-box width
pub height: CssPx, // margin-box height
pub ascent: CssPx, // baseline to top margin edge, before the shift
pub shift: CssPx, // resolved vertical-align shift, positive upwards
}
pub fn shaper_height(&self) -> CssPx // ascent + shift
pub fn below_baseline(&self) -> CssPx // height - shaper_heightparley places an inline box with its bottom edge on the baseline. To position it, the shaper is given
shaper_height() instead of the real height; the real geometry is kept alongside.
vertical-align: top and bottom are resolved against the line box, which only exists after
everything else on the line is placed. A line containing one is broken again with the shift the
previous pass revealed, up to MAX_REALIGN_PASSES = 4 (crates/zgui-layout/src/inline/measure.rs).
Each pass can only make the line taller, so it converges; the bound caps the cost.
Rasterising glyphs
Each text fragment names one line of one paragraph. During paint, visit_line turns it into
ShapedRuns:
pub struct ShapedRun<'a> {
pub face: FaceId,
pub size: f32, // device pixels
pub synthetic_bold: f32, // fraction of the size; 0 when the face covers the weight
pub synthetic_slant: f32, // degrees; 0 when a real italic was found
pub has_color: bool,
pub brush: Brush, // a slot, never a colour
pub glyphs: &'a [ShapedGlyph],
}
pub struct ShapedGlyph { pub glyph: u16, pub x: f32, pub y: f32 }Positions are relative to the line box's top-left corner. The painter adds the line box's absolute origin from the fragment tree, so a scrolled paragraph needs no new glyph walk.
Atlas or outlines
RasterPath::of (crates/zgui-text/src/glyph/route.rs) picks one path per run, before anything is
rasterised. A run goes to the atlas if it has colour glyphs, or if it is small enough, its transform is a
pure translation and its brush is a single colour. Everything else is drawn as outlines.
| Constant | Value | Meaning |
|---|---|---|
ATLAS_MAX_CSS_SIZE | 96 CSS px | Largest run the atlas serves, stated in CSS pixels so a heading takes the same path on every display |
ATLAS_MAX_SIZE | 256 device px | Hard cap on a cached tile. The effective limit is 96 at 1×, 192 at 2×, 256 from 3× |
| Path | Used for | Notes |
|---|---|---|
| Atlas | Small runs with a translation-only transform and a solid brush; all colour runs | Rasterised once on the CPU, drawn as one quad per glyph. The only path that can be hinted or use subpixel (per-channel) coverage. |
| Vector | Large sizes, non-translation transforms, non-solid brushes | Outlines filled by the frame's path rasteriser. |
Colour runs always use the atlas, because a colour glyph is layered outlines or a bitmap, with no single outline to fill.
The choice is made in FrameContent::visit_line (crates/zgui-paint/src/content/cache.rs). A vector
run never allocates an atlas tile or touches the glyph cache, so rotated headings do not evict body
text. A bitmap-only face, which has no curves, falls back to tiles.
Glyph keys and pen positions
GlyphKey holds the face, glyph index, size, SubpixelOffset, RasterStyle (Grayscale, Subpixel
or Color) and the synthetic bold and slant amounts. Floats are stored as bits so the key hashes and
compares exactly. A glyph's horizontal position is split into a whole pixel (where the tile is drawn)
and a quantised fraction (how far the outline is shifted before rasterising).
SubpixelOffset::STEPS = 4, so each glyph has at most four phases.
PenPosition::of quantises the position to quarter pixels first and only then splits it into pixel and
phase. Rounding the phase and flooring the pixel independently would disagree whenever the fraction
rounds up to a whole pixel, and the glyph would land almost a pixel left of where it belongs. The
position passed in must be absolute (including the line box's own left edge); a line box at half a
pixel shifts every phase on it.
Because position enters the key only as a phase, the same letter at the same phase anywhere on the page is one cache entry, and scrolling by whole pixels reuses every tile.
Subpixel coverage is used only when all three hold (TextPlacement::keeps_subpixel): the device
supports dual-source blending, the target is opaque, and the run's transform is a translation by
whole device pixels. Any other transform (rotation, scale, fractional translation) resamples the
tile and would turn the per-channel stripes into colour fringes, so those runs use grayscale coverage.
Recorded lines are keyed on whether they keep subpixel coverage, so a box that moves on or off the
pixel grid re-emits its text. Text shadows never use subpixel coverage.
The glyph cache
An atlas is a large texture shared by many small images, so a thousand glyphs are a thousand quads
sampling one texture. zgui-atlas owns allocation and eviction. The glyph cache
(crates/zgui-paint/src/content/glyphs/cache.rs) sits in front of it and remembers, per GlyphKey:
- The tile.
- Placement and size. These come from the rasterised image; without them a cache hit would still require rasterising to know where to draw.
- Absence. A space has no pixels and no tile. Without remembering that, every space would be re-hinted on every full repaint.
It does not cache failures that depend on the current state: an unresolved face (it may be registered later) or a full atlas.
| Situation | Behaviour |
|---|---|
| Atlas full | Evict one cold generation (and the matching glyph and vector-mask records), retry once. If the retry fails, draw nothing and refuse to cache the paint record, so it is not replayed with a missing letter |
| Atlas evicts a tile | The glyph cache drops the matching record immediately. A bounded tombstone remembers the key; rebuilding it bumps Counter::RebuiltAfterEviction |
| Blank answers and tombstones | Capped at 4 096 each (COLD_ANSWERS), since atlas pressure cannot evict them |
| Face has no outline, or glyph has no pixels | No primitive. Nothing is drawn in place of the glyph |
Atlas tile format
AtlasGlyph::of(key, image) makes two conversions:
- Subpixel glyphs have three coverage values per pixel; the atlas pool is four bytes wide, so a fourth channel is padded in.
- Colour glyphs arrive with straight alpha; the atlas is premultiplied, so colour channels are scaled by alpha. Uploading straight alpha makes soft edges glow.
AtlasKey is a hash of the whole GlyphKey, so requests that would rasterise identically share a tile.
The outline path
OutlineKey holds face, glyph, size and synthetic slant, and no position: an outline is the same curve
wherever it is drawn, and the path rasteriser antialiases analytically, so there is no phase. Outlines
are extracted unhinted, since hinting snaps to a pixel grid that a rotated curve no longer has.
GlyphOutline is Arc<BezPath>. The path rasteriser caches its encoding of a path by Arc identity,
so returning the same allocation each frame avoids re-encoding every glyph. Outlines
(crates/zgui-text-parley/src/raster/outline.rs) holds up to 512 and clears all at once when full.
Each placed outline glyph (OutlineGlyph) shares that allocation and carries its pen position;
the display list places it by translation. Repeated outlines can additionally be rasterised once into
glyph sheets; see Paint and the scene.
Carets and selection
Caret and selection rectangles come from visit_clusters. A caret plan records the box that owns it as
well as the paragraph, so when two boxes share one cached paragraph (same text and style), the caret is
drawn only in the box that holds it.
All text caches
| Cache | Where | Key | Cleared by |
|---|---|---|---|
| Lowered text styles | zgui-layout inline/content/styles.rs | Computed-style identity | Rebuilding the pass |
| Flattened content | zgui-layout inline/content/memo.rs | The boxes, their styles, the scale | Any of those changing |
| Face metrics | zgui-text-parley metrics/memo.rs | Query + size + writing mode | Any registration |
| Font query state | vendor/fontique collection/query.rs | Family list (last four), script and locale | A collection generation change |
| Struts | zgui-text-parley shape/strut.rs | ShapingKey | Shaper::forget_measurements |
| Face bytes | zgui-text-parley raster/faces.rs | FaceId | Never (a handle names a file and an index) |
| Shaped paragraphs | zgui-text paragraph/cache.rs | ParagraphKey | Inactive LRU eviction, a brush-slot move, or forget_caches |
| Recent breaks | zgui-text paragraph/recall.rs | BreakingKey, four deep | The fifth distinct width |
| Glyph tiles and placements | zgui-paint content/glyphs/cache.rs | GlyphKey | Atlas eviction, lost device |
| Glyph outlines | zgui-text-parley raster/outline.rs | OutlineKey, 512 deep | Reaching capacity |
The atlas soft limit is ATLAS_SOFT_BYTES = 64 MiB (crates/zgui-runtime/src/window/mod.rs).
What invalidates a paragraph
| Change | Cost | Reason |
|---|---|---|
color, or a theme change | Nothing | The slot's colour is rewritten in place |
text-align, text-indent, overflow-wrap, line-break | One break | BreakingKey changed |
| Available width | One break | Width is in BreakingKey |
Inline box height or vertical-align | One break | Both are in the break request |
| A float beside the text | One break | Line bands are in BreakingKey |
| Inline box width | One shape | Width is in ParagraphKey |
font-size, font-family, letter-spacing, font-feature-settings, direction, … | One shape | ShapingKey changed |
| The text | One shape | The string is in ParagraphKey |
| An element moving to a different brush slot | One shape for its contexts | The slot is in ParagraphKey |
| Device scale factor | Every paragraph reshapes | Scale is in ParagraphKey |
| A face registered or removed | Metrics memo and font query state cleared | The best match may have changed |
On the style side, TextKeyStore compares each element's previous shaping and breaking keys to
narrow a restyle to TextWork::None, Rebreak or Reshape; see
Invalidation. A text edit is
written into the existing box; see
Rewriting text in place.
Measured costs
| Figure | Value | Source |
|---|---|---|
| Shaping vs breaking, 1 000 words | about 28 : 1 | crates/zgui-text/src/lib.rs |
| Rasterising one glyph, with a stable scaler id | 32.0 µs | docs/perf/endtoend.md |
| Same, with a fresh scaler id per glyph | 74.8 µs | docs/perf/endtoend.md |
| Scale-factor change, gallery, 483 placed glyphs | 218–230 rasterisations | docs/perf/scale.md |
| Returning to a previously used scale | 0 rasterisations | docs/perf/scale.md |
The scaler id matters because swash runs a face's TrueType hinting programs (fpgm and prep) once
per font identity. A fresh identity per glyph re-runs them for every glyph. raster/glyphs.rs builds
the scaler with builder_with_id(font, identity(key.face, index)), a stable id per face.
Counters to watch: Counter::GlyphsRasterised should be zero when repainting unchanged text.
Counter::TextShaped and Counter::TextRebroken are each bumped in exactly one place.
Next
Paint and the scene
Where the sprites and vector items this stage produced become a display list.
The renderer
The atlas on the device, and how a coverage tile becomes a pixel.
Caches
Every cache in the pipeline, what invalidates it, and what a miss costs.
Text and fonts
The application side: registering faces, and what causes reshaping.
The layout engine
How zgui-layout builds and patches the box tree, drives the retained Cephal engine incrementally and in parallel, and produces fragments, paint order and the hit index.
Paint and the scene
How paint turns the fragment tree into a display list: primitives, clips, draw order, the stacking walk, damage culling, replay, vector routes, vector passes and batching.