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.
zgui-layout turns computed styles into boxes, sizes and positions them with the Cephal layout
engine, and produces fragments: the geometry that painting, hit testing and accessibility read.
It runs in two steps of the frame, after the
restyle and before paint:
| Step | Work |
|---|---|
f.boxes | Patch the box tree for the elements whose boxes changed. |
f.layout | Measure and arrange boxes, then compose fragments, collect damage and update the hit index. |
The sections follow that order: the box tree and how it is patched, the layout pass and its caches, then fragments and what is derived from them. The user-facing model is in Layout.
Elements, boxes and fragments
CSS separates three levels, and the crate keeps them separate.
| Level | Crate and module | Key | Relationship |
|---|---|---|---|
| Element | zgui-dom | NodeKey | what the author wrote |
| Box | zgui-layout::boxtree | BoxKey | one element generates zero, one or several boxes |
| Fragment | zgui-layout::fragment | FragKey | one box produces one fragment per line, column or page |
BoxKey is declared in zgui-dom (zgui_dom::side::BoxKey) and re-exported here, because the
document records which boxes each element generated. There is one box identity in the workspace.
Every stage after layout reads fragments, never the layout engine's own results. Painting, hit testing and accessible geometry all read the fragment tree, so none of them depends on the layout engine's types.
The box tree
A box is a BoxNode (crates/zgui-layout/src/node/box_node.rs):
| Field | Type | Meaning |
|---|---|---|
source | Option<NodeKey> | the element it came from; None for an anonymous box |
pseudo | Option<PseudoKind> | set when it realises ::before or ::after |
parent | Option<BoxKey> | the layout parent |
children | Vec<BoxKey> | children in layout order |
paint_children | Vec<BoxKey> | children in document order |
fc | FormattingContext | how it lays out its own children |
parent_fc | FormattingContext | how its parent lays it out |
style | ComputedStyle | the cascade result, shared with the element |
kind | BoxKind | Element, AnonymousBlock, AnonymousInlineRoot, TextRun or Marker |
block_level | bool | whether it participates as block-level |
text | Option<Box<str>> | the characters of a text run |
painted | PaintedContent | Box, Vector, Replaced or Custom |
Rare per-box data (replaced-content metadata, custom-element references) lives in sparse
side columns paged in blocks of 64 boxes, so an ordinary box pays only for the painted tag.
The two child lists differ:
children(layout order) hasorderapplied,display: contentsflattened, and out-of-flow boxes moved onto the box that positions them.paint_childrenkeeps document order, for accessible geometry and anything else that follows the document.
FormattingContext has ten values. How Cephal sees each one:
| Value | Cephal treatment |
|---|---|
Block, Table, MultiColumn | block layout (tables and multi-column are laid out as blocks) |
Flex, Grid | the flex and grid algorithms |
Atomic | the algorithm of its inner display (flex, grid or flow root) |
Inline, Replaced, Custom | leaves; zgui supplies the size |
None | not laid out |
Boxes generated per element
The builder settles every case while it builds the tree, so the layout walk never has to filter
(crates/zgui-layout/src/boxtree/).
| Case | Boxes |
|---|---|
display: none | none |
display: contents | none; its children are spliced into the parent's list (boxtree/contents.rs) |
| ordinary element | one |
element with ::before and ::after | three, plus one text run per generated string |
| list item | one, plus a marker box |
| text node | one text run; an empty text node generates none |
classify (boxtree/classify.rs) reads display and position once and returns a
Classification: participation, formatting context, whether the box is out of flow, whether it is
positioned, and whether it is a list item.
Anonymous boxes
BoxKind::is_anonymous covers AnonymousBlock, AnonymousInlineRoot, TextRun and Marker.
The builder creates the last three. AnonymousBlock (the wrapper for block-level children mixed
with inline-level ones) is declared but not yet constructed.
AnonymousInlineRoot is the common one. wrap_inline_runs (boxtree/anonymous.rs) wraps each
maximal run of in-flow inline-level children of a block container in one anonymous box, which
establishes the inline formatting context that breaks the run into lines.
- A container whose children are all block-level is returned unchanged and allocates nothing.
- An out-of-flow child ends the current run. It keeps its place in paint order but is left out of the layout list.
- A box that already establishes an inline formatting context is not wrapped again.
The wrapper's style is zgui_css::inherited_style(parent): the parent's inherited properties, and
initial values for everything else. Using the parent's full style would paint its border,
background and padding twice. Inherited values are shared, not copied, because text brush slots are
keyed by the identity of the cascade result a colour came from (see
MeasureContent).
Container rules
Builder::link (boxtree/build.rs) applies three container rules when it links children:
- Blockification. Children of a flex or grid container become block-level. A text run that
becomes a flex item stays
FormattingContext::Inline, so its characters still get line layout. order. Applied once, as a stable sort of the layout child list (boxtree/order.rs). The paint list stays in document order. A list already in order is not sorted.- Out-of-flow re-parenting. Cephal positions an absolutely positioned child against its direct
parent; CSS uses the nearest positioned ancestor. So an out-of-flow box is removed from the
layout list of the box it was written in and appended to the layout list of its containing block
(
boxtree/absolute.rs). When no ancestor is positioned, the containing block is the root box, which acts as the initial containing block. This holds for full builds and for incremental splices. Re-parenting runs once after the whole tree is built, because a containing block's child list is not final until its subtree is.
establishes_containing_block consults only position. Transforms, filters and will-change,
which also create a containing block for fixed descendants in CSS, are not applied by the box tree.
Updating the box tree
Most frames change a few elements. Rebuilding the whole box tree gives every box a new key, which
defeats fragment reuse, recorded paintings, hit-index entries and damage tracking: every fragment
compares as changed and the damage grows to the whole window. So the f.boxes step patches the
existing tree instead. Each full build is counted in Counter::BoxTreeBuilds. The first build
counts too; after that, the counter should rarely move.
Collecting owed rebuilds
The REBUILD_BOX and CHILDREN marks propagate to the root, so the root can only say whether a
rebuild is owed. The box-tree stage collects which elements owe one (boxtree/build.rs):
pub const REBUILDS: Dirty = Dirty::REBUILD_BOX.union(Dirty::CHILDREN);
pub struct Owed {
pub rebuilt: Vec<NodeIndex>, // elements whose own boxes changed
pub children: Vec<NodeIndex>, // elements that gained or lost a child
}
pub fn retire(document: &mut Document, root: NodeIndex) -> OwedThe two lists stay separate because they are serviced at different elements. An element whose own boxes changed is serviced by rebuilding its container, since wrapping, ordering and blockification are the container's decisions. An element whose child list changed already is the container.
Splice, rewrite text, or rebuild
build_boxes in crates/zgui-runtime/src/window/frame.rs tries these in order:
- Splice.
patch::rebuild(store, document, &owed) -> Option<Rebuilt>rebuilds the boxes of each target container and puts them where the old ones were. For a container that gained or lost children, it first tries to build only the children that changed and keep the rest. - Rewrite text.
patch::retext(store, document, root) -> Retextwrites new characters into the text runs that already exist and returnsRetext::Patched(n)orRetext::Rebuild. It runs even after a splice, because the same frame may have changed a label elsewhere. - Re-measure custom elements.
patch::custom::relayoutmarks custom elements that asked to be measured again. - Rebuild.
boxtree::build(store, document)replaces every box. It runs only when there is no root yet, a splice is refused, orretextreturnsRebuild.
When a splice is refused
Target selection (boxtree/patch/subtree/target.rs):
- Containers nested inside other targets are dropped; rebuilding the outer one covers them.
- More than 64 outermost containers (
MOST) means the change is not local: a full build is cheaper. - A
display: contentscontainer has no box of its own to replace, so the nearest ancestor that generates a box is rebuilt in its place. A container inside adisplay: nonesubtree owes nothing and is skipped. - A change whose container is not an element with a box (the root element, for example) is refused.
Each splice must also be confined (boxtree/patch/subtree/confine.rs): the boxes in the old
subtree are exactly the boxes its own elements generate, and nothing outside it is laid out from
inside it. Then takes_the_same_part compares the new root box with the old one:
| Check | Why |
|---|---|
| Same list | An out-of-flow box must hang under the same containing block; an in-flow box under the box of its element's parent. |
| Same participation | A box that switches between block-level and inline-level changes how its siblings are wrapped, and the siblings are not being rebuilt. |
| Same kind | A changed formatting context or box kind changes how the container's other children were sized. |
The new subtree is built first and discarded if it fails these checks; predicting the result would duplicate the builder's rules.
The largest case still refused is a box whose layout parent and paint parent differ, such as an out-of-flow box positioned against an ancestor further up. Both lists cannot be repaired from the replaced box, so it falls back to a full build.
Rewriting text in place
A text run's characters are copied into its box when the box is built. retext
(boxtree/patch/text.rs) updates them without a rebuild. A rewrite must:
- Drop the flattened inline content held for every ancestor. The cached flattened form is validated against the sequence of boxes, and a box rewritten in place is the same box, so a stale form would pass that check and draw the old text.
- Mark the box dirty so its layout and its ancestors' layouts are recomputed.
- Refuse changes it cannot express. Text appearing in an empty text node or disappearing
entirely changes which boxes exist, so
retextreturnsRebuild.
An element whose font changed (face, size, spacing, text-transform) keeps its boxes. retext
collects these elements and passes them to text::reshape::scope, which drops the flattened forms,
resolved lines, baselines and cached sizes computed from the old shaping.
Dirty::RESHAPE is not retired here. The fragment pass reads it to repaint a line whose glyphs
changed without its rectangle moving.
Layout with Cephal
Cephal is a retained, incremental CSS layout engine (block,
flexbox, grid, floats, margin collapse, absolute positioning) published on crates.io. zgui uses it
against its own box tree. The root Cargo.toml enables only the three algorithms the box tree
dispatches to:
cephal = { version = "0.1.0", default-features = false, features = [
"block",
"flex",
"grid",
] }Cephal can own a tree itself (cephal::Tree), but zgui uses the host-tree mode: LayoutTree<'a, C>
implements Cephal's LayoutTree, CacheAccess and schedule::Incremental traits
(crates/zgui-layout/src/tree/engine.rs) and drives cephal::compute directly.
| Cephal owns | zgui owns |
|---|---|
| the block, flex and grid algorithms, floats, margin collapse, absolute positioning | the box tree, box identities and both child lists |
the deepest-first scheduler and the per-node NodeCache | the persistent LayoutStore and invalidation marks |
LayoutInput, LayoutOutput and the engine Style | lowering computed CSS to an engine Style |
| inline layout, replaced content and custom elements | |
| device-pixel snapping, fragments, the hit index and paint order |
Style lowering. Each cascade result is lowered once per device scale into a LayoutStyle
(style/lowered.rs). Cascade results whose layout-relevant inputs are equal share one lowering, so
a paint-only change reuses it (Counter::StylesLoweredFromCache). The store interns the resulting
Cephal Style per box variant, and Cephal borrows it.
The layout pass
impl<'a, C: MeasureContent> LayoutTree<'a, C> {
pub fn new(store: &'a mut LayoutStore, content: &'a mut C, device: DeviceStyle) -> Self;
pub fn with_custom(self, custom: &'a dyn CustomLayoutSource) -> Self;
pub fn with_parallel(self, pool: &'a LayoutPool) -> Self;
pub fn layout_root(&mut self, viewport: cephal::Size<f32>) -> bool; // always runs
pub fn relayout_root(&mut self, viewport: cephal::Size<f32>) -> gate::Relayout;
pub fn layout_viewport(&mut self, width: f32, height: f32) -> bool;
}The runtime calls relayout_root from lay_out in crates/zgui-runtime/src/window/frame.rs, with
the surface size in device pixels. All absolute lengths in lowered styles are already in device
pixels.
relayout_root first asks gate::stands (tree/gate.rs). The previous result stands when the
viewport is unchanged, the scheduler queue is empty and the root is not dirty. It then returns
Relayout::Held and bumps Counter::LayoutsHeld. Otherwise layout_root runs, bumps
Counter::LayoutReachedRoot, and relayout_root returns Relayout::Ran:
- Intrinsic pre-pass. Measures boxes sized with
min-content,max-contentorfit-contentthat hold no intrinsic answer yet. The boxes come from a maintained roster, deepest first, so a document without content keywords pays no walk. - Scheduler. Cephal's
Scheduler::runrecomputes the queued boxes (see Incremental relayout). - Root layout.
cephal::compute::compute_root_layoutlays out from the root. Cached answers make untouched subtrees cost one lookup. - Scrollbar gutters. If
scroll_region::auto::revisechanges anoverflow: autogutter, the pass repeats, up toscroll_region::auto::MAX_PASSES(2) times. Only boxes with an undecidedautooverflow are checked, also from a roster.
The pass does not round. Rounding and fragment composition both need each box's cumulative absolute origin, so the fragment pass does both in one walk.
Container queries need a second fixed point: styles inside a container depend on its size, and its
size depends on those styles. container_query::run iterates until the sizes settle, up to
container_query::MAX_PASSES (3). A document that has not settled by then has contradictory
queries, and the third answer is kept.
Incremental relayout
Cephal's scheduler is deepest-first and stops at unchanged answers (cephal::schedule):
pub fn mark_dirty(store: &mut LayoutStore, box_: BoxKey) -> u32
pub fn is_dirty(store: &LayoutStore, box_: BoxKey) -> bool
pub fn mark_all_dirty(store: &mut LayoutStore) -> u32mark_dirty(tree/dirty.rs) clears the box's cached answers and queues the box and its parent with the scheduler. It also sets aCHAINbit on every ancestor, so walks that start at the root can still find the change. The chain bit is cleared after the pass.- The scheduler pops queued boxes deepest first. For each box it re-asks every question the box's cache held, with the same inputs, and compares the new answers with the old ones. If the parent could observe a difference, the parent is queued. If not, propagation stops there.
- If the parent is already dirty, the child's cache is simply cleared: the parent will re-run anyway.
- A box with nothing cached (never laid out, hidden, or sized only through its parent, like a text run) always queues its parent, because only the parent can tell whether it changed.
- Answers computed inside a shared block formatting context depend on siblings (margin collapsing, floats). They are not replayed in isolation; the parent recomputes them.
mark_all_dirty is used when the scale factor changes. Every length is in device pixels, so
every answer is stale. It clears every cache, intrinsic answer, baseline and resolved inline line,
forgets the viewport the results were computed for, and counts the boxes in
Counter::BoxesMarkedAllDirty.
Measurement caches
Each box has a Cephal NodeCache (cephal-0.1.0/src/tree/cache/mod.rs):
| Slot | Capacity | Used for |
|---|---|---|
| final layout | 1 | the PerformLayout answer |
| size probes | 3 inline + 8 spilled = 11 | ComputeSize answers |
- One final slot. Performing layout writes positions into descendants. Keeping an older full answer could return the right outer size while the subtree is still placed for another question.
- Eleven size slots. Grid track sizing asks one item several min- and max-content questions. The 8 spill entries are allocated only when needed. When all are full, the least recently used entry is evicted.
- Exact keys.
CacheKeypacks known dimensions, available space, parent size, requested axis, sizing mode, margin-collapse state and block-context identity. Floats are compared by their bits, soNaN,+0and-0stay distinct. - Normalised questions. Before lookup,
cephal::compute::normalizedrops the parent size on an axis the style never resolves against, and replaces the available space with a definite known size. Equivalent questions then share one entry. - Complete answers. A hit returns a whole
LayoutOutput: size, overflow and baselines.
BoxLayout::forget_layout clears both cache levels, the intrinsic answers and the atomic-inline
memo together. Clearing one without the others would let a pre-invalidation answer be served.
Counter::SizesHeld and Counter::SizesMeasured count size-probe hits and misses.
Intrinsic sizes
Boxes that use fit-content, min-content or max-content keep their min- and max-content answer
per axis on the box (BoxLayout::intrinsic). An intrinsic probe has no known dimensions, no parent
size and a fixed min/max-content constraint, so it does not depend on the containing block and
stays valid across frames and viewport changes. A settled document takes no intrinsic measurements.
The pre-pass clears only the two cache levels immediately after a probe (forget_cached_sizes).
Those entries were measured while the keyword was treated as auto and must not answer the real
layout. Any other invalidation (content, style, scale, gutter) clears the intrinsic answer too.
MeasureContent
Text, replaced content and custom elements are leaves to Cephal. Atomic inlines are laid out inside
the crate. The rest is answered by the measurer the caller passes in, which keeps the shaping
engine and image decoding out of zgui-layout and lets layout tests run without fonts
(crates/zgui-layout/src/measure.rs):
pub trait MeasureContent: ShapedClusters {
fn measure(&mut self, request: MeasureRequest<'_>) -> Measured;
fn shape(&mut self, content: &ParagraphContent<'_>) -> ShapedSummary;
fn shape_keyed(&mut self, key: ParagraphKey, content: &ParagraphContent<'_>) -> ShapedSummary; // defaulted
fn break_lines(&mut self, key: ParagraphKey, request: &BreakRequest<'_>) -> BrokenParagraph;
fn strut(&mut self, style: &TextStyle) -> StrutMetrics;
fn paint_slot(&mut self, paint: &TextPaint) -> Brush;
fn fork_measurer(&mut self, owned: &[ParagraphKey]) -> Option<Box<dyn WorkerMeasure>>; // defaulted
fn absorb_measurer(&mut self, worker: Box<dyn WorkerMeasure>); // defaulted
}Shaping and line breaking are separate calls. Shaping is expensive; breaking at a given width
is cheap. Flex and grid ask a paragraph for its size at many widths, so shape runs once per
distinct content and break_lines once per width. ShapedSummary carries the paragraph key and
its ContentWidths, which answer inline-axis intrinsic probes without breaking lines at all. The
text engine describes what happens behind these calls.
ShapedClusters is a required supertrait with no default. text-overflow needs cluster
boundaries to place the ellipsis, and a wrapper that silently inherited an empty answer would cut
every label at its start.
A MeasureRequest carries the box, its style, the dimensions layout has already fixed (known),
the available space with the box's own insets removed, the content's natural size if known, the
device scale, and final_pass (whether the answer is kept or is one of several probes).
Measured carries size, first_baseline and last_baseline. Both baselines are needed because
an inline-block aligns on its last line box.
paint_slot claims a brush slot keyed by the identity of the cascade result that the colour
came from, not by the colour. The slot survives a theme change that rewrites its colour, and two
runs that happen to compute the same colour are not recoloured together.
| Implementation | What it measures |
|---|---|
NoContent | Every box is empty. A test control that forks trivially, so text-free tests exercise parallel batches. |
NaturalSize | Replaced content at natural × scale. |
Paragraphs<S, R = NaturalSize> | A shaper, the paragraph cache and the brush table, delegating replaced content to R (text/paragraphs.rs). |
Box<dyn TextEngine> | The runtime's measurer (crates/zgui-runtime/src/text.rs). |
Parallel layout
An application owns one LayoutPool (tree/parallel.rs), shared by its windows. Windows still lay
out one at a time on the frame thread; the pool splits independent child subtrees inside one pass.
| Setting | Effect |
|---|---|
zgui::app().with_layout_threads(n) | requested pool width |
ZGUI_LAYOUT_THREADS=n | overrides the requested width |
width 0 or 1 | no pool |
| more than 8 | clamped to 8 (MAX_LAYOUT_THREADS) |
ZGUI_LAYOUT_BATCHES=0 | keeps the pool but runs every batch serially, for A/B runs |
Cephal hands the host each batch of independent child requests; run_batch
(tree/executor.rs) decides how to run it:
- It distributes only when the batch has at least 8 cold nodes (
MIN_COLD_NODES; nodes the cache cannot answer) and the planned subtrees hold at least 256 boxes (MIN_BATCH_BOXES). Steady frames are mostly cache hits, so they stay serial. - Batches nested inside a worker run serially on that worker.
- A subtree that contains a custom element is pinned to the frame thread, because the custom
layout source has no
Syncbound. The other subtrees in the batch still go to workers. A store with no custom boxes skips this check. - Before the workers start, the executor splits the store into disjoint mutable views. Each worker
writes its subtree's results in place. Nothing is copied in or committed out; results are
reassembled in request order. Distributed batches are counted in
Counter::LayoutBatchesDistributed.
Each worker needs its own text measurer. MeasureContent::fork_measurer(owned) returns a Send
WorkerMeasure that takes ownership of the shaped paragraphs the worker will break, and
absorb_measurer(worker) takes the results back after the batch. The default fork_measurer
returns None, which keeps that measurer's batches serial. A fork must return exactly the
measurements its producer would.
A paragraph can be probed on one worker and kept by the final pass on another measurer. The inline
layout then re-shapes it on the measurer that breaks it, which is a cache lookup when that measurer
already holds it (inline/measure.rs).
Shaping itself happens inside the serial layout recursion. When a pool exists, the runtime first shapes the dirty plain-text paragraphs before layout asks for them, spreading the work across the pool when there are enough misses; see Pre-shaping on workers.
Fragments
A fragment is one painted piece of one box, in device pixels. Inline content produces one per line.
| Group | Fields | Notes |
|---|---|---|
| Identity | key, box_, node, parent | node is None for an anonymous box |
| Geometry | border_box, padding_box, content_box, border, padding | in local space (see Units and snapping) |
| Ink | ink, local_ink, subtree_ink | painted extent in device space, in local space, and unioned over the subtree |
| Space | clip, clip_transform, transform, transform_hash | interned ids from zgui-scene, plus a matrix fingerprint |
| Order | stacking, scroll, subtree_order | stacking context, scroll frame, and the subtree's range of hit-order keys |
| Content | kind, content_hash, flags | what it draws |
| Folds | subtree_disjoint, subtree_rigid | computed over the subtree on the way back up |
FragmentKind is Box, Line { paragraph, line }, TextRun { paragraph, run },
Replaced { content }, Vector, Custom or Scrollbar { axis, part }.
FragmentFlags has seven bits: CLIPS_CHILDREN, IS_STACKING_CONTEXT, HAS_TRANSFORM,
IS_STICKY, HAS_READ_EXTENT, HAS_BLENDING_DESCENDANT and PAINTS_NOTHING (no background,
border, outline or shadow).
Fields that need care:
inkis everything the fragment writes, including shadow spread, outline offset and filter bleed. Damage is computed from it, so under-reporting leaves stale pixels. Pixels a fragment only reads (a blur's sampling radius) are tracked in a separate registry, flagged byHAS_READ_EXTENT, so they do not inflate damage for everything else.local_inkis the same extent in the fragment's own space. The hit index uses it, so entries stay valid when only the matrix above them moves.subtree_inklets painting skip a whole clean subtree with one rectangle test.transform_hashfingerprints the matrix. A space's id stays the same when its matrix changes, so without the hash a 90° rotation of a square would compare as unchanged.content_hashis zero except for lines. It captures what a line draws beyond its rectangle, such as atext-overflowcut and its marker.
FragmentKind::same_piece decides whether two kinds name the same piece. Lines and runs match by
index and ignore the paragraph id, because typing a character interns a new ParagraphId. Matching
on equality would recreate every line on every keystroke and lose its hit entry and paint record.
A reused line whose paragraph changed is still repainted.
The fragment pass
fragment::diff::rebuild is one walk that composes and snaps absolute positions, compares each
fragment with the previous frame (Change::Identical, TranslatedOnly or Changed), collects
damage into a DamageSet, folds subtree values on the way back up, and updates the hit index. It
enters boxes carrying any bit of ENTERS (RELAYOUT, REPOSITION, REFRAGMENT, RESTACK,
SCROLL, REPAINT, REHIT, RESHAPE) and returns RigidMoves. The runtime runs it even when
layout was held, because a colour change still needs damage. rebuild_in is the same walk with
caller-owned scratch buffers.
Each child gets one of three treatments:
| Treatment | When | Cost |
|---|---|---|
| keep | the parent did not move, the child carries no marks, and its layout result equals the one its fragments were composed from | read its folded values |
| translate | the child is clean and its subtree is rigid | one offset per fragment, plus damage |
| visit | anything else | full compose and compare |
The layout comparison (state.unrounded == state.composed) is required because marks are set on
the element that changed, not on siblings that moved because of it.
A subtree is rigid when every fragment in it moves by the same vector as its root. Sticky boxes,
position: fixed boxes and transformed boxes break rigidity and are recorded in subtree_rigid.
Clips do not, because a clip moves with its box. RigidMoves, the pass's return value, reports
whether the frame was a single rigid move and by how much, which lets the renderer shift existing
pixels instead of repainting a scrolled region.
Damage rules:
- A box with
PAINTS_NOTHINGowes no damage when it is born, retired, repainted or repositioned; its children damage themselves. This stops paintless containers (a virtual list's pane, for example) from damaging the whole scrollport. - A plain box that only changed size damages only the strips along the edges that moved, when its painting near other edges is unchanged.
- Born fragments are damaged whole; retired fragments are damaged where they were.
FrameDirty is how the pass reads and writes marks. Everything answers Dirty::all() and is used
for a first build. DocumentMarks<'a> reads the document. ENTERS is retired after the walk,
because the walk reads each node's marks twice.
Anonymous boxes have no element, and asking the document about no element returns
Dirty::all(). Roughly a fifth of a real document's boxes are anonymous, so this would make the
pass visit most of the tree on every frame. Owed::of (fragment/diff/dirty.rs) reads an
anonymous box's marks from the element it was generated for, and adds that element's subtree marks
to the box's own, because an anonymous inline root draws the lines its descendants' glyphs sit in.
Units and snapping
zgui-geom tags geometry with its coordinate space (Css, Device, Layout) using zero-sized
markers, so mixing spaces is a compile error. Inside the engine, arithmetic is f32 device pixels.
Au (1/60 CSS pixel as an i32) is used where the cascade passes lengths across, such as
container-query sizes; zgui_css::engine::geometry::from_au and to_au convert it exactly.
Snapping happens in the fragment walk (round/snap.rs): round each cumulative absolute edge, and
take each size as the difference of two rounded edges. Rounding sizes independently would let a
column of boxes drift by several pixels and leave one-pixel gaps between neighbours.
A fragment's rectangles are typed Device, but border_box, padding_box, content_box and
local_ink are in local space (absolute layout coordinates, no transforms applied), while
ink is in device space. Fragment::transform names the matrix between them.
Stacking contexts and paint order
A stacking context is painted as a unit. Within each one, children are painted in the passes of
PaintLevel, whose variant order is the CSS painting order:
pub enum PaintLevel {
NegativeStacking, Block, Float, Inline, Positioned, PositiveStacking,
}establishes (fragment/stacking.rs) returns true for the root box; a positioned box with a
z-index; position: fixed or sticky; a flex or grid item with a z-index; opacity below 1;
any mix-blend-mode other than normal; isolation: isolate; any filter, backdrop-filter or
clip-path; and any transform property.
- Stable ids.
id_of(key)is derived from the box key, so a context keeps its id for the box's lifetime, and a partial walk leaves other contexts' ids alone. - Walks the layout list. That list contains anonymous boxes and holds each out-of-flow box under
its containing block, which is where CSS paints it. At each box, children are stably sorted by
(level, z_index), so ties keep layout order (afterorder).children_in_paint_orderborrows the list unchanged when it is already sorted, which is almost always. - Membership, not sequence. Fragments store
stackingandIS_STACKING_CONTEXT; the sequence is derived bypaint_orderwhen needed.
Hit entries carry the paint-order key instead of computing their own, so hit testing always agrees with what is on screen.
Positioning, clipping and overflow
Fixed positioning. anchored::ignores_scroll returns true for position: fixed, so neither the
box nor its subtree takes any accumulated scroll offset.
Clipping (fragment/clip.rs). A clip is a chain: a rounded card inside two nested scrollports
is three tests.
overflow: visibleon both axes adds no link. Every other value clips, includingautowith no visible scrollbar.- The link is the padding box, with inner corner radii (outer radius minus border width, floored at a square corner).
- The link uses the box's corner shape (
--zgui-corner-shape, read byfragment/corner.rs), so content inside a squircle is clipped to the squircle. - A box is never clipped by its own clip. A scrollport's shadow belongs to the scrollport.
- A link is named by its owning box, so a resize rewrites the rectangle in place and everything that refers to the chain keeps referring to it.
Overflow (scroll_region/). Layout owns the scroll region; the scroll offset is applied by
the fragment pass and never re-enters layout. region_of(store, box) and
region_of_element(store, element) return a ScrollRegion: the scrollport rectangle, the
content size, and scrolls_x / scrolls_y, which say whether the user may scroll each axis
(overflow auto or scroll).
overflow: auto always counts as a scroll container; only the scrollbar's visibility depends on the
content. Which axes an auto box decided to scroll is kept between frames, so the next layout
starts from the previous answer and a gutter does not flicker while content is edited. Scrollbar
fragments are appended after line fragments, so editing text in a scrollport does not renumber the
scrollbar's fragment slots.
The hit index
The hit index answers "which fragments are under this point". It lives in zgui-layout because it
is built from the layout store, updated by the fragment pass, and ordered by paint order, which is
decided here.
pub struct HitEntry {
pub frag: FragKey,
pub node: Option<NodeKey>,
pub order: HitOrder, // u64 key in painting order
pub clip: ClipId,
pub clip_space: Option<SpatialId>,
pub space: Option<SpatialId>,
pub pointer_events: PointerEvents,
pub radii: Corners<Vec2<DevicePx>>,
pub bounds: Rect<DevicePx, Device>,
pub envelope: Rect<DevicePx, Device>,
}- Every rectangle is in the coordinate space that
spacenames, not in device pixels. An entry stays valid while its box's matrix animates. envelope(bounds plus shadows and outlines) is the index key, so a subtree whose ink covers the point is never dismissed early.clip_spaceis separate fromspacebecause a clip belongs to the ancestor that imposed it.
A query maps the point into each coordinate space once, tests coverage, rounded corners, the clip
chain and pointer-events, and sorts the hits by order key, topmost first. It returns fragment
keys; resolving them to elements for dispatch happens in the runtime. is_consistent() checks that
the forest and the entry table agree.
One R-tree per coordinate space
HitIndex holds one entry per fragment and a forest: one dynamic R-tree per coordinate space
(fragment/hit/rtree/, MAX_ENTRIES = 8, MIN_ENTRIES = 3). Entries record their leaf and nodes
record their parent, so removal costs the tree depth and allocates nothing.
Moving an entry is usually cheap:
| Placement | Condition | Cost |
|---|---|---|
InPlace | the new rectangle is inside its leaf's envelope | one write |
Stretched | it left the envelope but still overlaps it | its leaf plus the envelopes above |
Reinserted | it moved somewhere else | a search for a new leaf |
Updating entries
| Method | Use |
|---|---|
update(frag, entry) | An entry whose shape may have changed. Counts as churn only when the entry was Reinserted. |
refresh(frag, entry) | update, skipped when the entry is unchanged. |
translate(frag, entry) | A scroll or transform that moves a whole group by one vector. Never counts as churn, because neighbour relationships are unchanged. |
carry(frag, entry) | Writes the entry immediately and defers the tree repair. settle() then repairs the tree once for the whole run. |
The fragment pass calls settle right after the walk, and nothing may query the index in between.
The index is rebuilt in bulk (Counter::HitIndexRebuilds) only when:
- painting order changed (
Dirty::RESTACK), or a newborn fragment has to be placed among siblings that paint in a different order than they lay out; - a newborn fragment found no free order key between its neighbours (see below); or
- churn exceeds a quarter of the entries (
churn > len() / CHURN_FRACTION,CHURN_FRACTION = 4).
Order keys. A bulk build numbers entries in paint order with a stride of ORDER_STRIDE
(220) and records each subtree's key range in Fragment::subtree_order. A newborn
fragment takes a key in the gap between its neighbours, so inserting content does not force a
rebuild. When a gap is exhausted, the pass sets renumber and the index is rebuilt after the walk.
Counters and checks
The scroll benchmark in docs/performance.md holds scroll.translation.relayouts and
scroll.translation.hit_rebuilds at zero. A scroll changes no size and no style, so any relayout
or index rebuild there means a fast path broke. docs/perf/glide-split.md measures a scroll frame
at about 109 ns per moved box: 73 ns for the rigid-move walk and 35.5 ns for HitIndex::settle.
Counters this crate moves (compiled into release builds, because zgui-runtime enables
zgui-profile/counters):
| Area | Counters |
|---|---|
| box tree | BoxTreeBuilds, BoxesRebuilt, BoxesLive, BoxesMarkedAllDirty |
| styles | StylesLowered, StylesLoweredFromCache |
| layout | LayoutReachedRoot, LayoutsHeld, NodesRelaidOut, NodesChanged, SizesHeld, SizesMeasured, GuttersExamined, LayoutBatchesDistributed |
| text | BoxesReshaped, ParagraphsEvicted, ParagraphsForgotten |
| fragments | FragmentsDiffed, FragmentsRebuilt, FragmentsLive, NodesVisited, BoxesShifted |
| hit index | HitEntriesUpdated, HitEntriesMovedInPlace, HitEntriesReinserted, HitIndexRebuilds |
ZGUI_INVARIANTS=1 enables the level-agreement checks in crates/zgui-layout/src/invariants/.
Links between elements, boxes and fragments are stored on both sides and can drift apart. The
symptom is a click that hits nothing or a fragment painted for content that is gone, far from the
code that caused it. The checks always run in this crate's tests and are opt-in elsewhere.
Next
The text engine
What answers the measurement calls: shaping, line breaking and glyph rasterisation.
Paint and the scene
The paint-order walk over fragments, per-fragment recording, and culling against damage.
Invalidation
The marks the fragment pass enters and retires, and how damage rectangles merge.
Caches
Every cache in the pipeline, what invalidates it, and what a miss costs.
The style engine
How zgui drives Stylo — the DOM traits, stylesheets, the mutation filter, the restyle pass, selector matching, custom-property narrowing, computed-style sharing, damage translation and animations.
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.