zgui
Architecture

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

CrateContains
zgui-text-styleText properties lowered from the cascade, and the shaping and breaking hashes over them
zgui-textThe contracts: four seams, the value types on both sides, the paragraph cache
zgui-text-parleyThe 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:

StageWhereProduces
Flattencrates/zgui-layout/src/inline/content/generate.rsGenerated: the string, the map, the runs, the inline items
Shapecrates/zgui-text-parley/src/shape/build.rsShapedParagraph<ShapedLayout>
Breakcrates/zgui-text-parley/src/shape/breaking.rsBrokenParagraph
Line boxescrates/zgui-layout/src/inline/lines.rsCSS line boxes with baselines and ink extents
Placecrates/zgui-paint/src/content/glyphs/place.rsPlacedGlyph: an atlas tile and a rectangle
Emitcrates/zgui-paint/src/emit/text.rsSprites, 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.

SeamFileCalled byOther implementations
FontMetricsSourcemetrics/source.rsThe cascade, to resolve ex, ch, cap, icFixedMetrics
FontSourcefont/source.rsFace resolution and @font-face—
ParagraphShaperparagraph/shaper.rsLayout: once per paragraph, then once per widthMonoShaper
GlyphRasterglyph/raster.rsPaint: once per distinct glyphMonoRaster, 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_for exists because fallback is per character: a Latin sentence with one emoji resolves to two faces.
  • A FaceId is opaque and only meaningful to the source that issued it.
  • FaceRecord reports 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<'_>));
}
  • shape and break_lines are separate because their costs differ by more than an order of magnitude. All caching below depends on breaking without reshaping.
  • Engine is the shaper's private shaped form. For zgui-text-parley it is ShapedLayout: a parley::Layout, the byte length of the directional prefix, the last break, and whether any run may wrap.
  • shape_keyed lets a caller that already computed the ParagraphKey skip rehashing the paragraph.
  • fork returns a second shaper over the same font data with its own scratch space, for shaping on worker threads. None keeps 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_line yields glyphs (what is painted). visit_clusters yields 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.
  • outline is required, not defaulted. A rasteriser that silently returned no outlines would make every rotated, gradient-filled or very large run invisible.
  • NoRaster is 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.

LibraryVersionRole
parley0.11.1Text layout: styled ranges, bidi, script segmentation, shaping, line breaking, alignment, justification
fontique0.11.1, patchedFont collection: system enumeration, registration, family and attribute matching, per-script fallback
harfrust0.12 (via parley)The OpenType shaper parley calls. Not named by any zgui crate
skrifa0.44Font-file reader: face metrics (metrics/read.rs) and glyph outlines (raster/outline.rs)
swash0.2CPU rasteriser: hinting, coverage and colour rendering (raster/glyphs.rs), script lookup
kurbo0.13Bé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.02 of 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-transform changes 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/):

KeyCovers
ShapingKeyWhat 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
BreakingKeyWhat 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:

InputWhy
The generated string—
The device scaleHinting changes the glyphs
The paragraph's shaping propertiesDirection and writing mode
Each run's extent, ShapingKey and brush slot, in orderMoving a run boundary changes which characters shape together; slots are baked into glyphs
Each atomic inline's id, offset and widthContent widths include the boxes
The TextMap segmentsA 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-churn bench, 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 Owed bumps Counter::TextRebroken. ShapedParagraph::new is the only constructor and bumps Counter::TextShaped. Together they count every pass.
  • Recalled is 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_widths without breaking at all (crates/zgui-layout/src/inline/measure.rs).
RequestCost
Same content, style and widthReflected: one hash and one comparison
Same content, a previously probed width, probe = trueRecalled: scan of at most four entries
Same content, new widthOwed: one breaking pass
New content, new ShapingKey, new brush slot, new inline-box width, or new device scaleA 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:

MetricFallback
x_heightX_HEIGHT_FALLBACK = 0.5 × size
zero_advanceZERO_ADVANCE_FALLBACK = 0.5 × size, or the full size for upright vertical text
cap_heightThe face's ascent
ic_widthThe full size (ideographs are square)
Decoration thicknessDECORATION_THICKNESS_FALLBACK = 1/14 × size
Underline offsetUNDERLINE_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.
  • offset is 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_height

parley 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.

ConstantValueMeaning
ATLAS_MAX_CSS_SIZE96 CSS pxLargest run the atlas serves, stated in CSS pixels so a heading takes the same path on every display
ATLAS_MAX_SIZE256 device pxHard cap on a cached tile. The effective limit is 96 at 1×, 192 at 2×, 256 from 3×
PathUsed forNotes
AtlasSmall runs with a translation-only transform and a solid brush; all colour runsRasterised once on the CPU, drawn as one quad per glyph. The only path that can be hinted or use subpixel (per-channel) coverage.
VectorLarge sizes, non-translation transforms, non-solid brushesOutlines 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:

  1. The tile.
  2. Placement and size. These come from the rasterised image; without them a cache hit would still require rasterising to know where to draw.
  3. 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.

SituationBehaviour
Atlas fullEvict 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 tileThe glyph cache drops the matching record immediately. A bounded tombstone remembers the key; rebuilding it bumps Counter::RebuiltAfterEviction
Blank answers and tombstonesCapped at 4 096 each (COLD_ANSWERS), since atlas pressure cannot evict them
Face has no outline, or glyph has no pixelsNo 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

CacheWhereKeyCleared by
Lowered text styleszgui-layout inline/content/styles.rsComputed-style identityRebuilding the pass
Flattened contentzgui-layout inline/content/memo.rsThe boxes, their styles, the scaleAny of those changing
Face metricszgui-text-parley metrics/memo.rsQuery + size + writing modeAny registration
Font query statevendor/fontique collection/query.rsFamily list (last four), script and localeA collection generation change
Strutszgui-text-parley shape/strut.rsShapingKeyShaper::forget_measurements
Face byteszgui-text-parley raster/faces.rsFaceIdNever (a handle names a file and an index)
Shaped paragraphszgui-text paragraph/cache.rsParagraphKeyInactive LRU eviction, a brush-slot move, or forget_caches
Recent breakszgui-text paragraph/recall.rsBreakingKey, four deepThe fifth distinct width
Glyph tiles and placementszgui-paint content/glyphs/cache.rsGlyphKeyAtlas eviction, lost device
Glyph outlineszgui-text-parley raster/outline.rsOutlineKey, 512 deepReaching capacity

The atlas soft limit is ATLAS_SOFT_BYTES = 64 MiB (crates/zgui-runtime/src/window/mod.rs).

What invalidates a paragraph

ChangeCostReason
color, or a theme changeNothingThe slot's colour is rewritten in place
text-align, text-indent, overflow-wrap, line-breakOne breakBreakingKey changed
Available widthOne breakWidth is in BreakingKey
Inline box height or vertical-alignOne breakBoth are in the break request
A float beside the textOne breakLine bands are in BreakingKey
Inline box widthOne shapeWidth is in ParagraphKey
font-size, font-family, letter-spacing, font-feature-settings, direction, …One shapeShapingKey changed
The textOne shapeThe string is in ParagraphKey
An element moving to a different brush slotOne shape for its contextsThe slot is in ParagraphKey
Device scale factorEvery paragraph reshapesScale is in ParagraphKey
A face registered or removedMetrics memo and font query state clearedThe 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

FigureValueSource
Shaping vs breaking, 1 000 wordsabout 28 : 1crates/zgui-text/src/lib.rs
Rasterising one glyph, with a stable scaler id32.0 µsdocs/perf/endtoend.md
Same, with a fresh scaler id per glyph74.8 µsdocs/perf/endtoend.md
Scale-factor change, gallery, 483 placed glyphs218–230 rasterisationsdocs/perf/scale.md
Returning to a previously used scale0 rasterisationsdocs/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

On this page