Skip to content
Back to skills

Gum Layout Engine

ASecurity

Deep internals of Gum's layout engine — UpdateLayout call chain, UpdateChildren ordering, stacking pipeline, dirty state, perf. Triggers: debugging/optimizing UpdateLayout/UpdateChildren, RefreshParentRowColumnDimensionForThis, GetWhatToStackAfter, MakeDirty, ResumeLayoutUpdateIfDirtyRecursive, _cachedSiblingIndex.

  • 666 stars
  • 0 votes
  • 0 copies
  • 2 views
  • Added November 7, 2026
designgonodedebuggingperformance

Works with

  • cli

Security analysis

A100/100

Scanned November 24, 2026

npx -y skills add vchelaru/Gum --skill gum-layout-engine --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Gum Layout Engine?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Gum Layout Engine
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/vchelaru-gum-layout-engine/badge)](https://www.skillsdirectory.com/skills/vchelaru-gum-layout-engine)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: gum-layout-engine
description: Deep internals of Gum's layout engine — UpdateLayout call chain, UpdateChildren ordering, stacking pipeline, dirty state, perf. Triggers: debugging/optimizing UpdateLayout/UpdateChildren, RefreshParentRowColumnDimensionForThis, GetWhatToStackAfter, MakeDirty, ResumeLayoutUpdateIfDirtyRecursive, _cachedSiblingIndex.
trigger_phrase: UpdateLayout internals|UpdateChildren|GetWhatToStackAfter|RefreshParentRowColumnDimensionForThis|MakeDirty|ResumeLayoutUpdateIfDirtyRecursive|_cachedSiblingIndex|layout performance|ChildrenUpdateDepth|GetIfShouldCallUpdateOnParent|UseFixedStackChildrenSize|UpdateLayoutCallCount|isFontDirty|SuppressLayoutFromFontChange|font during layout
---

# Gum Layout Engine Internals

For user-facing layout concepts (units, stacking, wrapping, Anchor/Dock), see
the **gum-layout** skill. This skill is for people debugging, optimizing, or
extending the engine itself.

All layout logic lives in `GraphicalUiElement`, a partial class split across `GumRuntime/GraphicalUiElement.*.cs`:

| File | Holds |
|---|---|
| `.LayoutProperties.cs` | X/Y/Width/Height, units, origins, Min/Max, `ChildrenLayout`, stacking and grid settings |
| `.UpdateLayout.cs` | `UpdateLayout` and its parent climb |
| `.Dimensions.cs` | `UpdateDimensions`, `UpdateHeight`, `UpdateWidth`, `GetMaxCell*` |
| `.RequiredSize.cs` | `GetRequiredParent*`, `GetParentDimensions`, texture-based dimensions |
| `.ChildUpdates.cs` | `GetChildLayoutType`, `UpdateChildren`, wrapped-line helpers |
| `.Position.cs` | `UpdatePosition` and the offset helpers |
| `.Stacking.cs` | row and column dimensions, grid cells, sibling helpers, `GetWhatToStackAfter` |
| `.Suspension.cs` | `MakeDirty`, `SuspendLayout`, `ResumeLayout` |
| `.DockAndAnchor.cs` | `Dock` and `Anchor` |

The other `.cs` partials hold properties, state application, rendering hookup and animation.

## UpdateLayout Call Chain

Entry point: `UpdateLayout(ParentUpdateType, int childrenUpdateDepth, XOrY?)`

### Flow (in order)

1. **Resolve `updateParent`** — evaluate `ParentUpdateType` flags against actual
   parent state (stacks? depends on children? has ratio children?).

2. **Early out — suspended or invisible** — if layout is suspended
   (`mIsLayoutSuspended` or `IsAllLayoutSuspended`) OR the element is invisible
   and not needed for parent update, call `MakeDirty()` and return. "Invisible" is
   `IsHiddenWithinRenderTarget()`: the element or an ancestor below the nearest render target is not
   visible. A render target (hidden or not) is never hidden, and its own `Visible` does not hide its
   content, but elements hidden inside it are skipped like anywhere else (#7240).

3. **Propagate to parent (originating call only)** — if `updateParent` AND
   `GetIfShouldCallUpdateOnParent()`, the *originating* call (the element that
   changed) hands off to `parent.UpdateLayout()` with `childrenUpdateDepth + 1`
   and **returns**; the parent lays this element out as a child. A *propagated*
   climb (already size-gated — see Upward Propagation) instead falls through and
   re-evaluates whether to keep climbing at the end of the method.

4. **Clear dirty state** — `currentDirtyState = null`. This is critical: it
   prevents double-updates during `ResumeLayoutUpdateIfDirtyRecursive` (see
   below).

5. **Pre-children dimensions** — update dimensions that do NOT depend on
   children (Absolute, PercentageOfParent, etc.) so children have correct parent
   sizes when they lay out.

6. **First children pass (if dimensions depend on children)** — update children
   with absolute layout types so the parent can measure them. With
   `UseFixedStackChildrenSize`, only the first child is updated here (O(1)
   instead of O(n)), and only when the width is not measured from the children:
   the other children are unmeasured, so they would give a width that is too small.

7. **Post-children dimensions** — update RelativeToChildren / RelativeToMaxParentOrChildren
   dimensions now that children have been measured.

8. **Wrapped children pass** — if `WrapsChildren`, update `StackedWrapped`
   children and re-measure dimensions with wrapping considered.

9. **UpdatePosition** — calculate X/Y based on units, origin, parent stacking.
   For stacked children, this calls `GetWhatToStackAfter` to find position
   relative to the previous sibling.

10. **RefreshParentRowColumnDimensionForThis** — if parent stacks, update the
    per-row/column max dimension.

11. **Full children pass** — `UpdateChildren(depth, ChildType.All, ...)` updates
    all children. Children already updated in step 6 are skipped via
    `alreadyUpdated` set.

12. **Post-layout dimension check + gated climb** — re-update dimensions if a
    child change could have altered them (always for a wrapping stack sized to
    its children: Ratio children are placed only in step 11 and move the
    siblings stacked after them, which changes the lines). If that changes the
    size, this element is placed again (an origin other than top-left reads its
    own size) and every child, ignored ones included, is laid out again against
    the new size; then, for a propagated climb, continue
    up to the parent only if this element's own measured size or position
    actually changed (see Upward Propagation).

### Repeat visits of a child are cut down to placing it

Steps 6, 8 and 11 (and the post-children re-measure) visit the same child more than once, so a chain of k
nested content-sized stacks would cost 2^k layouts. Every child visit in `UpdateChildren` goes through
`LayOutChild` (`ChildUpdates.cs`): after a visit that changed no size or position inside the child, a later
visit in the same *session* (one outermost `UpdateLayout`; `UpdateLayoutWithinSession` continues it, the public
`UpdateLayout` starts a new one) only places the child again (`TryPlaceInsteadOfLayingOutAgain`). The result
must equal laying out every time: `GraphicalUiElement.SkipRepeatedChildLayouts = false` is the test hook that
does that, and `LayoutRandomTreeSweepTests` compares the two. The skip needs the same axis (`xOrY`, or a
settled visit of both axes, which also covers a one-axis request: a parent measures a `Ratio` child on one axis
before laying it out in full), the same parent size on the axes the child's units read, a `Ratio` size that
`GetRatioWidth`/`GetRatioHeight` still work out to the size the child has now, and a visit that placed the child
at its final size. Dropping any of them fails a sweep or a test.

Visits are recorded only where a child can be visited twice. `UpdateLayoutWithinSession(mayBeLaidOutAgain)` is true
for a child of a tracking parent, and a layout tracks its children when it was passed true, sizes from its children,
wraps, or has a Ratio-first pass (`trackChildVisits` into `UpdateChildren`). The public `UpdateLayout` passes false, so
a plain `Regular` or fixed-size container laid out once pays none of the bookkeeping. A new second pass over the
children needs to set `trackChildVisits`.

### Deferred font realization (step 4.5)

Right after the parent-delegate early-out, before measuring, a node loads any font deferred while
layout was suspended (`isFontDirty`, set under `IsAllLayoutSuspended`). This is what makes a bare
`UpdateLayout()` realize deferred fonts. A font load normally lays out again when the text's measured
size changed; that call is suppressed here (`SuppressLayoutFromFontChange`) because this pass already
sizes the element. See the **gum-property-assignment** skill for the full cascade.

### Renderable-reported size changes

A setter that changes what the renderable reports (texture size, aspect ratio, text measure,
descender) goes through `ChangeRenderableAndUpdateLayout`, which lays out only when a unit this
element uses reads a value that changed. Font loads get the same check in `LoadFontFromProperties`.
A new texture, source file or font setter that writes the renderable directly skips layout.

## Circular Input Is Undefined

The engine rejects only the cycles between a parent and its child (`IsSizeFollowingParentContentSize`, `GetChildLayoutType`). A cycle through an intermediate element, a convergent cycle, or a wrapped text whose height follows its width has no defined result: it may need several layouts to settle, may never settle, and is not worth a rule per shape or a dependency-graph cycle detector. `LayoutRandomTreeSweepTests.IllFormedSeedsNotHeld` lists the sweep seeds that do this. The one guard is `ToFiniteSize` in `.Dimensions.cs`, which writes an infinite size as 0 so a divergent cycle cannot spread infinity into positions; it is a safety net, not a fix.

## UpdateChildren Internals

### Two-pass ordering for Ratio dependencies

When some children use `Ratio` width/height and siblings use complex units
(RelativeToChildren, PercentageOfOtherDimension, MaintainFileAspectRatio,
ScreenPixel, RelativeToMaxParentOrChildren), those complex-unit siblings must be
updated **first**. Ratio children need sibling sizes to compute remaining space.

Pass 1 (conditional): update children with `DoesDimensionNeedUpdateFirstForRatio`
units. Pass 2: update all remaining children.

A `Ratio` child is resized by siblings, not by its own subtree, so a depth-limited visit (a climb out of a
short subtree, such as hiding content) can resize it while stopping short of its descendants. `LayOutChild`
therefore lays a `Ratio` child out again to full depth, in a new session, when its size changed under a
limited depth. The branch for an element with no renderable (a Screen) does the same in `LayOutScreenChild`;
both ask `NeedsFullDepthLayoutAfterSiblingsResizedIt`.

### shouldFlagAsUpdated

For `Regular` layout, children are flagged as updated to avoid redundant work.
For stacked layouts, children are **not** flagged — they need a second pass to
update positions in order (stacking depends on sibling order).

### _cachedSiblingIndex

Set on each child (`child._cachedSiblingIndex = i`) in the iteration loop
before calling `UpdateLayout`. Used by `GetWhatToStackAfter` to avoid an
O(n) `IndexOf` call. Falls back to `IndexOf` if the cache is stale (element
not at expected position).

## Stacking Position Pipeline

`UpdatePosition` → `TryAdjustOffsetsByParentLayoutType` → `GetWhatToStackAfter`

### GetWhatToStackAfter

Finds the previous visible sibling and computes the offset to stack after it.

1. **Find sibling index** — uses `_cachedSiblingIndex` (O(1)) with `IndexOf`
   fallback (O(n)). The cache is valid during `UpdateChildren` but may be stale
   for individual property-change-triggered layouts.

2. **Find previous placed sibling** — walks backward from `thisIndex` skipping
   siblings the stack does not place (`IsPlacedByParentLayout`).

3. **Determine wrap** — if wrapping, increments `StackedRowOrColumnIndex` and
   sums `StackedRowOrColumnDimensions` for all previous rows/columns.

4. **Compute offset** — for non-wrapping: previous sibling's position + size +
   `StackSpacing`. For wrapping: row/column dimension sum.

### Children the stack or grid skips

A child with `IgnoredByParentLayout` is laid out as in a Regular parent: `GetIfParentStacks`, `GetIfParentIsAutoGrid`
and `GetWrappedLineAxis` return false or null for it, and code reading the parent's layout from the child's side goes
through `GetParentChildrenLayoutForThis`. Every walk over siblings that counts stack slots, grid cells or Ratio space
must test `IsPlacedByParentLayout` (visible and not flagged), not `Visible`. Parent sizing still counts the child:
`GetMaxCellWidth`/`GetMaxCellHeight` return its extent separately so a grid does not multiply it by the cell count.

### RefreshParentRowColumnDimensionForThis

Maintains `parent.StackedRowOrColumnDimensions[rowOrColumnIndex]` — the max
cross-axis dimension for each row (LeftToRight) or column (TopToBottom).

**O(1) fast path**: if this child's dimension >= stored max, just set it.
This is the common case during sequential layout (e.g., populating a ListBox).

**O(n) fallback**: if this child's dimension < stored max, it may have been the
max-holder and shrunk. Must rescan all siblings in the same row/column to find
the true max.

The rescan stops at this child, so it is only right during the sequential pass;
calling it on one child afterwards drops later siblings from the max. In a
wrapping stack the row is the cross-axis parent for position, so a row-aligned
child placed before the row's largest member is fixed up by
`RepositionChildrenAlignedInWrappedLines` (position only, no row refresh) at the
end of `UpdateChildren`. It skips suspended children: they were not laid out in the
pass, so no line recorded them, and their own layout places them on resume.

An axis-only layout from a property setter (`Height` lays out `XOrY.Y`) also places the other
axis when that axis's size changed, since a width that is a percent of the height moves a
center or right origin. A parent laying out a child one axis at a time places it in full later,
so only the originating call does this.

## Dirty State and Suspension

### MakeDirty

Called when `UpdateLayout` is invoked on a suspended or invisible element.
Accumulates into `currentDirtyState`:
- `ParentUpdateType` — OR'd together across multiple calls
- `ChildrenUpdateDepth` — max of all calls
- `XOrY` — set to null if different axes were dirtied (means update both)

### ResumeLayoutUpdateIfDirtyRecursive

Called when layout is resumed after suspension. `ResumeLayout(recursive: true)` first clears every descendant's
suspension (`ClearLayoutSuspensionRecursive`), so the first layout covers the subtree; resuming them one at a time
laid a parent out again per child (rows squared, #7239). Then it walks the tree:
1. Clear `mIsLayoutSuspended`
2. If `currentDirtyState != null`, call `UpdateLayout` with accumulated state
3. Recurse into children

**No double-update**: the parent's `UpdateLayout` (step 2) calls
`UpdateChildren`, which calls each child's `UpdateLayout`, which clears that
child's `currentDirtyState`. When recursion (step 3) reaches that child, its
dirty state is already null — it skips the `UpdateLayout` call.

### Visibility-deferred work is resolved on show

Layout skipped because an element or an ancestor was hidden is always resolved when it is shown, in any suspend mode and resume order; a layout clears a dirty record only when it covers its depth and axes, and `resumeDescendantsOnResume` makes a non-recursive resume walk hidden descendants (skipping children the user suspended).

### EffectiveDirtyStateParentUpdateType

Adds all four `IfParent*` flags to `currentDirtyState.ParentUpdateType`. Each is checked against the real
parent when the update runs, and the climb passes the same flags up, so ancestors that stack or size from
children hear about a change skipped on a hidden element.

## Upward Propagation

### GetIfShouldCallUpdateOnParent

Returns true if:
- Parent dimensions depend on children (`GetIfDimensionsDependOnChildren`)
- Parent stacks children (any non-Regular `ChildrenLayout`)
- Any sibling uses `Ratio` width/height

When true, the *originating* call delegates to the parent (flow step 3);
*propagated* climbs above it are additionally size-gated (see below).

### Upward propagation is incremental and size-gated

A change climbs one level so the parent can re-measure, then continues to the
grandparent and beyond **only while each level's own measured size or position
keeps changing**. When a level re-measures unchanged, propagation stops there —
its siblings and ancestors are not relaid out. That is what keeps a change inside
one item of an N-item stack from costing O(N-siblings).

The element that actually changed (the *originating* call) always notifies its
parent **unconditionally**, so the parent can re-measure; only the *propagated*
climbs above it are size-gated. The `gateClimbOnSizeChange` flag distinguishes
the two. Why the source can't gate itself:

> An element's own size delta is **not** the same as its contribution to a
> content-sized or stacking parent. The clearest case is **visibility**: size is
> unchanged when an element is hidden or shown, but its contribution flips (full
> extent ↔ 0). Only the parent, by re-measuring, can tell whether the change
> matters. Gating at the source on the source's own size would silently drop
> visibility-driven (and add/remove) changes, because the parent would never
> re-measure.

`RelativeToMaxParentOrChildren` always propagates regardless of its own delta:
its size is the max of its content and its parent, so a content change can be
masked by a (stale) parent size while it still feeds the parent's size.

### Visibility changes propagate through TWO paths

A visibility toggle is not one code path:
- Becoming **invisible**: the `Visible` setter updates the parent *directly*
  (when the parent stacks / auto-grids / depends on children), separately from
  `UpdateLayout`'s climb.
- Becoming **visible**: flows through `UpdateLayout`'s normal (originating) climb, unless the element is still suspended; then the setter updates the parent directly, as it does on hide (a Ratio sibling counts here too).
  The parent's layout skips its still-suspended children, so after a recursive suspend and a non-recursive resume, suspended siblings of the shown element keep stale positions until their own `ResumeLayout`.

Both rely on the parent re-measuring — see the contribution-vs-size trap above
for why the parent, not the toggled element, is the source of truth.

## Performance Patterns

| Optimization | What it avoids | Where |
|---|---|---|
| `_cachedSiblingIndex` | O(n) `IndexOf` per child → O(n²) total | `GetWhatToStackAfter` |
| `RefreshParentRowColumn` fast path | O(n) rescan per child → O(n²) total | `RefreshParentRowColumnDimensionForThis` |
| `UseFixedStackChildrenSize` | Iterating all children in `GetMaxCellHeight` | `UpdateLayout` step 6, `UpdateHeight` |
| `xOrY` parameter | Recalculating unchanged axis | Throughout |
| `childrenUpdateDepth` | Unbounded recursion | `UpdateChildren` decrements per level |
| `alreadyUpdated` set | Re-updating children measured in pre-pass | `UpdateChildren` |
| `LayOutChild` repeat-visit skip | 2^depth layouts for nested content-sized stacks | `UpdateChildren` (`ChildUpdates.cs`) |

### Diagnostic Counters

- `UpdateLayoutCallCount` — total layout calls (incremented after parent propagation check)
- `ChildrenUpdatingParentLayoutCalls` — times a child triggered parent relayout

### Verifying propagation (and a test-isolation caution)

`UpdateLayoutCallCount` deltas are how you assert propagation didn't over-fire:
build an N-item stack, make a change that *shouldn't* affect siblings, and assert
the delta stays flat as N grows rather than scaling. See the layout-call-count
tests in `LayoutUnitTests`.

If an engine change instead makes the **RaylibGum draw-call-count** tests fail,
suspect pre-existing **test isolation** before suspecting your change. Those tests
assert exact draw-call deltas and are sensitive to renderables leaked onto the
shared layer (an `AddToManagers` with no matching `RemoveFromManagers`); combined
with run-to-run test ordering that is flaky *on a clean tree too*. A layout change
can shift render batching just enough to change how often the latent flake trips —
confirm by running the suite repeatedly on the base branch before assuming you
caused it.

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in design →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.