Custom elements
Build retained widgets in Rust that measure themselves, place their own children, and paint quads, paths, glyph runs, and shader effects.
A custom element is a widget you implement in Rust instead of composing it from built-in elements. It keeps its own state, measures itself, can place ordinary child elements, and paints with the same quads, paths, and glyphs that built-in elements use.
Use one when composing elements would need many nodes, or when built-in layout cannot place the
children the way you need. Use a canvas when
a list of shapes is enough, and a surface when another renderer
already produces a texture.
A complete example
This application shows a meter and two buttons that move it:
use zgui::canvas::zgui_color::Color;
use zgui::geom::{DevicePx, Point, Rect, Size};
use zgui::prelude::*;
/// A horizontal meter: a track with a fill proportional to `value`.
struct Meter {
value: f32,
}
impl CustomElement for Meter {
fn layout(&mut self, cx: &mut CustomLayoutCx<'_>) -> CustomMeasured {
// Use the size CSS fixed, or fall back to 120 × 8 CSS pixels.
CustomMeasured {
width: cx.known_width.unwrap_or(120.0 * cx.scale),
height: cx.known_height.unwrap_or(8.0 * cx.scale),
..CustomMeasured::default()
}
}
fn paint(&mut self, painter: &mut ScenePainter<'_>) {
let size = painter.size();
let radius = size.height.0 / 2.0;
let origin = Point::new(DevicePx(0.0), DevicePx(0.0));
// The track, then the fill in the element's CSS `color`.
painter.fill(Rect::new(origin, size), radius, Color::srgb(0.2, 0.2, 0.25, 1.0));
let filled = Size::new(DevicePx(size.width.0 * self.value), size.height);
painter.fill(Rect::new(origin, filled), radius, painter.current_color());
}
}
#[component]
fn Volume() -> impl IntoView {
let (element, handle) = zgui::custom::custom(Meter { value: 0.4 });
// Builds a click listener that moves the meter by `by`.
let step = move |by: f32| {
let handle = handle.clone();
move |_: &mut EventCx<'_, events::Click>| {
handle.update(|meter| meter.value = (meter.value + by).clamp(0.0, 1.0));
handle.repaint();
}
};
let down = step(-0.1);
let up = step(0.1);
view! {
column(class = "volume") {
{element.class("meter").into_view()}
row(class = "buttons") {
control(class = "button", on:click = down) {"-"}
control(class = "button", on:click = up) {"+"}
}
}
}
}
const SHEET: &str = css!(
":root {
background-color: #12141a;
color: #e8ecf4;
font-family: sans-serif;
display: flex;
align-items: center;
justify-content: center;
}
.volume { align-items: center; gap: 16px; }
.meter { width: 240px; height: 10px; color: #3b6cf6; }
.buttons { gap: 8px; }
.button { padding: 6px 16px; border-radius: 8px; background-color: #232936; }
.button:hover { background-color: #2b3243; }"
);
fn main() -> Result<(), zgui::Error> {
app()
.with_title("Meter")
.with_size(360.0, 200.0)
.with_stylesheet(SHEET)
.run(|| view! { Volume() })
}CustomElementhas two methods:layoutreturns the content size, andpaintdraws.zgui::custom::customreturns an ordinary element builder and a typedCustomHandle. The builder takes classes, inline styles, listeners, attributes, and children like any element.- The
Metervalue lives on the UI thread and keeps its state between frames. The click listeners change it through the handle withupdate, then callrepaintso zgui paints it again. - CSS sets the width, height, and colour.
painter.current_color()returns the computedcolor, so a:hoverrule could change the fill without any Rust code.
examples/custom.rs in the zgui repository is a larger version: a gauge with tick marks, a needle
drawn as a path, and a label that follows the needle.
Measure the element
layout returns the content size in device pixels. CSS owns the outer box: zgui applies width,
height, min and max sizes, aspect ratio, padding, borders, and box-sizing around your answer.
CustomLayoutCx has these fields:
| Field | Meaning |
|---|---|
known_width, known_height | A size layout has already fixed; use it when present |
available | Space::Definite, MinContent, or MaxContent per axis |
scale | Device pixels per CSS pixel |
style | The element's computed style |
final_pass | true when layout keeps this answer |
access | Measures, lays out, and places the element's children |
Layout may call layout several times per frame. CustomMeasured can also report
first_baseline and last_baseline, so the element aligns with text around it.
Place child elements
Children added with .child(...) are ordinary elements styled by ordinary CSS, but the custom
element decides where they go. This layout, adapted from examples/custom.rs, makes the meter
64 pixels tall, measures a label, and centres it above the current value. Remove the height rule
from the style sheet when you use it, because CSS sizes win over the content size.
use zgui::custom::Space;
fn layout(&mut self, cx: &mut CustomLayoutCx<'_>) -> CustomMeasured {
let width = cx.known_width.unwrap_or(260.0 * cx.scale);
let height = 64.0 * cx.scale;
if cx.final_pass && cx.access.child_count() > 0 {
// Let the label size itself...
let label = cx.access.measure_child(
0,
(None, None),
(Space::MaxContent, Space::MaxContent),
);
cx.access.layout_child(
0,
(Some(label.width), Some(label.height)),
(Space::Definite(label.width), Space::Definite(label.height)),
);
// ...then centre it over the value, kept inside the box.
let x = (width * self.value - label.width / 2.0).clamp(0.0, width - label.width);
cx.access.place_child(0, x, 0.0);
}
CustomMeasured { width, height, ..CustomMeasured::default() }
}The label is attached in the component, where percent is a signal holding the value as a
percentage:
let element = element.class("meter").child(
zgui::elements::label()
.class("meter__readout")
.child(move || format!("{}%", percent.get())),
);The rules:
- Only on the final pass, call
layout_childand thenplace_childfor every child. - Use
measure_childfor probes. It commits nothing, and repeated requests hit the layout cache. - Child indices follow document order.
place_childtakes device pixels from the element's border-box corner.
Paint
paint receives a ScenePainter. Coordinates are device pixels from the content-box corner. The
element's clip, transform, and inherited opacity apply to everything it draws.
| Method | Draws |
|---|---|
fill(rect, radius, color) | A solid rounded rectangle, as cheap as a CSS background |
stroke(rect, radius, width, color) | A solid rounded-rectangle border |
fill_path(path, color) | A solid path |
shape(&shape) | A full vector shape: fills, strokes, gradients, clips |
glyphs(&run, origin, color) | A pre-shaped glyph run; see Shape and draw glyph runs |
effect(rect, radius, &handle) | A registered shader effect, via ShaderPainterExt |
The painter also has size(), scale(), current_color() (the computed CSS color), and
origin(), the content-box corner on the window surface. Use origin() to convert pointer
positions from events into painter coordinates.
Prefer fill and stroke for rectangles. Paths go through the
vector routes: circles, rectangles, and
straight strokes become quads or marks, small solid shapes use cached masks, and the rest use the
GPU vector rasteriser. Keep unchanged paths in an Arc so their cached geometry is reused.
The painter cannot open groups or clips, because those must stay balanced with the surrounding
scene. Give a child overflow: hidden when you need an inner clip.
Custom primitives paint after the element's background and border and before its children. zgui
records them and replays them unchanged on later frames, without calling paint, until you call
repaint or relayout.
Update the element
Change the element's state from an event handler or effect through its handle, then say what changed:
handle.update(|meter| meter.value = 0.7);
handle.repaint();update changes the retained state only. It does not invalidate the element, so always follow it
with one of these:
repaint(): the drawn primitives changed. zgui callspainton the next frame.relayout(): the content size or child placement changed. zgui measures the element again, even when its computed style is unchanged, and repaints it. Use it when a child's position depends on the state, as in the label example above.
update returns whatever its closure returns, which is useful for reading the new value back.
The handle is cloneable but belongs to the UI thread. layout and paint also run on the UI
thread, so subtrees that contain custom elements are laid out there while other subtrees can use
layout workers. Do not block in either method, and do not change the document from them.
Shape and draw glyph runs
Use glyph runs when the element lays out its own text, such as a terminal grid or a code view
that positions one line at a time. Get Fonts in the component body and keep its Shaper in the
element:
use zgui::app::LineRequest;
use zgui::custom::{PaintSlot, ShapedRunOwned};
use zgui::view::Ident;
let fonts = expect_context::<Fonts>();
let scale = use_window().scale().get_untracked();
let mut shaper = fonts.shaper();
let families = [Ident::new("JetBrains Mono")];
let request = LineRequest {
families: &families,
weight: 400,
italic: false,
size_device_px: 14.0 * scale,
letter_spacing: 0.0,
ligatures: false,
};
let runs: Vec<ShapedRunOwned> = shaper.shape_line("cargo check", &request);shape_line never wraps. It returns owned runs in visual order, one per font after fallback. Each
glyph records the byte offset of its cluster, so a cell view can place a caret without shaping
again.
In paint, draw each run at the same line-box origin:
for run in &self.runs {
painter.glyphs(
&run.as_run(PaintSlot(0)),
self.origin,
painter.current_color(),
);
}glyphs paints with the colour argument and ignores the run's brush slot. Colour glyphs, such as
emoji, keep their own colours and use only the argument's alpha.
LineRequestsizes are device pixels.- Reshape when the text, style, registered fonts, or window scale changes. Keep the shaper and runs
between frames; do not shape in
paint. - A run's
FaceIds belong to theFontsthat shaped it, so do not draw runs from a replaced font collection.
Install support without zgui::app()
zgui::app() installs custom element support. If you drive zgui_runtime::App directly, install
it with the with_custom builder method:
let app = app.with_custom(Box::new(|_| zgui_custom::sources()));Next
GPU surfaces
Show textures from your own wgpu code in the document, driven by zgui or by a producer thread, and share a graphics device with a host.
Custom shaders and corner shapes
Write WGSL effects with shader!, bind them from CSS or a custom element, and cut squircle and other corner shapes with --zgui-corner-shape.