The frame
The frame loop step by step, what each step reads and writes, the reactive flush, observation delivery, when the loop parks, what wakes it, and the counters to read.
zgui-runtime runs the frame loop. It turns platform events, timers and finished work into frames,
runs each frame's steps in a fixed order, and parks the loop when nothing is owed. The
architecture overview summarises the phases; this page
covers each one in implementation order.
Platform callbacks
A platform backend owns the event loop and drives an zgui_platform::AppHandler.
zgui_runtime::Runtime is the implementation zgui ships.
pub trait AppHandler: 'static {
fn surfaces_available(&mut self, cx: &dyn PlatformCx);
fn surfaces_lost(&mut self, cx: &dyn PlatformCx) { }
fn surface_event(&mut self, cx: &dyn PlatformCx, surface: SurfaceId, event: SurfaceEvent);
fn wake(&mut self, cx: &dyn PlatformCx, reason: WakeReason);
fn idle(&mut self, cx: &dyn PlatformCx) -> IdlePolicy { IdlePolicy::Block }
fn deadline_reached(&mut self, cx: &dyn PlatformCx) { }
fn shutting_down(&mut self, cx: &dyn PlatformCx) { }
}| Callback | What Runtime does (crates/zgui-runtime/src/app.rs) |
|---|---|
surfaces_available | Installs the clock and waker, then opens every requested window that has no surface. On resume, rebuilds suspended window views. |
surfaces_lost | Drops every frame pipeline and surface, keeping the window specifications. |
surface_event | RedrawRequested runs a frame if the window wants one and presentation pacing does not hold it. CloseRequested consults close callbacks; an accepted close or Destroyed removes the window and applies the exit policy. Other events are queued on the named window. |
wake | Handles the reason: redraw the named surfaces, drain application commands, route an accessibility action, resolve a clipboard read, and so on. |
idle | Computes the park and returns an IdlePolicy. Runs any maintenance that is already due. |
deadline_reached | Turns a reached deadline into a redraw request (or a maintenance pass) for the windows parked on it. |
shutting_down | Closes every window. |
A frame runs from exactly one place: SurfaceEvent::RedrawRequested, and only when
Window::wants_a_frame(now) is true and Window::holds_a_frame(now) is false. Everything else
(input, a wake, a reached deadline) requests a redraw and returns.
Frame steps
pub fn frame(&mut self, clock: &dyn Clock) -> FrameReportWindow::frame runs inside the window's own reactive owner
(crates/zgui-runtime/src/window/frame.rs). That is why free functions such as set_timeout,
focused_node and observation registration resolve the right window from a listener, an effect or
a timer callback.
The frame reads the clock once, at the top: clock.now() for deadlines and clock.timestamp()
for every timestamp it hands out. The first column below is the profiling mark each step emits. The
marks label the ZGUI_LATENCY trace and the inspector's Timeline tab.
| Mark | Step | Owner | Writes | Skipped when |
|---|---|---|---|---|
f.drain | Dispatch queued events | zgui-input, zgui-runtime | interaction state, listener writes, commands | nothing was queued |
f.timers | Fire due callbacks | zgui-runtime | whatever the callbacks write | nothing is due |
f.scroll | Advance running scrolls | zgui-scroll | offsets, moved containers | nothing is scrolling |
f.gestures | Advance held contacts | zgui-input | gesture readings, the long-press moment | no contact is held |
f.reconfigure | Point the renderer at the surface | zgui-render | render target, damage (exposed bands or full) | no reconfiguration is owed |
f.device | Rebuild the media device | zgui-style | what the cascade matches against | viewport, scale and scheme did not move |
f.raf | Run next-frame callbacks | zgui-runtime, zgui-view | whatever the callbacks write | none pending |
f.animate | Advance running animations | zgui-anim, zgui-style | animated values, restyle marks, events | nothing is running |
f.flush | Run posted closures, then ready tasks | zgui-reactive | signals; the document through the Dom seam | called re-entrantly |
f.commands | Carry out what listeners asked for | zgui-runtime | focus, selection, pointer capture, sheets | the queue is empty |
f.images | Settle finished image decodes | zgui-runtime | image content, damage | nothing arrived |
f.restyle | Cascade elements that owe one | zgui-style | computed styles, damage bits | nothing owes a restyle |
f.brushes | Rewrite moved text colours | zgui-text | brush slots | no colour moved |
f.boxes | Patch the box tree | zgui-layout | spliced subtrees, rewritten text runs | nothing structural is owed |
f.layout | Measure, arrange, compose fragments | zgui-layout, zgui-text | sizes, positions, fragments, hit regions, damage | measuring only; composing always runs |
f.image_demand | Size pending decodes to laid-out boxes | zgui-runtime | decode requests | nothing new to decode |
f.enter | Enter owed focus traps | zgui-input | focus | nothing owes an entry |
f.dispatch_scroll | Announce containers that moved | zgui-runtime | scroll events, then a flush | nothing moved |
f.observe | Deliver settled geometry | zgui-runtime, zgui-view | observed signals, then a flush and relayout | nothing is observing |
f.rehit | Re-test under a stationary pointer | zgui-input | hover state, crossing events | the hit index did not change |
f.publish_brushes | Copy brushes into the display list | zgui-runtime | scene.text_paints | nothing changed |
f.caret | Plan the caret | zgui-runtime | the caret highlight and its damage | nothing editable has focus |
f.embed | Bind embedded surfaces to their boxes | zgui-runtime | attachments, damage | nothing is embedded |
f.paint | Grow damage, emit, draw and present | zgui-paint, renderer | display list, composed target, surface | see below |
f.a11y | Publish the accessibility tree | zgui-a11y | a tree update | nothing is listening or owed |
f.recycle | Recycle arenas, decide the park | zgui-runtime | arena slots, at most one redraw request | — |
Inside f.paint, p.expand grows the damage over fragments that read outside their ink, p.emit
runs the emit walk, p.upload flushes
atlas uploads, and the renderer's own marks follow:
| Mark | Work |
|---|---|
r.tables | Read the scene-table journals and flatten changed clip, paint, stop and coordinate-system slots. |
r.vectors | Plan the general vector passes and rasterise round 0. |
r.plan | Plan render passes, targets, mark bins and per-draw blocks. |
r.encoder | Create the frame's command encoder. |
r.shift | Copy the valid pixels of an accepted scroll shift. Only present when one was accepted. |
r.buffers | Upload changed table ranges, arena contents, transient instances and remaps. |
r.record | Record passes, submitting between vector rounds. Notes how many upload chunks were allocated, if any. |
acq.in, sub.out, pres.out | Acquire the surface, submit, present. |
A long r.tables is CPU preparation. A long r.buffers with no chunk allocation is copying and
buffer growth; a non-zero allocation count means the staging working set grew or the GPU is behind.
See the renderer for the full order inside draw.
Rules for the early steps:
- Pointer moves are coalesced on arrival. A move queued behind a move of the same pointer
replaces it. The earlier positions are kept as
PointerSamplevalues for handlers that want the whole path. Any other event is a barrier, so dispatch order never changes.PointerMovesCoalescedcounts folds. f.raftakes its whole batch before calling any callback, so a callback that requests another frame runs next frame. Callbacks run beforef.animateandf.flush, so their writes settle in the frame that received them.- Geometry is delivered before painting, so a popover that measures itself and moves is painted in its final place in the frame it opens.
- The re-hit test runs only when the hit index changed. A dropdown that opens under a stationary
cursor is still hovered, and a frame that moved nothing tests nothing (
HitRetests).
The frame returns what it did:
pub struct FrameReport {
pub outcome: FrameOutcome,
pub needs_another_frame: bool,
pub restyled: usize,
pub timers_fired: usize,
pub animated: usize,
}outcome.retires_damage() decides whether the window's damage is cleared. It is false only when
nothing was recorded (Unconfigured, Unacquired, DeviceUnavailable). A frame that composed
everything and then failed to acquire a surface has still written the persistent target, so its
damage is retired. See What a frame reports.
The reactive flush
The flush is the only point where the reactive layer runs. zgui_reactive::flush() first drains closures
posted with Ui::post, then polls ready tasks until they stall. Writing a signal outside a flush only
marks observers.
Three calls in run_frame decide which work the flush answers:
self.gate.requests_serviced(), immediately before the flush. Anything that asked for a frame up to here (a listener in this frame's dispatch, a timer callback, a task that finished) is answered by this flush. Placing it after the flush would lose requests that arrive in between.zgui_reactive::flush(). Effects run and mutate the document through theDomseam.document.changes_serviced(), after commands and image settling. Everything above produces changes; everything below consumes them. Without this call, a change made during this frame's own dispatch would still be flagged at the end and cause a second frame that damages nothing.
The restyle runs after that call, so a listener's write is styled, laid out and painted in the same
frame that dispatched the event. A click (move, press, release) is shown by one frame per event, not
two (a_click_runs_one_frame_for_each_event_and_not_two, crates/zgui/tests/wall_clock.rs).
Other flush points
Each extra flush exists because something later in the same frame reads the document.
| Site | Why | Bound |
|---|---|---|
settle_between_events (window/input.rs) | A press that opens a dialog must have built it before the next queued key is routed. | Once per queued event except the last |
run_frame | The frame's own reactive work. | Once |
dispatch_scroll (window/scroll/mod.rs) | A virtualised list must not render the rows it had before the scroll. | Once |
deliver_observations (window/observe.rs) | A popover measures itself, then moves; the move must be painted in the same frame. | Two passes |
The scroll and observation flushes call requests_serviced() first, so wakes raised by the handlers
they run are answered by that flush instead of causing another frame; the observation pass also marks
the document changes it made as serviced. A flush called from inside an effect is a no-op.
Iteration limits
Polling until nothing is ready never terminates when two effects write each other's sources.
zgui-reactive bounds it in two ways:
- Per task (
executor/budget.rs):BUDGETis 32 polls per task per flush in debug builds and 8 in release. A task that reaches it is set aside with its waker kept, the cycle is logged once aterrorlevel naming the spawn site, and the task is re-woken after the flush, which setsFlushOutcome::needs_another_frame. - Per flush (
executor/frame.rs): the pool is polled up toMAX_ROUNDS = 3times, to catch a wake that lands between a stall and the poll's return. A wake still arriving after the third round is left to the next frame.
A dependency cycle therefore costs a logged error and a presented frame, repeated each frame, not a hang. An ordinary task is polled once or twice per flush.
Observation delivery
deliver_observations is the only path from layout back into views. Popovers, virtualised lists and
scroll thumbs need it: they read a measurement, and what they do in response (move, resize, render
other rows) changes that measurement.
- Skipped whole when nothing observes. One emptiness test on the registry, not a walk.
- Only changed values are delivered, each on its own. A view watching the border box, the border
size (
NodeRef::observe_border_size, size only), the content size or the scroll position is told only when that quantity changed. Re-delivering an equal value would re-run effects and stop a document with a popover from ever settling. - At most two passes. Each pass delivers, flushes, then restyles and lays out again. After the
second pass, the runtime measures once more without delivering. If a watched value still moved,
it logs a warning, bumps
ObservationsTruncated, and asks for another frame, which delivers the remainder. A chain that settles in exactly two passes owes nothing.ObservationPassescounts passes.
Parking
Parking means the loop blocks in the windowing system and uses no CPU. The decision is
Runtime::idle:
fn idle(&mut self, cx: &dyn PlatformCx) -> IdlePolicy {
let now = cx.clock().now();
let mut policy = IdlePolicy::Block;
self.parked.clear();
for window in &mut self.windows {
let Some(deadline) = window.scheduled_deadline(now) else { continue };
if deadline.at > now {
self.parked.push((window.surface().id(), deadline.at, deadline.kind));
policy = policy.merge(IdlePolicy::BlockUntil(deadline.at));
} else {
match deadline.kind {
DeadlineKind::Render => window.request_frame(),
DeadlineKind::Maintenance => window.maintain(cx.clock().timestamp()),
}
}
}
policy
}| Condition | Policy |
|---|---|
| No window has a deadline | IdlePolicy::Block: wait for the windowing system. |
| Some deadline is in the future | IdlePolicy::BlockUntil(earliest). |
| A deadline has already passed | Run it now (request the frame, or do the maintenance) instead of installing it. |
The runtime never returns IdlePolicy::Spin.
The park logic prevents two failures. Both look the same from outside: nothing on screen changes.
- A stall. A deadline wakes the loop but nothing turns it into a redraw.
Runtime::deadline_reachedprevents this. It readsself.parkedinstead of recomputing the deadlines, because recomputing would return the next deadline and find nothing reached. - A spin. An already-passed deadline is installed; the platform finds no time remaining,
reports it reached, and repeats without running a frame. The
elsebranch above prevents this.
The headless backend asserts resumes <= frames + 1 after every turn
(Harness::assert_park_invariant, crates/zgui-platform-headless/src/harness.rs).
A settled application costs nothing: in docs/performance.md, idle.frames is 0.00 and
idle.turn is 0.07 µs. The regression test is a_settled_application_runs_no_frames_at_all.
Deadline sources
Window::scheduled_deadline merges seven render sources and one maintenance source; the earliest
wins.
| Source | Where it comes from | Dropped while occluded or starved |
|---|---|---|
| Next animation tick, or the first pending frame callback | AnimationCadence::due() | yes |
| Earliest scheduled callback | Timers::peek_for(document, now) | no |
| A held contact becoming a long press | Window::gesture_deadline() | no |
| A deferred configure becoming worth answering | ResizePace::due(interval) | no |
| Next caret blink | Carets::next_flip(now) | yes |
| Release of a presentation-paced frame | PresentPace::due() | no |
| A renderer-requested retry, or the starvation probe | retry_after | while occluded only |
| Idle maintenance | maintenance_due | no |
Every source is a fixed moment, never "now plus an interval". scheduled_deadline is called on
every loop turn, so a relative deadline would be pushed back by every unrelated wake. The animation
moment comes from the phase the last frame left, the resize moment from the last answered configure,
the blink from the caret's own origin.
While a reconfiguration is owed but not yet visible, wants_a_frame refuses every frame; while
presentation pacing holds a frame, holds_a_frame does the same. So render deadlines are floored to
those gates: a wake before them would be refused, recomputed and repeated.
A display-paced surface paces through blocking swap-chain acquisition, and PresentPace uses the
measured wait to release later work near the next refresh. A platform-paced surface (native Wayland)
uses compositor frame callbacks and normally has no acquisition wait. The surface's measured
presentation interval, when known, takes precedence over its reported refresh rate.
Idle maintenance
At the end of every normal frame, maintenance_due is set to two seconds later
(MAINTENANCE_DELAY). A later frame pushes it back, so an active window never trims and a parked
window gets exactly one maintenance wake. That wake runs Window::maintain, which does not lay
out, paint, draw or present:
Renderer::release_idle_resources()frees unused group targets, scroll scratch, completed upload chunks, persistent arenas, retained remap and table buffers, and the vector rasteriser's reproducible scratch;- paint records are re-noted, so the next drawn frame restores GPU residency in one pass instead of uploading each chunk transiently;
- embedded surfaces trim their working memory.
A test that asserts a silent loop must step past this one wake.
Wake sources
If a wake route is missing, the window does not crash; it silently stops responding to one kind of event. These are the routes:
| Source | Route |
|---|---|
| Input and surface events | Runtime::surface_event → Window::queue → Window::request_frame |
| A document change during a frame | Document::end_frame, FrameGate, the frame's own end-of-frame request |
| Work finishing elsewhere (tasks, decodes, cross-thread signal writes) | RuntimeWaker::wake → Waker::wake → WakeReason::ReactiveWork |
| A deadline (timer, animation, gesture, resize, caret, present hold, retry, maintenance) | IdlePolicy::BlockUntil → Runtime::deadline_reached |
| A frame owing more (unfinished reactive work, undelivered observations, deferred CPU vector layers, new image demand) | request_frame at the end of the frame |
| Application and desktop requests | The other WakeReason variants, below |
FrameGate
pub struct FrameGate { /* AtomicBool in_frame, AtomicBool another_frame */ }
impl FrameGate {
pub fn request(&self) -> bool; // true means deferred into the running frame
pub fn requests_serviced(&self);
pub fn begin_frame(&self);
pub fn end_frame(&self) -> bool; // takes `another_frame`
// in_frame(), needs_another_frame()
}Two atomics, because wakes arrive from any thread. A wake raised outside a frame goes to the platform.
A wake raised inside one sets another_frame and returns; a thousand in-frame wakes become one owed
frame (crates/zgui-runtime/src/wake.rs).
RuntimeWaker
RuntimeWaker holds an Arc<dyn zgui_platform::Waker>, the shared FrameGate, and the set of
SurfaceIds it wakes. Wakes are scoped to surfaces so that an image decoding for one window does
not redraw another. Runtime::open_live_window calls waker.owns(surface.id()) before the view is
built; closing a window calls disowns, so later wakes for it go nowhere.
zgui_platform::Waker is the only object in the platform contract that crosses threads. A signal
written on a worker reaches it synchronously, inside the write.
Wake reasons
#[non_exhaustive]
pub enum WakeReason {
ReactiveWork { surfaces: Box<[SurfaceId]> },
A11yAction(accesskit::ActionRequest),
A11yTreeRequested(SurfaceId),
ClipboardRead { serial: ClipboardSerial, result: Result<ClipboardData, ClipboardError> },
AppWork,
DeviceLost,
ColorSchemeChanged,
App(AppEvent),
SurfaceStateChanged(SurfaceId),
}| Reason | What the runtime does |
|---|---|
ReactiveWork | Requests frames on the named surfaces. |
A11yTreeRequested | Builds the full accessibility tree; nothing is dirty for a dirty check to notice. |
A11yAction | Offers the action to each window until one owns the node. |
ClipboardRead | Runs the callback stored under the serial; it may queue another clipboard operation, which is drained in the same turn. |
AppWork | Carries out deferred window opens and closes, quits, and clipboard requests. Not surface-scoped, because it creates and destroys surfaces. |
DeviceLost | Requests frames so each renderer can rebuild. |
ColorSchemeChanged | Reads cx.color_scheme() and pushes it into every window before requesting frames; a frame alone would rebuild an identical media device. |
App(AppEvent) | Desktop requests for the whole application: Reopen, an application-menu Menu action, or a menu Role replayed as its shortcut into the focused window. |
SurfaceStateChanged | Re-reads a window's state once the desktop finishes a change such as leaving full screen. |
Frame requests
Requesting a frame is idempotent:
pub fn request_frame(&self) {
if !self.awaiting_frame.replace(true) {
zgui_profile::latency::mark("req.redraw");
self.surface.request_redraw();
}
}The flag is cleared by frame_started() and by declined_a_frame(). A refused frame must also clear
the request; otherwise the flag stays set, no later request reaches the platform, and the window
stops redrawing.
An occluded frame never requests another at its end
(if needs_another_frame && outcome != Skipped(Occluded)). Honouring it would run a hidden window's
whole pipeline at full rate.
After a timed-out acquisition the window is starved: animation, frame-callback and caret deadlines stop, and a probe is scheduled after 1 second, doubling to 16 seconds. Input, focus gain, resize, a scale change or becoming visible clears it. A presented frame resets the backoff.
Timers and the clock
There is no timer thread. Timers are one more deadline source for the park.
impl Timers {
pub fn schedule(&mut self, document: DocumentId, now: Instant, after: Duration,
repeat: Repeat, callback: Rc<dyn Fn()>) -> TimerId;
pub fn cancel(&mut self, id: TimerId);
pub fn peek(&mut self) -> Option<(Instant, DocumentId)>;
pub fn peek_for(&self, document: DocumentId, now: Instant) -> Option<Instant>;
pub fn due(&mut self, document: DocumentId, now: Instant) -> Vec<Rc<dyn Fn()>>;
pub fn forget(&mut self, document: DocumentId);
}- One heap serves every window; entries carry their
DocumentId, and a window's frame takes only its own. - Ordered by deadline, then
TimerId, so simultaneous entries fire in registration order. - Cancellation is lazy.
peekdrops cancelled entries from the front, so a tooltip timer scheduled and cancelled on every pointer move costs no heap rebuild. - A repeating entry re-arms from
now, not from the missed deadline: a loop blocked for a second fires a 16 ms interval once, not sixty times. - A pending entry marks no node. A callback that writes nothing costs a frame that skips every stage from the restyle on.
Callbacks fire at f.timers, before the flush, each inside
zgui_reactive::enter_non_reactive_zone(), so reading a signal does not subscribe the current scope.
pub trait Clock: Send + Sync + 'static {
fn now(&self) -> Instant;
fn origin(&self) -> Instant;
fn timestamp(&self) -> Timestamp { /* now - origin */ }
}Nothing in zgui calls the system clock directly. Timers, animations and the park ask the platform, so a
test backend can move a zgui_platform::VirtualClock by hand and run a five-second animation in a
microsecond. PlatformCx::clock() returns Arc<dyn Clock> rather than a reading, so a caller that
keeps it always reads the current time.
Animation pacing
An animating window does not request frames itself, because that would run frames as fast as the machine allows. Instead, each frame leaves a deadline, and the park wakes the loop at that moment.
impl AnimationCadence {
pub const fn parked() -> Self;
pub const fn due(&self) -> Option<Instant>;
pub const fn park(&mut self);
pub fn advance(&mut self, now: Instant, interval: Duration);
}The deadline is a phase: one refresh interval after the moment the last frame was due, not after the last time the loop woke. "Now plus an interval" would be pushed back by every unrelated wake; two such wakes per interval halve the frame rate with no visible error except a choppier motion.
- A late frame catches up without bursting.
advancesteps the phase by whole intervals until it is in the future. - A window far behind re-anchors. Past
MAX_CATCH_UP = 8missed intervals, the phase restarts from now.
pace_animations(now) runs at the end of the frame, against the moment the frame was for, after the
cascade (which starts keyframe animations). An occluded or settled window calls park() and leaves
no deadline.
The interval comes from the surface's output, falling back to 60 Hz when the rate is unknown or zero
(zgui_platform::monitor::refresh_interval). A window dragged to another output is paced by that
output from the next frame.
Cadence tests
cargo xtask cadence runs anim_cadence and scroll_cadence in crates/zgui-runtime/tests/. Each
mounts a real window on the headless platform, gives its output a stated refresh rate, and drives a
virtual clock in exact intervals. anim_cadence checks that:
- an animation gets exactly one frame per refresh at 60, 75 and 240 Hz (the 75 Hz interval is not a whole number of milliseconds, so it catches rounding);
- an unrelated wake does not move the next tick;
- a finished animation leaves no deadline and draws nothing for ten seconds.
scroll_cadence counts composed positions that differ rather than frames, because an undamaged frame
is never presented. What reaches a real display is checked by hand:
cargo run --release -p zgui-bench --bin anim-cadence -- dev.zgui.anim 10
cargo run --release -p zgui-bench --bin scroll-cadence -- dev.zgui.scroll bottomCold start
The first frame of a window fills every cache for the first time.
- The surface is created hidden. An accessibility adapter must be attached before a surface is first shown.
- The renderer is built from the factory against the surface's extent and scale. No adapter
means
AppError::GpuUnavailable, never a silent fallback. - The waker is told it owns the surface, before the view is built.
Window::openruns. It creates the document, layout store, scroller and style engine, installs the application sheet atSheetOrigin::Author, opens aMountedscope, callszgui_view::provide_host, and builds and mounts the view. The window starts with full damage and a reconfiguration owed.- The desktop colour scheme is pushed in, so the first frame is styled in the right scheme.
- The first frame runs. Every box is built by the full-build path (
BoxTreeBuildscounts these), every paragraph is shaped, every glyph rasterised. - The surface is shown on the first
Presentedoutcome, so the window never flashes empty. A hidden macOS layer may refuse a drawable and report the frame as occluded; the runtime then shows the surface (the target already holds the frame) and requests the presenting frame at once.
docs/performance.md gives cold.first_frame for the 1 851-box gallery a 250 ms budget. It was
measured at 102–111 ms headless and 216–247 ms on screen with a device. The headless measurement
leaves out the graphics device, because pipeline compilation time varies more between drivers than
everything else combined. That first frame emits 1 101 primitives and culls 5 224.
Worker threads
Style and layout use worker pools sized to the machine's parallelism. A host that shares the machine, such as a game engine, can limit them:
let app = zgui::app().with_style_threads(1).with_layout_threads(1);0 and 1 run that stage on the frame thread with no pool. ZGUI_STYLE_THREADS and
ZGUI_LAYOUT_THREADS override the values.
More than one window
Runtime keeps two sets. live holds every window the application still wants, including one that
temporarily has no surface. windows holds the frame pipelines for surfaces that exist now. A
platform suspension clears the second and keeps the first; resume rebuilds each window from its
retained view factory.
Opening and closing are deferred. A listener runs inside a borrowed frame where no surface can be
created, so use_windows().open mints a WindowId, returns a pending WindowHandle, queues the
specification and wakes the loop with WakeReason::AppWork. The next handler turn creates the surface.
Closing a window unmounts its view and closes the surface the same way.
Everything is scoped to the right window:
- each window has its own
DocumentId, and timers are keyed by it; RuntimeWakerowns the open surfaces and drops one when it closes;idlemerges one deadline per window, anddeadline_reachedkeeps those not yet reached;- accessibility actions go to the window that owns the node.
The reactive ready queue is thread-wide, so an effect run in one window's frame can change another
window's document. After each flush, sweep_other_windows compares the other documents' revisions
and requests frames only for those that were written.
See Windows for the public API.
FrameProbe
A window's per-frame state exists only until the next frame overwrites it. A FrameProbe reads it
after each frame:
pub trait FrameProbe {
fn frame_ended(&self, window: &Window);
fn describe(&self) -> &str { "a frame probe" }
}- Called once, last, on every frame, with the window as the frame left it: the scene, the damage it answered, the layout, the renderer's report.
- Takes
&selfbecause the window is borrowed for the call. A probe keeps state in a cell or a signal, which also lets one probe serve several windows. - Installed with
App::with_probe(Rc<dyn FrameProbe>). One probe per application. zgui-devtoolsis the main consumer.
The probe cannot change the window or refuse a frame, so it cannot disturb what it measures.
use std::cell::Cell;
use std::rc::Rc;
use zgui::prelude::*;
use zgui::runtime::{FrameProbe, Window};
/// Counts the frames the window ran.
#[derive(Default)]
struct Frames(Cell<u64>);
impl FrameProbe for Frames {
fn frame_ended(&self, _window: &Window) {
self.0.set(self.0.get() + 1);
}
}
fn main() -> Result<(), zgui::Error> {
app()
.with_probe(Rc::new(Frames::default()))
.run(|| view! { column() })
}HostBinding
An embedded script engine needs hooks at specific points of the frame:
pub trait HostBinding {
fn before_dispatch(&mut self, target: Option<NodeId>, event: EventKind) -> bool { true }
fn checkpoint(&mut self) { }
fn before_paint(&mut self, timestamp: zgui_vocab::Timestamp) { }
fn shutting_down(&mut self) { }
}| Hook | Called at | Use |
|---|---|---|
before_dispatch | In f.drain, once per event, before the first listener | Intercept an event for the engine's own dispatcher; false cancels dispatch. |
checkpoint | Right after the frame's flush | Drain queued engine work. Direct document changes reach this frame's restyle; signal writes need a later flush. |
before_paint | After layout and observation delivery, before emission | Animation-frame callbacks. Changes are processed next frame. |
shutting_down | First line of Window::close | Teardown. |
NoBinding implements every default and compiles to nothing.
Window::install_binding is the only entry point. There is no App::with_binding, so reaching it
means building through zgui_runtime::App::into_handler and driving the Runtime yourself.
Example: a click
A click is three platform events (move, press, release) and three frames. Take one element:
use zgui::prelude::*;
#[component]
fn Swatch() -> impl IntoView {
let (picked, set_picked) = signal(false);
view! {
control(
class = "swatch",
class:picked = move || picked.get(),
on:click = move |_| set_picked.update(|on| *on = !*on),
) {
"pick"
}
}
}
const SHEET: &str = css!(
".swatch { padding: 8px 20px; border-radius: 8px; background: #232733 }
.swatch.picked { background: #2b6cff }"
);The release frame does the work:
- The platform reports a pointer release.
Runtime::surface_eventcallswindow.queue(event), which queues the input and callsrequest_frame. - The loop delivers
RedrawRequested. No reconfiguration is owed, sowindow.frame(clock)runs. f.drain. The router hit-tests the release against the previous frame's hit index and builds the capture, target and bubble path. No listener handles the release, so the framework defaultFrameworkDefault::Activate(node)runs. Only the primary button activates. The syntheticClickkeeps the release's button and modifiers and travels the same path a real one would. (A second activation of the same element soon after dispatchesdouble_clickafter the secondclick.) Theon:clickbody callsset_picked.update(..), which marks observers and runs none of them; its wake is folded byFrameGate::requestbecause a frame is in flight.f.timersthroughf.animateeach return on an emptiness test.requests_serviced(), thenf.flush. The render effect readingpickedruns once and adds the class through theDomseam, marking the element as owing a restyle.f.commands,changes_serviced(). No commands. The change is declared answered by this frame.f.restylecascades exactly one element. A background colour is repaint damage, not relayout. The new style is written onto the element's existing box.f.brushes,f.boxes. Nothing to do.f.layout. Measuring is skipped because no size changed. Composing always runs, and the fragment diff puts the swatch's rectangle into the damage.f.enterthroughf.caret. Emptiness tests. The hit index did not change, so no re-hit.f.paint. The damage is grown over anything that reads outside its ink. The emit walk skips every subtree the damage misses, replays recorded chunks where nothing changed, and re-encodes the swatch. The scene is finished, atlas uploads flushed, andrenderer.drawscissors to the same rectangle; everything outside keeps last frame's pixels.f.a11y,f.recycle. Nothing to publish.document.end_frame(),gate.end_frame()and the flush all report nothing owed.- The park. Nothing animates, no timer is set, no caret blinks: only the maintenance deadline
remains, two seconds out. After it runs once,
IdlePolicy::Block.
The click places and rasterises 0 glyphs, because the damage reaches one swatch and no text
(a_click_rasterises_no_glyph_and_stays_far_inside_one_frame, crates/zgui/tests/wall_clock.rs).
kitchen.click in docs/performance.md measures one class toggled on one element of a 1 851-box
document in tens of microseconds.
Counters
| Counter | Meaning |
|---|---|
frames_drawn | Frames whose work reached the renderer. Stays flat on a still document. |
box_tree_builds | Whole box-tree builds, including the first. Any after the first means a frame paid for the whole window. |
observation_passes, observations_truncated | Delivery passes, and deliveries still changing when the budget ran out. |
pointer_moves_coalesced | Pointer moves folded into a later move. |
hit_retests | Frames that re-tested under a stationary pointer. |
damage_px | Device pixels redrawn. |
vector_route_*, vector_backend_built | How vector shapes were drawn, and whether the general rasteriser was built (see vector routes). |
Next
The document
The node arena the frame reads and writes, and the seams around it.
Invalidation
The obligation bits every step of the frame retires, and how damage merges.
Reactive internals
How the graph is stored, and what the flush actually walks.
The platform layer
Surface, Clock, Waker, and what a second backend must not do.
Architecture overview
The stages of the zgui pipeline, what one frame does, the design principles behind them, how the crates are layered, and a map of the architecture pages.
The document
The zgui-dom node arena, stable addresses, the two sibling chains, interned names, lock-free parallel reads, the Dom and ViewHost seams, mutation batches, removed nodes, and the document-language seams.