burokku docs plan text-engine.md

Text engine #

Status: built. Phase 2's steps 1 and 2 rebuilt the engine as this design asks; interaction, step 3, is not planned yet. What follows is what the text engine must do, how it worked before the rebuild, and why that did not fit the plan in docs/plan/custom-elements.md and docs/plan/extension-api.md.

Decided marks what the design settled; Proposed marks recommendations that still need a decision; Open marks questions without a recommendation yet.

Scope #

Decided.

  • Cost follows the change. A large <text> that changes a little and often, such as a counter inside a long paragraph, a log that grows, or a line being typed, must not collect, shape, break, or draw the whole block again. This is the text engine's main job; see Cost follows the change.
  • No new style properties here. text keeps its six typography properties: font-family, font-size, font-weight, color, line-height, and text-wrap. The engine must keep room to add more later, such as font-style or text-align, without restructuring; see Room for more properties.

Today #

This section and the Today notes below describe the pipeline before text step 2a, which they motivate. Since then text collects, measures, and paints through its instance; see text-engine-implementation.md.

  1. Collect. collect_paragraph (ui/text/collect.rs) walks an outermost <text> and its subtree into a ParagraphInput: the text, styled runs with fully inherited ComputedTextStyle, a fingerprint, and the source NodeId.
  2. Lay out. The layout reconciler gives the paragraph one Taffy leaf, LayoutRole::Paragraph. The tree records the paragraph as the owner of every node it absorbs (UITree::owner). Taffy measures the leaf through TextMeasurer (layout/tree.rs), which LayoutEngine<TextEngine> owns.
  3. Shape. TextEngine (ui/text/engine.rs) shapes with Parley and caches per source node: the unbroken layout, up to four measured sizes, and the last shaped paragraph. ComputedLayout keeps the final ShapedParagraph for each source.
  4. Paint. The scene emits PaintItem::Text. scene/layers.rs asks the paragraph for its layer_image, which text/paint.rs draws on the CPU with vello_cpu into one image per paragraph at the window's scale factor. The image is kept until the paragraph or the scale changes.
  5. Fonts. BurokkuBuilder::font_data hands fonts to load_fonts, which builds the TextEngine before the host exists. Fontique adds the system fonts. Registering a font clears every cache.

Cost follows the change #

What one changed character costs today #

Every stage works on the whole <text> block:

Stage Cost of changing one character
Collect The whole subtree is walked into a new string, and the fingerprint hashes all of it.
Shape The fingerprint misses, so Parley builds and shapes the whole unbroken layout again.
Break lines Every line is broken again.
Paint The whole paragraph is drawn again into one new image.
Present The compositor gets a new image and uploads the whole bitmap.

A color change costs the same, because color is hashed into the fingerprint (text/model.rs) and passed to Parley as the brush.

The single image also has a size limit. An image dimension is capped at 65,535 pixels; a taller paragraph fails rasterize_paragraph, and scene/layers.rs returns the error, so the whole frame fails. At a scale of 2, that is about 1,500 lines of 16px Noto Sans at its normal line height. A long paragraph in a scroll container also draws its hidden lines.

Measured #

cargo bench -p burokku --features bench --bench text times one edit to a four-digit counter run in the middle of a paragraph of prose, 800px wide and painted at scale 2, and a resize that breaks lines again without shaping. Medians in milliseconds on one development machine:

Paragraph Collect Layout Paint Edit total Resize layout
1k characters, 1 line 0.00 0.12 1.41 1.54 0.01
10k characters, 1 line 0.02 1.14 13.59 14.75 0.12
50k characters, 1 line 0.06 5.61 71.01 76.61 0.53
100k characters, 1 line 0.11 12.34 143.49 156.18 1.54
100k characters, 1,000 lines 0.11 12.26 151.19 163.50 1.45
  • Painting dominates. Drawing the whole paragraph costs about ten times its layout, and a 10k-character paragraph already misses a 60 Hz frame on painting alone. Bands, which draw only what changed and what is visible, matter most.
  • Shaping is most of layout. Layout after an edit minus layout after a resize leaves shaping at about 0.11 ms per thousand characters; breaking lines costs about a tenth of that.
  • Hard line breaks do not help today. 1,000 lines cost the same as one, because the whole paragraph is one Parley layout. Segments would shape one line of about 100 characters instead.
  • The size limit is real. The 1,000-line paragraph's resize painted an image 69,446 pixels tall and failed.
  • Collecting is cheap. Under 0.2 ms even at 100k characters.

The table does not include uploading the image to the compositor.

After bands #

After phase 2, step 1b, the same bench draws only the bands an 800 × 600 view shows and reuses those that did not change. It adds a color change to the counter run, a line appended at the end, and a scroll by one view. Medians in milliseconds on the same machine; the last three columns are totals:

Paragraph Collect Layout Paint Edit total Resize layout Resize paint Color Append Scroll
1k characters, 1 line 0.00 0.12 0.91 1.03 0.00 0.01 0.84 0.12 0.00
10k characters, 1 line 0.01 1.05 0.09 1.15 0.04 0.09 0.16 0.17 0.00
50k characters, 1 line 0.05 5.37 0.46 5.89 0.22 0.45 0.79 0.79 3.80
100k characters, 1 line 0.10 10.71 0.91 11.73 0.46 3.60 1.59 1.61 4.33
100k characters, 1,000 lines 0.10 0.87 0.96 2.02 0.62 0.93 1.99 2.02 3.61
  • An edit costs what it touches. 2.02 ms for the 1,000-line paragraph, down from 163.50: one segment shapes and no band in view changes. The single-line paragraphs still shape their one segment in full.
  • Paint follows the view. Where the counter is out of view, paint is the cost of hashing the lines again, about 0.9 ms per 100k characters. Drawing a new view costs about 4 ms.
  • The size limit is gone. The 1,000-line paragraph's resize draws.

After paint-time color #

After phase 2, step 2c, a color change is Repaint: the text collects it, the engine recolors the lines it already broke, and only the band holding the run draws again. Medians in milliseconds for the color column, same machine:

Paragraph Color before Color after
1k characters, 1 line 0.84 0.94
10k characters, 1 line 0.16 0.07
50k characters, 1 line 0.79 0.32
100k characters, 1 line 1.59 0.65
100k characters, 1,000 lines 1.99 0.71

The 1k paragraph's one band holds the run, so it draws again either way. The bench still runs collect and layout after every change, so the rest is collecting the paragraph again and Taffy finding nothing to do.

Segments #

Proposed. Split a paragraph at hard line breaks into segments, and shape and break each segment on its own.

  • Nothing crosses a hard line break: shaping does not, and the bidirectional algorithm treats a line feed as a paragraph separator. So segments shape independently and give the same result as one layout.
  • Each segment is cached by its text and shaping styles. A change inside one segment shapes only that segment; the segments after it keep their layout and only move.
  • The paragraph's size combines its segments: heights add up, and the max-content and min-content widths are the largest of the segments'. The first baseline is the first segment's.
  • A width change breaks every segment again but shapes none, as the unbroken layout allows today.
  • An empty segment, a blank line, still takes one line at the style of its position.

Collecting only what changed #

Proposed. Each segment remembers the nodes it covers and their revisions. A change to a text node's data or a run's style marks only the segments that node covers, and only those are collected again. A child added or removed marks the segments around it. Segments keep their own text, so no stage rebuilds or hashes the whole string.

The absorbing hook subtree_changed in docs/plan/custom-elements.md is where this classification lives once text is an instance.

Bands #

Proposed. Paint a paragraph as bands instead of one image.

  • A band is a run of whole visual lines up to a fixed height, drawn as its own image and shown as its own layer. No image reaches the size limit, so a long paragraph no longer fails the frame.
  • A band's image is keyed by what it draws: its glyphs, their positions, and their colors. After a change, a band with an unchanged key keeps its image, so the compositor sees the same image and uploads nothing. A band that only moved gets a new frame.
  • Only bands that intersect the visible clip are drawn. Scrolling draws bands as they come into view.

Paint properties out of shaping #

Proposed. Shape with a run index as the brush and resolve the run's color when a band is drawn. A color change then shapes nothing and draws only the bands containing that run, which is the Repaint level in the custom elements plan.

Room for more properties #

Proposed. Each text property declares the stage it affects, and the caches read that declaration instead of a hard-coded list:

Stage Today Effect of a change
Layout font-family, font-size, font-weight, line-height, text-wrap Shape and break the affected segments again
Paint color Draw the affected bands again

A property added later, such as font-style (layout) or a text decoration (paint), then picks its cache key and dirty level from its stage. The parser, default, and stage come from the same declaration that custom style properties use in docs/plan/custom-elements.md.

Long segments #

Segments cut cost at hard line breaks only. A long segment with no line breaks, such as a long paragraph being typed, still shapes in full on every change, because Parley builds a layout in one pass.

Incremental shaping can be built on Parley by using it to shape chunks and laying out lines ourselves:

  • Chunks. Split a segment at safe boundaries, and shape each chunk as its own unbroken Parley layout, cached by its text, styles, and font generation, as browsers cache shaped words. An edit shapes only the chunks it touches.
  • Bidi. Resolve bidi levels over the whole segment, which needs no shaping, and split chunks where levels change. An edit that changes the levels of nearby text shapes those chunks again too.
  • Lines. Break lines across chunks from what Parley's clusters and runs expose: advances, soft line breaks, and run metrics. Breaking can restart at the edited line and stop once a break falls where it fell before, because greedy breaking converges.
  • Bands work unchanged, since they are keyed by the glyphs they draw.

The cost:

  • Safe boundaries. A chunk shaped alone must match the same text shaped in context. HarfBuzz marks where that holds, and HarfRust has unsafe_to_break, but Parley does not expose it. Splitting at spaces instead is wrong for fonts that kern or form ligatures across a space, which Blink detects and then stops caching words, and scripts written without spaces, such as Chinese or Thai, need another rule.
  • Owning line layout. The result is no longer a Parley Layout, so what is built on it has to be rebuilt: line breaking, alignment, inline boxes, cluster hit testing, cursor and selection, PlainEditor, and accessibility.

Proposed. Do not build it now. Measured shaping is about 0.11 ms per thousand characters (see Measured), so a segment fits in a 60 Hz frame up to roughly 50k characters, far beyond a typical paragraph. Segments are enough. If an application needs longer segments, shape in chunks only the segments over a length threshold and keep Parley's layout for the rest, at the price of two line layouts that hit testing and selection must both understand. Getting Parley to expose safe-to-break boundaries upstream would remove the guessing at chunk boundaries.

Why it does not fit the plan #

Phase 2, step 2 resolved most of this: text is a leaf definition whose instance collects through the absorbing hooks and measures and paints through the paragraph engine, which owner handles key. #183 moved text onto the public element API, with the paragraph engine a core service the engine lends through it; see The paragraph engine is a core service. Still open: loading fonts at run time, and interaction.

The plan makes text one built-in among others: a leaf definition whose instance absorbs its children, measures itself, and paints built-in data, registered through the extension API. Today text is not an element type with an instance; it is a pipeline that layout, the scene, and the host each know about by name.

Layout knows one kind of leaf #

Plan. A leaf measures itself through its instance's measure; text, an image, and a web view are all leaves.

Today. Other leaves measure through their instances, but text is still measured by name:

  • LayoutRole (layout/reconcile.rs) is Container, Leaf, which measures through the instance, or Paragraph { collected }, which only text gets.
  • LayoutEngine<M: TextMeasurer> takes one measurer, and its TextMeasureRequest carries a ParagraphInput.
  • ComputedLayout stores text results by name: final_paragraphs.

The leaf role that dispatches to the element's instance exists; text needs to become one implementation of it.

Measuring mutates a shared engine #

Plan. measure(&self, input) runs with the tree borrowed, changes nothing, and returns the same result for the same input.

Today. TextMeasurer::measure takes &mut self: measuring fills TextEngine's caches, and every paragraph shapes through one shared Parley font context and layout context. A &self hook on a text instance cannot reach that engine. A custom element measuring a label has the same problem.

Measuring needs a context that lends engine services, such as measure(&self, cx: &mut MeasureContext<'_>, input), or a paragraph engine behind interior mutability.

Collection is a tree walk, not a hook #

Plan. An absorbing element implements collect and subtree_changed, and the collected content lives in its instance.

Today. collect_paragraph matches Element::Text and reads the tree directly. The collected paragraph lives in layout state (LayoutRole::Paragraph), the shaped paragraph in ComputedLayout, and the image in the ShapedParagraph. Nothing belongs to the element, so a custom absorbing element, such as a <chart> collecting <series>, has nowhere to keep its content. Segments and bands need the same home.

The engine is keyed by tree nodes #

Plan. Text is one of the kinds of built-in data a custom element may paint, so a <chart> can draw axis labels.

Today. ParagraphInput::source is a NodeId. TextEngine caches in a SecondaryMap<NodeId, SourceEntry>, retain_sources drops entries whose node was not laid out, and errors name the paragraph node. A label that is not a <text> node has no key, and its cache entry would be dropped each frame.

Paragraphs need to belong to whoever shapes them, as a handle the caller keeps, with the node used only for diagnostics.

Paint does not follow the dirty levels #

Plan. A color change is Repaint, and built-in data is cheap to rebuild each frame.

Today. Color is a shaping input, and each paragraph is one image drawn while the frame's layers are built; see Cost follows the change.

Since text step 2c. color is Repaint, and a change to it breaks no line and draws again only the bands holding that run.

Fonts are fixed when the engine is built #

Plan. Extensions register fonts through the registry's font(data).

Today. Fonts come only from BurokkuBuilder::font_data, before the app starts. Registering at build fits the registry directly. Loading a font at run time, from JavaScript, has no path.

Since phase 1, step 3. Fonts register through Registry::font. Loading one at run time still has no path.

The paragraph engine is a core service #

docs/plan/extension-api.md asks whether built-ins may use capabilities the extension API does not offer, and text was the main case.

Decided (#183). text is an extension built on the public element API alone, in features/text: a leaf definition whose instance collects its paragraph from what it absorbs, and measures and paints it through the engine. The paragraph engine stays in the core, as a pipeline service rather than a feature, by rule 1 of docs/interaction/engine_state.md: layout measures text to do its own job and the scene draws bands to do its own, as both use Taffy. Moving the engine out would only replace one internal dependency with another, and

  • fonts are one set: Registry::font loads into the engine's font context, and an element's own engine would see none of them;
  • the cache and generation are layout's: an engine layout does not hold is outside what ComputedLayout reuses;
  • making ShapedParagraph, TextBox, and TextConstraint public now would freeze Parley's shape as API while interaction, editing, and IME are still undesigned;
  • selection needs paragraph hit testing, which a feature reads through TreeView with the engine in core, but would have to reach into another extension's internals with the engine in one.

An instance borrows the engine's paragraph engine; it never creates one. What the engine lends, through the collect, measure, and paint hooks, is narrow: InstanceGive::state_with_paragraphs lends Paragraphs, which creates a ParagraphHandle and updates its content from a ParagraphInput; MeasureContext::measure_paragraph measures a handle at an AvailableSpace; and PaintList::text draws one, shaped to the content box. ParagraphHandle is opaque, ParagraphInput and StyledTextRun own their text and styles, and TextError reports what could not be shaped. ShapedParagraph stays internal: the scene takes the shaped result itself, and selection reads it in the engine.

What stays in the core and is not coupling: LayoutEngine holding the engine, text_generation in ComputedLayout, PaintItem::Text and the bands, and Registry::font. These are the core providing a text service. text registers as a built-in extension, burokku-text, through Registry::element, so the tree has no constant for its tag, and textContent follows the content model: any element that absorbs raw text takes it.

Interaction has nothing to attach to #

Plan. Engine-owned state such as selection implements EngineState (docs/interaction/engine_state.md); an instance that changes layout asks through request_layout; IME is a window or app service (Window, item 7, in docs/plan/custom-elements.md).

Today.

  • Nothing maps a point to a character offset.
  • The tree makes the paragraph the owner of every run (UITree::owner), so a nested <text> run cannot be its own event target, and a link inside a paragraph is not possible.
  • There is no selection, caret, or copy. ui/interaction.rs names selection as future work.
  • crates/native delivers KeyboardInput and no IME or composition events.
  • Editing changes layout, which EngineState::reconcile cannot request, so an editable text element has to be an instance that calls request_layout. Typing is the small, frequent change that segments and bands exist for.

What is missing #

Besides style properties, which are out of scope:

  • Inline atoms: an icon or image inside a paragraph. Parley's InlineBox already carries the engine's missing-glyph boxes.
  • Interaction: character hit testing, selection, caret, copy, editing, and IME. Parley's cursor, selection, and PlainEditor can back most of it.
  • Fonts: loading at run time, a font-loaded event, and control over fallback order and locale.
  • Unverified: color emoji (COLR and bitmap glyphs). text/paint.rs has no handling of its own.

Order #

Decided. The text engine is rebuilt on the element traits and the extension API once they exist, the first phase in docs/plan/custom-elements.md (Implementation order), instead of being fixed in place first. Today's engine keeps working, unchanged, until the rebuild.

Rebuild steps, each keeping the existing tests passing. Steps 1 and 2 are built:

  1. A paragraph engine keyed by its owner: a paragraph handle that shapes, measures, and paints, with segments, bands, and paint-time color from the start.
  2. The text definition and instance. It measures through the measure context, collects through the absorbing hooks, and collects again only the segments whose nodes changed. Layout's Paragraph role and its text results give way to the leaf role and absorbing ownership.
  3. Interaction: character hit testing and run targets, then selection and copy, then editing and IME.

docs/plan/text-engine-implementation.md plans steps 1 and 2 as pull requests. Interaction is not planned yet.

Open questions #

  • Does text stay an image, drawn in bands, or become a layer data kind of its own, such as glyph runs that each surface draws? A glyph-run kind needs glyph drawing on every platform; CoreAnimation has no glyph-run layer.
  • Does IME belong to the window or the app? See Window, item 7, in docs/plan/custom-elements.md.