Custom widgets
In CPUI, a widget is any code that displays part of the interface. There is no base type to inherit from. A widget can be written in three ways, each offering more control than the previous one.
1. Functions
Section titled “1. Functions”The simplest way is to move part of the interface into a function that takes its data as parameters:
use cpui::Ui;
/// A number with a caption, as on a dashboard.fn stat(ui: &mut Ui<'_>, caption: &str, value: impl std::fmt::Display) { ui.card().gap(4).children(|ui| { ui.text(caption).text_sm().muted(); ui.title(value); });}
fn overview(ui: &mut Ui<'_>, files: usize, size: &str) { ui.grid(160).gap(16).children(|ui| { stat(ui, "Files", files); stat(ui, "Size", size); });}2. Composing a Widget
Section titled “2. Composing a Widget”When a widget has several optional settings, write it as a builder: a struct with one method per
setting. Implement Widget for it and place it with ui.add; it is then used in the same way
as a built-in widget:
use cpui::{Response, Ui, Widget};
/// A chip: a small outlined button that can be marked as selected.struct Chip<'t> { text: &'t str, selected: bool,}
impl<'t> Chip<'t> { fn new(text: &'t str) -> Chip<'t> { let selected = false; Chip { text, selected } }
fn selected(mut self, selected: bool) -> Chip<'t> { self.selected = selected; self }}
impl Widget for Chip<'_> { fn show(self, ui: &mut Ui<'_>) -> Response { let chip = ui.button(self.text).small(); chip.when(!self.selected, |b| b.outline()).response() }}
fn filters(ui: &mut Ui<'_>, selected: &mut usize) { ui.flow().gap(8).children(|ui| { for (i, name) in ["All", "Unread", "Archived"].into_iter().enumerate() { if ui.add(Chip::new(name).selected(*selected == i)).clicked() { *selected = i; } } });}A widget composed of built-in widgets keeps their behavior: keyboard focus, transitions and the
information screen readers need. ui.add returns an Element, so the widget also accepts
.tooltip(…) and .disabled(…), and exposes .clicked() and the other results.
A widget library can also provide settings that chain after ui.add, such as
ui.add(Rating::new(&mut stars)).max(10): implement a trait for Element<'_, '_, Rating> whose
methods modify the widget through Element::with.
A widget that reacts to the pointer as a single unit does not require custom drawing either. Set
its hover and pressed styles with .hover(…) and .active(…) on its container, and read the
result with children_with_response (see Interaction states).
3. Custom drawing
Section titled “3. Custom drawing”When the required look cannot be composed from built-in widgets, draw it with ui.canvas:
- Input. The canvas returns a
Responsewith clicks, hover and presses. During drawing,Painter::responseprovides the same state. - Colors. Take colors and radii from
Painter::theme, so that light and dark mode and custom themes work without extra code. - Value. Pass the value the widget edits as
&mut. When the value changes, callResponse::mark_changedon the returned response. - Pointer. On hover, set the cursor shape with
ui.set_cursor. If the widget is draggable, declare it withui.grab, so that a touch drag on it is not treated as scrolling. - Transitions. Call
ui.animate(key, target)before the canvas to obtain a smoothly changing value.
The rating widget below draws five dots; clicking the n-th dot sets n stars. main shows how to
test a custom-drawn widget: it renders to an offscreen target and clicks the third dot.
use cpui::{App, Context, CursorIcon, Offscreen, Rect, Response, Theme, Ui, Widget};
const DOT: f32 = 16.0;const GAP: f32 = 6.0;
/// A rating from 0 to 5 stars.struct Rating<'v> { value: &'v mut u32,}
impl Widget for Rating<'_> { fn show(self, ui: &mut Ui<'_>) -> Response { let value = *self.value; let mut response = ui.canvas(5.0 * DOT + 4.0 * GAP, DOT).paint(|p| { let hovered = p.response().hovered(); let (on, off) = (p.theme().accent, p.theme().border_strong); for i in 0..5 { let x = i as f32 * (DOT + GAP); let inset = if hovered { 0.0 } else { 1.0 }; let dot = Rect::new(x, 0.0, DOT, DOT).inset(inset, inset); p.rounded(dot, DOT / 2.0, if i < value { on } else { off }); } }); if response.hovered() { ui.set_cursor(CursorIcon::Pointer); } if response.clicked() && let Some((x, _)) = ui.pointer() { let picked = ((x - response.rect().x) / (DOT + GAP)) as u32 + 1; *self.value = picked.min(5); response.mark_changed(); } response }}
struct Review { stars: u32,}
impl App for Review { fn ui(&mut self, ui: &mut Ui<'_>) { ui.add(Rating { value: &mut self.stars, }); }}
fn main() -> Result<(), cpui::Error> { let mut target = Offscreen::new(200.0, 100.0, 1.0)?; let mut ctx = Context::new(Theme::light()); let mut app = Review { stars: 0 }; ctx.frame(&mut target, &mut app);
// The center of the third dot. ctx.input.pointer = Some((2.0 * (DOT + GAP) + DOT / 2.0, DOT / 2.0)); ctx.input.pressed = true; ctx.frame(&mut target, &mut app); ctx.input.released = true; ctx.frame(&mut target, &mut app); assert_eq!(app.stars, 3); Ok(())}For large content, or when you need bitmaps, polygons or clipping, use ui.custom. Its content is
drawn in App::paint, directly through a Frame.
4. Where state lives
Section titled “4. Where state lives”| State | Where it is kept |
|---|---|
| The widget’s value (text, choice, rating) | In your app’s fields, passed to the widget as &mut |
| Whether a section is expanded or a popup is open | Kept by CPUI. A dialog is opened and closed by the key it was declared with: ui.open_dialog(key) |
| How far a transition has run | Kept by CPUI; read it with ui.animate |
| The widget’s own temporary state (where a drag started, whether a detail is shown) | Kept by CPUI through ui.local and ui.local_mut, one copy per instance. When the widget is no longer shown, the value is dropped and its Drop runs |
| Focus, caret, scroll position | Kept by CPUI per widget id. Use ui.key to keep the ids of list items stable |
Keep state that only the widget needs in ui.local. The button below stores its own click count;
two instances count independently:
use cpui::{Response, Ui, Widget};
/// A counter button that remembers its own count.struct Clicks;
impl Widget for Clicks { fn show(self, ui: &mut Ui<'_>) -> Response { let n = ui.local("n", || 0u32); let response = ui.button(format_args!("Clicked {n} times")).response(); if response.clicked() { ui.local_mut("n", || 0u32, |n| *n += 1); } response }}
fn two_counters(ui: &mut Ui<'_>) { // Each instance placed with `ui.add` has its own count. ui.add(Clicks); ui.add(Clicks);}5. Keyboard and screen readers
Section titled “5. Keyboard and screen readers”Like a built-in widget, a canvas can support the keyboard and describe itself to screen readers:
.focusable()makes it a Tab stop. A press focuses it; when focused from the keyboard, it shows the theme’s focus ring, with the radius set by.rounded(radius).response.focused()reports whether it has focus..keys(&[…])lists the keys it handles while focused; read them withui.key_pressed_on(&response, key). While it has focus,ui.key_pressedelsewhere in the window does not report these keys.ui.input().shiftreports whether Shift is held..aria_role(Role::Slider),.aria_label(…),.aria_value(…)and.aria_range(value, min, max)describe its role and value to assistive technology. Screen readers adjust a slider with the arrow keys, so handle them with.keys.ui.tooltip(&response, text)shows a tooltip whose text can depend on the pointer position, such as the value under the pointer in a chart.Style::focus_ring,Style::itemandStyle::dimmedapply the focus ring, row style and disabled style of the built-in widgets to a box.
use cpui::accesskit::Role;use cpui::{IconName, Key, Rect, Response, Ui, Widget};
/// Stars from 0 to 5, set by clicking or with the arrow keys.struct Stars<'v>(&'v mut u32);
impl Widget for Stars<'_> { fn show(self, ui: &mut Ui<'_>) -> Response { const STAR: f32 = 20.0; let value = *self.0; let mut response = ui .canvas(STAR * 5.0, STAR) .keys(&[Key::Left, Key::Right]) .rounded(4) .aria_role(Role::Slider) .aria_range(f64::from(value), 0.0, 5.0) .paint(|p| { let (on, off) = (p.theme().accent, p.theme().border_strong); for i in 0..5 { let star = Rect::new(i as f32 * STAR, 0.0, STAR, STAR); p.icon(IconName::Star, star, if i < value { on } else { off }); } }); if ui.key_pressed_on(&response, Key::Right) { *self.0 = (value + 1).min(5); } if ui.key_pressed_on(&response, Key::Left) { *self.0 = value.saturating_sub(1); } if *self.0 != value { response.mark_changed(); } response }}
fn review(ui: &mut Ui<'_>, stars: &mut u32) { ui.add(Stars(stars)).aria_label("Rating");}6. Text and input methods
Section titled “6. Text and input methods”A canvas can also take text, for an editor that lays out and draws its text itself:
.ime()makes it take text while focused: typed, pasted, and composed with an input method such as Pinyin. It also takes the editing keys of a text input, such as Backspace, Enter and the arrows, whichui.key_pressed_onreports.ui.ime_on(&response)returns the text of this frame. Insertime.text()at the caret.- While drawing,
p.ime()returns the input method’s composition,ime.preedit(). Draw it at the caret, usually underlined; it is not part of the text until committed. p.ime_caret(rect)tells the input method where the caret is, so its candidate window opens next to it.
Only the focused widget receives text and composition. When focus moves away, ui.ime_on returns
None and the composition is discarded.
use cpui::{Font, Key, Rect, Response, Sizing, Ui};
/// One line of text drawn by hand, which takes typing and input methods.fn note(ui: &mut Ui<'_>, text: &mut String) -> Response { let font = Font::ui(14.0); let editor = ui.canvas(Sizing::FILL, 24).ime().rounded(4).paint(|p| { let color = p.theme().foreground; let x = 4.0 + p.measure(font, text.as_str()); p.text(font, (4.0, 4.0), text.as_str(), color); if let Some(ime) = p.ime() { let width = p.measure(font, ime.preedit()); p.text(font, (x, 4.0), ime.preedit(), color); p.line((x, 21.0), (x + width, 21.0), 1.0, color); p.ime_caret(Rect::new(x + width, 4.0, 1.0, 16.0)); } }); if let Some(ime) = ui.ime_on(&editor) { text.push_str(ime.text()); } if ui.key_pressed_on(&editor, Key::Backspace) { text.pop(); } editor}