# Text engine implementation Status: built. Steps 1a to 2c are built, each noted as Built below. How the text engine that `docs/plan/text-engine.md` designs was built: a paragraph engine on Parley whose cost follows the change, and the `text` element on the element traits of `docs/plan/custom-elements.md`. **Decided** marks what the design settled; **Proposed** marks recommendations that still need a decision; **Open** marks questions without a recommendation yet. ## Scope **In scope.** - Phase 2, step 1: the paragraph engine. Owner handles, segments, shaping and breaking per segment, run-index brushes with paint-time color, and bands. - Phase 2, step 2: the `text` definition and instance. Measuring through the measure context, the absorbing hooks, collecting only what changed, and `color` at the `Repaint` level. **Not in scope yet.** - Interaction: character hit testing, run targets, selection, copy, editing, and IME. The engine keeps what they will need, Parley's clusters per segment and a record per visual line, and adds nothing for them. - Shaping long segments in chunks; see Long segments in `docs/plan/text-engine.md`. A segment still shapes in full. - New text properties, inline atoms, and loading fonts at run time. ## What a change costs after the rebuild | Change | Collect | Shape | Break lines | Draw | |---|---|---|---|---| | Text of one run | the segments the run touches | those segments | those segments | visible bands whose lines changed | | Shaping style of a run, such as `font-size` | the segments under it | those segments | those segments | visible bands whose lines changed | | Color of a run | the runs under it | nothing | nothing | visible bands holding those runs | | Child added, removed, or moved | the whole paragraph | changed segments only | changed segments only | visible bands whose lines changed | | Width | nothing | nothing | every segment | visible bands whose lines changed | | Scroll | nothing | nothing | nothing | bands coming into view | | Font registered | nothing | everything | everything | everything visible | Expected results for the cases in `benches/text.rs`, from the measured rates in `docs/plan/text-engine.md` (shaping about 0.11 ms per thousand characters, drawing about 5 ms per thousand logical pixels of lines at 800px and scale 2): | Edit to the counter run | Today | Expected | |---|---|---| | 100k characters, 1,000 lines | 163.5 ms | under 3 ms: one ~100-character segment and one band | | 100k characters, 1 line | 156.2 ms | about 15 ms: the whole segment shapes, one band draws | | 10k characters, 1 line | 14.8 ms | about 4 ms | Step 1b checks these against the bench: 2.02 ms, 11.73 ms, and 1.15 ms. See After bands in `text-engine.md`. ## The paragraph engine ### Ownership **Proposed.** ```rust pub(crate) struct ParagraphEngine { fonts: FontContext, layout: LayoutContext, font_generation: u64, paragraphs: SlotMap, released: Rc>>, } /// Kept by whoever shapes the paragraph. Not `Clone`; dropping it frees /// the paragraph at the engine's next use. pub(crate) struct ParagraphHandle { id: ParagraphId, released: Rc>>, } impl ParagraphEngine { pub fn create(&mut self, owner: NodeId) -> ParagraphHandle; pub fn register_font(&mut self, data: Vec) -> Result; pub fn edit(&mut self, paragraph: &ParagraphHandle) -> ParagraphEditor<'_>; pub fn measure(&mut self, paragraph: &ParagraphHandle, constraint: TextConstraint) -> Result; pub fn bands(&mut self, paragraph: &ParagraphHandle, request: BandRequest) -> Result, TextError>; } ``` - A paragraph belongs to whoever holds its handle: the `text` instance, or a custom element drawing labels. The owner's `NodeId` is used only in errors and warnings. This replaces the cache keyed by `NodeId` and `retain_sources`, so a label that is measured only in some frames keeps its cache. - One engine per application, owned by the host next to layout, because fonts are shared. Layout lends it to measuring through the measure context, the absorbing hooks lend it to collecting, and the scene lends it to drawing. - Every query is a pure function of the paragraph's content, the width, and the scale. The engine's caches are its own business behind `&mut self`, so they can never disagree with Taffy's. - Registering a font bumps the generation. A paragraph shaped under an older generation shapes everything again and drops its band images when next used. ### Segments and runs **Proposed.** - The engine's input is content, not tree nodes: segments of owned text, each with runs. A run has a byte range, a `ShapingStyle` (family, size, weight, line height, wrap), and a `PaintStyle` (color). Today's `ComputedTextStyle` splits into these two; see Text properties by stage. - A segment ends after each line feed, U+000A, which stays in the segment it ends. Each segment then breaks and measures as its slice did inside one Parley layout, which leaves out of the height the empty line after a final line feed. Text that ends with a line feed ends with an empty segment that takes no space, as today. Empty text keeps today's size. - The other breaks Parley forces (a lone carriage return, U+2028, U+2029) end a segment too, since Parley cannot lay out a combining mark clustered onto one inside its layout. U+0085 breaks no line in Parley and stays inside a segment. - A segment's hash covers its text and its runs' ranges and shaping styles, but not their colors. An equal hash is compared in full before reuse, as `TextFingerprint` is today. - One run per text node, not coalesced, so one node's color can change alone. A difference in brush alone does not split shaping in Parley 0.11: `shape_text` starts a new shaping item only on size, locale, variations, features, spacing, bidi level, or script. Shaping stays as it is with today's coalesced runs. - `MAX_STYLED_RUNS` applies per segment, since Parley indexes its style table with a `u16`. A paragraph is no longer limited to 65,534 runs in total. ### Shaping and breaking a segment **Proposed.** - A segment shapes through Parley's `StyleRunBuilder` (`LayoutContext::style_run_builder`): one `TextStyle` per run, whose brush is the run's index in the segment, then the run ranges. Parley skips its own range splitting, and `build_into` reuses the segment's allocations when it shapes again. - A segment keeps one Parley layout and breaks it in place. `break_lines` computes lines again from the shaped clusters without changing them, so the unbroken copy that today's engine clones for every width is not needed. The segment remembers the width it is broken at, its content widths, and its size under up to four constraints, as `MAX_MEASUREMENTS` does today, so Taffy's repeated measuring breaks nothing again. - Constraints resolve at the paragraph. `MaxContent` breaks every segment unbounded. `MinContent` breaks every segment at the paragraph's min-content width, the largest of its segments'. `Definite(width)` breaks every segment at `width`. The paragraph's width is the largest segment width, its height the sum of segment heights, and its first baseline the first segment's. - The fallback to replacement boxes is decided for the whole paragraph, as one layout decides it: only when no segment positions a glyph, and then in every segment. Deciding per segment made a line of only spaces in a paragraph with no usable font collapse to no height, and with any font registered a missing character still gets a fallback glyph, so per segment never helped. Metric validation and the run limit apply per segment. ### The same result as one layout **Proposed.** A test proves segments equivalent to one layout instead of assuming it. It shapes a corpus both as one Parley layout and as segments, and compares width, height, first baseline, line count, and every glyph position moved by its segment's top. The corpus covers several lines, blank lines, a final line feed, empty text, CJK, mixed sizes and line heights, `nowrap`, and min-content, max-content, and definite widths. Two differences are deliberate and stay out of the corpus: - **Bidi base direction per segment.** Parley resolves bidi over its whole text with one base level from the first strong character (`analysis/mod.rs` passes no base level). A segment takes its own, as UAX #9 does for text divided by paragraph separators (rules P1 to P3), so an Arabic line below an English first line starts at the right. A later `direction` property needs Parley to accept a base level, which joins the safe-to-break boundaries as something to ask Parley for. - **Line height per segment.** Parley 0.11 resolves one line height for a whole layout, so a single layout of mixed line heights gives every line the last run's. A segment resolves its own, so each line feed gets the line height of the text around it, as the box model implies and `font-size` already does. Confirmed by probe: `tight`(×1)`\n``loose`(×2.5) is `[40, 40]` as one layout and `[16, 40]` as segments. ### Lines **Proposed.** After the segments break at the paint width, the paragraph keeps one record per visual line: its segment and index there, its top in the paragraph, its height, the runs it draws, and a hash of what it draws. The hash covers glyph ids and their positions relative to the line, each glyph run's font, size, variation coordinates, synthesis, and run index, and the line's metrics. Hashing walks the glyphs once, far cheaper than shaping them. Lines of segments that did not break again keep their hashes and only move. Tops add up in `f64`, as Parley's do. ### Bands **Proposed.** - **Boundaries depend on content.** A band is a run of whole lines. A line whose hash is a multiple of `ANCHOR_INTERVAL` starts a new band once the current one is at least `MIN_BAND` tall, and a line that would take a band past `MAX_BAND` starts a new one regardless. Since anchors depend on what lines draw and not where they are, an edit that adds or removes lines changes only the bands around it: the bands after it settle on the same anchors, keep their lines, and only move. Cutting bands greedily by height would move every boundary after the edit instead. - **Keys.** A band's key hashes its lines' hashes, their tops within the band, the colors of the runs they draw, and the scale. - **Drawing.** A band draws like today's paragraph image, with `vello_cpu`. Its image extends past its lines by `LAYER_IMAGE_PADDING` horizontally. Vertically it covers the ink its lines can reach, each line recording how far its glyphs' font bounding boxes at their baselines, faux bold's expansion, and its replacement boxes with their strokes reach above and below the line box, and the padding beyond that, so a glyph taller than a tight `line-height` survives the band's edges. Band edges snap to the window's device pixels: the layer tree passes `draw_bands` where the content origin falls within a device pixel, from its unscrolled window position, so each image lands on whole pixels, glyphs are drawn at that sub-pixel offset and stay where layout put them, neighboring bands meet without seams, and scrolling by whole device pixels draws nothing again. - **Width.** A band wider than `MAX_COLUMN` device pixels splits into columns of that width, each drawn only when visible. A `nowrap` line in a horizontally scrolling container then draws what is in view. No image nears the 65,535-pixel limit, so a long paragraph no longer fails the frame. Only the columns near the view are made, so a line of any width draws, at a cost that does not grow with its length. - **Visibility.** Only bands and columns that intersect the visible rectangle are drawn: the clip of the scroll containers around the paragraph, intersected with the viewport and moved into the paragraph's coordinates. - **Reuse.** The paragraph keeps the images of the bands it drew, by key. A band whose key did not change returns the same `Rc`, and the reconciler, which identifies images by `Rc`, then creates and uploads nothing. Images of bands more than a viewport away from the visible rectangle are dropped. - **Layers.** The paragraph's layer, `key(source, TEXT)`, becomes a container at the content origin with one sublayer per drawn band. Band layers use the parts from `TEXT_BAND = 1 << 30` up, by the band's slot times `COLUMNS_PER_BAND` (1,024) plus the column's index modulo that, since the columns in one view are far fewer, clear of thumbs and scroll groups and below an instance's `CONTENT` parts, which phase 1 put at `1 << 31`. A band's slot comes from what it draws apart from color, its lines' shape hashes and their tops within the band, so a band that only moves keeps its layers; two bands with the same content take the next free slot in order. Moving or scrolling the paragraph changes one frame. Starting values, tuned by the bench: `MAX_BAND` 512 and `MIN_BAND` 64 logical pixels, `ANCHOR_INTERVAL` 8, `MAX_COLUMN` 4,096 device pixels. ### Paint-time color **Proposed.** - Shaping uses the run index as the brush. Drawing a band looks up the run's `PaintStyle`, and so do replacement boxes. - `ParagraphEditor::set_run_paint` changes no segment hash, breaks nothing, and gives new keys only to the bands whose lines draw that run. - Step 1 leaves `color` at `Reflow`, because today's pipeline collects again only on a layout change. The new collection then shapes nothing, since segment hashes leave color out. Step 2c makes `color` `Repaint`. ### Errors **Proposed.** A paragraph that fails to shape or draw draws nothing for that frame and is reported once, naming its owner, instead of failing the frame. With bands removing the size limit, this answers the first item under To decide in `docs/todo.md`. ## The `text` element ### Definition and instance **Proposed.** - The definition is a leaf that absorbs text nodes and `text` elements, as `rules.md` allows today. - Only an outermost `text` holds a `ParagraphHandle`. One moved into another `text` drops its handle when it learns of the move, and one moved out creates its handle when it next collects. - `measure` asks the engine, lent by the measure context, for the paragraph's size under the constraint, and returns its first baseline. - `paint` emits text as built-in data, `{ paragraph, origin, width }`, and the scene asks the engine for the bands. The width is the content width layout gave the leaf; the engine breaks lines again lazily if it differs from the last width measured, so no final resolution pass is needed. - Removed: `LayoutRole::Paragraph`, `TextMeasurer`, `TextMeasureRequest`, `LayoutEngine`'s type parameter, `ComputedLayout::final_paragraphs` and the pass that resolves them, `text_owner` (replaced by absorbing ownership), `CollectedParagraph`, `ParagraphInput`, `TextFingerprint`, and `TextEngine`. **Built** (text step 2a, `ui/text/element.rs`): - `TextInstance` is the `text` definition's instance. `collect` walks the `AbsorbedSubtree` into a paragraph input, with each nested `text`'s style inherited, creates its `ParagraphHandle` on first use, and updates it, so the engine diffs the segments by key. It returns `Clean` when the input is unchanged and `Reflow` otherwise; collecting only what changed is step 2b. - `owner_changed` drops the handle when the element is absorbed into another `text`; released, it collects a new one. A new absorbing element is marked for collecting when it is created, so an empty `text` holds a paragraph too. - `measure` asks the engine for the size under the known width, else the available width. `paint` calls `PaintList::text`, which shapes the paragraph at the content width layout gave and draws it in bands, so no final resolution pass is needed. - A paragraph that cannot be collected, measured, or painted prints a warning and shows nothing, instead of failing layout. - Removed: `LayoutRole::Paragraph`, `TextMeasurer`, `TextMeasureRequest`, `TextMeasurement`, `LayoutEngine`'s type parameter, `ComputedLayout::final_paragraphs` and the pass that resolves them, `CollectedParagraph`, `collect_paragraph`, and `TextEngine`, with the errors only they raised. - Not as proposed: `LayoutEngine` owns the paragraph engine, which the host reaches through it to lend to collecting and painting, rather than the host owning it beside layout. `ParagraphInput` and `TextFingerprint` stay as the engine's input, since no editor API replaces `update` yet. - The engine shapes a paragraph again from its kept input when fonts changed since it was shaped, because its owner updates it only when its content changes. ### Collecting only what changed **Proposed.** - The instance keeps its absorbed subtree flattened in pre-order. Each entry holds the node, its revisions when collected, its computed text style if it is an element, and, for a text node, the segment and byte offset where it starts. - Collecting compares each entry's revisions with the tree's, which reads no text, and acts on what changed: - **`content` of a text node.** Collect again from the start of the segment where the node starts to the first line feed at or after its end. Segments after that start in later nodes, so their positions hold. - **`style.layout` of an element.** Resolve styles again over its subtree, which is a contiguous range of entries, and collect again the segments its text nodes touch. - **`style.paint` only.** Resolve colors again over its subtree and set the paint of its runs. No segment is collected. - **`structure` of any entry.** Collect the whole subtree again, then diff the new segments against the old by hash: the common prefix and suffix first, then the middle by hash, so unchanged segments keep their shaping. Collecting is cheap, 0.11 ms at 100k characters; shaping is what is saved. - Collecting returns `Reflow` when a segment changed, `Repaint` when only paint did, and `Clean` otherwise. - The revisions already say what changed, so this needs no `subtree_changed` classification. If phase 1 routes changes per node, the instance can skip the comparison, which stays as the fallback. **Built** (text step 2b, `ui/text/collect.rs`): - `CollectedSubtree` keeps the absorbed nodes flattened in tree order, each with its revisions when collected, the element it is inside, and, for an element, its resolved style and the end of its range. - Collecting walks the subtree again only when the owner's or an entry's `structure` revision changed. Otherwise it compares revisions: an element whose `style` changed resolves its style and those of the elements in its range again, and nothing changed at all returns `Clean` without reading text or touching the engine. - Each text node is its own run, as Segments and runs proposes, so one node's color can change without splitting a run another node shares. Like text nodes side by side then count one run each toward `MAX_STYLED_RUNS` per segment, where they used to count as one. - Collecting returns `Repaint` when the new paragraph has the same text in runs that shape alike, `Reflow` when it does not, and `Clean` when it is equal. - Not as proposed: when any node changed, the instance reads every text node again and hands the engine a whole `ParagraphInput`, which splits it into segments and diffs them by key, so only changed segments shape again. Collecting from the start of the touched segment only, and the byte offsets that needs, wait for an engine API that takes a range of segments. The owner's style is compared by value rather than by revision, since the owner's revisions also record what its own collecting returns. `Repaint` is decided by comparing the paragraphs rather than by `style.paint` revisions, so it holds while `color` still bumps `style.layout`, until step 2c. ### Text properties by stage **Proposed.** One table gives each text property its stage: shaping (`font-family`, `font-size`, `font-weight`, `line-height`, `text-wrap`) or paint (`color`). `TextStyle::set_property` takes its dirty level from the table, so `color` becomes `Repaint`, and the same table decides whether a value goes into `ShapingStyle` or `PaintStyle`. A property added later picks its stage there and nowhere else. **Built** (text step 2c, `ui_tree/styles/text.rs`): - `TEXT_PROPERTIES` gives each text property a `TextStage`: `Shaping` for `font-family`, `font-size`, `font-weight`, `line-height`, and `text-wrap`, `Paint` for `color`. `TextStyle::set_property` and `remove_property` take their dirty level from it, so `color` is `Repaint`. - A `color` change still reaches the outermost `text`, which phase 1 marks for collecting before every frame, including one that skips layout. It collects the change as `Repaint`, and the frame draws the new color without laying out again. - When an update has the same text in runs that shape alike, the engine keeps every segment and size and recolors its kept shaping. The broken lines are shared, and line records already made keep their shape hashes and hash only their colors again. So a color change breaks nothing, and only the bands whose lines draw the run draw again, as Paint-time color proposes. - Not as proposed: `ComputedTextStyle` is not split into `ShapingStyle` and `PaintStyle`. Which of its fields shape is listed in `shaping_equal`, and a test checks that each property changes shaping exactly when its stage is `Shaping`. There is no `ParagraphEditor::set_run_paint`; `update` recolors when the new input shapes like the last. ## What phase 1 must provide Step 2 depends on phase 1, step 4 (Instances). Step 1 depends on nothing in phase 1. 1. **A measure context.** `measure(&self, cx: &mut MeasureContext<'_>, input)`, lending the paragraph engine. The trait sketch in `custom-elements.md` has `measure(&self, input)`, which cannot reach the engine. 2. **Absorbing hooks.** `collect(&mut self, cx, subtree) -> Dirty`, with the engine lent, and ownership of absorbed nodes replacing `text_owner`. 3. **Changes flow upward.** Recording a change to an absorbed node marks its outermost absorbing ancestor for collecting, which walks only its ancestors. Before every frame, including a paint-only frame that skips layout, the host collects the marked instances. `Reflow` bumps the element's layout revision, as `request_layout` does; `Repaint` only draws again. Without this, a paint-only change under a `text` never reaches it, which is why `color` is `Reflow` today. 4. **Painting built-in text.** The paint hook can emit text data that names a paragraph, and the scene lends the engine to draw it. 5. **Lifetime.** Dropping an instance drops its handle. **Built.** All five: `MeasureContext::measure_paragraph` (1); `collect`, tree-kept owners (#132), and `InstanceGive::state_with_paragraphs` while collecting (2); marking and `UITree::collect_marked` before every frame (#133) (3); `PaintList::text`, which the scene draws as a `text` element's paragraph (4); and a `ParagraphHandle` an instance keeps (5). Items 1, 4, and 5 and the engine lent to `collect` landed in #134, crate-private; #183 made them public, narrowed to a handle, and moved `text` onto them in `features/text`. ## Steps **Built**, one stacked pull request per step. Each keeps the existing behavior tests passing; unit tests of internals that a step replaces are ported to the new API. - **1a. The paragraph engine and segments.** `ParagraphEngine`, handles, segments with hashes, shaping and breaking per segment, run-index brushes. It replaces `TextEngine` behind today's pipeline: an adapter implements `TextMeasurer`, keeps one handle per paragraph node until step 2 gives paragraphs real owners, splits today's `ParagraphInput` into segments, and diffs them by hash, so a change shapes only the segments it touched. Paint still draws one image per paragraph, now from its segments. Tests: the equivalence corpus, and counts showing that an edit shapes one segment and that a color change or a resize shapes none. `benches/support/text_hooks.rs` follows the new cache. - **1b. Lines and bands.** Line records and hashes, bands with content boundaries and keys, the container layer, drawing only visible bands and columns, and errors that no longer fail the frame. Scene tests that expect one image under `key(label, TEXT)` change to expect bands under it. New tests on the memory surface: a paragraph taller than the image limit presents; an edit keeps unchanged band images by `Rc`; a scrolled paragraph presents only its visible bands; a color change draws again only the bands holding that run. The bench draws through the scene in an 800 × 600 viewport and adds a color change, a line appended to a long log, and a scroll by one viewport. `text-engine.md` and `todo.md` record the results. - **2a. The `text` definition and instance** (after phase 1, step 4). Measuring and painting through the instance, collecting the whole subtree through the absorbing hook with the diff by hash. Removes the adapter and the pieces listed under Definition and instance. - **2b. Collecting only what changed.** The flattened subtree and the comparison of revisions. - **2c. Text properties by stage.** The stage table and `color` at `Repaint`, plus changes flowing upward if phase 1 did not bring them. ## Risks - **Memory per segment.** A Parley layout holds about a dozen vectors, so a paragraph of many short lines pays several hundred bytes per line on top of its glyphs. One layout per segment instead of today's unbroken layout plus a broken clone offsets part of it. The bench's heap attribution measures it in step 1a. - **Hashing lines on resize.** A width change hashes every line again. The resize case in the bench covers it. - **Seams and blur between bands.** Snapped origins should prevent them; step 1b includes screenshots at scale 2 on macOS. - **The bidi change** is visible in multi-line text that mixes directions. ## Open questions - Whether band images are kept per paragraph, near the visible rectangle, or under one pixel budget for the whole engine. - Whether the paragraph engine becomes extension API. Owner handles make that possible without exposing tree nodes; see `docs/plan/extension-api.md`. - Whether text stays images drawn in bands or becomes a layer data kind of its own; bands keep it an image for now. See `docs/plan/text-engine.md`.