zgui
Architecture

Invalidation and damage

The fifteen dirty bits a node can owe, how marks propagate and walks clear them, how style changes become obligations, and how damage rectangles are collected and merged.

Invalidation decides how much work a frame does. Every node records which of its retained results are out of date, each stage redoes only that work, and the renderer redraws only the damaged parts of the window. The types live in zgui-bits; the stages that set and clear them are described below.

Two terms:

  • Invalidation records which retained results (styles, boxes, layout, fragments, recordings) are out of date.
  • Damage is the set of surface rectangles whose pixels are out of date.

Per-stage obligations

Each stage needs to know something different about a node:

StageQuestion
CascadeMust selectors be matched again, or only the cascade re-run?
Box constructionDo different boxes exist here now?
LayoutIs this box's size stale?
TextMust this paragraph be reshaped, or only re-broken into lines?
FragmentsDid this piece move or change?
PaintWhich pixels are wrong?
AccessibilityDoes this node project differently?

A single dirty flag cannot tell a colour change from a width change, so every stage would have to assume the worst. Each node therefore carries a set of obligations, one bit per kind of work. Sets combine with bitwise or, so:

  • Marking a bit that is already set changes nothing. Propagation uses this to stop early.
  • Bits do not imply any order. The order comes from the frame pipeline.
  • Each bit is cleared only by the stage that services it.

Dirty bits

Dirty is a bitflags type over u32 in crates/zgui-bits/src/dirty/bits.rs.

BitValueMeaningTypically set by
RESTYLE1 << 0Match selectors again for this element.attribute, class or state write; insertion
RECASCADE1 << 1Re-run the cascade only; matches still hold.root font-metric change; viewport units; cascade-tier animation
REBUILD_BOX1 << 2Rebuild the boxes this element generates.CONSTRUCT_BOX / CONSTRUCT_DESCENDANTS damage; first cascade; generated-content style change
RELAYOUT1 << 3Layout inputs changed; cached size and position are invalid.layout-affecting damage; viewport or scale change
RESHAPE1 << 4Text content or a shaping-relevant style changed.text edit; font change
REBREAK1 << 5Only a line-breaking or alignment style changed.text-align, word-break, and similar
REPOSITION1 << 6Absolute position changed; size and content did not.the fragment pass
REPAINT1 << 7Paint output changed.paint-key change; fragment pass; animation tick
CHILDREN1 << 8The child list changed (insert, remove, reorder).document mutation
A11Y1 << 9The accessibility projection changed.mutation; listener change; scroll; accessibility-key change
REHIT1 << 10The hit-test entry changed.fragment change; stacking or ink change; pointer-events
SCROLL1 << 11A scroll offset at this node changed.zgui_scroll::mark::scrolled
REFRAGMENT1 << 12Transform, ink or scrollable overflow changed; size, position and content did not.corner radius, box shadow, transform
RESTACK1 << 13Stacking-context membership or paint order changed.z-index
ANIMATING1 << 14An animation or transition is running, so the next frame has a deadline.animation tick

Ink is the rectangle a fragment actually paints. It can be larger than the border box (shadows, blur) or smaller (corner clipping). Damage is always computed from ink.

Two tests in bits.rs fix the layout: the_lattice_has_fifteen_distinct_bits and every_flag_fits_the_low_half_of_a_word. The second keeps every bit in the low 32 bits, because DirtyCell packs two copies of the set into one 64-bit word.

DirtyCell: own bits and subtree bits

Each node stores what it owes itself and the union of what it and all its descendants owe, in one atomic word (crates/zgui-bits/src/dirty/cell.rs):

#[repr(transparent)]
pub struct DirtyCell(AtomicU64);

const SUBTREE_SHIFT: u32 = 32;
bits 63–32
Subtree
The union of what this node and everything below it owes.
bits 31–0
Own
What this node owes itself.
The two halves of a DirtyCell

Marking a node and informing an ancestor is one atomic read-modify-write per level. A walk can skip a clean subtree with one load.

MethodOrderingBehaviour
clean()—Owes nothing.
new(own, subtree)—Both halves as given. own is not folded into subtree.
own(), subtree()AcquireOne half.
get()AcquireBoth halves from one load. Use this in walks; two separate loads can disagree.
is_clean()AcquireWhole word is zero.
mark(bits)AcqRelAdds to both halves. Returns whether the subtree half gained a bit.
mark_subtree(bits)AcqRelAdds to the subtree half only. Returns whether it changed.
clear_own(bits)AcqRelRemoves from the own half only.
retire_phase(phase, keep)AcqRelClears phase from the subtree half and re-adds keep, atomically.
use zgui_bits::{Dirty, DirtyCell};

let cell = DirtyCell::clean();
assert!(cell.mark(Dirty::REPAINT));   // gained a bit: propagate to the parent
assert!(!cell.mark(Dirty::REPAINT));  // already set: propagation stops
cell.clear_own(Dirty::REPAINT);
assert_eq!(cell.own(), Dirty::empty());
assert_eq!(cell.subtree(), Dirty::REPAINT);

The two halves never affect each other. A property test (the_halves_track_the_model_and_never_alias) checks this against a reference model, and a loom test (crates/zgui-bits/tests/dirty_cell_loom.rs) checks the concurrent protocol. All methods take &self, so a worker thread can mark a cell while a walk reads it.

Dirty and DirtyCell are re-exported as zgui_dom::dirty::{Dirty, DirtyCell}. The umbrella crate exposes the whole crate as zgui::bits.

Marking

Marking is implemented in crates/zgui-dom/src/dirty/propagate.rs:

pub fn mark(store: &mut DocumentStore, node: NodeIndex, bits: Dirty);
pub fn propagate(store: &mut DocumentStore, node: NodeIndex, bits: Dirty);

mark:

  1. Checks whether the node's own bits already contain bits.
  2. Adds bits to the node's cell. If step 1 said yes, returns: an earlier mark already reached the ancestors.
  3. Otherwise walks up. At each ancestor it first records the child it came from in the ancestor's dirty-child record, then adds bits to the ancestor's subtree half. It stops at the first ancestor whose subtree half already had them.

Marking n nodes therefore costs O(n + depth), not O(n · depth).

Two details matter:

  • Step 1 tests the own half, not the subtree half. The style engine's "work below me" flag is stored in the subtree half, so a subtree bit can be set without any ancestor having been told. Testing the subtree half would skip propagation and leave the element unstyled forever. The regression test is a_node_carrying_only_the_engines_descent_flag_still_marks_its_ancestors.
  • The dirty-child record is updated before the early stop. An ancestor that already owes the same bits for a different child must still learn about this child.

propagate is steps 3 alone. It exists for subtrees built while detached: their marks were recorded with no parents to tell. When such a subtree is linked in, ancestors::splice (crates/zgui-dom/src/mutate/ancestors.rs) folds own | subtree into the new parent chain.

The dirty-child record

The subtree half skips a clean subtree. It cannot skip clean siblings: a node with 10,000 children and one dirty child would still check 10,000 cells. DirtyChildren (crates/zgui-dom/src/dirty/children/) records which children to descend into.

  • Up to four children (EXACT = 4) are stored inline on the node. That covers the common cases: hover moving between two rows, focus moving, an edge pair, one insertion.
  • The fifth child moves the record to an overflow table in the document, keyed by the owner. Each further mark is one insertion, wherever the child sits.
  • Past OVERFLOW_CAP (4096) children the record degrades to "every child".

Children are recorded by identity (NodeIndex), never by position. Element positions are numbered lazily, so a position recorded before a structural change could name the wrong child afterwards.

The record may over-report but never under-report. A child that has since moved to another parent is filtered out when the record is read.

The dirty walk

Every stage descends the same way (crates/zgui-dom/src/dirty/walk.rs):

pub fn walk(
    store: &mut DocumentStore,
    root: NodeIndex,
    phase: Dirty,
    visit: &mut impl FnMut(&DocumentStore, NodeIndex),
) -> Dirty;

pub fn walk_in(scratch: &mut Scratch, /* same arguments */) -> Dirty;
  • visit runs only for nodes whose own bits intersect phase. Nodes that only have work below them are passed through.
  • A subtree is skipped when (own | subtree) does not intersect phase. That is one load.
  • The return value is what still remains for phase at or below root. It is empty unless a callback marked something.

Three ordering rules:

  1. Visit on the way down. Each stage's output is read by the node's descendants.
  2. Clear a node's own bits just before calling visit. If the callback re-marks its own node, that mark survives as a request for the next pass. Clearing on the way back up would erase it.
  3. Rebuild the dirty-child record from all bits, not just phase. One record serves every stage. Rebuilding it from one phase would drop a child that only owes, say, accessibility work.

On the way back up, the walk calls retire_phase(phase, surviving) with what the children still owe, so a concurrent reader never sees a subtree half that has lost outstanding work.

Contract on visit: it may mark the node it was called for, or a descendant not yet reached. Marking a sibling, an ancestor or an already-visited node leaves work that no walk will find until something marks it again. A stage that needs wider reach runs a second walk.

walk_in reuses a Scratch so repeated walks in one frame do not allocate (inline buffers hold 64 entries). Counters: Counter::DirtyWalkSteps counts steps, including skips, and Counter::NodesVisited counts every node examined. NodesVisited is the one that reveals a walk touching thousands of clean nodes.

Clearing bits

A bit is cleared only by the stage that did the work.

BitsCleared byFile
RESTYLE, RECASCADEthe style engine, after its traversalcrates/zgui-style/src/engine/restyle.rs
REBUILD_BOX, then CHILDRENzgui_layout::boxtree::retire, two walkscrates/zgui-layout/src/boxtree/build.rs
RELAYOUT, REPOSITION, REFRAGMENT, RESTACK, SCROLL, REPAINT, REHIT, RESHAPE (diff::ENTERS)the fragment pass, after its walkcrates/zgui-layout/src/fragment/diff/mod.rs
A11Ythe accessibility projectioncrates/zgui-a11y/src/build/pending.rs
ANIMATINGthe animation tick, at its startcrates/zgui-anim/src/frame/retire.rs

Notes:

  • boxtree::retire returns lists, not a boolean. The root's subtree half only says whether something owes a rebuild. retire returns Owed { rebuilt, children }, and boxtree::patch::rebuild rebuilds only the boxes those elements generate. See Box-tree patching.
  • patch::retext reads RESHAPE but does not clear it. The fragment pass also needs it, to repaint a line whose glyphs changed but whose geometry did not.
  • The fragment pass clears after its walk, not during. It reads a node's bits twice (once to decide whether the subtree settled, once to decide what an unmoved fragment still owes).
  • No phase walk clears REBREAK. The style translation sets it, and the runtime reads it in owes_further_work (crates/zgui-runtime/src/window/observe.rs) to decide whether geometry observations need another style-and-layout pass.

An obligation that is never cleared makes every frame expensive: every box is examined, no subtree is skipped, every fragment counts as changed, and the damage covers the whole window.

The style engine's own "work below me" flag is not stored separately. It is read from the subtree half, setting it is mark_subtree, and clearing it is a no-op. The rule, stated in crates/zgui-dom/src/stylo/flags.rs: a descent flag may only be consumed by the traversal that retires the bits it was raised for.

Style changes

A restyle compares each element's old and new computed style and turns the difference into dirty bits. Stylo reports damage, zgui classifies layout-affecting changes by cost, and two key comparisons refine the result: the paint key decides repainting, and the text keys decide between reshaping and re-breaking.

Stylo damage and zgui's layout bits

Stylo computes four damage bits of its own (repaint, rebuild stacking context, recalculate overflow, relayout) and leaves the upper bits for the embedder. zgui defines these in crates/zgui-dom/src/stylo/element/damage/mod.rs:

BitMeaning
CONSTRUCT_BOX (1 << 4)This element's box must be rebuilt.
CONSTRUCT_FC (1 << 5)Its formatting context must be rebuilt.
CONSTRUCT_DESCENDANTS (1 << 6)Its descendants' boxes must be rebuilt.
RESHAPE_TEXT (1 << 7)Text may need reshaping.
REBREAK_TEXT (1 << 8)Text may need re-breaking.
RECALCULATE_INK (1 << 9)Ink changed; nothing moved.
RELAYOUT_BOX (1 << 10)Sizes and positions must be recomputed.

Stylo fills them through a hook that receives two computed styles and nothing else:

pub fn layout_damage(old: &ComputedValues, new: &ComputedValues) -> RestyleDamage {
    match classify::cost(old, new) {
        Cost::Repaint  => RestyleDamage::empty(),
        Cost::Ink      => RECALCULATE_INK,
        Cost::Geometry => RELAYOUT_BOX | RESHAPE_TEXT | REBREAK_TEXT,
        Cost::Layout   => RestyleDamage::reconstruct() | ALL,
    }
}

Cost classification

classify::cost checks property groups from widest to narrowest and returns at the first group that changed:

Is structure unchanged?
No
Cost::Layout
Yes
Is geometry unchanged?
No
Cost::Geometry
Yes
Does the surface cover the same area?
No
Cost::Ink
Yes
Are the surface colours unchanged?
No
Cost::Repaint
Cost::Layout
Nothing known moved, so the changed property is one this classifier does not name.
How a style change is assigned a cost
GroupDecidesExamples
structurewhich boxes exist and how they nestdisplay, position, float, order, generated-content strings, grid-template-columns, animation and transition declarations
geometry::boxesbox positions and sizeswidths, margins, insets, alignment
geometry::textglyphs and line positionsthe font group, line-height, letter-spacing, text-align, word-break, writing-mode
surface::coversshape of the painted areacorner radii and shapes, box-shadow, backdrop-filter, clip, masks, image-rendering, color-scheme
surface::colourscolours drawn into itthe four border colours

A property is structural if the box builder reads it. grid-template-columns is structural because the builder resolves its line names into the container's box. grid-column-start is not, because grid sizing reads it from the style each time.

If no group changed, the answer is Cost::Layout. Stylo calls the hook only after deciding that a layout-affecting property changed, so "no difference found" means the property is one this classifier does not know. Treating it as the widest change keeps unknown properties correct.

Translating damage into dirty bits

crates/zgui-style/src/damage/translate.rs:

pub fn translate(
    store: &mut DocumentStore,
    texts: &mut TextKeyStore,
    record: &Restyled,
    style: &ComputedStyle,
    out: &mut DamageSink,
);
ConditionMarks
first cascade (record.initial)RELAYOUT, REBUILD_BOX
any of zgui's layout bitsRELAYOUT
… plus CONSTRUCT_BOXREBUILD_BOX
… plus CONSTRUCT_DESCENDANTSREBUILD_BOX on the node and on its subtree half
… plus RESHAPE_TEXT, if the text keys agreeRESHAPE
… plus REBREAK_TEXT, if the text keys agreeREBREAK
otherwise RECALCULATE_INK, or overflow recalculation without relayoutREFRAGMENT, REHIT, REPAINT
otherwise a stacking-context rebuild without relayoutRESTACK, REHIT, REPAINT
the paint key changedREPAINT; also REHIT if the inherited UI group changed; REBUILD_BOX if a generated-content style changed
the accessibility key changedA11Y

Reasons for this mapping:

  • A first cascade produces no Stylo damage, because there is no old style to compare. Without the first row, a newly inserted subtree would get no boxes. This also covers a subtree leaving display: none: its style data was discarded, so every element in it is styled for the first time again.
  • Stylo's four bits are nested. Relayout includes overflow recalculation, which includes a stacking rebuild, which includes repaint. So the rows are tested widest first, and the narrower Stylo bits are ignored under a relayout.
  • Relayout is not rebuild. A width or margin change only discards a cached size. A display or position change discards boxes.
  • Marks are collected, then applied. DamageSink folds (NodeIndex, Dirty) pairs in a hash map and apply writes them afterwards. Marking walks to the root, and doing that while reading Stylo's data would mix two kinds of document access.

The paint key

Stylo's repaint bit cannot decide repainting. Border colours, radii, visibility, masks and shadows classify as Cost::Repaint, which maps to empty damage. Repainting is decided by comparing PaintStyleKey (crates/zgui-dom/src/side/paint_key.rs) instead, after every restyle.

Each field is the address of a shared, immutable computed-value group: background, border, effects, outline, svg, inherited_ui, inherited_box, text, box_, position, inherited_text, the generated-content styles pseudo_before and pseudo_after, and the two custom-property maps (custom). Stylo shares groups between elements with equal values, so equal addresses prove equal values and the comparison is a few integer tests.

Different addresses do not prove different values. The key may report a change that did not happen, but never misses one. PaintStyleKey::UNSTYLED is all zeros and a group's address is never null, so a node's first style always counts as a change.

A generated-content style is copied into the box that displays it, so paint_key::pseudos_moved marks REBUILD_BOX rather than just REPAINT. The accessibility key (a11y_key.rs) works the same way and marks A11Y.

Reshaping and rebreaking text

Shaping turns characters into positioned glyphs (fonts, kerning, ligatures). Line breaking splits shaped text into lines and aligns them. Shaping is far more expensive, so a width or alignment change must not cause one.

The Stylo hook has no memory and must assume any layout change reshapes. TextKeyStore (crates/zgui-style/src/damage/layout_damage.rs) adds that memory. It keeps each element's last ShapingKey and BreakingKey (hashed from exactly the properties each stage reads) and compares:

ComparisonTextWork
shaping key changedReshape
only breaking key changedRebreak
neither changedNone
no previous keysReshape

The narrowing only applies inside a relayout. When Stylo reports RestyleDamage::reconstruct() (generated content appeared or disappeared), the text changed without the element's own style changing, so the narrowing is skipped.

The store drops elements that left the document, but only when it has doubled in size since the last sweep (minimum 64 entries), so sweeping costs a constant per insertion.

Text content changes take a different path. set_text marks the text node RESHAPE | A11Y. boxtree::patch::retext then writes the new characters into the existing box, drops the cached flattened form of the inline formatting context, and invalidates the layout of the box and its ancestors. It falls back to a rebuild only when text appears in an empty text node or becomes empty, because that changes which boxes exist. A font change on an element keeps the boxes and discards the shaping-derived caches below it through reshape::scope.

Viewport changes

zgui-style's device epoch (crates/zgui-style/src/device/mod.rs) handles a new surface size, scale or colour scheme:

ChangeInvalidation
anyStylo reports which stylesheet origins' media queries may now answer differently. Only non-empty origin sets are forced dirty, so a resize that crosses no media query restyles nothing.
size, if any viewport unit was ever resolvedinvalidate_units marks only elements whose style used a viewport unit: RECASCADE for a unit in a declaration, RESTYLE for one read while matching a query (that decides which rules match).
sizeRELAYOUT on the root only. Layout caches decide how far the change reaches.
scaleRELAYOUT on every element, because every box snaps to a new device-pixel grid.

Box-tree patching

boxtree::patch::rebuild (crates/zgui-layout/src/boxtree/patch/subtree/) rebuilds only the elements in Owed and splices the new boxes in place:

  • An element whose own boxes changed is rebuilt through its container, because wrapping, ordering and blockification are decided there.
  • An element whose child list changed is rebuilt itself.
  • Under a display: contents element, the nearest ancestor that generates a box is rebuilt. Containers under display: none are skipped.

A splice is refused when the subtree is not confined: when its boxes are not exactly the boxes its elements generate, when something outside is laid out from inside it, or when the new box takes part in its container differently. The largest refused case is an out-of-flow box whose layout parent and paint parent differ. A refusal builds the whole box tree from the root.

A whole build gives every box a new key, so fragment reuse, paint recordings, hit entries and damage all start from scratch. Counter::BoxTreeBuilds counts whole builds, including the first. A steady-state frame that increments it paid for the whole window.

Damage rectangles

The renderer keeps its target between frames, so pixels outside the damage are already correct. The damage set must cover everything that changed, and should cover as little else as possible.

crates/zgui-bits/src/damage_set/mod.rs:

pub const MAX_DAMAGE: usize = 6;

pub struct DamageSet<const N: usize = MAX_DAMAGE> { /* rects, len, full */ }

Invariants:

  • Rectangles are pairwise disjoint. Each rectangle is redrawn in its own pass, so overlap would draw the shared pixels twice.
  • A full set holds no rectangles. Resize, scale change, device loss, theme change and the first frame produce a full set. The caller knows the surface bounds.

The limit of six was chosen by measurement. With four, dragging a panel edge through a page with two scroll bars and a dock merged the edge strips and bars into the whole page on every step; eight was no better than six. CONTRIBUTING.md requires scenario evidence before the number changes.

MethodBehaviour
new(), full(), for_frame()Empty; whole surface; empty unless ZGUI_FULL_DAMAGE=1.
absorb(rect)Adds rect, keeping the set disjoint (see below).
absorb_whole(rect)Adds rect so that one held rectangle contains all of it.
absorb_set(&other)Absorbs every rectangle of other; becomes full if other is.
contains(rect)One held rectangle covers all of rect.
intersects(rect)rect overlaps something to be redrawn.
clip_to(surface)Cuts every rectangle to surface.
bounds(), area()None when full. area is a sum, since rectangles are disjoint.
set_full(), is_full(), is_empty(), clear(), len(), rects()State accessors.

PartialEq is order-sensitive. Compare area() or rects() as a set when you mean coverage.

Merging rectangles

absorb handles four cases:

  1. Contained already: do nothing. Scrolling hits this case thousands of times per frame.
  2. Overlapping and worth merging: merge with every held rectangle it overlaps where the union adds no more waste than the larger of the two areas (merge::worth_merging). Repeat until none is left.
  3. Touching nothing: push it.
  4. Meeting a held rectangle only at a corner (for example the right and bottom bands a widened window exposes): add only the parts outside the held rectangles, as disjoint pieces, if they fit. Otherwise fall back to absorb_whole.

When the set is full to capacity, push merges the pair with the least waste, then re-absorbs the union so the set stays disjoint. Waste is counted over the closure: if the union of two rectangles would also swallow a third, that third rectangle's surroundings count too (merge::least_wasted_pair). Conversion to device pixels rounds outward on every side (diff::pixels), so no hairline of the old frame survives at an edge.

Damage sources

Most damage comes from the fragment pass (crates/zgui-layout/src/fragment/diff/mod.rs). It composes each visited box's absolute geometry, compares it with the previous fragment, and absorbs what changed:

pub enum Change { Identical, TranslatedOnly, Changed }
const REPAINTS_IN_PLACE: Dirty = Dirty::REPAINT.union(Dirty::RESHAPE);
SourceDamage
Change::Changed or TranslatedOnlyprevious ink and new ink
a plain box that only changed sizeonly strips along the edges that moved, when nothing else about its painting depends on its size
Change::Identical and the node owes REPAINT or RESHAPEthe fragment's ink
a box created this frame that paints nothing itselfnothing (its painted children damage themselves)
fragments retired before the walktheir subtree ink, skipping boxes that painted nothing
a fragment destroyed during the walk (Pass::retire)its subtree ink
a rigid translation (diff/rigid/)subtree ink before and after, once for the subtree
zgui_paint::expandthe read region of composites (backdrop filters, blurs) the damage touches
the caret planthe caret rectangle

The Identical row is needed because a colour change or a same-width text change moves nothing. A geometry comparison alone would not damage the hovered button or the updated counter.

Finishing the damage set

After the fragment pass, crates/zgui-runtime/src/window/frame.rs does the following, in order:

  1. Scroll shift. If exactly one scrollport moved by a whole-pixel vector and the renderer can move its composed pixels, the movement's damage is replaced by: damage from before layout, RigidMoves::beyond (damage not caused by the move), and the bands the copy exposes. See Shifting a composed scrollport.
  2. Clip to the surface. A scroll in a tall document absorbs ink far outside the window.
  3. Expand over read regions (zgui_paint::expand). A backdrop filter or blur reads pixels outside what it writes. Reading last frame's pixels there would smear. Expansion runs to a fixpoint bounded by the number of registered read regions. When it runs and the damage then covers more than half the surface (FULL_DAMAGE_SHARE = 0.5), or the bound is reached, the set becomes full.

The set is then frozen. The paint walk emits everything that intersects it, changed or not, because the renderer clears each rectangle before drawing it. See Culling against damage.

ZGUI_FULL_DAMAGE=1 makes every frame start fully damaged, disabling partial redraw. The variable is read once. Use it first when you see a visual artefact: if it disappears, it is a damage-tracking bug.

Scrolling

A scroll restyles nothing and lays nothing out. It marks one fixed set of bits (crates/zgui-scroll/src/mark/mod.rs):

pub const SCROLLED: Dirty = Dirty::SCROLL.union(Dirty::A11Y);

This is marked only on the scroll container. SCROLL makes the fragment pass enter the container and recompose its descendants at the new offset. A11Y is one node, because descendants' accessibility bounds are relative to the container. A unit test asserts that SCROLLED contains none of RESTYLE, RECASCADE, RELAYOUT, REBUILD_BOX, RESHAPE, REPAINT or RESTACK.

Inside the fragment pass each child takes one of three routes:

RouteWhenCost
cachedparent settled, child clean, and its layout result unchangedread the child's stored fragments
translatechild clean and its subtree rigidone offset applied to the subtree, two absorb calls
visitanything elsefull composition
fn can_skip(&self, child: BoxKey, generator: Option<zgui_dom::NodeKey>) -> bool {
    let owed = self.owed_by(child, generator);
    !owed.own.intersects(ENTERS)
        && !owed.subtree.intersects(ENTERS)
        && !self.store.fragments_of_box(child).is_empty()
        && self.store.state(child).is_some_and(|state| state.unrounded == state.composed)
}

Being clean is not enough: a sibling that grew moves later boxes without marking them, so the layout result is compared as well.

A subtree is rigid if it contains no sticky box, no box positioned against the viewport, and no transform, and its snapping origin is unchanged. These are folded up the fragment tree so the check is one boolean.

RigidMoves reports whether the pass stayed incremental, the common movement vector (by), whether moves conflicted, how many subtrees moved, and the damage not caused by the movement (beyond). Reports from several passes in one frame are combined.

Current figures from docs/performance.md in the zgui repository: a pure scroll translation frame (scroll.translation) has 0 restyles, 0 relayouts and 0 hit-index rebuilds, and takes about 48 µs at the median, against about 1 ms for a frame that recycles a row into view (scroll.recycle).

Anonymous boxes

CSS creates boxes that no element owns: wrappers around inline runs, the box that establishes an inline formatting context, text runs between elements. Asking the document about "no element" would answer Dirty::all() and make the subtree unskippable. Owed::of (crates/zgui-layout/src/fragment/diff/dirty.rs) asks about such a box using the element it was generated for instead, and folds that element's subtree bits into the box's own bits, because an anonymous inline formatting context draws the lines its descendants' glyphs sit on.

Examples

Each trace follows one change from the write to the damage.

A colour change

A :hover rule changes one element's background-color.

state write         node: RESTYLE; ancestors' subtree half |= RESTYLE
cascade             Stylo reports repaint only; translate sets no layout bits
paint key           background group address changed -> REPAINT
layout              nothing owes layout; Counter::LayoutsHeld
fragment pass       Change::Identical, own & REPAINTS_IN_PLACE -> absorb ink
damage              one rectangle
paint walk          subtrees outside it are skipped
cleared             RESTYLE by the style engine; REPAINT by the fragment pass

A width change

attribute write     node: RESTYLE
classify::cost      geometry changed -> Cost::Geometry
translate           RELAYOUT; text keys unchanged -> no RESHAPE, no REBREAK
                    paint key: `position` group moved -> REPAINT as well (over-reports)
patch::style        new style written to the box; cached layout dropped up to the root
layout              Cephal relays out the dirty region
fragment pass       Changed for the element, TranslatedOnly for what the flow moved
damage              previous and new ink of everything that moved, merged

A text change

set_text            text node: RESHAPE | A11Y
cascade             nothing to do
boxtree::retire     nothing owes REBUILD_BOX or CHILDREN
patch::retext       characters rewritten in place; layout invalidated up to the root
layout              paragraph shaped, then broken
fragment pass       same width -> Identical, but RESHAPE is in REPAINTS_IN_PLACE -> ink absorbed
cleared             ENTERS by the fragment pass; A11Y by the projection

An insertion

A row is appended to a list.

insert_before       parent: CHILDREN; new node: RESTYLE | A11Y
ancestors::splice   the new subtree's bits folded into the parent chain
cascade             first cascade for each new element -> RELAYOUT | REBUILD_BOX
boxtree::retire     Owed { rebuilt, children }
patch::rebuild      new boxes spliced in; whole build only if the splice is refused
layout              new boxes and their ancestors relaid out
fragment pass       new fragments Changed; rows below TranslatedOnly
damage              the list from the insertion point down

Next

On this page