zgui
Architecture

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) { }
}
CallbackWhat Runtime does (crates/zgui-runtime/src/app.rs)
surfaces_availableInstalls the clock and waker, then opens every requested window that has no surface. On resume, rebuilds suspended window views.
surfaces_lostDrops every frame pipeline and surface, keeping the window specifications.
surface_eventRedrawRequested 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.
wakeHandles the reason: redraw the named surfaces, drain application commands, route an accessibility action, resolve a clipboard read, and so on.
idleComputes the park and returns an IdlePolicy. Runs any maintenance that is already due.
deadline_reachedTurns a reached deadline into a redraw request (or a maintenance pass) for the windows parked on it.
shutting_downCloses 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) -> FrameReport

Window::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.

MarkStepOwnerWritesSkipped when
f.drainDispatch queued eventszgui-input, zgui-runtimeinteraction state, listener writes, commandsnothing was queued
f.timersFire due callbackszgui-runtimewhatever the callbacks writenothing is due
f.scrollAdvance running scrollszgui-scrolloffsets, moved containersnothing is scrolling
f.gesturesAdvance held contactszgui-inputgesture readings, the long-press momentno contact is held
f.reconfigurePoint the renderer at the surfacezgui-renderrender target, damage (exposed bands or full)no reconfiguration is owed
f.deviceRebuild the media devicezgui-stylewhat the cascade matches againstviewport, scale and scheme did not move
f.rafRun next-frame callbackszgui-runtime, zgui-viewwhatever the callbacks writenone pending
f.animateAdvance running animationszgui-anim, zgui-styleanimated values, restyle marks, eventsnothing is running
f.flushRun posted closures, then ready taskszgui-reactivesignals; the document through the Dom seamcalled re-entrantly
f.commandsCarry out what listeners asked forzgui-runtimefocus, selection, pointer capture, sheetsthe queue is empty
f.imagesSettle finished image decodeszgui-runtimeimage content, damagenothing arrived
f.restyleCascade elements that owe onezgui-stylecomputed styles, damage bitsnothing owes a restyle
f.brushesRewrite moved text colourszgui-textbrush slotsno colour moved
f.boxesPatch the box treezgui-layoutspliced subtrees, rewritten text runsnothing structural is owed
f.layoutMeasure, arrange, compose fragmentszgui-layout, zgui-textsizes, positions, fragments, hit regions, damagemeasuring only; composing always runs
f.image_demandSize pending decodes to laid-out boxeszgui-runtimedecode requestsnothing new to decode
f.enterEnter owed focus trapszgui-inputfocusnothing owes an entry
f.dispatch_scrollAnnounce containers that movedzgui-runtimescroll events, then a flushnothing moved
f.observeDeliver settled geometryzgui-runtime, zgui-viewobserved signals, then a flush and relayoutnothing is observing
f.rehitRe-test under a stationary pointerzgui-inputhover state, crossing eventsthe hit index did not change
f.publish_brushesCopy brushes into the display listzgui-runtimescene.text_paintsnothing changed
f.caretPlan the caretzgui-runtimethe caret highlight and its damagenothing editable has focus
f.embedBind embedded surfaces to their boxeszgui-runtimeattachments, damagenothing is embedded
f.paintGrow damage, emit, draw and presentzgui-paint, rendererdisplay list, composed target, surfacesee below
f.a11yPublish the accessibility treezgui-a11ya tree updatenothing is listening or owed
f.recycleRecycle arenas, decide the parkzgui-runtimearena 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:

MarkWork
r.tablesRead the scene-table journals and flatten changed clip, paint, stop and coordinate-system slots.
r.vectorsPlan the general vector passes and rasterise round 0.
r.planPlan render passes, targets, mark bins and per-draw blocks.
r.encoderCreate the frame's command encoder.
r.shiftCopy the valid pixels of an accepted scroll shift. Only present when one was accepted.
r.buffersUpload changed table ranges, arena contents, transient instances and remaps.
r.recordRecord passes, submitting between vector rounds. Notes how many upload chunks were allocated, if any.
acq.in, sub.out, pres.outAcquire 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 PointerSample values for handlers that want the whole path. Any other event is a barrier, so dispatch order never changes. PointerMovesCoalesced counts folds.
  • f.raf takes its whole batch before calling any callback, so a callback that requests another frame runs next frame. Callbacks run before f.animate and f.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:

  1. 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.
  2. zgui_reactive::flush(). Effects run and mutate the document through the Dom seam.
  3. 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.

SiteWhyBound
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_frameThe 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): BUDGET is 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 at error level naming the spawn site, and the task is re-woken after the flush, which sets FlushOutcome::needs_another_frame.
  • Per flush (executor/frame.rs): the pool is polled up to MAX_ROUNDS = 3 times, 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. ObservationPasses counts 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
}
ConditionPolicy
No window has a deadlineIdlePolicy::Block: wait for the windowing system.
Some deadline is in the futureIdlePolicy::BlockUntil(earliest).
A deadline has already passedRun 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_reached prevents this. It reads self.parked instead 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 else branch 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.

SourceWhere it comes fromDropped while occluded or starved
Next animation tick, or the first pending frame callbackAnimationCadence::due()yes
Earliest scheduled callbackTimers::peek_for(document, now)no
A held contact becoming a long pressWindow::gesture_deadline()no
A deferred configure becoming worth answeringResizePace::due(interval)no
Next caret blinkCarets::next_flip(now)yes
Release of a presentation-paced framePresentPace::due()no
A renderer-requested retry, or the starvation proberetry_afterwhile occluded only
Idle maintenancemaintenance_dueno

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:

SourceRoute
Input and surface eventsRuntime::surface_event → Window::queue → Window::request_frame
A document change during a frameDocument::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 requestsThe 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),
}
ReasonWhat the runtime does
ReactiveWorkRequests frames on the named surfaces.
A11yTreeRequestedBuilds the full accessibility tree; nothing is dirty for a dirty check to notice.
A11yActionOffers the action to each window until one owns the node.
ClipboardReadRuns the callback stored under the serial; it may queue another clipboard operation, which is drained in the same turn.
AppWorkCarries out deferred window opens and closes, quits, and clipboard requests. Not surface-scoped, because it creates and destroys surfaces.
DeviceLostRequests frames so each renderer can rebuild.
ColorSchemeChangedReads 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.
SurfaceStateChangedRe-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. peek drops 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. advance steps the phase by whole intervals until it is in the future.
  • A window far behind re-anchors. Past MAX_CATCH_UP = 8 missed 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:

  1. 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);
  2. an unrelated wake does not move the next tick;
  3. 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 bottom

Cold start

The first frame of a window fills every cache for the first time.

  1. The surface is created hidden. An accessibility adapter must be attached before a surface is first shown.
  2. The renderer is built from the factory against the surface's extent and scale. No adapter means AppError::GpuUnavailable, never a silent fallback.
  3. The waker is told it owns the surface, before the view is built.
  4. Window::open runs. It creates the document, layout store, scroller and style engine, installs the application sheet at SheetOrigin::Author, opens a Mounted scope, calls zgui_view::provide_host, and builds and mounts the view. The window starts with full damage and a reconfiguration owed.
  5. The desktop colour scheme is pushed in, so the first frame is styled in the right scheme.
  6. The first frame runs. Every box is built by the full-build path (BoxTreeBuilds counts these), every paragraph is shaped, every glyph rasterised.
  7. The surface is shown on the first Presented outcome, 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;
  • RuntimeWaker owns the open surfaces and drops one when it closes;
  • idle merges one deadline per window, and deadline_reached keeps 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 &self because 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-devtools is 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) { }
}
HookCalled atUse
before_dispatchIn f.drain, once per event, before the first listenerIntercept an event for the engine's own dispatcher; false cancels dispatch.
checkpointRight after the frame's flushDrain queued engine work. Direct document changes reach this frame's restyle; signal writes need a later flush.
before_paintAfter layout and observation delivery, before emissionAnimation-frame callbacks. Changes are processed next frame.
shutting_downFirst line of Window::closeTeardown.

NoBinding implements every default and compiles to nothing.

Partial· Installed, and not surfaced through the umbrella crate.

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:

  1. The platform reports a pointer release. Runtime::surface_event calls window.queue(event), which queues the input and calls request_frame.
  2. The loop delivers RedrawRequested. No reconfiguration is owed, so window.frame(clock) runs.
  3. 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 default FrameworkDefault::Activate(node) runs. Only the primary button activates. The synthetic Click keeps the release's button and modifiers and travels the same path a real one would. (A second activation of the same element soon after dispatches double_click after the second click.) The on:click body calls set_picked.update(..), which marks observers and runs none of them; its wake is folded by FrameGate::request because a frame is in flight.
  4. f.timers through f.animate each return on an emptiness test.
  5. requests_serviced(), then f.flush. The render effect reading picked runs once and adds the class through the Dom seam, marking the element as owing a restyle.
  6. f.commands, changes_serviced(). No commands. The change is declared answered by this frame.
  7. f.restyle cascades exactly one element. A background colour is repaint damage, not relayout. The new style is written onto the element's existing box.
  8. f.brushes, f.boxes. Nothing to do.
  9. f.layout. Measuring is skipped because no size changed. Composing always runs, and the fragment diff puts the swatch's rectangle into the damage.
  10. f.enter through f.caret. Emptiness tests. The hit index did not change, so no re-hit.
  11. 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, and renderer.draw scissors to the same rectangle; everything outside keeps last frame's pixels.
  12. f.a11y, f.recycle. Nothing to publish. document.end_frame(), gate.end_frame() and the flush all report nothing owed.
  13. 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

CounterMeaning
frames_drawnFrames whose work reached the renderer. Stays flat on a still document.
box_tree_buildsWhole box-tree builds, including the first. Any after the first means a frame paid for the whole window.
observation_passes, observations_truncatedDelivery passes, and deliveries still changing when the budget ran out.
pointer_moves_coalescedPointer moves folded into a later move.
hit_retestsFrames that re-tested under a stationary pointer.
damage_pxDevice pixels redrawn.
vector_route_*, vector_backend_builtHow vector shapes were drawn, and whether the general rasteriser was built (see vector routes).

Next

On this page