Devtools
Open and use the zgui-devtools inspector: the element tree, computed style, frame counters, timeline, reactive scopes, style support and memory, plus writing a frame probe of your own.
zgui-devtools is an inspector docked beside your window. Use it to find an element and see its box
and computed style, and to see what the last frame did, where its time went, and how much memory
the renderer holds.
Add the inspector
[dependencies]
zgui = "0.1"
zgui-devtools = "0.1"Create one DevTools, pass its probe to the app, and wrap the root view in Inspector:
use zgui::prelude::*;
use zgui_devtools::{DevTools, Inspector, InspectorProps};
fn main() -> Result<(), zgui::Error> {
let tools = DevTools::new();
app()
.with_probe(tools.probe())
.run(move || view! { Inspector(tools = tools) {Body()} })
}| Part | Role |
|---|---|
Inspector around the root view | draws the panel and handles its shortcuts |
tools.probe() passed to with_probe | reads each finished frame; only a probe has access to the frame |
Without the probe the panel still opens, but everything that comes from a frame is empty (the Parity tab still works). The panel installs its own style sheet and does not change yours.
The crate turns on zgui's instrument feature, which records
component boundaries for the Elements and Reactivity tabs. Unlike the rest
of the component library, it reads framework internals through crates below the public API. Nothing
in zgui depends on it, so an application that does not add it contains none of it.
Open and use the inspector
| Key | Action |
|---|---|
| F12 | open or close the panel |
| Ctrl+Shift+C | open the panel and toggle pick mode |
| Escape | leave pick mode (only handled while picking) |
| F8 | freeze the panel on the current frame, or resume |
The shortcuts are registered with the window, so they work before anything has focus. The inspector handles them in the capture phase and does not pass them to the application; all other keys reach the application.
To inspect an element, press Ctrl+Shift+C and move the pointer over the application: the element under it is outlined. Press to select it. The press leaves pick mode and is not delivered to the application. The panel never picks its own elements.
The panel docks on the right, and the application keeps the rest of the width. It opens 560 CSS pixels wide. To resize it, drag the divider, or focus the divider and press ←/→ (16 px per press). The panel is at least 280 px wide and leaves the application at least 160 px. Its width is kept when you close and reopen it.
Elements tab
A tree of the document, with a pane below it describing the selected node. To resize the two panes, drag the rule between them, or focus it and press ↑/↓; each pane is at least 80 px high.
The tree
Two chips switch between two views:
Components: one row per component instance, with its file and line.All nodes: every element and text run, with component boundaries.
The tree starts at your content. The panel's own elements and the overlay roots are hidden, and
portalled content (dialogs, menus, toasts) appears at the top level. Element rows show the name,
id and classes; text rows show the first 80 characters. Rows start expanded, and at most 400 are
drawn at once, so collapse rows you are not reading to see more.
Hovering a row outlines that node in the application (for a component, everything it built).
Clicking a row selects it. Picking with the pointer expands the tree to the node and selects it; in
the Components view, it selects the component that built the node.
The selected node
- The node as a selector, for example
box#save.button.button-primary. fragments: how many fragments its box has (wrapped text has several).- Vector rendering, for elements with vector content: which paths drew its shapes (analytic quads, marks, path glyphs, CPU layer, atlas mask, or the general rasteriser, Vello), and whether it was in the frame that initialised Vello.
- The box model: the
border,paddingandcontentboxes aswidth x height at x, y, in device pixels, taken from the laid-out fragment. There is no margin box; computed margins are in the style list. - The computed style: 24 layout properties always (
display,position, sizes and min/max, flex properties,align-items,justify-content,gap, overflow,box-sizing, font size, family and line height,color,background-color,opacity), then every property not at its initial value. Values equal to the initial value are dimmed, and colours get a swatch.
Frame tab
What the last frame drew, damaged and recomputed:
| Line | Meaning |
|---|---|
primitives | primitives in the display list |
batches | batches in the scene |
vector passes | rasterisation passes for vector content |
vector backend | the general vector rasteriser and whether it has been initialised |
damage | the number of damage rectangles, or the whole surface |
of the surface | damage as a percentage of the surface |
| (up to 12 lines) | the damage rectangles, w x h at x, y |
what this frame redid | every counter that changed, largest first |
Counters are per-frame differences, not totals, so they show the cost of one action. A frame
identical to the previous one shows no counter moved: this frame repeated the last one.
Useful counters (the full set is in crates/zgui-profile/src/counter/table.rs):
| Counter | Counts | Look at it when |
|---|---|---|
elements_restyled | elements whose selectors were matched again | a class changed, the pointer moved |
selector_matches | individual selector-against-element tests | a restyle is expensive |
nodes_visited | nodes a traversal looked at | a stage walks the whole document |
boxes_rebuilt | boxes rebuilt from their element | rows were added to or removed from a list |
nodes_relaid_out | nodes with a new size or position | a width changed |
text_shaped | text runs shaped | text changed |
fragments_diffed / fragments_rebuilt | fragments compared / recomputed | content moved |
repaints | fragments painted instead of replayed | a colour changed |
chunks_translated | cached paint chunks replayed at an offset | scrolling |
hit_index_rebuilds | hit index rebuilds | scrolling; should stay 0 |
primitives_emitted / primitives_culled | primitives added to / dropped before the scene | every frame |
glyphs_placed / glyphs_rasterised | glyphs positioned / rasterised | repainted text; the second should be 0 |
atlas_tiles_evicted | cached rasters evicted | Memory shows a large atlas |
wakes | event-loop wake-ups | an idle app keeps drawing |
draw_calls, damage_px and bytes_uploaded come from the GPU renderer and are 0 with a renderer
that draws nothing.
Timeline tab
Frame-time graph. One point per frame for the last 30 seconds (1800 frames). The top of the fixed scale is four refresh intervals, and a rule marks one interval (16.7 ms at 60 Hz). When there are more frames than columns, each column shows its slowest frame, so a single slow frame is never averaged away. The slowest frame's time is printed below the graph.
Stages. The frame loop records a mark at each stage boundary (f.begin, f.drain, f.timers,
… f.restyle, f.boxes, f.layout, … f.paint, f.a11y, f.recycle, f.end). The tab shows
the time between consecutive marks as a coloured strip (events, style, layout, paint, render, gpu,
other) and as a list, for example Recompute styles (f.restyle) 209.0 us. A stage that takes more
than a quarter of the frame gets a red border. Marks without a description show their raw name.
- The timeline shows the frame before the one that draws it, because the current frame's marks are not complete yet.
- Marks are kept in a 4096-entry ring buffer, started by
DevTools::new(), so the first frame after opening the panel already has a timeline. - The graph and stages are only updated while this tab is showing.
Reactivity tab
| Line | Meaning |
|---|---|
instances alive | component instances that exist now |
instances built | component instances created since start |
deepest scope | depth of the deepest scope |
Below, one row per component type: name, file and line, instance count, and depth range, with the
most instances first. Compare the first two numbers: if instances are reused, alive stays flat
while built rises; if scopes leak, both rise.
The tab cannot show which effects subscribe to which signal, because reactive_graph keeps its
subscriber sets private.
Parity tab
Shows which CSS properties this build's style engine supports, read directly from the crates that declare them. Check it when a declaration has no effect.
| Line | Meaning |
|---|---|
longhands | every property the engine generates |
implemented | parsed, cascaded and used |
parsed and ignored | parsed and cascaded, but not used |
absent | not available |
Below is a list of known gaps: the subject, the property to use instead, and the reason. Each row has a check that it is still accurate; an outdated row fails the build.
Memory tab
Device memory, as a bar and one line per part:
| Line | Holds | Large when |
|---|---|---|
fixed | memory allocated at construction | — |
targets | the frame's composition target | the surface is large |
scratch | scratch textures | the surface is large or much content is drawn at once |
atlases | cached raster content | glyphs or images are not being evicted |
buffers | vertex, instance and uniform buffers | the display list is not being reused |
total | the sum | — |
Host memory: nodes and document (bytes of records, arena slots, key tables and columns; text
and attribute strings are not counted).
General vector rasteriser: the configured backend, whether it was initialised, and which elements' vector content caused Vello to initialise.
Caches: one line per budgeted cache (paint chunks, vector layers, glyph atlas,
decoded images, paragraph shaping, vector resources, render targets, device memory), with
its content, limit, pinned amount and excess, and a bar that turns red above the limit. Each cache
reports in its own unit (bytes or entries), so do not add up caches with different units. A cache
above its limit is evicting too slowly. A cache shown with no level has no limit on purpose: its
content cannot be rebuilt, or a lower-level cache already bounds it.
Tips for reading the numbers
- Read counts before durations. Counts describe the work done and are the same on any machine; times depend on the machine.
- Check the counters against your change. A colour change should move
repaintsand leavenodes_relaid_outat 0. A scroll should movechunks_translatedand leaveelements_restyledandhit_index_rebuildsat 0. A new row should rebuild only that row's boxes. - Compare damage with primitives. Many primitives with little damage means the frame builds primitives for content it does not redraw.
- Press F8 to keep a single frame's values. Freezing stops sampling, and the panel keeps its values.
The Frame tab describes the frame before the one on screen, and the Timeline tab the frame before that. Read the numbers against the cost model.
Control the inspector from code
DevTools is Copy; the probe, the panel and every tab share one set of signals.
| Method | Effect |
|---|---|
DevTools::new() | a closed inspector with nothing selected |
probe() | the Rc<dyn FrameProbe> for with_probe |
is_open(), set_open(bool) | panel visibility |
set_picking(bool) | pick mode |
set_frozen(bool) | stop or resume sampling |
tab(), show(Tab) | the visible tab |
pick(NodeId) | select a node and open the panel |
picked(), picked_component() | the selected node, and the component that built it |
tree_mode(), set_tree_mode(TreeMode) | Components or Full tree |
set_expanded(NodeId, bool) | expand or collapse one tree row |
set_highlighted(Option<NodeId>) | outline a node in the application |
width(), set_width(f64) | panel width, in CSS pixels |
Tab is Elements, Frame, Timeline, Reactivity, Parity or Memory (Tab::ALL lists them
in tab-strip order).
Overhead
- Panel closed: the probe returns immediately and writes nothing, so an idle window stays idle.
a_closed_inspector_leaves_the_window_idleasserts 0 frames in 120 refresh intervals. - Frozen with F8: the same (
freezing_returns_the_window_to_idle). - Open: it samples and publishes only values that changed. The computed style is read only when
the selection changes or the frame restyled; the tree and reactive counts only when the document
changed. An open panel on an unchanging document stays idle:
tests/idle.rsshows every tab and asserts 0 frames in 300 intervals.
Two costs remain even while the panel is closed. DevTools::new() starts the timeline's mark ring
buffer, so each mark takes a clock read, an allocation and a lock instead of one atomic load. And
zgui-profile's counters feature stays on in any build that links the inspector, which costs one
atomic add per counter increment. Both go away when you remove the dependency.
Write your own frame probe
The inspector reads frames through FrameProbe, a public trait you can implement yourself:
pub trait FrameProbe {
/// A frame has finished on `window`.
fn frame_ended(&self, window: &Window);
/// A name for diagnostics.
fn describe(&self) -> &str { "a frame probe" }
}frame_ended is called once at the end of every frame, with the window in the state that frame
left it (scene, damage, layout, renderer report). It cannot change the window or cancel a frame. It
takes &self, so keep data in a Cell, RefCell or signal.
use std::cell::Cell;
use std::rc::Rc;
use zgui::prelude::*;
use zgui::runtime::{FrameProbe, Window};
/// One line for every frame that drew anything.
#[derive(Default)]
struct Trace {
frames: Cell<u64>,
}
impl FrameProbe for Trace {
fn frame_ended(&self, window: &Window) {
let count = self.frames.get() + 1;
self.frames.set(count);
let damage = window.damage();
if damage.rects().is_empty() && !damage.is_full() {
return;
}
eprintln!(
"frame {count}: {} primitives, {} damaged rectangles, {} bytes on the device",
window.scene().primitives.len(),
damage.rects().len(),
window.renderer().memory().total(),
);
}
}
fn main() -> Result<(), zgui::Error> {
app().with_probe(Rc::new(Trace::default())).run(|| view! { column() })
}In a test, keep an Rc to the probe, pass a clone to with_probe, and read what it collected after
driving the window (see Testing). For counter assertions, use
zgui-profile with its counters feature directly: call counter::exclusive() first (the counters
are process-wide), then compare counter::snapshot() before and after with Counters::delta.
A window has one probe: with_probe replaces any earlier one, so you cannot install the
inspector and your own probe side by side. To feed both, install a probe that forwards to each:
struct Both(Rc<dyn FrameProbe>, Rc<dyn FrameProbe>);
impl FrameProbe for Both {
fn frame_ended(&self, window: &Window) {
self.0.frame_ended(window);
self.1.frame_ended(window);
}
}Component boundaries
With zgui's instrument feature on, each #[component] instance puts two marker nodes around its
content and registers its name, file, line and scope. Markers only occupy positions in the child
list: they have no box, match no selector and do not affect layout. With the feature off nothing is
recorded; only a static record per component type remains in the binary.
Cargo unifies features across a build, so cargo test --workspace turns instrument on everywhere.
Tests that count a node's children must ignore the markers.